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
feat: ChatGPT and Claude give your bots tasks through the Codync connector
leepokai84948226a7b2
diff --git a/CLAUDE.md b/CLAUDE.mdindex d48c78cd..564e378b 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -30,7 +30,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess- Chat/session ownership, groups, collaboration, memory and visible-message rules: [conversation runtime](docs/architecture/conversation-runtime.md).- **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 with the bearer token (`~/.codync/token`) is **loopback only** (desktop app, SSH tunnel, local helpers). Phones and other remote clients use the E2E channel (`/channel` direct, or the Cloudflare relay). Default port **19222**.-- Remote access (Cloudflare relay primary, direct LAN/Tailscale alternative, accounts, SSH, public routine webhooks queued in the relay §7.8): [docs/reference/remote-relay.md](docs/reference/remote-relay.md).+- Remote access (Cloudflare relay primary, direct LAN/Tailscale alternative, accounts, SSH, public routine webhooks queued in the relay §7.8, the cloud assistant MCP connector at mcp.codync.dev §7.9): [docs/reference/remote-relay.md](docs/reference/remote-relay.md).- Remote screen (`host/src/screen/` is the reference): phones view/control the computer over WebRTC (hardware H.264, non-trickle SDP relayed by `screenOffer`, input on data channels `input` / `input-fast`); bots get the built-in `computer` MCP server (`codync-host mcp computer`, `host/src/mcp.rs`) when their `computer` flag is on; its tools run on the bundled cua-driver, which Codync Screen starts on macOS so its grants apply ([computer use](docs/features/computer-use.md)). Capture/input live in a helper on `~/.codync/screen.sock`: `apps/screen-macos` (macOS, launchd agent the desktop app registers via `SMAppService`, owns the TCC grants) or `apps/screen-linux` (`codync-screen`: portals + GStreamer, started by the host). On by default (Linux: only with a graphical session); `setScreenEnabled` is accepted only from loopback. An interactive phone takes over (bots may only look).- Multiple computers per account are future work, not a current priority: the product targets one computer. The multi-computer structure (`AccountStore`, `BotReference`) stays because relay/accounts/SSH build on it; don't extend or polish multi-computer features unless asked. Bots on the user's other computers reach each other through `codync-network` (`host/crates/network`, peer to peer over iroh, signed roster with an owner; `codync-host network`): [computer network](docs/features/computer-network.md).- Environments: `iOS Dev` / desktop `dist:*:dev` use the isolated Codync Dev app; `iOS` / `dist:*:main` retain production identities. Stop only the variant being rebuilt. Resource map, signing and diagnostics: [Dev app isolation](docs/guides/dev-app.md).diff --git a/cloud/README.md b/cloud/README.mdindex d3cde919..95987770 100644--- a/cloud/README.md+++ b/cloud/README.md@@ -7,6 +7,11 @@ Cloudflare Worker for accounts and the off-LAN relay (spec: [docs/reference/remo15-minute cron that expires requests and prunes nonces, a 5-minute cron that runs the release gatewhile a release waits behind GitHub's latest mark or the Homebrew tap trails it (`src/release-gate.ts`), and the public routinewebhook route `POST /v1/hooks/:computerId/:routineId` (spec §7.8). D1 schema: `migrations/` (later files rebuild some tables).+- **Cloud assistant connector** (`src/routes/assistant.ts`, spec §7.9): the MCP server at `mcp.codync.dev/mcp`+ (dev `dev-mcp.codync.dev`, same Worker) that ChatGPT, Claude and other MCP clients sign in to with the Codync+ account (Clerk OAuth, tokens bound to the connector URL); its tool calls go to the account's computers through+ their DOs (`src/host-calls.ts`), and only a computer that turned cloud assistants on answers them.+ Setup and checks: [docs/features/cloud-assistants.md](../docs/features/cloud-assistants.md).- **`ComputerRelay`** (`src/relay.ts`): one Durable Object per computer (SQLite storage, WebSocketHibernation). It admits device sockets against the host-signed ACL, forwards channel frames it can'tread, reports presence, holds the offline mailbox, and queues routine webhook deliveries (`hookbox`,@@ -64,6 +69,7 @@ npx wrangler deploy --env dev # → https://dev-api.codync.dev| `CLERK_ISSUER` | var | Clerk Frontend API URL; tokens must carry this `iss` || `CLERK_AUTHORIZED_PARTIES` | var, optional | comma-separated; a token with `azp` must match || `CLERK_JWT_KEY` | var, dev/e2e only | public key for networkless verification |+| `ASSISTANT_LIMITER` | rate limit binding | cloud assistant (MCP connector) requests per account, 120 per minute |`RELEASE_GATE_TOKEN` is a fine-grained token without expiry. If it's revoked, set a new one with`npx wrangler secret put RELEASE_GATE_TOKEN`: without a working token the release gate runs only afterdiff --git a/cloud/src/api.ts b/cloud/src/api.tsindex 5611363d..429d69ee 100644--- a/cloud/src/api.ts+++ b/cloud/src/api.ts@@ -6,6 +6,7 @@ import type { Ctx } from "./routes/common";export { ApiError, type Ctx } from "./routes/common";export * from "./routes/account";+export * from "./routes/assistant";export * from "./routes/host";export * from "./routes/relay";export * from "./routes/webhooks";diff --git a/cloud/src/auth.ts b/cloud/src/auth.tsindex e577ed7f..58ba6e36 100644--- a/cloud/src/auth.ts+++ b/cloud/src/auth.ts@@ -1,6 +1,8 @@-// Authentication: Clerk session JWTs (users) and Codync-Sig (host and device keys, spec §5).+// Authentication: Clerk session JWTs (users), Clerk OAuth access tokens (the cloud assistant, §7.9)+// and Codync-Sig (host and device keys, spec §5).import { verifyToken } from "@clerk/backend";+import { verifyMachineAuthToken } from "@clerk/backend/internal";import type { Env } from "./index";// ---- encoding ----@@ -131,3 +133,24 @@ export async function verifyClerk(req: Request, env: Env): Promise<ClerkUser | nreturn null;}}++/**+ * The Codync account behind a cloud assistant's OAuth access token, which Clerk issued as the+ * connector's authorization server for `audience` (the connector's URL) alone. Opaque tokens are+ * checked with Clerk, JWTs against its keys. `null` when the bearer token is missing or doesn't verify.+ */+export async function verifyAssistant(req: Request, env: Env, audience: string): Promise<string | null> {+ const auth = req.headers.get("Authorization") ?? "";+ if (!auth.startsWith("Bearer ")) return null;+ try {+ const r = await verifyMachineAuthToken(+ auth.slice(7).trim(),+ { audience, ...(env.CLERK_JWT_KEY ? { jwtKey: env.CLERK_JWT_KEY } : { secretKey: env.CLERK_SECRET_KEY }) },+ );+ if (r.errors || r.tokenType !== "oauth_token" || !("clientId" in r.data)) return null;+ const t = r.data;+ return !t.revoked && !t.expired && t.subject.startsWith("user_") ? t.subject : null;+ } catch {+ return null;+ }+}diff --git a/cloud/src/host-calls.ts b/cloud/src/host-calls.tsnew file mode 100644index 00000000..3c5152c1--- /dev/null+++ b/cloud/src/host-calls.ts@@ -0,0 +1,52 @@+// Calls the relay DO puts to its host and waits on, by id: the cloud assistant's tool calls (§7.9).+// One is open only while the request that asked is, so none keeps a sleeping DO awake.++import { randomId } from "./auth";++export interface Answer {+ ok: boolean;+ result?: unknown;+ error?: string;+ /** No answer: the host is gone, or didn't answer in time (an older host ignores the call). */+ code?: "offline" | "timeout";+}++const MAX_ERROR = 2000;++export class HostCalls {+ private readonly open = new Map<string, (a: Answer) => void>();++ ask(host: WebSocket, msg: Record<string, unknown>, ms: number): Promise<Answer> {+ const id = randomId("", 12);+ return new Promise((resolve) => {+ const timer = setTimeout(() => this.settle(id, { ok: false, code: "timeout" }), ms);+ this.open.set(id, (a) => {+ clearTimeout(timer);+ resolve(a);+ });+ try {+ host.send(JSON.stringify({ ...msg, id }));+ } catch {+ this.settle(id, { ok: false, code: "offline" });+ }+ });+ }++ /** `{"t":"assistant.result","id","ok","result"|"error"}` from the host. */+ answered(msg: Record<string, unknown>): void {+ if (typeof msg.id !== "string") return;+ const error = typeof msg.error === "string" ? msg.error.slice(0, MAX_ERROR) : "Refused";+ this.settle(msg.id, msg.ok === true ? { ok: true, result: msg.result } : { ok: false, error });+ }++ /** The host went away: nothing it was asked gets an answer. */+ offline(): void {+ for (const id of [...this.open.keys()]) this.settle(id, { ok: false, code: "offline" });+ }++ private settle(id: string, a: Answer): void {+ const done = this.open.get(id);+ this.open.delete(id);+ done?.(a);+ }+}diff --git a/cloud/src/index.ts b/cloud/src/index.tsindex 2b0241ee..f8420a83 100644--- a/cloud/src/index.ts+++ b/cloud/src/index.ts@@ -20,6 +20,8 @@ export interface Env {TURN_LIMITER?: RateLimit;/** Public routine webhook deliveries per sender IP and hook. */HOOK_LIMITER?: RateLimit;+ /** Cloud assistant (MCP connector) requests per account. */+ ASSISTANT_LIMITER?: RateLimit;CLERK_ISSUER: string;CLERK_SECRET_KEY?: string;/** dev / e2e only: networkless verification with this public key. */@@ -71,6 +73,12 @@ const routes: [string, RegExp, Handler][] = [["GET", /^\/v1\/relay\/device\/([^/]+)$/, api.relayDevice],["POST", /^\/v1\/webhooks\/clerk$/, api.clerkWebhook],["POST", new RegExp(`^/v1/hooks/${ID}/${ID}$`), api.routineHook],+ // The cloud assistant's MCP connector (mcp.codync.dev, §7.9).+ ["POST", /^\/mcp$/, api.mcp],+ ["GET", /^\/mcp$/, api.mcpStream],+ ["GET", /^\/\.well-known\/oauth-protected-resource(?:\/mcp)?$/, api.resourceMetadata],+ ["GET", /^\/\.well-known\/oauth-authorization-server$/, api.authServerMetadata],+ ["OPTIONS", /^\/(?:mcp|\.well-known\/oauth-[a-z-]+(?:\/mcp)?)$/, api.assistantPreflight],];export default {diff --git a/cloud/src/relay.ts b/cloud/src/relay.tsindex 50b0efde..fbe43446 100644--- a/cloud/src/relay.ts+++ b/cloud/src/relay.ts@@ -1,13 +1,14 @@// ComputerRelay: one Durable Object per computer (spec §7, §8.5).//// Presence, ciphertext forwarding between the host socket and device sockets, ACL admission, and the-// offline mailbox (device → host), and the queue of public routine webhook deliveries (§7.8). It never-// parses channel frames and never stores chat. Reached only through requests the Worker builds itself+// offline mailbox (device → host), the queue of public routine webhook deliveries (§7.8), and the cloud+// assistant's tool calls to the host (§7.9). It never parses channel frames and never stores chat. Reached only through requests the Worker builds itself// (`X-Codync-Internal: 1`), never a client's own request.import { DurableObject } from "cloudflare:workers";import { b64url, fromB64url, NONCE_TTL_MS, randomId, utf8, verifyEd25519 } from "./auth";import { authorized, deliveryId, forwarded, HOOK_ID, HOOK_MAX_BODY, parseHooks } from "./hooks";+import { HostCalls } from "./host-calls";import type { Env } from "./index";const MAX_DEVICE_SOCKETS = 16;@@ -29,6 +30,8 @@ const HOOK_PER_COMPUTER = 1000;const HOOK_MAX_BYTES = 16 * 1024 * 1024;const HOOK_RETRY_MIN_MS = 30_000;const HOOK_RETRY_MAX_MS = 15 * 60_000;+/** The host answers a cloud assistant's call at once; past this it's too old to know them, or stuck. */+const ASSISTANT_TIMEOUT_MS = 10_000;/** No ping for this long (both sides ping every 30 s): the socket is dead and gets closed. */const SILENT_TIMEOUT_MS = 90_000;const ALARM_MS = 60_000;@@ -118,6 +121,8 @@ export class ComputerRelay extends DurableObject<Env> {private readonly rates = new Map<string, { start: number; msgs: number; bytes: number }>();/** Sockets this instance retired. Hibernation drops it, so a socket still in it later means the DO never slept. */private readonly retiredHere = new WeakSet<WebSocket>();+ /** Cloud assistant calls waiting on the host. */+ private readonly calls = new HostCalls();constructor(ctx: DurableObjectState, env: Env) {super(ctx, env);@@ -145,6 +150,7 @@ export class ComputerRelay extends DurableObject<Env> {if (pathname === "/relay") return this.relay(req);if (pathname === "/internal/block" && req.method === "POST") return this.block(req);if (pathname === "/internal/hook" && req.method === "POST") return this.hook(req);+ if (pathname === "/internal/assistant" && req.method === "POST") return this.assistant(req);if (pathname === "/internal/changed" && req.method === "POST") {this.toHosts({ t: "cloud.changed" });return Response.json({});@@ -343,6 +349,18 @@ export class ComputerRelay extends DurableObject<Env> {);}+ // ---- the cloud assistant (§7.9) ----++ /** `POST /internal/assistant {user, tool, args}`: the host's answer, as an `Answer`. */+ private async assistant(req: Request): Promise<Response> {+ const body = (await req.json().catch(() => null)) as { user?: unknown; tool?: unknown; args?: unknown } | null;+ if (typeof body?.user !== "string" || typeof body.tool !== "string") return errorResponse(400, "badRequest");+ const host = this.readyHost();+ if (!host) return Response.json({ ok: false, code: "offline" }, { status: 503 });+ const call = { t: "assistant.call", user: body.user, tool: body.tool, args: body.args ?? {} };+ return Response.json(await this.calls.ask(host, call, ASSISTANT_TIMEOUT_MS));+ }+// ---- messages ----override async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {@@ -398,6 +416,8 @@ export class ComputerRelay extends DurableObject<Env> {return this.onHooks(ws, msg);case "hook.ack":return this.onHookAck(ws, msg, now);+ case "assistant.result":+ return this.calls.answered(msg);case "ping":return send(ws, PONG);default:@@ -650,6 +670,7 @@ export class ComputerRelay extends DurableObject<Env> {this.setMeta("lastSeenAt", String(now));this.sql.exec("UPDATE mailbox SET state = 'queued' WHERE state = 'delivering'");this.sql.exec("UPDATE hookbox SET state = 'queued' WHERE state = 'delivering'");+ this.calls.offline();if (!this.readyHost(exclude)) {const presence = JSON.stringify(this.presence(exclude));for (const [ws] of this.devices()) send(ws, presence);diff --git a/cloud/src/routes/assistant.ts b/cloud/src/routes/assistant.tsnew file mode 100644index 00000000..21cb2784--- /dev/null+++ b/cloud/src/routes/assistant.ts@@ -0,0 +1,286 @@+// The Codync connector for the user's cloud assistant (ChatGPT, Claude…) at mcp.codync.dev (§7.9): an MCP+// server over Streamable HTTP (JSON answers, no sessions, no server stream) for stateless clients+// (2026-07-28) and `initialize` ones alike. Clerk is its authorization server, so an assistant signs in+// with the Codync account and gets a token for this server's URL alone. Tool calls go to the account's computers over+// their relay sockets, and only a computer whose user turned cloud assistants on answers them. Unlike the+// device channel, the cloud sees these calls.++import type { Answer } from "../host-calls";+import { verifyAssistant } from "../auth";+import { ApiError, type Ctx } from "./common";++/** Newest first; the first takes no `initialize` (every request names its version). */+const PROTOCOLS = ["2026-07-28", "2025-11-25", "2025-06-18", "2025-03-26"];+const LEGACY = PROTOCOLS.slice(1);+const VERSION_KEY = "io.modelcontextprotocol/protocolVersion";+const SERVER_INFO = { name: "codync", title: "Codync", version: "2", websiteUrl: "https://codync.dev" };+/** The tool list is the same for everyone and changes only with a deploy. */+const TOOLS_TTL_MS = 3_600_000;+const SCOPES = ["profile", "email"];+const DOCS = "https://codync.dev/docs/cloud-assistants";++const INSTRUCTIONS =+ "Codync connects you to the user's own coding bots, running on their computers. Use list_bots to find one, " ++ "message_bot to give it a self-contained task, and read_replies to collect its answer. Bots work in their own " ++ "folders with their own tools and can take minutes: after messaging one, tell the user what you asked for and " ++ "check read_replies when they come back or ask, instead of waiting in a loop.";++const COMPUTER = {+ type: "string",+ description: "Which of the user's computers, by name from list_computers. Needed only when several are online.",+};++const TOOLS = [+ {+ name: "list_computers",+ title: "List computers",+ description: "The computers in the user's Codync account, and whether each is online.",+ inputSchema: { type: "object", properties: {} },+ annotations: { readOnlyHint: true, openWorldHint: false },+ },+ {+ name: "list_bots",+ title: "List bots",+ description:+ "The user's Codync bots you can message, with their IDs, specialties and status. Narrow it with query; it " ++ "returns at most limit at a time, with next for the rest. Without computer, every online computer answers.",+ inputSchema: {+ type: "object",+ properties: {+ query: { type: "string", description: "Words that must all appear in the bot's name or description." },+ limit: { type: "integer", minimum: 1, maximum: 50, description: "At most this many (default 20)." },+ cursor: { type: "string", description: "next from the previous call, for the rest." },+ computer: COMPUTER,+ },+ },+ annotations: { readOnlyHint: true, openWorldHint: false },+ },+ {+ name: "message_bot",+ title: "Message a bot",+ description:+ "Send a self-contained request to one of the user's Codync bots. It runs in that bot's own chat on the " ++ "user's computer, with the bot's tools, folder and permissions, and this returns as soon as it is queued. " ++ "Get the reply later with read_replies.",+ inputSchema: {+ type: "object",+ properties: {+ botId: { type: "string", description: "The bot's id from list_bots." },+ message: { type: "string", description: "The task, relevant context, file paths and the expected result." },+ computer: COMPUTER,+ },+ required: ["botId", "message"],+ },+ annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: false },+ },+ {+ name: "read_replies",+ title: "Read replies",+ description:+ "Your recent message_bot requests, newest first, with each bot's reply once it's done. status is queued, " ++ "sent (running), completed, failed or cancelled. Give requestId for one request.",+ inputSchema: {+ type: "object",+ properties: {+ requestId: { type: "string", description: "One request's id from message_bot." },+ computer: COMPUTER,+ },+ },+ annotations: { readOnlyHint: true, openWorldHint: false },+ },+];+const HOST_TOOLS = new Set(["list_bots", "message_bot", "read_replies"]);++const CORS = {+ "Access-Control-Allow-Origin": "*",+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",+ "Access-Control-Allow-Headers": "Authorization, Content-Type, Mcp-Protocol-Version, Mcp-Session-Id",+ "Access-Control-Expose-Headers": "WWW-Authenticate",+};++const json = (v: unknown, status = 200, headers: Record<string, string> = {}) =>+ Response.json(v, { status, headers: { ...CORS, ...headers } });++/** A tool's own failure: the assistant sees it as the tool's answer (`isError`). */+class ToolError extends Error {}++export const assistantPreflight = async () => new Response(null, { status: 204, headers: CORS });++/** Protected resource metadata (RFC 9728): Clerk issues the tokens. */+export const resourceMetadata = async (c: Ctx) =>+ json({+ resource: `${c.url.origin}/mcp`,+ authorization_servers: [c.env.CLERK_ISSUER],+ scopes_supported: SCOPES,+ bearer_methods_supported: ["header"],+ resource_name: "Codync",+ resource_documentation: DOCS,+ });++/** Clerk's own metadata, for clients that still look for it on this host. */+export async function authServerMetadata(c: Ctx) {+ const res = await fetch(`${c.env.CLERK_ISSUER}/.well-known/oauth-authorization-server`, { cf: { cacheTtl: 3600 } });+ if (!res.ok) throw new ApiError("internal", "The sign-in service didn't answer");+ return json(await res.json());+}++/** The account the request's token stands for, or `null` and the challenge that says where to sign in. */+async function signedIn(c: Ctx): Promise<[string, null] | [null, Response]> {+ const user = await verifyAssistant(c.req, c.env, `${c.url.origin}/mcp`);+ if (user) return [user, null];+ const metadata = `${c.url.origin}/.well-known/oauth-protected-resource/mcp`;+ const challenge = `Bearer resource_metadata="${metadata}", scope="${SCOPES.join(" ")}"`;+ return [null, json({ error: "invalid_token" }, 401, { "WWW-Authenticate": challenge })];+}++/** No server-to-client stream: everything is a POST with its JSON answer. */+export async function mcpStream(c: Ctx): Promise<Response> {+ const [, refused] = await signedIn(c);+ return refused ?? new Response(null, { status: 405, headers: { ...CORS, Allow: "POST" } });+}++export async function mcp(c: Ctx): Promise<Response> {+ const [user, refused] = await signedIn(c);+ if (refused) return refused;+ if (c.env.ASSISTANT_LIMITER && !(await c.env.ASSISTANT_LIMITER.limit({ key: user })).success) {+ return json({ error: "rate_limited" }, 429, { "Retry-After": "60" });+ }+ let msg: { id?: unknown; method?: unknown; params?: Record<string, unknown> };+ try {+ msg = JSON.parse(new TextDecoder().decode(c.raw));+ } catch {+ return json(failure(null, -32700, "Parse error"));+ }+ if (!msg || typeof msg !== "object" || Array.isArray(msg)) return json(failure(null, -32600, "Invalid request"));+ // A notification or a response: nothing to answer.+ if (msg.id === undefined || msg.method === undefined) return new Response(null, { status: 202, headers: CORS });+ const id = msg.id;+ const meta = msg.params?._meta as Record<string, unknown> | undefined;+ const version = meta?.[VERSION_KEY] ?? c.req.headers.get("MCP-Protocol-Version");+ if (msg.method !== "initialize" && typeof version === "string" && !PROTOCOLS.includes(version)) {+ return json(failure(id, -32022, "Unsupported protocol version", { supported: PROTOCOLS, requested: version }));+ }+ switch (msg.method) {+ case "server/discover":+ return json(+ success(id, {+ supportedVersions: PROTOCOLS,+ capabilities: { tools: {} },+ instructions: INSTRUCTIONS,+ ttlMs: TOOLS_TTL_MS,+ cacheScope: "public",+ }),+ );+ case "initialize": {+ const asked = msg.params?.protocolVersion;+ return json(+ success(id, {+ protocolVersion: typeof asked === "string" && LEGACY.includes(asked) ? asked : LEGACY[0],+ capabilities: { tools: {} },+ serverInfo: SERVER_INFO,+ instructions: INSTRUCTIONS,+ }),+ );+ }+ case "ping":+ return json(success(id, {}));+ case "tools/list":+ return json(success(id, { tools: TOOLS, ttlMs: TOOLS_TTL_MS, cacheScope: "public" }));+ case "tools/call": {+ const name = msg.params?.name;+ const args = msg.params?.arguments ?? {};+ if (typeof name !== "string" || !TOOLS.some((t) => t.name === name)) return json(failure(id, -32602, `Unknown tool: ${name}`));+ if (typeof args !== "object" || Array.isArray(args)) return json(failure(id, -32602, "arguments must be an object"));+ try {+ const result = await tool(c, user, name, args as Record<string, unknown>);+ return json(success(id, { content: [{ type: "text", text: JSON.stringify(result) }] }));+ } catch (e) {+ if (!(e instanceof ToolError)) throw e;+ return json(success(id, { content: [{ type: "text", text: e.message }], isError: true }));+ }+ }+ default:+ return json(failure(id, -32601, "Method not found"));+ }+}++/** Every result is complete (no follow-up rounds) and names this server. */+const success = (id: unknown, result: Record<string, unknown>) => ({+ jsonrpc: "2.0",+ id,+ result: { resultType: "complete", _meta: { "io.modelcontextprotocol/serverInfo": SERVER_INFO }, ...result },+});+const failure = (id: unknown, code: number, message: string, data?: unknown) => ({+ jsonrpc: "2.0",+ id,+ error: data === undefined ? { code, message } : { code, message, data },+});++interface Computer {+ id: string;+ name: string;+ online: number;+ last_seen_at: number | null;+}++async function tool(c: Ctx, user: string, name: string, args: Record<string, unknown>): Promise<unknown> {+ const { results: all } = await c.env.DB.prepare(+ "SELECT id, name, online, last_seen_at FROM computers WHERE owner_user_id = ? AND status = 'active' ORDER BY claimed_at",+ )+ .bind(user)+ .all<Computer>();+ if (name === "list_computers") {+ return { computers: all.map((x) => ({ name: x.name, online: !!x.online, lastSeenAt: x.last_seen_at })) };+ }+ if (!all.length) throw new ToolError("No computer is in this Codync account yet: sign in to Codync on a computer first.");+ if (!HOST_TOOLS.has(name)) throw new ToolError(`Unknown tool: ${name}`);+ const { computer: wanted, ...rest } = args;+ const online = all.filter((x) => x.online);+ // Every online computer answers a listing that names none.+ if (wanted === undefined && name !== "message_bot" && online.length > 1) {+ return {+ computers: await Promise.all(+ online.map((x) =>+ ask(c, x, user, name, rest).then(+ (result) => ({ computer: x.name, ...(result as object) }),+ (e: Error) => ({ computer: x.name, error: e.message }),+ ),+ ),+ ),+ };+ }+ return ask(c, pick(all, online, wanted), user, name, rest);+}++function pick(all: Computer[], online: Computer[], wanted: unknown): Computer {+ const names = (list: Computer[]) => list.map((x) => x.name).join(", ");+ if (typeof wanted === "string" && wanted) {+ const hit = all.find((x) => x.name.toLowerCase() === wanted.toLowerCase() || x.id === wanted);+ if (!hit) throw new ToolError(`No computer called ${wanted} in this account: ${names(all)}.`);+ return hit;+ }+ if (all.length === 1) return all[0]!;+ if (online.length === 1) return online[0]!;+ throw new ToolError(+ online.length ? `Say which computer: ${names(online)}.` : `None of the user's computers is online: ${names(all)}.`,+ );+}++async function ask(c: Ctx, computer: Computer, user: string, tool: string, args: Record<string, unknown>): Promise<unknown> {+ const res = await c.env.RELAY.get(c.env.RELAY.idFromName(computer.id)).fetch(+ new Request("https://do/internal/assistant", {+ method: "POST",+ headers: { "X-Codync-Internal": "1" },+ body: JSON.stringify({ user, tool, args }),+ }),+ );+ const a = (await res.json()) as Answer;+ if (a.ok) return a.result;+ if (a.code === "offline") throw new ToolError(`${computer.name} is offline: Codync isn't running there, or it can't reach the internet.`);+ if (a.code === "timeout") {+ throw new ToolError(+ `${computer.name} didn't answer. Its Codync may be too old for cloud assistants: update it, then turn them on there (codync-host cloud --assistants on).`,+ );+ }+ throw new ToolError(a.error ?? "Refused");+}diff --git a/cloud/test/assistant.test.ts b/cloud/test/assistant.test.tsnew file mode 100644index 00000000..fd9f5596--- /dev/null+++ b/cloud/test/assistant.test.ts@@ -0,0 +1,171 @@+// The cloud assistant's MCP connector (§7.9): OAuth discovery, token checks, MCP methods and tool calls+// that reach the account's computers over their relay sockets.++import { SELF } from "cloudflare:test";+import { describe, expect, it } from "vitest";+import { HostCalls } from "../src/host-calls";+import { clerkToken, env, hostSocket, newHost, ORIGIN, type Json, type Sock, type TestHost } from "./helpers";++const oauthToken = (sub: string, aud = `${ORIGIN}/mcp`) =>+ clerkToken(sub, { aud, client_id: "https://assistant.example/client.json", scope: "profile email", jti: "oat_test" }, "at+jwt");++let next = 0;+async function rpc(token: string | null, method: string, params?: unknown) {+ const res = await SELF.fetch(`${ORIGIN}/mcp`, {+ method: "POST",+ headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream", ...(token ? { Authorization: `Bearer ${token}` } : {}) },+ body: JSON.stringify({ jsonrpc: "2.0", id: ++next, method, params }),+ });+ return { status: res.status, headers: res.headers, body: res.status === 200 ? ((await res.json()) as Json) : null };+}++/** A tool call's answer: the parsed result, or the error text the assistant sees. */+async function callTool(token: string, name: string, args: Record<string, unknown> = {}) {+ const r = await rpc(token, "tools/call", { name, arguments: args });+ const { content, isError } = r.body.result;+ return isError ? { error: content[0].text as string } : { result: JSON.parse(content[0].text) as Json };+}++/** A registered computer owned by `userId`, named `name`. */+async function owned(userId: string, name: string): Promise<TestHost> {+ const host = await newHost();+ await env.DB.batch([+ env.DB.prepare("INSERT OR IGNORE INTO accounts(user_id, email, created_at) VALUES (?, NULL, ?)").bind(userId, Date.now()),+ env.DB.prepare("UPDATE computers SET owner_user_id = ?, name = ?, claimed_at = ? WHERE id = ?").bind(userId, name, Date.now(), host.cid),+ ]);+ return host;+}++/** The host answers the next cloud assistant call with `answer`; returns the call it got. */+async function answers(ws: Sock, answer: Record<string, unknown>): Promise<Json> {+ const call = await ws.nextT("assistant.call");+ ws.send({ t: "assistant.result", id: call.id, ...answer });+ return call;+}++describe("discovery and sign-in", () => {+ it("points assistants at Clerk to sign in", async () => {+ for (const path of ["/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp"]) {+ const meta = (await (await SELF.fetch(ORIGIN + path)).json()) as Json;+ expect(meta.resource).toBe(`${ORIGIN}/mcp`);+ expect(meta.authorization_servers).toEqual([env.CLERK_ISSUER]);+ }+ const preflight = await SELF.fetch(`${ORIGIN}/mcp`, { method: "OPTIONS" });+ expect(preflight.status).toBe(204);+ expect(preflight.headers.get("Access-Control-Allow-Headers")).toContain("Authorization");+ });++ it("refuses a missing token, an app session token and one for another server, with the metadata's address", async () => {+ for (const token of [null, await clerkToken("user_session"), await oauthToken("user_session", "https://elsewhere.example/mcp")]) {+ const r = await rpc(token, "tools/list");+ expect(r.status).toBe(401);+ expect(r.headers.get("WWW-Authenticate")).toBe(+ `Bearer resource_metadata="${ORIGIN}/.well-known/oauth-protected-resource/mcp", scope="profile email"`,+ );+ }+ });++ it("serves stateless clients", async () => {+ const token = await oauthToken("user_modern");+ const meta = { _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } };+ const found = (await rpc(token, "server/discover", meta)).body.result;+ expect(found).toMatchObject({ resultType: "complete", supportedVersions: expect.arrayContaining(["2026-07-28"]), capabilities: { tools: {} } });+ expect(found._meta["io.modelcontextprotocol/serverInfo"].name).toBe("codync");+ const listed = (await rpc(token, "tools/list", meta)).body.result;+ expect(listed).toMatchObject({ resultType: "complete", cacheScope: "public", ttlMs: expect.any(Number) });+ const old = await rpc(token, "tools/list", { _meta: { "io.modelcontextprotocol/protocolVersion": "1900-01-01" } });+ expect(old.body.error).toMatchObject({ code: -32022, data: { requested: "1900-01-01", supported: expect.arrayContaining(["2026-07-28"]) } });+ });++ it("answers initialize, ping and tools/list, and takes notifications", async () => {+ const token = await oauthToken("user_init");+ const init = await rpc(token, "initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "t", version: "1" } });+ expect(init.body.result.protocolVersion).toBe("2025-06-18");+ expect(init.body.result.capabilities).toEqual({ tools: {} });+ expect((await rpc(token, "initialize", { protocolVersion: "1999-01-01" })).body.result.protocolVersion).toBe("2025-11-25");+ expect((await rpc(token, "ping")).body.result.resultType).toBe("complete");+ const tools = (await rpc(token, "tools/list")).body.result.tools.map((t: Json) => t.name);+ expect(tools).toEqual(["list_computers", "list_bots", "message_bot", "read_replies"]);+ const note = await SELF.fetch(`${ORIGIN}/mcp`, {+ method: "POST",+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },+ body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }),+ });+ expect(note.status).toBe(202);+ expect((await rpc(token, "tools/call", { name: "rm_rf" })).body.error.code).toBe(-32602);+ expect((await rpc(token, "resources/list")).body.error.code).toBe(-32601);+ expect((await SELF.fetch(`${ORIGIN}/mcp`)).status).toBe(401);+ expect((await SELF.fetch(`${ORIGIN}/mcp`, { headers: { Authorization: `Bearer ${token}` } })).status).toBe(405);+ });+});++describe("tool calls", () => {+ it("reach the account's computer and pass its answer or refusal back", async () => {+ const token = await oauthToken("user_one");+ expect((await callTool(token, "list_bots")).error).toContain("No computer is in this Codync account");+ const host = await owned("user_one", "desk");+ expect((await callTool(token, "list_computers")).result.computers).toEqual([{ name: "desk", online: false, lastSeenAt: null }]);+ expect((await callTool(token, "list_bots")).error).toBe("desk is offline: Codync isn't running there, or it can't reach the internet.");++ const ws = await hostSocket(host);+ const listing = callTool(token, "list_bots", { query: "review" });+ const call = await answers(ws, { ok: true, result: { bots: [{ id: "b1", name: "Reviewer" }], total: 1 } });+ expect(call).toMatchObject({ t: "assistant.call", user: "user_one", tool: "list_bots", args: { query: "review" } });+ expect((await listing).result).toEqual({ bots: [{ id: "b1", name: "Reviewer" }], total: 1 });++ const refused = callTool(token, "message_bot", { botId: "b1", message: "hi" });+ await answers(ws, { ok: false, error: "Cloud assistants are off on this computer." });+ expect((await refused).error).toBe("Cloud assistants are off on this computer.");++ // Another account's token never reaches this computer.+ expect((await callTool(await oauthToken("user_other"), "list_bots")).error).toContain("No computer");+ ws.ws.close();+ });++ it("asks every online computer for a listing, and which one for a message", async () => {+ const token = await oauthToken("user_two");+ const desk = await hostSocket(await owned("user_two", "desk"));+ const laptop = await hostSocket(await owned("user_two", "laptop"));+ await owned("user_two", "server");+ await expect.poll(async () => (await callTool(token, "list_computers")).result.computers.filter((c: Json) => c.online).length).toBe(2);++ const listing = callTool(token, "list_bots");+ await answers(desk, { ok: true, result: { bots: [{ id: "d" }] } });+ await answers(laptop, { ok: false, error: "Cloud assistants are off on this computer." });+ expect((await listing).result.computers).toEqual(+ expect.arrayContaining([+ { computer: "desk", bots: [{ id: "d" }] },+ { computer: "laptop", error: "Cloud assistants are off on this computer." },+ ]),+ );+ expect((await callTool(token, "message_bot", { botId: "d", message: "hi" })).error).toBe("Say which computer: desk, laptop.");+ expect((await callTool(token, "message_bot", { botId: "d", message: "hi", computer: "nas" })).error).toBe(+ "No computer called nas in this account: desk, laptop, server.",+ );+ const sent = callTool(token, "message_bot", { botId: "d", message: "hi", computer: "Laptop" });+ const call = await answers(laptop, { ok: true, result: { requestId: "r1" } });+ expect(call.args).toEqual({ botId: "d", message: "hi" });+ expect((await sent).result).toEqual({ requestId: "r1" });+ desk.ws.close();+ laptop.ws.close();+ });++ it("ends a call whose host goes away", async () => {+ const token = await oauthToken("user_gone");+ const ws = await hostSocket(await owned("user_gone", "desk"));+ const listing = callTool(token, "list_bots");+ await ws.nextT("assistant.call");+ ws.ws.close();+ expect((await listing).error).toContain("desk is offline");+ });+});++describe("host calls", () => {+ it("time out when the host never answers (an older host ignores them)", async () => {+ const sent: string[] = [];+ const calls = new HostCalls();+ const answer = await calls.ask({ send: (m: string) => sent.push(m) } as unknown as WebSocket, { t: "assistant.call" }, 20);+ expect(answer).toEqual({ ok: false, code: "timeout" });+ expect(JSON.parse(sent[0]!)).toMatchObject({ t: "assistant.call", id: expect.any(String) });+ });+});diff --git a/cloud/test/helpers.ts b/cloud/test/helpers.tsindex d1ce8d72..4dbd71f0 100644--- a/cloud/test/helpers.ts+++ b/cloud/test/helpers.ts@@ -18,9 +18,11 @@ export const ORIGIN = `https://${AUTHORITY}`;let clerkKey: Promise<CryptoKey> | undefined;+/** A Clerk session token, or with `typ: "at+jwt"` an OAuth access token Clerk issued to a cloud assistant. */export async function clerkToken(sub: string,claims: Record<string, unknown> = {},+ typ = "JWT",): Promise<string> {clerkKey ??= crypto.subtle.importKey("jwk",@@ -31,7 +33,7 @@ export async function clerkToken();const now = Math.floor(Date.now() / 1000);const part = (v: unknown) => b64url(enc.encode(JSON.stringify(v)));- const head = `${part({ alg: "RS256", typ: "JWT", kid: "ins_test" })}.${part({+ const head = `${part({ alg: "RS256", typ, kid: "ins_test" })}.${part({iss: env.CLERK_ISSUER,sub,sid: `sess_${sub}`,diff --git a/cloud/wrangler.toml b/cloud/wrangler.tomlindex 58e731d2..1bd5ddf9 100644--- a/cloud/wrangler.toml+++ b/cloud/wrangler.toml@@ -3,8 +3,9 @@ main = "src/index.ts"compatibility_date = "2026-09-01"compatibility_flags = ["nodejs_compat"]-# main: production at api.codync.dev (Clerk production instance)-routes = [{ pattern = "api.codync.dev", custom_domain = true }]+# main: production at api.codync.dev (Clerk production instance); mcp.codync.dev is the cloud assistant's+# MCP connector (src/routes/assistant.ts), served by the same Worker.+routes = [{ pattern = "api.codync.dev", custom_domain = true }, { pattern = "mcp.codync.dev", custom_domain = true }][[migrations]]tag = "v1"@@ -41,19 +42,25 @@ name = "HOOK_LIMITER"namespace_id = "1021"simple = { limit = 60, period = 60 }+# Cloud assistant (MCP connector) requests per account (POST /mcp).+[[ratelimits]]+name = "ASSISTANT_LIMITER"+namespace_id = "1031"+simple = { limit = 120, period = 60 }+# Sweep expired requests and nonces; wake the release gate (src/release-gate.ts).# src/index.ts routes on these exact strings (SWEEP_CRON, RELEASE_GATE_CRON): change both together.[triggers]crons = ["*/15 * * * *", "*/5 * * * *"]-# dev: the deployed test environment at dev-api.codync.dev (Clerk development instance).+# dev: the deployed test environment at dev-api.codync.dev and dev-mcp.codync.dev (Clerk development instance).[env.dev]name = "codync-cloud-dev"-routes = [{ pattern = "dev-api.codync.dev", custom_domain = true }]+routes = [{ pattern = "dev-api.codync.dev", custom_domain = true }, { pattern = "dev-mcp.codync.dev", custom_domain = true }]vars = { CLERK_ISSUER = "https://sunny-mollusk-8651.clerk.accounts.dev" }d1_databases = [{ binding = "DB", database_name = "codync-dev", database_id = "0c03c398-3cec-4f06-a76e-998176ca19ae", migrations_dir = "migrations" }]durable_objects.bindings = [{ name = "RELAY", class_name = "ComputerRelay" }]-ratelimits = [{ name = "REGISTER_LIMITER", namespace_id = "1002", simple = { limit = 10, period = 60 } }, { name = "TURN_LIMITER", namespace_id = "1012", simple = { limit = 12, period = 60 } }, { name = "HOOK_LIMITER", namespace_id = "1022", simple = { limit = 60, period = 60 } }]+ratelimits = [{ name = "REGISTER_LIMITER", namespace_id = "1002", simple = { limit = 10, period = 60 } }, { name = "TURN_LIMITER", namespace_id = "1012", simple = { limit = 12, period = 60 } }, { name = "HOOK_LIMITER", namespace_id = "1022", simple = { limit = 60, period = 60 } }, { name = "ASSISTANT_LIMITER", namespace_id = "1032", simple = { limit = 120, period = 60 } }]triggers = { crons = ["*/15 * * * *"] }# local: wrangler dev / e2e with a local D1; CLERK_JWT_KEY is injected by the test (--var).@@ -63,4 +70,4 @@ routes = []vars = { CLERK_ISSUER = "https://clerk.test.local" }d1_databases = [{ binding = "DB", database_name = "codync-local", database_id = "local", migrations_dir = "migrations" }]durable_objects.bindings = [{ name = "RELAY", class_name = "ComputerRelay" }]-ratelimits = [{ name = "REGISTER_LIMITER", namespace_id = "1003", simple = { limit = 10, period = 60 } }, { name = "TURN_LIMITER", namespace_id = "1013", simple = { limit = 12, period = 60 } }, { name = "HOOK_LIMITER", namespace_id = "1023", simple = { limit = 60, period = 60 } }]+ratelimits = [{ name = "REGISTER_LIMITER", namespace_id = "1003", simple = { limit = 10, period = 60 } }, { name = "TURN_LIMITER", namespace_id = "1013", simple = { limit = 12, period = 60 } }, { name = "HOOK_LIMITER", namespace_id = "1023", simple = { limit = 60, period = 60 } }, { name = "ASSISTANT_LIMITER", namespace_id = "1033", simple = { limit = 120, period = 60 } }]diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.mdindex 0c41feba..bafb5223 100644--- a/docs/architecture/file-structure.md+++ b/docs/architecture/file-structure.md@@ -113,6 +113,7 @@ Codync/| Desktop local host / SSH lifecycle | `apps/desktop/src/main/host-controller.ts`, `ssh.ts` || Desktop store, chat and controls | `apps/desktop/src/renderer/store/bot-store.ts` (actions; state in `bot-mirror.ts`, events stream in `bot-sync.ts`), `views/thread/`, `components/` || Cloud routes / authentication / relay | `cloud/src/index.ts`, `api.ts`, `routes/`, `auth.ts`, `relay.ts` |+| Cloud assistants (the MCP connector at mcp.codync.dev) | `cloud/src/routes/assistant.ts` (MCP, OAuth metadata, routing to computers), `host-calls.ts` (the relay DO's calls to its host); `host/src/chat/team/assistant.rs` (the switch, the tools, the replies) || Push encryption / APNs delivery / decryption | `host/src/remote/push.rs`, `relay/src/`, `apps/ios/NotificationService/` || Widget and activity rendering | `apps/ios/Kit/Sources/CodyncKit/Design/`, `apps/ios/Widgets/` || Android screens (one file per iOS view: `BotListView.kt`, `ChatScreen.kt`, `BotDetailsView.kt` (+ `BotSettingsForm.kt`, `BotTemplateView.kt`), `PairingView.kt`, `SettingsView.kt`, …) | `apps/android/app/src/main/kotlin/com/codync/android/` |diff --git a/docs/features/cloud-assistants.md b/docs/features/cloud-assistants.mdnew file mode 100644index 00000000..7d1f41bc--- /dev/null+++ b/docs/features/cloud-assistants.md@@ -0,0 +1,72 @@+# Cloud assistants (the Codync MCP connector)++A hosted assistant the user already talks to (ChatGPT, Claude on the web or phone, any MCP client) adds Codync as+a connector at `https://mcp.codync.dev/mcp`, signs in with the Codync account, and can then list the user's bots,+give one a task and read its reply. The bots run on the user's computers as always; the assistant reaches them+through the Codync cloud over the computer's relay socket, like public routine webhooks+([relay reference §7.9](../reference/remote-relay.md#79-cloud-assistantmcp-connector)).++## How it works++```+ChatGPT / Claude ──MCP over HTTPS──▶ mcp.codync.dev (cloud Worker)+ │ OAuth: Clerk issues a token for this URL, bound to the Codync account+ ▼+ the account's computer's relay DO ──assistant.call──▶ codync-host+ ◀─assistant.result── (answers only if turned on)+```++- **Sign-in**: Clerk is the authorization server; the Worker is only the protected resource. The connector's+ 401 names its metadata (`/.well-known/oauth-protected-resource/mcp`), which points at Clerk. Clients register+ with a Client ID Metadata Document (CIMD: ChatGPT and Claude do); dynamic registration (DCR) stays off, the+ MCP spec deprecates it. Tokens are JWTs with `aud` = the connector URL, and the Worker accepts no other+ audience, so a token Clerk issued for something else never works here.+- **Protocol**: Streamable HTTP with JSON answers and no sessions. Stateless clients (2026-07-28: version in each+ request's `_meta`, `server/discover`) and `initialize` clients (2025-03-26 to 2025-11-25) both work.+- **Tools**: `list_computers` (from the account, answered by the Worker), and `list_bots`, `message_bot`,+ `read_replies`, answered by the host. With several computers online, a listing asks each; a message needs+ `computer` then. `message_bot` returns at once; the bot's reply waits on the host for `read_replies`, since+ nothing can wake a hosted assistant.+- **Host** (`host/src/chat/team/assistant.rs`): the assistant messages bots like a bot does+ (`Back::Assistant`): the bot's chat shows "Message from Cloud assistant" and the reply is kept in memory (the+ newest 50 requests, at most 16 running) until read. Only this computer's bots: bots on the user's other+ computers in its network aren't reachable through the connector yet.++## Who can get in++The cloud sees these calls in plain text, and a bot can run anything on its computer, so the computer decides:++- **Off by default.** `codync-host cloud --assistants on` (local API `setAssistants`, loopback only) turns it on+ for one computer; the setting is the `assistants` field of `cloudStatus`. There's no app switch yet.+- **Only the computer's own account.** The Worker routes a call only to computers the token's account owns, and+ the host checks the call's account against its owner again.+- **Not on a private relay**: it has no accounts, so the host ignores `assistant.call` there.+- Revoking: turn it off on the computer, or remove the connector's access in the Codync account (Clerk).++## Configuration++| Where | What |+|---|---|+| `cloud/wrangler.toml` | custom domains `mcp.codync.dev` (main) and `dev-mcp.codync.dev` (dev) on the same Worker; `ASSISTANT_LIMITER` 120 requests per account per minute |+| Clerk (each instance) | Agents → MCP server: the connector URL (`https://mcp.codync.dev/mcp`, dev `https://dev-mcp.codync.dev/mcp`) with public clients allowed. OAuth applications → Settings: CIMD on (any compatible client), DCR off, PKCE required, JWT access tokens with audience |+| Cloudflare zone | the configuration rule "API hosts: no Browser Integrity Check" lists both MCP hosts: assistants' servers call without a browser user agent |++Clerk's MCP server page re-runs its public checks (401 challenge with scopes, resource metadata, discovery); all+pass on both instances. A local check of a deployment:+`curl -i https://mcp.codync.dev/mcp` → `401` with `WWW-Authenticate: Bearer resource_metadata=…, scope=…`.++## Verification++- `cloud/test/assistant.test.ts`: discovery, token checks (missing, app session, other audience), both protocol+ eras, routing to one or several computers, refusals, a host going away; `HostCalls` timing out.+- `host/src/chat/team/assistant/tests.rs`: the switch, the account check, a real bot turn and `read_replies`.+- End to end (dev, 2026-10-26): a scratch host claimed by the Clerk test user `[email protected]`+ (code `424242`), assistants on; an OAuth client run with the dev test client "Codync MCP e2e" (public, redirect+ `http://127.0.0.1:8976/callback`) signed in on Clerk's page, got an `at+jwt` for `https://dev-mcp.codync.dev/mcp`,+ and listed the computer and its bots, messaged a Claude bot and read its reply ("pong").++## Not yet++- An app switch for cloud assistants (desktop, iPhone, Android, TUI); the CLI is the only way to turn it on.+- Bots on the user's other computers through the connector's computer (codync-network).+- Notifying the assistant when a reply is ready (MCP has no way to wake a hosted assistant).diff --git a/docs/features/computer-network.md b/docs/features/computer-network.mdindex 42f5f780..31590072 100644--- a/docs/features/computer-network.md+++ b/docs/features/computer-network.md@@ -67,7 +67,8 @@ that was off learns of a removal.- One network per computer; the `.network` address suffix comes with several.- Shared networks (other people's computers) need the per-network list of offered bots and inbound rules first.- Bots can't reach Claude Code or Codex sessions on another computer through the host (the standalone daemon can).-- No MCP connector door for hosted assistants yet.+- The cloud assistant connector ([cloud assistants](cloud-assistants.md)) reaches only the bots of the computer it+ talks to, not that computer's network.## Code and verificationdiff --git a/docs/guides/environments-and-deployment.md b/docs/guides/environments-and-deployment.mdindex 89283213..f7c2c7ae 100644--- a/docs/guides/environments-and-deployment.md+++ b/docs/guides/environments-and-deployment.md@@ -20,6 +20,7 @@ The environment is chosen when building, never stored: the host compiles in its- **Development:** app configuration and Worker configuration target `https://dev-api.codync.dev`; dev Clerk issuer and D1 binding are configured in source. Exercise the live path before claiming readiness.- **Production:** `main.plist` targets `https://api.codync.dev` with the Clerk production instance (`clerk.codync.dev`, Google sign-in through the `codync-auth` Google Cloud project, published). The root Worker is deployed with D1 `codync`, `CLERK_SECRET_KEY` and `CLERK_WEBHOOK_SECRET` (Clerk webhook endpoint `https://api.codync.dev/v1/webhooks/clerk`, `user.deleted`), and `RELEASE_GATE_TOKEN` (dispatches the release gate; renewal in the [cloud README](../../cloud/README.md)).+- **Cloud assistants (MCP connector):** the Worker also serves `mcp.codync.dev` (main) and `dev-mcp.codync.dev` (dev), deployed 2026-10-26. Each Clerk instance lists its URL under Agents → MCP server (public checks pass) with CIMD on and DCR off, and the zone's "no Browser Integrity Check" rule covers both hosts ([cloud assistants](../features/cloud-assistants.md)).- **Local:** Wrangler's `local` environment supports the isolated integration test and its test issuer. It is not a real Google sign-in test.## Troubleshooting: a running host appears offline on another computerdiff --git a/docs/guides/user-docs.md b/docs/guides/user-docs.mdindex a145afe6..5e2d40d6 100644--- a/docs/guides/user-docs.md+++ b/docs/guides/user-docs.md@@ -23,6 +23,7 @@ the change.| `conversations` | Messages, files, approval cards, stop, replies, reactions, commands, fresh conversations, notifications | [chat messages](../features/chat-messages.md), [file attachments](../features/file-attachments.md), [context and memory](../features/context-and-memory.md), [notifications](../design/push-and-live-activity.md) || `groups` | Group chats | [groups and replies](../features/groups-and-replies.md) || `teamwork` | Bots messaging bots, bots on your other computers, Manage the team | [bot collaboration](../features/bot-collaboration.md), [computer network](../features/computer-network.md) |+| `cloud-assistants` | The MCP connector for ChatGPT, Claude and other assistants: turning it on, adding it, what it can do, privacy | [cloud assistants](../features/cloud-assistants.md) || `routines` | Schedules, webhooks, runs | [routines](../features/routines.md) || `artifacts` | Artifacts, the Library | [artifacts](../features/artifacts.md) || `memory` | Layers, dreaming, the agent's own memory | [context and memory](../features/context-and-memory.md), [bot memory](../design/bot-memory.md) |diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.mdindex cd009656..ce6df0fa 100644--- a/docs/reference/remote-relay.md+++ b/docs/reference/remote-relay.md@@ -377,6 +377,7 @@ Host → DO:| `mbox.ack` | `seq`, `ok`(bool), `code`(`ok:false` 時:`unauthorized`/`unknownBot`/`invalid`) | 刪除 mailbox 項目,通知發送裝置 `mbox.delivered` 或 `mbox.failed` || `hooks` | `hooks`:`[{"id","key","enabled"}]`(完整集合,≤ 1000) | 取代 DO 存的 webhook 集合(§7.8);格式錯誤 → `{"t":"error","code":"badHooks"}` 且保留舊集合。成功 → `{"t":"hooks.ok","n"}` || `hook.ack` | `seq`, `ok`(bool), `retry`(bool), `code` | `ok` 或 `retry:false` → 刪除;`retry:true` → 退回 queued,`not_before = now + min(30 s·2^attempts, 15 min)` |+| `assistant.result` | `id`, `ok`(bool), `result` 或 `error` | 回答同 `id` 的 `assistant.call`(§7.9);沒有等待中的 `id` 就忽略 || `ping` | — | auto-response |DO → Host:@@ -388,6 +389,7 @@ DO → Host:| `close` | `link`(device 斷線) || `mbox.item` | `seq`, `from`(dk), `nonce`(clientNonce), `d`(blob b64url), `exp` || `hook.item` | `seq`, `hook`(routine id), `delivery`, `headers`(白名單,小寫名), `body`(b64url), `at` |+| `assistant.call` | `id`, `user`(Clerk user id), `tool`(`list_bots`/`message_bot`/`read_replies`), `args`(§7.9) || `hooks.ok` | `n` || `cloud.changed` | —(Worker 通知:請立刻拉 `/v1/host/state`) || `acl.ok` / `error` | 見上 |@@ -457,6 +459,17 @@ Close code 總表:`1000` 正常、`1011` 內部錯誤/逾時、`4001 unautho- **Host 處理**(`routines::hooks`):驗證 → GitHub `ping` 回 ok 不執行 → 暫停回 `paused` → 轉成 event(JSON 物件原樣;GitHub → `{source:"github", event:"<event>.<action>", repo, sender, text, url, payload}`;其他 → `{text}`)→ trigger 不符回 ok(忽略)→ 排入 run。routine 正在執行 → `retry:true`。- **信任邊界**:webhook 內容在 Cloudflare 以 HTTPS 解開,雲端看得到明文,也存著 key(用來驗 HMAC)。這不是 §6 的端對端加密;App 與文件都需明講。+### 7.9 Cloud assistant(MCP connector)++讓使用者已在用的雲端助理(ChatGPT、Claude 等 MCP client)以 Codync 帳號登入後,列出、指派並讀回使用者的 bot。設計與設定:[cloud assistants](../features/cloud-assistants.md)。++- **網址**:`https://mcp.codync.dev/mcp`(dev:`dev-mcp.codync.dev`),同一個 Worker 的 custom domain(`cloud/src/routes/assistant.ts`)。Streamable HTTP,只用 POST 與 JSON 回應,無 session、無 server stream(`GET /mcp`:未登入 `401`,登入 `405`)。同時服務 2026-07-28 無狀態 client(`_meta` 帶版本、`server/discover`、不支援的版本 → `-32022`)與 `initialize` client(2025-03-26~2025-11-25)。+- **登入**:Clerk 是 authorization server,Worker 只是 protected resource。未帶有效 token → `401`,`WWW-Authenticate: Bearer resource_metadata="<origin>/.well-known/oauth-protected-resource/mcp", scope="profile email"`;metadata 指向 Clerk issuer(`/.well-known/oauth-authorization-server` 也代轉 Clerk 的,給舊 client)。Client 以 CIMD 註冊(DCR 關閉)。Token 必須是 Clerk 發的 OAuth access token(`at+jwt`,或 opaque 時向 Clerk 驗),`aud` 必須等於 `<origin>/mcp`;App 的 session token 不算。`ASSISTANT_LIMITER`:每帳號每分鐘 120 次。+- **路由**:Worker 只把呼叫送到 token 帳號擁有、`active` 的 computer。`list_computers` 由 Worker 從 D1 回答;其餘工具:指定 `computer`(名稱或 id)→ 該台;未指定時帳號只有一台、或只有一台在線 → 該台;`list_bots`/`read_replies` 在多台在線時每台都問並合併成 `{computers:[{computer, …}]}`;`message_bot` 則要求指定。+- **DO**:`POST /internal/assistant {user, tool, args}` → host 不在線 `503 {"ok":false,"code":"offline"}`;否則送 `assistant.call`,在 request 存活期間等同 `id` 的 `assistant.result`,最多 10 秒(逾時 `{"ok":false,"code":"timeout"}`,舊 host 會忽略這個訊息)。host 斷線時等待中的呼叫一律 `offline`。只在 request 存活時佔用 DO,不排隊、不存任何內容。+- **Host**(`chat::team::assistant`):預設關閉,`setAssistants`(loopback only,`codync-host cloud --assistants on|off`)才開;`user` 必須等於 host 的 owner(`/v1/host/state`);private relay 上不處理。`message_bot` 走一般 bot request(`Back::Assistant`),回覆留在 host 記憶體給 `read_replies`(最新 50 則,同時最多 16 則執行中,重啟即忘)。+- **信任邊界**:和 §7.8 一樣,雲端以 HTTPS 解開並看得到這些呼叫與回覆的明文,不是 §6 的端對端加密。因此要電腦本機同意(開關)才放行,雲端無法自行替電腦打開;App 與文件都需明講。+---## 8. Cloud HTTP API@@ -504,6 +517,8 @@ The route table below summarizes the contract. Executable schema and validation**Routine webhook(公開)**:`POST /v1/hooks/{computerId}/{routineId}`,§7.8。+**Cloud assistant(MCP connector)**:`POST /mcp`、`GET /.well-known/oauth-protected-resource[/mcp]`、`GET /.well-known/oauth-authorization-server`,§7.9。+**Relay**:§7.1。**Webhook**:`user.deleted` → accounts `status='deleted'`、devices 撤銷、grants 撤銷(`accountDeleted`)、computers owner=NULL、DO block + changed。## 9. Host integrationdiff --git a/host/clippy.toml b/host/clippy.tomlindex 1a248a62..4524cafd 100644--- a/host/clippy.toml+++ b/host/clippy.toml@@ -1,4 +1,4 @@# Tests may unwrap: a panic there is the failure report.allow-unwrap-in-tests = trueallow-expect-in-tests = true-doc-valid-idents = ["SQLite", "OpenCode", "JSON-RPC", ".."]+doc-valid-idents = ["SQLite", "OpenCode", "JSON-RPC", "ChatGPT", ".."]diff --git a/host/src/api/devices.rs b/host/src/api/devices.rsindex d00c5092..d1de3e60 100644--- a/host/src/api/devices.rs+++ b/host/src/api/devices.rs@@ -63,6 +63,8 @@ const LOCAL_ONLY: &[&str] = &["setCloud","setCloudUrl","setApproval",+ // Letting the cloud assistant in is decided at the computer, never through the cloud.+ "setAssistants",// Who is in the user's network of computers is decided at a computer."networkStatus","networkCreate",diff --git a/host/src/api/remote.rs b/host/src/api/remote.rsindex 9560db78..77dcdf88 100644--- a/host/src/api/remote.rs+++ b/host/src/api/remote.rs@@ -117,6 +117,10 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Valuelet approval = serde_json::from_value(b["approval"].clone()).context("`approval` is code or auto")?;serde_json::to_value(crate::remote::cloud::set_approval(hub, approval)?)?}+ "setAssistants" => {+ let on = b["enabled"].as_bool().ok_or_else(|| anyhow!("`enabled` is required"))?;+ serde_json::to_value(crate::chat::team::assistant::set_enabled(hub, on)?)?+ }"claimSign" => claim_sign(hub, &b).await?,_ => return Ok(ControlFlow::Continue(b)),}))diff --git a/host/src/chat/team.rs b/host/src/chat/team.rsindex 60aca9c6..e0622f6e 100644--- a/host/src/chat/team.rs+++ b/host/src/chat/team.rs@@ -1,7 +1,8 @@//! Bot messages. The recipient uses its own ACP session and its reply comes back to the sender//! as a turn of its own, so no bot ever waits on another; native subagents remain the harness's//! responsibility. A recipient on another of the user's computers is reached over-//! codync-network (`remote`).+//! codync-network (`remote`), and the user's cloud assistant reaches this computer's bots through+//! the Codync connector (`assistant`).use crate::agent::bot::Cmd;use crate::hub::Hub;@@ -11,6 +12,7 @@ use serde::Serialize;use serde_json::{Value, json};use std::sync::Arc;+pub mod assistant;mod directory;pub mod remote;mod requests;@@ -118,6 +120,7 @@ impl BotRequest {let _ = message.hub.send_cmd(sender, Cmd::BotReply(reply));}Back::Remote(to) => remote::answer(&message.hub, to, &outcome, self.hops),+ Back::Assistant { request } => message.hub.assistant.answered(request, outcome),}}}@@ -156,7 +159,7 @@ pub fn reply_prompt(replies: &[BotReply]) -> String {)}-#[derive(Clone, Copy, Serialize)]+#[derive(Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "lowercase")]pub(crate) enum RequestStatus {Queued,@@ -166,18 +169,22 @@ pub(crate) enum RequestStatus {Cancelled,}-/// Where a request's outcome goes: a bot on this computer, or an agent on another one.+/// Where a request's outcome goes: a bot on this computer, an agent on another one, or the+/// user's cloud assistant.enum Back {Local { sender: String },Remote(remote::Return),+ Assistant { request: String },}impl Back {/// The user stopped the recipient: a local sender's notice already shows it, and a remote one- /// hears so, without a reply turn.+ /// or the cloud assistant hears so, without a reply turn.fn cancelled(&self, hub: &Arc<Hub>, hops: u8) {- if let Self::Remote(to) = self {- remote::cancelled(hub, to, hops);+ match self {+ Self::Local { .. } => {}+ Self::Remote(to) => remote::cancelled(hub, to, hops),+ Self::Assistant { request } => hub.assistant.cancelled(request),}}}@@ -200,6 +207,9 @@ struct MessageLifetime {impl MessageLifetime {fn start(&mut self) {self.started = true;+ if let Back::Assistant { request } = &self.back {+ self.hub.assistant.started(request);+ }for id in &self.entries {if let Some(mut e) = self.hub.store.entry(id) {let heading = e.data["heading"].as_str().unwrap_or("Bot request");diff --git a/host/src/chat/team/assistant.rs b/host/src/chat/team/assistant.rsnew file mode 100644index 00000000..d70ea26d--- /dev/null+++ b/host/src/chat/team/assistant.rs@@ -0,0 +1,212 @@+//! The user's cloud assistant (ChatGPT, Claude or another one they connected to Codync) through+//! the Codync connector at `mcp.codync.dev` (docs/reference/remote-relay.md §7.9). The cloud+//! forwards its tool calls over this computer's relay socket; they're answered only while the+//! user has turned cloud assistants on here, and only for this computer's own account. It+//! messages this computer's bots the way a bot does. Nothing can wake it, so the replies wait here+//! until it reads them (in memory: a restart forgets them).++use super::{+ Back, BotRequest, MAX_MESSAGE_BYTES, MessageLifetime, REQUEST_QUOTE_BYTES, RequestStatus, directory, visible_bot,+};+use crate::LockExt;+use crate::agent::acp::truncate;+use crate::agent::bot::Cmd;+use crate::hub::Hub;+use crate::remote::cloud::{self, CloudStatus};+use crate::store::{EntryKind, Lane, Store, now_ms};+use anyhow::{Result, anyhow, bail};+use serde_json::{Value, json};+use std::sync::{Arc, Mutex};++/// How it shows in a bot's chat, and its id there (`sourceBotId`).+const NAME: &str = "Cloud assistant";+const ID: &str = "assistant";+/// kv: `on` lets the cloud assistant in.+const KV: &str = "cloud_assistants";+/// Requests still running at a time.+const MAX_RUNNING: usize = 16;+/// Requests remembered, oldest finished ones forgotten first; `read_replies` shows the newest.+const KEEP: usize = 50;+const SHOW: usize = 20;+const OFF: &str = "Cloud assistants are off on this computer. To let ChatGPT or Claude message its bots, \+run `codync-host cloud --assistants on` on it.";++pub fn enabled(store: &Store) -> bool {+ store.kv_get(KV).as_deref() == Some("on")+}++/// `setAssistants`: whether the cloud assistant may reach this computer's bots. Local only.+pub fn set_enabled(hub: &Hub, on: bool) -> Result<CloudStatus> {+ cloud::require_accounts(&hub.store)?;+ hub.store.kv_set(KV, if on { "on" } else { "off" })?;+ tracing::info!(on, "cloud assistants changed");+ cloud::update_status(hub, |s| s.assistants = on);+ Ok(hub.cloud.status())+}++/// Answers one `assistant.call` from the relay: `{"t":"assistant.result","id","ok","result"|"error"}`.+pub fn answer(hub: &Arc<Hub>, call: &Value) -> Value {+ let id = &call["id"];+ let tool = call["tool"].as_str().unwrap_or_default();+ match run(hub, call["user"].as_str().unwrap_or_default(), tool, &call["args"]) {+ Ok(result) => json!({"t": "assistant.result", "id": id, "ok": true, "result": result}),+ Err(e) => {+ tracing::info!(tool, error = format!("{e:#}"), "refused a cloud assistant call");+ json!({"t": "assistant.result", "id": id, "ok": false, "error": format!("{e:#}")})+ }+ }+}++fn run(hub: &Arc<Hub>, user: &str, tool: &str, args: &Value) -> Result<Value> {+ if !enabled(&hub.store) {+ bail!(OFF);+ }+ // The cloud only routes the account's own calls here; this computer checks that too.+ if user.is_empty() || hub.cloud.status().owner.map(|o| o.user_id).as_deref() != Some(user) {+ bail!("This computer isn't in your Codync account.");+ }+ match tool {+ "list_bots" => directory::list(hub, ID, args, &[]),+ "message_bot" => message(hub, args),+ "read_replies" => Ok(hub.assistant.read(args["requestId"].as_str())),+ _ => bail!("unknown tool: {tool}"),+ }+}++fn message(hub: &Arc<Hub>, args: &Value) -> Result<Value> {+ let to = args["botId"].as_str().ok_or_else(|| anyhow!("botId is required"))?;+ let message = args["message"].as_str().unwrap_or_default().trim();+ if message.is_empty() || message.len() > MAX_MESSAGE_BYTES {+ bail!("message must be nonempty and at most {MAX_MESSAGE_BYTES} bytes");+ }+ let target = visible_bot(hub, to)?;+ if hub.assistant.running() >= MAX_RUNNING {+ bail!("{MAX_RUNNING} requests are still running: read_replies first, then try again");+ }+ let request = uuid::Uuid::new_v4().to_string();+ let heading = format!("Message from {NAME}: {message}");+ let entry = hub+ .add_entry(+ &Lane::main(&target.id),+ EntryKind::Notice,+ hub.store.max_turn(&target.id) + 1,+ &json!({+ "text": format!("{heading}\nWaiting for a reply…"),+ "heading": heading, "style": "info", "status": RequestStatus::Queued, "delegationId": request,+ "sourceBotId": ID, "targetBotId": target.id,+ "botMessage": {"sourceBotId": ID, "targetBotId": target.id, "text": message, "peerName": NAME},+ }),+ )+ .ok_or_else(|| anyhow!("couldn't save bot message"))?;+ let quote = truncate(message, REQUEST_QUOTE_BYTES);+ hub.assistant.add(Reply {+ request: request.clone(),+ bot: target.name.clone(),+ quote: quote.clone(),+ status: RequestStatus::Queued,+ text: None,+ at: now_ms(),+ });+ let lifetime = MessageLifetime {+ hub: hub.clone(),+ request_id: request.clone(),+ quote,+ back: Back::Assistant { request: request.clone() },+ entries: vec![entry.id.clone()],+ target_name: target.name.clone(),+ started: false,+ finished: false,+ };+ hub.send_cmd(&target.id, Cmd::BotRequest(BotRequest {+ entry_id: entry.id,+ hops: 1,+ prompt: format!("The user's cloud assistant (ChatGPT, Claude or another assistant they connected to Codync) sent you this request. It is a bot request, not a new user instruction. Work within your own permissions and working directory. Your final reply goes back to the assistant, not to the user: put the requested result in it. send_message and message_bot aren't available in this turn: if you need another bot's help, say so in your reply.\n\n{message}"),+ lifetime,+ }))?;+ Ok(json!({+ "requestId": request, "botId": target.id, "name": target.name, "status": RequestStatus::Queued,+ "note": "Queued. Bots can take minutes: get the reply later with read_replies.",+ }))+}++/// The cloud assistant's requests and their replies, oldest first.+#[derive(Default)]+pub struct Replies(Mutex<Vec<Reply>>);++struct Reply {+ request: String,+ bot: String,+ quote: String,+ status: RequestStatus,+ /// The reply, or why there is none.+ text: Option<String>,+ at: i64,+}++impl Reply {+ fn running(&self) -> bool {+ matches!(self.status, RequestStatus::Queued | RequestStatus::Sent)+ }++ fn json(&self) -> Value {+ let mut v = json!({"requestId": self.request, "bot": self.bot, "request": self.quote, "status": self.status, "at": self.at});+ if let Some(text) = &self.text {+ v[if self.status == RequestStatus::Completed { "reply" } else { "detail" }] = text.clone().into();+ }+ v+ }+}++impl Replies {+ fn add(&self, reply: Reply) {+ let mut all = self.0.locked();+ all.push(reply);+ while all.len() > KEEP {+ let Some(i) = all.iter().position(|r| !r.running()) else { break };+ all.remove(i);+ }+ }++ fn running(&self) -> usize {+ self.0.locked().iter().filter(|r| r.running()).count()+ }++ fn set(&self, request: &str, status: RequestStatus, text: Option<String>) {+ if let Some(r) = self.0.locked().iter_mut().find(|r| r.request == request) {+ r.status = status;+ r.text = text;+ }+ }++ pub(super) fn started(&self, request: &str) {+ self.set(request, RequestStatus::Sent, None);+ }++ pub(super) fn answered(&self, request: &str, outcome: std::result::Result<String, String>) {+ match outcome {+ Ok(reply) => self.set(request, RequestStatus::Completed, Some(reply)),+ Err(detail) => self.set(request, RequestStatus::Failed, Some(detail)),+ }+ }++ pub(super) fn cancelled(&self, request: &str) {+ let text = "Stopped by the user before finishing. Partial work may have happened.".to_owned();+ self.set(request, RequestStatus::Cancelled, Some(text));+ }++ /// One request, or the newest ones (running and finished).+ fn read(&self, request: Option<&str>) -> Value {+ let all = self.0.locked();+ let shown: Vec<Value> = match request {+ Some(id) => all.iter().filter(|r| r.request == id).map(Reply::json).collect(),+ None => all.iter().rev().take(SHOW).map(Reply::json).collect(),+ };+ if request.is_some() && shown.is_empty() {+ return json!({"replies": [], "note": "No such request here: this computer forgets them when Codync restarts."});+ }+ json!({"replies": shown, "running": all.iter().filter(|r| r.running()).count()})+ }+}++#[cfg(test)]+mod tests;diff --git a/host/src/chat/team/assistant/tests.rs b/host/src/chat/team/assistant/tests.rsnew file mode 100644index 00000000..e7db573c--- /dev/null+++ b/host/src/chat/team/assistant/tests.rs@@ -0,0 +1,37 @@+use super::super::tests::Fixture;+use super::*;+use crate::remote::cloud::Owner;++fn call(hub: &Arc<Hub>, user: &str, tool: &str, args: &Value) -> Value {+ answer(hub, &json!({"t": "assistant.call", "id": "c1", "user": user, "tool": tool, "args": args}))+}++fn refused(v: &Value, why: &str) {+ assert!(v["ok"] == false && v["error"].as_str().unwrap().contains(why), "{v}");+}++#[tokio::test]+async fn the_cloud_assistant_needs_the_switch_and_the_account_and_reads_replies_later() {+ let f = Fixture::new();+ let hub = &f.hub;+ refused(&call(hub, "user_1", "list_bots", &json!({})), "Cloud assistants are off");+ set_enabled(hub, true).unwrap();+ assert!(hub.cloud.status().assistants);+ refused(&call(hub, "user_1", "list_bots", &json!({})), "isn't in your Codync account");+ cloud::update_status(hub, |s| s.owner = Some(Owner { user_id: "user_1".into(), email: None }));+ refused(&call(hub, "user_2", "list_bots", &json!({})), "isn't in your Codync account");++ let listed = call(hub, "user_1", "list_bots", &json!({"query": "b"}));+ assert_eq!((&listed["id"], &listed["result"]["bots"][0]["id"]), (&json!("c1"), &json!("b")));+ let sent = call(hub, "user_1", "message_bot", &json!({"botId": "b", "message": "review this"}));+ let request = sent["result"]["requestId"].as_str().unwrap().to_owned();+ let read = || hub.assistant.read(Some(&request))["replies"][0].clone();+ f.until(|| read()["status"] == "completed").await;+ assert_eq!((&read()["bot"], &read()["reply"]), (&json!("b"), &json!("reply: review this")));+ // The bot's chat shows who asked.+ let history = hub.store.history("b", i64::MAX, 50).unwrap();+ let notice = history.into_iter().find(|e| e.data["delegationId"] == *request).unwrap();+ assert_eq!(notice.data["botMessage"]["peerName"], NAME);+ refused(&call(hub, "user_1", "message_bot", &json!({"botId": "nobody", "message": "hi"})), "unknown or hidden bot");+ f.shutdown().await;+}diff --git a/host/src/chat/team/tests.rs b/host/src/chat/team/tests.rsindex cd45fa93..64c989d9 100644--- a/host/src/chat/team/tests.rs+++ b/host/src/chat/team/tests.rs@@ -5,13 +5,13 @@ use crate::store::Store;use std::path::PathBuf;use std::time::Duration;-struct Fixture {- hub: Arc<Hub>,+pub(super) struct Fixture {+ pub(super) hub: Arc<Hub>,dir: PathBuf,}impl Fixture {- fn new() -> Self {+ pub(super) 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();@@ -74,7 +74,7 @@ impl Fixture {sent.unwrap()}- async fn until(&self, condition: impl Fn() -> bool) {+ pub(super) async fn until(&self, condition: impl Fn() -> bool) {// Generous: Windows runners need several seconds to run 16 queued turns.tokio::time::timeout(Duration::from_secs(30), async {while !condition() {@@ -118,7 +118,7 @@ impl Fixture {.collect()}- async fn shutdown(self) {+ pub(super) async fn shutdown(self) {self.hub.shutdown().await;// Windows may still hold files of an agent that just exited.let _ = std::fs::remove_dir_all(self.dir);diff --git a/host/src/cloud_cli.rs b/host/src/cloud_cli.rsindex ba02bd03..f7adec13 100644--- a/host/src/cloud_cli.rs+++ b/host/src/cloud_cli.rs@@ -18,6 +18,11 @@ pub struct CloudArgs {/// the cloud, can then add a device).#[arg(long, value_parser = ["code", "auto"])]approval: Option<String>,+ /// Whether the cloud assistant (ChatGPT, Claude…) you connect to Codync through+ /// mcp.codync.dev may message this computer's bots: `on` or `off` (the default). Its calls+ /// reach this computer through the cloud unencrypted.+ #[arg(long, value_parser = ["on", "off"])]+ assistants: Option<String>,/// Cloud base URL for this computer. `https://…`, or `http://127.0.0.1` / `localhost` for a relay on this machine.#[arg(long, conflicts_with = "clear_url")]url: Option<String>,@@ -32,7 +37,7 @@ pub struct CloudArgs {/// `codync-host cloud`: shows or changes the cloud this computer uses.pub async fn run(args: CloudArgs) -> Result<()> {- let CloudArgs { port, enable, disable, approval, url, clear_url, token } = args;+ let CloudArgs { port, enable, disable, approval, assistants, url, clear_url, token } = args;let mut status = None;if clear_url {status = Some(local_call(port, "setCloudUrl", json!({ "url": "" })).await?);@@ -51,6 +56,9 @@ pub async fn run(args: CloudArgs) -> Result<()> {if let Some(approval) = approval {status = Some(local_call(port, "setApproval", json!({ "approval": approval })).await?);}+ if let Some(assistants) = assistants {+ status = Some(local_call(port, "setAssistants", json!({ "enabled": assistants == "on" })).await?);+ }if enable || disable {status = Some(local_call(port, "setCloud", json!({"enabled": !disable})).await?);}@@ -61,7 +69,7 @@ pub async fn run(args: CloudArgs) -> Result<()> {let text = |k: &str| status[k].as_str().unwrap_or("-").to_owned();let owner = status["owner"]["email"].as_str().or(status["owner"]["userId"].as_str()).unwrap_or("none");println!(- "enabled: {}\nurl: {}\nrelay: {}\ntoken: {}\nregistered: {}\nconnected: {}\naccount: {owner}\napproval: {}\nlast error: {}",+ "enabled: {}\nurl: {}\nrelay: {}\ntoken: {}\nregistered: {}\nconnected: {}\naccount: {owner}\napproval: {}\nassistants: {}\nlast error: {}",status["enabled"],text("url"),text("relay"),@@ -69,6 +77,7 @@ pub async fn run(args: CloudArgs) -> Result<()> {status["registered"],status["connected"],text("approval"),+ if status["assistants"] == true { "on" } else { "off" },text("lastError"),);Ok(())diff --git a/host/src/hub.rs b/host/src/hub.rsindex f5ec696b..c14e9e7c 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -77,6 +77,8 @@ pub struct Hub {pub groups: crate::chat::group::Rooms,/// The user's other computers (codync-network), once this one is in a network.pub network: crate::network::Network,+ /// The user's cloud assistant: its requests to this computer's bots and their replies.+ pub assistant: crate::chat::team::assistant::Replies,pub store: Store,pub host_id: String,pub identity: Identity,@@ -121,6 +123,7 @@ impl Hub {team: crate::chat::team::Requests::default(),groups: crate::chat::group::Rooms::default(),network: crate::network::Network::default(),+ assistant: crate::chat::team::assistant::Replies::default(),store,host_id,identity,diff --git a/host/src/remote/cloud.rs b/host/src/remote/cloud.rsindex 6da7ac54..23e5e1da 100644--- a/host/src/remote/cloud.rs+++ b/host/src/remote/cloud.rs@@ -59,6 +59,8 @@ pub struct CloudStatus {pub owner: Option<Owner>,pub last_error: Option<String>,pub approval: Approval,+ /// The user's cloud assistant may message this computer's bots (`setAssistants`, local only).+ pub assistants: bool,/// Whose relay: on a private one there is no account, access request or relayed screen.pub relay: RelayKind,}diff --git a/host/src/remote/relay.rs b/host/src/remote/relay.rsindex 1267ad27..1dd32316 100644--- a/host/src/remote/relay.rs+++ b/host/src/remote/relay.rs@@ -64,6 +64,7 @@ pub async fn run(hub: Arc<Hub>) {cloud::update_status(&hub, |s| {cloud::show(s, address.as_ref());s.approval = cloud::approval(&hub.store);+ s.assistants = crate::chat::team::assistant::enabled(&hub.store);s.registered = false;s.connected = false;if address.is_none() {@@ -407,6 +408,11 @@ impl Session {let ack = hook_item(&self.hub, &v);self.send(&ack).await?;}+ // A private relay has no accounts, so no cloud assistant (§7.9).+ "assistant.call" if self.address.kind == cloud::RelayKind::Codync => {+ let result = crate::chat::team::assistant::answer(&self.hub, &v);+ self.send(&result).await?;+ }"cloud.changed" => self.pull(),"acl.ok" => {self.retried = false;diff --git a/web/app/docs/pages.ts b/web/app/docs/pages.tsindex d974c3ed..f6b7df40 100644--- a/web/app/docs/pages.ts+++ b/web/app/docs/pages.ts@@ -44,6 +44,12 @@ export const docSections: { title: string; pages: DocPage[] }[] = [description:"Bots can ask each other for help, hand work off, and, with Manage the team on, create and set up other bots.",},+ {+ slug: "cloud-assistants",+ title: "Cloud assistants",+ description:+ "Add Codync to ChatGPT, Claude or another assistant as a connector, so it can give your bots tasks and read their answers.",+ },],},{diff --git a/web/content/docs/cloud-assistants.mdx b/web/content/docs/cloud-assistants.mdxnew file mode 100644index 00000000..4231c63c--- /dev/null+++ b/web/content/docs/cloud-assistants.mdx@@ -0,0 +1,36 @@+You can give a task to your Codync bots from an assistant you already use on the web or on your phone, such as ChatGPT or Claude. Add Codync to it as a connector, sign in with your Codync account, and the assistant can see your bots, ask one to do something, and read its answer. The bots still do the work on your computer, with their own agent, folder, tools and approval setting.++## Turn it on for a computer++Cloud assistants are off on every computer until you turn them on there. On the computer whose bots the assistant may use, run:++```sh+codync-host cloud --assistants on+```++The computer has to be in your Codync account (signed in) and use the Codync relay. `codync-host cloud` shows the setting as `assistants: on`; `--assistants off` turns it off again.++## Add the connector++In your assistant's settings, add a custom connector (it may be called a connector, an app or an MCP server) with this address:++```+https://mcp.codync.dev/mcp+```++The assistant opens Codync's sign-in page. Sign in with the account your computer is in, then allow the assistant access. You can remove the connector in the assistant whenever you like.++## What the assistant can do++- **List your computers** and whether each one is online.+- **List your bots**, with their names, descriptions and status. It can search them by name or description.+- **Message a bot**: it sends one bot a task, the way one bot asks another for help ([Teamwork](/docs/teamwork)). The bot works on it in its own chat.+- **Read replies**: bots can take a few minutes, so the assistant comes back for the answer, for example when you ask it how the task went.++If several of your computers are online, the assistant says which one a message is for. It reaches only the bots of computers where you turned cloud assistants on, and not hidden bots or groups.++In the bot's chat, the request shows as a row saying **Message from Cloud assistant**, like a message from another bot. Its reply goes back to the assistant, not to you in that chat. Your computer keeps the replies until the assistant reads them, and forgets them when Codync restarts.++## Privacy++Unlike the encrypted connection between your devices and your computer, a cloud assistant's requests and the bots' replies pass through the Codync relay in readable form, over HTTPS. The assistant's service (OpenAI, Anthropic or another) also sees them, as it does everything in that conversation. That's why it's off until you turn it on at the computer: the relay can't turn it on for you, and it only passes on requests from your own account. More in [Privacy](/docs/privacy).diff --git a/web/content/docs/privacy.mdx b/web/content/docs/privacy.mdxindex 908d14fd..4494a770 100644--- a/web/content/docs/privacy.mdx+++ b/web/content/docs/privacy.mdx@@ -26,6 +26,8 @@ The relay can't add a device to your computer. A new device needs either a pairi**Public routine webhooks are the exception to end-to-end encryption.** A service that calls a routine's public URL sends its data to the relay over HTTPS. The relay can read it and keeps the routine's key to check signatures. If you don't want that, use the routine's local URL instead.+**Cloud assistants are the other exception.** If you turn them on at a computer and add the Codync connector to ChatGPT, Claude or another assistant, the assistant's requests to your bots and the bots' replies pass through the relay over HTTPS, and the relay can read them. They're off until you turn them on at the computer, and the relay passes on only requests from your own account. See [Cloud assistants](/docs/cloud-assistants).+**Remote screen** sessions are encrypted between your phone and your computer. When there's no direct path, the video goes through a Cloudflare relay that can't see what's on your screen.## Push notificationsdiff --git a/web/public/llms.txt b/web/public/llms.txtindex 607b41e5..1ee07d22 100644--- a/web/public/llms.txt+++ b/web/public/llms.txt@@ -33,6 +33,7 @@ Key facts:- [Bots](https://www.codync.dev/docs/bots) and [agents](https://www.codync.dev/docs/agents)- [Group chats](https://www.codync.dev/docs/groups)- [Teamwork](https://www.codync.dev/docs/teamwork)+- [Cloud assistants](https://www.codync.dev/docs/cloud-assistants): the Codync connector for ChatGPT, Claude and other MCP clients- [Routines](https://www.codync.dev/docs/routines)- [Memory](https://www.codync.dev/docs/memory)- [Connectors and skills](https://www.codync.dev/docs/connectors-and-skills)