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
docs: document routines and Linux servers, update paths
leepokaid48ceea9106d
diff --git a/AGENTS.md b/AGENTS.mdindex cdc3c36e..ac6876f6 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -34,7 +34,7 @@ Use four-space indentation for Swift and Rust. Follow Swift 6 strict concurrencyName Swift files after their main `UpperCamelCase` type; use `snake_case.rs` and `kebab-case.ts`. Follow role suffixes such as `View`, `Row`, and `Store`. See `docs/architecture/file-structure.md` and `CLAUDE.md` for architectural conventions.-- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation for system Liquid Glass, as specified in `docs/design/ui-conventions.md`. Keep system authentication and widget containers native. Outside these exceptions, avoid: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncMenu`, `.codyncDialog`, `ToggleStyle.codync`). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.+- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation for system Liquid Glass, as specified in `docs/design/ui-conventions.md`. The macOS menu bar also uses native `MenuBarExtra(.menu)`, menus, pickers and toggles. Keep system authentication and widget containers native. Outside these exceptions, avoid: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncMenu`, `.codyncDialog`, `ToggleStyle.codync`). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.## Testing Guidelinesdiff --git a/CLAUDE.md b/CLAUDE.mdindex ae002a3f..d8eaa8af 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -17,11 +17,11 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess- Clients: iOS app, native Mac window (menu bar app), native Linux app (`apps/linux/`, GTK 4 + libadwaita in Rust), terminal UI (`codync-host tui`, `host/src/tui/`, ratatui; layout and state vocabulary modeled on herdr). All talk to the host API; no web UI.- Shared Swift (`kit/`): `CodyncKit` (models, client, theme, avatars) + `CodyncUI` (`BotStore` + chat screens) used by iOS and macOS. Platform specifics go through `BotStore` hooks or `Platform.swift`.- UI principle: buttons an icon can express are icon-only (with tooltip / accessibility label); text only where an icon would be ambiguous (approval choices).-- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation for system Liquid Glass, as specified in `docs/design/ui-conventions.md`. Keep system authentication and widget containers native. Outside these exceptions, avoid: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncMenu`, `.codyncDialog`, `ToggleStyle.codync`). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.-- `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.+- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation for system Liquid Glass, as specified in `docs/design/ui-conventions.md`. The macOS menu bar also uses native `MenuBarExtra(.menu)`, menus, pickers and toggles. Keep system authentication and widget containers native. Outside these exceptions, avoid: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncMenu`, `.codyncDialog`, `ToggleStyle.codync`). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.+- `host/` — **codync-host** (Rust, macOS + Linux). Detects installed harnesses (`agent/backends.rs`: login-shell PATH + known dirs) and the ACP registry (`agent/registry.rs`, cached in `~/.codync/registry.json`, binaries under `~/.codync/agents`). Drives agents over **ACP** (JSON-RPC on stdio, hand-rolled in `agent/acp.rs`, updates kept as `serde_json::Value` so new adapter variants never break parsing). One actor per bot (`agent/bot.rs`) owns the agent process + session and maps `session/update` onto transcript entries.- **Chat ≠ 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*.- **Group chats and threads** are host features every client drives through the same methods (`send` with `threadId`, `thread`, `createBot {kind: group}`); clients never route, parse mentions or count replies themselves. A group is a roster row whose members answer in their own sessions (Grok Bot's room turns); a thread on a bot's message is a forked session: [docs/features/groups-and-threads.md](docs/features/groups-and-threads.md).-- 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/features/bot-collaboration.md](docs/features/bot-collaboration.md).+- Bot collaboration: built-in `team` MCP (`chat/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/features/bot-collaboration.md](docs/features/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/features/context-and-memory.md](docs/features/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).diff --git a/README.md b/README.mdindex ce16adc4..f44b81cd 100644--- a/README.md+++ b/README.md@@ -50,6 +50,8 @@ codync-host pair # QR code in the terminal, or SettingBuilding the Linux app yourself needs `libgtk-4-dev libadwaita-1-dev`: `cargo install --path apps/linux`.+**Linux server / cloud VM** — the host runs headless on any distro (static binary, x86_64 + arm64). Setup, remote access and limitations: [docs/guides/linux-servers.md](docs/guides/linux-servers.md).+Remote access uses an encrypted channel over direct LAN/Tailscale or the Cloudflare relay. Tailscale is optional. Configure matching app/host environments and follow the [Cloudflare test guide](docs/guides/cloudflare-testing.md); development configuration exists, while production configuration still needs completion.**Agents** — install and sign in to whichever you use; Codync finds them. Claude Code, Codex and Pi run through their ACP adapters (fetched by `npx`, so Node.js is needed for those).@@ -71,7 +73,7 @@ Remote access uses an encrypted channel over direct LAN/Tailscale or the Cloudfl| `codync-host devices` | list/revoke authorized remote devices || `codync-host access` | review device access requests |-Data lives in `~/.codync`. The local bearer token authorizes loopback helpers and SSH-forwarded callers. Remote devices use individual keys and grants over the encrypted channel; revoke a lost device through device management rather than rotating the loopback token. Host methods and caller permissions live in `host/src/api.rs`.+Data lives in `~/.codync`. The local bearer token authorizes loopback helpers and SSH-forwarded callers. Remote devices use individual keys and grants over the encrypted channel; revoke a lost device through device management rather than rotating the loopback token. Host methods and caller permissions live in `host/src/api/mod.rs`.## Repositorydiff --git a/docs/README.md b/docs/README.mdindex 2aa372ae..6dd72362 100644--- a/docs/README.md+++ b/docs/README.md@@ -12,6 +12,7 @@ Source review, a passing build, local integration tests and production acceptanc| Build, install, restart and run checks | [Development](guides/development.md) || Test a phone over Cloudflare instead of LAN | [Cloudflare testing](guides/cloudflare-testing.md) || Configure dev/main or deploy the services | [Environments and deployment](guides/environments-and-deployment.md) |+| Run the host on a Linux server or cloud VM | [Linux servers](guides/linux-servers.md) || Set up accounts, approvals or desktop SSH | [Accounts and SSH](guides/accounts-and-ssh.md) || Change transport or cryptography | [Remote protocol](reference/remote-relay.md) and [shared vectors](reference/fixtures/README.md) || Change an Apple screen or button | [UI conventions](design/ui-conventions.md) |@@ -60,3 +61,5 @@ Service-local entry points remain in [cloud/README.md](../cloud/README.md) and [- Focused fixture/crypto checks passed: Swift 14 tests; Rust 12 tests across library/binary targets; Cloudflare vectors/relay 43 tests.- `git diff --check` passed. These checks validate the documentation move and its executable consumers, not the deployed Cloudflare path.- Wrangler reported a production route placement warning; see [environment readiness](guides/environments-and-deployment.md). Deployed-device acceptance remains separate.++- [Routines](features/routines.md): scheduled and webhook-triggered bot work, Apple UI, execution history and reference parity.diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.mdindex 13267afd..ba38addf 100644--- a/docs/architecture/file-structure.md+++ b/docs/architecture/file-structure.md@@ -7,7 +7,17 @@ This is the map of the current repository. Paths below are repository-relative.```textCodync/├── host/ # Rust daemon and terminal client-│ ├── src/ # Runtime modules; tui/ contains terminal UI+│ ├── src/+│ │ ├── main.rs # CLI entry, shared helpers (LockExt, http)+│ │ ├── hub.rs, store.rs # Shared state + event fan-out / SQLite persistence+│ │ ├── service.rs # Data dir, launchd/systemd install, keep-awake+│ │ ├── usage.rs, screen.rs, mcp.rs+│ │ ├── api/ # HTTP/SSE dispatch, caller permissions (devices.rs)+│ │ ├── agent/ # ACP client, harness discovery, registry, sign-in, setup PTYs, bot actor+│ │ ├── chat/ # Groups, bot-to-bot requests, prompt snapshots, memory+│ │ ├── remote/ # Identity, wire crypto, E2E channel, cloud, relay socket, push+│ │ ├── market/ # Marketplace, Composio, MCP OAuth+│ │ └── tui/ # Terminal client│ └── tests/ # Host integration tests and scripted ACP agents├── kit/ # Shared Swift package│ ├── Sources/@@ -54,14 +64,15 @@ Codync/| Responsibility | Source entry points ||---|---|| CLI and background service | `host/src/main.rs`, `service.rs` |-| API, caller permissions, event ordering | `host/src/api.rs`, `devices.rs`, `hub.rs` |+| API, caller permissions, event ordering | `host/src/api/`, `hub.rs` || SQLite transcript, bots, lanes and sessions | `host/src/store.rs` |-| Agent process, ACP, queue and session lifecycle | `host/src/bot.rs`, `acp.rs` |-| Group room turns / bot-to-bot requests | `host/src/group.rs` / `team.rs` |-| Prompt snapshots and memory keeper | `host/src/context.rs`, `memory.rs` |-| Identity, encryption and direct channel | `host/src/identity.rs`, `crypto.rs`, `channel.rs` |-| Host cloud state and relay connection | `host/src/cloud.rs`, `relay.rs` |-| Agent discovery, marketplace, auth terminal | `host/src/backends.rs`, `registry.rs`, `market.rs`, `composio.rs`, `term.rs` |+| Agent process, ACP, queue and session lifecycle | `host/src/agent/bot.rs`, `acp.rs` |+| Group room turns / bot-to-bot requests | `host/src/chat/group.rs` / `team.rs` |+| Prompt snapshots and memory keeper | `host/src/chat/context.rs`, `memory.rs` |+| Identity, encryption and direct channel | `host/src/remote/identity.rs`, `crypto.rs`, `channel.rs` |+| Host cloud state and relay connection | `host/src/remote/cloud.rs`, `relay.rs` |+| Agent discovery, sign-in, setup terminal | `host/src/agent/backends.rs`, `registry.rs`, `auth.rs`, `term.rs` |+| Marketplace, Composio, connector OAuth | `host/src/market/` || Screen bridge and built-in MCP tools | `host/src/screen.rs`, `mcp.rs` || Swift transport and cloud API | `kit/Sources/CodyncKit/Client/` || Account aggregation / one host mirror | `kit/Sources/CodyncUI/Store/AccountStore.swift` / `BotStore.swift` |@@ -71,7 +82,7 @@ Codync/| Apple account sessions / public environment config | `apps/shared/AccountSession.swift`, `apps/shared/Config/` || Mac local host / SSH lifecycle | `apps/macos/App/HostController.swift`, `SSHTunnel.swift` || Cloud routes / authentication / relay | `cloud/src/index.ts`, `api.ts`, `auth.ts`, `relay.ts` |-| Push encryption / APNs delivery / decryption | `host/src/push.rs`, `relay/src/`, `apps/ios/NotificationService/` |+| Push encryption / APNs delivery / decryption | `host/src/remote/push.rs`, `relay/src/`, `apps/ios/NotificationService/` || Widget and activity rendering | `kit/Sources/CodyncKit/Design/`, `apps/ios/Widgets/` |## Dependency rules@@ -98,7 +109,7 @@ Codync/| computer / host | User-facing paired environment / the daemon that serves it || cloud / relay | Account + E2E service / context-dependent transport or APNs Worker; always name the directory when ambiguous |-Use lowercase repository folders; PascalCase folders inside Swift targets. Swift files follow their main type (`UpperCamelCase.swift`), Rust uses `snake_case.rs`, and TypeScript uses `kebab-case.ts`. Prefer one main type per file; small related view siblings can share a plural file such as `ChatRows.swift`.+Use lowercase repository folders; PascalCase folders inside Swift targets. Swift files follow their main type (`UpperCamelCase.swift`), Rust uses `snake_case.rs` (a folder module is `name/mod.rs`), and TypeScript uses `kebab-case.ts`. Prefer one main type per file; small related view siblings can share a plural file such as `ChatRows.swift`.Role suffixes: `View`, `Row`, `Card`, `Window`, `Store`, `Controller`; button styles describe the effect (`PressScale`). Keep feature vocabulary aligned across Swift, Rust, Linux and the terminal client.diff --git a/docs/architecture/overview.md b/docs/architecture/overview.mdindex 56eb4a94..5ee2f56d 100644--- a/docs/architecture/overview.md+++ b/docs/architecture/overview.md@@ -39,9 +39,9 @@ Cloud account metadata includes names, public keys, ownership and access state.## Host execution-`api.rs` and `channel.rs` share dispatch and caller checks. `hub.rs` coordinates actors and event publication; `store.rs` persists mutations and the global revision. Clients catch up from `rev`, then follow events. Duplicate sends are identified by `clientNonce`.+`api/` and `remote/channel.rs` share dispatch and caller checks. `hub.rs` coordinates actors and event publication; `store.rs` persists mutations and the global revision. Clients catch up from `rev`, then follow events. Duplicate sends are identified by `clientNonce`.-`bot.rs` serializes each bot's turns and owns its ACP process. A main chat and its reply threads can have distinct sessions. Group turns are queued on member bots and use their main sessions; the group itself has no harness. See [groups and threads](../features/groups-and-threads.md), [collaboration](../features/bot-collaboration.md) and [context/memory](../features/context-and-memory.md).+`agent/bot.rs` serializes each bot's turns and owns its ACP process. A main chat and its reply threads can have distinct sessions. Group turns are queued on member bots and use their main sessions; the group itself has no harness. See [groups and threads](../features/groups-and-threads.md), [collaboration](../features/bot-collaboration.md) and [context/memory](../features/context-and-memory.md).## Apple state and routingdiff --git a/docs/archive/bot-computer-ssh-plan-2026-09-25.md b/docs/archive/bot-computer-ssh-plan-2026-09-25.mdindex 9e8380ae..b4eeda0a 100644--- a/docs/archive/bot-computer-ssh-plan-2026-09-25.md+++ b/docs/archive/bot-computer-ssh-plan-2026-09-25.md@@ -175,7 +175,7 @@ MVP 支援既有 key/agent 驗證與 macOS 客戶端;password、互動式 MF## 8. 目前評估依據-對照 `apps/ios/Views/BotListView.swift`、`SettingsView.swift`、`kit/Sources/CodyncUI/Store/BotStore.swift`、`HostClient.swift`、`host/src/acp.rs` 與 `apps/macos/App/HostController.swift`:目前是一個 active computer 對應一個 store/client 的設計,尚無跨 computer 的 account store 或 SSH 連線管理。因此此功能不能只換手機左上角圖示或加 `computerId` 就算完成。+對照 `apps/ios/Views/BotListView.swift`、`SettingsView.swift`、`kit/Sources/CodyncUI/Store/BotStore.swift`、`HostClient.swift`、`host/src/agent/acp.rs` 與 `apps/macos/App/HostController.swift`:目前是一個 active computer 對應一個 store/client 的設計,尚無跨 computer 的 account store 或 SSH 連線管理。因此此功能不能只換手機左上角圖示或加 `computerId` 就算完成。SSH 與 Clerk 具體 API/平台相容性應在實作階段依當時官方文件和已安裝版本核對;本文件未宣告任何 SSH 或多帳號功能已經可用。diff --git a/docs/archive/cloudflare-account-device-plan-2026-09-25.md b/docs/archive/cloudflare-account-device-plan-2026-09-25.mdindex cb163e04..230f2cd9 100644--- a/docs/archive/cloudflare-account-device-plan-2026-09-25.md+++ b/docs/archive/cloudflare-account-device-plan-2026-09-25.md@@ -57,9 +57,9 @@ Cloudflare API、D1、裝置目錄、雲端授權/撤權與中繼由 Claude Co| Mac 已使用 ClerkKit,支援 Google 登入 | `apps/shared/AccountSession.swift`、`docs/guides/accounts-and-ssh.md` | 延伸現有登入,不另建帳號系統 || 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` | 必須新增逐裝置授權,才能精準撤權 |+| host 使用共用 pairing token,旋轉會使所有舊裝置失效 | `host/src/main.rs`、`host/src/api/mod.rs` | 必須新增逐裝置授權,才能精準撤權 || 手機配對資料依帳號分區存入 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 抽象接中繼 |+| 命令走 HTTP API,事件走 SSE | `host/src/api/mod.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-macos/`、`kit/Sources/CodyncUI/Screen/` | 影像傳輸與聊天中繼分開 |diff --git a/docs/design/mobile-widgets.md b/docs/design/mobile-widgets.mdindex e635515b..2686617a 100644--- a/docs/design/mobile-widgets.md+++ b/docs/design/mobile-widgets.md@@ -34,7 +34,8 @@- Claude 使用既有暖色;Codex 使用藍色;90% 以上顯示警示色。- 採平面深淺色表面、小型圖示、11–13 pt 標籤;大字只用於主要數值。- App 的 Usage 卡片同步縮小字級、圖示、內距,並使用同一款刻度條。-- Widgets 頁可從 Settings 或 Usage 的「Widgets & setup」進入,提供類型/provider/大小切換、三種主畫面尺寸預覽與設定教學。+- 底部的 State 分頁以頂部切換呈現 Widget/Live Activity/Dynamic Island 三頁;用量上限從右上角圖示開成 sheet。Computers & settings 不再放這些入口。+- Widget 頁提供類型/provider/大小切換、三種主畫面尺寸預覽與設定教學。加入 widget 的教學(`WidgetSetupDemo.swift`)用 SwiftUI 畫出一支 iPhone,手指實際演出長按、Edit、Add Widget、找到 Codync、Add Widget、Done;整段由單一時鐘驅動,會循環,可暫停/播放,也可以拖曳進度條。- 「Lock Screen widgets」頁可切換 Bots/Usage limits,預覽圓形、矩形與行內形式。正式 widget 與預覽共用 `AccessoryWidgetCard`。- 設定清單讀取實際電腦配對狀態與 `WidgetCenter` 的已安裝配置;不以點過教學當作完成。- 查詢失敗時顯示錯誤與「Check again」,不會永久停在載入狀態。@@ -46,7 +47,7 @@## Live Activity 與 Dynamic Island-Settings 與 Widgets 頁都能進入「Live Activity & Dynamic Island」。這裡提供 Live Activities 開關、系統授權狀態,以及形式/任務狀態預覽。預覽明確標示 Sample task,不會啟動實際任務或 Live Activity。+State 分頁的 Live Activity 頁顯示鎖定畫面形式,Dynamic Island 頁顯示 Compact/Minimal/Expanded。這裡提供 Live Activities 開關、系統授權狀態,以及形式/任務狀態預覽。預覽明確標示 Sample task,不會啟動實際任務或 Live Activity。| 形式 | 資訊與互動 || --- | --- |diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdindex 7cdb6ec1..b0596f0c 100644--- a/docs/design/ui-conventions.md+++ b/docs/design/ui-conventions.md@@ -2,7 +2,7 @@## iPhone navigation-The bot list and conversation use the system `NavigationStack` toolbar. `ToolbarItem` owns the account, computer, new-chat, call and more buttons; the conversation uses the system back button. iOS supplies Liquid Glass, control sizing, grouping and interaction feedback.+The bot list and conversation use the system `NavigationStack` toolbar. `ToolbarItem` owns the account, computer, new-chat, call and more buttons; menus opened from these toolbar buttons (New, the computer filter) are native `Menu`s, because the bar hosts its items outside SwiftUI's layout and `.codyncMenu` can't anchor to them; the conversation uses the system back button. iOS supplies Liquid Glass, control sizing, grouping and interaction feedback.Do not wrap those toolbar controls in `IconButtonStyle`, hand-sized rounded backgrounds or another glass effect. The account avatar is toolbar content, with the system supplying the enclosing surface. This is the explicit exception to the custom-chrome rule below.@@ -10,6 +10,16 @@ Do not wrap those toolbar controls in `IconButtonStyle`, hand-sized rounded backSources: `apps/ios/Views/BotListView.swift`, `AccountSwitcherView.swift`, `kit/Sources/CodyncUI/Thread/ThreadView.swift`, `Chrome.swift`, `Bots/BotRow.swift`.+## macOS menu bar++Use `MenuBarExtra` with `.menuBarExtraStyle(.menu)`. Its commands, submenus, checkmarked toggles, usage-icon picker, separators and keyboard navigation use system styling. Do not add custom cards, hover backgrounds, icon buttons or a window-style menu panel here.++The menu retains host installation/restart, bot conversation/stop actions, approval review, usage limits, remote-screen permissions, launch-at-login and quit. Pairing opens a separate titled window because its QR needs a persistent scanning surface. The chat window retains its own UI conventions.++Usage limits appear directly in the top-level menu, grouped by provider with native section headers. Show each window's percentage, reset time when available, and the provider's last update; do not hide them in submenus.++Source: `apps/macos/App/CodyncMacApp.swift`.+## Shared application controlsOther custom screens use `Chrome.swift` and `Controls.swift`:@@ -35,3 +45,11 @@ Anything with a background fill gets no extra drawn border. Use `Palette`, `InteProvider identity and activity presentation are shared in `CodyncKit/Design`; use those components rather than re-creating mappings per app. See [mobile widgets](mobile-widgets.md) for current rendering and previews.The [2026-09-25 audit](../archive/ui-audit-2026-09-25.md) is historical. Its old line numbers and recommendations are not the current UI policy or a list of confirmed open bugs.++Model discovery keeps loading and refresh in one fixed-size slot beside the Model picker. Refresh retains the current catalog while loading, and loading does not add a separate row to the settings card.++## macOS conversation details++The details inspector uses a compact device summary instead of an empty screen preview. Keep the computer name, remote-screen state, and iPhone hint together; show the hint only when screen capture is ready. Use 16-point horizontal insets, 28-point section gaps, and 12-point corner radii on flat surfaces, without borders.++Routines use a short empty state with one setup action and an icon action for asking in chat. Populated lists move the add action into the section header. Agent metadata uses explicit Runtime and Working folder labels; paths remain selectable and wrap. Keep status and section headings readable in both appearances through `Palette`.diff --git a/docs/features/bot-collaboration.md b/docs/features/bot-collaboration.mdindex 15d3d724..e96c1753 100644--- a/docs/features/bot-collaboration.md+++ b/docs/features/bot-collaboration.md@@ -28,8 +28,8 @@ This first version uses synchronous request/reply over MCP and does not introduc## 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/chat/team.rs`: discovery, wait graph, request lifetime and persisted notices.+- `host/src/agent/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.diff --git a/docs/features/context-and-memory.md b/docs/features/context-and-memory.mdindex ab82be7c..af63cce2 100644--- a/docs/features/context-and-memory.md+++ b/docs/features/context-and-memory.md@@ -15,7 +15,7 @@ where the harness owns the conversation.Codync never replays the transcript into a session. Each turn sends only the new message(s); the harness keepsits own context and compacts it itself.-## Instruction snapshot (`host/src/context.rs`)+## Instruction snapshot (`host/src/chat/context.rs`)- The bot's instructions are rendered once: profile (name, description, skills, phone-friendly rule) plus thememory section. They're stored as a snapshot in `kv` under `context.<bot>`, keyed by **session + compaction@@ -32,7 +32,7 @@ its own context and compacts it itself.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`)+## Memory (`host/src/chat/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.diff --git a/docs/features/groups-and-threads.md b/docs/features/groups-and-threads.mdindex 692caf96..86b11398 100644--- a/docs/features/groups-and-threads.md+++ b/docs/features/groups-and-threads.md@@ -19,8 +19,12 @@ replies itself.`workingThread` (where the running turn talks). A group's `status` / `activity` are its busymember's (`"Alice: Writing a reply…"`); its `lastMessage` names who spoke (`"Alice: …"`).- Entry: `threadId`; `data.author` (the bot that wrote it; every agent-made entry has one);- on a root, `data.thread = {count, lastAt, authors}` (`authors`: bot ids and `"user"`, first- reply first), kept up to date by the host.+ on a root, `data.thread = {count, lastAt, authors, unread}` (`authors`: bot ids and `"user"`,+ first reply first; `unread`: replies newer than the thread was last read), kept up to date by+ the host.+- Read state (Slack's): the main chat and each thread are read separately. A bot's `unread`+ badge is the sum. Reading the main chat leaves a thread's new replies unread; opening the+ thread (or replying in it) reads them. A root doesn't turn unread when its summary changes.- `sync` / `events` catch-up carries recent entries of chats *and* threads. Paging:`history` (main chat only), `thread` (a whole thread).@@ -34,10 +38,11 @@ replies itself.| `updateBot` | `{id, name?, members?, pinned?, hidden?}` | A group can't become a bot or the reverse. || `deleteBot` | `botId` | A group's bots stay. A deleted bot leaves its groups. || `stop` | `botId` | For a group: ends its room turns (main and threads) and stops members working in it. |+| `react` | `entryId, emoji` | Toggles the user's reaction on a chat message (`data.reactions`, oldest first, at most 8). A reacted-to message never turns unread again. The bot isn't told. || `respondPermission` | `entryId, optionId?` | Routed to `data.author`, so cards in a group reach the bot that asked. |-| `markRead` | `botId` | Unread counts include thread replies. |+| `markRead` | `botId, threadId?, all?` | The main chat, one thread (`threadId`), or everything (`all`, the roster's "Mark as read"). A no-op when nothing there is unread, so clients call it whenever a chat or thread is on screen. `send` marks its own lane read. |-## How a group answers (`host/src/group.rs`, Grok Bot's design)+## How a group answers (`host/src/chat/group.rs`, Grok Bot's design)- The user's message starts a *room turn* in its lane: up to 3 rounds, 10 replies in all.- Who answers each round: the members @-mentioned since the user's last message (full@@ -52,7 +57,7 @@ replies itself.- Tool calls, thoughts and permission cards of a member's group turn are written to thegroup (with `author`), not to the member's own chat. One "done" push per room turn.-## How a thread continues (`host/src/bot.rs`)+## How a thread continues (`host/src/agent/bot.rs`)- In a bot's chat, a thread is its own ACP session. The first reply forks the chat's session(`session/fork`, e.g. Claude) so the thread starts from everything said so far; an agent@@ -64,6 +69,6 @@ replies itself.## Client checklistRoster row for groups (member avatars), a trace per lane (main chat, or one thread), author label on group replies, the thread summary-under a root (opens the thread), "Reply in thread" on any main-chat message, a thread view+under a root (opens the thread; "N new" while `unread > 0`), "Reply in thread" on any main-chat message (Mac: while the pointer is over a message, its footer beside the time shows quick reactions, reply, copy — never on the bubble; iPhone: long-press, reactions on top of the menu), reactions under a message (tap to take back), a thread view(root, replies, composer sending `threadId`), group create/edit (name, members), Stop in agroup calls `stop` with the group id.diff --git a/docs/features/marketplace.md b/docs/features/marketplace.mdindex 67cdb2db..1810f7fd 100644--- a/docs/features/marketplace.md+++ b/docs/features/marketplace.md@@ -4,15 +4,36 @@ The Plugins screen configures capabilities installed on the selected computer. A| Capability | Implementation | Behavior || --- | --- | --- |-| Agents | `host/src/backends.rs`, `host/src/registry.rs` | Detect installed harnesses and resolve ACP registry adapters |-| Connectors | `host/src/market.rs` | Discover MCP servers or add one manually; install per computer and enable per bot |-| Connected apps | `host/src/composio.rs` | Expose connected Composio apps as connectors |-| Skills | `host/src/market.rs` | Instruction folders containing `SKILL.md`, stored under `~/.codync/skills/<id>` |+| Agents | `host/src/agent/backends.rs`, `host/src/agent/registry.rs` | Detect installed harnesses and resolve ACP registry adapters |+| Connectors | `host/src/market/mod.rs` | Discover MCP servers or add one manually; install per computer and enable per bot |+| Connected apps | `host/src/market/composio.rs` | Expose connected Composio apps as connectors |+| Skills | `host/src/market/mod.rs` | Instruction folders containing `SKILL.md`, stored under `~/.codync/skills/<id>` |-An enabled connector is passed to the agent as an MCP server when its session starts or resumes. An enabled skill tells the bot where its instruction folder lives. These are distinct from the built-in `team` and `computer` MCP services.+An enabled connector is passed to the agent as an MCP server when its session starts or resumes. Local connectors are spawned by the agent; remote ones always go through the host's stdio proxy (`codync-host mcp remote`, `host/src/mcp.rs`), so they work with agents that only speak stdio and always carry a fresh token.++## Sign-in for remote connectors (`host/src/market/oauth.rs`)++Installing a remote connector probes it; a 401 marks it `signedOut` and bots don't get it until someone signs in. Sign-in follows the MCP authorization spec: protected-resource metadata → authorization-server metadata → dynamic client registration (both redirect URIs at once) → PKCE. Tokens stay on the computer and are refreshed on use (or after a 401).++| Where the user signs in | Redirect URI | Who finishes |+| --- | --- | --- |+| On the computer (Mac app, TUI; loopback caller) | `http://127.0.0.1:<port>/oauth/callback` | the host's callback page |+| On the phone (E2E channel caller) | `<cloud>/v1/oauth/callback` → 302 `codync://oauth?…` | the app's system sign-in sheet sends `connectorSignInFinish` |++The cloud page is stateless and the code is useless without the PKCE verifier held by the host. Servers without dynamic client registration (e.g. GitHub) need a token header instead (custom connector, URL + headers). `connectorTarget` (loopback only) hands the proxy the URL and headers.++Registry packages install only at the exact version the MCP Registry lists (no `latest`), since they run as the user. An enabled skill tells the bot where its instruction folder lives. These are distinct from the built-in `team` and `computer` MCP services.Registry and repository metadata are untrusted: the host validates names and paths before installing. Secret values stay on the computer; listings report whether required values are configured. Adapter downloads and external authorization depend on the selected provider.To check a change, use a disposable bot on the intended computer, verify discovery/install/configuration, start a new session as needed, and confirm the agent actually receives the capability. Listing an item alone does not verify its authentication or runtime behavior.See [file structure](../architecture/file-structure.md), [bot collaboration](bot-collaboration.md), and [remote screen](remote-screen.md).++## Model selection++The shared bot editor requests `agentModels {backend}` from the selected computer. The host starts an isolated ACP session under its probe directory with saved agent credentials, no MCP servers and no prompt, then closes the process. The response is `{models: [{id, name, description}], currentModelId}`.++Discovery prefers ACP `configOptions` with category `model` (including grouped options), with conventional `model`/`models` IDs as a compatibility fallback. Older agents may expose `models.availableModels`. Model names and IDs come from the agent; Codync does not bundle a provider catalog. See the [ACP config option contract](https://agentclientprotocol.com/protocol/v1/session-config-options).++The editor keeps Default, shows available models in a dropdown, and resets the selected model when changing agents. Errors are visible and retryable. Custom commands and agents without model discovery retain manual ID entry; an existing unlisted ID is preserved. The probe uses an isolated directory, so project-specific agent configuration can differ from the real bot session. Changing the model restarts the bot's agent sessions with fresh model context and preserves the stored chat history. The agent remains responsible for validating availability when a session starts.diff --git a/docs/features/routines.md b/docs/features/routines.mdnew file mode 100644index 00000000..39012057--- /dev/null+++ b/docs/features/routines.md@@ -0,0 +1,217 @@+# Routines++Routines belong to an agent bot. **Set up a routine** opens a form for the name,+instruction, trigger and timeout; Save creates it immediately. Edit opens the same+form and preserves existing triggers by default. **Ask in chat** is a separate+option that inserts an explanatory draft; send it to ask the bot to configure the+routine. Every agent receives the built-in `routines` MCP server. The Mac conversation details+panel and the iPhone's **More → Routines** show the saved instruction, triggers,+pause/resume, edit, delete, test run and execution history. Creation/update notices+open the routine.++## Apple setup interface++The editor keeps task fields first, followed by trigger choices and their settings.+Trigger choices use adaptive columns, selected checkmarks and short descriptions.+Inputs use the shared palette with a visible filled surface. Interval input also+shows its duration in words. Run timeout is under an animated Run settings+expansion. A fixed footer keeps Create routine / Save changes and inline errors+visible while the form scrolls; it explains the local execution requirement.+The layout uses the same light/dark tokens, type family and custom controls as the+rest of Codync, with Reduce Motion support.++## Conversational setup and tools++Every agent receives the `routines` MCP server automatically; no marketplace+installation is needed. Its tools are `list_routines`, `save_routine`,+`set_routine_enabled`, `delete_routine`, `run_routine` and `routine_webhook`.+The same setup guidance is included in newly rendered agent context and MCP+initialization instructions.++For chat setup, the bot should resolve the task, trigger and timezone from the+conversation, asking only about missing or ambiguous details. It should check the+task's required tools, sign-ins and files, list existing routines to avoid+accidental duplication, then save and report the returned configuration and next+occurrence. A saved webhook whose external sender is not connected must be+reported as awaiting connection. Testing runs the actual instruction, so creating+a schedule alone should not trigger an unsolicited test execution.++A deterministic ACP fixture exercises the actual advertised MCP subprocess:+initialize, discover all six tools, reject an invalid schedule, create, read,+edit, pause/resume, fetch webhook credentials, delete, and execute a test run.+This verifies tool wiring and persisted behavior; it does not guarantee how every+provider model will interpret an ambiguous natural-language request.++## Triggers++A routine has an OR list of triggers:++- `interval`: `seconds` (1 second through 365 days).+- `once`: `at` (Unix milliseconds, in the future when created).+- `cron`: a five-field `expression` and IANA `timeZone`, including DST.+- `webhook`: every authenticated JSON delivery runs the routine.+- `event`: `source`, `event` (`*` matches all), and optional exact-match `filters`.+ `messageContains` matches a substring of `text`. Source names are `slack`,+ `github`, `origin`, `microsoftTeams`, `linear`, `sentry`, `pagerduty`, and `email`.++For example, Sunday at 14:20 in Taipei is `20 14 * * 0` with `Asia/Taipei`.+The host computes and displays the next occurrence. Calendar parsing uses+[Croner](https://docs.rs/croner/3.0.1/croner/), with chrono-tz for named zones.++## Execution++The host checks deadlines every second, even with no client connected. Definitions,+next deadlines and run records are saved in SQLite (`routines.v1`). Due triggers+are coalesced into one run per routine; only one routine per bot is dispatched at a+time. Bot actors serialize routine work with ordinary conversation work.++Each run gets its own conversation thread and agent session. Final results appear+in the main conversation and use normal encrypted push delivery. Returning `(pass)`+or no text completes silently. A test run can run a paused routine. Pausing or+deleting cancels pending runs; work already running can finish. Deleting a bot+cancels its pending work. Missed intervals coalesce rather than replaying a backlog.++Pending runs survive a restart. The actor claims a run only when it reaches the+front of its queue, using the latest saved instruction. Runs interrupted during+execution become `recovering` and load their existing agent session. If the+provider cannot load it, they become `interrupted` instead of replaying the task+in a new session. Session recovery cannot guarantee exactly-once external side+effects; inspect the transcript before retrying an interrupted action.++Each run has a timeout (default one hour, configurable from 1 to 86400 seconds).+A hung agent is terminated so subsequent work can proceed. Completed results are+persisted before publication, with stable transcript IDs to avoid duplicate+results after restart. Failed publication retries without rerunning the agent.+The latest 1000 terminal runs are retained globally, plus active/unpublished runs;+the panel returns the latest 200 runs per bot. Deduplication lasts while the+corresponding run record is retained.++Intervals retain their original cadence; missed deadlines coalesce into one+pending wake, including when a prior run is still active. Enabled time schedules+keep the computer from idle sleep. Explicit sleep, closing the lid and powering+off still suspend local execution. The host uses an exclusive data-directory lock+to prevent two daemons from firing the same schedules. Shutdown stops scheduling+before stopping actors.++## Webhook delivery++`routineWebhook` returns a per-routine URL and secret. The ordinary listing never+returns the secret. Send JSON to `/hooks/routines/<id>` using+`Authorization: Bearer <key>`. `X-Delivery-Id` deduplicates retries against retained+run records. Bodies are limited to 64 KB. The routine must be enabled. Event+routines additionally require a matching normalized payload, for example:++```json+{"source":"github","event":"pull_request.opened","repo":"owner/repo","text":"A PR opened"}+```++The displayed URL uses host loopback. An external sender needs a deliberately+configured forwarding service and must normalize its provider's event into this+format. This implementation does **not** provision SaaS subscriptions, use Grok+Bot's private cloud, register provider webhooks, or provision an inbound email+address. Do not describe an event routine as connected before verifying delivery.+The local endpoint is not automatically published through Codync's E2E relay.++## API++All normal methods use the existing authenticated host API / authorized E2E channel:++| Method | Body |+|---|---|+| `routines` | `botId` |+| `saveRoutine` | `botId`, optional `id`, `name`, `instruction`, `triggers`, optional `enabled`, `timeoutSeconds` |+| `setRoutineEnabled` | `botId`, `id`, `enabled` |+| `deleteRoutine` | `botId`, `id` |+| `runRoutine` | `botId`, `id` |+| `routineWebhook` | `botId`, `id` |++The local-only `routineCall` backs the MCP tools. Each MCP instance is scoped to+its bot. Phone and Mac panels refresh while visible; definitions do not currently+participate in offline client caches. Run transcript entries use normal rev/SSE.++## Reference and parity++Observed on the installed Grok Bot on 2026-09-26: a routine list in conversation+details, instruction and trigger details, pause/resume, delete, and chat-based+editing. Creation produces a linked transcript card. The shipped renderer also+contains test-run and webhook credential controls, interval/one-shot/cron schedule+formatting and multiple provider trigger types.++The local reconstruction at+`/Users/libokai/mycode/nimplex/sandbox/grok-bot-architecture-2026-09-15` contains a+partial automation fire consumer with event matching, durable wake delivery and+completion reporting. Most automation modules it imports are absent. Its renderer+and private cloud are not source-complete references.++Remaining differences from the reference: provider subscription provisioning,+cloud execution/delivery while the host is offline, inactivity auto-pause, and Linux/TUI routine panels. The Apple UI+uses Codync's shared native controls. This is not a verified complete one-to-one+reconstruction of every Grok Bot routine behavior.++## Validation++`host/tests/routines_e2e.rs` starts isolated hosts and deterministic ACP agents,+checks real scheduled execution, webhook credentials, delivery deduplication,+pause/delete/edit while queued, crash recovery in the same session, unsupported+session recovery, hung-agent timeout, recurring work after failure, single-host+ownership, silent completion, and the advertised routine MCP server. Unit tests+cover timezone calculation, invalid schedules, event filters, persistence,+pause/resume and bot ownership. Swift tests cover the wire model and transcript links.++## Public webhook ingress without a fixed IP++Research checked on 2026-09-26:++- [OpenClaw Gmail webhook setup](https://docs.openclaw.ai/cli/webhooks)+ supports Tailscale Funnel for a public push endpoint. Serve is private to the+ tailnet; it is not a replacement for a public URL used by an arbitrary SaaS.+- [Hermes webhook adapter](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/messaging/webhooks.md)+ provides an HTTP listener, route secrets/signature validation, filtering and+ event-triggered cron jobs. Its documented setup still requires a reachable+ server URL; enabling the adapter alone does not solve NAT traversal.++For Codync, a fixed IP on the user's computer is unnecessary. Two possible+approaches are a configured outbound tunnel, or a Codync cloud ingress with a+persistent event queue and delivery over the host's outbound connection. The+latter fits offline delivery but is **proposed, not implemented** here.++The existing relay accepts authorized devices' encrypted frames. A third-party+HTTP sender cannot produce those frames or act as a paired device. Public ingress+therefore needs its own per-routine authorization, provider signature checking,+rate/body limits, delivery IDs, expiry, acknowledgements and revocation. Cloud+HTTPS termination sees the incoming provider payload; it must not be presented as+the same end-to-end encryption boundary as device messages. Local execution waits+until the host reconnects and is awake.++## Usability comparison (2026-09-27)++The installed Grok Bot was inspected through Computer Use. Its sidebar emphasizes+the routine name and a human-readable schedule (for example, Every Sunday at+2:20 PM). Details expose Instruction, When to run, Pause, Edit and Delete. The+conversation contains a linked creation notice; an existing edit draft refers to+the routine by name. No reference routine was run, paused or deleted during this+comparison.++Codync retains that compact sidebar and the chat-based setup path, while providing+a direct editor. Common calendar schedules use Daily / Weekdays / Weekly with a+time control; Custom retains raw cron. Intervals use seconds, minutes, hours or+days. Editing hydrates the original schedule, timezone and interval exactly;+compound and provider-event triggers retain a lossless Keep existing triggers+fallback. Expired one-shot timestamps are preserved when editing other fields.++Saved definitions appear immediately. Paused schedules omit next-run deadlines.+List/details expose queued/running/recovery/failure states and empty run history.+Edit with bot includes the routine ID in a draft without sending it. Webhook+credentials have explicit copy controls, and the panel distinguishes testing the+task from verifying an external delivery. These changes do not configure public+ingress or claim a provider connection is working.++Verification: shared Swift tests passed (46 tests; an unrelated offline-mailbox+assertion failed on the first run, then passed both the targeted and full rerun).+macOS Debug and iOS Simulator builds passed. On the installed Mac build, an+isolated fixture bot was used to create a Sunday 09:00 Asia/Taipei routine, reopen+its populated editor, change it to weekdays, and pause it. API inspection+confirmed one updated routine with `0 9 * * 1-5` and `enabled: false`. Edit with+bot populated an unsent draft with the routine ID. The test bot and working+directory were removed. Screenshots are in `build/routine-usability-calendar.jpeg`+and `build/routine-usability-details.jpeg`.diff --git a/docs/guides/environments-and-deployment.md b/docs/guides/environments-and-deployment.mdindex 3eeca853..ba9ae95f 100644--- a/docs/guides/environments-and-deployment.md+++ b/docs/guides/environments-and-deployment.md@@ -8,7 +8,7 @@ Reviewed against repository configuration on 2026-09-26. Checked-in configuratio| --- | --- | --- || Apple app | `apps/shared/Config/dev.plist`, `main.plist` | `project.yml` copies the selected file to bundled `AccountConfig.plist`; Debug uses dev, Release uses main || Account SDK | `apps/shared/AccountSession.swift` | Public Clerk configuration; development environment overrides are supported |-| Host | `host/src/cloud.rs` | `CODYNC_CLOUD=off` or stored disable wins; then `CODYNC_CLOUD_URL`, stored URL, compiled default |+| Host | `host/src/remote/cloud.rs` | `CODYNC_CLOUD=off` or stored disable wins; then `CODYNC_CLOUD_URL`, stored URL, compiled default || Cloud Worker / D1 / DO | `cloud/wrangler.toml` | Root production, `dev`, or `local` environment || APNs Worker | `relay/wrangler.toml` | Separate deployment and secrets; see [relay README](../../relay/README.md) |diff --git a/docs/guides/linux-servers.md b/docs/guides/linux-servers.mdnew file mode 100644index 00000000..14a5aa85--- /dev/null+++ b/docs/guides/linux-servers.md@@ -0,0 +1,59 @@+# Running the host on a Linux server or cloud VM++`codync-host` runs on any 64-bit Linux machine: a desktop, a home server, or a headless cloud VM (AWS, GCP, Azure, Hetzner, DigitalOcean…). It needs no display. Bots run on that machine and you message them from the iPhone, the Mac app or `codync-host tui`.++## Requirements++| Need | Why |+| --- | --- |+| x86_64 or arm64 Linux | Release builds exist for both architectures |+| `ca-certificates` | HTTPS to the ACP registry, push relay and cloud. Every normal VM image has it; bare container images (`debian`, `ubuntu`) need `apt-get install ca-certificates`. Without it every command exits with `TLS setup failed: install the ca-certificates package` |+| systemd | Only for `codync-host install` (background service). Without systemd, run `codync-host serve` under your own supervisor |+| Node.js | Claude Code, Codex and Pi run through ACP adapters fetched with `npx` |+| The agents you want, signed in | The host drives the CLIs installed on this machine with their own credentials. Sign in over SSH (`claude`, `codex login`…) as the same user that runs the host |++Distro and C library don't matter. From the first release built by the updated workflow, Linux release binaries are static musl builds with no glibc dependency. Earlier releases (≤ 2.1.0) were built against glibc 2.39 and only start on Ubuntu 24.04 or newer. On older distros they fail with `GLIBC_2.39 not found`; build from source or use a newer release there.++## Install++Run as the user who owns the agents (not root, unless the agents are root's):++```sh+brew install leepokai/codync/codync-host # or download codync-host-linux-<arch>.tar.gz from GitHub Releases+codync-host install # systemd --user service, restarts on crash+sudo loginctl enable-linger "$USER" # keep it running after you log out of SSH+codync-host status+```++`install` saves the current `PATH` into the service, so install Node and the agents first. If you add an agent later and the host doesn't find it, run `codync-host install` again. `install` needs a real login session (SSH login, not `sudo su user`), otherwise `systemctl --user` can't reach the user's service manager.++Other commands work the same as on a desktop: `codync-host pair`, `codync-host tui`, `codync-host uninstall` (keeps data in `~/.codync`). Logs go to the journal: `journalctl --user -u codync-host -f`.++## Reaching it from the phone++The phone connects over the encrypted device channel. The pairing link lists only **Tailscale** and **private (LAN/VPC)** addresses; the host never advertises a public IP.++- **Tailscale (recommended for VMs):** install Tailscale on the VM and on the phone, then `codync-host pair`. The Tailscale name comes first in the link. You don't need to open port 19222 in the cloud firewall.+- **Cloudflare cloud:** `codync-host cloud --url https://…` if you run your own Codync cloud. The production cloud isn't live yet (see [environments](environments-and-deployment.md)).+- **Mac app over SSH:** the Mac app can attach an SSH computer and tunnel to its loopback API ([Accounts and SSH](accounts-and-ssh.md)). From any terminal: `ssh -L 19222:127.0.0.1:19222 vm`, then `codync-host tui` locally.++The host listens on `0.0.0.0:19222`. The local API (`/api/*`, `/events`, terminals; bearer token) answers **loopback callers only**, so a public address never exposes it. From outside, only `/health` (host id, computer id, version) and the end-to-end encrypted device channel answer, and the channel only serves devices holding this host's pairing keys. Keep 19222 closed in the cloud firewall anyway unless you deliberately pair over a VPN or private network.++## Limitations on a headless server++- **Remote screen and the `computer` tool don't work.** They need a desktop session (portals + GStreamer, `apps/screen-linux/`). The feature is off by default, so nothing else is affected.+- **No Linux desktop app.** The GTK app (`codync`) needs a desktop, and its release build needs glibc 2.39+ (Ubuntu 24.04 or newer). On a server, use the phone, the Mac app over SSH, or `codync-host tui`.+- **Keep-awake is a no-op.** The host tries `systemd-inhibit` while a bot works; VMs don't sleep, and failure only logs a warning.+- **One computer per account.** A VM counts as the account's computer; multiple computers are future work.+- **Usage limits** come from the local Claude and Codex installs, same as on a desktop.++## Verification — 2026-09-26++Tested in Docker on arm64 (the x86_64 build is the same code and the same CI job):++- Static musl build of `host/` 2.2.0 started on Ubuntu 22.04, Debian 12, Amazon Linux 2023, Rocky Linux 9 and Alpine 3. `serve`, `status`, `pair --json`, `info` and `cloud` worked with no display.+- On a systemd container (Ubuntu 22.04, lingering user): `install` created and started the service, `pair` worked, a killed host was restarted by systemd with a new PID, and `uninstall` removed it and kept the data.+- The v2.1.0 glibc release failed on Ubuntu 22.04 and Debian 12 (`GLIBC_2.39 not found`). The workflow now builds musl for that reason.+- Host tests passed on Linux: 101 + 9 + 1.++Not covered: a real cloud provider VM, pairing a physical iPhone over Tailscale to a VM, and bot turns with signed-in agents on the VM (these need real credentials). Those use the same code paths as a Linux desktop.diff --git a/docs/reference/fixtures/README.md b/docs/reference/fixtures/README.mdindex 9f28786f..d2f30036 100644--- a/docs/reference/fixtures/README.md+++ b/docs/reference/fixtures/README.md@@ -13,7 +13,7 @@ cmp docs/reference/fixtures/remote-relay-vectors.json /tmp/codync-relay-vectors.Consumers:-- `host/src/crypto.rs` (`include_str!`)+- `host/src/remote/crypto.rs` (`include_str!`)- `kit/Tests/CodyncKitTests/RelayVectorsTests.swift`- `cloud/test/vectors.test.ts` and `cloud/test/relay.test.ts`diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.mdindex af9912a3..abee0dc2 100644--- a/docs/reference/remote-relay.md+++ b/docs/reference/remote-relay.md@@ -57,8 +57,8 @@ Shared deterministic [vectors](fixtures/remote-relay-vectors.json) and their [ge| --- | --- || Worker API / authentication / DO | `cloud/src/api.ts`, `auth.ts`, `relay.ts` || Cloud schema | `cloud/migrations/` |-| Host identity / crypto / channel | `host/src/identity.rs`, `crypto.rs`, `channel.rs` |-| Host cloud / relay | `host/src/cloud.rs`, `relay.rs` |+| Host identity / crypto / channel | `host/src/remote/identity.rs`, `crypto.rs`, `channel.rs` |+| Host cloud / relay | `host/src/remote/cloud.rs`, `relay.rs` || Swift transports / identity | `kit/Sources/CodyncKit/Client/` || Account and per-computer state | `kit/Sources/CodyncUI/` || Apple account integration | `apps/shared/AccountSession.swift` |@@ -178,7 +178,7 @@ codync://pair?v=3&name=<pct>&id=<computerId>&sk=<signPub>&bk=<boxPub>&code=<pair### 4.3 授權表與 ACL(host 為權威)-host 的授權裝置表(`host/src/devices.rs`)每一列:`key, name, platform, source(local|account), grant_id, scopes, lease_until`。+host 的授權裝置表(`host/src/api/devices.rs`)每一列:`key, name, platform, source(local|account), grant_id, scopes, lease_until`。規則(**雲端只能縮短授權,不能新增**):- 新增列只有兩條路:§4.1 的 `pair`(`source=local`,`grant_id=NULL`)與 §4.2 B 的 host 核准(`source=account`,`grant_id` = decision 回傳值,`key` = host 顯示給使用者的 dk)。@@ -484,7 +484,7 @@ The route table below summarizes the contract. Executable schema and validation## 9. Host integration-`host/src/api.rs` dispatches inner methods and enforces caller permissions. Bearer HTTP/SSE is loopback-only; remote callers use the encrypted channel. `host/src/cloud.rs` manages registration, claims, access state and grant revocation retries; `host/src/relay.rs` manages the outgoing relay connection. Inspect these implementations for current method signatures and storage keys.+`host/src/api/mod.rs` dispatches inner methods and enforces caller permissions. Bearer HTTP/SSE is loopback-only; remote callers use the encrypted channel. `host/src/remote/cloud.rs` manages registration, claims, access state and grant revocation retries; `host/src/remote/relay.rs` manages the outgoing relay connection. Inspect these implementations for current method signatures and storage keys.`codync-host cloud` reports cloud status; `devices` lists/revokes device access; `access` handles pending approval. `reset-token` rotates the local bearer credential, not remote device grants.