import { z } from "zod"; import { usageQuerySchema, usageReportSchema } from "./usage.js"; import { goalChangeSchema, sessionGoalSchema } from "./goal.js"; import { acpAgentSettingsSchema, acpFeaturesSchema, acpRemoteAgentSchema, acpProviderSchema } from "./acp.js"; import { editorRequestSchema, editorResultSchema } from "./editor.js"; import { fusionStartResultSchema } from "./fusion.js"; import { liveActivityIdSchema, liveActivityPushToStartSchema, liveActivitySubscriptionSchema, wakeupNoticeSchema } from "./live-activity.js"; import { backgroundTaskSchema, agentInfoSchema, gatewayStatusSchema, keepAwakeModeSchema, machineInfoSchema, machineKeepAwakeSchema, machineMetricsSnapshotSchema, portInfoSchema, projectSummarySchema, terminalInfoSchema, sessionDriverSchema, sessionSummarySchema, subagentInfoSchema, gitInfoSchema, worktreeEntrySchema, questionAnswerSchema, pendingPermissionSchema, } from "./model.js"; import { contentBlockSchema, sessionConfigOptionSchema, sessionEventSchema, sessionNoticeSchema } from "./updates.js"; import { sideChatSchema } from "./side.js"; import { mcpMethods } from "./rpc-mcp.js"; import { lsaMethods } from "./lsa.js"; // ── JSON-RPC 2.0 framing ───────────────────────────────────────────── export const rpcIdSchema = z.union([z.string(), z.number()]); export type RpcId = z.infer; export const rpcErrorSchema = z.object({ code: z.number().int(), message: z.string(), data: z.unknown().optional(), }); export type RpcErrorObject = z.infer; export const rpcMessageSchema = z.object({ jsonrpc: z.literal("2.0"), id: rpcIdSchema.optional(), method: z.string().optional(), params: z.unknown().optional(), result: z.unknown().optional(), error: rpcErrorSchema.optional(), }); export type RpcMessage = z.infer; /** Application error codes carried in `error.data.code`. */ export const appErrorCodeSchema = z.enum([ "invalid_params", "not_found", "agent_unavailable", "not_supported", /** The session exists but can't be joined yet (e.g. a new Codex thread before its first turn). */ "not_ready", "busy", /** Client side: the link to the computer is down. */ "offline", /** The computer has an access password and this connection hasn't been unlocked (`access.unlock`). */ "locked", "internal", ]); export type AppErrorCode = z.infer; export const RPC_INVALID_PARAMS = -32602; export const RPC_METHOD_NOT_FOUND = -32601; export const RPC_APP_ERROR = -32000; // ── Methods (client → host) ────────────────────────────────────────── /** * The host's RPC revision, in `machine.info`. Goes up when the host gains * methods or notifications an app may rely on, so an app can tell the * computer is older than itself and say so (an absent revision is 0). * 1: side conversations (`sessions.side`), `machine.info.protocol` itself. * 2: session terminals (`terminals.create` `sessionId`, `TerminalInfo.sessionId`). * 3: whole-computer CPU and physical memory sampling (`machine.metrics`). * 4: smart keep-awake & battery telemetry (`machine.keepAwake`), real git working-tree * diff/revert (`git.diff`, `git.revertFile`), fast `@file` search (`fs.projectFiles`), * clipboard & screen privacy (`clipboard.*`, `screen.privacy`), push-to-start wakeup * (`liveActivities.registerPushToStart`), and LSA Phase 1 steward RPCs (`lsa.*`). */ export const HOST_PROTOCOL = 4; const empty = z.looseObject({}); export const gitDiffFileStatusSchema = z.enum(["modified", "added", "deleted", "renamed", "untracked"]); export type GitDiffFileStatus = z.infer; export const gitDiffFileSchema = z.object({ path: z.string(), oldPath: z.string().optional(), status: gitDiffFileStatusSchema, oldText: z.string(), newText: z.string(), additions: z.number().int().nonnegative(), deletions: z.number().int().nonnegative(), binary: z.boolean().optional(), }); export type GitDiffFile = z.infer; export const gitDiffResultSchema = z.object({ files: z.array(gitDiffFileSchema), truncated: z.boolean(), branch: z.string().optional(), }); export type GitDiffResult = z.infer; export const projectFileEntrySchema = z.object({ path: z.string(), relativePath: z.string(), isDir: z.boolean().optional(), }); export type ProjectFileEntry = z.infer; export const screenPrivacyStateSchema = z.object({ curtain: z.boolean(), lockOnDisconnect: z.boolean(), supported: z.boolean(), }); export type ScreenPrivacyState = z.infer; export const directoryEntrySchema = z.object({ name: z.string(), path: z.string(), /** Looks like a code project (has .git, package.json, …). */ project: z.boolean().optional(), /** A file (only listed when asked for); everything else is a directory. */ file: z.boolean().optional(), size: z.number().int().optional(), }); export type DirectoryEntry = z.infer; const acpMethods = { "agents.editor": { params: editorRequestSchema, result: editorResultSchema }, "agents.acp": { params: z.object({ agent: z.string().min(1), sessionId: z.string().optional() }), result: z.object({ features: acpFeaturesSchema, settings: acpAgentSettingsSchema, interactions: z.array(pendingPermissionSchema) }), }, "agents.pending": { params: empty, result: z.object({ interactions: z.array(z.object({ agent: z.string(), request: pendingPermissionSchema })) }) }, "agents.configure": { params: z.object({ agent: z.string().min(1), settings: acpAgentSettingsSchema, sessionId: z.string().optional() }), result: empty, }, "agents.authenticate": { params: z.object({ agent: z.string().min(1), methodId: z.string().optional(), logout: z.boolean().optional() }), result: z.object({ terminalId: z.string().optional() }), }, "agents.respond": { params: z.object({ agent: z.string().min(1), requestId: z.string().min(1), optionId: z.string().optional(), answers: z.array(questionAnswerSchema).optional() }), result: empty, }, "agents.providers": { params: z.object({ agent: z.string().min(1), operation: z.enum(["list", "set", "disable"]), config: z.object({ providerId: z.string(), apiType: z.string().optional(), baseUrl: z.url().optional(), headers: z.record(z.string(), z.string()).optional() }).optional() }), result: z.object({ providers: z.array(acpProviderSchema) }), }, "agents.custom": { params: z.object({ save: acpRemoteAgentSchema.optional(), remove: z.string().optional() }), result: z.object({ agents: z.array(acpRemoteAgentSchema) }), }, } as const; const coreMethods = { "desktop.shutdown": { params: z.object({ pid: z.number().int().positive() }), result: empty }, /** Opens a local path in the chosen desktop editor, file manager, or terminal (local only). */ "desktop.openPath": { params: z.object({ path: z.string().min(1), app: z.enum(["default", "reveal", "cursor", "vscode", "zed", "terminal"]).optional(), }), result: z.object({ ok: z.boolean() }), }, "usage.summary": { params: usageQuerySchema, result: usageReportSchema }, "liveActivities.subscribe": { params: liveActivitySubscriptionSchema, result: z.object({}), }, "liveActivities.unsubscribe": { params: z.object({ activityId: liveActivityIdSchema }), result: z.object({}), }, "liveActivities.registerPushToStart": { params: liveActivityPushToStartSchema, result: z.looseObject({ ok: z.boolean().optional() }), }, "machine.info": { params: empty, result: machineInfoSchema, }, "machine.metrics": { params: empty, result: machineMetricsSnapshotSchema }, "machine.keepAwake": { params: z.object({ mode: keepAwakeModeSchema.optional() }), result: machineKeepAwakeSchema, }, "machine.rename": { /** Empty restores the configured default; names never change peer identities. */ params: z.object({ name: z.string().trim().max(40) }), result: machineInfoSchema, }, "projects.list": { params: z.object({ limit: z.number().int().positive().max(200).optional() }), result: z.object({ projects: z.array(projectSummarySchema) }), }, "sessions.list": { params: z.object({ limit: z.number().int().positive().max(200).optional(), /** Only sessions updated strictly before this timestamp (pagination). */ before: z.number().optional(), /** Tie-breaker session id when multiple sessions share the `before` timestamp. */ beforeId: z.string().optional(), includeArchived: z.boolean().optional(), }), result: z.object({ sessions: z.array(sessionSummarySchema), nextBefore: z.number().optional(), nextBeforeId: z.string().optional(), }), }, "sessions.get": { params: z.object({ sessionId: z.string().min(1) }), result: z.object({ session: sessionSummarySchema.optional() }), }, /** * The models a new session of `agent` can start on, for choosing one before * there is a session (whose own list comes later, in its `ls_config`). * `current` is the one the agent takes when `sessions.create` names none: * its own default, which a new session keeps unless another is picked. * Agents that tell their models only to a session give what they said in * the latest one opened on this computer; never asked by starting one, so * empty until there has been one (`current` too may be missing then). * With an empty list `sessions.create` takes no model. Hosts older than * this method answer "method not found". */ "agents.models": { params: z.object({ agent: z.string().min(1), /** Where the session will work: an agent's project settings can choose another model. */ cwd: z.string().optional(), /** Preview settings supported by a selected model without changing the agent's default. */ model: z.string().optional(), }), result: z.object({ /** As a session's model option lists them (`group`: the heading some agents put models under). */ models: z.array(z.object({ value: z.string(), name: z.string(), description: z.string().optional(), group: z.string().optional() })), current: z.string().optional(), /** Settings available before the first prompt; omitted by older hosts or agents without a template. */ config: z.array(sessionConfigOptionSchema).optional(), }), }, "sessions.create": { params: z.object({ agent: z.string().min(1), cwd: z.string().min(1), prompt: z.array(contentBlockSchema).optional(), clientMessageId: z.string().optional(), /** Client-generated idempotency key so a retried create does not spawn a duplicate session. */ requestId: z.string().max(128).optional(), /** One of `agents.models`' values; absent: the agent's own default. */ model: z.string().optional(), /** Explicit choices from agents.models.config, applied before the first prompt. */ config: z.record(z.string(), z.string()).optional(), /** * Start in a new git worktree of `cwd`'s repository (its own branch, from * the last commit) instead of in `cwd` itself. Refused with `not_a_repo` * outside a git repository. */ worktree: z.boolean().optional(), }), result: z.object({ session: sessionSummarySchema }), }, /** * A new session that starts with this one's conversation: all of it, or up * to and including the turn of `itemId` (a message in it). The original is * untouched. With `worktree` the new session works in a new git worktree of * the project instead of the same directory. */ "sessions.fork": { params: z.object({ sessionId: z.string().min(1), itemId: z.string().min(1).optional(), worktree: z.boolean().optional() }), result: z.object({ session: sessionSummarySchema }), }, "sessions.subscribe": { params: z.object({ sessionId: z.string().min(1), /** Last seq the client already has; 0 for a fresh subscription. */ fromSeq: z.number().int().nonnegative(), /** * The client loads pictures when it shows them (`sessions.image`): they * arrive as image blocks with a `linkshell-event:` uri and no data. * Without it, large pictures are replaced by a text note. */ lazyImages: z.boolean().optional(), /** * Back after more than about a page of events (an app returning from the background): start * at the latest turns, as a fresh subscription does, rather than replaying all it missed. * What it skipped is read with `sessions.history`, as the user scrolls up to it. */ latest: z.boolean().optional(), }), /** * A fresh subscription starts at the session's latest turns, not at its * beginning: `startSeq` is the seq before the first event sent (0 when the * whole log was). `sessions.history` pages back from there. */ result: z.object({ session: sessionSummarySchema, startSeq: z.number().int().nonnegative().optional() }), }, /** The page of events before `beforeSeq` (whole turns), oldest first; `startSeq` 0 means that was the beginning. */ "sessions.history": { params: z.object({ sessionId: z.string().min(1), beforeSeq: z.number().int().positive(), lazyImages: z.boolean().optional(), }), result: z.object({ events: z.array(sessionEventSchema), startSeq: z.number().int().nonnegative() }), }, /** The sub-agents this session started, newest first, wherever in its history they are. */ "sessions.subagents": { params: z.object({ sessionId: z.string().min(1) }), result: z.object({ subagents: z.array(subagentInfoSchema) }), }, "sessions.cancelSubagent": { params: z.object({ sessionId: z.string().min(1), nativeSessionId: z.string().min(1) }), result: empty, }, /** * One sub-agent's conversation: the call that started it and the events * under it (the latest 2000), oldest first. Later ones arrive on the * session's own subscription, with this call as `parentToolCallId`. */ "sessions.subagent": { params: z.object({ sessionId: z.string().min(1), toolCallId: z.string().min(1), lazyImages: z.boolean().optional() }), result: z.object({ events: z.array(sessionEventSchema) }), }, /** * Asks in a side conversation of the session (a new one without `sideId`): * answered from what the session knows, never added to it. Returns once the * question is on its way; the answer comes in `session.side`. Only for an * agent whose capabilities say `side`. */ "sessions.side": { params: z.object({ sessionId: z.string().min(1), sideId: z.string().min(1).optional(), text: z.string().min(1).max(20_000) }), result: z.object({ side: sideChatSchema }), }, /** The session's open side conversations, oldest first. */ "sessions.sides": { params: z.object({ sessionId: z.string().min(1) }), result: z.object({ sides: z.array(sideChatSchema) }), }, /** Stops the answer under way. */ "sessions.sideCancel": { params: z.object({ sessionId: z.string().min(1), sideId: z.string().min(1) }), result: empty, }, /** Ends a side conversation: it is forgotten, and whatever the agent kept for it let go. */ "sessions.sideClose": { params: z.object({ sessionId: z.string().min(1), sideId: z.string().min(1) }), result: empty, }, /** The commands this session left running in the background, and the ones that have ended; newest first. */ "sessions.tasks": { params: z.object({ sessionId: z.string().min(1) }), result: z.object({ tasks: z.array(backgroundTaskSchema) }), }, /** * A background task's output, a piece at a time from the end: the text * before byte `before` (default: the end), at most `limit` bytes. `start` is * where that text begins (0: the beginning); `size` is the whole output's. */ "sessions.taskOutput": { params: z.object({ sessionId: z.string().min(1), taskId: z.string().min(1), before: z.number().int().nonnegative().optional(), limit: z.number().int().positive().max(256 * 1024).optional(), }), result: z.object({ text: z.string(), start: z.number().int().nonnegative(), size: z.number().int().nonnegative() }), }, /** Stops one background task, leaving the session's turn and its other tasks alone. */ "sessions.stopTask": { params: z.object({ sessionId: z.string().min(1), taskId: z.string().min(1) }), result: empty, }, /** Opens a read-only computer-use preview through the existing bulk-stream transport. */ "sessions.preview": { params: z.object({ sessionId: z.string().min(1), direct: z.boolean().optional() }), result: z.object({ port: z.number().int().positive(), token: z.string() }), }, /** Explicit local user action; normal frame updates never reopen a dismissed preview. */ "desktop.preview.show": { params: z.object({ sessionId: z.string().min(1) }), result: empty, }, /** The picture behind a `linkshell-event:` uri. */ "sessions.image": { params: z.object({ sessionId: z.string().min(1), uri: z.string().min(1) }), result: z.object({ mimeType: z.string(), data: z.string() }), }, "sessions.unsubscribe": { params: z.object({ sessionId: z.string().min(1) }), result: empty, }, "sessions.prompt": { params: z.object({ sessionId: z.string().min(1), /** Client-generated idempotency key; a retried send is not delivered twice. */ clientMessageId: z.string().min(1), content: z.array(contentBlockSchema).min(1), /** * What to do while a turn is running. "queue": hold the message (it * shows in SessionSummary.queue, where it can be reordered, taken back * or sent at once) and send it when the turn ends. Unset: the agent's * own way — taken into the running turn where it can be, queued where not. */ whenBusy: z.enum(["queue"]).optional(), }), /** queued: held until the running turn ends (see `whenBusy`, `sessions.sendQueued`). */ result: z.object({ delivery: z.enum(["started", "steered", "queued", "duplicate"]) }), }, "sessions.cancel": { params: z.object({ sessionId: z.string().min(1) }), result: empty, }, "sessions.permission": { params: z.object({ sessionId: z.string().min(1), requestId: z.string().min(1), optionId: z.string().min(1), }), result: empty, }, /** * Answers the questions of a pending request (an `ls_permission` with * `questions`). Skipping or stopping instead is `sessions.permission` with * one of the request's options. */ "sessions.answer": { params: z.object({ sessionId: z.string().min(1), requestId: z.string().min(1), answers: z.array(questionAnswerSchema).max(50) }), result: empty, }, "sessions.goal": { params: z.object({ sessionId: z.string(), change: goalChangeSchema }), result: z.object({ goal: sessionGoalSchema.nullable() }), }, "sessions.setConfig": { params: z.object({ sessionId: z.string().min(1), optionId: z.string().min(1), value: z.string().min(1), }), result: empty, }, /** * Sends a queued message (the first, or `clientMessageId`) now instead of * when the running turn ends: taken into that turn where the agent allows * it, otherwise the turn is stopped first, wherever it runs. */ "sessions.sendQueued": { params: z.object({ sessionId: z.string().min(1), clientMessageId: z.string().min(1).optional() }), result: empty, }, /** Puts the queued messages in this order (ids not named keep theirs, after the named ones). */ "sessions.reorderQueue": { params: z.object({ sessionId: z.string().min(1), clientMessageIds: z.array(z.string().min(1)) }), result: empty, }, /** Drops a message still waiting in the host's queue (see SessionSummary.queue). */ "sessions.unqueue": { params: z.object({ sessionId: z.string().min(1), clientMessageId: z.string().min(1) }), result: z.object({ removed: z.boolean() }), }, /** Archives (or restores) a session: hidden from lists, kept on disk; natively where the agent supports it. */ "sessions.archive": { params: z.object({ sessionId: z.string().min(1), archived: z.boolean() }), result: z.object({ session: sessionSummarySchema }), }, /** Names a session; an empty title goes back to the agent's own. */ "sessions.rename": { params: z.object({ sessionId: z.string().min(1), title: z.string().max(200) }), result: z.object({ session: sessionSummarySchema }), }, /** * Deletes a session: the agent's own record where it has one (Codex thread, * Claude transcript), and LinkShell's copy either way. Not while it runs. */ /** * Deletes a session. Its worktree (when it has one that no other session * uses) goes with it if nothing in it would be lost; `worktree: "remove"` * removes it even with uncommitted changes or new commits, "keep" never. */ "sessions.delete": { params: z.object({ sessionId: z.string().min(1), worktree: z.enum(["keep", "remove"]).optional() }), result: empty, }, "sessions.takeover": { params: z.object({ sessionId: z.string().min(1) }), result: z.object({ driver: sessionDriverSchema.optional() }), }, "sessions.release": { params: z.object({ sessionId: z.string().min(1) }), result: z.object({ driver: sessionDriverSchema.optional() }), }, /** * How a desktop terminal should launch the agent's native UI attached to the * host (used by `linkshell `). The shim execs exactly what it gets. * For handoff agents the calling connection becomes the session's desktop * controller: it receives `desktop.yield` when a device takes over. */ "desktop.launch": { params: z.object({ agent: z.string().min(1), sessionId: z.string().optional(), args: z.array(z.string()).default([]), /** The terminal's working directory and environment. */ cwd: z.string().optional(), env: z.record(z.string(), z.string()).optional(), }), result: z.object({ command: z.string(), args: z.array(z.string()), env: z.record(z.string(), z.string()).optional(), /** Set for handoff agents: the session this terminal now drives. */ sessionId: z.string().optional(), }), }, /** The shim's native UI exited after a `desktop.yield`; the device may drive now. */ "desktop.yielded": { params: z.object({ sessionId: z.string().min(1) }), result: empty, }, /** The user is back at the keyboard: stop remote driving, relaunch the native UI. */ "desktop.reclaim": { params: z.object({ sessionId: z.string().min(1) }), result: z.object({ command: z.string(), args: z.array(z.string()), env: z.record(z.string(), z.string()).optional(), }), }, // ── Gateway: reach this computer from anywhere ── "gateway.status": { params: empty, result: gatewayStatusSchema }, /** * Applies the computer's current gateway choice and account (local only): * after `linkshell login` / `logout` or `linkshell host --gateway`, a running * host connects, moves or disconnects without a restart. */ "gateway.refresh": { params: empty, result: gatewayStatusSchema }, /** Explicitly end this computer's gateway account binding (local only). */ "gateway.account.leave": { params: empty, result: empty }, /** * Opens a pairing window (local only). `link` is what the QR encodes; the * code can be typed instead. `pairing.done` follows when a device pairs. */ "pairing.start": { params: empty, result: z.object({ link: z.string(), code: z.string(), expiresAt: z.number(), gateway: z.string() }), }, "devices.revoke": { params: z.object({ deviceId: z.string().min(1) }), result: empty }, // ── Access password: optional, set on the computer itself ── /** * Unlocks this connection with the password, or with a `token` an earlier unlock returned (so a * reconnect doesn't ask again). Hosts without the method have no password. Wrong guesses are * throttled per device (`busy`). */ "access.unlock": { params: z.object({ password: z.string().max(256).optional(), token: z.string().max(512).optional() }), result: z.object({ token: z.string(), expiresAt: z.number() }), }, /** Whether this computer has a password (local only). */ "access.status": { params: empty, result: z.object({ password: z.boolean() }) }, /** Sets the password, or removes it when none is given (local only). Remote connections reconnect. */ "access.set": { params: z.object({ password: z.string().min(4).max(128).optional() }), result: z.object({ password: z.boolean() }), }, // ── Git: sessions in worktrees & working-tree diffs ── /** What git says about `path`; no `git` when it isn't in a repository. */ "git.info": { params: z.object({ path: z.string().min(1) }), result: z.object({ git: gitInfoSchema.optional() }) }, /** Real git working-tree diff (or against `base`), bounded by `maxBytes` and including untracked text files by default. */ "git.diff": { params: z.object({ cwd: z.string().min(1), base: z.string().optional(), includeUntracked: z.boolean().optional(), maxBytes: z.number().int().positive().max(10_000_000).optional(), }), result: gitDiffResultSchema, }, /** Restores a tracked file or removes an untracked file strictly inside the repository root. */ "git.revertFile": { params: z.object({ cwd: z.string().min(1), path: z.string().min(1) }), result: z.object({ ok: z.boolean() }), }, /** Commits staged or specified paths inside `cwd`'s repository. */ "git.commit": { params: z.object({ cwd: z.string().min(1), message: z.string().min(1).max(4000), stageAll: z.boolean().optional(), paths: z.array(z.string().min(1)).max(500).optional(), }), result: z.object({ sha: z.string(), branch: z.string().optional(), summary: z.string(), }), }, /** The worktrees LinkShell made, newest first. */ "worktrees.list": { params: empty, result: z.object({ worktrees: z.array(worktreeEntrySchema) }) }, /** Removes a worktree and its branch. Refused (`busy`) while a session uses it, or (`dirty`) when work in it would be lost, unless `force`. */ "worktrees.remove": { params: z.object({ path: z.string().min(1), force: z.boolean().optional() }), result: empty }, // ── Directories: pick where a new session runs ── /** Subdirectories of `path` (default: the home directory). */ "fs.list": { params: z.object({ path: z.string().optional(), hidden: z.boolean().default(false), /** Also list the directory's files (after its subdirectories), to browse a project. */ files: z.boolean().default(false), }), result: z.object({ path: z.string(), parent: z.string().optional(), home: z.string(), entries: z.array(directoryEntrySchema), /** The directory holds more than a listing carries (1000 entries). */ truncated: z.boolean().optional(), }), }, /** * A file's contents, for viewing. Text comes a part at a time: up to * `maxBytes` from `offset`, with `nextOffset` when more follows. A picture * comes whole, as base64. A binary file is only described, and a file too * big to look at on a phone (text over 20 MB, a picture over 10 MB) is * refused with `too_large`. */ "fs.read": { params: z.object({ path: z.string().min(1), offset: z.number().int().nonnegative().default(0), maxBytes: z.number().int().min(1).max(2_000_000).default(512_000), }), result: z.object({ path: z.string(), size: z.number().int(), modifiedAt: z.number(), kind: z.enum(["text", "image", "binary"]), text: z.string().optional(), data: z.string().optional(), mimeType: z.string().optional(), /** Text: more of the file follows this part. */ truncated: z.boolean(), /** Where the next part starts (pass it as `offset`). */ nextOffset: z.number().int().optional(), }), }, /** Original file bytes, in bounded chunks, independently of preview limits. */ "fs.download": { params: z.object({ path: z.string().min(1), offset: z.number().int().nonnegative().default(0), maxBytes: z.number().int().min(1).max(1_048_576).default(262_144), /** Subsequent chunks must still belong to the same file revision. */ revision: z.string().optional(), }), result: z.object({ size: z.number().int().nonnegative(), revision: z.string(), data: z.string(), nextOffset: z.number().int().nonnegative(), done: z.boolean(), }), }, /** * Saves a file from the device into `dir`. A name that's taken gets a * numbered suffix ("photo 2.jpg") rather than overwriting; subsequent chunks * pass `appendPath` and `offset` so each chunk stays below the relay frame cap. */ "fs.upload": { params: z.object({ dir: z.string().min(1), name: z.string().min(1).max(255), /** base64; up to ~20 MB single-shot upload (smaller when chunked via `offset`/`appendPath`). */ data: z.string().max(30_000_000), offset: z.number().int().nonnegative().optional(), appendPath: z.string().optional(), }), result: z.object({ path: z.string(), size: z.number().int() }), }, /** * Replaces a UTF-8 text file (or creates one in an existing directory), * atomically and keeping its mode. With `expectedModifiedAt` (the * `modifiedAt` the editor last read) a file changed on disk since is refused * with `conflict` instead of being overwritten. */ "fs.write": { params: z.object({ path: z.string().min(1), text: z.string(), expectedModifiedAt: z.number().optional(), }), result: z.object({ path: z.string(), modifiedAt: z.number(), size: z.number().int() }), }, /** Creates a directory `name` inside `parent`. */ "fs.mkdir": { params: z.object({ parent: z.string().min(1), name: z.string().min(1).max(255) }), result: z.object({ path: z.string() }), }, /** Directories under the home directory whose name contains `query`, projects first. */ "fs.search": { params: z.object({ query: z.string().min(1).max(200), limit: z.number().int().min(1).max(200).default(60) }), result: z.object({ entries: z.array(directoryEntrySchema), truncated: z.boolean() }), }, /** Fast project file listing under `cwd` (`git ls-files` with directory walk fallback) for `@file` autocomplete. */ "fs.projectFiles": { params: z.object({ cwd: z.string().min(1), query: z.string().max(200).optional(), limit: z.number().int().min(1).max(2000).optional(), }), result: z.object({ files: z.array(projectFileEntrySchema), truncated: z.boolean(), }), }, // ── Clipboard: encrypted host clipboard access ── "clipboard.read": { params: empty, result: z.object({ text: z.string() }), }, "clipboard.write": { params: z.object({ text: z.string().max(2_000_000) }), result: z.object({ ok: z.boolean() }), }, // ── Terminals: plain shells on the host, any command, like SSH ── "terminals.list": { params: empty, result: z.object({ terminals: z.array(terminalInfoSchema) }), }, "terminals.create": { params: z.object({ cwd: z.string().optional(), /** Open it for this session, in its directory unless `cwd` says otherwise (see `TerminalInfo.sessionId`). */ sessionId: z.string().optional(), /** Run this in the shell right away (the shell stays open after it). */ command: z.string().max(4000).optional(), cols: z.number().int().min(10).max(1000).default(80), rows: z.number().int().min(4).max(500).default(24), }), result: z.object({ terminal: terminalInfoSchema }), }, /** * Start receiving `terminal.output` for a terminal. With `fromSeq` the host * sends only newer output when it still has it; otherwise `replay` holds the * recent screen history to redraw from scratch. */ "terminals.attach": { params: z.object({ terminalId: z.string().min(1), fromSeq: z.number().int().min(0).optional(), replayFormat: z.literal("frames-v1").optional(), fromFrame: z.number().int().min(0).optional(), snapshot: z.boolean().optional() }), result: z.object({ terminal: terminalInfoSchema, /** Output to write before any `terminal.output` that follows. */ replay: z.string(), /** Clear the screen before writing `replay` (the host no longer has what came after `fromSeq`). */ reset: z.boolean(), /** The last output seq `replay` covers; later chunks arrive as `terminal.output`. */ seq: z.number().int(), recording: z.object({ afterFrame: z.number().int(), throughFrame: z.number().int() }).optional(), state: z.object({ snapshotId: z.string(), length: z.number().int().min(0), frame: z.number().int().min(0), cols: z.number().int().min(1), rows: z.number().int().min(1) }).optional(), }), }, "terminals.state": { params: z.object({ terminalId: z.string().min(1), snapshotId: z.string().min(1), offset: z.number().int().min(0) }), result: z.object({ data: z.string(), nextOffset: z.number().int().min(0), done: z.boolean() }), }, "terminals.replay": { params: z.object({ terminalId: z.string().min(1), afterFrame: z.number().int().min(0), throughFrame: z.number().int().min(0) }), result: z.object({ frames: z.array(z.object({ frame: z.number().int(), cols: z.number().int(), rows: z.number().int(), data: z.string() })), nextFrame: z.number().int(), done: z.boolean(), }), }, "terminals.detach": { params: z.object({ terminalId: z.string().min(1) }), result: empty, }, "terminals.input": { params: z.object({ terminalId: z.string().min(1), data: z.string().max(1_000_000) }), result: empty, }, "terminals.resize": { params: z.object({ terminalId: z.string().min(1), cols: z.number().int().min(10).max(1000), rows: z.number().int().min(4).max(500), }), result: empty, }, "terminals.close": { params: z.object({ terminalId: z.string().min(1) }), result: empty, }, // ── Previews: the host's local servers, reached through this channel ── /** Servers listening on the host that look like something to preview. */ "ports.list": { params: empty, result: z.object({ ports: z.array(portInfoSchema) }), }, /** * A TCP stream to `port` on the host's loopback, like `ssh -L`: the device * runs a local listener and carries each connection over this channel, so a * page, its WebSocket (hot reload) and its cookies all work unchanged. The * host's bytes arrive as `proxy.data`; the stream ends with `proxy.closed`. */ "proxy.open": { params: z.object({ port: z.number().int().min(1).max(65535), /** Carry the stream on the direct channel, if this connection has one open. */ direct: z.boolean().optional(), }), /** `channel`: the stream's number on the direct channel, when it goes there instead of over `proxy.*`. */ result: z.object({ streamId: z.string(), channel: z.number().int().nonnegative().optional() }), }, /** * Sets up the direct channel (see `direct.ts`): the device's WebRTC offer, * holding the `linkshell-bulk` data channel, answered by the host. Each side * has gathered its addresses before sending. A new offer replaces the * connection made by an earlier one. */ "direct.offer": { params: z.object({ sdp: z.string().min(1).max(200_000) }), result: z.object({ sdp: z.string() }), }, /** * Starts the host's screen viewer: a page plus H.264 stream on a loopback * port, opened like a preview (`proxy.open`) at `/?token=…&display=…`. */ "screen.start": { params: empty, result: z.object({ port: z.number().int(), token: z.string(), displays: z.array(z.object({ index: z.number().int(), name: z.string() })), }), }, /** * Whether this computer's screen can be watched and controlled: the capture * program, and the two permissions the system gives to an app by name. With * `ask`, the system puts its own question for the first one missing and opens * its settings page there, on the computer. */ "screen.access": { params: z.object({ ask: z.boolean().optional() }), result: z.object({ /** This kind of computer can show its screen at all. */ supported: z.boolean(), ffmpeg: z.boolean(), /** May record the screen / post pointer and key events; null where that isn't known. */ recording: z.boolean().nullable(), control: z.boolean().nullable(), /** The app the system lists for these permissions: the one to allow. */ app: z.string().optional(), /** Why the answer is missing, or what stands in the way besides the permissions. */ problem: z.string().optional(), }), }, /** Privacy curtain (dim/blank physical screen while viewing remotely) and auto-lock on disconnect. */ "screen.privacy": { params: z.object({ curtain: z.boolean().optional(), lockOnDisconnect: z.boolean().optional(), }), result: screenPrivacyStateSchema, }, /** Starts Fusion Mode's remote half on this computer and returns its control endpoint (docs/v2/fusion.md). */ "fusion.start": { params: empty, result: fusionStartResultSchema, }, /** Ends any Fusion session on this computer: windows go back where they were, virtual displays go. */ "fusion.stop": { params: empty, result: empty, }, /** Bytes to the host's end of a stream (base64). */ "proxy.write": { params: z.object({ streamId: z.string().min(1), data: z.string().max(2_000_000) }), result: empty, }, "proxy.close": { params: z.object({ streamId: z.string().min(1) }), result: empty, }, } as const; export const methods: typeof coreMethods & typeof acpMethods & typeof mcpMethods & typeof lsaMethods = { ...coreMethods, ...acpMethods, ...mcpMethods, ...lsaMethods, }; export type MethodName = keyof typeof methods; export type MethodParams = z.input<(typeof methods)[M]["params"]>; export type MethodResult = z.infer<(typeof methods)[M]["result"]>; export function isMethodName(name: string): name is MethodName { return Object.prototype.hasOwnProperty.call(methods, name); } // ── Notifications (host → client) ──────────────────────────────────── export const notifications = { "machine.changed": machineInfoSchema, "agent.changed": z.object({ agent: agentInfoSchema }), "agent.interaction": z.object({ agent: z.string(), request: z.union([pendingPermissionSchema, z.object({ requestId: z.string(), resolved: z.literal(true) })]) }), "session.notice": z.object({ sessionId: z.string(), notice: sessionNoticeSchema }), "session.event": sessionEventSchema, /** * Sent before a subscription's backlog when it doesn't continue from the * client's `fromSeq`: the events that follow start after `startSeq`, so a * client holding older events of this session drops them first. */ "session.window": z.object({ sessionId: z.string(), startSeq: z.number().int().nonnegative() }), "session.summary": z.object({ session: sessionSummarySchema }), /** A side conversation changed (to every client), or ended (`closed`). */ "session.side": z.object({ sessionId: z.string(), side: sideChatSchema, closed: z.boolean().optional() }), /** A session was deleted (from any device, or natively by the agent). */ "session.removed": z.object({ sessionId: z.string() }), "session.preview.show": z.object({ sessionId: z.string() }), /** To a desktop shim: a device is taking over; exit the native UI, then call desktop.yielded. */ "desktop.yield": z.object({ sessionId: z.string() }), /** To a desktop shim: progress from the remote driver, to show in the terminal. */ "desktop.remoteActivity": z.object({ sessionId: z.string(), line: z.string() }), "pairing.done": z.object({ device: z.object({ id: z.string(), name: z.string() }) }), "gateway.changed": gatewayStatusSchema, /** Output from an attached terminal, in order; `seq` increases by one per chunk. */ "terminal.output": z.object({ terminalId: z.string(), seq: z.number().int(), data: z.string(), frame: z.number().int().optional(), cols: z.number().int().optional(), rows: z.number().int().optional() }), /** A terminal's list entry changed (title, size, exit), or it was closed (`closed`). */ "terminal.changed": z.object({ terminal: terminalInfoSchema, closed: z.boolean().optional() }), /** Bytes from the host's end of a `proxy.open` stream (base64), in order. */ "proxy.data": z.object({ streamId: z.string(), data: z.string() }), /** The host's end of a stream closed (the server hung up, or refused). */ "proxy.closed": z.object({ streamId: z.string(), error: z.string().optional() }), /** Zero-plaintext transition wakeup metadata. */ "liveActivities.wakeup": wakeupNoticeSchema, } as const; export type NotificationName = keyof typeof notifications; export type NotificationParams = z.infer<(typeof notifications)[N]>;