Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
Sync in-progress work from the main tree
leepokaic24564c267db
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8368f7e2..0320d0d0 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -19,6 +19,8 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess- UI principle: buttons an icon can express are icon-only (with tooltip / accessibility label); text only where an icon would be ambiguous (approval choices).- `host/` — **codync-host** (Rust, macOS + Linux). Detects installed harnesses (`backends.rs`: login-shell PATH + known dirs) and the ACP registry (`registry.rs`, cached in `~/.codync/registry.json`, binaries under `~/.codync/agents`). Drives agents over **ACP** (JSON-RPC on stdio, hand-rolled in `acp.rs`, updates kept as `serde_json::Value` so new adapter variants never break parsing). One actor per bot (`bot.rs`) owns the agent process + session and maps `session/update` onto transcript entries.- **Thread ≠ session**: a bot is one endless transcript (SQLite `entries`, ordered by `seq`); the ACP session underneath is resumed with `session/load` or replaced by *New session*.+- Bot collaboration: built-in `team` MCP (`team.rs`) lists visible bots and asks one for a reply through its actor queue. Requests are separate turns, cycle-checked and cancellable; native subagents stay with the harness. See [docs/bot-collaboration.md](docs/bot-collaboration.md).+- **Context & memory** (Grok Bot's design): frozen instruction snapshot per session + compaction epoch (Claude gets it as a system prompt), profile edits as update blocks, per-bot memory files written by a keeper agent, busy-time messages folded into one turn, interrupted turns resumed: [docs/context-and-memory.md](docs/context-and-memory.md).- **Chat shows only**: user messages, the *final* agent message of each turn (`data.final`), permission cards, notices. Narration, thoughts, tool calls, plans are trace entries (Full conversation sheet).- **Sync**: every mutation stamps a global `rev`. Clients call `GET /events?since=<rev>` (catch-up in rev order, then live). Emission happens under `Hub::emit_lock` so events leave in rev order. Clients upsert by id; never skip undecodable events (the iOS app rewinds to rev 0).- API: `POST /api/<method>` + SSE, bearer token (`~/.codync/token`). Default port **19222**, binds 0.0.0.0 for Tailscale/LAN.diff --git a/Codync.xcodeproj/project.pbxproj b/Codync.xcodeproj/project.pbxprojindex 4bdc1bdb..ffc4f35f 100644--- a/Codync.xcodeproj/project.pbxproj+++ b/Codync.xcodeproj/project.pbxproj@@ -21,12 +21,14 @@48DAAA1384E5B8D0BA27C895 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1E47C60032C326157E0386B8 /* SwiftUI.framework */; };498C81B8C82557C85F912238 /* HostLink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75CAC64DDC41D4A222A12DDE /* HostLink.swift */; };513F59BF65DED5379AB950A1 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = D2C705F063CD20F5B3036BD4 /* Assets.xcassets */; };+ 52AEBEAEADB347DA7E3CDC40 /* WidgetPreviews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 744DB8C27E27A424EA8E1549 /* WidgetPreviews.swift */; };52CF04B855C6AAEC47B75B8F /* CodyncKit in Frameworks */ = {isa = PBXBuildFile; productRef = 1285DDFA0390A76ECDAAD6C0 /* CodyncKit */; };5F9AE9B8E7FF66F194162BDC /* ScreenHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = AB932B6C1849B8DF7CF7C2E3 /* ScreenHelper.swift */; };6A15821964A5EE5AEBB0C420 /* ClerkConfig.plist in Resources */ = {isa = PBXBuildFile; fileRef = 19D41F16A62FEF37BE0AD1FC /* ClerkConfig.plist */; };826FEDA23997E436D632E579 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 4CFB70DD8757C90695CDA211 /* PrivacyInfo.xcprivacy */; };8AC8D90C21B92480E2809758 /* AccountSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4B8EAB09016D328195FE2AD /* AccountSession.swift */; };8CD641A45F144BF41D703D2A /* CodyncMacApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2969919CCC8BC89F277C43A6 /* CodyncMacApp.swift */; };+ A12D125989D2EA1AC5308218 /* WidgetGalleryView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E8563C243AB130DFA063CAD /* WidgetGalleryView.swift */; };AA601649E43A5AF73DCF5B5E /* WebRTC in Frameworks */ = {isa = PBXBuildFile; productRef = 2D9748E611692583AFC5A152 /* WebRTC */; };ACCB28F3DB9C89108B7911E3 /* Input.swift in Sources */ = {isa = PBXBuildFile; fileRef = 842DA106CA15E3810C3C9461 /* Input.swift */; };AFC0CD8BD1FA61F810C96057 /* com.pokai.Codync.screen.plist in CopyFiles */ = {isa = PBXBuildFile; fileRef = 895BB6C2EB8986266EB4159A /* com.pokai.Codync.screen.plist */; };@@ -104,6 +106,7 @@/* Begin PBXFileReference section */00F135A0B168269BD6C2A199 /* CodyncWidgets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodyncWidgets.swift; sourceTree = "<group>"; };+ 0E8563C243AB130DFA063CAD /* WidgetGalleryView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetGalleryView.swift; sourceTree = "<group>"; };19D41F16A62FEF37BE0AD1FC /* ClerkConfig.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = ClerkConfig.plist; sourceTree = "<group>"; };1E47C60032C326157E0386B8 /* SwiftUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftUI.framework; path = System/Library/Frameworks/SwiftUI.framework; sourceTree = SDKROOT; };1F16B11B2920E9D05621AFE7 /* ViewingBadge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewingBadge.swift; sourceTree = "<group>"; };@@ -118,6 +121,7 @@6D734BEE7CD3F84677B0218B /* Widgets.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = Widgets.appex; sourceTree = BUILT_PRODUCTS_DIR; };739EC95223CC8F8717C33736 /* PairingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingView.swift; sourceTree = "<group>"; };741B706007BA1B91CB853699 /* Screen.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Screen.app; sourceTree = BUILT_PRODUCTS_DIR; };+ 744DB8C27E27A424EA8E1549 /* WidgetPreviews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetPreviews.swift; sourceTree = "<group>"; };74BB0269490A0689868F05F7 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };75CAC64DDC41D4A222A12DDE /* HostLink.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostLink.swift; sourceTree = "<group>"; };7A2F5A7F5A648909D8CC5C19 /* kit */ = {isa = PBXFileReference; lastKnownFileType = folder; name = kit; path = kit; sourceTree = SOURCE_ROOT; };@@ -195,6 +199,7 @@E1B79D48C1D6F90D53751B3F /* RootView.swift */,DE4AE9A34F61B3D28E0C2550 /* SettingsView.swift */,47BCE8E2AFA6CA829DBC489A /* UsageView.swift */,+ 0E8563C243AB130DFA063CAD /* WidgetGalleryView.swift */,);path = Views;sourceTree = "<group>";@@ -203,6 +208,7 @@isa = PBXGroup;children = (00F135A0B168269BD6C2A199 /* CodyncWidgets.swift */,+ 744DB8C27E27A424EA8E1549 /* WidgetPreviews.swift */,5CD54037D222223E9929C80F /* Resources */,);path = Widgets;@@ -572,6 +578,7 @@buildActionMask = 2147483647;files = (F191B13B972C72CB4253B449 /* CodyncWidgets.swift in Sources */,+ 52AEBEAEADB347DA7E3CDC40 /* WidgetPreviews.swift in Sources */,);runOnlyForDeploymentPostprocessing = 0;};@@ -602,6 +609,7 @@E430F9317B690366F62164DB /* RootView.swift in Sources */,DEF7478AB86DB605F52905F5 /* SettingsView.swift in Sources */,ED143C01BF7AD4953101D160 /* UsageView.swift in Sources */,+ A12D125989D2EA1AC5308218 /* WidgetGalleryView.swift in Sources */,);runOnlyForDeploymentPostprocessing = 0;};diff --git a/README.md b/README.mdindex 9ad36426..10089f06 100644--- a/README.md+++ b/README.md@@ -18,6 +18,7 @@ iPhone · Mac window · Linux (GTK) ⇄ HTTP + SSE ⇄ codync-host ⇄ ACP```- **Bots** have a name, a character avatar, standing instructions, an agent backend, a project folder and a permission policy. Each bot is **one endless conversation**; the agent sessions underneath are an implementation detail (resumed with `session/load`, restarted with *New session*).+- **Bots can ask each other for help.** Tell one “ask Reviewer to check these changes.” The built-in `team` MCP server lets it discover your other visible bots and wait for a reply. Requests appear in both chats; each recipient keeps its own agent, folder and approvals. Native subagents stay under the coding agent's control. See [bot collaboration](docs/bot-collaboration.md).- **The chat only shows what matters**: your messages, each turn's final reply, approval cards and notices. Every tool call, diff, plan and thought is one tap away in *Full conversation*. While a bot works, its row shows what it's doing right now.- **Agents are detected automatically**: the host hydrates PATH from your login shell (plus Homebrew, ~/.local/bin, nvm, bun, volta, asdf, mise, pnpm…), finds every harness you have installed, and prefers its native ACP mode. Anything else in the official [ACP registry](https://agentclientprotocol.com/registry) can be picked too — Codync fetches it on first use (npx, uvx or a checksummed binary).- **codync-host** (Rust, macOS + Linux) runs on your computer. It speaks the [Agent Client Protocol](https://agentclientprotocol.com) to each agent, keeps transcripts in SQLite, and serves the phone. Every change carries a global `rev`, so the phone reconnects with `since: rev` and never misses anything.diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swiftindex 673b5c5b..32bb6b12 100644--- a/apps/ios/App/CodyncApp.swift+++ b/apps/ios/App/CodyncApp.swift@@ -12,6 +12,7 @@ struct CodyncApp: App {private var model: BotStore { app.model }@Environment(\.scenePhase) private var scenePhase@State private var tab = AppTab.bots+ @AppStorage("onboardingCompleted") private var onboardingCompleted = falsevar body: some Scene {WindowGroup {@@ -20,8 +21,14 @@ struct CodyncApp: App {.environment(model).environment(app.account).tint(Palette.accent)- .sheet(isPresented: Bindable(app.account).showSwitcher) {- NavigationStack { AccountSwitcherView().environment(app.account).environment(model) }+ .sheet(isPresented: Binding(+ get: { onboardingCompleted && app.account.showSwitcher },+ set: { app.account.showSwitcher = $0 }+ )) {+ NavigationStack { AccountSwitcherView() }+ .environment(app.account)+ .environment(model)+ .tint(Palette.accent)}.onChange(of: app.account.userID, initial: true) { _, userID inapp.switchAccount(to: userID)@@ -105,10 +112,13 @@ final class AppStore {private static func makeStore(_ storage: SharedStore.Context) -> BotStore {let store = BotStore(pairing: storage.pairing, clientKind: "ios", persistsPairing: true, storage: storage)store.onPaired = { PushRegistrar.shared.syncDevice(with: $0) }- store.onBotUpdated = { [weak store] bot in- guard let store else { return }- LiveActivities.shared.update(bot: bot)- BotsWidgetFeed.update(store.roster)+ store.onBotUpdated = { bot in LiveActivities.shared.update(bot: bot) }+ store.onRosterChanged = { roster in+ BotsWidgetFeed.update(roster, storage: storage)+ if roster.isEmpty {+ LiveActivities.shared.endAll()+ WidgetCenter.shared.reloadAllTimelines()+ }}store.onSent = { [weak store] bot inguard let store else { return }@@ -118,6 +128,7 @@ final class AppStore {storage.usage = usageWidgetCenter.shared.reloadAllTimelines()}+ BotsWidgetFeed.update(store.roster, storage: storage)return store}}@@ -160,15 +171,34 @@ final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCent/// something the widget shows changes (who is working / needs you / unread).@MainActorenum BotsWidgetFeed {- private static var shown = ""+ private struct Snapshot: Equatable {+ let id: String+ let name: String+ let shape: String+ let color: String+ let status: String+ let activity: String+ let message: String?+ let lastAt: Int64++ init(_ bot: Bot) {+ id = bot.id; name = bot.name; shape = bot.avatarShape; color = bot.avatarColor+ status = bot.status; activity = bot.activity; message = bot.lastMessage; lastAt = bot.lastAt+ }+ }+ private static var shown: [Snapshot]?+ private static var scope: String?- static func reset() { shown = "" }+ static func reset() { shown = nil; scope = nil }- static func update(_ roster: [Bot]) {- SharedStore.bots = roster- let signature = roster.map { "\($0.id):\($0.status):\($0.unread)" }.joined(separator: ",")- guard signature != shown else { return }+ static func update(_ roster: [Bot], storage: SharedStore.Context) {+ guard storage.id == SharedStore.activeContext.id else { return }+ storage.bots = roster+ let currentScope = storage.id + ":" + SharedStore.Context.digest(storage.pairing?.token ?? "unpaired")+ let signature = roster.filter { !$0.hidden }.map(Snapshot.init)+ guard signature != shown || scope != currentScope else { return }shown = signature+ scope = currentScopeWidgetCenter.shared.reloadTimelines(ofKind: "CodyncBots")}}diff --git a/apps/ios/Views/PairingView.swift b/apps/ios/Views/PairingView.swiftindex 102bcf51..c2aaf7cc 100644--- a/apps/ios/Views/PairingView.swift+++ b/apps/ios/Views/PairingView.swift@@ -5,6 +5,7 @@ import VisionKit/// First run: explain the model, then pair with a computer running codync-host.struct PairingView: View {+ var introductory = true/// Set when adding another computer from the profile sheet; shows a close button.var onDone: (() -> Void)?@Environment(BotStore.self) private var model@@ -17,22 +18,27 @@ struct PairingView: View {var body: some View {ScrollView {VStack(alignment: .leading, spacing: 28) {- HStack(spacing: -10) {- CharacterAvatar(shape: "blob", color: "blue", size: 64, mood: .working)- CharacterAvatar(shape: "squircle", color: "orange", size: 64)- CharacterAvatar(shape: "teardrop", color: "violet", size: 64, mood: .working)+ if introductory {+ HStack(spacing: -10) {+ CharacterAvatar(shape: "blob", color: "blue", size: 64, mood: .working)+ CharacterAvatar(shape: "squircle", color: "orange", size: 64)+ CharacterAvatar(shape: "teardrop", color: "violet", size: 64, mood: .working)+ }+ .padding(.top, 40)}- .padding(.top, 40)VStack(alignment: .leading, spacing: 10) {- Text("Your coding agents,\nas teammates.")+ Text(introductory ? "Your coding agents,\nas teammates." : "Connect a computer").font(.system(size: 34, weight: .semibold)).tracking(-0.6).foregroundStyle(Palette.text)- Text("Give each agent a name, a job and a project. Then just message the right one — it works on your computer while your phone is in your pocket.")+ Text(introductory+ ? "Give each agent a name, a job and a project. Then just message the right one — it works on your computer while your phone is in your pocket."+ : "Pair a Mac or Linux computer to see its bots in this account.").font(.body).foregroundStyle(Palette.secondary)}+ .padding(.top, !introductory && onDone != nil ? 48 : 0)VStack(alignment: .leading, spacing: 14) {Step(n: 1, title: "Install Codync on your computer", detail: "Mac — then open Codync in the menu bar and click Install host:", code: "brew install --cask leepokai/codync/codync")@@ -74,7 +80,7 @@ struct PairingView: View {}}- Text("Pair this computer with the account currently selected on this iPhone. Your phone connects over Tailscale or local Wi-Fi; your code and chats stay on the computer.")+ Text("Your phone connects over Tailscale or local Wi-Fi. Your code and chats stay on the computer. You can manage accounts after setup.").font(.footnote).foregroundStyle(Palette.tertiary)}diff --git a/apps/ios/Views/RootView.swift b/apps/ios/Views/RootView.swiftindex 84574716..8bd4a492 100644--- a/apps/ios/Views/RootView.swift+++ b/apps/ios/Views/RootView.swift@@ -7,6 +7,7 @@ enum AppTab: Hashable { case bots, usage }struct RootView: View {@Environment(BotStore.self) private var model@Binding var tab: AppTab+ @AppStorage("onboardingCompleted") private var onboardingCompleted = false/// The open bot, as a NavigationStack path.private var path: Binding<[String]> {@@ -17,9 +18,11 @@ struct RootView: View {Group {if model.pairing == nil {NavigationStack {- PairingView()+ PairingView(introductory: !onboardingCompleted).toolbar {- ToolbarItem(placement: .topBarLeading) { AccountSwitcherButton() }+ if onboardingCompleted {+ ToolbarItem(placement: .topBarLeading) { AccountSwitcherButton() }+ }}}} else {@@ -42,6 +45,11 @@ struct RootView: View {}}.background(Palette.background)+ .onChange(of: model.pairing != nil, initial: true) { _, paired in+ // Existing installations have already completed setup. Keep this+ // device-level milestone across account changes and unpairing.+ if paired { onboardingCompleted = true }+ }.storeErrorAlert(model).fullScreenCover(item: Bindable(model).screenRequest) { request inScreenView(watching: request.watching)diff --git a/apps/ios/Views/SettingsView.swift b/apps/ios/Views/SettingsView.swiftindex 0d276052..0e89b41b 100644--- a/apps/ios/Views/SettingsView.swift+++ b/apps/ios/Views/SettingsView.swift@@ -62,6 +62,11 @@ struct SettingsView: View {}Section {+ NavigationLink {+ WidgetGalleryView()+ } label: {+ Label("Widgets", systemImage: "square.grid.2x2")+ }notificationsRow}@@ -97,7 +102,7 @@ struct SettingsView: View {}}.sheet(isPresented: $addingComputer) {- PairingView { addingComputer = false }+ PairingView(introductory: false) { addingComputer = false }}.confirmationDialog("Remove \(confirmForget?.name ?? "computer")?", isPresented: Binding(get: { confirmForget != nil }, set: { if !$0 { confirmForget = nil } }), titleVisibility: .visible) {Button("Remove", role: .destructive) {diff --git a/apps/ios/Views/UsageView.swift b/apps/ios/Views/UsageView.swiftindex 53e32dab..fe54cd25 100644--- a/apps/ios/Views/UsageView.swift+++ b/apps/ios/Views/UsageView.swift@@ -22,7 +22,7 @@ struct UsageView: View {description: Text("Your computer reads the limits from Claude Code and Codex.")).padding(.top, 60)}- Button("How to add a widget") { widgetHelp = true }+ Button("Widgets & setup") { widgetHelp = true }.font(.subheadline.weight(.medium)).foregroundStyle(Palette.secondary).padding(.top, 4)@@ -33,7 +33,17 @@ struct UsageView: View {.navigationTitle("Usage").navigationBarTitleDisplayMode(.inline).refreshable { await model.refreshUsage() }- .sheet(isPresented: $widgetHelp) { WidgetHelp() }+ .sheet(isPresented: $widgetHelp) {+ NavigationStack {+ WidgetGalleryView()+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button("Close", systemImage: "xmark") { widgetHelp = false }.labelStyle(.iconOnly)+ }+ }+ }+ .environment(model)+ }}}@@ -42,12 +52,12 @@ private struct ProviderCard: View {@Binding var collapsed: Boolvar body: some View {- VStack(alignment: .leading, spacing: 14) {- HStack(spacing: 12) {- AgentIcon(registry: provider.registry, size: 28)- .frame(width: 52, height: 52)- .background(provider.tint.opacity(0.12), in: RoundedRectangle(cornerRadius: 14, style: .continuous))- Text(provider.name).font(.title3.weight(.semibold)).foregroundStyle(Palette.text)+ VStack(alignment: .leading, spacing: 12) {+ HStack(spacing: 10) {+ AgentIcon(registry: provider.registry, size: 22)+ .frame(width: 34, height: 34)+ .background(provider.tint.opacity(0.12), in: RoundedRectangle(cornerRadius: 10, style: .continuous))+ Text(provider.name).font(.subheadline.weight(.semibold)).foregroundStyle(Palette.text)Spacer()Button(collapsed ? "Expand" : "Collapse", systemImage: "chevron.up") {withAnimation(.snappy) { collapsed.toggle() }@@ -66,7 +76,7 @@ private struct ProviderCard: View {}.font(.subheadline).foregroundStyle(Palette.text)- TickBar(percent: top.percent, tint: provider.tint)+ UsageTicks(percent: top.percent, tint: provider.widgetTint, height: 15)if let reset = top.resetsShort() {Text(reset).font(.caption.monospacedDigit()).foregroundStyle(Palette.tertiary).frame(maxWidth: .infinity, alignment: .trailing)@@ -76,7 +86,7 @@ private struct ProviderCard: View {if !collapsed {Divider()- VStack(spacing: 12) {+ VStack(spacing: 8) {ForEach(provider.windows) { w inrow(w.label, "\(Int(w.percent.rounded()))%")if let reset = w.resetsShort() { row("\(w.label) reset", reset.replacingOccurrences(of: "resets ", with: "")) }@@ -87,8 +97,8 @@ private struct ProviderCard: View {.transition(.opacity)}}- .padding(18)- .background(Palette.surface, in: RoundedRectangle(cornerRadius: 24, style: .continuous))+ .padding(14)+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 20, style: .continuous))}private var source: String {@@ -107,51 +117,6 @@ private struct ProviderCard: View {Spacer()Text(value).foregroundStyle(Palette.text).monospacedDigit()}- .font(.body)- }-}--/// Nowdex-style bar: a row of ticks, filled up to the percentage.-private struct TickBar: View {- let percent: Double- let tint: Color-- var body: some View {- GeometryReader { geo in- let count = max(1, Int(geo.size.width / 7))- let filled = Int((Double(count) * min(100, percent) / 100).rounded())- let color = percent >= 90 ? Palette.danger : tint- HStack(spacing: 3) {- ForEach(0..<count, id: \.self) { i in- Capsule().fill(i < filled ? color : color.opacity(0.18))- }- }- }- .frame(height: 24)- .accessibilityElement()- .accessibilityLabel("\(Int(percent.rounded())) percent used")- }-}--private struct WidgetHelp: View {- @Environment(\.dismiss) private var dismiss-- var body: some View {- NavigationStack {- List {- Label("Touch and hold an empty spot on your Home Screen until the apps jiggle.", systemImage: "hand.tap")- Label("Tap Edit, then Add Widget.", systemImage: "plus.square")- Label("Search for Codync and pick Provider usage or Usage limits.", systemImage: "magnifyingglass")- Label("Touch and hold the widget, then Edit Widget to choose Claude or Codex.", systemImage: "slider.horizontal.3")- }- .navigationTitle("Add a widget")- .navigationBarTitleDisplayMode(.inline)- .toolbar {- ToolbarItem(placement: .cancellationAction) {- Button("Close", systemImage: "xmark") { dismiss() }.labelStyle(.iconOnly)- }- }- }- .presentationDetents([.medium])+ .font(.footnote)}}diff --git a/apps/ios/Views/WidgetGalleryView.swift b/apps/ios/Views/WidgetGalleryView.swiftnew file mode 100644index 00000000..ee06eb43--- /dev/null+++ b/apps/ios/Views/WidgetGalleryView.swift@@ -0,0 +1,196 @@+import CodyncKit+import CodyncUI+import SwiftUI+import WidgetKit++/// The installed widgets and these previews share their rendering components.+struct WidgetGalleryView: View {+ @Environment(BotStore.self) private var model+ @Environment(\.scenePhase) private var scenePhase+ @Environment(\.dynamicTypeSize) private var typeSize+ @State private var kind = "usage"+ @State private var providerID = "claude"+ @State private var hasWidget: Bool?+ @State private var widgetCheckFailed = false++ private var provider: UsageProvider? { Usage.widgetPreview.providers.first { $0.id == providerID } }++ var body: some View {+ ScrollView {+ VStack(alignment: .leading, spacing: 24) {+ HStack(spacing: 14) {+ CharacterAvatar(shape: "hex", color: "gray", size: 42)+ .frame(width: 58, height: 58)+ .background(Palette.bubbleUser, in: RoundedRectangle(cornerRadius: 16))+ VStack(alignment: .leading, spacing: 4) {+ Text("Codync, at a glance.")+ .font(.title3.weight(.semibold)).tracking(-0.4)+ Text("Your bots and usage, right on your Home Screen.")+ .font(.footnote).foregroundStyle(Palette.secondary)+ }+ }+ .padding(16)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 22))++ VStack(alignment: .leading, spacing: 9) {+ sectionLabel("Get set up")+ VStack(spacing: 0) {+ setupRow("Connect a computer", complete: model.pairing != nil)+ Divider().padding(.leading, 42)+ setupRow("Add a Codync widget", complete: hasWidget == true,+ status: hasWidget == nil ? (widgetCheckFailed ? "Unable to check" : "Checking") : nil)+ }+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 18))+ if widgetCheckFailed {+ VStack(alignment: .leading, spacing: 6) {+ Text("Couldn't check your widgets. You can still add one using the steps below.")+ .foregroundStyle(Palette.secondary)+ Button("Check again") { checkWidgets() }+ }+ .font(.caption)+ } else {+ Text(hasWidget == nil ? "Checking your widgets…" : "Steps check themselves as you finish them.")+ .font(.caption2).foregroundStyle(Palette.tertiary)+ }+ }++ VStack(alignment: .leading, spacing: 14) {+ HStack {+ sectionLabel("Choose your widget")+ Spacer()+ Text("Sample data").font(.caption2).foregroundStyle(Palette.secondary)+ }+ if typeSize.isAccessibilitySize {+ kindPicker.pickerStyle(.menu)+ if kind == "usage" { providerPicker.pickerStyle(.menu) }+ } else {+ kindPicker.pickerStyle(.segmented)+ if kind == "usage" {+ providerPicker.pickerStyle(.segmented)+ }+ }+ VStack(spacing: 18) {+ preview(wide: true)+ .frame(height: 158)+ ViewThatFits(in: .horizontal) {+ HStack(alignment: .center, spacing: 18) {+ preview(wide: false).frame(width: 158, height: 158)+ previewDescription.frame(minWidth: 100)+ }+ VStack(alignment: .leading, spacing: 12) {+ preview(wide: false).frame(width: 158, height: 158)+ previewDescription+ }+ }+ }+ .padding(14)+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 26))+ }++ guide(number: "01", title: "Add the widget", icon: "plus.square.on.square",+ detail: "Touch and hold your Home Screen. Tap Edit, then Add Widget. Search for Codync and choose Bots or Provider usage.")+ guide(number: "02", title: "Make it yours", icon: "slider.horizontal.3",+ detail: "Touch and hold Provider usage, then tap Edit Widget to choose Claude or Codex. Widgets follow the account selected in Codync.")+ guide(number: "03", title: "On your Lock Screen", icon: "lock",+ detail: "Touch and hold your Lock Screen. Tap Customize, choose the Lock Screen, then tap the widget area. Select Codync to add Bots or Usage limits.")+ Text("Widgets show the last reported state. Open Codync for live updates and approvals.")+ .font(.caption).foregroundStyle(Palette.secondary)+ }+ .padding(18)+ .frame(maxWidth: 560)+ .frame(maxWidth: .infinity)+ }+ .background(Palette.background)+ .navigationTitle("Widgets")+ .navigationBarTitleDisplayMode(.inline)+ .task { checkWidgets() }+ .onChange(of: scenePhase) { _, phase in if phase == .active { checkWidgets() } }+ }++ private var kindPicker: some View {+ Picker("Widget", selection: $kind) {+ Text("Provider usage").tag("usage")+ Text("Bots").tag("bots")+ }+ }++ private var providerPicker: some View {+ Picker("Provider", selection: $providerID) {+ Text("Claude").tag("claude")+ Text("Codex").tag("codex")+ }+ }++ private var previewDescription: some View {+ VStack(alignment: .leading, spacing: 6) {+ Text("Small & medium").font(.subheadline.weight(.medium))+ Text(kind == "usage" ? "Small shows the tightest limit. Medium shows both windows." : "See who needs you and who's still working.")+ .font(.caption).foregroundStyle(Palette.secondary)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }++ @ViewBuilder private func preview(wide: Bool) -> some View {+ Group {+ if kind == "usage", let provider {+ ProviderWidgetCard(provider: provider, layout: wide ? .medium : .small)+ } else {+ BotsWidgetCard(bots: Bot.widgetPreview, wide: wide)+ }+ }+ .padding(14)+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 22))+ .accessibilityElement(children: .contain)+ .accessibilityLabel(wide ? "Medium widget preview" : "Small widget preview")+ }++ private func sectionLabel(_ title: String) -> some View {+ Text(title).font(.caption.weight(.medium)).foregroundStyle(Palette.secondary)+ .accessibilityAddTraits(.isHeader)+ }++ private func setupRow(_ title: String, complete: Bool, status: String? = nil) -> some View {+ HStack(spacing: 10) {+ Image(systemName: complete ? "checkmark.circle.fill" : "circle")+ .foregroundStyle(complete ? Palette.added : Palette.tertiary)+ .font(.system(size: 15))+ Text(title).font(.footnote).foregroundStyle(complete ? Palette.secondary : Palette.text)+ Spacer()+ }+ .padding(14)+ .accessibilityElement(children: .ignore)+ .accessibilityLabel(title)+ .accessibilityValue(status ?? (complete ? "Complete" : "Not complete"))+ }++ private func guide(number: String, title: String, icon: String, detail: String) -> some View {+ VStack(alignment: .leading, spacing: 12) {+ sectionLabel(title)+ HStack(alignment: .top, spacing: 14) {+ VStack(spacing: 8) {+ Image(systemName: icon).font(.system(size: 24, weight: .light))+ Text(number).font(.system(size: 10, weight: .medium, design: .monospaced))+ .foregroundStyle(Palette.tertiary)+ }+ .frame(width: 42)+ Text(detail).font(.footnote).foregroundStyle(Palette.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }+ .padding(18)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 20))+ }+ }++ private func checkWidgets() {+ widgetCheckFailed = false+ WidgetCenter.shared.getCurrentConfigurations { result in+ let installed = (try? result.get())?.contains { $0.kind.hasPrefix("Codync") }+ Task { @MainActor in+ hasWidget = installed+ widgetCheckFailed = installed == nil+ }+ }+ }+}diff --git a/apps/ios/Widgets/CodyncWidgets.swift b/apps/ios/Widgets/CodyncWidgets.swiftindex adc867ea..7e585b49 100644--- a/apps/ios/Widgets/CodyncWidgets.swift+++ b/apps/ios/Widgets/CodyncWidgets.swift@@ -24,11 +24,12 @@ struct BotsEntry: TimelineEntry {}struct BotsTimeline: TimelineProvider {- func placeholder(in context: Context) -> BotsEntry { BotsEntry(date: .now, bots: Bot.samples, paired: true) }+ func placeholder(in context: Context) -> BotsEntry { BotsEntry(date: .now, bots: Bot.widgetPreview, paired: true) }func getSnapshot(in context: Context, completion: @escaping (BotsEntry) -> Void) {- let bots = SharedStore.bots- completion(BotsEntry(date: .now, bots: bots.isEmpty && context.isPreview ? Bot.samples : bots, paired: true))+ let storage = SharedStore.activeContext+ completion(BotsEntry(date: .now, bots: context.isPreview ? Bot.widgetPreview : storage.bots,+ paired: context.isPreview || storage.pairing != nil))}/// The app writes the roster and reloads this widget when a bot's state changes.@@ -44,7 +45,7 @@ struct BotsWidget: Widget {var body: some WidgetConfiguration {StaticConfiguration(kind: "CodyncBots", provider: BotsTimeline()) { entry inBotsWidgetView(entry: entry)- .containerBackground(Palette.background, for: .widget)+ .containerBackground(Palette.surface, for: .widget)}.configurationDisplayName("Bots").description("Which bots need you, which are working, and what they said last.")@@ -63,23 +64,34 @@ struct BotsWidgetView: View {return rank($0) != rank($1) ? rank($0) < rank($1) : $0.lastAt > $1.lastAt}}- private var needing: Int { entry.bots.filter(\.needsInput).count }- private var working: Int { entry.bots.filter { $0.isWorking && !$0.needsInput }.count }+ private var needing: Int { ordered.filter(\.needsInput).count }+ private var working: Int { ordered.filter { $0.isWorking && !$0.needsInput }.count }/// The one line that sums up the roster.private var headline: (count: Int, label: String, needs: Bool) {if needing > 0 { return (needing, needing == 1 ? "needs you" : "need you", true) }if working > 0 { return (working, "working", false) }- return (entry.bots.count, entry.bots.count == 1 ? "bot, all quiet" : "bots, all quiet", false)+ return (ordered.count, ordered.count == 1 ? "bot, all quiet" : "bots, all quiet", false)}var body: some View {if !entry.paired {- EmptyWidget(text: "Open Codync to pair with your computer.")+ switch family {+ case .accessoryInline:+ Text("Connect Codync to your computer")+ case .accessoryCircular:+ Image(systemName: "desktopcomputer")+ .accessibilityLabel("Connect Codync to your computer")+ case .accessoryRectangular:+ Label("Connect a computer", systemImage: "desktopcomputer")+ .font(.caption)+ default:+ EmptyWidget(text: "Open Codync to pair with your computer.")+ }} else {switch family {case .accessoryInline:- Text(needing > 0 ? "\(needing) bot\(needing == 1 ? "" : "s") need\(needing == 1 ? "s" : "") you" : working > 0 ? "\(working) working" : "Bots all quiet")+ Text(needing > 0 ? "\(needing) bot\(needing == 1 ? "" : "s") need\(needing == 1 ? "s" : "") you" : working > 0 ? "\(working) working" : ordered.isEmpty ? "No bots yet" : "Bots all quiet")case .accessoryCircular:VStack(spacing: 0) {Text("\(headline.count)").font(.system(size: 24, weight: .semibold, design: .rounded))@@ -95,40 +107,10 @@ struct BotsWidgetView: View {}.frame(maxWidth: .infinity, alignment: .leading)case .systemMedium:- HStack(alignment: .top, spacing: 16) {- summary.frame(width: 104, alignment: .leading)- VStack(alignment: .leading, spacing: 10) {- ForEach(ordered.prefix(3)) { bot in- Link(destination: entry.links[bot.id] ?? URL(string: "codync://computers")!) { BotLine(bot: bot, detail: line(bot)) }- }- Spacer(minLength: 0)- }- }+ BotsWidgetCard(bots: entry.bots, wide: true, links: entry.links)default:- VStack(alignment: .leading, spacing: 0) {- HStack(spacing: -6) {- ForEach(ordered.prefix(3)) { bot in- CharacterAvatar(bot: bot, size: 30, animated: false)- }- }- Spacer(minLength: 6)- summary- }- .frame(maxWidth: .infinity, alignment: .leading)- .widgetURL(ordered.first.flatMap { entry.links[$0.id] })- }- }- }-- private var summary: some View {- VStack(alignment: .leading, spacing: 2) {- Text("\(headline.count)")- .font(.system(size: 40, weight: .semibold, design: .rounded))- .foregroundStyle(headline.needs ? Palette.warning : Palette.text)- .contentTransition(.numericText())- Text(headline.label).font(.subheadline).foregroundStyle(Palette.secondary)- if family == .systemSmall, let first = ordered.first, first.isWorking {- Text(first.name).font(.caption).foregroundStyle(Palette.tertiary).lineLimit(1).padding(.top, 2)+ BotsWidgetCard(bots: entry.bots, wide: false)+ .widgetURL(ordered.first.flatMap { entry.links[$0.id] })}}}@@ -140,31 +122,12 @@ struct BotsWidgetView: View {}}-private struct BotLine: View {- let bot: Bot- let detail: String-- var body: some View {- HStack(spacing: 10) {- CharacterAvatar(bot: bot, size: 28, animated: false)- VStack(alignment: .leading, spacing: 1) {- Text(bot.name).font(.subheadline.weight(.semibold)).foregroundStyle(Palette.text).lineLimit(1)- Text(detail)- .font(.caption)- .foregroundStyle(bot.needsInput ? Palette.warning : Palette.secondary)- .lineLimit(1)- }- Spacer(minLength: 0)- }- }-}-private struct EmptyWidget: View {let text: Stringvar body: some View {VStack(alignment: .leading, spacing: 8) {- CharacterAvatar(shape: "blob", color: "gray", size: 30)+ CharacterAvatar(shape: "blob", color: "gray", size: 26, mood: .idle)Spacer(minLength: 0)Text(text).font(.caption).foregroundStyle(Palette.secondary)}@@ -172,17 +135,6 @@ private struct EmptyWidget: View {}}-extension Bot {- static let samples: [Bot] = {- let json = """- [{"id":"1","name":"Reviewer","avatarShape":"blob","avatarColor":"green","backend":"claude","cwd":"/","status":"needsInput","activity":"Run cargo test --all?","lastAt":3},- {"id":"2","name":"Fixer","avatarShape":"squircle","avatarColor":"orange","backend":"codex","cwd":"/","status":"working","activity":"Editing store.rs","lastAt":2},- {"id":"3","name":"Docs writer","avatarShape":"teardrop","avatarColor":"violet","backend":"claude","cwd":"/","status":"idle","lastMessage":"README updated.","lastAt":1}]- """- return (try? JSONDecoder().decode([Bot].self, from: Data(json.utf8))) ?? []- }()-}-// MARK: - Usage limitsstruct UsageEntry: TimelineEntry {@@ -196,11 +148,11 @@ struct UsageIntent: WidgetConfigurationIntent {struct UsageTimeline: AppIntentTimelineProvider {func placeholder(in context: Context) -> UsageEntry {- UsageEntry(date: .now, usage: .sample)+ UsageEntry(date: .now, usage: .widgetPreview)}func snapshot(for configuration: UsageIntent, in context: Context) async -> UsageEntry {- UsageEntry(date: .now, usage: SharedStore.usage ?? .sample)+ UsageEntry(date: .now, usage: context.isPreview ? .widgetPreview : (SharedStore.usage ?? Usage()))}/// Refreshes every 30 minutes, or right after the next limit resets if that's sooner.@@ -209,8 +161,13 @@ struct UsageTimeline: AppIntentTimelineProvider {}static func timeline() async -> Timeline<UsageEntry> {- let fetched = await fetch()- let usage = fetched ?? SharedStore.usage ?? Usage()+ let storage = SharedStore.activeContext+ let computer = storage.pairing?.token+ let fetched = await fetch(storage: storage)+ guard SharedStore.activeContext.id == storage.id, storage.pairing?.token == computer else {+ return Timeline(entries: [UsageEntry(date: .now, usage: Usage())], policy: .after(.now + 5))+ }+ let usage = fetched ?? storage.usage ?? Usage()let nextReset = usage.providers.flatMap(\.windows).compactMap(\.resetDate).filter { $0 > .now }.min()var next = Date.now + (fetched == nil ? 5 * 60 : 30 * 60)if let nextReset, nextReset + 1 < next { next = max(nextReset + 1, .now + 5 * 60) }@@ -219,23 +176,20 @@ struct UsageTimeline: AppIntentTimelineProvider {/// Asks the paired host directly (works over Tailscale), falling back to the app's cache./// `refresh` makes the host re-read the limits first instead of answering from its cache.- static func fetch(refresh: Bool = false) async -> Usage? {- guard let pairing = SharedStore.orderedPairing, let client = await HostClient.resolve(pairing),- let usage = try? await client.usage(refresh: refresh) else { return nil }- SharedStore.usage = usage+ static func fetch(refresh: Bool = false, storage: SharedStore.Context = SharedStore.activeContext) async -> Usage? {+ guard let pairing = storage.orderedPairing, let client = await HostClient.resolve(pairing),+ let usage = try? await client.usage(refresh: refresh),+ SharedStore.activeContext.id == storage.id, storage.pairing?.token == pairing.token else { return nil }+ storage.usage = usagereturn usage}}-extension Usage {- static let sample = Usage(providers: [])-}-struct UsageWidget: Widget {var body: some WidgetConfiguration {AppIntentConfiguration(kind: "CodyncUsage", intent: UsageIntent.self, provider: UsageTimeline()) { entry inUsageWidgetView(entry: entry)- .containerBackground(Palette.background, for: .widget)+ .containerBackground(Palette.surface, for: .widget)}.configurationDisplayName("Usage limits").description("Claude and Codex subscription limits from your computer.")@@ -307,7 +261,7 @@ struct UsageWidgetView: View {VStack(alignment: .leading, spacing: 2) {Text("\(item.provider) · \(item.window.label)").font(.caption).foregroundStyle(Palette.secondary).lineLimit(1)Text(percent(item.window))- .font(.system(size: 40, weight: .semibold, design: .rounded))+ .font(.system(size: 34, weight: .semibold, design: .rounded)).monospacedDigit().foregroundStyle(item.window.percent >= 90 ? Palette.danger : Palette.text).minimumScaleFactor(0.7)@@ -324,7 +278,7 @@ struct UsageWidgetView: View {}.font(.caption2).foregroundStyle(Palette.secondary)- UsageBar(percent: item.window.percent, height: 4)+ UsageTicks(percent: item.window.percent, tint: Palette.usageTint(item.window.percent), height: 10)}}@@ -365,11 +319,11 @@ struct ProviderUsageEntry: TimelineEntry {struct ProviderUsageTimeline: AppIntentTimelineProvider {func placeholder(in context: Context) -> ProviderUsageEntry {- ProviderUsageEntry(date: .now, usage: .preview, provider: .claude)+ ProviderUsageEntry(date: .now, usage: .widgetPreview, provider: .claude)}func snapshot(for configuration: ProviderUsageIntent, in context: Context) async -> ProviderUsageEntry {- let usage = SharedStore.usage.flatMap { $0.providers.isEmpty ? nil : $0 } ?? .preview+ let usage = context.isPreview ? .widgetPreview : (SharedStore.usage ?? Usage())return ProviderUsageEntry(date: .now, usage: usage, provider: configuration.provider)}@@ -380,110 +334,34 @@ struct ProviderUsageTimeline: AppIntentTimelineProvider {}}-/// The widget's refresh button: asks the host to re-read the limits; WidgetKit-/// reloads the widget when this returns.-struct RefreshUsageIntent: AppIntent {- static let title: LocalizedStringResource = "Refresh usage"-- func perform() async throws -> some IntentResult {- _ = await UsageTimeline.fetch(refresh: true)- return .result()- }-}--extension Usage {- static let preview: Usage = {- let json = """- {"providers":[{"id":"claude","name":"Claude","source":"claude","updatedAt":0,"windows":[- {"id":"five_hour","label":"5-hour","percent":16},{"id":"seven_day","label":"Weekly","percent":59}]},- {"id":"codex","name":"Codex","source":"sessions","updatedAt":0,"windows":[- {"id":"primary","label":"5-hour","percent":8},{"id":"secondary","label":"Weekly","percent":70}]}]}- """- return (try? JSONDecoder().decode(Usage.self, from: Data(json.utf8))) ?? Usage()- }()-}-struct ProviderUsageWidget: Widget {var body: some WidgetConfiguration {AppIntentConfiguration(kind: "CodyncProviderUsage", intent: ProviderUsageIntent.self, provider: ProviderUsageTimeline()) { entry inProviderUsageView(entry: entry)}.configurationDisplayName("Provider usage")- .description("One provider's session and weekly limits, with its character.")- .supportedFamilies([.systemMedium])+ .description("Session and weekly limits in a compact, easy-to-read card.")+ .supportedFamilies([.systemSmall, .systemMedium])}}-/// A provider card: its character and name on the left, the two main limits on the right.+/// Uses the exact same card as the in-app widget gallery.struct ProviderUsageView: View {let entry: ProviderUsageEntry-+ @Environment(\.widgetFamily) private var familyprivate var provider: UsageProvider? { entry.usage.providers.first { $0.id == entry.provider.rawValue } }var body: some View {- let tint = provider?.tint ?? Palette.accentGroup {- if let provider {- HStack(spacing: 18) {- VStack(alignment: .leading, spacing: 2) {- ProviderMascot(provider, size: 52)- Spacer(minLength: 4)- Text(provider.name).font(.system(.title3, design: .serif, weight: .bold)).foregroundStyle(Palette.text)- Text("Usage").font(.subheadline).foregroundStyle(Palette.secondary)- }- .frame(width: 80, alignment: .leading)- VStack(alignment: .leading, spacing: 10) {- ForEach(provider.windows.prefix(2)) { window(provider, $0) }- Spacer(minLength: 0)- HStack {- Text("updated \(Date(milliseconds: provider.updatedAt).formatted(date: .omitted, time: .shortened))")- Spacer()- Button(intent: RefreshUsageIntent()) {- Image(systemName: "arrow.clockwise").font(.subheadline.weight(.semibold))- }- .buttonStyle(.plain)- .accessibilityLabel("Refresh")- }- .font(.caption2)- .foregroundStyle(Palette.secondary)- }- }+ if let provider, !provider.windows.isEmpty {+ ProviderWidgetCard(provider: provider, layout: family == .systemSmall ? .small : .medium, date: entry.date)} else {- EmptyWidget(text: SharedStore.pairing == nil ? "Open Codync to pair with your computer."- : "No \(entry.provider.rawValue.capitalized) usage reported yet.")+ EmptyWidget(text: "Open Codync to connect a computer and check \(entry.provider.rawValue.capitalized) usage.")}}- .containerBackground(for: .widget) {- LinearGradient(colors: [tint.opacity(0.16), tint.opacity(0.03), tint.opacity(0.12)],- startPoint: .topLeading, endPoint: .bottomTrailing)- .background(Palette.background)- }+ .containerBackground(Palette.surface, for: .widget).widgetURL(URL(string: "codync://usage"))}-- private func window(_ provider: UsageProvider, _ w: UsageWindow) -> some View {- let color = w.percent >= 90 ? Palette.danger : provider.tint- return VStack(alignment: .leading, spacing: 5) {- HStack(alignment: .firstTextBaseline, spacing: 6) {- Text(w.title).font(.system(.subheadline, design: .serif, weight: .bold)).foregroundStyle(Palette.text)- Text([w.span, w.resetsShort(now: entry.date)].compactMap(\.self).joined(separator: " · "))- .font(.caption2)- .foregroundStyle(Palette.secondary)- .lineLimit(1)- Spacer(minLength: 4)- Text("\(Text("\(Int(w.percent.rounded()))").font(.system(.title3, design: .serif, weight: .bold)))\(Text("%").font(.system(.caption, design: .serif, weight: .bold)))")- .foregroundStyle(color)- .monospacedDigit()- }- GeometryReader { geo in- ZStack(alignment: .leading) {- Capsule().fill(Palette.text.opacity(0.1))- Capsule().fill(color).frame(width: geo.size.width * min(1, max(0.03, w.percent / 100)))- }- }- .frame(height: 7)- }- }}// MARK: - Live Activitydiff --git a/apps/ios/Widgets/WidgetPreviews.swift b/apps/ios/Widgets/WidgetPreviews.swiftnew file mode 100644index 00000000..f53cdadf--- /dev/null+++ b/apps/ios/Widgets/WidgetPreviews.swift@@ -0,0 +1,59 @@+#if DEBUG+import CodyncKit+import SwiftUI+import WidgetKit++// Native WidgetKit previews exercise the actual configurations, including their+// system margins and accessory families. All data here is explicitly synthetic.+#Preview(as: .systemSmall) {+ ProviderUsageWidget()+} timeline: {+ ProviderUsageEntry(date: .now, usage: .widgetPreview, provider: .claude)+ ProviderUsageEntry(date: .now, usage: .widgetPreview, provider: .codex)+ ProviderUsageEntry(date: .now, usage: Usage(), provider: .claude)+}++#Preview(as: .systemMedium) {+ ProviderUsageWidget()+} timeline: {+ ProviderUsageEntry(date: .now, usage: .widgetPreview, provider: .claude)+ ProviderUsageEntry(date: .now, usage: .widgetPreview, provider: .codex)+}++#Preview(as: .systemSmall) {+ BotsWidget()+} timeline: {+ BotsEntry(date: .now, bots: Bot.widgetPreview, paired: true)+ BotsEntry(date: .now, bots: [], paired: true)+ BotsEntry(date: .now, bots: [], paired: false)+}++#Preview(as: .systemMedium) {+ BotsWidget()+} timeline: {+ BotsEntry(date: .now, bots: Bot.widgetPreview, paired: true)+ BotsEntry(date: .now, bots: [], paired: true)+ BotsEntry(date: .now, bots: [], paired: false)+}++#Preview(as: .accessoryRectangular) {+ BotsWidget()+} timeline: {+ BotsEntry(date: .now, bots: Bot.widgetPreview, paired: true)+ BotsEntry(date: .now, bots: [], paired: false)+}++#Preview(as: .accessoryCircular) {+ UsageWidget()+} timeline: {+ UsageEntry(date: .now, usage: .widgetPreview)+ UsageEntry(date: .now, usage: Usage())+}++#Preview(as: .accessoryInline) {+ UsageWidget()+} timeline: {+ UsageEntry(date: .now, usage: .widgetPreview)+ UsageEntry(date: .now, usage: Usage())+}+#endifdiff --git a/docs/bot-collaboration.md b/docs/bot-collaboration.mdnew file mode 100644index 00000000..18c431da--- /dev/null+++ b/docs/bot-collaboration.md@@ -0,0 +1,36 @@+# Bot collaboration++Create two or more bots normally, giving each a clear name, description, project folder and agent. Then message one:++> Ask Reviewer to inspect the changes in /path/to/project. Have it report bugs without editing files, then summarize its findings for me.++Every bot receives the built-in `team` MCP server. `list_bots` returns the other visible bots' IDs, descriptions, agents, folders and status. `ask_bot(botId, message)` sends a self-contained request and waits for the recipient's final text reply. The requesting bot incorporates that answer into its response to you. The same tools work across ACP backends that support MCP servers.++The host records the request and its outcome in both chats using existing notice entries, so the current iOS, macOS, Linux and terminal clients can display them. Tool details also remain in the trace. There is no additional team setup screen.++## Execution++- Each bot still owns one ACP process/session and runs one turn at a time. A busy recipient queues the request. Different bots can work concurrently.+- Requests have their own reply channel and never merge with user messages or another request. Contiguous user messages keep the existing batching behavior.+- The recipient uses its own folder, tools, memory and permission policy. Permission cards appear in its chat. The requesting bot's entire transcript is not copied; only the request is passed. Requests are not treated as user facts by the memory keeper.+- The host rejects self-delegation, duplicate outstanding requests to the same recipient, and direct or indirect wait cycles, including queued requests. Up to 64 requests can be outstanding host-wide.+- Native Claude Code/Codex subagents remain managed by the harness. Codync does not turn them into permanent bots or override their delegation settings.++## Stops, failures and restart++- The wait limit is ten minutes, including queue and approval time. Failure is a tool error, not a fabricated successful reply. `ask_bot` is not automatically retried.+- Stopping the requesting bot cancels its outgoing requests. A queued request is removed; a running delegated turn's ACP process is stopped. Unrelated queued messages on the recipient remain. Stopping the recipient also releases its requesters once its turn stops.+- Deleting either bot cancels affected requests. Recipient startup failures, crashes, refusals and empty replies surface to the requester.+- Pending request notices are persisted with IDs and statuses. After host restart they become interrupted errors; delegated turns are not automatically replayed. Check partial work before retrying. Ordinary user turns retain their existing session-resume behavior.+- Completion push notifications come from the requesting bot; delegated replies do not send a second “done” push. Recipient permission requests still use the usual “needs you” notifications.++This first version uses synchronous request/reply over MCP and does not introduce a task scheduler or isolated worktrees. Give bots explicit file ownership when they share a working directory. Rebuild and restart the host to load the new built-in MCP server; phone clients need no protocol upgrade.++## Code and verification++- `host/src/team.rs`: discovery, wait graph, request lifetime and persisted notices.+- `host/src/bot.rs`: queue boundaries, recipient execution, completion and targeted cancellation.+- `host/src/mcp.rs`: the authenticated local MCP → HTTP bridge.+- `host/tests/team_e2e.rs`: a real host and MCP subprocess, with scripted ACP agents, covering discovery → delegation → recipient approval → reply → client sync. No paid provider calls.++Run `cargo test` and `cargo clippy --all-targets -- -D warnings` in `host/`.diff --git a/docs/clerk-macos.md b/docs/clerk-macos.mdindex db7ffe06..6a45cb40 100644--- a/docs/clerk-macos.md+++ b/docs/clerk-macos.md@@ -80,3 +80,17 @@ push revocation and Keychain migration remain work in the architecture plan.Verify with two real Google accounts: add both, switch, cancel OAuth, restart,check each account's pairings, sign out just one, and verify the other remains.A simulator build verifies compilation, not the Dashboard settings or OAuth flow.++### Local verification on 2026-09-25++- iOS Simulator build succeeded with normal simulator signing. Do not use+ `CODE_SIGNING_ALLOWED=NO` for a Clerk runtime smoke test: an unsigned simulator+ installation failed Keychain initialization with OSStatus -34018.+- The app launches, the top-left Accounts sheet opens, and its Computers & settings+ destination navigates successfully in iPhone 17 Pro / iOS 26.5 Simulator.+- `swift test --package-path kit`: 9 tests passed, including account storage+ separation, legacy pairing preservation, and rejecting another account or+ computer's old widget link.+- Real Google login, two-account switching, and Clerk Dashboard configuration still+ need end-to-end verification with test accounts. No cloud ownership implementation+ or Cloudflare deployment was performed in this change.diff --git a/docs/cloudflare-account-device-plan.md b/docs/cloudflare-account-device-plan.mdindex a320fed1..ffb1e978 100644--- a/docs/cloudflare-account-device-plan.md+++ b/docs/cloudflare-account-device-plan.md@@ -1,7 +1,13 @@# Codync 帳號、裝置管理與 Cloudflare 架構計畫日期:2026-09-25-狀態:規劃文件;尚未實作或部署。文中的時間、容量與保留期限是建議產品設定,不是服務商限制。+狀態:雲端、逐裝置授權與 SSH 為規劃,尚未部署;手機帳號入口與本機資料分區已實作,詳見補充計畫的落地範圍。文中的時間、容量與保留期限是建議產品設定,不是服務商限制。++## 執行分工(2026-09-25 更新)++Cloudflare API、D1、裝置目錄、雲端授權/撤權與中繼由 Claude Code 接續實作。本次 Codex 修改範圍是手機帳號入口、共享 Clerk session wrapper、本機帳號分區與計畫文件;未建立或部署 `cloud/`,也未修改既有 `relay/`。++前後端整合時以已驗證的 Clerk user ID 作帳號關聯;不要把目前手機的配對資料分區誤認為已完成後端 ownership。新增 API 後應接到 `CloudClient`/account store,而非重新複製一套登入流程。## 1. 目標與核心決策@@ -39,10 +45,10 @@| 現況 | 程式位置 | 對計畫的影響 ||---|---|---|| Mac 已使用 ClerkKit,支援 Google 登入 | `apps/shared/AccountSession.swift`、`docs/clerk-macos.md` | 延伸現有登入,不另建帳號系統 |-| iOS 尚未接 Clerk,以掃碼配對進入主畫面 | `apps/ios/App/CodyncApp.swift`、`apps/ios/Views/RootView.swift`、`PairingView.swift` | 新增可略過的登入入口與雲端電腦清單 |+| iOS 已接 Clerk 帳號入口,電腦仍靠掃碼配對 | `apps/ios/App/CodyncApp.swift`、`apps/ios/Views/RootView.swift`、`PairingView.swift` | 登入入口已建立;雲端電腦清單待實作 || host SQLite 位於 `~/.codync/codync.db` | `host/src/main.rs`、`host/src/store.rs` | 保留本機資料與既有 `rev` 同步機制 || host 使用共用 pairing token,旋轉會使所有舊裝置失效 | `host/src/main.rs`、`host/src/api.rs` | 必須新增逐裝置授權,才能精準撤權 |-| 手機配對資料序列化到 App Group UserDefaults | `kit/Sources/CodyncKit/Client/SharedStore.swift` | 秘密搬到 Keychain,UserDefaults 僅留顯示資料與參照 |+| 手機配對資料依帳號分區存入 App Group UserDefaults | `kit/Sources/CodyncKit/Client/SharedStore.swift` | 秘密搬到 Keychain,UserDefaults 僅留顯示資料與參照 || 命令走 HTTP API,事件走 SSE | `host/src/api.rs`、`kit/Sources/CodyncKit/Client/HostClient.swift` | 第一版沿用;後續用 transport 抽象接中繼 || 已有 Cloudflare Worker 轉送 APNs,使用加密 ticket | `relay/src/index.ts`、`relay/wrangler.toml` | 保留相容性;它目前不是裝置目錄或聊天中繼 || Remote screen 使用獨立 helper 與 WebRTC | `apps/screen/`、`kit/Sources/CodyncUI/Screen/` | 影像傳輸與聊天中繼分開 |diff --git a/docs/context-and-memory.md b/docs/context-and-memory.mdnew file mode 100644index 00000000..b131cec3--- /dev/null+++ b/docs/context-and-memory.md@@ -0,0 +1,71 @@+# Context and memory++How a bot keeps its instructions, context and long-term memory. The mechanisms follow Grok Bot's design+(`system-prompt-assembly`, `sand-memory`, `turn-memory`, `upgrade-recreate-resume`) and are adapted to ACP,+where the harness owns the conversation.++## Two memories++| | Where | Owner | Lifetime |+|---|---|---|---|+| Transcript | SQLite `entries` | Codync | Forever, one endless thread per bot |+| Model context | ACP session (`bots.session_id`) | The harness | Until *New session*, a failed resume, or an agent/command/folder change |+| Long-term memory | `~/.codync/bots/<id>/memory/` | Codync (keeper) + the user | Forever, across sessions |++Codync never replays the transcript into a session. Each turn sends only the new message(s); the harness keeps+its own context and compacts it itself.++## Instruction snapshot (`host/src/context.rs`)++- The bot's instructions are rendered once: profile (name, description, skills, phone-friendly rule) plus the+ memory section. They're stored as a snapshot in `kv` under `context.<bot>`, keyed by **session + compaction+ epoch**, and don't change until one of those changes. This keeps the prompt byte-identical so the prompt+ cache stays warm.+- **Claude** (`agentCapabilities._meta.claudeCode` present) receives the snapshot as a real system prompt:+ `_meta.systemPrompt.append` on `session/new` and `session/load`. It survives compaction.+- **Other harnesses** receive it in the first message of each session (`<bot-profile>…</bot-profile>`).+- **Compaction epoch:** Codync advertises `clientCapabilities.session.compaction`. Each completed+ `compaction_update` (deduplicated by `compactionId`) increments `context.epoch.<bot>`. The next turn+ re-renders the snapshot, and Claude's session is loaded again with the new system prompt. The adapter+ rebuilds its query and resumes the same conversation.+- **Profile edits mid-session** (name, description, skills) are sent once as an `<agent_profile_update>` block+ appended to the next message. After that turn reaches the agent, the change is recorded in+ `snapshot.announced`. The next compaction folds it into the snapshot.++## Memory (`host/src/memory.rs`)++- Facts are plain markdown, one `- (YYYY-MM-DD) fact` per line:+ - `profile.md` holds who the user is. All of it goes into the prompt, up to 100 facts.+ - `log/YYYY-MM.md` holds dated history, including `[note]` and `[episode]` lines. The newest 30 go into the+ prompt, within 4,000 characters.+- **Keeper:** after a turn ends normally, if the user's message is memorable (not "thanks"/"ok"), a one-shot+ agent of the bot's own harness extracts facts using Grok Bot's extraction prompt+ (`profile:` / `log:` / `note:` / `remove:`).+ - On Claude it runs with a replaced system prompt, no tools, no settings, `persistSession: false` and the+ `haiku` model.+ - Other harnesses get the instructions inline, in `~/.codync/memory-keeper`.+- **Episodes:** every 6 remembered exchanges (pending turns in `memory.episode.<bot>`), the keeper writes one+ `[episode]` journal sentence.+- The agent is told where its memory folder is so it can grep older facts. Facts learned mid-session reach its+ prompt at the next compaction or session.+- **API:** `memory`, `forgetMemory`, `clearMemory`. The Memory card in bot settings lists and removes facts.++## Turns++- Messages sent while the agent works are folded into one next turn, joined by blank lines.+- Bot-to-bot requests occupy separate turns in the same queue; user messages are only folded together up to the next request. Requests never feed the user-fact memory keeper. See [bot collaboration](bot-collaboration.md).+- Delegated turns do not set the restart marker: their waiter disappears on restart. Pending delegation notices become interrupted errors instead of automatically replaying work.+- `turn.inflight.<bot>` holds the start time of a running turn. If the host stops mid-turn (update, crash, restart), the next+ start resumes that session with a hidden "you were interrupted, don't repeat finished steps" prompt. If the+ session can't be resumed, or the turn started over an hour ago, it does nothing.++## Limits++- Harnesses other than Claude have no system prompt channel and don't report compaction. For them, the first+ message carries the instructions and the snapshot only refreshes when a new session starts.+- Compaction is the harness's own. Codync can't choose what survives it, only re-apply its instructions+ afterwards.+- A session a harness has deleted (for example, one cleaned up after a month) can't be resumed. The bot+ starts fresh, but its memory remains.+- User-level memory shared across bots, project memory and the daily memory "dreaming" pass from Grok Bot+ are not implemented.diff --git a/docs/mobile-widgets-design.md b/docs/mobile-widgets-design.mdnew file mode 100644index 00000000..c3e5b438--- /dev/null+++ b/docs/mobile-widgets-design.md@@ -0,0 +1,79 @@+# Mobile onboarding 與 Widgets 設計++更新:2026-09-25。此工作範圍是 iOS 介面與 WidgetKit;Cloudflare 後端由 Claude Code 另行實作。++## 參考方向++透過 iPhone Mirroring 觀察已安裝的兩個 app,沿用它們已建立的資訊層級:++- **Nowdex 的狀態首頁**:小型 provider 圖示、緊湊的用量卡片、細刻度進度條、標籤靠左/數值靠右、次要重置時間。+- **Nomo 的 Home 設定頁**:簡短介紹、依實際狀態完成的設定清單、加入 widget 與編輯 widget 的分段教學。++這次觀察到的是上述頁面,未完整操作兩款 app 的內部 widget 選擇頁。Codync 以自己的 SwiftUI 元件、角色圖示與教學重建這些模式,沒有匯入兩款 app 的程式碼、影片或素材。++## Onboarding 與帳號++1. 首次開啟先顯示連接電腦流程,隱藏左上角 profile/帳號切換入口,也不彈出帳號選單。+2. 儲存第一台配對電腦後,記錄此裝置的 `onboardingCompleted`。+3. 既有已配對安裝自動視為完成 onboarding。+4. 完成後才顯示帳號入口;切換到沒有電腦的帳號,或解除配對後,入口仍保留,避免無法切回原帳號。+5. 「帳號」代表 Codync 的 Google/Clerk 登入身分。帳號與 computer 是不同概念。++目前完成條件沿用現有的配對資料儲存事件,不代表已驗證雲端登入或 host 當下在線。待雲端 onboarding 整合時,應由單一流程明確管理登入、電腦註冊與完成狀態。++## Widget 與 App 內預覽++| 類型 | Small | Medium |+| --- | --- | --- |+| Provider usage | provider、最接近上限的用量、細刻度條、重置時間 | 同一 provider 的兩個用量視窗與重置時間 |+| Bots | 待回應/工作中的數量與角色圖示 | 狀態摘要與最多三個 bot,待回應優先 |++- Provider usage 可在系統「編輯 Widget」選擇 Claude 或 Codex。+- Claude 使用既有暖色;Codex 使用藍色;90% 以上顯示警示色。+- 採平面深淺色表面、小型圖示、11–13 pt 標籤;大字只用於主要數值。+- App 的 Usage 卡片同步縮小字級、圖示、內距,並使用同一款刻度條。+- Widgets 頁可從 Settings 或 Usage 的「Widgets & setup」進入,提供類型/provider 切換、小/中預覽與設定教學。+- 設定清單讀取實際電腦配對狀態與 `WidgetCenter` 的已安裝配置;不以點過教學當作完成。+- 查詢失敗時顯示錯誤與「Check again」,不會永久停在載入狀態。+- 預覽明確標示 Sample data。已安裝的 widget 不用範例資料掩蓋未配對或尚無用量的狀態。+- App 教學、設定清單與說明支援 Dynamic Type;無障礙大字體改用選單切換類型/provider。固定大小的 widget 保留緊湊數值,並提供完整的 VoiceOver 用量與重置描述。+- 教學涵蓋 Home Screen 與 Lock Screen;新增 WidgetKit 原生預覽涵蓋小/中尺寸、矩形/圓形/行內配件與空狀態。++`kit/Sources/CodyncKit/Design/WidgetCards.swift` 是共用繪製元件;`apps/ios/Views/WidgetGalleryView.swift` 與 `apps/ios/Widgets/CodyncWidgets.swift` 共用它,減少預覽與實際 widget 的差異。++## 資料與互動++- Widgets 跟隨 App 目前選取的帳號,讀取該帳號的 App Group 快取;不合併不同帳號的 bots 或用量。+- 切換帳號時由既有 App 流程重載 widgets;非同步用量請求保留原 storage context,避免舊回應寫入新帳號。+- 切換或移除目前電腦時清除舊用量、bot 快取與偏好 URL;更新同一台電腦的地址則保留快取。+- App 與 widget 的非同步用量回應都核對 computer token,避免切換途中收到的舊資料覆蓋新電腦。+- Bot 新增、改名、活動變化、隱藏、刪除與清空都會更新 widget feed;刷新判斷包含 widget 實際顯示的欄位。+- Bot 連結帶有帳號與電腦範圍,舊 widget 的連結不會直接開啟其他帳號的 bot。+- Provider widget 點擊開啟 Usage。Bot 的中尺寸可點擊個別 bot。+- Widgets 顯示最近回報的狀態;即時聊天與審批在 App 完成。WidgetKit 排程由系統決定,不保證即時更新。+- Bots 由 App 更新快取後重載;用量沿用目前直接連 host 的刷新與快取退路,未加入新的 Cloudflare API。++## 驗證與後續++已完成:++- iOS Simulator build,含 widget extension 與原生 WidgetKit 預覽巨集,沒有編譯警告。+- Swift package 10 個測試,包含跨帳號隔離與跨電腦 widget 快取清除/保留的回歸測試。+- 首次 onboarding 隱藏帳號入口;完成後,即使沒有電腦仍保留帳號入口。+- App 內 Widgets 頁、Claude/Codex 預覽切換、淺色/深色與無障礙大字體佈局檢查。+- 共用卡片的離線圖片輸出:Claude、Codex、接近上限、Bots 工作/待回應、空清單;每種包含小/中尺寸及淺色/深色。+- 本機 HTTP/SSE 測試 host 到 App Group 的整合檢查:初次 bot/用量同步、狀態不變時改名及活動更新、刪除 bot、切換到離線電腦後清除上一台資料。+- 系統 Add Widget 搜尋能找到 Codync。測試配對不會保留在模擬器。++驗證限制:系統 widget 搜尋結果沒有提供可點擊的 accessibility 元素,座標點擊與捲動仍回報 `noWindowsAvailable`,鍵盤導覽也未能開啟結果。因此尚未在系統 Home/Lock Screen 上實際加入 widget、編輯 provider 或量測背景刷新排程;原生預覽可編譯與共用卡片圖片檢查不等同這些整合驗證。++重現方式:++```sh+swift test --package-path kit+python3 tools/render-widgets.py+```++圖片輸出在 `build/widget-previews/widgets-light.png` 與 `widgets-dark.png`。腳本使用 macOS 的 SwiftUI ImageRenderer,直接繪製產品共用元件;產物不含使用者資料。實際 WidgetKit 預覽在 `apps/ios/Widgets/WidgetPreviews.swift`,可於 Xcode canvas 切換 timeline 的 provider/空狀態。++帳號/雲端架構與 SSH computer 路線分別見 [帳號與裝置計畫](cloudflare-account-device-plan.md) 與 [Bot/computer/SSH 計畫](bot-computer-ssh-plan.md)。diff --git a/host/src/api.rs b/host/src/api.rsindex 3a25aa4f..7bc694b2 100644--- a/host/src/api.rs+++ b/host/src/api.rs@@ -107,6 +107,7 @@ fn str_arg<'a>(b: &'a Value, k: &str) -> Result<&'a str> {pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {Ok(match method {+ "teamCall" => crate::team::call(hub, str_arg(&b, "botId")?, str_arg(&b, "name")?, &b["arguments"]).await?,"hello" => {let port = hub.port;json!({@@ -185,6 +186,22 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {hub.send_cmd(str_arg(&b, "botId")?, Cmd::NewSession)?;json!({})}+ "memory" => {+ let bot = str_arg(&b, "botId")?.to_owned();+ tokio::task::spawn_blocking(move || crate::memory::describe(&bot)).await??+ }+ "forgetMemory" => {+ let bot = str_arg(&b, "botId")?.to_owned();+ let id = str_arg(&b, "id")?.to_owned();+ let removed =+ tokio::task::spawn_blocking(move || crate::memory::Memory::for_bot(&bot)?.remove(&id)).await??;+ json!({"removed": removed})+ }+ "clearMemory" => {+ let bot = str_arg(&b, "botId")?.to_owned();+ tokio::task::spawn_blocking(move || crate::memory::Memory::for_bot(&bot)?.clear()).await??;+ json!({})+ }"respondPermission" => {let entry_id = str_arg(&b, "entryId")?;let e = hub.store.entry(entry_id).ok_or_else(|| anyhow!("unknown card"))?;@@ -275,7 +292,7 @@ pub async fn dispatch(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Value> {let step: crate::term::Step =serde_json::from_value(b["step"].clone()).context("`step` is install or login")?;let (cols, rows) = term_size(&b);- json!({"term": hub.terms.start(str_arg(&b, "backend")?, step, b["method"].as_str(), cols, rows)?})+ json!({"term": hub.terms.start(str_arg(&b, "backend")?, step, b["method"].as_str(), cols, rows).await?})}"agentAuth" => crate::auth::check(&hub.store, str_arg(&b, "backend")?).await?,"agentAuthenticate" => {diff --git a/host/src/auth.rs b/host/src/auth.rsindex 3f2747d9..fd5ad399 100644--- a/host/src/auth.rs+++ b/host/src/auth.rs@@ -13,7 +13,7 @@use crate::LockExt;use crate::acp::{AUTH_REQUIRED, Acp, Incoming, RpcError};use crate::backends;-use crate::registry::Cmd;+use crate::registry::{Cmd, env_prefix, shell_quote};use crate::store::Store;use anyhow::{Context, Result, anyhow, bail};use serde::Serialize;@@ -100,6 +100,8 @@ pub async fn check(store: &Store, backend: &str) -> Result<Value> {CHECKED.locked().insert(backend.to_owned(), status.clone());let mut v = serde_json::to_value(&status)?;v["savedEnv"] = json!(saved_env(store, backend));+ // Codync's own sign-in command (phone-friendly device flows where the CLI has one).+ v["login"] = json!(backends::login_available(backend));Ok(v)}@@ -130,7 +132,11 @@ async fn probe(store: &Store, backend: &str) -> Result<Status> {type Started = (Arc<Acp>, mpsc::UnboundedReceiver<Incoming>, Value, Cmd);async fn start(store: &Store, backend: &str) -> Result<Started> {- let candidates = backends::launch_candidates(backend, |_| {}).await?;+ // The installed CLI alone when there is one: resolving the registry build can mean a long download.+ let candidates = match backends::local_candidate(backend) {+ Some(local) => vec![local],+ None => backends::launch_candidates(backend, |_| {}).await?,+ };let env = env(store, backend);let dir = probe_dir();tokio::fs::create_dir_all(&dir).await?;@@ -139,7 +145,7 @@ async fn start(store: &Store, backend: &str) -> Result<Started> {for (i, cmd) in candidates.into_iter().enumerate() {// A first `npx` run downloads the package: give the last candidate time.let budget = Duration::from_secs(if i + 1 < count { 20 } else { 180 });- let (acp, rx) = match Acp::spawn(&cmd.acp(), &dir.to_string_lossy(), &env) {+ let (acp, mut rx) = match Acp::spawn(&cmd.acp(), &dir.to_string_lossy(), &env) {Ok(v) => v,Err(e) => {last = Some(e);@@ -162,7 +168,19 @@ async fn start(store: &Store, backend: &str) -> Result<Started> {);match tokio::time::timeout(budget, init).await {Ok(Ok(init)) => return Ok((acp, rx, init, cmd)),- Ok(Err(e)) => last = Some(e),+ Ok(Err(e)) => {+ // Its last stderr line usually says why it quit.+ let why = std::iter::from_fn(|| rx.try_recv().ok()).find_map(|inc| match inc {+ Incoming::Closed { stderr_tail } => {+ stderr_tail.lines().rev().find(|l| !l.trim().is_empty()).map(str::to_owned)+ }+ _ => None,+ });+ last = Some(match why {+ Some(why) => e.context(why),+ None => e,+ });+ }Err(_) => last = Some(anyhow!("the agent didn't start within {}s", budget.as_secs())),}acp.kill().await;@@ -174,35 +192,16 @@ fn text(v: &Value) -> Option<String> {v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)}-fn shell_quote(s: &str) -> String {- if !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "-_./=@:+,".contains(c)) {- s.to_owned()- } else {- format!("'{}'", s.replace('\'', "'\\''"))- }-}-fn joined_args(v: &Value) -> String {v.as_array().map(|a| a.iter().filter_map(Value::as_str).map(shell_quote).collect::<Vec<_>>().join(" ")).unwrap_or_default()}-fn env_prefix(v: &Value) -> String {- v.as_object()- .map(|m| {- m.iter()- .filter(|(k, _)| !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))- .filter_map(|(k, v)| Some(format!("{k}={} ", shell_quote(v.as_str()?))))- .collect::<String>()- })- .unwrap_or_default()-}-/// The agent's advertised sign-in methods, in Codync's terms.fn methods(backend: &str, init: &Value, cmd: &Cmd) -> Vec<Method> {let empty = Map::new();- init["authMethods"]+ let mut out = init["authMethods"].as_array().into_iter().flatten()@@ -248,7 +247,12 @@ fn methods(backend: &str, init: &Value, cmd: &Cmd) -> Vec<Method> {};Some(Method { id, name, description: text(&m["description"]), kind })})- .collect()+ .collect::<Vec<_>>();+ // Some agents list a key twice: prose-only ("set Z_AI_API_KEY") and as a real env-var method.+ let keyed: Vec<String> =+ out.iter().filter(|m| matches!(m.kind, MethodKind::EnvVar { .. })).map(|m| m.name.clone()).collect();+ out.retain(|m| !matches!(m.kind, MethodKind::Agent) || !keyed.contains(&m.name));+ out}/// The terminal command for a method found by the last check.@@ -308,6 +312,7 @@ mod tests {{"id": "d", "name": "Browser"},{"id": "e", "name": "Api key", "_meta": {"api-key": {"provider": "openai"}}},{"id": "f", "name": "Qwen style", "_meta": {"type": "terminal", "args": ["--auth-type=openai"]}},+ {"id": "g", "name": "Key"},]});let m = methods("x", &init, &cmd());let kinds: Vec<_> = m.iter().map(|m| (m.id.as_str(), &m.kind)).collect();diff --git a/host/src/backends.rs b/host/src/backends.rsindex 9b810fb9..0be708e5 100644--- a/host/src/backends.rs+++ b/host/src/backends.rs@@ -27,7 +27,7 @@ pub struct Harness {pub setup: &'static str,/// How Codync installs the CLI for you (in a setup terminal).pub install: Option<Install>,- /// Shell command that signs in, run in a setup terminal.+ /// Shell command that signs in, run in a setup terminal (`{bin}` = the CLI).pub login: &'static str,/// How to tell whether it's signed in without starting it.pub signed_in: Option<SignInCheck>,@@ -67,6 +67,10 @@ fn claude_signed_in(_: bool, out: &str) -> bool {serde_json::from_str::<Value>(out).is_ok_and(|v| v["loggedIn"] == true)}+fn qoder_signed_in(_: bool, out: &str) -> bool {+ serde_json::from_str::<Value>(out).is_ok_and(|v| v["logged_in"] == true)+}+fn says_logged_in(_: bool, out: &str) -> bool {let out = out.to_lowercase();out.contains("logged in") && !out.contains("not logged in")@@ -79,9 +83,9 @@ pub const HARNESSES: &[Harness] = &[bins: &["claude"],local: None,registry: Some("claude-acp"),- setup: "Install Claude Code and run `claude` once to sign in.",+ setup: "Install Claude Code and run `claude auth login`.",install: Some(Install::Script("curl -fsSL https://claude.ai/install.sh | bash")),- login: "claude auth login",+ login: "{bin} auth login",signed_in: Some(SignInCheck { args: "auth status", ok: claude_signed_in }),},Harness {@@ -90,20 +94,20 @@ pub const HARNESSES: &[Harness] = &[bins: &["codex"],local: None,registry: Some("codex-acp"),- setup: "Install Codex CLI and run `codex login`.",- install: Some(Install::Npm("@openai/codex")),- login: "codex login --device-auth",+ setup: "Install Codex CLI and run `codex login --device-auth`.",+ install: Some(Install::Script("curl -fsSL https://chatgpt.com/codex/install.sh | sh")),+ login: "{bin} login --device-auth",signed_in: Some(SignInCheck { args: "login status", ok: exit_ok }),},Harness {id: "cursor",name: "Cursor",- bins: &["cursor-agent"],+ bins: &["cursor-agent", "agent"],local: Some("{bin} acp"),registry: Some("cursor"),setup: "Install Cursor CLI (curl https://cursor.com/install -fsS | bash) and run `cursor-agent login`.",install: Some(Install::Script("curl https://cursor.com/install -fsS | bash")),- login: "cursor-agent login",+ login: "NO_OPEN_BROWSER=1 {bin} login",signed_in: Some(SignInCheck { args: "status", ok: says_logged_in }),},Harness {@@ -112,9 +116,9 @@ pub const HARNESSES: &[Harness] = &[bins: &["pi"],local: None,registry: Some("pi-acp"),- setup: "Install pi (npm install -g @mariozechner/pi-coding-agent) and sign in with `pi`.",- install: Some(Install::Npm("@mariozechner/pi-coding-agent")),- login: "pi",+ setup: "Install pi (npm install -g @earendil-works/pi-coding-agent), run `pi` and type /login.",+ install: Some(Install::Npm("@earendil-works/pi-coding-agent")),+ login: "{bin}",signed_in: None,},Harness {@@ -125,7 +129,7 @@ pub const HARNESSES: &[Harness] = &[registry: Some("opencode"),setup: "Install OpenCode (curl -fsSL https://opencode.ai/install | bash) and run `opencode auth login`.",install: Some(Install::Script("curl -fsSL https://opencode.ai/install | bash")),- login: "opencode auth login",+ login: "{bin} auth login",signed_in: None,},Harness {@@ -134,9 +138,9 @@ pub const HARNESSES: &[Harness] = &[bins: &["grok"],local: Some("{bin} agent stdio"),registry: Some("grok-build"),- setup: "Install Grok Build (curl -fsSL https://x.ai/cli/install.sh | bash) and run `grok` once to sign in.",- install: Some(Install::Script("curl -fsSL https://x.ai/cli/install.sh | bash")),- login: "grok",+ setup: "Install Grok Build (curl -fsSL https://x.ai/cli/install.sh | bash) and run `grok login --device-auth`.",+ install: Some(Install::Npm("@xai-official/grok")),+ login: "{bin} login --device-auth",signed_in: None,},Harness {@@ -145,9 +149,9 @@ pub const HARNESSES: &[Harness] = &[bins: &["gemini"],local: Some("{bin} --acp"),registry: Some("gemini"),- setup: "Install Gemini CLI (npm install -g @google/gemini-cli) and run `gemini` once to sign in.",+ setup: "Install Gemini CLI (npm install -g @google/gemini-cli) and run `gemini` to sign in with Google.",install: Some(Install::Npm("@google/gemini-cli")),- login: "gemini",+ login: "NO_BROWSER=true {bin}",signed_in: None,},Harness {@@ -156,9 +160,9 @@ pub const HARNESSES: &[Harness] = &[bins: &["copilot"],local: Some("{bin} --acp --stdio"),registry: Some("github-copilot-cli"),- setup: "Install Copilot CLI (npm install -g @github/copilot) and run `copilot` to sign in.",+ setup: "Install Copilot CLI (npm install -g @github/copilot) and run `copilot login`.",install: Some(Install::Npm("@github/copilot")),- login: "copilot",+ login: "{bin} login --device-code",signed_in: None,},Harness {@@ -167,9 +171,9 @@ pub const HARNESSES: &[Harness] = &[bins: &["qwen"],local: Some("{bin} --acp"),registry: Some("qwen-code"),- setup: "Install Qwen Code (npm install -g @qwen-code/qwen-code) and sign in with `qwen`.",+ setup: "Install Qwen Code (npm install -g @qwen-code/qwen-code), run `qwen` and type /auth.",install: Some(Install::Npm("@qwen-code/qwen-code")),- login: "qwen",+ login: "{bin}",signed_in: None,},Harness {@@ -179,19 +183,21 @@ pub const HARNESSES: &[Harness] = &[local: Some("{bin} acp"),registry: Some("goose"),setup: "Install goose and run `goose configure`.",- install: None,- login: "goose configure",+ install: Some(Install::Script(+ "curl -fsSL https://github.com/aaif-goose/goose/releases/download/stable/download_cli.sh | bash",+ )),+ login: "{bin} configure",signed_in: None,},Harness {id: "kimi",- name: "Kimi CLI",+ name: "Kimi Code",bins: &["kimi"],local: Some("{bin} acp"),registry: Some("kimi"),- setup: "Install Kimi CLI and sign in with `kimi`.",- install: None,- login: "kimi",+ setup: "Install Kimi Code (curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash) and run `kimi login`.",+ install: Some(Install::Script("curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash")),+ login: "{bin} login",signed_in: None,},Harness {@@ -201,8 +207,8 @@ pub const HARNESSES: &[Harness] = &[local: Some("{bin} exec --output-format acp-daemon"),registry: Some("factory-droid"),setup: "Install Droid (curl -fsSL https://app.factory.ai/cli | sh) and sign in with `droid`.",- install: Some(Install::Script("curl -fsSL https://app.factory.ai/cli | sh")),- login: "droid",+ install: Some(Install::Npm("droid")),+ login: "{bin}",signed_in: None,},Harness {@@ -211,9 +217,9 @@ pub const HARNESSES: &[Harness] = &[bins: &["amp"],local: None,registry: Some("amp-acp"),- setup: "Install Amp and sign in with `amp login`.",- install: None,- login: "amp login",+ setup: "Install Amp (curl -fsSL https://ampcode.com/install.sh | bash) and run `amp login`.",+ install: Some(Install::Script("curl -fsSL https://ampcode.com/install.sh | bash")),+ login: "{bin} login",signed_in: None,},Harness {@@ -222,10 +228,10 @@ pub const HARNESSES: &[Harness] = &[bins: &["kilo"],local: Some("{bin} acp"),registry: Some("kilo"),- setup: "Install Kilo CLI (npm install -g @kilocode/cli) and sign in.",+ setup: "Install Kilo CLI (npm install -g @kilocode/cli) and run `kilo auth login`.",install: Some(Install::Npm("@kilocode/cli")),- login: "kilo",- signed_in: None,+ login: "{bin} auth login",+ signed_in: Some(SignInCheck { args: "profile --json", ok: exit_ok }),},Harness {id: "cline",@@ -233,9 +239,9 @@ pub const HARNESSES: &[Harness] = &[bins: &["cline"],local: Some("{bin} --acp"),registry: Some("cline"),- setup: "Install Cline CLI (npm install -g cline) and sign in.",+ setup: "Install Cline CLI (npm install -g cline) and run `cline auth`.",install: Some(Install::Npm("cline")),- login: "cline",+ login: "{bin} auth",signed_in: None,},Harness {@@ -246,8 +252,8 @@ pub const HARNESSES: &[Harness] = &[registry: Some("auggie"),setup: "Install Auggie (npm install -g @augmentcode/auggie) and run `auggie login`.",install: Some(Install::Npm("@augmentcode/auggie")),- login: "auggie login",- signed_in: None,+ login: "{bin} login",+ signed_in: Some(SignInCheck { args: "account status", ok: exit_ok }),},Harness {id: "vibe",@@ -255,9 +261,9 @@ pub const HARNESSES: &[Harness] = &[bins: &["vibe-acp", "vibe"],local: None,registry: Some("mistral-vibe"),- setup: "Install Mistral Vibe and run `vibe` once to sign in.",- install: None,- login: "vibe",+ setup: "Install Mistral Vibe (curl -LsSf https://mistral.ai/vibe/install.sh | bash) and run `vibe --setup`.",+ install: Some(Install::Script("curl -LsSf https://mistral.ai/vibe/install.sh | bash")),+ login: "vibe --setup",signed_in: None,},Harness {@@ -268,7 +274,7 @@ pub const HARNESSES: &[Harness] = &[registry: None,setup: "Install Kiro CLI (curl -fsSL https://cli.kiro.dev/install | bash) and run `kiro-cli login`.",install: Some(Install::Script("curl -fsSL https://cli.kiro.dev/install | bash")),- login: "kiro-cli login",+ login: "{bin} login",signed_in: None,},Harness {@@ -277,9 +283,9 @@ pub const HARNESSES: &[Harness] = &[bins: &["devin"],local: Some("{bin} acp"),registry: Some("devin"),- setup: "Install the Devin CLI and sign in.",- install: None,- login: "devin",+ setup: "Install the Devin CLI (curl -fsSL https://cli.devin.ai/install.sh | bash) and run `devin auth login`.",+ install: Some(Install::Script("curl -fsSL https://cli.devin.ai/install.sh | bash")),+ login: "{bin} auth login",signed_in: None,},Harness {@@ -288,9 +294,75 @@ pub const HARNESSES: &[Harness] = &[bins: &["qodercli"],local: Some("{bin} --acp"),registry: Some("qoder"),- setup: "Install Qoder CLI and sign in.",- install: None,- login: "qodercli",+ setup: "Install Qoder CLI (npm install -g @qoder-ai/qodercli) and run `qodercli login`.",+ install: Some(Install::Npm("@qoder-ai/qodercli")),+ login: "{bin} login",+ signed_in: Some(SignInCheck { args: "status -o json", ok: qoder_signed_in }),+ },+ Harness {+ id: "codebuddy",+ name: "CodeBuddy Code",+ bins: &["codebuddy", "cbc"],+ local: Some("{bin} --acp"),+ registry: Some("codebuddy-code"),+ setup: "Install CodeBuddy Code (npm install -g @tencent-ai/codebuddy-code) and sign in with `codebuddy`.",+ install: Some(Install::Npm("@tencent-ai/codebuddy-code")),+ login: "{bin}",+ signed_in: None,+ },+ Harness {+ id: "minimax",+ name: "MiniMax Code",+ bins: &["mcode"],+ local: Some("{bin} acp"),+ registry: Some("minimax-code"),+ setup: "Install MiniMax Code (npm install -g @minimax-ai/code) and run `mcode login`.",+ install: Some(Install::Npm("@minimax-ai/code")),+ login: "{bin} login",+ signed_in: None,+ },+ Harness {+ id: "junie",+ name: "Junie",+ bins: &["junie"],+ local: Some("{bin} --acp=true"),+ registry: Some("junie"),+ setup: "Install Junie (curl -fsSL https://junie.jetbrains.com/install.sh | bash) and sign in with `junie`.",+ install: Some(Install::Script("curl -fsSL https://junie.jetbrains.com/install.sh | bash")),+ login: "{bin}",+ signed_in: None,+ },+ Harness {+ id: "antigravity",+ name: "Google Antigravity",+ bins: &["agy"],+ local: None,+ registry: Some("antigravity-acp"),+ setup: "Install the Antigravity CLI (curl -fsSL https://antigravity.google/cli/install.sh | bash) and sign in with `agy`.",+ install: Some(Install::Script("curl -fsSL https://antigravity.google/cli/install.sh | bash")),+ login: "{bin}",+ signed_in: None,+ },+ Harness {+ id: "cortex",+ name: "Cortex Code",+ bins: &["cortex"],+ local: Some("{bin} acp serve"),+ registry: Some("cortex-code"),+ setup: "Install Cortex Code (curl -LsS https://ai.snowflake.com/static/cc-scripts/install.sh | sh) and set up a connection with `cortex`.",+ install: Some(Install::Script("curl -LsS https://ai.snowflake.com/static/cc-scripts/install.sh | sh")),+ login: "{bin}",+ signed_in: None,+ },+ Harness {+ id: "poolside",+ name: "Poolside",+ bins: &["pool"],+ local: Some("{bin} acp"),+ registry: Some("poolside"),+ setup: "Install Poolside (curl -fsSL https://downloads.poolside.ai/pool/install.sh | sh) and run `pool login`.",+ install: Some(Install::Script("curl -fsSL https://downloads.poolside.ai/pool/install.sh | sh")),+ login: "{bin} login",signed_in: None,},];@@ -539,16 +611,8 @@ pub fn is_known(id: &str) -> bool {/// Ways to start this backend, best first. Local CLIs can be too old to speak/// ACP, so the registry build is kept as a fallback.pub async fn launch_candidates(id: &str, progress: impl Fn(&str)) -> anyhow::Result<Vec<registry::Cmd>> {- let mut out = vec![];+ let mut out: Vec<registry::Cmd> = local_candidate(id).into_iter().collect();let h = harness(id);- if let Some(h) = h- && let Some(template) = h.local- && let Some(path) = h.bins.iter().find_map(|b| which(b))- {- let program = shell_quote(&path.to_string_lossy());- let args = template.strip_prefix("{bin}").unwrap_or(template).trim().to_owned();- out.push(registry::Cmd { program, args });- }let reg_id = h.map_or(Some(id), |h| h.registry);if let Some(agent) = reg_id.and_then(registry::agent) {match registry::command(&agent, &progress).await {@@ -564,6 +628,44 @@ pub async fn launch_candidates(id: &str, progress: impl Fn(&str)) -> anyhow::ResOk(out)}+/// The registry build that *is* the harness's CLI (same npm package), so it can+/// sign in without the CLI installed. Adapters (claude-acp…) don't count.+fn registry_cli(h: &Harness) -> Option<Value> {+ let Some(Install::Npm(pkg)) = h.install else { return None };+ let agent = registry::agent(h.registry?)?;+ let npx = agent["distribution"]["npx"]["package"].as_str()?;+ (npx == pkg || npx.strip_prefix(pkg).is_some_and(|v| v.starts_with('@'))).then_some(agent)+}++/// Codync's own sign-in command for `id` can run now.+pub fn login_available(id: &str) -> bool {+ harness(id)+ .is_some_and(|h| h.bins.iter().any(|b| on_path(b)) || !h.login.contains("{bin}") || registry_cli(h).is_some())+}++/// Codync's own sign-in command for `id`, with `{bin}` resolved.+pub async fn login_command(id: &str) -> anyhow::Result<String> {+ let h = harness(id).ok_or_else(|| anyhow::anyhow!("no sign-in command for {id}"))?;+ let bin = match h.bins.iter().find_map(|b| which(b)) {+ Some(p) => shell_quote(&p.to_string_lossy()),+ None => match registry_cli(h) {+ Some(agent) => registry::command(&agent, |_| {}).await?.program,+ None if !h.login.contains("{bin}") => String::new(),+ None => anyhow::bail!("Install {} first.", h.name),+ },+ };+ Ok(h.login.replace("{bin}", &bin))+}++/// The installed CLI's own ACP mode, if it has one and it's installed.+pub fn local_candidate(id: &str) -> Option<registry::Cmd> {+ let h = harness(id)?;+ let template = h.local?;+ let path = h.bins.iter().find_map(|b| which(b))?;+ let args = template.strip_prefix("{bin}").unwrap_or(template).trim().to_owned();+ Some(registry::Cmd { program: shell_quote(&path.to_string_lossy()), args })+}+fn shell_quote(s: &str) -> String {if s.chars().all(|c| c.is_ascii_alphanumeric() || "-_./".contains(c)) {s.to_owned()diff --git a/host/src/bot.rs b/host/src/bot.rsindex 54d547f3..ffccbf30 100644--- a/host/src/bot.rs+++ b/host/src/bot.rs@@ -5,9 +5,16 @@//! agent message of each turn, permission cards and notices. Narration between//! tool calls, thoughts, tool calls and plans are trace entries shown in the//! "full conversation" sheet, and surface live as the roster activity line.+//!+//! Context (from Grok Bot too): the bot's instructions and memory are a frozen+//! snapshot per session and compaction epoch (`context`), finished exchanges feed+//! its memory keeper (`memory`), messages sent while it works are folded into+//! its next turn, and a turn cut off by a host restart is resumed.use crate::acp::{self, Acp, Incoming};+use crate::context::{self, Identity, Snapshot};use crate::hub::{BotStatus, Hub};+use crate::memory;use crate::push::{self, AlertKind};use crate::store::{BotConfig, EntryKind, Permission, now_ms};use anyhow::{Result, anyhow, bail};@@ -29,6 +36,8 @@ pub enum NoticeStyle {pub enum Cmd {Send { entry_id: String, text: String },+ Ask(crate::team::Ask),+ CancelAsk { id: String },Stop,Permission { entry_id: String, option_id: Option<String> },NewSession,@@ -36,6 +45,11 @@ pub enum Cmd {Shutdown,}+enum Queued {+ User { entry_id: String, text: String },+ Ask(crate::team::Ask),+}+pub struct BotHandle {pub tx: mpsc::UnboundedSender<Cmd>,/// The actor task; it kills its agent process on the way out.@@ -45,14 +59,27 @@ pub struct BotHandle {pub fn spawn(hub: Arc<Hub>, cfg: BotConfig) -> BotHandle {let (tx, rx) = mpsc::unbounded_channel();let session_id = hub.store.bot(&cfg.id).ok().flatten().and_then(|b| b.session_id);+ // A turn the previous host process never finished (crash, update, restart), unless+ // it's stale: an hour-old task is more likely unwanted than awaited (gawkbot's rule).+ let interrupted = hub+ .store+ .kv_get(&inflight_key(&cfg.id))+ .and_then(|v| v.parse::<i64>().ok())+ .is_some_and(|started| now_ms() - started < STALE_RESUME_MS);+ let keeper = memory::spawn_keeper(hub.clone(), cfg.id.clone());let actor = Actor {hub,cfg,conn: None,session_id,session_fresh: false,+ applied_system: None,+ keeper,+ turn_text: None,+ announce: None,turn: None,queue: VecDeque::new(),+ active_ask: None,seg: Seg::None,tools: HashMap::new(),plan_entry: None,@@ -62,16 +89,18 @@ pub fn spawn(hub: Arc<Hub>, cfg: BotConfig) -> BotHandle {exit_tail: None,tools_changed: false,};- let task = tokio::spawn(actor.run(rx));+ let task = tokio::spawn(actor.run(rx, interrupted));BotHandle { tx, task }}-struct Conn {- acp: Arc<Acp>,- rx: mpsc::UnboundedReceiver<Incoming>,+pub(crate) struct Conn {+ pub(crate) acp: Arc<Acp>,+ pub(crate) rx: mpsc::UnboundedReceiver<Incoming>,can_load: bool,/// The agent can reach remote (HTTP) MCP servers itself.mcp_http: bool,+ /// Claude's adapter: takes `_meta.systemPrompt` and `_meta.claudeCode.options`.+ pub(crate) claude: bool,/// Sessions already created or loaded in this process.loaded: HashSet<String>,}@@ -94,8 +123,16 @@ struct Actor {session_id: Option<String>,/// True until the first prompt of a new ACP session has been sent.session_fresh: bool,+ /// (session, instructions) last handed to Claude as its system prompt by this process.+ applied_system: Option<(String, String)>,+ keeper: mpsc::UnboundedSender<memory::Exchange>,+ /// The user's words for this turn (None for a hidden turn); feeds memory.+ turn_text: Option<String>,+ /// A profile update this turn carried, recorded once the agent got it.+ announce: Option<(Snapshot, Identity)>,turn: Option<i64>,- queue: VecDeque<(String, String)>,+ queue: VecDeque<Queued>,+ active_ask: Option<crate::team::Ask>,seg: Seg,tools: HashMap<String, String>,plan_entry: Option<String>,@@ -113,9 +150,13 @@ struct Actor {type Done = Result<Value>;impl Actor {- async fn run(mut self, mut rx: mpsc::UnboundedReceiver<Cmd>) {+ /// `interrupted`: the previous host process stopped mid-turn; resume it first.+ async fn run(mut self, mut rx: mpsc::UnboundedReceiver<Cmd>, interrupted: bool) {let (done_tx, mut done_rx) = mpsc::unbounded_channel::<Done>();let mut flush_tick = tokio::time::interval(Duration::from_millis(300));+ if interrupted {+ self.resume_interrupted(&done_tx).await;+ }loop {tokio::select! {cmd = rx.recv() => {@@ -134,6 +175,8 @@ impl Actor {_ = flush_tick.tick() => self.flush(false),}}+ self.hub.team.cancel_from(&self.cfg.id);+ self.complete_ask(Err(anyhow!("recipient shut down")));if let Some(c) = self.conn.take() {c.acp.kill().await;}@@ -148,11 +191,29 @@ impl Actor {async fn on_cmd(&mut self, cmd: Cmd, done_tx: &mpsc::UnboundedSender<Done>) -> bool {match cmd {Cmd::Send { entry_id, text } => {- self.queue.push_back((entry_id, text));+ self.queue.push_back(Queued::User { entry_id, text });+ if self.turn.is_none() {+ self.next_in_queue(done_tx).await;+ }+ }+ Cmd::Ask(ask) => {+ self.queue.push_back(Queued::Ask(ask));if self.turn.is_none() {self.next_in_queue(done_tx).await;}}+ Cmd::CancelAsk { id } => {+ self.queue.retain(|q| !matches!(q, Queued::Ask(a) if a.id == id));+ if self.active_ask.as_ref().is_some_and(|a| a.id == id) {+ self.hub.team.cancel_from(&self.cfg.id);+ self.stop_requested = true;+ // The request has expired. Kill only its process so a harness+ // ignoring cooperative cancellation cannot block the queue.+ if let Some(c) = self.conn.take() {+ c.acp.kill().await;+ }+ }+ }Cmd::Stop => self.stop().await,Cmd::Permission { entry_id, option_id } => self.answer_permission(&entry_id, option_id).await,Cmd::NewSession => {@@ -160,6 +221,10 @@ impl Actor {self.stop().await;}self.forget_session();+ // Like Grok Bot's clearConversation: the half-written episode goes too; memory stays.+ if let Err(error) = memory::set_pending_episode(&self.hub.store, &self.cfg.id, &[]) {+ tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't clear the pending episode");+ }self.notice("New session — the agent starts with a fresh context.", NoticeStyle::Divider);}Cmd::Reconfigure(cfg) => {@@ -167,16 +232,20 @@ impl Actor {let restart =cfg.backend != self.cfg.backend || cfg.command != self.cfg.command || cfg.cwd != self.cfg.cwd;self.tools_changed |= cfg.connectors != self.cfg.connectors || cfg.computer != self.cfg.computer;- // New skills are announced with the next prompt.- if cfg.skills != self.cfg.skills && self.session_id.is_some() {- self.session_fresh = true;- }+ // Name, description and skill changes reach the agent as a profile update+ // on the next message (see `context`).self.cfg = cfg;if restart {if let Some(c) = self.conn.take() {c.acp.kill().await;}- self.forget_session();+ if self.session_id.is_some() {+ self.forget_session();+ self.notice(+ "The agent, command or folder changed — the agent starts with a fresh context.",+ NoticeStyle::Divider,+ );+ }// A running prompt now fails; finish_turn reports it.}}@@ -186,8 +255,10 @@ impl Actor {}async fn stop(&mut self) {+ self.hub.team.cancel_from(&self.cfg.id);// Queued messages are dropped too: Stop means "stop everything".- for (entry_id, _) in self.queue.drain(..) {+ for queued in self.queue.drain(..) {+ let Queued::User { entry_id, .. } = queued else { continue };if let Some(mut e) = self.hub.store.entry(&entry_id) {e.data["status"] = "cancelled".into();self.hub.set_entry(&entry_id, &e.data);@@ -207,46 +278,140 @@ impl Actor {}async fn next_in_queue(&mut self, done_tx: &mpsc::UnboundedSender<Done>) {- while self.turn.is_none() {- let Some((entry_id, text)) = self.queue.pop_front() else { return };- if let Err(e) = self.start_turn(&entry_id, &text, done_tx).await {- let mut msg = format!("Couldn't start the agent: {e}");- if e.to_string().to_lowercase().contains("auth")- && let Some(h) = crate::backends::harness(&self.cfg.backend)- {- msg = format!("{0} needs you to sign in. Open {0} in Marketplace to sign in.", h.name);+ while self.turn.is_none() && !self.queue.is_empty() {+ if matches!(self.queue.front(), Some(Queued::Ask(_))) {+ let Some(Queued::Ask(ask)) = self.queue.pop_front() else { unreachable!("front is an ask") };+ if ask.reply.is_closed() {+ continue;}- self.notice(&msg, NoticeStyle::Error);- self.turn = None;- self.hub.set_runtime(&self.id(), |r| {- r.status = BotStatus::Error;- r.activity = "Couldn't start".into();- r.started_at = None;- });+ let ids = [ask.entry_id.clone()];+ let prompt = ask.prompt.clone();+ self.active_ask = Some(ask);+ let result = self.start_turn(&ids, &prompt, false, done_tx).await;+ // Another bot's words are not facts learned from the user.+ self.turn_text = None;+ if let Err(e) = result {+ self.start_failed(&e);+ }+ continue;+ }+ // Messages sent while the agent worked go out together as its next turn+ // without crossing a bot request: each ask gets its own reply.+ let mut batch = Vec::new();+ while matches!(self.queue.front(), Some(Queued::User { .. })) {+ if let Some(Queued::User { entry_id, text }) = self.queue.pop_front() {+ batch.push((entry_id, text));+ }+ }+ let ids: Vec<String> = batch.iter().map(|(id, _)| id.clone()).collect();+ let text = batch.iter().map(|(_, t)| t.as_str()).collect::<Vec<_>>().join("\n\n");+ if let Err(e) = self.start_turn(&ids, &text, false, done_tx).await {+ self.start_failed(&e);}}}- async fn start_turn(&mut self, entry_id: &str, text: &str, done_tx: &mpsc::UnboundedSender<Done>) -> Result<()> {- let turn = self.hub.store.entry(entry_id).map_or(0, |e| e.turn);- if let Some(mut e) = self.hub.store.entry(entry_id) {- e.data["status"] = "sent".into();- self.hub.set_entry(entry_id, &e.data);+ fn start_failed(&mut self, e: &anyhow::Error) {+ self.complete_ask(Err(anyhow!("couldn't start recipient: {e:#}")));+ let mut msg = format!("Couldn't start the agent: {e}");+ if e.to_string().to_lowercase().contains("auth")+ && let Some(h) = crate::backends::harness(&self.cfg.backend)+ {+ msg = format!("{0} needs you to sign in. Open {0} in Marketplace to sign in.", h.name);+ }+ self.notice(&msg, NoticeStyle::Error);+ self.turn = None;+ self.set_inflight(false);+ self.hub.set_runtime(&self.id(), |r| {+ r.status = BotStatus::Error;+ r.activity = "Couldn't start".into();+ r.started_at = None;+ });+ self.hub.team.cancel_from(&self.cfg.id);+ }++ fn complete_ask(&mut self, result: Result<String>) {+ if let Some(ask) = self.active_ask.take() {+ let _ = ask.reply.send(result);+ }+ }++ /// Grok Bot's upgrade resume: the previous host process stopped mid-turn, so+ /// the agent is told, in the same session, to finish without redoing steps.+ async fn resume_interrupted(&mut self, done_tx: &mpsc::UnboundedSender<Done>) {+ self.set_inflight(false);+ if self.session_id.is_none() {+ return;+ }+ if let Err(e) = self.start_turn(&[], RESUME_PROMPT, true, done_tx).await {+ self.start_failed(&e);+ }+ }++ /// Marks a turn as running across host restarts (see [`Self::resume_interrupted`]).+ fn set_inflight(&self, on: bool) {+ let value = if on { now_ms().to_string() } else { String::new() };+ if let Err(error) = self.hub.store.kv_set(&inflight_key(&self.cfg.id), &value) {+ tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't record the running turn");+ }+ }++ /// This session's frozen instructions (reads memory files when re-rendering).+ async fn snapshot(&self, session: &str) -> Result<Snapshot> {+ let (hub, cfg, session) = (self.hub.clone(), self.cfg.clone(), session.to_owned());+ tokio::task::spawn_blocking(move || context::resolve(&hub.store, &cfg, &session)).await?+ }++ /// Starts a turn for the given user entries (none for a hidden turn).+ async fn start_turn(+ &mut self,+ entry_ids: &[String],+ text: &str,+ hidden: bool,+ done_tx: &mpsc::UnboundedSender<Done>,+ ) -> Result<()> {+ let turn = entry_ids+ .last()+ .and_then(|id| self.hub.store.entry(id))+ .map_or_else(|| self.hub.store.max_turn(&self.cfg.id), |e| e.turn);+ for id in entry_ids {+ if let Some(mut e) = self.hub.store.entry(id) {+ e.data["status"] = "sent".into();+ self.hub.set_entry(id, &e.data);+ }}self.turn = Some(turn);+ self.turn_text = (!hidden).then(|| text.to_owned());+ self.announce = None;self.stop_requested = false;+ self.hub.team.start_turn(&self.cfg.id);self.exit_tail = None;self.seg = Seg::None;self.tools.clear();self.plan_entry = None;self.last_text = None;+ // A delegated turn has no live waiter after a host restart. Its persisted+ // notices are marked interrupted instead of silently repeating work.+ self.set_inflight(self.active_ask.is_none());self.hub.set_runtime(&self.id(), |r| {r.status = BotStatus::Working;- r.activity = "Starting…".into();+ r.activity = if hidden { "Picking up where it left off…" } else { "Starting…" }.into();r.started_at = Some(now_ms());});self.ensure_session().await?;+ if hidden && self.session_fresh {+ // The interrupted session couldn't be resumed, so there is nothing to continue.+ self.turn = None;+ self.set_inflight(false);+ self.hub.team.cancel_from(&self.cfg.id);+ self.hub.set_runtime(&self.id(), |r| {+ r.status = BotStatus::Idle;+ r.activity = String::new();+ r.started_at = None;+ });+ return Ok(());+ }// Session-start chatter (banners, command lists) isn't part of the reply.// Some adapters (pi-acp) send it on a timer right after session/new.if self.session_fresh {@@ -259,31 +424,25 @@ impl Actor {}}}- let conn = self.conn.as_ref().ok_or_else(|| anyhow!("agent not running"))?;+ let claude = self.conn.as_ref().is_some_and(|c| c.claude);+ let sid = self.session_id.clone().ok_or_else(|| anyhow!("no session"))?;+ let snapshot = self.snapshot(&sid).await?;let mut prompt = text.to_owned();if self.session_fresh {self.session_fresh = false;- let mut profile = format!(- "You are \"{}\", a persistent agent the user delegates work to from their phone.",- self.cfg.name- );- if !self.cfg.description.trim().is_empty() {- profile.push_str(" Standing instructions:\n");- profile.push_str(self.cfg.description.trim());- }- if let Some(skills) = crate::market::skills_brief(&self.hub.store, &self.cfg.skills) {- profile.push('\n');- profile.push_str(&skills);- }- profile.push_str(- "\nKeep your final reply short and phone-friendly: say what you did and what needs the user.",- );- prompt = format!("<bot-profile>\n{profile}\n</bot-profile>\n\n{text}");+ // Claude already has the instructions as its system prompt.+ if !claude {+ prompt = format!("<bot-profile>\n{}\n</bot-profile>\n\n{prompt}", snapshot.system);+ }+ }+ if let Some((update, identity)) = context::profile_update(&self.hub.store, &snapshot, &self.cfg) {+ prompt = format!("{prompt}\n\n{update}");+ self.announce = Some((snapshot, identity));}self.hub.set_runtime(&self.id(), |r| r.activity = "Thinking…".into());- let acp = conn.acp.clone();+ let acp = self.conn.as_ref().ok_or_else(|| anyhow!("agent not running"))?.acp.clone();let params = json!({- "sessionId": self.session_id,+ "sessionId": sid,"prompt": [{"type": "text", "text": prompt}],});let done_tx = done_tx.clone();@@ -293,21 +452,22 @@ impl Actor {Ok(())}- /// ACP `mcpServers` for this bot's connectors, plus the built-in `computer` server.+ /// ACP connectors, team collaboration, and optional computer control.fn mcp_servers(&self, http_ok: bool) -> Value {let all = crate::market::connectors(&self.hub.store);let mut servers: Vec<Value> =all.iter().filter(|c| self.cfg.connectors.contains(&c.id)).filter_map(|c| c.acp(http_ok)).collect();- if self.cfg.computer {- match std::env::current_exe() {- Ok(exe) => servers.push(json!({- "name": "computer",- "command": exe,- "args": ["mcp", "computer", "--bot", self.cfg.id, "--port", self.hub.port.to_string()],- "env": [],- })),- Err(error) => tracing::warn!(%error, "can't locate codync-host for the computer MCP server"),+ match std::env::current_exe() {+ Ok(exe) => {+ for name in [Some("team"), self.cfg.computer.then_some("computer")].into_iter().flatten() {+ servers.push(json!({+ "name": name, "command": exe,+ "args": ["mcp", name, "--bot", self.cfg.id, "--port", self.hub.port.to_string()],+ "env": [],+ }));+ }}+ Err(error) => tracing::warn!(%error, "can't locate codync-host for built-in MCP servers"),}Value::Array(servers)}@@ -320,21 +480,12 @@ impl Actor {}}if self.conn.is_none() {- let candidates = match self.cfg.command.as_deref().map(str::trim) {- Some(c) if !c.is_empty() => vec![c.to_owned()],- _ => {- let hub = self.hub.clone();- let id = self.cfg.id.clone();- crate::backends::launch_candidates(&self.cfg.backend, move |msg: &str| {- let msg = msg.to_owned();- hub.set_runtime(&id, |r| r.activity = msg);- })- .await?- .iter()- .map(crate::registry::Cmd::acp)- .collect()- }- };+ let (hub, id) = (self.hub.clone(), self.cfg.id.clone());+ let candidates = launch_commands(&self.cfg, move |msg: &str| {+ let msg = msg.to_owned();+ hub.set_runtime(&id, |r| r.activity = msg);+ })+ .await?;self.hub.set_runtime(&self.id(), |r| r.activity = "Starting agent…".into());// Keys saved from an "environment variable" sign-in.let env = crate::auth::env(&self.hub.store, &self.cfg.backend);@@ -359,9 +510,20 @@ impl Actor {}}let servers = self.mcp_servers(self.conn.as_ref().is_some_and(|c| c.mcp_http));+ let claude = self.conn.as_ref().is_some_and(|c| c.claude);+ // Claude gets the frozen instructions as its system prompt. When a compaction+ // re-rendered them, loading the session again swaps the prompt in (the adapter+ // rebuilds its query and resumes the same conversation).+ let snapshot = match (&self.session_id, claude) {+ (Some(sid), true) => Some(self.snapshot(sid).await?),+ _ => None,+ };let Some(conn) = self.conn.as_mut() else { bail!("agent not running") };if let Some(sid) = self.session_id.clone() {- if conn.loaded.contains(&sid) {+ let prompt_current = snapshot+ .as_ref()+ .is_none_or(|s| self.applied_system.as_ref().is_some_and(|(a, t)| *a == sid && *t == s.system));+ if conn.loaded.contains(&sid) && prompt_current {return Ok(());}if !conn.can_load {@@ -373,10 +535,11 @@ impl Actor {return Box::pin(self.ensure_session()).await;}self.hub.set_runtime(&self.cfg.id, |r| r.activity = "Resuming session…".into());- let res = conn- .acp- .request("session/load", json!({"sessionId": sid, "cwd": self.cfg.cwd, "mcpServers": servers}))- .await;+ let mut params = json!({"sessionId": sid, "cwd": self.cfg.cwd, "mcpServers": servers});+ if let Some(s) = &snapshot {+ params["_meta"] = system_meta(&s.system);+ }+ let res = conn.acp.request("session/load", params).await;// The agent replays history as session/update before answering; drop it.while let Ok(inc) = conn.rx.try_recv() {if let Incoming::Request { id, .. } = inc {@@ -385,7 +548,10 @@ impl Actor {}match res {Ok(_) => {- conn.loaded.insert(sid);+ conn.loaded.insert(sid.clone());+ if let Some(s) = snapshot {+ self.applied_system = Some((sid, s.system));+ }return Ok(());}Err(e) => {@@ -394,8 +560,16 @@ impl Actor {}}}+ let system = {+ let (hub, cfg) = (self.hub.clone(), self.cfg.clone());+ tokio::task::spawn_blocking(move || context::render(&hub.store, &cfg)).await?+ };let Some(conn) = self.conn.as_mut() else { bail!("agent not running") };- let res = conn.acp.request("session/new", json!({"cwd": self.cfg.cwd, "mcpServers": servers})).await?;+ let mut params = json!({"cwd": self.cfg.cwd, "mcpServers": servers});+ if claude {+ params["_meta"] = system_meta(&system);+ }+ let res = conn.acp.request("session/new", params).await?;let sid = res["sessionId"].as_str().ok_or_else(|| anyhow!("agent returned no sessionId"))?.to_owned();conn.loaded.insert(sid.clone());if let Some(model) = self.cfg.model.clone().filter(|m| !m.is_empty()) {@@ -417,6 +591,10 @@ impl Actor {self.session_id = Some(sid.clone());self.session_fresh = true;self.hub.store.set_session(&self.cfg.id, Some(&sid))?;+ context::adopt(&self.hub.store, &self.cfg, &sid, system.clone())?;+ if claude {+ self.applied_system = Some((sid, system));+ }Ok(())}@@ -469,13 +647,38 @@ impl Actor {_ => {}}let failed = done.is_err() && !self.stop_requested;+ let delegated = self.active_ask.is_some();+ let reply = if stopped {+ Err(anyhow!("recipient was stopped; partial work may have happened"))+ } else if stop_reason != "end_turn" {+ Err(anyhow!("recipient did not finish ({stop_reason}); partial work may have happened"))+ } else {+ final_text+ .clone()+ .filter(|s| !s.trim().is_empty())+ .ok_or_else(|| anyhow!("recipient finished without a text reply"))+ };+ self.complete_ask(reply);self.turn = None;+ self.set_inflight(false);+ // The message reached the agent: the profile update it carried is now known to it.+ if let (Ok(_), Some((snapshot, identity))) = (&done, self.announce.take())+ && let Err(error) = context::mark_announced(&self.hub.store, &self.cfg.id, &snapshot, identity)+ {+ tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't record the profile update");+ }+ if let (Some(user), Some(agent), "end_turn") = (self.turn_text.take(), &final_text, stop_reason.as_str())+ && memory::is_memorable(&user)+ {+ let _ = self.keeper.send(memory::Exchange { user, agent: agent.clone(), at: now_ms() });+ }self.hub.set_runtime(&self.id(), |r| {r.status = if failed { BotStatus::Error } else { BotStatus::Idle };r.activity = String::new();r.started_at = None;});- if !self.stop_requested {+ self.hub.team.cancel_from(&self.cfg.id);+ if !self.stop_requested && !delegated {let body =final_text.unwrap_or_else(|| if failed { "The agent failed.".into() } else { "Finished.".into() });push::notify(&self.hub, &self.cfg, &self.cfg.name, &body, AlertKind::Done);@@ -568,6 +771,19 @@ impl Actor {self.set_activity(&title);}}+ // The agent summarized its context: the next turn gets freshly rendered+ // instructions and memory (see `context`).+ "compaction_update" if u["status"] == "completed" => {+ let Some(sid) = &self.session_id else { return };+ let id = u["compactionId"].as_str().unwrap_or_default();+ match context::bump_epoch(&self.hub.store, &self.cfg.id, sid, id) {+ Ok(true) => self.notice("Earlier context was summarized to make room.", NoticeStyle::Info),+ Ok(false) => {}+ Err(error) => {+ tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't record the compaction");+ }+ }+ }"usage_update" => {let info = &u["_meta"]["_claude/rateLimit"];if info.is_object() {@@ -741,8 +957,36 @@ impl Actor {}}+/// Told to a bot whose turn the previous host process cut off (Grok Bot's upgrade resume).+const RESUME_PROMPT: &str = "[Codync restarted on this computer and interrupted you mid-task. You've been resumed with your full conversation intact. Continue exactly where you left off and finish what you were doing. If your previous step already completed an action, do NOT repeat it — just carry on from there.]";++/// An interrupted turn older than this isn't resumed.+const STALE_RESUME_MS: i64 = 60 * 60 * 1000;++fn inflight_key(bot_id: &str) -> String {+ format!("turn.inflight.{bot_id}")+}++/// Claude's `_meta`: the bot's instructions appended to Claude Code's own system prompt.+fn system_meta(system: &str) -> Value {+ json!({"systemPrompt": {"append": system}})+}++/// Shell commands that may start the bot's agent over ACP, best first.+/// `progress` receives short status lines ("Downloading Cursor…").+pub(crate) async fn launch_commands(cfg: &BotConfig, progress: impl Fn(&str)) -> Result<Vec<String>> {+ Ok(match cfg.command.as_deref().map(str::trim) {+ Some(c) if !c.is_empty() => vec![c.to_owned()],+ _ => crate::backends::launch_candidates(&cfg.backend, progress)+ .await?+ .iter()+ .map(crate::registry::Cmd::acp)+ .collect(),+ })+}+/// Spawns an ACP agent and completes the `initialize` handshake.-async fn start_agent(command: &str, cwd: &str, env: &[(String, String)], budget: Duration) -> Result<Conn> {+pub(crate) async fn start_agent(command: &str, cwd: &str, env: &[(String, String)], budget: Duration) -> Result<Conn> {let (acp, rx) = Acp::spawn(command, cwd, env)?;let init = tokio::time::timeout(budget,@@ -750,7 +994,12 @@ async fn start_agent(command: &str, cwd: &str, env: &[(String, String)], budget:"initialize",json!({"protocolVersion": 1,- "clientCapabilities": {"fs": {"readTextFile": false, "writeTextFile": false}, "terminal": false},+ // `session.compaction`: tell us when the agent summarizes its context.+ "clientCapabilities": {+ "fs": {"readTextFile": false, "writeTextFile": false},+ "terminal": false,+ "session": {"compaction": {}},+ },"clientInfo": {"name": "codync", "title": "Codync", "version": env!("CARGO_PKG_VERSION")},}),),@@ -769,7 +1018,8 @@ async fn start_agent(command: &str, cwd: &str, env: &[(String, String)], budget:};let can_load = init["agentCapabilities"]["loadSession"].as_bool().unwrap_or(false);let mcp_http = init["agentCapabilities"]["mcpCapabilities"]["http"].as_bool().unwrap_or(false);- Ok(Conn { acp, rx, can_load, mcp_http, loaded: HashSet::new() })+ let claude = init["agentCapabilities"]["_meta"]["claudeCode"].is_object();+ Ok(Conn { acp, rx, can_load, mcp_http, claude, loaded: HashSet::new() })}async fn recv_incoming(conn: &mut Option<Conn>) -> Option<Incoming> {diff --git a/host/src/context.rs b/host/src/context.rsnew file mode 100644index 00000000..67da6ea9--- /dev/null+++ b/host/src/context.rs@@ -0,0 +1,227 @@+//! What a bot is told about itself, frozen per context window: Grok Bot's+//! "prompt snapshots".+//!+//! The bot's instructions (name, description, skills, memory) are rendered once+//! and kept as a [`Snapshot`] keyed by the ACP session and its *compaction+//! epoch*. Harnesses that take a system prompt (Claude, via `_meta.systemPrompt`)+//! get it as one; others get it in the first message of the session. The+//! snapshot stays byte-identical, so the prompt cache stays warm, until the+//! agent compacts its context (a `compaction_update`) or a new session starts.+//! Profile edits in between are announced once as an `<agent_profile_update>`+//! block on the next message and folded into the snapshot after the next+//! compaction. Memory learned in between reaches the prompt the same way.++use crate::memory::{self, Memory};+use crate::store::{BotConfig, Store};+use anyhow::Result;+use serde::{Deserialize, Serialize};++#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]+pub struct Identity {+ pub name: String,+ pub description: String,+ pub skills: Vec<String>,+}++impl Identity {+ pub fn of(cfg: &BotConfig) -> Self {+ let mut skills = cfg.skills.clone();+ skills.sort();+ Self { name: cfg.name.trim().to_owned(), description: cfg.description.trim().to_owned(), skills }+ }+}++#[derive(Serialize, Deserialize, Clone, Debug)]+#[serde(rename_all = "camelCase")]+pub struct Snapshot {+ pub session: String,+ pub epoch: u32,+ /// The rendered instructions, exactly as the agent got them.+ pub system: String,+ /// The identity rendered into `system`.+ pub system_identity: Identity,+ /// The identity the agent last heard of (`system` or a later update block).+ pub announced: Identity,+}++fn key(bot_id: &str) -> String {+ format!("context.{bot_id}")+}++fn epoch_key(bot_id: &str) -> String {+ format!("context.epoch.{bot_id}")+}++/// `(epoch, last compaction id)` stored as `session \t epoch \t id`.+fn epoch_state(store: &Store, bot_id: &str, session: &str) -> (u32, String) {+ store+ .kv_get(&epoch_key(bot_id))+ .and_then(|v| {+ let mut parts = v.splitn(3, '\t');+ (parts.next()? == session).then(|| {+ (parts.next().and_then(|n| n.parse().ok()).unwrap_or(0), parts.next().unwrap_or("").to_owned())+ })+ })+ .unwrap_or_default()+}++/// How many times the agent has compacted `session`.+pub fn epoch(store: &Store, bot_id: &str, session: &str) -> u32 {+ epoch_state(store, bot_id, session).0+}++/// Counts a finished compaction once (adapters may repeat its terminal update).+/// Returns whether it was new.+pub fn bump_epoch(store: &Store, bot_id: &str, session: &str, compaction_id: &str) -> Result<bool> {+ let (n, last) = epoch_state(store, bot_id, session);+ if !compaction_id.is_empty() && compaction_id == last {+ return Ok(false);+ }+ store.kv_set(&epoch_key(bot_id), &format!("{session}\t{}\t{compaction_id}", n + 1))?;+ Ok(true)+}++fn load(store: &Store, bot_id: &str) -> Option<Snapshot> {+ store.kv_get(&key(bot_id)).and_then(|v| serde_json::from_str(&v).ok())+}++fn save(store: &Store, bot_id: &str, s: &Snapshot) -> Result<()> {+ store.kv_set(&key(bot_id), &serde_json::to_string(s)?)+}++/// The snapshot for `session` at its current epoch, rendering a fresh one when+/// the stored one belongs to another session or an earlier epoch. Reads memory files.+pub fn resolve(store: &Store, cfg: &BotConfig, session: &str) -> Result<Snapshot> {+ let epoch = epoch(store, &cfg.id, session);+ if let Some(s) = load(store, &cfg.id).filter(|s| s.session == session && s.epoch == epoch) {+ return Ok(s);+ }+ adopt(store, cfg, session, render(store, cfg))+}++/// Records `system` (already handed to a new session) as that session's snapshot.+pub fn adopt(store: &Store, cfg: &BotConfig, session: &str, system: String) -> Result<Snapshot> {+ let identity = Identity::of(cfg);+ let s = Snapshot {+ session: session.to_owned(),+ epoch: epoch(store, &cfg.id, session),+ system,+ system_identity: identity.clone(),+ announced: identity,+ };+ save(store, &cfg.id, &s)?;+ Ok(s)+}++/// The bot's instructions, rendered live. Reads memory files.+pub fn render(store: &Store, cfg: &BotConfig) -> String {+ let name = cfg.name.trim();+ let mut lines = vec!["Agent profile:".to_owned()];+ if !name.is_empty() {+ lines.push(format!("Title: {name}"));+ lines.push(format!("Your agent name is \"{name}\". If the user asks for your name, answer with \"{name}\"."));+ }+ if !cfg.description.trim().is_empty() {+ lines.push(format!("Description: {}", cfg.description.trim()));+ }+ lines.push(+ "You are a persistent agent the user delegates work to from their phone through Codync. They see only your final reply of each turn, so keep it short and phone-friendly: say what you did and what needs the user."+ .to_owned(),+ );+ lines.push(crate::team::INSTRUCTIONS.to_owned());+ if let Some(skills) = crate::market::skills_brief(store, &cfg.skills) {+ lines.push(skills);+ }+ let mut out = lines.join("\n");+ match Memory::for_bot(&cfg.id) {+ Ok(mem) => {+ let (section, _) = memory::render(&mem.recall(memory::RECENT_PROMPT_LIMIT), mem.location());+ out.push_str("\n\n");+ out.push_str(§ion);+ }+ Err(error) => tracing::warn!(bot = %cfg.id, error = format!("{error:#}"), "no memory folder"),+ }+ out+}++/// The `<agent_profile_update>` block to append to the next message when the+/// bot's identity changed since the agent last heard it.+pub fn profile_update(store: &Store, snapshot: &Snapshot, cfg: &BotConfig) -> Option<(String, Identity)> {+ let identity = Identity::of(cfg);+ if identity == snapshot.announced {+ return None;+ }+ let or_none = |s: &str, none: &str| if s.is_empty() { none.to_owned() } else { s.to_owned() };+ let skills = crate::market::skills_brief(store, &cfg.skills).unwrap_or_else(|| "Skills: none.".into());+ let text = [+ "<agent_profile_update>".to_owned(),+ "Your agent profile changed. This full update is authoritative and supersedes the Agent profile section in your instructions and every earlier profile update in this conversation.".to_owned(),+ format!("Current name: {}", or_none(&identity.name, "(no name)")),+ format!("Current description: {}", or_none(&identity.description, "(no description)")),+ skills,+ "Use this identity until a future conversation summary folds it into the Agent profile section.".to_owned(),+ "</agent_profile_update>".to_owned(),+ ]+ .join("\n");+ Some((text, identity))+}++/// After the turn that carried an update reached the agent: remember it heard+/// `identity`, unless the snapshot moved on meanwhile (a compaction re-rendered it).+pub fn mark_announced(store: &Store, bot_id: &str, turn_snapshot: &Snapshot, identity: Identity) -> Result<()> {+ let Some(mut current) = load(store, bot_id) else { return Ok(()) };+ if current.session != turn_snapshot.session+ || current.epoch != turn_snapshot.epoch+ || current.system != turn_snapshot.system+ || current.announced == identity+ {+ return Ok(());+ }+ current.announced = identity;+ save(store, bot_id, ¤t)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn cfg(name: &str, description: &str) -> BotConfig {+ serde_json::from_value(serde_json::json!({+ "id": "5f0c7a52-0000-4000-8000-000000000001", "name": name, "description": description,+ "backend": "claude", "cwd": "/tmp",+ }))+ .expect("valid bot")+ }++ fn store() -> Store {+ let path = std::env::temp_dir().join(format!("codync-context-{}.db", uuid::Uuid::new_v4()));+ Store::open(&path).expect("temp store")+ }++ #[test]+ fn snapshot_is_frozen_until_compaction_and_updates_are_announced_once() {+ let store = store();+ let a = cfg("Fixer", "Fix bugs");+ let first = adopt(&store, &a, "s1", "SYSTEM v1".into()).expect("adopt");+ // Frozen: resolving again returns the same text, even though a live render differs.+ assert_eq!(resolve(&store, &a, "s1").expect("resolve").system, "SYSTEM v1");+ assert!(profile_update(&store, &first, &a).is_none());++ let b = cfg("Fixer", "Fix bugs and write tests");+ let (text, identity) = profile_update(&store, &first, &b).expect("changed");+ assert!(text.contains("Current description: Fix bugs and write tests"));+ mark_announced(&store, &a.id, &first, identity).expect("mark");+ let snap = resolve(&store, &b, "s1").expect("resolve");+ assert_eq!(snap.system, "SYSTEM v1");+ assert!(profile_update(&store, &snap, &b).is_none());++ // A compaction folds the new identity into a fresh render.+ assert!(bump_epoch(&store, &a.id, "s1", "c1").expect("bump"));+ assert!(!bump_epoch(&store, &a.id, "s1", "c1").expect("bump"));+ let folded = resolve(&store, &b, "s1").expect("resolve");+ assert_eq!(folded.epoch, 1);+ assert!(folded.system.contains("Description: Fix bugs and write tests"));+ // A new session starts over at epoch 0.+ assert_eq!(epoch(&store, &a.id, "s2"), 0);+ }+}diff --git a/host/src/hub.rs b/host/src/hub.rsindex 2db002db..d5933254 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -34,6 +34,7 @@ pub struct Runtime {}pub struct Hub {+ pub team: crate::team::Requests,pub store: Store,pub host_id: String,pub token: String,@@ -58,6 +59,7 @@ impl Hub {let (events, _) = broadcast::channel(1024);let screen = Arc::new(Screen::new(Screen::load_enabled(&store), events.clone()));Arc::new(Self {+ team: crate::team::Requests::default(),store,host_id,token,@@ -176,6 +178,7 @@ impl Hub {}pub fn delete_bot(&self, id: &str) -> Result<()> {+ self.team.cancel_bot(id);let _ = self.send_cmd(id, Cmd::Shutdown);self.bots.locked().remove(id);self.runtime.locked().remove(id);diff --git a/host/src/main.rs b/host/src/main.rsindex a87ef63c..4f0ca933 100644--- a/host/src/main.rs+++ b/host/src/main.rs@@ -5,14 +5,17 @@ mod api;mod auth;mod backends;mod bot;+mod context;mod hub;mod market;mod mcp;+mod memory;mod push;mod registry;mod screen;mod service;mod store;+mod team;mod term;mod tui;mod usage;@@ -116,6 +119,13 @@ enum Sub {#[derive(Subcommand)]enum McpServer {+ /// Discover and ask the user's other bots for help.+ Team {+ #[arg(long)]+ bot: String,+ #[arg(long, default_value_t = service::DEFAULT_PORT)]+ port: u16,+ },/// See and operate this computer's desktop.Computer {#[arg(long)]@@ -241,7 +251,8 @@ async fn main() -> Result<()> {println!("Token rotated. Restart the host and pair your phone again.");Ok(())}- Sub::Mcp { server: McpServer::Computer { bot, port } } => mcp::serve(bot, port).await,+ Sub::Mcp { server: McpServer::Computer { bot, port } } => mcp::serve(bot, port, mcp::Server::Computer).await,+ Sub::Mcp { server: McpServer::Team { bot, port } } => mcp::serve(bot, port, mcp::Server::Team).await,Sub::Tui { url, token, port } => {tui::run(url.unwrap_or_else(|| format!("http://127.0.0.1:{port}")), token).await}diff --git a/host/src/mcp.rs b/host/src/mcp.rsindex b04dccdf..e8152eff 100644--- a/host/src/mcp.rs+++ b/host/src/mcp.rs@@ -1,7 +1,6 @@-//! `codync-host mcp computer --bot <id>`: the built-in `computer` MCP server-//! (stdio) handed to bots that have computer use turned on. Each tool call is-//! forwarded to the running host (`POST /api/computerCall`), which checks the-//! bot's permission and who's in control, then drives the screen helper.+//! Built-in stdio MCP servers: `team` discovers and asks other bots; `computer`+//! operates the desktop when enabled. Calls go through authenticated loopback+//! HTTP to the running host, which owns delegation and screen control.use anyhow::Result;use serde_json::{Value, json};@@ -10,6 +9,12 @@ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};const PROTOCOL_VERSION: &str = "2025-06-18";+#[derive(Clone, Copy)]+pub enum Server {+ Computer,+ Team,+}+const INSTRUCTIONS: &str = "Operate this computer's desktop like a person would. Start with `screenshot` \(or `ui_tree` to find controls precisely), then act; every action returns a fresh screenshot. \Coordinates are pixels in the latest screenshot. Prefer keyboard shortcuts and `open_app` over hunting with the mouse. \@@ -93,11 +98,15 @@ fn tools() -> Value {}/// Serves MCP on stdio until the agent closes it.-pub async fn serve(bot: String, port: u16) -> Result<()> {+pub async fn serve(bot: String, port: u16, server: Server) -> Result<()> {let token = std::fs::read_to_string(crate::service::data_dir().join("token")).unwrap_or_default();let token = token.trim().to_owned();let mut lines = BufReader::new(tokio::io::stdin()).lines();let mut out = tokio::io::stdout();+ let (name, instructions, available_tools) = match server {+ Server::Computer => ("codync-computer", INSTRUCTIONS, tools()),+ Server::Team => ("codync-team", crate::team::INSTRUCTIONS, crate::team::tools()),+ };while let Some(line) = lines.next_line().await? {let Ok(msg) = serde_json::from_str::<Value>(&line) else { continue };let Some(id) = msg.get("id").filter(|id| !id.is_null()).cloned() else {@@ -108,12 +117,12 @@ pub async fn serve(bot: String, port: u16) -> Result<()> {"initialize" => Ok(json!({"protocolVersion": params["protocolVersion"].as_str().unwrap_or(PROTOCOL_VERSION),"capabilities": {"tools": {}},- "serverInfo": {"name": "codync-computer", "version": env!("CARGO_PKG_VERSION")},- "instructions": INSTRUCTIONS,+ "serverInfo": {"name": name, "version": env!("CARGO_PKG_VERSION")},+ "instructions": instructions,})),"ping" => Ok(json!({})),- "tools/list" => Ok(json!({"tools": tools()})),- "tools/call" => Ok(call(port, &token, &bot, params).await),+ "tools/list" => Ok(json!({"tools": available_tools})),+ "tools/call" => Ok(call(port, &token, &bot, params, server).await),method => Err(json!({"code": -32601, "message": format!("unknown method {method}")})),};let msg = match reply {@@ -129,24 +138,33 @@ pub async fn serve(bot: String, port: u16) -> Result<()> {}/// One tool call through the host. Failures are tool errors the agent can read, not protocol errors.-async fn call(port: u16, token: &str, bot: &str, params: &Value) -> Value {+async fn call(port: u16, token: &str, bot: &str, params: &Value, server: Server) -> Value {let body = json!({"botId": bot,"name": params["name"],"arguments": params.get("arguments").filter(|a| a.is_object()).cloned().unwrap_or_else(|| json!({})),});+ let (method, timeout) = match server {+ Server::Computer => ("computerCall", Duration::from_secs(60)),+ Server::Team => ("teamCall", crate::team::ASK_TIMEOUT + Duration::from_secs(30)),+ };let res = crate::http()- .post(format!("http://127.0.0.1:{port}/api/computerCall"))+ .post(format!("http://127.0.0.1:{port}/api/{method}")).bearer_auth(token).json(&body)- .timeout(Duration::from_secs(60))+ .timeout(timeout).send().await;let error = match res {Ok(r) => {let ok = r.status().is_success();match r.json::<Value>().await {- Ok(v) if ok => return json!({"content": v["content"]}),+ Ok(v) if ok => {+ return match server {+ Server::Computer => json!({"content": v["content"]}),+ Server::Team => json!({"content": [{"type": "text", "text": v.to_string()}]}),+ };+ }Ok(v) => v["error"].as_str().unwrap_or("the Codync host refused the call").to_owned(),Err(e) => format!("bad response from the Codync host: {e}"),}diff --git a/host/src/memory.rs b/host/src/memory.rsnew file mode 100644index 00000000..c98dd5b7--- /dev/null+++ b/host/src/memory.rs@@ -0,0 +1,795 @@+//! A bot's long-term memory, modeled on Grok Bot's: plain markdown facts in+//! `~/.codync/bots/<id>/memory/`: `profile.md` (who the user is, kept in mind+//! every turn) and `log/YYYY-MM.md` (dated history), one `- (YYYY-MM-DD) fact`+//! per line, so the user and the agent can read, grep and edit them.+//!+//! After each memorable exchange the bot's *keeper* runs a one-shot agent of the+//! same harness that extracts facts (`profile:` / `log:` / `note:` / `remove:`);+//! every [`EPISODE_INTERVAL`] exchanges it also writes a one-line `[episode]`+//! journal entry. The bot sees memory through its frozen prompt (`context`).++use crate::LockExt;+use crate::acp::{self, Acp, Incoming};+use crate::hub::Hub;+use crate::store::{BotConfig, Store};+use anyhow::{Context as _, Result, anyhow, bail};+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};+use std::collections::HashSet;+use std::fmt::Write as _;+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex};+use std::time::Duration;+use tokio::sync::mpsc;++const PROFILE_FILE: &str = "profile.md";+const LOG_DIR: &str = "log";+const PROFILE_HEADER: &str =+ "# About the user\n\n<!-- Enduring facts, one per line as \"- (YYYY-MM-DD) <fact>\". -->\n\n";+const LOG_HEADER: &str = "# Memory log\n\n<!-- Dated facts, one per line as \"- (YYYY-MM-DD) <fact>\". -->\n\n";++/// Profile facts shown in the prompt.+const PROFILE_PROMPT_LIMIT: usize = 100;+/// Log facts shown in the prompt (newest first), within [`RECENT_CHAR_BUDGET`].+pub const RECENT_PROMPT_LIMIT: usize = 30;+const RECENT_CHAR_BUDGET: usize = 4_000;+const MAX_FACT_CHARS: usize = 500;+/// Archived facts scanned for ones relevant to an exchange (beyond those in the prompt).+const ARCHIVE_SCAN_LIMIT: usize = 500;+const RELEVANT_LIMIT: usize = 10;+/// Exchanges per `[episode]` journal line.+pub const EPISODE_INTERVAL: usize = 6;+/// An exchange side is cut to this before it goes to the keeper.+const EXCHANGE_CHARS: usize = 8_000;+const KEEPER_TIMEOUT: Duration = Duration::from_secs(180);++const EPISODE_PREFIX: &str = "[episode] ";+const NOTE_PREFIX: &str = "[note] ";+const NONE: &str = "NONE";+const DAY_MS: i64 = 86_400_000;++/// Serializes writes to memory files (the keeper and the API both write).+static WRITES: Mutex<()> = Mutex::new(());++#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]+#[serde(rename_all = "lowercase")]+pub enum Kind {+ /// Who the user is and how to work with them; kept indefinitely.+ Profile,+ /// Dated history: projects, decisions, commitments, episodes, notes.+ Log,+}++#[derive(Serialize, Clone, Debug)]+#[serde(rename_all = "camelCase")]+pub struct Fact {+ pub id: String,+ pub content: String,+ pub created_at: i64,+ pub kind: Kind,+ #[serde(skip)]+ path: PathBuf,+ #[serde(skip)]+ line: usize,+ #[serde(skip)]+ order: usize,+}++pub struct Recall {+ pub profile: Vec<Fact>,+ pub recent: Vec<Fact>,+}++/// One bot's memory folder.+pub struct Memory {+ dir: PathBuf,+}++impl Memory {+ pub fn for_bot(bot_id: &str) -> Result<Self> {+ // Bot ids are host-generated UUIDs; anything else must not become a path.+ if bot_id.is_empty() || !bot_id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {+ bail!("invalid bot id");+ }+ Ok(Self { dir: crate::service::data_dir().join("bots").join(bot_id).join("memory") })+ }++ #[cfg(test)]+ fn at(dir: PathBuf) -> Self {+ Self { dir }+ }++ pub fn location(&self) -> &Path {+ &self.dir+ }++ fn profile_path(&self) -> PathBuf {+ self.dir.join(PROFILE_FILE)+ }++ fn log_paths(&self) -> Vec<PathBuf> {+ let mut paths: Vec<PathBuf> = std::fs::read_dir(self.dir.join(LOG_DIR))+ .into_iter()+ .flatten()+ .flatten()+ .map(|e| e.path())+ .filter(|p| p.extension().is_some_and(|x| x == "md"))+ .collect();+ paths.sort();+ paths+ }++ pub fn facts(&self) -> Vec<Fact> {+ let mut facts = parse_facts(&read(&self.profile_path()), Kind::Profile, &self.profile_path(), 0);+ for path in self.log_paths() {+ let base = facts.len();+ facts.extend(parse_facts(&read(&path), Kind::Log, &path, base));+ }+ facts+ }++ /// Newest first: every profile fact (capped) and the latest log facts.+ pub fn recall(&self, recent_limit: usize) -> Recall {+ let mut facts = self.facts();+ facts.sort_by(|a, b| b.created_at.cmp(&a.created_at).then(b.order.cmp(&a.order)));+ let (profile, recent): (Vec<Fact>, Vec<Fact>) = facts.into_iter().partition(|f| f.kind == Kind::Profile);+ Recall {+ profile: profile.into_iter().take(PROFILE_PROMPT_LIMIT).collect(),+ recent: recent.into_iter().take(recent_limit).collect(),+ }+ }++ /// Profile facts first, then newest.+ pub fn list(&self, limit: usize) -> Vec<Fact> {+ let mut facts = self.facts();+ facts.sort_by(|a, b| {+ (b.kind == Kind::Profile)+ .cmp(&(a.kind == Kind::Profile))+ .then(b.created_at.cmp(&a.created_at))+ .then(b.order.cmp(&a.order))+ });+ facts.truncate(limit);+ facts+ }++ /// Records a fact unless an equal one exists. Returns whether it was added.+ pub fn add(&self, content: &str, kind: Kind, at_ms: i64) -> Result<bool> {+ let content = normalize(content);+ if content.is_empty() {+ return Ok(false);+ }+ let _g = WRITES.locked();+ if self.facts().iter().any(|f| dedupe_key(&f.content) == dedupe_key(&content)) {+ return Ok(false);+ }+ let (path, header) = match kind {+ Kind::Profile => (self.profile_path(), PROFILE_HEADER),+ Kind::Log => (self.dir.join(LOG_DIR).join(format!("{}.md", &ymd(at_ms)[..7])), LOG_HEADER),+ };+ let raw = read(&path);+ let mut body = if raw.is_empty() { header.to_owned() } else { raw };+ if !body.ends_with('\n') {+ body.push('\n');+ }+ let _ = writeln!(body, "- ({}) {content}", ymd(at_ms));+ write_atomic(&path, &body)?;+ Ok(true)+ }++ pub fn remove(&self, id: &str) -> Result<bool> {+ let _g = WRITES.locked();+ let Some(fact) = self.facts().into_iter().find(|f| f.id == id) else { return Ok(false) };+ let mut lines: Vec<&str> = Vec::new();+ let raw = read(&fact.path);+ lines.extend(raw.split('\n'));+ if fact.line < lines.len() {+ lines.remove(fact.line);+ }+ write_atomic(&fact.path, &lines.join("\n"))?;+ Ok(true)+ }++ pub fn remove_by_content(&self, content: &str) -> Result<bool> {+ self.remove(&fact_id(&normalize(content)))+ }++ pub fn clear(&self) -> Result<()> {+ let _g = WRITES.locked();+ match std::fs::remove_dir_all(self.dir.join(LOG_DIR)) {+ Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),+ _ => {}+ }+ write_atomic(&self.profile_path(), PROFILE_HEADER)+ }+}++fn read(path: &Path) -> String {+ std::fs::read_to_string(path).unwrap_or_default()+}++fn write_atomic(path: &Path, body: &str) -> Result<()> {+ let dir = path.parent().ok_or_else(|| anyhow!("memory path has no folder"))?;+ std::fs::create_dir_all(dir)?;+ let tmp = path.with_extension("md.tmp");+ std::fs::write(&tmp, body)?;+ std::fs::rename(&tmp, path).with_context(|| format!("writing {}", path.display()))+}++fn parse_facts(raw: &str, kind: Kind, path: &Path, base: usize) -> Vec<Fact> {+ let mut out = Vec::new();+ for (line, text) in raw.split('\n').enumerate() {+ let Some(rest) = text.trim_end().strip_prefix("- (") else { continue };+ let Some((date, content)) = rest.split_once(") ") else { continue };+ let Some(created_at) = parse_ymd(date) else { continue };+ let content = normalize(content);+ if content.is_empty() {+ continue;+ }+ out.push(Fact {+ id: fact_id(&content),+ content,+ created_at,+ kind,+ path: path.to_owned(),+ line,+ order: base + out.len(),+ });+ }+ out+}++pub fn normalize(raw: &str) -> String {+ raw.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(MAX_FACT_CHARS).collect()+}++fn dedupe_key(content: &str) -> String {+ normalize(content).to_lowercase()+}++/// Stable id of a fact (FNV-1a of its dedupe key), so the same text is the same fact.+fn fact_id(content: &str) -> String {+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;+ for b in dedupe_key(content).bytes() {+ h ^= u64::from(b);+ h = h.wrapping_mul(0x0100_0000_01b3);+ }+ format!("{h:016x}")+}++// MARK: dates (UTC, no calendar crate needed)++/// `YYYY-MM-DD` for a unix time in ms.+pub fn ymd(ms: i64) -> String {+ if ms <= 0 {+ return "unknown date".into();+ }+ let z = ms.div_euclid(DAY_MS) + 719_468;+ let era = z.div_euclid(146_097);+ let doe = z - era * 146_097;+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+ let mp = (5 * doy + 2) / 153;+ let d = doy - (153 * mp + 2) / 5 + 1;+ let m = if mp < 10 { mp + 3 } else { mp - 9 };+ let y = yoe + era * 400 + i64::from(m <= 2);+ format!("{y:04}-{m:02}-{d:02}")+}++fn parse_ymd(s: &str) -> Option<i64> {+ let mut parts = s.splitn(3, '-').map(str::parse::<i64>);+ let (y, m, d) = (parts.next()?.ok()?, parts.next()?.ok()?, parts.next()?.ok()?);+ if !(1..=12).contains(&m) || !(1..=31).contains(&d) {+ return None;+ }+ let y = if m <= 2 { y - 1 } else { y };+ let era = y.div_euclid(400);+ let yoe = y - era * 400;+ let doy = (153 * ((m + 9) % 12) + 2) / 5 + d - 1;+ let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;+ Some((era * 146_097 + doe - 719_468) * DAY_MS)+}++// MARK: prompt++fn fact_line(f: &Fact) -> String {+ format!("- (learned {}) {}", ymd(f.created_at), f.content)+}++/// The memory section of the bot's instructions, and whether it holds any facts.+pub fn render(recall: &Recall, location: &Path) -> (String, bool) {+ let mut lines = vec![+ "Memory: durable facts you have learned about the user and their world.".to_owned(),+ "These persist across every session with this bot, even after a new session starts. Rely on them so you stay consistent and avoid re-asking what you already know.".to_owned(),+ format!(+ "Your memory lives in a folder at {}: {PROFILE_FILE} holds who the user is (kept in mind every turn) and {LOG_DIR}/ holds dated history.",+ location.display()+ ),+ "Read or grep those files when you need older facts that are not listed here. Memory is updated automatically after each exchange: when the user asks you to remember or forget something, just confirm it in your reply and it will be recorded.".to_owned(),+ ];+ if !recall.profile.is_empty() {+ lines.push("About the user:".into());+ lines.extend(recall.profile.iter().map(fact_line));+ }+ if !recall.recent.is_empty() {+ lines.push("Recently:".into());+ let mut budget = RECENT_CHAR_BUDGET;+ let mut shown = 0;+ for f in &recall.recent {+ let line = fact_line(f);+ if shown > 0 && line.len() > budget {+ break;+ }+ budget = budget.saturating_sub(line.len());+ lines.push(line);+ shown += 1;+ }+ let omitted = recall.recent.len() - shown;+ if omitted > 0 {+ lines.push(format!("({omitted} more log facts on disk — grep the {LOG_DIR}/ folder for them.)"));+ }+ }+ let has_facts = !recall.profile.is_empty() || !recall.recent.is_empty();+ if !has_facts {+ lines.push("No facts recorded yet.".into());+ }+ (lines.join("\n"), has_facts)+}++// MARK: extraction (prompts as in Grok Bot)++const TRIVIAL: &[&str] = &[+ "hi",+ "hey",+ "hello",+ "yo",+ "sup",+ "thanks",+ "thank you",+ "ty",+ "thx",+ "ok",+ "okay",+ "k",+ "kk",+ "cool",+ "nice",+ "great",+ "awesome",+ "perfect",+ "yes",+ "yep",+ "yeah",+ "no",+ "nope",+ "sure",+ "got it",+ "gotcha",+ "lol",+ "haha",+ "np",+ "done",+ "good",+ "bye",+];++/// Small talk ("thanks", "ok") isn't worth a keeper run.+pub fn is_memorable(user: &str) -> bool {+ let user = user.trim();+ if user.is_empty() {+ return false;+ }+ if user.chars().count() > 40 || user.contains('?') {+ return true;+ }+ let bare = user.to_lowercase();+ let bare = bare.trim_end_matches(|c: char| c.is_whitespace() || "!.…,~)]".contains(c));+ !TRIVIAL.contains(&bare.split_whitespace().collect::<Vec<_>>().join(" ").as_str())+}++pub fn extraction_system_prompt() -> String {+ [+ "You maintain the long-term memory of a personal assistant. Read the latest exchange and decide what — if anything — is worth remembering for future, unrelated conversations.",+ "",+ "Tag each fact you keep with a category:",+ "- \"profile\": enduring facts about who the user is and how to work with them — their name and how to address them, role, location, languages, lasting preferences and constraints, and important people or relationships. These are remembered indefinitely.",+ "- \"log\": substantive history worth keeping — ongoing projects and tasks, decisions, commitments, and time-bound details.",+ "- \"note\": minor, low-stakes details that might help someday but are not worth keeping in mind every turn (small one-off preferences, incidental context). Notes fade from the always-visible list fastest but stay on disk.",+ "",+ "Do NOT record one-off request mechanics, what the assistant did this turn, general knowledge, or anything already present in the existing memory list.",+ "",+ "If the new exchange updates or contradicts a fact in the existing memory list (e.g. the user moved, changed jobs, or renamed something), drop anything clearly superseded: output a line \"remove: <the exact existing fact text>\" and then add the corrected fact. Only remove facts that appear verbatim in the existing list — never invent removals.",+ "",+ "Write each fact as a self-contained statement, one per line: \"profile: <fact>\", \"log: <fact>\", or \"note: <fact>\" to add (e.g. \"profile: The user's name is Ian\", \"log: Planning a trip to Tokyo in October 2025\"), or \"remove: <existing fact>\" to drop a superseded one.",+ "Output exactly NONE (and nothing else) when there is nothing to add or remove.",+ ]+ .join("\n")+}++pub fn extraction_user_prompt(user: &str, agent: &str, existing: &[String]) -> String {+ let existing = if existing.is_empty() {+ "(empty)".to_owned()+ } else {+ existing.iter().map(|m| format!("- {m}")).collect::<Vec<_>>().join("\n")+ };+ let side = |s: &str| if s.trim().is_empty() { "(no message)".to_owned() } else { s.trim().to_owned() };+ format!("Existing memory:\n{existing}\n\nLatest exchange:\nUser: {}\nAssistant: {}", side(user), side(agent))+}++#[derive(Debug, Default, PartialEq, Eq)]+pub struct Extraction {+ pub additions: Vec<(String, Kind)>,+ pub removals: Vec<String>,+}++pub fn parse_extraction(raw: &str, existing: &[String]) -> Extraction {+ let mut out = Extraction::default();+ let raw = raw.trim();+ if raw.is_empty() || raw.eq_ignore_ascii_case(NONE) {+ return out;+ }+ let mut seen: HashSet<String> = existing.iter().map(|m| dedupe_key(m)).collect();+ for line in raw.lines() {+ let line = strip_bullet(line);+ let (tag, rest) = match line.split_once(':') {+ Some((t, r)) if ["profile", "log", "note", "remove"].contains(&t.trim().to_lowercase().as_str()) => {+ (Some(t.trim().to_lowercase()), r)+ }+ _ => (None, line),+ };+ let bare = normalize(rest);+ if bare.is_empty() || bare.eq_ignore_ascii_case(NONE) {+ continue;+ }+ if tag.as_deref() == Some("remove") {+ out.removals.push(bare);+ continue;+ }+ let content = if tag.as_deref() == Some("note") { normalize(&format!("{NOTE_PREFIX}{bare}")) } else { bare };+ if seen.insert(dedupe_key(&content)) {+ out.additions.push((content, if tag.as_deref() == Some("profile") { Kind::Profile } else { Kind::Log }));+ }+ }+ out+}++fn strip_bullet(line: &str) -> &str {+ let t = line.trim_start();+ for b in ["- ", "* ", "• "] {+ if let Some(r) = t.strip_prefix(b) {+ return r;+ }+ }+ let digits = t.chars().take_while(char::is_ascii_digit).count();+ if digits > 0+ && let Some(r) = t[digits..].strip_prefix(". ").or_else(|| t[digits..].strip_prefix(") "))+ {+ return r;+ }+ t+}++const STOPWORDS: &[&str] = &[+ "that", "this", "with", "from", "they", "them", "then", "than", "what", "when", "where", "which", "will", "would",+ "could", "should", "have", "been", "being", "about", "just", "like", "your", "does", "were", "also", "into",+ "over", "only", "some", "more", "most", "very", "much", "here", "there", "their", "these", "those", "because",+ "while", "after", "before", "user",+];++fn tokens(text: &str) -> HashSet<String> {+ text.to_lowercase()+ .split(|c: char| !c.is_alphanumeric())+ .filter(|w| w.chars().count() >= 4 && !STOPWORDS.contains(w))+ .map(str::to_owned)+ .collect()+}++/// What the keeper is shown as "existing memory": everything in the prompt plus+/// archived facts that share words with the exchange.+pub fn existing_for_extraction(mem: &Memory, exchange: &str) -> Vec<String> {+ let recall = mem.recall(RECENT_PROMPT_LIMIT);+ let in_prompt: Vec<&Fact> = recall.profile.iter().chain(&recall.recent).collect();+ let shown: HashSet<String> = in_prompt.iter().map(|f| dedupe_key(&f.content)).collect();+ let query = tokens(exchange);+ let mut relevant: Vec<(usize, Fact)> = if query.is_empty() {+ Vec::new()+ } else {+ mem.list(ARCHIVE_SCAN_LIMIT)+ .into_iter()+ .filter(|f| !shown.contains(&dedupe_key(&f.content)))+ .map(|f| (tokens(&f.content).intersection(&query).count(), f))+ .filter(|(overlap, _)| *overlap > 0)+ .collect()+ };+ relevant.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.created_at.cmp(&a.1.created_at)));+ in_prompt+ .into_iter()+ .map(|f| f.content.clone())+ .chain(relevant.into_iter().take(RELEVANT_LIMIT).map(|(_, f)| f.content))+ .collect()+}++pub fn apply(mem: &Memory, ex: &Extraction, known: &[String], now: i64) -> Result<(usize, usize)> {+ let known: HashSet<String> = known.iter().map(|k| dedupe_key(k)).collect();+ let mut removed = 0;+ for r in &ex.removals {+ if known.contains(&dedupe_key(r)) && mem.remove_by_content(r)? {+ removed += 1;+ }+ }+ let mut added = 0;+ for (content, kind) in &ex.additions {+ if mem.add(content, *kind, now)? {+ added += 1;+ }+ }+ Ok((added, removed))+}++#[derive(Serialize, Deserialize, Clone, Debug)]+pub struct EpisodeTurn {+ pub ts: i64,+ pub user: String,+ pub agent: String,+}++pub fn episode_system_prompt(bot_name: &str) -> String {+ [+ format!("You maintain the long-term memory of a personal assistant named {bot_name}."),+ format!("You are given the most recent turns of a conversation between the user and {bot_name}, in order, each tagged with its date."),+ format!("Write ONE short journal-style sentence (two at most) capturing what the user and {bot_name} were actually working on across these turns — the throughline, key decisions, and outcomes — so it stays useful months from now."),+ "Anchor any time references with the absolute dates shown, never relative words like \"yesterday\". Drop greetings, acknowledgements, and anything ephemeral. Never invent details.".to_owned(),+ "Output just the sentence(s), no preamble or bullets. Output exactly NONE if nothing in this stretch is worth remembering.".to_owned(),+ ]+ .join("\n")+}++pub fn episode_user_prompt(bot_name: &str, turns: &[EpisodeTurn]) -> String {+ let body = turns+ .iter()+ .map(|t| {+ let mut parts = vec![format!("({})", ymd(t.ts))];+ if !t.user.trim().is_empty() {+ parts.push(format!("User: {}", t.user.trim()));+ }+ if !t.agent.trim().is_empty() {+ parts.push(format!("{bot_name}: {}", t.agent.trim()));+ }+ parts.join("\n")+ })+ .collect::<Vec<_>>()+ .join("\n\n");+ format!("Recent turns, oldest first:\n\n{body}")+}++fn episode_key(bot_id: &str) -> String {+ format!("memory.episode.{bot_id}")+}++pub fn pending_episode(store: &Store, bot_id: &str) -> Vec<EpisodeTurn> {+ store.kv_get(&episode_key(bot_id)).and_then(|v| serde_json::from_str(&v).ok()).unwrap_or_default()+}++pub fn set_pending_episode(store: &Store, bot_id: &str, turns: &[EpisodeTurn]) -> Result<()> {+ store.kv_set(&episode_key(bot_id), &serde_json::to_string(turns)?)+}++// MARK: keeper++/// A finished user ↔ agent exchange worth remembering.+pub struct Exchange {+ pub user: String,+ pub agent: String,+ pub at: i64,+}++/// Starts the bot's keeper: exchanges are remembered one at a time, in the+/// background. It stops when the bot actor drops the sender.+pub fn spawn_keeper(hub: Arc<Hub>, bot_id: String) -> mpsc::UnboundedSender<Exchange> {+ let (tx, mut rx) = mpsc::unbounded_channel::<Exchange>();+ tokio::spawn(async move {+ while let Some(x) = rx.recv().await {+ if let Err(e) = remember(&hub, &bot_id, x).await {+ tracing::warn!(bot = %bot_id, error = format!("{e:#}"), "memory keeper failed");+ }+ }+ });+ tx+}++async fn remember(hub: &Arc<Hub>, bot_id: &str, x: Exchange) -> Result<()> {+ let Some(cfg) = hub.store.bot(bot_id)?.filter(|b| !b.deleted).map(|b| b.config) else { return Ok(()) };+ let user = acp::truncate(&x.user, EXCHANGE_CHARS);+ let agent = acp::truncate(&x.agent, EXCHANGE_CHARS);++ let id = bot_id.to_owned();+ let exchange_text = format!("{user}\n{agent}");+ let existing = tokio::task::spawn_blocking(move || {+ Memory::for_bot(&id).map(|mem| existing_for_extraction(&mem, &exchange_text))+ })+ .await??;+ let raw =+ one_shot(hub, &cfg, &extraction_system_prompt(), &extraction_user_prompt(&user, &agent, &existing)).await?;+ let extraction = parse_extraction(&raw, &existing);+ let id = bot_id.to_owned();+ let (added, removed) = tokio::task::spawn_blocking(move || {+ Memory::for_bot(&id).and_then(|mem| apply(&mem, &extraction, &existing, crate::store::now_ms()))+ })+ .await??;+ tracing::info!(bot = %bot_id, added, removed, "memory updated");++ let mut pending = pending_episode(&hub.store, bot_id);+ pending.push(EpisodeTurn { ts: x.at, user, agent });+ if pending.len() < EPISODE_INTERVAL {+ return set_pending_episode(&hub.store, bot_id, &pending);+ }+ set_pending_episode(&hub.store, bot_id, &[])?;+ let raw = one_shot(hub, &cfg, &episode_system_prompt(&cfg.name), &episode_user_prompt(&cfg.name, &pending)).await?;+ let narrative = normalize(&raw);+ if !narrative.is_empty() && !narrative.eq_ignore_ascii_case(NONE) {+ let at = pending.last().map_or(x.at, |t| t.ts);+ let id = bot_id.to_owned();+ tokio::task::spawn_blocking(move || {+ Memory::for_bot(&id).and_then(|mem| mem.add(&format!("{EPISODE_PREFIX}{narrative}"), Kind::Log, at))+ })+ .await??;+ }+ Ok(())+}++/// Runs one prompt on a throwaway agent of the bot's harness and returns its reply.+/// Claude gets a real system prompt, no tools, no settings and no saved session;+/// other harnesses get the instructions inline.+async fn one_shot(hub: &Arc<Hub>, cfg: &BotConfig, system: &str, user: &str) -> Result<String> {+ let cwd = crate::service::data_dir().join("memory-keeper");+ tokio::fs::create_dir_all(&cwd).await?;+ let cwd = cwd.to_string_lossy().into_owned();+ let env = crate::auth::env(&hub.store, &cfg.backend);+ let mut conn = None;+ let mut last_err = None;+ for command in crate::bot::launch_commands(cfg, |_| {}).await? {+ match crate::bot::start_agent(&command, &cwd, &env, Duration::from_secs(60)).await {+ Ok(c) => {+ conn = Some(c);+ break;+ }+ Err(e) => last_err = Some(e),+ }+ }+ let mut conn = conn.ok_or_else(|| last_err.unwrap_or_else(|| anyhow!("no agent to run the memory keeper")))?;+ let acp = conn.acp.clone();+ let result = async {+ let mut params = json!({"cwd": cwd, "mcpServers": []});+ let text = if conn.claude {+ params["_meta"] = json!({+ "systemPrompt": system,+ "claudeCode": {"options": {"tools": [], "persistSession": false, "settingSources": [], "model": "haiku"}},+ });+ user.to_owned()+ } else {+ format!("{system}\n\n---\n\n{user}")+ };+ let sid = acp.request("session/new", params).await?["sessionId"]+ .as_str()+ .ok_or_else(|| anyhow!("agent returned no sessionId"))?+ .to_owned();+ let prompt = acp.request("session/prompt", json!({"sessionId": sid, "prompt": [{"type": "text", "text": text}]}));+ tokio::pin!(prompt);+ let deadline = tokio::time::sleep(KEEPER_TIMEOUT);+ tokio::pin!(deadline);+ let mut out = String::new();+ loop {+ tokio::select! {+ r = &mut prompt => { r?; break }+ inc = conn.rx.recv() => {+ if !collect(&acp, inc, &mut out).await {+ bail!("the memory keeper's agent exited");+ }+ }+ () = &mut deadline => bail!("the memory keeper timed out"),+ }+ }+ while let Ok(inc) = conn.rx.try_recv() {+ collect(&acp, Some(inc), &mut out).await;+ }+ Ok(out)+ }+ .await;+ acp.kill().await;+ result+}++/// Keeps reply text; refuses anything the agent asks of us. False once the agent is gone.+async fn collect(acp: &Acp, inc: Option<Incoming>, out: &mut String) -> bool {+ match inc {+ None | Some(Incoming::Closed { .. }) => false,+ Some(Incoming::Notification { method, params }) => {+ let u = ¶ms["update"];+ if method == "session/update" && u["sessionUpdate"] == "agent_message_chunk" {+ out.push_str(&acp::content_text(&u["content"]));+ }+ true+ }+ Some(Incoming::Request { id, method, .. }) => {+ let _ = if method == "session/request_permission" {+ acp.respond(id, json!({"outcome": {"outcome": "cancelled"}})).await+ } else {+ acp.respond_error(id, -32601, "not supported").await+ };+ true+ }+ }+}++/// `memory` API: the facts a bot has, for the Memory screen.+pub fn describe(bot_id: &str) -> Result<Value> {+ let mem = Memory::for_bot(bot_id)?;+ Ok(json!({"location": mem.location(), "facts": mem.list(1_000)}))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn temp() -> Memory {+ let dir = std::env::temp_dir().join(format!("codync-memory-{}", uuid::Uuid::new_v4()));+ Memory::at(dir)+ }++ #[test]+ fn dates_round_trip() {+ assert_eq!(ymd(0), "unknown date");+ assert_eq!(ymd(1_758_800_000_000), "2025-09-25");+ assert_eq!(ymd(951_782_400_000), "2000-02-29");+ for day in ["2024-02-29", "2026-01-01", "1999-12-31"] {+ assert_eq!(ymd(parse_ymd(day).expect("valid date")), day);+ }+ assert_eq!(parse_ymd("2026-13-01"), None);+ }++ #[test]+ fn facts_are_stored_deduped_and_removed() {+ let mem = temp();+ let t = parse_ymd("2026-09-25").expect("valid date");+ assert!(mem.add("The user's name is Kai", Kind::Profile, t).expect("add"));+ assert!(!mem.add("the user's name is kai", Kind::Profile, t).expect("add"));+ assert!(mem.add("Shipping Codync 2.2", Kind::Log, t).expect("add"));+ assert!(read(&mem.dir.join("log/2026-09.md")).contains("- (2026-09-25) Shipping Codync 2.2"));+ let recall = mem.recall(RECENT_PROMPT_LIMIT);+ assert_eq!(recall.profile.len(), 1);+ assert_eq!(recall.recent.len(), 1);+ let (text, has) = render(&recall, mem.location());+ assert!(has && text.contains("- (learned 2026-09-25) The user's name is Kai"));+ assert!(mem.remove_by_content("Shipping Codync 2.2").expect("remove"));+ assert!(mem.recall(10).recent.is_empty());+ mem.clear().expect("clear");+ assert!(mem.facts().is_empty());+ let _ = std::fs::remove_dir_all(&mem.dir);+ }++ #[test]+ fn extraction_output_is_parsed() {+ let existing = vec!["Lives in Taipei".to_owned()];+ let ex = parse_extraction(+ "- profile: The user's name is Ian\n2. log: Planning a trip\nnote: likes tea\nremove: Lives in Taipei\nprofile: lives in taipei\nNONE",+ &existing,+ );+ assert_eq!(+ ex.additions,+ vec![+ ("The user's name is Ian".to_owned(), Kind::Profile),+ ("Planning a trip".to_owned(), Kind::Log),+ ("[note] likes tea".to_owned(), Kind::Log),+ ]+ );+ assert_eq!(ex.removals, vec!["Lives in Taipei".to_owned()]);+ assert_eq!(parse_extraction(" none ", &[]), Extraction::default());+ }++ #[test]+ fn small_talk_is_not_memorable() {+ assert!(!is_memorable("thanks!"));+ assert!(!is_memorable(" OK. "));+ assert!(is_memorable("my name is Kai"));+ assert!(is_memorable("why?"));+ }+}diff --git a/host/src/registry.rs b/host/src/registry.rsindex 2f377dcb..999b9b76 100644--- a/host/src/registry.rs+++ b/host/src/registry.rs@@ -98,7 +98,7 @@ pub fn launch_kind(agent: &Value) -> Option<Launch> {None}-fn shell_quote(s: &str) -> String {+pub fn shell_quote(s: &str) -> String {if !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "-_./=@:+,".contains(c)) {s.to_owned()} else {@@ -114,8 +114,9 @@ fn args_of(v: &Value) -> String {}/// `KEY=value ` pairs; keys that aren't plain identifiers are dropped (they'd be shell syntax).-fn env_prefix(v: &Value) -> String {- v["env"]+/// Goes through `env` so the result still works after `exec`.+pub fn env_prefix(env: &Value) -> String {+ let pairs = env.as_object().map(|m| {m.iter()@@ -123,7 +124,8 @@ fn env_prefix(v: &Value) -> String {.filter_map(|(k, v)| Some(format!("{k}={} ", shell_quote(v.as_str()?)))).collect::<String>()})- .unwrap_or_default()+ .unwrap_or_default();+ if pairs.is_empty() { pairs } else { format!("env {pairs}") }}/// One path component made only of `[A-Za-z0-9._-]` and not `.`/`..`.@@ -168,14 +170,14 @@ pub async fn command(agent: &Value, progress: impl Fn(&str)) -> Result<Cmd> {target["cmd"].as_str().and_then(contained).ok_or_else(|| anyhow!("registry entry has a bad cmd"))?;let dir = install_binary(agent, target, cmd, &progress).await?;Ok(Cmd {- program: format!("{}{}", env_prefix(target), shell_quote(&dir.join(cmd).to_string_lossy())),+ program: format!("{}{}", env_prefix(&target["env"]), shell_quote(&dir.join(cmd).to_string_lossy())),args: args_of(target),})}Some(Launch::Npx) => Ok(Cmd {program: format!("{}npx -y {}",- env_prefix(&d["npx"]),+ env_prefix(&d["npx"]["env"]),shell_quote(d["npx"]["package"].as_str().unwrap_or_default())),args: args_of(&d["npx"]),@@ -183,7 +185,7 @@ pub async fn command(agent: &Value, progress: impl Fn(&str)) -> Result<Cmd> {Some(Launch::Uvx) => Ok(Cmd {program: format!("{}uvx {}",- env_prefix(&d["uvx"]),+ env_prefix(&d["uvx"]["env"]),shell_quote(d["uvx"]["package"].as_str().unwrap_or_default())),args: args_of(&d["uvx"]),@@ -313,7 +315,7 @@ mod tests {async fn npx_command_is_quoted() {let a = json!({"id": "x", "name": "X", "distribution": {"npx": {"package": "@s/[email protected]", "args": ["--acp", "a b"], "env": {"K": "v", "BAD;rm": "x"}}}});if crate::backends::on_path("npx") {- assert_eq!(command(&a, |_| {}).await.unwrap().acp(), "K=v npx -y @s/[email protected] --acp 'a b'");+ assert_eq!(command(&a, |_| {}).await.unwrap().acp(), "env K=v npx -y @s/[email protected] --acp 'a b'");}}diff --git a/host/src/store.rs b/host/src/store.rsindex 080d9cc5..6b386450 100644--- a/host/src/store.rs+++ b/host/src/store.rs@@ -397,13 +397,27 @@ impl Store {let c = self.db.locked();let mut st = c.prepare("SELECT id FROM entries WHERE (kind = 'permission' AND json_extract(data, '$.status') = 'pending')- OR (kind = 'user' AND json_extract(data, '$.status') = 'queued')",+ OR (kind = 'user' AND json_extract(data, '$.status') = 'queued')+ OR (kind = 'notice' AND json_extract(data, '$.delegationId') IS NOT NULL+ AND json_extract(data, '$.status') IN ('queued', 'sent'))",)?;st.query_map([], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?};for id in &ids {if let Some(mut e) = self.entry(id) {- let status = if e.kind == EntryKind::User.as_str() { "failed" } else { "expired" };+ let status = if e.kind == EntryKind::Notice.as_str() {+ let heading = e.data["heading"].as_str().unwrap_or("Bot request");+ e.data["text"] = format!(+ "{heading}\nInterrupted by host restart. Partial work may have happened; check before retrying."+ )+ .into();+ e.data["style"] = "error".into();+ "failed"+ } else if e.kind == EntryKind::User.as_str() {+ "failed"+ } else {+ "expired"+ };e.data["status"] = status.into();self.update_entry(id, &e.data)?;}diff --git a/host/src/team.rs b/host/src/team.rsnew file mode 100644index 00000000..78def9af--- /dev/null+++ b/host/src/team.rs@@ -0,0 +1,533 @@+//! Small, host-local bot delegation. The recipient uses its own ACP session;+//! native subagents remain the harness's responsibility.++use crate::LockExt;+use crate::bot::Cmd;+use crate::hub::{BotStatus, Hub};+use crate::store::{BotConfig, EntryKind};+use anyhow::{Result, anyhow, bail};+use serde::Serialize;+use serde_json::{Value, json};+use std::collections::{HashMap, HashSet};+use std::sync::{Arc, Mutex};+use std::time::Duration;+use tokio::sync::{oneshot, watch};++pub const ASK_TIMEOUT: Duration = Duration::from_secs(600);+const MAX_MESSAGE_BYTES: usize = 32_000;++pub const INSTRUCTIONS: &str = "Use list_bots to find the user's other Codync bots. \+Use ask_bot when the user requests another bot's help or its specialty is useful. \+Provide a self-contained request: the recipient has its own conversation, working directory, \+tools and permissions, not your context. It returns its final reply to you. \+Coordinate file ownership before asking for edits in a shared project. \+Do not ask a bot that is waiting for you. Native subagents are managed by your own harness; \+these tools are for collaborating with the user's existing bots.";++pub fn tools() -> Value {+ json!([+ {+ "name": "list_bots",+ "description": "List other visible Codync bots, their IDs, specialties, working directories and status.",+ "inputSchema": {"type": "object", "properties": {}},+ "annotations": {"readOnlyHint": true},+ },+ {+ "name": "ask_bot",+ "description": "Ask an existing Codync bot to do a bounded task and wait for its final reply (up to 10 minutes, including queue time). It may use tools and modify files under its own permissions. Does not share your conversation or change its working directory. Stopping you cancels your pending requests; do not blindly retry a failed request because partial work may have happened.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "botId": {"type": "string", "description": "Recipient ID from list_bots."},+ "message": {"type": "string", "description": "Task, relevant context, file paths and expected result."},+ },+ "required": ["botId", "message"],+ },+ "annotations": {"readOnlyHint": false, "idempotentHint": false},+ }+ ])+}++struct Request {+ from: String,+ to: String,+ cancel: watch::Sender<bool>,+}++/// The wait graph includes queued requests, not only running recipients.+/// Reserving an edge and checking for cycles happen under the same lock.+#[derive(Default)]+pub struct Requests(Mutex<RequestState>);++#[derive(Default)]+struct RequestState {+ pending: HashMap<String, Request>,+ active: HashSet<String>,+}++impl Requests {+ fn begin(&self, id: &str, from: &str, to: &str) -> Result<watch::Receiver<bool>> {+ let mut state = self.0.locked();+ if !state.active.contains(from) {+ bail!("the requesting bot is no longer working");+ }+ let requests = &mut state.pending;+ if from == to {+ bail!("a bot cannot ask itself");+ }+ if requests.len() >= 64 {+ bail!("too many pending bot requests");+ }+ if requests.values().any(|r| r.from == from && r.to == to) {+ bail!("already waiting for this bot");+ }+ let mut pending = vec![to];+ let mut seen = HashSet::new();+ while let Some(bot) = pending.pop() {+ if bot == from {+ bail!("this request would make bots wait for each other; finish the current request first");+ }+ if seen.insert(bot) {+ pending.extend(requests.values().filter(|r| r.from == bot).map(|r| r.to.as_str()));+ }+ }+ let (cancel, rx) = watch::channel(false);+ requests.insert(id.to_owned(), Request { from: from.to_owned(), to: to.to_owned(), cancel });+ Ok(rx)+ }++ pub fn cancel_from(&self, bot: &str) {+ let mut state = self.0.locked();+ state.active.remove(bot);+ for request in state.pending.values().filter(|r| r.from == bot) {+ request.cancel.send_replace(true);+ }+ }++ pub fn start_turn(&self, bot: &str) {+ self.0.locked().active.insert(bot.to_owned());+ }++ pub fn cancel_bot(&self, bot: &str) {+ let mut state = self.0.locked();+ state.active.remove(bot);+ for request in state.pending.values().filter(|r| r.from == bot || r.to == bot) {+ request.cancel.send_replace(true);+ }+ }+}++/// Sent through the recipient's normal actor queue, but never merged with user+/// messages or another request. Only this turn can resolve its reply channel.+pub struct Ask {+ pub id: String,+ pub entry_id: String,+ pub prompt: String,+ pub reply: oneshot::Sender<Result<String>>,+}++#[derive(Clone, Copy, Serialize)]+#[serde(rename_all = "lowercase")]+enum Status {+ Completed,+ Failed,+ Cancelled,+}++struct Pending {+ hub: Arc<Hub>,+ id: String,+ target: String,+ entries: Vec<String>,+ finished: bool,+}++impl Pending {+ fn finish(&mut self, status: Status, detail: &str) {+ for id in &self.entries {+ if let Some(mut e) = self.hub.store.entry(id) {+ e.data["status"] = json!(status);+ let heading = e.data["heading"].as_str().unwrap_or("Bot request");+ e.data["text"] = format!("{heading}\n{detail}").into();+ if !matches!(status, Status::Completed) {+ e.data["style"] = "error".into();+ }+ self.hub.set_entry(id, &e.data);+ }+ }+ self.finished = true;+ }+}++impl Drop for Pending {+ fn drop(&mut self) {+ if !self.finished {+ self.finish(Status::Cancelled, "Request cancelled. Partial work may have happened.");+ }+ self.hub.team.0.locked().pending.remove(&self.id);+ // Targeted cancellation never clears unrelated user messages or turns.+ let _ = self.hub.send_cmd(&self.target, Cmd::CancelAsk { id: self.id.clone() });+ }+}++fn visible_bot(hub: &Hub, id: &str) -> Result<BotConfig> {+ hub.store+ .bot(id)?+ .filter(|r| !r.deleted && !r.config.hidden)+ .map(|r| r.config)+ .ok_or_else(|| anyhow!("unknown or hidden bot"))+}++pub async fn call(hub: &Arc<Hub>, from: &str, name: &str, args: &Value) -> Result<Value> {+ let source = visible_bot(hub, from)?;+ match name {+ "list_bots" => {+ let bots: Vec<Value> = hub+ .store+ .bots()?+ .into_iter()+ .filter(|b| !b.deleted && !b.config.hidden && b.config.id != from)+ .map(|b| {+ json!({+ "id": b.config.id, "name": b.config.name, "description": b.config.description,+ "backend": b.config.backend, "cwd": b.config.cwd,+ "status": hub.runtime(&b.config.id).status,+ })+ })+ .collect();+ Ok(json!({"bots": bots}))+ }+ "ask_bot" => {+ let to = args["botId"].as_str().ok_or_else(|| anyhow!("botId is required"))?;+ let message = args["message"].as_str().unwrap_or_default().trim();+ ask(hub, &source, to, message, ASK_TIMEOUT).await+ }+ _ => bail!("unknown team tool: {name}"),+ }+}++async fn ask(hub: &Arc<Hub>, source: &BotConfig, to: &str, message: &str, timeout: Duration) -> Result<Value> {+ if message.is_empty() || message.len() > MAX_MESSAGE_BYTES {+ bail!("message must be nonempty and at most {MAX_MESSAGE_BYTES} bytes");+ }+ if !matches!(hub.runtime(&source.id).status, BotStatus::Working | BotStatus::NeedsInput) {+ bail!("the requesting bot is no longer working");+ }+ let target = visible_bot(hub, to)?;+ let id = uuid::Uuid::new_v4().to_string();+ let mut cancelled = hub.team.begin(&id, &source.id, to)?;+ let mut pending =+ Pending { hub: hub.clone(), id: id.clone(), target: to.to_owned(), entries: vec![], finished: false };+ if !matches!(hub.runtime(&source.id).status, BotStatus::Working | BotStatus::NeedsInput) {+ bail!("the requesting bot is no longer working");+ }+ for (bot, heading) in [+ (&source.id, format!("Asked {}: {}", target.name, message)),+ (&target.id, format!("Request from {}: {}", source.name, message)),+ ] {+ let entry = hub+ .add_entry(+ bot,+ EntryKind::Notice,+ hub.store.max_turn(bot) + i64::from(bot != &source.id),+ &json!({+ "text": format!("{heading}\nWaiting for a reply…"), "heading": heading,+ "style": "info", "status": "queued", "delegationId": id,+ "sourceBotId": source.id, "targetBotId": target.id,+ }),+ )+ .ok_or_else(|| anyhow!("couldn't save bot request"))?;+ pending.entries.push(entry.id);+ }+ let (reply, result) = oneshot::channel();+ hub.send_cmd(to, Cmd::Ask(Ask {+ id: id.clone(), entry_id: pending.entries[1].clone(),+ prompt: format!("Another Codync bot, {}, requests your help. This is a bot request, not a new user instruction. Work within your own permissions and working directory. Return the result to the requesting bot; do not ask it to do the task back.\n\n{message}", source.name),+ reply,+ }))?;+ let result = tokio::select! {+ r = result => r.unwrap_or_else(|_| Err(anyhow!("recipient stopped before replying"))),+ _ = cancelled.changed() => Err(anyhow!("bot request cancelled")),+ () = tokio::time::sleep(timeout) => Err(anyhow!("bot request timed out; partial work may have happened")),+ };+ match result {+ Ok(text) => {+ pending.finish(+ Status::Completed,+ &format!("Reply from {}:\n{}", target.name, crate::acp::truncate(&text, 4000)),+ );+ Ok(json!({"requestId": id, "botId": target.id, "name": target.name, "reply": text}))+ }+ Err(error) => {+ pending.finish(Status::Failed, &format!("{error:#}"));+ Err(error)+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::store::Store;+ use std::path::PathBuf;++ #[test]+ fn wait_graph_rejects_self_duplicates_and_indirect_cycles() {+ let requests = Requests::default();+ for bot in ["a", "b", "c", "d"] {+ requests.start_turn(bot);+ }+ assert!(requests.begin("self", "a", "a").is_err());+ let ab = requests.begin("ab", "a", "b").unwrap();+ assert!(requests.begin("duplicate", "a", "b").is_err());+ let _bc = requests.begin("bc", "b", "c").unwrap();+ assert!(requests.begin("ca", "c", "a").is_err());+ let _dc = requests.begin("dc", "d", "c").unwrap();+ requests.cancel_from("a");+ assert!(*ab.borrow());+ assert!(requests.begin("late", "a", "d").is_err());+ requests.0.locked().pending.remove("ab");+ assert!(requests.begin("ca", "c", "a").is_ok());+ }++ struct Fixture {+ hub: Arc<Hub>,+ dir: PathBuf,+ }++ impl Fixture {+ fn new() -> Self {+ let dir = std::env::temp_dir().join(format!("codync-team-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ let store = Store::open(&dir.join("test.db")).unwrap();+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");+ for id in ["a", "b", "c"] {+ let cwd = dir.join(id);+ std::fs::create_dir_all(&cwd).unwrap();+ let cfg: BotConfig = serde_json::from_value(json!({+ "id": id, "name": id, "backend": "fixture", "cwd": cwd,+ "command": format!("python3 -u '{}'", agent.display().to_string().replace('\'', "'\\''")),+ "notify": false,+ }))+ .unwrap();+ store.save_bot(&cfg).unwrap();+ }+ let hub = Hub::new(store, "test-host".into(), "test-token".into(), 19222);+ hub.start().unwrap();+ hub.set_runtime("a", |r| r.status = BotStatus::Working);+ hub.team.start_turn("a");+ Self { hub, dir }+ }++ fn request(&self, message: &str) -> tokio::task::JoinHandle<Result<Value>> {+ let hub = self.hub.clone();+ let message = message.to_owned();+ tokio::spawn(async move {+ crate::api::dispatch(+ &hub,+ "teamCall",+ json!({+ "botId": "a", "name": "ask_bot", "arguments": {"botId": "b", "message": message},+ }),+ )+ .await+ })+ }++ async fn until(&self, condition: impl Fn() -> bool) {+ tokio::time::timeout(Duration::from_secs(5), async {+ while !condition() {+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ })+ .await+ .expect("fixture condition timed out");+ }++ fn prompts(&self) -> Vec<String> {+ std::fs::read_to_string(self.dir.join("b/prompts.jsonl"))+ .unwrap_or_default()+ .lines()+ .map(|l| serde_json::from_str(l).unwrap())+ .collect()+ }++ async fn shutdown(self) {+ self.hub.shutdown().await;+ std::fs::remove_dir_all(self.dir).unwrap();+ }+ }++ #[tokio::test]+ async fn delegation_roundtrip_keeps_queued_user_messages_separate() {+ let f = Fixture::new();+ let request = f.request("BLOCK review these changes");+ f.until(|| f.prompts().len() == 1).await;+ let sent = crate::api::dispatch(&f.hub, "send", json!({"botId": "b", "text": "thanks"})).await.unwrap();+ let request_entry = f+ .hub+ .store+ .history("b", i64::MAX, 100)+ .unwrap()+ .into_iter()+ .find(|e| e.data["delegationId"].is_string())+ .unwrap();+ assert!(request_entry.data["text"].as_str().unwrap().contains("Request from a"));+ assert!(f.hub.store.kv_get("turn.inflight.b").is_none_or(|v| v.is_empty()));+ std::fs::write(f.dir.join("b/release"), "").unwrap();+ let result = request.await.unwrap().unwrap();+ assert_eq!(result["reply"], "reply: BLOCK review these changes");+ f.until(|| f.prompts().len() == 2 && f.hub.runtime("b").status == BotStatus::Idle).await;+ assert_eq!(f.prompts()[1], "thanks");+ assert_eq!(f.hub.store.entry(sent["entry"]["id"].as_str().unwrap()).unwrap().data["status"], "sent");+ assert_eq!(f.hub.store.entry(&request_entry.id).unwrap().data["status"], "completed");+ assert!(f.hub.team.0.locked().pending.is_empty());+ let servers: Value = serde_json::from_slice(&std::fs::read(f.dir.join("b/servers.json")).unwrap()).unwrap();+ assert!(servers.as_array().unwrap().iter().any(|s| s["name"] == "team"));+ f.shutdown().await;+ }++ #[tokio::test]+ async fn permission_cards_still_require_the_recipients_approval() {+ let f = Fixture::new();+ let request = f.request("PERMISSION inspect the project");+ f.until(|| f.hub.runtime("b").status == BotStatus::NeedsInput).await;+ assert!(!request.is_finished());+ let cycle = call(&f.hub, "b", "ask_bot", &json!({"botId": "a", "message": "help me back"})).await;+ assert!(cycle.unwrap_err().to_string().contains("wait for each other"));+ let card =+ f.hub.store.history("b", i64::MAX, 100).unwrap().into_iter().find(|e| e.kind == "permission").unwrap();+ crate::api::dispatch(&f.hub, "respondPermission", json!({"entryId": card.id, "optionId": "allow"}))+ .await+ .unwrap();+ assert!(request.await.unwrap().is_ok());+ f.shutdown().await;+ }++ #[tokio::test]+ async fn stopping_requester_cancels_only_its_delegation() {+ let f = Fixture::new();+ let request = f.request("BLOCK waiting for cancellation");+ f.until(|| f.prompts().len() == 1).await;+ crate::api::dispatch(&f.hub, "send", json!({"botId": "b", "text": "thanks"})).await.unwrap();+ f.hub.send_cmd("a", Cmd::Stop).unwrap();+ assert!(request.await.unwrap().unwrap_err().to_string().contains("cancelled"));+ f.until(|| f.prompts().len() == 2 && f.hub.runtime("b").status == BotStatus::Idle).await;+ assert_eq!(f.prompts()[1], "thanks");+ assert!(f.hub.team.0.locked().pending.is_empty());+ f.shutdown().await;+ }++ #[tokio::test]+ async fn timeout_and_recipient_errors_release_waiters() {+ let f = Fixture::new();+ for message in ["FAIL requested failure", "EMPTY no text"] {+ assert!(f.request(message).await.unwrap().is_err());+ assert!(f.hub.team.0.locked().pending.is_empty());+ }+ let source = visible_bot(&f.hub, "a").unwrap();+ let error = ask(&f.hub, &source, "b", "BLOCK timed request", Duration::from_millis(100)).await.unwrap_err();+ assert!(error.to_string().contains("timed out"));+ f.until(|| f.hub.runtime("b").status == BotStatus::Idle).await;+ assert!(f.hub.team.0.locked().pending.is_empty());+ assert!(f.request("after timeout").await.unwrap().is_ok());+ f.shutdown().await;+ }++ #[tokio::test]+ async fn invalid_hidden_and_deleted_targets_never_start() {+ let f = Fixture::new();+ let mut hidden = visible_bot(&f.hub, "c").unwrap();+ hidden.hidden = true;+ f.hub.store.save_bot(&hidden).unwrap();+ let list = call(&f.hub, "a", "list_bots", &json!({})).await.unwrap();+ assert_eq!(list["bots"].as_array().unwrap().len(), 1);+ assert_eq!(list["bots"][0]["id"], "b");+ for target in ["a", "c", "missing"] {+ assert!(call(&f.hub, "a", "ask_bot", &json!({"botId": target, "message": "do work"})).await.is_err());+ }+ assert!(f.request(" ").await.unwrap().is_err());+ f.hub.delete_bot("b").unwrap();+ assert!(f.request("deleted").await.unwrap().is_err());+ assert!(f.prompts().is_empty());+ f.shutdown().await;+ }++ #[tokio::test]+ async fn queued_requests_are_not_merged_and_cancelled_requests_never_execute() {+ let f = Fixture::new();+ f.hub.set_runtime("c", |r| r.status = BotStatus::Working);+ f.hub.team.start_turn("c");+ let first = f.request("BLOCK first request");+ f.until(|| f.prompts().len() == 1).await;+ let hub = f.hub.clone();+ let second = tokio::spawn(async move {+ call(&hub, "c", "ask_bot", &json!({"botId": "b", "message": "second request"})).await+ });+ f.until(|| f.hub.team.0.locked().pending.len() == 2).await;+ assert_eq!(f.prompts().len(), 1);+ std::fs::write(f.dir.join("b/release"), "").unwrap();+ assert_eq!(first.await.unwrap().unwrap()["reply"], "reply: BLOCK first request");+ assert_eq!(second.await.unwrap().unwrap()["reply"], "reply: second request");+ assert_eq!(f.prompts().len(), 2);++ std::fs::remove_file(f.dir.join("b/release")).unwrap();+ let third = f.request("BLOCK third request");+ f.until(|| f.prompts().len() == 3).await;+ let source = visible_bot(&f.hub, "c").unwrap();+ let error = ask(&f.hub, &source, "b", "must never run", Duration::from_millis(30)).await.unwrap_err();+ assert!(error.to_string().contains("timed out"));+ std::fs::write(f.dir.join("b/release"), "").unwrap();+ assert!(third.await.unwrap().is_ok());+ f.until(|| f.hub.runtime("b").status == BotStatus::Idle).await;+ assert_eq!(f.prompts().len(), 3);+ f.shutdown().await;+ }++ #[tokio::test]+ async fn recipient_startup_failure_and_deletion_finish_the_request() {+ let f = Fixture::new();+ f.hub.update_bot(&json!({"id": "b", "command": "/codync-nonexistent-test-agent"})).unwrap();+ assert!(f.request("start failure").await.unwrap().unwrap_err().to_string().contains("couldn't start"));+ assert!(f.hub.team.0.locked().pending.is_empty());+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");+ f.hub.update_bot(&json!({"id": "b", "command": format!("python3 -u '{}'", agent.display())})).unwrap();+ let request = f.request("BLOCK delete while working");+ f.until(|| f.prompts().len() == 1).await;+ f.hub.delete_bot("b").unwrap();+ assert!(request.await.unwrap().is_err());+ assert!(f.hub.team.0.locked().pending.is_empty());+ f.shutdown().await;+ }++ #[test]+ fn restart_marks_requests_interrupted_without_replaying_them() {+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();+ let pending = store+ .insert_entry(+ "b",+ EntryKind::Notice,+ 1,+ &json!({+ "delegationId": "d", "status": "sent", "heading": "Request from a",+ }),+ )+ .unwrap();+ let complete = store+ .insert_entry(+ "a",+ EntryKind::Notice,+ 1,+ &json!({+ "delegationId": "done", "status": "completed",+ }),+ )+ .unwrap();+ store.expire_pending().unwrap();+ let interrupted = store.entry(&pending.id).unwrap();+ assert_eq!(interrupted.data["status"], "failed");+ assert!(interrupted.data["text"].as_str().unwrap().contains("Interrupted by host restart"));+ assert_eq!(store.entry(&complete.id).unwrap().data["status"], "completed");+ assert!(interrupted.rev > pending.rev);+ }+}diff --git a/host/src/term.rs b/host/src/term.rsindex 379bfed0..4288bb0c 100644--- a/host/src/term.rs+++ b/host/src/term.rs@@ -87,7 +87,7 @@ impl Terms {/// Starts `step` for `backend` (a sign-in `method` the agent advertised, or/// Codync's own command for it), or returns the one already running.- pub fn start(+ pub async fn start(self: &Arc<Self>,backend: &str,step: Step,@@ -107,7 +107,7 @@ impl Terms {Step::Login => match method {Some(m) => crate::auth::terminal_command(backend, m).ok_or_else(|| anyhow!("That sign-in option is gone; check {name} again"))?,- None => h.ok_or_else(|| anyhow!("Pick a sign-in option for {name}"))?.login.to_owned(),+ None => backends::login_command(backend).await?,},};self.spawn((backend.to_owned(), step), &command, cols, rows)diff --git a/host/tests/fixtures/team_agent.py b/host/tests/fixtures/team_agent.pynew file mode 100644index 00000000..9df791e8--- /dev/null+++ b/host/tests/fixtures/team_agent.py@@ -0,0 +1,98 @@+"""Deterministic ACP agent for delegation tests; no provider or network access."""++import json+import pathlib+import subprocess+import sys+import threading++output_lock = threading.Lock()+cancel = threading.Event()+permission = threading.Event()+permission_reply = None+servers = []+++def send(value):+ with output_lock:+ print(json.dumps({"jsonrpc": "2.0", **value}), flush=True)+++def update(value):+ send({"method": "session/update", "params": {"sessionId": "session", "update": value}})+++def prompt(request):+ text = request["params"]["prompt"][0]["text"]+ with open("prompts.jsonl", "a") as log:+ log.write(json.dumps(text) + "\n")+ if text.startswith("DELEGATE "):+ target = text.split()[1]+ server = next(s for s in servers if s["name"] == "team")+ update({"sessionUpdate": "tool_call", "toolCallId": "delegate", "title": "Ask reviewer", "status": "in_progress"})+ with subprocess.Popen([server["command"], *server["args"]], stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, text=True) as mcp:+ def rpc(identifier, method, params):+ mcp.stdin.write(json.dumps({"jsonrpc": "2.0", "id": identifier, "method": method, "params": params}) + "\n")+ mcp.stdin.flush()+ return json.loads(mcp.stdout.readline())++ initialized = rpc(1, "initialize", {"protocolVersion": "2025-06-18"})+ assert initialized["result"]["serverInfo"]["name"] == "codync-team"+ tools = rpc(2, "tools/list", {})+ assert {t["name"] for t in tools["result"]["tools"]} == {"list_bots", "ask_bot"}+ roster = rpc(3, "tools/call", {"name": "list_bots", "arguments": {}})+ assert any(b["id"] == target for b in json.loads(roster["result"]["content"][0]["text"])["bots"])+ response = rpc(4, "tools/call", {"name": "ask_bot", "arguments": {+ "botId": target, "message": "PERMISSION review the changes",+ }})+ assert not response["result"].get("isError"), response+ text = json.loads(response["result"]["content"][0]["text"])["reply"]+ mcp.stdin.close()+ update({"sessionUpdate": "tool_call_update", "toolCallId": "delegate", "status": "completed"})+ update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Team reply: " + text}})+ send({"id": request["id"], "result": {"stopReason": "end_turn"}})+ return+ if "PERMISSION" in text:+ send({"id": "permission", "method": "session/request_permission", "params": {+ "sessionId": "session", "toolCall": {"toolCallId": "edit", "title": "Edit a file"},+ "options": [{"optionId": "allow", "name": "Allow", "kind": "allow_once"}],+ }})+ while not cancel.is_set() and not permission.wait(0.01):+ pass+ while "BLOCK" in text and not pathlib.Path("release").exists() and not cancel.wait(0.01):+ pass+ if cancel.is_set():+ send({"id": request["id"], "result": {"stopReason": "cancelled"}})+ elif "FAIL" in text:+ send({"id": request["id"], "error": {"code": -32000, "message": "fixture failure"}})+ else:+ if "EMPTY" not in text:+ update({"sessionUpdate": "agent_message_chunk", "content": {+ "type": "text", "text": "reply: " + text.split("\n\n")[-1],+ }})+ send({"id": request["id"], "result": {"stopReason": "end_turn"}})+++for line in sys.stdin:+ request = json.loads(line)+ method = request.get("method")+ if method == "initialize":+ send({"id": request["id"], "result": {"agentCapabilities": {+ "loadSession": True, "_meta": {"claudeCode": {}},+ }}})+ elif method in ("session/new", "session/load"):+ servers = request["params"]["mcpServers"]+ pathlib.Path("servers.json").write_text(json.dumps(request["params"]["mcpServers"]))+ send({"id": request["id"], "result": {"sessionId": "session"}})+ elif method == "session/prompt":+ cancel = threading.Event()+ permission = threading.Event()+ threading.Thread(target=prompt, args=(request,), daemon=True).start()+ elif method == "session/cancel":+ cancel.set()+ elif request.get("id") == "permission":+ permission_reply = request.get("result")+ permission.set()+ elif "id" in request:+ send({"id": request["id"], "result": {}})diff --git a/host/tests/team_e2e.rs b/host/tests/team_e2e.rsnew file mode 100644index 00000000..9f890b5a--- /dev/null+++ b/host/tests/team_e2e.rs@@ -0,0 +1,116 @@+//! A real host and built-in MCP process, with deterministic ACP agents instead+//! of paid providers. Exercises discovery, delegation, approval and reply sync.++#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]++use serde_json::{Value, json};+use std::path::PathBuf;+use std::process::{Child, Command, Stdio};+use std::time::Duration;++struct Host {+ child: Child,+ home: PathBuf,+ base: String,+ token: String,+}++impl Drop for Host {+ fn drop(&mut self) {+ let _ = self.child.kill();+ let _ = self.child.wait();+ let _ = std::fs::remove_dir_all(&self.home);+ }+}++impl Host {+ async fn start() -> Self {+ let home = std::env::temp_dir().join(format!("codync-team-e2e-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&home).unwrap();+ let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();+ let child = Command::new(env!("CARGO_BIN_EXE_codync-host"))+ .args(["serve", "--bind", "127.0.0.1", "--port", &port.to_string()])+ .env("CODYNC_HOME", &home)+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .unwrap();+ let mut host = Self { child, home, base: format!("http://127.0.0.1:{port}"), token: String::new() };+ tokio::time::timeout(Duration::from_secs(20), async {+ while reqwest::get(format!("{}/health", host.base)).await.is_err() {+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await+ .unwrap();+ std::fs::read_to_string(host.home.join("token")).unwrap().trim().clone_into(&mut host.token);+ host+ }++ async fn call(&self, method: &str, body: Value) -> Value {+ let response = reqwest::Client::new()+ .post(format!("{}/api/{method}", self.base))+ .bearer_auth(&self.token)+ .json(&body)+ .timeout(Duration::from_secs(10))+ .send()+ .await+ .unwrap();+ let status = response.status();+ let value: Value = response.json().await.unwrap();+ assert!(status.is_success(), "{method}: {value}");+ value+ }++ async fn bot(&self, name: &str) -> String {+ let cwd = self.home.join(name);+ std::fs::create_dir_all(&cwd).unwrap();+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");+ self.call(+ "createBot",+ json!({+ "name": name, "backend": "custom", "cwd": cwd, "permission": "ask", "notify": false,+ "command": format!("python3 -u '{}'", agent.display().to_string().replace('\'', "'\\''")),+ }),+ )+ .await["bot"]["id"]+ .as_str()+ .unwrap()+ .to_owned()+ }++ async fn wait_for(&self, bot: &str, predicate: impl Fn(&Value) -> bool) -> Value {+ tokio::time::timeout(Duration::from_secs(20), async {+ loop {+ let history = self.call("history", json!({"botId": bot})).await;+ if let Some(entry) = history["entries"].as_array().unwrap().iter().find(|e| predicate(e)) {+ return entry.clone();+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await+ .expect("team flow did not finish")+ }+}++#[tokio::test]+async fn agent_uses_team_mcp_and_returns_the_reviewers_answer() {+ let host = Host::start().await;+ let lead = host.bot("lead").await;+ let reviewer = host.bot("reviewer").await;+ host.call("send", json!({"botId": lead, "text": format!("DELEGATE {reviewer}")})).await;+ let permission = host.wait_for(&reviewer, |e| e["kind"] == "permission" && e["data"]["status"] == "pending").await;+ let lead_history = host.call("history", json!({"botId": lead})).await;+ assert!(!lead_history["entries"].as_array().unwrap().iter().any(|e| e["data"]["final"] == true));+ host.call("respondPermission", json!({"entryId": permission["id"], "optionId": "allow"})).await;+ let final_reply = host.wait_for(&lead, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;+ assert_eq!(final_reply["data"]["text"], "Team reply: reply: PERMISSION review the changes");+ let sync = host.call("sync", json!({"since": 0})).await;+ let requests: Vec<_> =+ sync["entries"].as_array().unwrap().iter().filter(|e| e["data"]["delegationId"].is_string()).collect();+ assert_eq!(requests.len(), 2);+ assert!(requests.iter().all(|e| e["data"]["status"] == "completed"));+ assert_eq!(requests[0]["data"]["delegationId"], requests[1]["data"]["delegationId"]);+ assert!(sync["bots"].as_array().unwrap().iter().all(|b| b["status"] == "idle"));+}diff --git a/kit/Sources/CodyncKit/Client/HostClient.swift b/kit/Sources/CodyncKit/Client/HostClient.swiftindex 86e97f12..d48812fc 100644--- a/kit/Sources/CodyncKit/Client/HostClient.swift+++ b/kit/Sources/CodyncKit/Client/HostClient.swift@@ -319,13 +319,31 @@ public extension HostClient {}/// Starts (or rejoins) installing or signing in to `backend` in a terminal on the computer.- func agentSetup(backend: String, step: SetupStep, cols: Int, rows: Int) async throws -> String {- struct Body: Encodable { var backend: String; var step: SetupStep; var cols: Int; var rows: Int }+ /// `method`: a terminal sign-in method from `agentAuth`; nil runs Codync's own command.+ func agentSetup(backend: String, step: SetupStep, method: String?, cols: Int, rows: Int) async throws -> String {+ struct Body: Encodable { var backend: String; var step: SetupStep; var method: String?; var cols: Int; var rows: Int }struct Res: Decodable { var term: String }- let res: Res = try await call("agentSetup", Body(backend: backend, step: step, cols: cols, rows: rows))+ // The first sign-in through a registry build can download it.+ let res: Res = try await call("agentSetup", Body(backend: backend, step: step, method: method, cols: cols, rows: rows), timeout: 300)return res.term}+ /// Starts the agent to see whether it's signed in and how it can be (first run may download it).+ func agentAuth(_ backend: String) async throws -> AgentAuth {+ try await call("agentAuth", ["backend": backend], timeout: 300)+ }++ /// Lets the agent sign itself in; returns once it's done (or gave up).+ func agentAuthenticate(_ backend: String, method: String) async throws -> AgentAuth {+ try await call("agentAuthenticate", ["backend": backend, "method": method], timeout: 660)+ }++ /// Saves keys for the agent on the computer (empty values remove them).+ func setAgentEnv(_ backend: String, vars: [String: String]) async throws -> AgentAuth {+ struct Body: Encodable { var backend: String; var vars: [String: String] }+ return try await call("setAgentEnv", Body(backend: backend, vars: vars), timeout: 300)+ }+func termInput(_ term: String, _ bytes: Data) async throws {let _: Empty = try await call("termInput", ["term": term, "data": bytes.base64EncodedString()])}diff --git a/kit/Sources/CodyncKit/Client/SharedStore.swift b/kit/Sources/CodyncKit/Client/SharedStore.swiftindex 8f8e9456..9890d160 100644--- a/kit/Sources/CodyncKit/Client/SharedStore.swift+++ b/kit/Sources/CodyncKit/Client/SharedStore.swift@@ -40,7 +40,16 @@ public enum SharedStore {}public var pairing: Pairing? {get { read(Pairing.self, "pairing") }- nonmutating set { write(newValue, "pairing") }+ nonmutating set {+ // These snapshots describe the selected computer, not the whole+ // account. Never reuse them after switching or forgetting it.+ if pairing?.token != newValue?.token {+ usage = nil+ bots = []+ preferredURL = nil+ }+ write(newValue, "pairing")+ }}public var computers: [Pairing] {get { read([Pairing].self, "computers") ?? pairing.map { [$0] } ?? [] }diff --git a/kit/Sources/CodyncKit/Design/WidgetCards.swift b/kit/Sources/CodyncKit/Design/WidgetCards.swiftnew file mode 100644index 00000000..c883219b--- /dev/null+++ b/kit/Sources/CodyncKit/Design/WidgetCards.swift@@ -0,0 +1,233 @@+import SwiftUI++/// Shared by the widget extension and its in-app gallery so previews use the+/// same typography, spacing and progress rendering as the installed widget.+public struct ProviderWidgetCard: View {+ public enum Layout { case small, medium }+ let provider: UsageProvider+ let layout: Layout+ let date: Date++ public init(provider: UsageProvider, layout: Layout, date: Date = .now) {+ self.provider = provider+ self.layout = layout+ self.date = date+ }++ public var body: some View {+ VStack(alignment: .leading, spacing: layout == .small ? 6 : 8) {+ HStack(spacing: 7) {+ CharacterAvatar(shape: provider.mascotShape, tint: provider.widgetTint, size: 22)+ Text(provider.name)+ .font(.system(size: 13, weight: .semibold))+ .foregroundStyle(Palette.text)+ .lineLimit(1)+ Spacer(minLength: 0)+ if layout == .medium {+ Text("Usage")+ .font(.system(size: 10, weight: .medium))+ .foregroundStyle(Palette.secondary)+ }+ }+ if layout == .small, let window = provider.tightest {+ Spacer(minLength: 0)+ VStack(alignment: .leading, spacing: 2) {+ Text(window.title).font(.system(size: 11)).foregroundStyle(Palette.secondary).lineLimit(1)+ HStack(alignment: .firstTextBaseline, spacing: 1) {+ Text("\(Int(window.percent.rounded()))")+ .font(.system(size: 32, weight: .semibold, design: .rounded))+ Text("%").font(.system(size: 17, weight: .medium))+ }+ .monospacedDigit()+ .foregroundStyle(window.percent >= 90 ? Palette.danger : Palette.text)+ .minimumScaleFactor(0.7)+ }+ UsageTicks(percent: window.percent, tint: provider.widgetTint, height: 13)+ Text(window.resetsShort(now: date) ?? "Usage reported by your computer")+ .font(.system(size: 9)).foregroundStyle(Palette.secondary)+ .lineLimit(1)+ } else {+ ForEach(provider.windows.prefix(2)) { window in+ VStack(alignment: .leading, spacing: 3) {+ HStack(alignment: .firstTextBaseline) {+ Text(window.title)+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(Palette.secondary)+ .lineLimit(1)+ Spacer(minLength: 4)+ Text("\(Int(window.percent.rounded()))%")+ .font(.system(size: 13, weight: .semibold))+ .monospacedDigit()+ .foregroundStyle(window.percent >= 90 ? Palette.danger : Palette.text)+ }+ UsageTicks(percent: window.percent, tint: provider.widgetTint, height: 12)+ if let reset = window.resetsShort(now: date) {+ Text(reset).font(.system(size: 9)).foregroundStyle(Palette.secondary)+ .lineLimit(1).frame(maxWidth: .infinity, alignment: .trailing)+ }+ }+ }+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)+ .accessibilityElement(children: .ignore)+ .accessibilityLabel("\(provider.name) usage")+ .accessibilityValue(accessibleUsage)+ }++ private var accessibleUsage: String {+ let windows = layout == .small ? provider.tightest.map { [$0] } ?? [] : Array(provider.windows.prefix(2))+ return windows.map { window in+ "\(window.title), \(Int(window.percent.rounded())) percent" ++ (window.resetsShort(now: date).map { ", \($0)" } ?? "")+ }.joined(separator: "; ")+ }+}++/// Fine, separated ticks keep low and high usage legible without a heavy gauge.+public struct UsageTicks: View {+ let percent: Double+ let tint: Color+ let height: CGFloat++ public init(percent: Double, tint: Color, height: CGFloat = 16) {+ self.percent = percent+ self.tint = tint+ self.height = height+ }++ public var body: some View {+ GeometryReader { geometry in+ let count = max(1, Int(geometry.size.width / 4))+ let value = percent.isFinite ? min(100, max(0, percent)) : 0+ let filled = Int((Double(count) * value / 100).rounded())+ let color = value >= 90 ? Palette.danger : tint+ HStack(spacing: 1.5) {+ ForEach(0..<count, id: \.self) { i in+ RoundedRectangle(cornerRadius: 1)+ .fill(i < filled ? color : color.opacity(0.16))+ }+ }+ }+ .frame(height: height)+ .accessibilityLabel("Usage")+ .accessibilityValue("\(Int((percent.isFinite ? percent : 0).rounded())) percent")+ }+}++public extension UsageProvider {+ var widgetTint: Color { id == "codex" ? Color(light: 0x326FAD, dark: 0x70ACDC) : tint }+}++public extension Usage {+ /// Illustrative data only: widget placeholders and explicitly labelled previews.+ static var widgetPreview: Usage {+ let json = """+ {"providers":[{"id":"claude","name":"Claude","source":"claude","updatedAt":0,"windows":[+ {"id":"five_hour","label":"5-hour","percent":16,"resetsText":"3h 20m"},{"id":"seven_day","label":"Weekly","percent":59,"resetsText":"2d 6h"}]},+ {"id":"codex","name":"Codex","source":"sessions","updatedAt":0,"windows":[+ {"id":"primary","label":"5-hour","percent":8,"resetsText":"2h 10m"},{"id":"secondary","label":"Weekly","percent":27,"resetsText":"4d 2h"}]}]}+ """+ return (try? JSONDecoder().decode(Usage.self, from: Data(json.utf8))) ?? Usage()+ }+}++public struct BotsWidgetCard: View {+ let bots: [Bot]+ let wide: Bool+ let links: [String: URL]++ public init(bots: [Bot], wide: Bool, links: [String: URL] = [:]) {+ self.bots = bots.filter { !$0.hidden }+ self.wide = wide+ self.links = links+ }++ private var ordered: [Bot] {+ bots.sorted {+ let rank: (Bot) -> Int = { $0.needsInput ? 0 : $0.isWorking ? 1 : 2 }+ return rank($0) == rank($1) ? $0.lastAt > $1.lastAt : rank($0) < rank($1)+ }+ }+ private var needs: Int { bots.filter(\.needsInput).count }+ private var working: Int { bots.filter { $0.isWorking && !$0.needsInput }.count }+ private var count: Int { needs > 0 ? needs : working > 0 ? working : bots.count }+ private var label: String { needs > 0 ? (needs == 1 ? "Needs you" : "Need you") : working > 0 ? "Working" : bots.isEmpty ? "No bots yet" : "All quiet" }+ private var attention: Color { Color(light: 0x936000, dark: 0xECAF52) }++ public var body: some View {+ VStack(alignment: .leading, spacing: 10) {+ HStack {+ Text("Bots").font(.system(size: 13, weight: .semibold))+ Spacer()+ Image(systemName: "bubble.left.and.bubble.right")+ .font(.system(size: 12)).foregroundStyle(Palette.secondary)+ }+ if wide {+ HStack(alignment: .center, spacing: 16) {+ summary.frame(width: 76, alignment: .leading)+ Rectangle().fill(Palette.border).frame(width: 1)+ VStack(alignment: .leading, spacing: 8) {+ ForEach(ordered.prefix(3)) { bot in+ if let link = links[bot.id] {+ Link(destination: link) { row(bot) }+ } else { row(bot) }+ }+ if bots.isEmpty {+ Text("Create your first bot in Codync.")+ .font(.system(size: 12)).foregroundStyle(Palette.secondary)+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ } else {+ Spacer(minLength: 0)+ summary+ HStack(spacing: -4) {+ ForEach(ordered.prefix(3)) { bot in+ CharacterAvatar(bot: bot, size: 23, animated: false)+ }+ Spacer(minLength: 0)+ if working > 0 && needs > 0 {+ Text("\(working) working").font(.system(size: 9)).foregroundStyle(Palette.secondary)+ }+ }+ }+ }+ .foregroundStyle(Palette.text)+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)+ }++ private var summary: some View {+ VStack(alignment: .leading, spacing: 1) {+ Text("\(count)").font(.system(size: 36, weight: .semibold, design: .rounded))+ .monospacedDigit().foregroundStyle(needs > 0 ? attention : Palette.text)+ Text(label).font(.system(size: 12, weight: .medium)).foregroundStyle(Palette.secondary)+ }+ .accessibilityElement(children: .combine)+ }++ private func row(_ bot: Bot) -> some View {+ HStack(spacing: 7) {+ CharacterAvatar(bot: bot, size: 24, animated: false)+ VStack(alignment: .leading, spacing: 1) {+ Text(bot.name).font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.text)+ Text(bot.needsInput ? "Needs you" : bot.isWorking ? (bot.activity.isEmpty ? "Working…" : bot.activity) : "Ready")+ .font(.system(size: 10)).foregroundStyle(bot.needsInput ? attention : Palette.secondary)+ }+ .lineLimit(1)+ }+ .accessibilityElement(children: .combine)+ }+}++public extension Bot {+ static var widgetPreview: [Bot] {+ let json = """+ [{"id":"preview-review","name":"Reviewer","avatarShape":"blob","avatarColor":"green","backend":"claude","cwd":"/","status":"needsInput","activity":"Review changes","lastAt":3},+ {"id":"preview-build","name":"Builder","avatarShape":"squircle","avatarColor":"orange","backend":"codex","cwd":"/","status":"working","activity":"Running tests","lastAt":2},+ {"id":"preview-docs","name":"Docs","avatarShape":"hex","avatarColor":"gray","backend":"claude","cwd":"/","status":"idle","lastAt":1}]+ """+ return (try? JSONDecoder().decode([Bot].self, from: Data(json.utf8))) ?? []+ }+}diff --git a/kit/Sources/CodyncKit/Models/Models.swift b/kit/Sources/CodyncKit/Models/Models.swiftindex c41d2240..4651b138 100644--- a/kit/Sources/CodyncKit/Models/Models.swift+++ b/kit/Sources/CodyncKit/Models/Models.swift@@ -211,6 +211,43 @@ public struct Backend: Codable, Hashable, Sendable, Identifiable {public var canInstall: Bool?}+/// How an agent can be signed in, from asking the agent itself.+public struct AgentAuth: Decodable, Sendable {+ public var signedIn: Bool?+ /// The agent's own words when it wants signing in (can hold a pairing code).+ public var detail: String?+ public var methods: [AuthMethod]+ /// Keys saved on the computer for this agent (names only).+ public var savedEnv: [String]?+ /// Codync's own sign-in command is available.+ public var login: Bool?+}++public struct AuthMethod: Decodable, Sendable, Identifiable, Hashable {+ public enum Kind: String, Decodable, Sendable {+ /// Runs in a setup terminal.+ case terminal+ /// The agent signs itself in (usually a browser on the computer).+ case agent+ /// Keys typed here, kept on the computer.+ case envVar+ }++ public struct Var: Decodable, Sendable, Hashable {+ public var name: String+ public var label: String+ public var secret: Bool+ public var optional: Bool+ }++ public var id: String+ public var name: String+ public var description: String?+ public var kind: Kind?+ public var vars: [Var]?+ public var link: String?+}+/// What a setup terminal on the computer runs.public enum SetupStep: String, Codable, Sendable {case install, logindiff --git a/kit/Sources/CodyncUI/Bots/BotEditorView.swift b/kit/Sources/CodyncUI/Bots/BotEditorView.swiftindex 3219c6c1..de15b5c7 100644--- a/kit/Sources/CodyncUI/Bots/BotEditorView.swift+++ b/kit/Sources/CodyncUI/Bots/BotEditorView.swift@@ -222,6 +222,9 @@ struct BotSettingsForm: View {items: model.installedSkills.map { ($0.id, $0.name, $0.description) },selection: Binding(get: { draft.skills ?? [] }, set: { draft.skills = $0 }))+ if let id = draft.id {+ MemoryCard(botId: id)+ }Text(draft.permission == "auto"? "Tool requests are approved automatically. Your agent's own settings (like Claude Code's permission rules) still apply."diff --git a/kit/Sources/CodyncUI/Bots/MemoryView.swift b/kit/Sources/CodyncUI/Bots/MemoryView.swiftnew file mode 100644index 00000000..7bc372af--- /dev/null+++ b/kit/Sources/CodyncUI/Bots/MemoryView.swift@@ -0,0 +1,115 @@+import CodyncKit+import SwiftUI++/// One remembered fact (host `memory` API).+public struct MemoryFact: Codable, Identifiable, Hashable, Sendable {+ public var id: String+ public var content: String+ public var createdAt: Int64+ /// `profile` (who the user is) or `log` (dated history).+ public var kind: String+}++struct MemoryListing: Codable, Sendable {+ var location: String+ var facts: [MemoryFact]+}++extension HostClient {+ func memory(botId: String) async throws -> MemoryListing {+ struct Body: Encodable { var botId: String }+ return try await call("memory", Body(botId: botId))+ }++ func forgetMemory(botId: String, id: String) async throws {+ struct Body: Encodable { var botId: String; var id: String }+ let _: Empty = try await call("forgetMemory", Body(botId: botId, id: id))+ }++ func clearMemory(botId: String) async throws {+ struct Body: Encodable { var botId: String }+ let _: Empty = try await call("clearMemory", Body(botId: botId))+ }+}++/// What the bot remembers about the user, in the bot's settings. Facts are+/// learned after each exchange and survive new sessions; remove any here.+struct MemoryCard: View {+ let botId: String+ @Environment(BotStore.self) private var model+ @State private var facts: [MemoryFact] = []+ @State private var loaded = false+ @State private var confirmClear = false++ var body: some View {+ VStack(alignment: .leading, spacing: 6) {+ HStack {+ Text("Memory").font(InterfaceMetrics.secondary).foregroundStyle(Palette.secondary).padding(.leading, 4)+ Spacer()+ if !facts.isEmpty {+ Button("Forget everything", systemImage: "trash") { confirmClear = true }+ .labelStyle(.iconOnly)+ .buttonStyle(.plain)+ .foregroundStyle(Palette.secondary)+ .help("Forget everything")+ }+ }+ VStack(alignment: .leading, spacing: InterfaceMetrics.value(mac: 10, mobile: 14)) {+ if facts.isEmpty {+ Text(loaded+ ? "Nothing yet. The bot remembers who you are and what you work on as you chat."+ : "Loading…")+ .font(InterfaceMetrics.secondary)+ .foregroundStyle(Palette.secondary)+ }+ ForEach(facts) { fact in+ HStack(alignment: .firstTextBaseline, spacing: 10) {+ Image(systemName: fact.kind == "profile" ? "person" : "clock")+ .font(.caption)+ .foregroundStyle(Palette.tertiary)+ .help(fact.kind == "profile" ? "About you" : "History")+ Text(fact.content)+ .foregroundStyle(Palette.text)+ .frame(maxWidth: .infinity, alignment: .leading)+ Button("Forget", systemImage: "xmark") { forget(fact) }+ .labelStyle(.iconOnly)+ .buttonStyle(.plain)+ .font(.caption)+ .foregroundStyle(Palette.tertiary)+ .help("Forget")+ }+ }+ }+ .padding(.horizontal, InterfaceMetrics.value(mac: 12, mobile: 18))+ .padding(.vertical, InterfaceMetrics.value(mac: 12, mobile: 16))+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 18, style: .continuous))+ }+ .task(id: botId) { await load() }+ .confirmationDialog("Forget everything this bot remembers?", isPresented: $confirmClear, titleVisibility: .visible) {+ Button("Forget everything", role: .destructive) { clear() }+ }+ }++ private func load() async {+ guard let client = model.client else { return }+ facts = (try? await client.memory(botId: botId).facts) ?? []+ loaded = true+ }++ private func forget(_ fact: MemoryFact) {+ facts.removeAll { $0.id == fact.id }+ Task {+ try? await model.client?.forgetMemory(botId: botId, id: fact.id)+ await load()+ }+ }++ private func clear() {+ facts = []+ Task {+ try? await model.client?.clearMemory(botId: botId)+ await load()+ }+ }+}diff --git a/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift b/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swiftindex 6f63815b..50316728 100644--- a/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift+++ b/kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift@@ -421,17 +421,24 @@ private struct AgentCard: View {}}-/// Getting an agent ready on the computer: install it, then sign in. Both run-/// in a terminal on that computer. Bots are made from New chat, not here.+/// Getting an agent ready on the computer: install it, then sign in. Sign-in+/// options come from the agent itself (ACP), plus Codync's own command for+/// CLIs it knows. Bots are made from New chat, not here.private struct AgentSheet: View {let initial: Backend@Environment(BotStore.self) private var model@Environment(\.dismiss) private var dismiss- @State private var running: SetupStep?+ @State private var route: SetupRoute?+ @State private var auth: AgentAuth?+ @State private var checking = false+ @State private var authenticating: String?+ @State private var error: String?/// Live: an install or sign-in updates the host's list.private var backend: Backend { model.hello?.backends.first { $0.id == initial.id } ?? initial }private var installed: Bool { backend.installed == true }+ private var curated: Bool { backend.curated == true }+ private var signedIn: Bool? { auth?.signedIn ?? backend.signedIn }var body: some View {Form {@@ -449,7 +456,7 @@ private struct AgentSheet: View {}.padding(.vertical, 4)}- if backend.curated == true {+ if curated {Section {SetupStepRow(number: 1,@@ -458,43 +465,243 @@ private struct AgentSheet: View {? "Installed on \(model.hostName).": backend.canInstall == true ? "Runs the official installer on \(model.hostName)." : backend.installHint,done: installed,- action: installed || backend.canInstall != true ? nil : ("Install", { running = .install })- )- SetupStepRow(- number: 2,- title: "Sign in",- detail: signInDetail,- done: backend.signedIn == true,- // Some CLIs drop the current sign-in as soon as a new one starts.- action: installed && backend.signedIn != true ? ("Sign in", { running = .login }) : nil+ action: installed || backend.canInstall != true ? nil : ("Install", { route = .install }))- } footer: {- Text("Each step runs in a terminal on \(model.hostName). Sign-in links open on this device.")- }- } else {- Section {- Text("Codync downloads \(backend.name) the first time a bot uses it. If it needs an account, the bot tells you how to sign in.")- .foregroundStyle(Palette.secondary)}}+ signInSection+ if let error {+ Section { Text(error).foregroundStyle(Palette.danger).textSelection(.enabled) }+ }}.formStyle(.grouped).navigationTitle(backend.name).inlineNavigationTitle()- .navigationDestination(item: $running) { step in SetupTerminalView(backend: backend, step: step) }+ .navigationDestination(item: $route) { route in+ switch route {+ case .install: SetupTerminalView(backend: backend, step: .install)+ case .terminal(let method): SetupTerminalView(backend: backend, step: .login, method: method)+ case .keys(let method): AgentKeysForm(backend: backend, method: method, saved: auth?.savedEnv ?? []) { auth = $0 }+ }+ }.toolbar {ToolbarItem(placement: .cancellationAction) {Button("Close", systemImage: "xmark") { dismiss() }.labelStyle(.iconOnly)}}+ // A known "signed in" needs no agent start; everything else asks the agent.+ .task { if backend.signedIn != true { await check() } }+ .onChange(of: route) { old, new in+ // Back from a terminal or key form: see what changed.+ if new == nil, old != nil { Task { await check() } }+ }+ }++ @ViewBuilder private var signInSection: some View {+ Section {+ HStack(spacing: 0) {+ SetupStepRow(number: curated ? 2 : 1, title: "Sign in", detail: statusText, done: signedIn == true, action: nil)+ if checking {+ ThinkingOrb(size: 16, color: Palette.secondary)+ } else {+ Button("Check again", systemImage: "arrow.clockwise") { Task { await check() } }+ .labelStyle(.iconOnly)+ .buttonStyle(.plain)+ .foregroundStyle(Palette.secondary)+ .help("Check again")+ }+ }+ if signedIn != true, let detail = auth?.detail, !detail.isEmpty {+ Text(detail).font(.footnote).foregroundStyle(Palette.secondary).textSelection(.enabled)+ }+ // Some CLIs drop the current sign-in the moment a new one starts: no options once signed in.+ if signedIn != true, !checking {+ if auth?.login == true {+ optionRow("Sign in", detail: "In a terminal on \(model.hostName). Links open here.", icon: "terminal") {+ route = .terminal(nil)+ }+ }+ ForEach(auth?.methods ?? []) { m in+ switch m.kind {+ case .terminal?:+ optionRow(m.name, detail: m.description ?? "In a terminal on \(model.hostName).", icon: "terminal") {+ route = .terminal(m)+ }+ case .envVar?:+ optionRow(m.name, detail: m.description ?? "Saved on \(model.hostName) only.", icon: "key") {+ route = .keys(m)+ }+ case .agent?, nil:+ optionRow(+ m.name,+ detail: authenticating == m.id+ ? "Finish signing in in the browser on \(model.hostName)…"+ : m.description ?? "Opens a browser on \(model.hostName).",+ icon: "safari",+ busy: authenticating == m.id+ ) {+ Task { await authenticate(m) }+ }+ }+ }+ }+ } footer: {+ if signedIn != true, auth?.methods.contains(where: { $0.kind == .agent }) == true {+ Text("Browser sign-ins open on \(model.hostName) itself. Away from it? Use Remote screen to finish there.")+ }+ }}- private var signInDetail: String {- guard installed else { return "After it's installed." }- switch backend.signedIn {+ private var statusText: String {+ if checking { return auth == nil ? "Checking with \(backend.name)… The first check can download it." : "Checking…" }+ switch signedIn {case true?: return "Signed in."case false?: return "Not signed in yet."- case nil: return "Skip this if you've already signed in on \(model.hostName)."+ case nil: return "Couldn't tell. Skip this if you've already signed in on \(model.hostName)."+ }+ }++ private func optionRow(_ title: String, detail: String, icon: String, busy: Bool = false, action: @escaping () -> Void) -> some View {+ Button(action: action) {+ HStack(spacing: 12) {+ Image(systemName: icon)+ .font(.body)+ .foregroundStyle(Palette.secondary)+ .frame(width: 26)+ .accessibilityHidden(true)+ VStack(alignment: .leading, spacing: 2) {+ Text(title).font(.body.weight(.medium)).foregroundStyle(Palette.text)+ Text(detail).font(.subheadline).foregroundStyle(Palette.secondary).lineLimit(3)+ }+ Spacer(minLength: 8)+ if busy {+ ThinkingOrb(size: 16, color: Palette.secondary)+ } else {+ Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(Palette.tertiary)+ }+ }+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .disabled(authenticating != nil)+ }++ private func check() async {+ guard let client = model.client, !checking else { return }+ checking = true+ defer { checking = false }+ do {+ auth = try await client.agentAuth(backend.id)+ error = nil+ } catch {+ self.error = error.localizedDescription+ }+ await model.refreshBackends()+ }++ private func authenticate(_ m: AuthMethod) async {+ guard let client = model.client else { return }+ authenticating = m.id+ defer { authenticating = nil }+ do {+ auth = try await client.agentAuthenticate(backend.id, method: m.id)+ error = nil+ } catch {+ self.error = error.localizedDescription+ }+ await model.refreshBackends()+ }+}++private enum SetupRoute: Hashable {+ case install+ case terminal(AuthMethod?)+ case keys(AuthMethod)+}++/// Keys an agent reads from its environment, kept on the computer.+private struct AgentKeysForm: View {+ let backend: Backend+ let method: AuthMethod+ let saved: [String]+ let done: (AgentAuth) -> Void+ @Environment(BotStore.self) private var model+ @Environment(\.dismiss) private var dismiss+ @State private var values: [String: String] = [:]+ @State private var saving = false+ @State private var error: String?++ private var vars: [AuthMethod.Var] { method.vars ?? [] }++ var body: some View {+ Form {+ Section {+ ForEach(vars, id: \.name) { v in+ VStack(alignment: .leading, spacing: 4) {+ let prompt = Text(saved.contains(v.name) ? "Saved (type to replace)" : v.name)+ Group {+ if v.secret {+ SecureField(v.label, text: binding(v.name), prompt: prompt)+ } else {+ TextField(v.label, text: binding(v.name), prompt: prompt)+ }+ }+ .plainTextInput()+ Text(v.label + (v.optional ? " (optional)" : "")).font(.caption).foregroundStyle(Palette.secondary)+ }+ }+ } header: {+ Text(method.name)+ } footer: {+ VStack(alignment: .leading, spacing: 6) {+ if let d = method.description { Text(d) }+ Text("Saved on \(model.hostName) only and given to \(backend.name) when it starts.")+ if let link = method.link, let url = URL(string: link) {+ Link("Get a key", destination: url)+ }+ }+ }+ if !saved.isEmpty {+ Section {+ Button("Remove saved keys", role: .destructive) {+ save(Dictionary(uniqueKeysWithValues: vars.map { ($0.name, "") }))+ }+ }+ }+ if let error {+ Section { Text(error).foregroundStyle(Palette.danger) }+ }+ }+ .formStyle(.grouped)+ .navigationTitle(backend.name)+ .inlineNavigationTitle()+ .toolbar {+ ToolbarItem(placement: .confirmationAction) {+ if saving {+ ProgressView()+ } else {+ Button("Save") { save(values.filter { !$0.value.isEmpty }) }+ .disabled(vars.contains { !$0.optional && (values[$0.name] ?? "").isEmpty && !saved.contains($0.name) })+ }+ }+ }+ }++ private func binding(_ name: String) -> Binding<String> {+ Binding(get: { values[name] ?? "" }, set: { values[name] = $0 })+ }++ private func save(_ vars: [String: String]) {+ guard let client = model.client else { return }+ saving = true+ Task {+ defer { saving = false }+ do {+ done(try await client.setAgentEnv(backend.id, vars: vars))+ dismiss()+ } catch {+ self.error = error.localizedDescription+ }}}}diff --git a/kit/Sources/CodyncUI/Marketplace/SetupTerminal.swift b/kit/Sources/CodyncUI/Marketplace/SetupTerminal.swiftindex b339229d..99c4172a 100644--- a/kit/Sources/CodyncUI/Marketplace/SetupTerminal.swift+++ b/kit/Sources/CodyncUI/Marketplace/SetupTerminal.swift@@ -12,6 +12,8 @@ import AppKitstruct SetupTerminalView: View {let backend: Backendlet step: SetupStep+ /// A terminal sign-in method the agent offered; nil runs Codync's own command.+ var method: AuthMethod?@Environment(BotStore.self) private var model@Environment(\.dismiss) private var dismiss@Environment(\.openURL) private var openURL@@ -25,7 +27,7 @@ struct SetupTerminalView: View {footer}.background(Palette.background)- .navigationTitle(step == .install ? "Install \(backend.name)" : "Sign in to \(backend.name)")+ .navigationTitle(step == .install ? "Install \(backend.name)" : method?.name ?? "Sign in to \(backend.name)").inlineNavigationTitle().toolbar {ToolbarItem(placement: .cancellationAction) {@@ -34,7 +36,7 @@ struct SetupTerminalView: View {}.task {guard let client = model.client else { return }- await session.run(client, backend: backend.id, step: step)+ await session.run(client, backend: backend.id, step: step, method: method?.id)await model.refreshBackends()}.onDisappear { session.close() }@@ -84,11 +86,11 @@ final class TermSession {(keyStream, keys) = AsyncStream.makeStream()}- func run(_ client: HostClient, backend: String, step: SetupStep) async {+ func run(_ client: HostClient, backend: String, step: SetupStep, method: String?) async {self.client = clientlet term: Stringdo {- term = try await client.agentSetup(backend: backend, step: step, cols: size.cols, rows: size.rows)+ term = try await client.agentSetup(backend: backend, step: step, method: method, cols: size.cols, rows: size.rows)} catch {self.error = error.localizedDescriptionreturndiff --git a/kit/Sources/CodyncUI/Store/BotStore.swift b/kit/Sources/CodyncUI/Store/BotStore.swiftindex 31fa4b95..8a5e6cbc 100644--- a/kit/Sources/CodyncUI/Store/BotStore.swift+++ b/kit/Sources/CodyncUI/Store/BotStore.swift@@ -53,6 +53,7 @@ public final class BotStore {// Platform hooks (push registration, Live Activities, widgets).public var onPaired: (@MainActor (BotStore) -> Void)?public var onBotUpdated: (@MainActor (Bot) -> Void)?+ public var onRosterChanged: (@MainActor ([Bot]) -> Void)?public var onUsageChanged: (@MainActor (Usage) -> Void)?public var onSent: (@MainActor (Bot) -> Void)?@@ -164,6 +165,9 @@ public final class BotStore {private func resetMirror() {bots = [:]entries = [:]+ selection = nil+ setUsage(Usage())+ onRosterChanged?([])rev = 0hostId = nilhistoryComplete = []@@ -181,6 +185,7 @@ public final class BotStore {saveTask?.cancel()onPaired = nilonBotUpdated = nil+ onRosterChanged = nilonUsageChanged = nilonSent = nilclient = nil@@ -281,10 +286,13 @@ public final class BotStore {bots[bot.id] = botbump(bot.rev)onBotUpdated?(bot)+ onRosterChanged?(roster)case let .botDeleted(id, r):bots[id] = nilentries[id] = nilbump(r)+ if selection == id { selection = nil }+ onRosterChanged?(roster)case let .entry(e):upsert(e)bump(e.rev)@@ -490,8 +498,11 @@ public final class BotStore {}public func refreshUsage() async {- guard let client else { return }- if let u = try? await client.usage(refresh: true) { setUsage(u) }+ guard !retired, let client, let token = pairing?.token else { return }+ if let u = try? await client.usage(refresh: true),+ !retired, !Task.isCancelled, pairing?.token == token {+ setUsage(u)+ }}public func loadOlder(_ botId: String) async {diff --git a/kit/Tests/CodyncKitTests/AccountStorageTests.swift b/kit/Tests/CodyncKitTests/AccountStorageTests.swiftindex ba31b045..384dac23 100644--- a/kit/Tests/CodyncKitTests/AccountStorageTests.swift+++ b/kit/Tests/CodyncKitTests/AccountStorageTests.swift@@ -51,3 +51,41 @@ import TestingsignedIn.pairing = nil#expect(local.pairing == old)}++@Test func widgetCachesFollowTheSelectedComputer() throws {+ let suite = "CodyncWidgetTests.\(UUID().uuidString)"+ let defaults = try #require(UserDefaults(suiteName: suite))+ defer { defaults.removePersistentDomain(forName: suite) }+ let account = SharedStore.Context(accountID: "user_a", defaults: defaults)+ let other = SharedStore.Context(accountID: "user_b", defaults: defaults)+ let first = Pairing(name: "Mac", token: "mac-token", urls: ["https://mac.invalid"])+ let second = Pairing(name: "Linux", token: "linux-token", urls: ["https://linux.invalid"])+ account.pairing = first+ account.usage = .widgetPreview+ account.bots = Bot.widgetPreview+ account.preferredURL = first.urls.first+ other.pairing = first+ other.usage = .widgetPreview+ other.bots = Bot.widgetPreview++ // Refreshing the addresses of the same computer preserves its snapshot.+ var updated = first+ updated.urls.append("https://mac-backup.invalid")+ account.pairing = updated+ #expect(account.usage == .widgetPreview)+ #expect(account.bots == Bot.widgetPreview)++ account.pairing = second+ #expect(account.usage == nil)+ #expect(account.bots.isEmpty)+ #expect(account.preferredURL == nil)+ #expect(other.usage == .widgetPreview)+ #expect(other.bots == Bot.widgetPreview)++ account.usage = .widgetPreview+ account.bots = Bot.widgetPreview+ account.pairing = nil+ #expect(account.usage == nil)+ #expect(account.bots.isEmpty)+ #expect(other.pairing == first)+}diff --git a/tools/render-widgets.py b/tools/render-widgets.pynew file mode 100644index 00000000..2aba01de--- /dev/null+++ b/tools/render-widgets.py@@ -0,0 +1,21 @@+#!/usr/bin/env python3+"""Export the shared SwiftUI widget cards for visual review (macOS + Xcode)."""+from pathlib import Path+import subprocess++root = Path(__file__).resolve().parents[1]+package = root / "kit"+subprocess.run(["swift", "build", "--package-path", str(package), "--target", "CodyncKit"], check=True)+build = Path(subprocess.check_output(+ ["swift", "build", "--package-path", str(package), "--show-bin-path"], text=True).strip())+output = root / "build" / "widget-previews"+output.mkdir(parents=True, exist_ok=True)+executable = output / "render-widgets"+subprocess.run([+ "xcrun", "swiftc", "-parse-as-library", "-I", str(build / "Modules"),+ str(root / "tools" / "render-widgets.swift"),+ *map(str, sorted((build / "CodyncKit.build").glob("*.swift.o"))),+ "-o", str(executable),+], check=True)+subprocess.run([str(executable), str(output)], check=True)+diff --git a/tools/render-widgets.swift b/tools/render-widgets.swiftnew file mode 100644index 00000000..6eea66d0--- /dev/null+++ b/tools/render-widgets.swift@@ -0,0 +1,77 @@+import AppKit+import CodyncKit+import SwiftUI++// Exports views directly with ImageRenderer. These are layout review artifacts,+// not screenshots of SpringBoard or a substitute for WidgetKit integration tests.+@main+struct WidgetDesignExport {+ @MainActor static func main() throws {+ let output = URL(fileURLWithPath: CommandLine.arguments[1], isDirectory: true)+ for (name, scheme) in [("light", ColorScheme.light), ("dark", ColorScheme.dark)] {+ let renderer = ImageRenderer(content: WidgetBoard()+ .environment(\.colorScheme, scheme))+ renderer.scale = 2+ guard let image = renderer.cgImage else { fatalError("SwiftUI could not render \(name)") }+ let bitmap = NSBitmapImageRep(cgImage: image)+ guard let png = bitmap.representation(using: .png, properties: [:]) else {+ fatalError("Could not encode \(name)")+ }+ let url = output.appendingPathComponent("widgets-\(name).png")+ try png.write(to: url)+ print(url.path)+ }+ }+}++private struct WidgetBoard: View {+ private let date = Date(timeIntervalSince1970: 1_790_400_000)++ private func provider(_ index: Int, high: Bool = false) -> UsageProvider {+ var p = Usage.widgetPreview.providers[index]+ for i in p.windows.indices {+ p.windows[i].resetsAt = Int64((date.timeIntervalSince1970 + Double((i + 1) * 12_000)) * 1_000)+ if high { p.windows[i].percent = i == 0 ? 96 : 100 }+ }+ return p+ }++ var body: some View {+ VStack(alignment: .leading, spacing: 18) {+ Text("Codync · Widget layout review").font(.title2.weight(.semibold))+ Text("158 pt small · 338 × 158 pt medium · sample data")+ .font(.caption).foregroundStyle(Palette.secondary)+ providerRow("Claude", provider(0))+ providerRow("Codex", provider(1))+ providerRow("Near the limit", provider(0, high: true))+ HStack(spacing: 20) {+ card { BotsWidgetCard(bots: Bot.widgetPreview, wide: false) }.frame(width: 158)+ card { BotsWidgetCard(bots: Bot.widgetPreview, wide: true) }.frame(width: 338)+ }+ HStack(spacing: 20) {+ card { BotsWidgetCard(bots: [], wide: false) }.frame(width: 158)+ card { BotsWidgetCard(bots: [], wide: true) }.frame(width: 338)+ }+ Text("Shared SwiftUI cards. Excludes system widget chrome and refresh scheduling.")+ .font(.caption2).foregroundStyle(Palette.secondary)+ }+ .padding(24)+ .foregroundStyle(Palette.text)+ .background(Palette.background)+ }++ private func providerRow(_ title: String, _ provider: UsageProvider) -> some View {+ VStack(alignment: .leading, spacing: 6) {+ Text(title).font(.caption.weight(.medium)).foregroundStyle(Palette.secondary)+ HStack(spacing: 20) {+ card { ProviderWidgetCard(provider: provider, layout: .small, date: date) }.frame(width: 158)+ card { ProviderWidgetCard(provider: provider, layout: .medium, date: date) }.frame(width: 338)+ }+ }+ }++ private func card<Content: View>(@ViewBuilder content: () -> Content) -> some View {+ content().padding(14).frame(height: 158)+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 22))+ }+}