diff --git a/.agents/skills/format-driving/references/tools.md b/.agents/skills/format-driving/references/tools.md index 5322fed..02c2cd4 100644 --- a/.agents/skills/format-driving/references/tools.md +++ b/.agents/skills/format-driving/references/tools.md @@ -287,15 +287,21 @@ Creates or replaces one memory file; Claude reads it the next time it checks its ### add_skill -Installs a skill from an uploaded .zip (its folder with SKILL.md) or SKILL.md file. A skill with the same name is replaced. Use after uploading a skill's .zip or SKILL.md, to install it in Format. +Installs a skill from an uploaded .zip (its folder with SKILL.md) or SKILL.md file. If a skill with the same name exists, nothing changes and it answers 409 with data.clash (name, suggested), unless overwrite is true (replace it) or name gives a new name (keep both). Use after uploading a skill's .zip or SKILL.md, to install it in Format; on a name already in use, ask the person before passing overwrite or a new name. -- changes state · command `skill.add` · params: `uploadId` string +- changes state · command `skill.add` · params: `uploadId` string, `overwrite?` boolean, `name?` string + +### check_skill_name + +Whether a skill name is already in use: exists, suggested (a free name to keep both under) and plugin (the plugin it came with, if any). Use before adding or writing a skill, to see whether its name is taken and which free name keeps both. + +- read-only · command `skill.clash` · params: `name` string ### create_skill -Creates a skill from a name, a description (when Claude should use it) and its instructions, written as its SKILL.md. Use to write a new skill for Format's Claude from a name, a description and instructions. +Creates a skill from a name, a description (when Claude should use it) and its instructions, written as its SKILL.md. A name already in use is refused with 409 unless overwrite is true. Use to write a new skill for Format's Claude from a name, a description and instructions. -- changes state · command `skill.create` · params: `name` string, `description` string, `instructions` string +- changes state · command `skill.create` · params: `name` string, `description` string, `instructions` string, `overwrite?` boolean ### delete_skill @@ -323,9 +329,9 @@ One skill: its SKILL.md and the list of its files. Use to read a skill's SKILL.m ### install_skill_from_marketplace -Installs one skill from a marketplace on its own, without its plugin. It is listed under From Anthropic and partners when the marketplace is Anthropic's, otherwise From marketplaces. Use to add one skill from a marketplace without its plugin. +Installs one skill from a marketplace on its own, without its plugin. It is listed under From Anthropic and partners when the marketplace is Anthropic's, otherwise From marketplaces. A name already in use is refused with 409 and data.clash unless overwrite is true or name gives a new one. Use to add one skill from a marketplace without its plugin. -- changes state · command `skill.installFrom` · params: `marketplace` string, `path` string +- changes state · command `skill.installFrom` · params: `marketplace` string, `path` string, `overwrite?` boolean, `name?` string ### list_skills @@ -561,7 +567,7 @@ Whether the built-in browser is installed and open, and its current page (url, t ### get_claude_code_status -Whether the Claude Code CLI is installed (its path and version) and which engine answers chats now: api (the Anthropic API key) or claude-code (the person's own Claude Code sign-in). programs says the same for each agent program FormAT looks for: claude, codex, cursor and antigravity (finding is runs, broken or missing; said is the sentence to show). Use when chats run without an API key, to see whether Claude Code is installed and whether it or the API key answers. +Whether the Claude Code CLI is installed (its path and version) and which engine answers chats now: api (the Anthropic API key) or claude-code (the person's own Claude Code sign-in). programs says the same for each agent program FormAT looks for: claude, codex, cursor and antigravity (finding is runs, broken or missing; said is the sentence to show). sandbox says whether Claude Code's own sandbox is on for its commands here (sandboxed, the host names they may reach from setting claudeCodeDomains, and note, the sentence to show). Use when chats run without an API key, to see whether Claude Code is installed and whether it or the API key answers. - read-only · command `claudecode.status` · params: none @@ -577,27 +583,45 @@ Returns the conversation of one demo, and puts the demo back first when it was d - changes state · command `demo.restore` · params: `id` string +### answer_device + +Answers a device that opened the pairing link and is waiting: allow pairs it, otherwise it is turned down. Only FormAT's window can run this. Only FormAT's window runs this; tell the person to allow or turn down a waiting device in Settings, Other devices. + +- changes state · command `devices.answer` · params: `id` string, `allow` boolean + ### forget_devices -Changes the pairing code, so every paired device has to pair again. Use when the person wants every paired device to pair again. +Unpairs every device at once, turns down any device still waiting and changes the pairing code, so each one has to pair again. Only FormAT's window can run this. Only FormAT's window runs this; tell the person to choose Forget paired devices in Settings, Other devices. - changes state · command `devices.forget` · params: none +### list_paired_devices + +The devices paired with Format: id, a name read from the device's browser, when it paired and when it was last seen. Use to see which phones and computers are paired and when each was last seen. + +- read-only · command `devices.list` · params: none + +### unpair_device + +Unpairs one device: its sign-in stops working at once, open connections from it close, and it has to pair again with a new code. Only FormAT's window can run this. Only FormAT's window runs this; tell the person to choose Unpair beside the device in Settings, Other devices. + +- changes state · command `devices.revoke` · params: `id` string + ### open_to_devices -Starts Format's network listener (port 8492) so a paired phone or computer on the same network can use Format, and shared links can be opened. Only paired devices reach chats; shared artifact links are read-only. Returns the pairing link and QR code. Use when the person wants to continue on their phone or another computer, or to share links beyond this computer. +Starts Format's https network listener (port 8492; the first start makes this install's own certificate) so a paired phone or computer on the same network can use Format, and shared links can be opened. Only paired devices reach chats; shared artifact links are read-only. Only FormAT's window can run this; it gets the pairing link and QR code back. Only FormAT's window runs this; tell the person to open Settings, Other devices, when they want to continue on their phone or another computer. - changes state · command `devices.start` · params: none ### get_devices_status -Whether Format is reachable from other devices on this network (a phone or another computer), its addresses, and, when on, the pairing link and its QR code as SVG. Use to see whether Format is open to the person's other devices and to get the pairing link. +Whether Format is reachable from other devices on this network (a phone or another computer), its https addresses, the listener certificate's SHA-256 fingerprint and the paired devices. Only FormAT's window also gets the pairing link, its QR code as SVG, how many seconds the code has left, and the devices waiting to be allowed. Use to see whether Format is open to the person's other devices and which devices are paired; the pairing link shows only in FormAT's window. - read-only · command `devices.status` · params: none ### close_to_devices -Stops the network listener; paired devices and shared links stop working until it starts again. Use when the person wants Format reachable from this computer only. +Stops the network listener; paired devices and shared links stop working until it starts again. Paired devices stay paired. Use when the person wants Format reachable from this computer only. - changes state · command `devices.stop` · params: none @@ -711,7 +735,7 @@ The plugins installed in Format: each bundles skills, commands (installed as ski ### get_sandbox_status -Whether Claude's bash commands run sandboxed on this computer (bubblewrap on Linux, sandbox-exec on macOS), whether the sandbox is on (setting sandbox) and whether it allows the network (setting sandboxNetwork). Use when a command Claude ran in Format failed on files outside its folder or on the network, to see whether the sandbox caused it. +Whether Claude's bash commands run sandboxed on this computer (bubblewrap on Linux, sandbox-exec on macOS), whether the sandbox is on (setting sandbox) and whether it allows the network (setting sandboxNetwork). claudeCode says the same for chats answered through Claude Code, which use Claude Code's own sandbox (sandboxed, domains, note). Use when a command Claude ran in Format failed on files outside its folder or on the network, to see whether the sandbox caused it. - read-only · command `sandbox.status` · params: none @@ -723,7 +747,7 @@ The chat settings: model, effort, thinking, permission mode, autoCompact and com ### set_setting -Sets one chat setting: model takes a model id from models.list, effort one of low, medium, high, xhigh, max, permissionMode ask, auto or plan, thinking (show Claude's thinking) true or false, autoCompact (summarize long chats) true or false, compactAt the share of the context window that triggers it, 0.05 to 0.95, webTools (web search and fetch) and workspaceTools (bash and files in the chat's folder) true or false, toolAllow and toolDeny lists of bash, write, edit, agentModel the sub-agents' model id (empty for the chat's model), agentLimit the most sub-agents in one reply, 0 to 10, artifactNetwork (let artifact pages load images and data from the internet) true or false, memory (Claude keeps notes across chats with the memory tool) true or false, outsideAgents (coding agents using Format over MCP) ask, allowed or blocked, sandbox (Claude's bash runs sandboxed: only the chat's folder writable, the home folder hidden) true or false, sandboxNetwork (let sandboxed commands reach the network) true or false, browserTools (Claude can use the built-in browser) true or false, chatEngine (who answers: auto uses the API key when set and otherwise the person's Claude Code sign-in, api, or claude-code) auto, api or claude-code. Use when the person asks for another model, effort, permission mode or tool setting; it applies to all chats. +Sets one chat setting: model takes a model id from models.list, effort one of low, medium, high, xhigh, max, permissionMode ask, auto or plan, thinking (show Claude's thinking) true or false, autoCompact (summarize long chats) true or false, compactAt the share of the context window that triggers it, 0.05 to 0.95, webTools (web search and fetch) and workspaceTools (bash and files in the chat's folder) true or false, toolAllow and toolDeny lists of bash, write, edit, agentModel the sub-agents' model id (empty for the chat's model), agentLimit the most sub-agents in one reply, 0 to 10, artifactNetwork (let artifact pages load images and data from the internet) true or false, memory (Claude keeps notes across chats with the memory tool) true or false, outsideAgents (coding agents using Format over MCP) ask, allowed or blocked, sandbox (Claude's bash runs sandboxed: only the chat's folder writable, the home folder hidden) true or false, sandboxNetwork (let sandboxed commands reach the network) true or false, browserTools (Claude can use the built-in browser) true or false, chatEngine (who answers: auto uses the API key when set and otherwise the person's Claude Code sign-in, api, or claude-code) auto, api or claude-code, claudeCodeDomains (the only host names Claude Code's sandboxed commands may reach, such as example.com or *.example.com; empty for no network) a list. Use when the person asks for another model, effort, permission mode or tool setting; it applies to all chats. - changes state · command `settings.set` · params: `key` string, `value` any diff --git a/.agents/skills/format-harness/references/command-map.md b/.agents/skills/format-harness/references/command-map.md index 721e39b..758f6f8 100644 --- a/.agents/skills/format-harness/references/command-map.md +++ b/.agents/skills/format-harness/references/command-map.md @@ -53,6 +53,7 @@ Generated by ./format agents sync from the engine's command registry; do not edi | `memory.read` | `./format cli memory.read path=...` | `read_memory_file` | Read a memory file | | `memory.write` | `./format cli memory.write path=... text=...` | `write_memory_file` | Write a memory file | | `skill.add` | `./format cli skill.add uploadId=...` | `add_skill` | Add a skill | +| `skill.clash` | `./format cli skill.clash name=...` | `check_skill_name` | Check a skill name | | `skill.create` | `./format cli skill.create name=... description=... instructions=...` | `create_skill` | Write a skill | | `skill.delete` | `./format cli skill.delete name=...` | `delete_skill` | Delete a skill | | `skill.discover` | `./format cli skill.discover` | `discover_skills` | Discover skills | @@ -99,7 +100,10 @@ Generated by ./format agents sync from the engine's command registry; do not edi | `claudecode.status` | `./format cli claudecode.status` | `get_claude_code_status` | Claude Code | | `demo.list` | `./format cli demo.list` | `list_demos` | Demos | | `demo.restore` | `./format cli demo.restore id=...` | `restore_demo` | Restore a demo chat | +| `devices.answer` | `./format cli devices.answer id=... allow=...` | `answer_device` | Allow or turn down a device | | `devices.forget` | `./format cli devices.forget` | `forget_devices` | Forget paired devices | +| `devices.list` | `./format cli devices.list` | `list_paired_devices` | Paired devices | +| `devices.revoke` | `./format cli devices.revoke id=...` | `unpair_device` | Unpair a device | | `devices.start` | `./format cli devices.start` | `open_to_devices` | Open to other devices | | `devices.status` | `./format cli devices.status` | `get_devices_status` | Other devices | | `devices.stop` | `./format cli devices.stop` | `close_to_devices` | Close to other devices | diff --git a/.agents/skills/format-harness/references/tool-map.md b/.agents/skills/format-harness/references/tool-map.md index a287136..35f6207 100644 --- a/.agents/skills/format-harness/references/tool-map.md +++ b/.agents/skills/format-harness/references/tool-map.md @@ -53,6 +53,7 @@ Generated by ./format agents sync from the engine's command registry; do not edi | `read_memory_file` | `memory.read` | `backend/app/engine/cmd_memory.py` | read | | `write_memory_file` | `memory.write` | `backend/app/engine/cmd_memory.py` | write | | `add_skill` | `skill.add` | `backend/app/engine/cmd_skill.py` | write | +| `check_skill_name` | `skill.clash` | `backend/app/engine/cmd_skill.py` | read | | `create_skill` | `skill.create` | `backend/app/engine/cmd_skill.py` | write | | `delete_skill` | `skill.delete` | `backend/app/engine/cmd_skill.py` | write | | `discover_skills` | `skill.discover` | `backend/app/engine/marketplaces.py` | read | @@ -99,7 +100,10 @@ Generated by ./format agents sync from the engine's command registry; do not edi | `get_claude_code_status` | `claudecode.status` | `backend/app/engine/claude_code.py` | read | | `list_demos` | `demo.list` | `backend/app/engine/cmd_demo.py` | read | | `restore_demo` | `demo.restore` | `backend/app/engine/cmd_demo.py` | write | +| `answer_device` | `devices.answer` | `backend/app/engine/devices.py` | write | | `forget_devices` | `devices.forget` | `backend/app/engine/devices.py` | write | +| `list_paired_devices` | `devices.list` | `backend/app/engine/devices.py` | read | +| `unpair_device` | `devices.revoke` | `backend/app/engine/devices.py` | write | | `open_to_devices` | `devices.start` | `backend/app/engine/devices.py` | write | | `get_devices_status` | `devices.status` | `backend/app/engine/devices.py` | read | | `close_to_devices` | `devices.stop` | `backend/app/engine/devices.py` | write | diff --git a/.claude/skills/format-driving/references/tools.md b/.claude/skills/format-driving/references/tools.md index 5322fed..02c2cd4 100644 --- a/.claude/skills/format-driving/references/tools.md +++ b/.claude/skills/format-driving/references/tools.md @@ -287,15 +287,21 @@ Creates or replaces one memory file; Claude reads it the next time it checks its ### add_skill -Installs a skill from an uploaded .zip (its folder with SKILL.md) or SKILL.md file. A skill with the same name is replaced. Use after uploading a skill's .zip or SKILL.md, to install it in Format. +Installs a skill from an uploaded .zip (its folder with SKILL.md) or SKILL.md file. If a skill with the same name exists, nothing changes and it answers 409 with data.clash (name, suggested), unless overwrite is true (replace it) or name gives a new name (keep both). Use after uploading a skill's .zip or SKILL.md, to install it in Format; on a name already in use, ask the person before passing overwrite or a new name. -- changes state · command `skill.add` · params: `uploadId` string +- changes state · command `skill.add` · params: `uploadId` string, `overwrite?` boolean, `name?` string + +### check_skill_name + +Whether a skill name is already in use: exists, suggested (a free name to keep both under) and plugin (the plugin it came with, if any). Use before adding or writing a skill, to see whether its name is taken and which free name keeps both. + +- read-only · command `skill.clash` · params: `name` string ### create_skill -Creates a skill from a name, a description (when Claude should use it) and its instructions, written as its SKILL.md. Use to write a new skill for Format's Claude from a name, a description and instructions. +Creates a skill from a name, a description (when Claude should use it) and its instructions, written as its SKILL.md. A name already in use is refused with 409 unless overwrite is true. Use to write a new skill for Format's Claude from a name, a description and instructions. -- changes state · command `skill.create` · params: `name` string, `description` string, `instructions` string +- changes state · command `skill.create` · params: `name` string, `description` string, `instructions` string, `overwrite?` boolean ### delete_skill @@ -323,9 +329,9 @@ One skill: its SKILL.md and the list of its files. Use to read a skill's SKILL.m ### install_skill_from_marketplace -Installs one skill from a marketplace on its own, without its plugin. It is listed under From Anthropic and partners when the marketplace is Anthropic's, otherwise From marketplaces. Use to add one skill from a marketplace without its plugin. +Installs one skill from a marketplace on its own, without its plugin. It is listed under From Anthropic and partners when the marketplace is Anthropic's, otherwise From marketplaces. A name already in use is refused with 409 and data.clash unless overwrite is true or name gives a new one. Use to add one skill from a marketplace without its plugin. -- changes state · command `skill.installFrom` · params: `marketplace` string, `path` string +- changes state · command `skill.installFrom` · params: `marketplace` string, `path` string, `overwrite?` boolean, `name?` string ### list_skills @@ -561,7 +567,7 @@ Whether the built-in browser is installed and open, and its current page (url, t ### get_claude_code_status -Whether the Claude Code CLI is installed (its path and version) and which engine answers chats now: api (the Anthropic API key) or claude-code (the person's own Claude Code sign-in). programs says the same for each agent program FormAT looks for: claude, codex, cursor and antigravity (finding is runs, broken or missing; said is the sentence to show). Use when chats run without an API key, to see whether Claude Code is installed and whether it or the API key answers. +Whether the Claude Code CLI is installed (its path and version) and which engine answers chats now: api (the Anthropic API key) or claude-code (the person's own Claude Code sign-in). programs says the same for each agent program FormAT looks for: claude, codex, cursor and antigravity (finding is runs, broken or missing; said is the sentence to show). sandbox says whether Claude Code's own sandbox is on for its commands here (sandboxed, the host names they may reach from setting claudeCodeDomains, and note, the sentence to show). Use when chats run without an API key, to see whether Claude Code is installed and whether it or the API key answers. - read-only · command `claudecode.status` · params: none @@ -577,27 +583,45 @@ Returns the conversation of one demo, and puts the demo back first when it was d - changes state · command `demo.restore` · params: `id` string +### answer_device + +Answers a device that opened the pairing link and is waiting: allow pairs it, otherwise it is turned down. Only FormAT's window can run this. Only FormAT's window runs this; tell the person to allow or turn down a waiting device in Settings, Other devices. + +- changes state · command `devices.answer` · params: `id` string, `allow` boolean + ### forget_devices -Changes the pairing code, so every paired device has to pair again. Use when the person wants every paired device to pair again. +Unpairs every device at once, turns down any device still waiting and changes the pairing code, so each one has to pair again. Only FormAT's window can run this. Only FormAT's window runs this; tell the person to choose Forget paired devices in Settings, Other devices. - changes state · command `devices.forget` · params: none +### list_paired_devices + +The devices paired with Format: id, a name read from the device's browser, when it paired and when it was last seen. Use to see which phones and computers are paired and when each was last seen. + +- read-only · command `devices.list` · params: none + +### unpair_device + +Unpairs one device: its sign-in stops working at once, open connections from it close, and it has to pair again with a new code. Only FormAT's window can run this. Only FormAT's window runs this; tell the person to choose Unpair beside the device in Settings, Other devices. + +- changes state · command `devices.revoke` · params: `id` string + ### open_to_devices -Starts Format's network listener (port 8492) so a paired phone or computer on the same network can use Format, and shared links can be opened. Only paired devices reach chats; shared artifact links are read-only. Returns the pairing link and QR code. Use when the person wants to continue on their phone or another computer, or to share links beyond this computer. +Starts Format's https network listener (port 8492; the first start makes this install's own certificate) so a paired phone or computer on the same network can use Format, and shared links can be opened. Only paired devices reach chats; shared artifact links are read-only. Only FormAT's window can run this; it gets the pairing link and QR code back. Only FormAT's window runs this; tell the person to open Settings, Other devices, when they want to continue on their phone or another computer. - changes state · command `devices.start` · params: none ### get_devices_status -Whether Format is reachable from other devices on this network (a phone or another computer), its addresses, and, when on, the pairing link and its QR code as SVG. Use to see whether Format is open to the person's other devices and to get the pairing link. +Whether Format is reachable from other devices on this network (a phone or another computer), its https addresses, the listener certificate's SHA-256 fingerprint and the paired devices. Only FormAT's window also gets the pairing link, its QR code as SVG, how many seconds the code has left, and the devices waiting to be allowed. Use to see whether Format is open to the person's other devices and which devices are paired; the pairing link shows only in FormAT's window. - read-only · command `devices.status` · params: none ### close_to_devices -Stops the network listener; paired devices and shared links stop working until it starts again. Use when the person wants Format reachable from this computer only. +Stops the network listener; paired devices and shared links stop working until it starts again. Paired devices stay paired. Use when the person wants Format reachable from this computer only. - changes state · command `devices.stop` · params: none @@ -711,7 +735,7 @@ The plugins installed in Format: each bundles skills, commands (installed as ski ### get_sandbox_status -Whether Claude's bash commands run sandboxed on this computer (bubblewrap on Linux, sandbox-exec on macOS), whether the sandbox is on (setting sandbox) and whether it allows the network (setting sandboxNetwork). Use when a command Claude ran in Format failed on files outside its folder or on the network, to see whether the sandbox caused it. +Whether Claude's bash commands run sandboxed on this computer (bubblewrap on Linux, sandbox-exec on macOS), whether the sandbox is on (setting sandbox) and whether it allows the network (setting sandboxNetwork). claudeCode says the same for chats answered through Claude Code, which use Claude Code's own sandbox (sandboxed, domains, note). Use when a command Claude ran in Format failed on files outside its folder or on the network, to see whether the sandbox caused it. - read-only · command `sandbox.status` · params: none @@ -723,7 +747,7 @@ The chat settings: model, effort, thinking, permission mode, autoCompact and com ### set_setting -Sets one chat setting: model takes a model id from models.list, effort one of low, medium, high, xhigh, max, permissionMode ask, auto or plan, thinking (show Claude's thinking) true or false, autoCompact (summarize long chats) true or false, compactAt the share of the context window that triggers it, 0.05 to 0.95, webTools (web search and fetch) and workspaceTools (bash and files in the chat's folder) true or false, toolAllow and toolDeny lists of bash, write, edit, agentModel the sub-agents' model id (empty for the chat's model), agentLimit the most sub-agents in one reply, 0 to 10, artifactNetwork (let artifact pages load images and data from the internet) true or false, memory (Claude keeps notes across chats with the memory tool) true or false, outsideAgents (coding agents using Format over MCP) ask, allowed or blocked, sandbox (Claude's bash runs sandboxed: only the chat's folder writable, the home folder hidden) true or false, sandboxNetwork (let sandboxed commands reach the network) true or false, browserTools (Claude can use the built-in browser) true or false, chatEngine (who answers: auto uses the API key when set and otherwise the person's Claude Code sign-in, api, or claude-code) auto, api or claude-code. Use when the person asks for another model, effort, permission mode or tool setting; it applies to all chats. +Sets one chat setting: model takes a model id from models.list, effort one of low, medium, high, xhigh, max, permissionMode ask, auto or plan, thinking (show Claude's thinking) true or false, autoCompact (summarize long chats) true or false, compactAt the share of the context window that triggers it, 0.05 to 0.95, webTools (web search and fetch) and workspaceTools (bash and files in the chat's folder) true or false, toolAllow and toolDeny lists of bash, write, edit, agentModel the sub-agents' model id (empty for the chat's model), agentLimit the most sub-agents in one reply, 0 to 10, artifactNetwork (let artifact pages load images and data from the internet) true or false, memory (Claude keeps notes across chats with the memory tool) true or false, outsideAgents (coding agents using Format over MCP) ask, allowed or blocked, sandbox (Claude's bash runs sandboxed: only the chat's folder writable, the home folder hidden) true or false, sandboxNetwork (let sandboxed commands reach the network) true or false, browserTools (Claude can use the built-in browser) true or false, chatEngine (who answers: auto uses the API key when set and otherwise the person's Claude Code sign-in, api, or claude-code) auto, api or claude-code, claudeCodeDomains (the only host names Claude Code's sandboxed commands may reach, such as example.com or *.example.com; empty for no network) a list. Use when the person asks for another model, effort, permission mode or tool setting; it applies to all chats. - changes state · command `settings.set` · params: `key` string, `value` any diff --git a/.claude/skills/format-harness/references/command-map.md b/.claude/skills/format-harness/references/command-map.md index 721e39b..758f6f8 100644 --- a/.claude/skills/format-harness/references/command-map.md +++ b/.claude/skills/format-harness/references/command-map.md @@ -53,6 +53,7 @@ Generated by ./format agents sync from the engine's command registry; do not edi | `memory.read` | `./format cli memory.read path=...` | `read_memory_file` | Read a memory file | | `memory.write` | `./format cli memory.write path=... text=...` | `write_memory_file` | Write a memory file | | `skill.add` | `./format cli skill.add uploadId=...` | `add_skill` | Add a skill | +| `skill.clash` | `./format cli skill.clash name=...` | `check_skill_name` | Check a skill name | | `skill.create` | `./format cli skill.create name=... description=... instructions=...` | `create_skill` | Write a skill | | `skill.delete` | `./format cli skill.delete name=...` | `delete_skill` | Delete a skill | | `skill.discover` | `./format cli skill.discover` | `discover_skills` | Discover skills | @@ -99,7 +100,10 @@ Generated by ./format agents sync from the engine's command registry; do not edi | `claudecode.status` | `./format cli claudecode.status` | `get_claude_code_status` | Claude Code | | `demo.list` | `./format cli demo.list` | `list_demos` | Demos | | `demo.restore` | `./format cli demo.restore id=...` | `restore_demo` | Restore a demo chat | +| `devices.answer` | `./format cli devices.answer id=... allow=...` | `answer_device` | Allow or turn down a device | | `devices.forget` | `./format cli devices.forget` | `forget_devices` | Forget paired devices | +| `devices.list` | `./format cli devices.list` | `list_paired_devices` | Paired devices | +| `devices.revoke` | `./format cli devices.revoke id=...` | `unpair_device` | Unpair a device | | `devices.start` | `./format cli devices.start` | `open_to_devices` | Open to other devices | | `devices.status` | `./format cli devices.status` | `get_devices_status` | Other devices | | `devices.stop` | `./format cli devices.stop` | `close_to_devices` | Close to other devices | diff --git a/.claude/skills/format-harness/references/tool-map.md b/.claude/skills/format-harness/references/tool-map.md index a287136..35f6207 100644 --- a/.claude/skills/format-harness/references/tool-map.md +++ b/.claude/skills/format-harness/references/tool-map.md @@ -53,6 +53,7 @@ Generated by ./format agents sync from the engine's command registry; do not edi | `read_memory_file` | `memory.read` | `backend/app/engine/cmd_memory.py` | read | | `write_memory_file` | `memory.write` | `backend/app/engine/cmd_memory.py` | write | | `add_skill` | `skill.add` | `backend/app/engine/cmd_skill.py` | write | +| `check_skill_name` | `skill.clash` | `backend/app/engine/cmd_skill.py` | read | | `create_skill` | `skill.create` | `backend/app/engine/cmd_skill.py` | write | | `delete_skill` | `skill.delete` | `backend/app/engine/cmd_skill.py` | write | | `discover_skills` | `skill.discover` | `backend/app/engine/marketplaces.py` | read | @@ -99,7 +100,10 @@ Generated by ./format agents sync from the engine's command registry; do not edi | `get_claude_code_status` | `claudecode.status` | `backend/app/engine/claude_code.py` | read | | `list_demos` | `demo.list` | `backend/app/engine/cmd_demo.py` | read | | `restore_demo` | `demo.restore` | `backend/app/engine/cmd_demo.py` | write | +| `answer_device` | `devices.answer` | `backend/app/engine/devices.py` | write | | `forget_devices` | `devices.forget` | `backend/app/engine/devices.py` | write | +| `list_paired_devices` | `devices.list` | `backend/app/engine/devices.py` | read | +| `unpair_device` | `devices.revoke` | `backend/app/engine/devices.py` | write | | `open_to_devices` | `devices.start` | `backend/app/engine/devices.py` | write | | `get_devices_status` | `devices.status` | `backend/app/engine/devices.py` | read | | `close_to_devices` | `devices.stop` | `backend/app/engine/devices.py` | write | diff --git a/.docs/wiki/Architecture.md b/.docs/wiki/Architecture.md index e7d395a..d09be1e 100644 --- a/.docs/wiki/Architecture.md +++ b/.docs/wiki/Architecture.md @@ -32,8 +32,8 @@ The engine owns all state: | Where | Holds | | --- | --- | -| `data/format.db` (SQLite, WAL, schema 8) | conversations, messages (a tree by `parent_id`), artifacts and versions, projects, connectors, schedules and runs, shares, `meta` key-values (settings, tasks, outputs) | -| `data/` folders | uploads, memory, skills, plugins, exports, snapshots, the browser profile, the pairing secret, saved keys | +| `data/format.db` (SQLite, WAL, schema 9) | conversations, messages (a tree by `parent_id`), artifacts and versions, projects, connectors, schedules and runs, shares, paired devices (a SHA-256 of each device token, never the token), `meta` key-values (settings, tasks, outputs) | +| `data/` folders | uploads, memory, skills, plugins, exports, snapshots, the browser profile, the one-time pairing code (`pairing.json`), the devices listener's certificate and private key (`devices/`, 0600), saved keys | | `workspace/chats/` | each chat's own folder for Claude's tools | Demo chats are ordinary rows: at start `engine/demos.py` reads each folder under `app/demos` and, once per data folder, writes its conversation, messages, artifact and output files (`conversations.demo` names the demo; `meta` key `demos.seeded` remembers which were added, so a deleted demo stays deleted until `demo.restore`). `meta` key `demos.shipped` records, per demo, a digest of the shipped `chat.json`, page and `files/` plus the title and file list it was made with. When the digest of the app's copy differs (or is missing, as in a data folder made before this existed) and the chat is still as made (title as shipped, only the recorded messages in one unbranched line ending in the recorded reply, only its own one-version artifact, no other files in its folder), `demos.update_if_stale` rebuilds it in place at the next start: same conversation id, pin, project and place in the list, share links moved to the new artifact. A chat the person renamed, continued, edited or branched is left alone. A demo is added by its folder alone: `chat.json` and the page, plus an optional `about.json` (`blurb`, one line for the Help menu, and `order`, an integer, 1000 when missing); `demo.list` returns them sorted by `order` and the window takes its list, menu entries and sidebar order from it. @@ -51,4 +51,4 @@ The window keeps only view state, and layout state (sidebar, panel, terminal, si | Local dictation | `./format install-voice` | `engine/voice.py` | | Built-in browser | `./format install-browser` | `engine/browser.py` | | Native renderer | `./format native build`, `FORMAT_NATIVE=1` | `engine/native.py`, `native/format-render` | -| Other devices | Settings, Other devices | `engine/devices.py` (second server on 8492) | +| Other devices | Settings, Other devices | `engine/devices.py` (second server on 8492, https only), `engine/lan_cert.py`, `engine/device_tokens.py` | diff --git a/.docs/wiki/Engine.md b/.docs/wiki/Engine.md index ebea204..2a8931a 100644 --- a/.docs/wiki/Engine.md +++ b/.docs/wiki/Engine.md @@ -25,7 +25,9 @@ Python 3.12, FastAPI, in `backend/app`. | `engine/projects.py`, `memory.py`, `skills.py`, `connectors.py`, `plugins.py` | projects, memory, skills, MCP connectors, plugins | | `engine/schedules.py` | scheduled tasks on a scheduler thread | | `engine/terminal.py` | PTY terminals and the Claude tab | -| `engine/devices.py` | the LAN server, pairing, share links | +| `engine/devices.py` | the LAN server (TLS only), the gate, one-time pairing codes that run out after five minutes, the pairing requests the window allows or turns down, share links | +| `engine/lan_cert.py` | the listener's self-signed certificate and key, made once per install, and its SHA-256 fingerprint | +| `engine/device_tokens.py` | per-device tokens (stored as hashes), unpairing, closing a revoked device's open connections | | `engine/browser.py` | the built-in browser on its worker thread | | `engine/voice.py` | transcription | | `mcp_server.py`, `mcp_stdio.py`, `agent_guide.py` | Format as an MCP server | diff --git a/CLAUDE.md b/CLAUDE.md index bf4bdce..dc75d6b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ A.T, the Agentic Terminal: a chat and agent workspace on the Claude API, in the - `frontend/src/styles/` holds the family's vendored Studio Dark sheets unchanged (`tokens.css`, `scrollbars.css`, `fonts.css`, `shell.css`, `dialogs.css`, `light-mode.css`) beside Format's own `ft-*.css` (`ft-` classes). Colours and z-index come from tokens only. - `native/format-render` is the family-standard wgpu crate (`Gpu`, `budget`, opt-in `native_start` on FORMAT_NATIVE): a terminal glyph grid (vt100 screen, fontdue atlas, one full-screen shader) with a CLI binary (`info`, `snapshot`) and a winit demo window behind the `window` feature. The engine calls the binary from `backend/app/engine/native.py` (`native.status`, `terminal.snapshot`); nothing runs while FORMAT_NATIVE is unset, and the window's terminal stays xterm. - `backend/app/harness/` is the only place a Claude API request is built (system prompt, content blocks, effort, thinking, caching); `backend/app/providers/` holds one adapter per provider. Chat runs through `chat.send`, `chat.stop`, `chat.retry`, `chat.edit`, `chat.branch`, `chat.compact` and `chat.wait`; a stored compaction block (beta `compact-2026-09-04`) starts every later request, and attachments of 1 MB or more go through the Files API; keys through `keys.set`, `keys.clear`, `keys.status`. A chat is a tree of messages (`parent_id`) with `conversations.leaf_id` marking the path on screen; `messages_of` returns that path. -- Tools live in `backend/app/engine/tools.py` (definitions, the per-chat folder `workspace/chats/`, approvals, executors); the loop is `chat._run`, which keeps a whole multi-round reply in one message with `tool_result` blocks inline and lets `harness.api_messages` split it for the API. Approvals: `tool.approve`, `tool.pending`; questions: `tool.answer`; the plan and the files Claude sends: `tasks.get`, `outputs.list`, downloads under `/api/chats/{id}/`. Sub-agents (`spawn_agent`) run inside the parent's tool call (`chat._run_agent`) and keep their transcript in `meta.agents`. Artifacts (`publish_artifact`, `backend/app/engine/artifacts.py`) are versioned rows served at `/api/artifacts/{id}/v/{n}` under a sandboxing CSP; the window shows them in `frontend/src/ui/artifact-panel.ts`, never with `allow-same-origin`. The chat folder's files come through `files.list` and `files.read` and preview in `frontend/src/ui/files-pane.ts`, which shares the side track with the artifact panel (`data-ft-side`); comments on them travel in `chat.send` `comments`. Projects (`backend/app/engine/projects.py`, `cmd_project.py`) hold instructions and knowledge files (uploads); `projects.context` is read at the start of each reply, and `harness.build` puts the instructions in the system prompt and the files at the start of the first user turn. Memory (`memory.py`) runs Anthropic's client-side memory tool on `data/memory` (general or per project); skills (`skills.py`) are SKILL.md folders in `data/skills`, listed in the system prompt and loaded through the `skill` tool. Connectors (`connectors.py`) send public https MCP servers through the API's MCP connector (`mcp_servers`, `mcp_toolset`, beta `mcp-client-2025-11-20`) and run every other server in the engine with the `mcp` SDK, as client tools named `mcp____` that go through approvals. Format is itself an MCP server (`backend/app/mcp_server.py`, generated from the command registry: a tool per command with `.` as `_`, plus `run_command`, chat and artifact resources, three prompts), served at `/mcp` (`routers/mcp_http.py`, Streamable HTTP) and over stdio by `./format mcp` (`mcp_stdio.py`, a proxy to the running engine's REST API with header `x-format-agent`). Outside agents pass `agents.require` (setting `outsideAgents`: ask, allowed, blocked; ask publishes `agents.consent` and waits for the window). Scheduled tasks (`backend/app/engine/schedules.py`, tables `schedules` and `schedule_runs`, schema 7) run on a scheduler thread started with the engine; each run is `chat.send` into a new chat, and `background.list` reports every chat working or waiting. Documents, spreadsheets and decks are artifact kinds written by `write_document` and exported by `documents.py`. Other devices (`backend/app/engine/devices.py`) run a second, cookie-gated server on port 8492 only while the person turns it on; share links (`artifact.share`, table `shares`, schema 8) are served at `/s/{token}`. Plugins (`plugins.py`) install a Claude plugin folder's skills, commands and MCP servers as Format skills and connectors and track them in `data/plugins//.format-plugin.json`. The built-in browser (`browser.py`, optional Playwright) runs on one worker thread; Claude's `browser` tool and the window's Browser pane (`frontend/src/ui/browser-pane.ts`) drive the same page. +- Tools live in `backend/app/engine/tools.py` (definitions, the per-chat folder `workspace/chats/`, approvals, executors); the loop is `chat._run`, which keeps a whole multi-round reply in one message with `tool_result` blocks inline and lets `harness.api_messages` split it for the API. Approvals: `tool.approve`, `tool.pending`; questions: `tool.answer`; the plan and the files Claude sends: `tasks.get`, `outputs.list`, downloads under `/api/chats/{id}/`. Sub-agents (`spawn_agent`) run inside the parent's tool call (`chat._run_agent`) and keep their transcript in `meta.agents`. Artifacts (`publish_artifact`, `backend/app/engine/artifacts.py`) are versioned rows served at `/api/artifacts/{id}/v/{n}` under a sandboxing CSP; the window shows them in `frontend/src/ui/artifact-panel.ts`, never with `allow-same-origin`. The chat folder's files come through `files.list` and `files.read` and preview in `frontend/src/ui/files-pane.ts`, which shares the side track with the artifact panel (`data-ft-side`); comments on them travel in `chat.send` `comments`. Projects (`backend/app/engine/projects.py`, `cmd_project.py`) hold instructions and knowledge files (uploads); `projects.context` is read at the start of each reply, and `harness.build` puts the instructions in the system prompt and the files at the start of the first user turn. Memory (`memory.py`) runs Anthropic's client-side memory tool on `data/memory` (general or per project); skills (`skills.py`) are SKILL.md folders in `data/skills`, listed in the system prompt and loaded through the `skill` tool. Connectors (`connectors.py`) send public https MCP servers through the API's MCP connector (`mcp_servers`, `mcp_toolset`, beta `mcp-client-2025-11-20`) and run every other server in the engine with the `mcp` SDK, as client tools named `mcp____` that go through approvals. Format is itself an MCP server (`backend/app/mcp_server.py`, generated from the command registry: a tool per command with `.` as `_`, plus `run_command`, chat and artifact resources, three prompts), served at `/mcp` (`routers/mcp_http.py`, Streamable HTTP) and over stdio by `./format mcp` (`mcp_stdio.py`, a proxy to the running engine's REST API with header `x-format-agent`). Outside agents pass `agents.require` (setting `outsideAgents`: ask, allowed, blocked; ask publishes `agents.consent` and waits for the window). Scheduled tasks (`backend/app/engine/schedules.py`, tables `schedules` and `schedule_runs`, schema 7) run on a scheduler thread started with the engine; each run is `chat.send` into a new chat, and `background.list` reports every chat working or waiting. Documents, spreadsheets and decks are artifact kinds written by `write_document` and exported by `documents.py`. Other devices (`backend/app/engine/devices.py`) run a second, https-only server on port 8492 only while the person turns it on, with a per-install certificate (`lan_cert.py`, fingerprint in the pairing code) and a revocable token per paired device (`device_tokens.py`, table `paired_devices`, schema 9); share links (`artifact.share`, table `shares`, schema 8) are served at `/s/{token}`. Plugins (`plugins.py`) install a Claude plugin folder's skills, commands and MCP servers as Format skills and connectors and track them in `data/plugins//.format-plugin.json`. The built-in browser (`browser.py`, optional Playwright) runs on one worker thread; Claude's `browser` tool and the window's Browser pane (`frontend/src/ui/browser-pane.ts`) drive the same page. - Terminals are engine PTYs (`backend/app/engine/terminal.py`): the window's dock attaches over `WS /api/terminal/{id}`, and `terminal.write` and `terminal.read` let the CLI and agents use the same shells. Claude's own bash commands are mirrored into one read-only session of kind `agent` (no PTY), shown as the Claude tab. Layout state (sidebar, panel, terminal) lives on `documentElement` data attributes set before first paint. - The manual for people using Format is `docs/`; the developer wiki is `.docs/wiki` (architecture, engine, window, agents, checks, releasing); `BRANCHING.md` covers branches and tags. Update the manual page a change shows on. - Planning documents (DEV_PLAN, BUILD_NOTES, UI_STUDY, PARITY_BASELINE, the root HASHOUT_LOG) ship in the planning sidecar zip, not in this tree. The living logs `frontend/HASHOUT_LOG.md` and `backend/HASHOUT_LOG.md` are in the tree: read them before editing. diff --git a/NOTICE.md b/NOTICE.md index 3fa9ec9..3889eeb 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -102,6 +102,7 @@ Two page quirks: the Miranda page lists its download under the name `Uranus - Ar | Libraries inside the Pillow wheel | libjpeg, libpng, libtiff, libwebp, libavif, OpenJPEG, Little CMS, HarfBuzz, Brotli, zstd, xz, libxcb: permissive (see the wheel's LICENSE); FreeType 2.14.3 used under the FreeType License | Portions of this software are copyright (c) 2026 The FreeType Project (www.freetype.org). All rights reserved. | | certifi | MPL-2.0 | engine: its `cacert.pem`, frozen unedited | | segno | BSD-3-Clause | the pairing QR code | +| cryptography 50.0.2 | Apache-2.0 OR BSD-3-Clause (its wheel bundles OpenSSL 3, Apache-2.0) | makes the other-devices listener's own certificate and key | | keyring | MIT | keeps the key that seals the outside-agent choice in the system keychain | | FastAPI, Starlette, Pydantic | MIT | engine | | Uvicorn, httpx | BSD-3-Clause | engine | diff --git a/SECURITY.md b/SECURITY.md index 962ae77..012e005 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -30,9 +30,11 @@ something outside it could get in: reachable from another machine, or lets a web page on another origin drive it. - **Other devices** (off by default): the second listener on port 8492 that opens only while the person turns it on. Reaching chats from a device that is not paired, - guessing or reusing the pairing link, keeping access after Forget paired devices or - Close to other devices, or a share link opening more than the one artifact it was - made for, or still answering after Stop sharing. + guessing or reusing the pairing link, keeping access after Unpair, Forget paired + devices or Close to other devices, the listener answering without TLS or with a + certificate other than the one whose fingerprint the pairing code carries, or a + share link opening more than the one artifact it was made for, or still answering + after Stop sharing. - **Agents and the MCP server** (`/mcp`, and `./format mcp` over stdio): an agent acting before the person has allowed outside agents in Settings. - **Approvals and Claude's tools**: a command, file change, browser action or local diff --git a/agents/manifest.json b/agents/manifest.json index 3148185..c76320f 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -49,7 +49,10 @@ "set_connector_in_conversation", "list_demos", "restore_demo", + "answer_device", "forget_devices", + "list_paired_devices", + "unpair_device", "open_to_devices", "get_devices_status", "close_to_devices", @@ -98,6 +101,7 @@ "get_settings", "set_setting", "add_skill", + "check_skill_name", "create_skill", "delete_skill", "discover_skills", @@ -136,6 +140,7 @@ "get_conversation", "list_conversations", "list_demos", + "list_paired_devices", "get_devices_status", "list_chat_files", "read_chat_file", @@ -155,6 +160,7 @@ "get_schedule", "list_schedules", "get_settings", + "check_skill_name", "discover_skills", "get_skill", "list_skills", @@ -210,7 +216,10 @@ "set_connector_in_conversation", "list_demos", "restore_demo", + "answer_device", "forget_devices", + "list_paired_devices", + "unpair_device", "open_to_devices", "get_devices_status", "close_to_devices", @@ -259,6 +268,7 @@ "get_settings", "set_setting", "add_skill", + "check_skill_name", "create_skill", "delete_skill", "discover_skills", diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index f8120cd..805eb03 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1355,3 +1355,75 @@ Git transports. Every git call runs with `protocol.ext.allow=never`, so a source Tool processes, second pass. `_kill` waits up to 3 seconds for the whole process group, not only its leader, and then sends SIGKILL to the group if anything in it still runs, so a child that ignores SIGTERM ends too (tests/test_tool_processes.py). The shared finder, version 1.0.2 (app/engine/agent_lookup.py, hash in setup/agents.py `LOOKUP_HASHES`). On Windows `start_argv` no longer puts cmd.exe in front of an npm, pnpm or bun shim: `shim_target` reads the .cmd and runs the .exe it names, or node.exe (beside the shim, then on PATH) and the script it names. A shim of another kind still goes through cmd.exe, now with /d, and only when every word, the program's path included, passes `cmd_safe`: none of & | < > ^ ( ) ! % " and no control character (\x00-\x1f, \x7f), with or without spaces, because the shim reads its arguments again through %* and quoting does not hold there; otherwise the start is refused with an OSError that says to pass long text through stdin or a file. A name ending in .cmd or .bat followed by dots or spaces counts as a shim too. The Claude Code chat run passes its child environment to `start_argv`, so node is looked for on the same PATH the program gets (tests/test_windows_start.py; not run on Windows). The other Form engines still carry 1.0.1. + +### Other devices over TLS with a token per device (unreleased) +- refers-to: app/engine/lan_cert.py :: ensure, fingerprint, write_private; app/engine/device_tokens.py :: issue, check, revoke, revoke_all, watch; app/engine/devices.py :: Gate, _pair, _held, _code, _spend, listener_config, status, devices_list, devices_revoke, devices_forget; app/engine/store.py :: paired_devices (schema 9); app/core/local_guard.py :: LocalGuard._permitted; requirements.txt, requirements_macos.txt :: cryptography +- kind: decision +- logged: unreleased + +The owner's decision: the devices listener speaks TLS only, with a certificate made per install, its fingerprint in the pairing code, and a revocable token per device in place of the one shared pairing secret. + +Certificate. `lan_cert.ensure` makes an EC P-256 self-signed certificate on the first devices.start (CN "FormAT paired devices", SAN localhost, 127.0.0.1 and the LAN addresses of that moment, EKU serverAuth, not a CA) and keeps it in `data/devices/listener.crt` with its key in `listener.key`, written through a 0600 temporary file and os.replace, so the key is never readable by others even for a moment. It is reused while it matches its key and has more than 30 days left; the life is 825 days because iOS refuses server certificates that last longer. A new address does not make a new certificate (the browser warns about the name, as it already does about the issuer), because a new certificate means a new warning and a new fingerprint on every device. cryptography was already frozen into the engine through pyjwt's extra; it is now pinned directly in both lists and has its own NOTICE row. + +TLS only. `listener_config` gives uvicorn the certificate and key, so a plain http request to 8492 fails the handshake and gets no HTTP answer (seen in tests/test_artifacts_and_devices.py with a real uvicorn on a free port, which also pins the served certificate by its fingerprint). The Gate also answers 426 to any scope that is not https or wss, as a second line in case the listener is ever built without TLS. + +Pinning. A browser cannot be told to pin a certificate from a link, so the pairing link carries `fp=` and the window shows the same fingerprint for the person to compare with the browser's certificate warning; the browser then keeps its exception for that one certificate. `/pair` refuses a link whose fingerprint is not this install's, so a code shown for another certificate never pairs. A client that can pin (a future companion app) reads `fp` from the code. + +Tokens. `pairing.json` holds a one-time code (key `code`; the old `secret` key is not read, so the old shared secret is retired on upgrade and old cookies stop working). `/pair` checks fingerprint and code, spends the code under a lock (two scans of one code pair one device), issues a 32-byte token in cookie `format_device` (HttpOnly, Secure, SameSite=Lax; Strict would drop the cookie on the redirect that follows a scan) and stores only its SHA-256 in `paired_devices` with a name read from the User-Agent. `last seen` is written at most once a minute per device. devices.list and devices.status never return a token or its hash. + +Revocation. devices.revoke deletes one row and devices.forget all of them (and changes the code). Every paired request runs under `_held`, which watches an asyncio.Event per device; revoking sets it through call_soon_threadsafe from the command thread, the request task is cancelled, and a WebSocket gets close 4401 (an HTTP request that has not started its answer gets the not-paired page). New requests fail at once because each one looks its token up again. The token lookup and the watch are two steps, and devices.revoke runs on a command thread, so an unpair landing between them would leave that request unwatched; `_held` therefore checks the device row again after the watch is in place (`device_tokens.alive`) and refuses if it is gone. + +LocalGuard. Its same-origin fallback compared the Origin only as http, so a paired page served over https would have been refused; it now compares with the request's own scheme. + +Not done here: the window's new Paired devices list and fingerprint line were type-checked and built but not driven in a throttled browser; a renewal of the certificate is not announced in the window beyond the new fingerprint it shows. + +### Pairing asks the window, codes run out, and pairing is window-only (unreleased) +- refers-to: app/engine/devices.py :: CODE_LIFE, REQUEST_LIFE, WAIT_COOKIE, _read_code, _current_code, _spend, _ask, _request_of, _settle, _collect, _forget_requests, pending, answer, Gate._pair, Gate._wait, Gate._held, _device_of, status, devices_answer; app/engine/commands.py :: Spec.window_only, window_only; app/core/window_key.py :: own_window; app/engine/agents.py :: refuse_window_only, outside_result; app/routers/commands.py :: run; app/routers/mcp_http.py :: _call +- kind: decision +- logged: unreleased + +The owner's decision, in three parts. + +Window-only. `is_window` is true for a paired device too (it has to be, so a phone can chat), so it cannot tell the computer's own window from a phone. `own_window` is true only for a scope with the window key and without `format.paired`. A command registered with `window_only=True` (devices.start, devices.revoke, devices.forget, devices.answer) is refused with 403 on the REST route for anything that is not the own window, also when it carries `x-format-agent`, and always on the MCP route. Results for anyone but the own window pass through `outside_result`, which drops `pairUrl`, `qr`, `pairExpiresIn` and `pending` from a devices result, so a paired device or an agent never sees the code. devices.stop stays open to a paired device: it can only cut itself off. + +Codes run out. `pairing.json` now holds `made` beside `code`; a code older than CODE_LIFE (300 s) is not read, so `_spend` refuses it and the next status makes a new one. A file without `made` (written by the previous step on this branch) reads as expired. The window gets `pairExpiresIn` and asks for status again when it reaches zero, so the QR it shows is never stale for long. + +The window confirms each device. The fingerprint in the link is checked by the server against its own certificate, which proves nothing about the phone's connection: a man in the middle forwards the same link. So `/pair` no longer issues a token. It spends the code, records a request in memory (id, the User-Agent name, a six-digit check number, the SHA-256 of a wait secret, state) and redirects to `/pair/wait` with the wait secret in cookie `format_pair_wait` (Path=/pair, HttpOnly, Secure, five minutes). The wait page shows the name, the check number and the certificate fingerprint, and refreshes every 2 s. The window lists the request with the same three things; devices.answer marks it allowed or turned down. Only the next wait poll that finds it allowed takes it out of the table and issues the device token, both under the lock (`_collect`), so two polls cannot pair twice; devices.forget drops the requests and unpairs every device under the same lock (`_forget_requests(unpair=True)`), so a forget cannot land between taking an allowed request and issuing its token and leave that device paired. A request runs out after REQUEST_LIFE (300 s); devices.forget and stopping the listener drop every request. The wait cookie opens nothing else (the gate looks only for `format_device`). The check number lets the person tell their own phone's request from another one made with the same code at the same moment. The phone page's fingerprint is for comparing with the browser's certificate details; the page itself would be forwarded by a middle party, which is why the browser's own certificate view is the one to read. + +Admission. `_held` used to re-check the device row after the watch was registered. It now re-checks the token itself (`device_tokens.check(token) == device`), so a device whose row is gone, or whose token no longer matches, at that moment is refused; `device_tokens.alive` is gone. tests/test_device_pairing_consent.py covers each part. + +Not done here: the window shows a waiting device only in Settings, Other devices, not as a sheet over whatever is open; the wait page polls with a meta refresh, not the event stream. + +### Claude Code starts with its own sandbox and never in bypass mode (unreleased) +- refers-to: app/engine/claude_code_sandbox.py :: support, settings_for, check_args, write_launch, status, clean_domains; app/engine/claude_code.py :: launch_args, run, status; app/engine/sandbox.py :: status_command; app/engine/cmd_settings.py :: claudeCodeDomains +- kind: decision +- logged: unreleased + +The owner's decision: the Claude Code route runs with Claude Code's own sandbox on, limited to the chat's folder, with network only to the host names the person lists, and never with bypass permissions. The setting names come from Claude Code 2.1.332 on the build machine (its --help and the settings schema inside the binary), not from memory. + +Launch. `run` writes a settings file per reply into `data/claude-code/launch-.json` (0600, through `lan_cert.write_private`) and removes it when the reply ends; `launch_args` passes it with `--settings` and adds `--setting-sources user`, so `.claude/settings.json` and `settings.local.json` in the chat folder (which Claude itself can write) are never read and cannot widen the sandbox for a later reply. `--settings` outranks user settings for the keys it sets. The file holds `permissions.disableBypassPermissionsMode: "disable"` always, and where the sandbox can run: `sandbox.enabled`, `failIfUnavailable` (a sandbox that fails to start stops the reply instead of running unsandboxed while the window says sandboxed), `allowUnsandboxedCommands: false` (the per-command escape is ignored), `autoAllowBashIfSandboxed: false` (FormAT's own approvals still decide), `excludedCommands: []`, `network.allowedDomains` from setting `claudeCodeDomains` with `network.strictAllowlist: true` (anything else is refused, not asked), and `filesystem.allowWrite` the chat folder with `denyWrite` the uploads and skills folders that `--add-dir` makes readable. `check_args` refuses any argument list carrying `--dangerously-skip-permissions`, `--allow-dangerously-skip-permissions` or `--permission-mode bypassPermissions`, as a ProviderError, so the reply ends with that sentence and nothing starts; the mode table has no bypass entry, so this only fires if someone adds one. + +Platforms. `support` takes the platform, a `which` and the kernel release so tests can fake each one: macOS needs sandbox-exec; Linux needs bwrap and socat on PATH, and a WSL 1 kernel (release with "Microsoft" but not "WSL2" or "standard") is refused; Windows is reported unavailable because Claude Code's Windows sandbox refuses every command until its own set-up has chosen a mode, which FormAT cannot do for the person; anything else is unavailable. Where it is unavailable no `sandbox` key is written (the reply runs, and a person who set Claude Code's sandbox up themselves keeps their own setting) and `status` says in plain words that its commands are not sandboxed. + +Window. `sandbox.status` gains `claudeCode` (sandboxed, kind, domains, note) and `claudecode.status` gains `sandbox`; each reply's `meta.claudeCode.sandboxed` records what that reply ran with. `claudeCodeDomains` is checked on save: host names or `*.` wildcards, lowercased, duplicates dropped, at most 200 (tests/test_claude_code_sandbox.py, which needs no Claude Code). + +Reads and file tools. The sandbox's `filesystem.denyRead` holds FormAT's data folder (its database, tokens and certificate key) with `allowRead` re-opening the chat folder, uploads and skills, as FormAT's own sandbox hides the data folder. `--add-dir` also made uploads and skills writable for Claude Code's own Write and Edit tools, which the sandbox does not cover and which Allow all accepts without asking inside added folders; `permissions.deny` now carries an `Edit(///**)` rule for each (on Windows `//c/...`, the POSIX form Claude Code matches rules against), on every platform, so a Claude Code chat reads installed skills but cannot replace one outside the overwrite check (that route has no `save_skill`). `check_args` also refuses the `--flag=value` spellings. + +Hidden paths. `hidden_paths` hides what FormAT's own sandbox hides (the home folder and the resolved data folder) plus `BACKEND_DIR/.env`, or the whole backend folder when there is no `.env`; the sandbox's `denyRead` takes that list and `allowRead` re-opens the chat folder, uploads and skills. The same list now also becomes `permissions.deny` rules, built before the early return, so Claude Code's own Read and Edit tools are kept off it whether or not the sandbox runs. Claude Code checks deny before allow, so a deny on a folder that holds the chat folder would also refuse the chat folder: `hidden_rules` walks each hidden folder down towards the kept folders and denies every entry beside that path (`Read(//p/**)` and `Edit(//p/**)` for a folder, `Read(//p)` and `Edit(//p)` for a file), and denies a hidden folder whole when nothing kept is inside it. `permissions.allow` then names `Read(///**)` for each kept folder inside a hidden one. The walk runs at each launch, so an entry created beside the path afterwards (a new file in the home folder) is not covered until the next reply; the OS sandbox still hides it from commands. Claude Code reads its own files in the home folder as a program, not through its Read tool, so the rules are not expected to stop it starting (not seen in a live session); its Read tool can no longer open `~/.claude`. + +Not done here: whether `excludedCommands` and `allowedDomains` from the person's own user settings merge with the launch file's lists was not confirmed in the binary; a person's own entries there may still apply. No real Claude Code session was started (the rules for this change forbid signing in), so the sandbox was not seen refusing a write or a host in a live reply. + +### A skill name already in use is never replaced without asking (unreleased) +- refers-to: app/engine/skills.py :: SkillExists, free_name, clash, _renamed, _install, add_upload, create_from_text, create, install_from; app/engine/cmd_skill.py :: skill.clash, skill.add, skill.create; app/engine/marketplaces.py :: install_skill, skill.installFrom; app/engine/plugins.py :: _skill_name, _planned, _refuse_clashes, install; app/engine/tools.py :: SAVE_SKILL; app/engine/commands.py :: CommandError.data; app/routers/commands.py :: _run; app/harness/prompt.py :: skill +- kind: decision +- logged: unreleased + +The owner's decision: adding or importing a skill whose name is taken warns and asks (Overwrite, Keep both with a new name, Cancel); agents get a clear refusal unless they pass an explicit overwrite. + +`_install` raises `SkillExists` (409) before it copies anything when the folder exists, unless `overwrite` is true or the source is that same folder (re-saving a skill from its own folder, kept from the earlier fix). `rename` installs under another name and rewrites `name:` in the copy's front matter so the folder and SKILL.md agree. `free_name` suggests `name-2`, `name-3` and so on, cut to 64 characters. skill.add, skill.create and skill.installFrom take `overwrite` and (add, installFrom) `name`; the 409 carries `data.clash` {name, suggested}, which `CommandError.data` hands to the REST body as `data` so the window can ask without parsing the sentence; MCP and the CLI get the sentence, which says to pass overwrite or a new name. skill.clash reports a name's state without changing anything. `create_from_text` now stages in a folder with a time stamp, so two writes of one name cannot share a staging folder. + +Claude's save_skill takes `overwrite`; without it a taken name is refused as a tool error, and the skill-chat prompt tells Claude to pass it only when the person is editing that skill and to ask otherwise. The person still approves every save_skill card, and the card says "replace" when overwrite is set. + +Plugins keep replacing their own skills on a reinstall (they pass overwrite), but `_refuse_clashes` refuses the whole install, before anything is copied, when a skill or command name it would create belongs to a standalone skill or to another plugin. tests/test_skill_names.py covers each path; tests/test_skill_replace.py now passes overwrite where it means to replace. + +Not done here: a plugin clash has no Overwrite or Keep both choice, only the refusal; the window's dialog was type-checked and built but not driven in a throttled browser. diff --git a/backend/app/agent_guide.py b/backend/app/agent_guide.py index 79c7edb..a463e55 100644 --- a/backend/app/agent_guide.py +++ b/backend/app/agent_guide.py @@ -11,10 +11,13 @@ "artifact.share": ("share_artifact", "Use when the person wants a read-only link to a page, document, sheet or deck for someone else."), "artifact.unshare": ("unshare_artifact", "Use when the person wants a shared link to stop working."), "artifact.shares": ("list_artifact_links", "Use to see whether an artifact is shared and its links."), - "devices.status": ("get_devices_status", "Use to see whether Format is open to the person's other devices and to get the pairing link."), - "devices.start": ("open_to_devices", "Use when the person wants to continue on their phone or another computer, or to share links beyond this computer."), + "devices.status": ("get_devices_status", "Use to see whether Format is open to the person's other devices and which devices are paired; the pairing link shows only in FormAT's window."), + "devices.answer": ("answer_device", "Only FormAT's window runs this; tell the person to allow or turn down a waiting device in Settings, Other devices."), + "devices.start": ("open_to_devices", "Only FormAT's window runs this; tell the person to open Settings, Other devices, when they want to continue on their phone or another computer."), "devices.stop": ("close_to_devices", "Use when the person wants Format reachable from this computer only."), - "devices.forget": ("forget_devices", "Use when the person wants every paired device to pair again."), + "devices.forget": ("forget_devices", "Only FormAT's window runs this; tell the person to choose Forget paired devices in Settings, Other devices."), + "devices.list": ("list_paired_devices", "Use to see which phones and computers are paired and when each was last seen."), + "devices.revoke": ("unpair_device", "Only FormAT's window runs this; tell the person to choose Unpair beside the device in Settings, Other devices."), "claudecode.status": ("get_claude_code_status", "Use when chats run without an API key, to see whether Claude Code is installed and whether it or the API key answers."), "browser.status": ("get_browser_status", "Use to see whether Format's built-in browser is installed and open, and which page it shows."), "browser.open": ("open_in_browser", "Use to open a page in Format's built-in browser, which the person watches in its Browser pane; returns the page as text with numbered elements."), @@ -97,7 +100,8 @@ "schedule.update": ("update_schedule", "Use to change, pause (enabled false) or resume a scheduled task."), "settings.get": ("get_settings", "Use to see the current model, effort, thinking and permission mode before sending."), "settings.set": ("set_setting", "Use when the person asks for another model, effort, permission mode or tool setting; it applies to all chats."), - "skill.add": ("add_skill", "Use after uploading a skill's .zip or SKILL.md, to install it in Format."), + "skill.add": ("add_skill", "Use after uploading a skill's .zip or SKILL.md, to install it in Format; on a name already in use, ask the person before passing overwrite or a new name."), + "skill.clash": ("check_skill_name", "Use before adding or writing a skill, to see whether its name is taken and which free name keeps both."), "skill.create": ("create_skill", "Use to write a new skill for Format's Claude from a name, a description and instructions."), "skill.delete": ("delete_skill", "Use only when the person asks to remove a skill."), "skill.enable": ("enable_skill", "Use to turn a skill on or off for Format's Claude."), diff --git a/backend/app/core/local_guard.py b/backend/app/core/local_guard.py index 5ad228e..fc66a70 100644 --- a/backend/app/core/local_guard.py +++ b/backend/app/core/local_guard.py @@ -29,7 +29,7 @@ def __init__(self, app, origins: list[str]) -> None: self.app = app self.allowed = {key for key in (_origin_key(o) for o in origins) if key is not None} - def _permitted(self, headers: dict[str, str], paired: bool = False) -> bool: + def _permitted(self, headers: dict[str, str], paired: bool = False, scheme: str = "http") -> bool: host = headers.get("host", "") if BROWSER_MARK in headers: return False @@ -44,14 +44,15 @@ def _permitted(self, headers: dict[str, str], paired: bool = False) -> bool: if key in self.allowed: return True own = _origin_key(f"{key[0]}://{host}") - return key[0] == "http" and own is not None and own == key + return key[0] == scheme and own is not None and own == key async def __call__(self, scope, receive, send) -> None: if scope["type"] not in ("http", "websocket"): await self.app(scope, receive, send) return headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope.get("headers", [])} - if self._permitted(headers, scope.get("format.paired") is True): + scheme = "https" if scope.get("scheme") in ("https", "wss") else "http" + if self._permitted(headers, scope.get("format.paired") is True, scheme): await self.app(scope, receive, send) return if scope["type"] == "websocket": diff --git a/backend/app/core/window_key.py b/backend/app/core/window_key.py index 8e8d497..4afa47e 100644 --- a/backend/app/core/window_key.py +++ b/backend/app/core/window_key.py @@ -38,6 +38,10 @@ def is_window(scope) -> bool: return paired(scope) or valid(header_of(scope)) +def own_window(scope) -> bool: + return not paired(scope) and valid(header_of(scope)) + + def claim() -> str | None: if STATE["claimed"]: STATE["secondClaim"] = True diff --git a/backend/app/engine/agents.py b/backend/app/engine/agents.py index fbdd271..8cc024b 100644 --- a/backend/app/engine/agents.py +++ b/backend/app/engine/agents.py @@ -51,9 +51,20 @@ def require_outside(client: str, channel: str, cid: str, params: dict | None) -> raise CommandError("Only the person, in FormAT's window, can change whether outside agents may use FormAT.", 403) +WINDOW_ONLY = "Only the FormAT window on this computer can do this." +_PAIRING_KEYS = ("pairUrl", "qr", "pairExpiresIn", "pending") + + +def refuse_window_only(cid: str) -> None: + from app.engine.commands import window_only + if window_only(cid): + raise CommandError(WINDOW_ONLY, 403) + + def outside_result(cid: str, result): - if cid.startswith("devices.") and isinstance(result, dict) and result.get("pairUrl"): - return result | {"pairUrl": None, "qr": None, "pairing": "Only FormAT's window shows the pairing link"} + if cid.startswith("devices.") and isinstance(result, dict) and any(k in result for k in _PAIRING_KEYS): + kept = {k: v for k, v in result.items() if k not in _PAIRING_KEYS} + return kept | {"pairUrl": None, "qr": None, "pending": [], "pairing": "Only FormAT's window shows the pairing link"} return result diff --git a/backend/app/engine/claude_code.py b/backend/app/engine/claude_code.py index 3c7811a..e19d3ec 100644 --- a/backend/app/engine/claude_code.py +++ b/backend/app/engine/claude_code.py @@ -3,9 +3,10 @@ import subprocess import threading import time +from pathlib import Path from app import providers -from app.engine import agent_lookup, events, projects, skills, tools, uploads +from app.engine import agent_lookup, claude_code_sandbox, events, projects, skills, tools, uploads from app.engine.cmd_account import account from app.engine.cmd_message import messages_of, update from app.engine.cmd_settings import current @@ -100,14 +101,14 @@ def decision_for(short: str, settings: dict, conversation_id: str | None = None) @command("claudecode.status", "Claude Code", mutates=False, - description="Whether the Claude Code CLI is installed (its path and version) and which engine answers chats now: api (the Anthropic API key) or claude-code (the person's own Claude Code sign-in). programs says the same for each agent program FormAT looks for: claude, codex, cursor and antigravity (finding is runs, broken or missing; said is the sentence to show).") + description="Whether the Claude Code CLI is installed (its path and version) and which engine answers chats now: api (the Anthropic API key) or claude-code (the person's own Claude Code sign-in). programs says the same for each agent program FormAT looks for: claude, codex, cursor and antigravity (finding is runs, broken or missing; said is the sentence to show). sandbox says whether Claude Code's own sandbox is on for its commands here (sandboxed, the host names they may reach from setting claudeCodeDomains, and note, the sentence to show).") def status() -> dict: found = info(fresh=True) try: now = route(current()) except providers.ProviderError: now = None - return found | {"route": now, "chatEngine": current().get("chatEngine", "auto"), "programs": programs()} + return found | {"route": now, "chatEngine": current().get("chatEngine", "auto"), "programs": programs(), "sandbox": claude_code_sandbox.status(current())} def _previous_session(path: list[dict]) -> str | None: @@ -170,6 +171,23 @@ def _system(conversation_id: str) -> str: return "\n\n".join(parts) +def launch_args(program: str, model_id: str, settings: dict, system: str, launch: Path, servers: dict, blocked: list[str], session: str | None) -> list[str]: + args = [program, "-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--include-partial-messages", + "--permission-prompt-tool", "stdio", "--model", model_id, "--permission-mode", MODES.get(settings.get("permissionMode", "ask"), "manual"), + "--settings", str(launch), "--setting-sources", "user", + "--append-system-prompt", system, "--add-dir", str(uploads.root()), "--add-dir", str(skills.root())] + if settings.get("effort") in ("low", "medium", "high", "xhigh", "max"): + args += ["--effort", settings["effort"]] + if servers: + args += ["--mcp-config", json.dumps({"mcpServers": servers})] + if blocked: + args += ["--disallowedTools", *blocked] + if session: + args += ["--resume", session, "--fork-session"] + claude_code_sandbox.check_args(args) + return args + + def _text_of(c) -> str: if isinstance(c, str): return c @@ -362,20 +380,11 @@ def on_results(message: dict) -> None: session = _previous_session(path) folder = str(tools.workspace(conversation_id)) found = info() - args = [found["path"] or "claude", "-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--include-partial-messages", - "--permission-prompt-tool", "stdio", "--model", model["id"], "--permission-mode", MODES.get(settings.get("permissionMode", "ask"), "manual"), - "--append-system-prompt", _system(conversation_id), "--add-dir", str(uploads.root()), "--add-dir", str(skills.root())] - if settings.get("effort") in ("low", "medium", "high", "xhigh", "max"): - args += ["--effort", settings["effort"]] + boxed = claude_code_sandbox.support() + launch: Path | None = None from app.engine import connectors servers, blocked = connectors.claude_code_servers(settings.get("connectorsOff")) - if servers: - args += ["--mcp-config", json.dumps({"mcpServers": servers})] - if blocked: - args += ["--disallowedTools", *blocked] - if session: - args += ["--resume", session, "--fork-session"] - meta["claudeCode"] = {"version": found.get("version"), "resumed": session} + meta["claudeCode"] = {"version": found.get("version"), "resumed": session, "sandboxed": boxed["available"]} def watch() -> None: while proc.poll() is None: @@ -391,6 +400,8 @@ def drain() -> None: try: if not found["installed"]: raise providers.ProviderError(found.get("said") or "Claude Code is not installed: install it from https://claude.com/claude-code and sign in once with `claude`") + launch = claude_code_sandbox.write_launch(claude_code_sandbox.settings_for(Path(folder), list(settings.get("claudeCodeDomains") or []), [uploads.root(), skills.root()], boxed, claude_code_sandbox.hidden_paths())) + args = launch_args(found["path"] or "claude", model["id"], settings, _system(conversation_id), launch, servers, blocked, session) run_env = child_env(found["path"]) proc = subprocess.Popen(agent_lookup.start_argv(args, run_env), cwd=folder, env=run_env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1) threading.Thread(target=drain, daemon=True).start() @@ -461,6 +472,8 @@ def drain() -> None: finally: if proc and proc.poll() is None: proc.terminate() + if launch: + launch.unlink(missing_ok=True) chat._close_open_calls(blocks, meta) message = update(mid, blocks, meta) chat.RUNS.pop(conversation_id, None) diff --git a/backend/app/engine/claude_code_sandbox.py b/backend/app/engine/claude_code_sandbox.py new file mode 100644 index 0000000..5f3af00 --- /dev/null +++ b/backend/app/engine/claude_code_sandbox.py @@ -0,0 +1,152 @@ +import json +import logging +import platform as _platform +import re +import secrets +import shutil +import sys +from collections.abc import Callable +from pathlib import Path, PurePosixPath, PureWindowsPath + +from app import providers +from app.core import config + +FORBIDDEN_FLAGS = ("--dangerously-skip-permissions", "--allow-dangerously-skip-permissions") +FORBIDDEN_MODES = ("bypassPermissions",) +DOMAIN = re.compile(r"^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$") +MAX_DOMAINS = 200 +log = logging.getLogger(__name__) + + +class LaunchRefused(providers.ProviderError): + pass + + +def support(platform: str | None = None, which: Callable[[str], str | None] = shutil.which, release: str | None = None) -> dict: + plat = platform or sys.platform + rel = (release if release is not None else _platform.release()).lower() + if plat == "darwin": + if which("sandbox-exec"): + return {"available": True, "kind": "macos", "said": ""} + return {"available": False, "kind": None, "said": "this Mac has no sandbox-exec"} + if plat.startswith("linux"): + if "microsoft" in rel and "wsl2" not in rel and "standard" not in rel: + return {"available": False, "kind": None, "said": "WSL 1 has no sandbox for it; WSL 2 does"} + missing = [p for p in ("bwrap", "socat") if not which(p)] + if missing: + return {"available": False, "kind": None, "said": f"install {' and '.join('bubblewrap' if p == 'bwrap' else p for p in missing)} to turn it on"} + return {"available": True, "kind": "linux", "said": ""} + if plat in ("win32", "cygwin"): + return {"available": False, "kind": None, "said": "on Windows it needs its own set-up first"} + return {"available": False, "kind": None, "said": f"it has no sandbox on {plat}"} + + +def clean_domains(value: object) -> list[str]: + if not isinstance(value, list) or len(value) > MAX_DOMAINS: + raise ValueError(f"takes a list of up to {MAX_DOMAINS} host names, such as example.com or *.example.com") + out: list[str] = [] + for item in value: + host = item.strip().lower() if isinstance(item, str) else "" + if len(host) > 253 or not DOMAIN.match(host): + raise ValueError(f"takes host names such as example.com or *.example.com, and {item!r} is not one") + if host not in out: + out.append(host) + return out + + +def path_rule(tool: str, path: Path | str, windows: bool, tree: bool = True) -> str: + tail = "/**" if tree else "" + if windows: + p = PureWindowsPath(str(path)) + drive = p.drive.rstrip(":").lower() + rest = "/".join(p.parts[1:]) + return f"{tool}(//{drive}/{rest}{tail})" if len(drive) == 1 else f"{tool}({p.as_posix()}{tail})" + return f"{tool}(/{PurePosixPath(str(path)).as_posix()}{tail})" + + +def edit_rule(path: Path | str, windows: bool) -> str: + return path_rule("Edit", path, windows) + + +def hidden_paths() -> list[Path]: + home = Path.home() + key = config.BACKEND_DIR / ".env" + found = [home] if home.is_dir() else [] + found += [config.data_dir().resolve(), (key if key.is_file() else config.BACKEND_DIR).resolve()] + return list(dict.fromkeys(found)) + + +def _covers(parent: Path, child: Path) -> bool: + return child == parent or child.is_relative_to(parent) + + +def _denied_within(root: Path, kept: list[Path]) -> list[tuple[Path, bool]]: + if any(_covers(k, root) for k in kept): + return [] + if not any(_covers(root, k) for k in kept): + return [(root, root.is_dir() or not root.exists())] + try: + entries = sorted(root.iterdir()) + except OSError: + log.warning("Claude Code launch: cannot list %s to hide its contents", root) + return [] + return [d for e in entries for d in _denied_within(e, kept)] + + +def hidden_rules(hidden: list[Path], kept: list[Path], windows: bool) -> list[str]: + keep = [k.resolve() for k in kept] + found = dict.fromkeys(d for h in hidden for d in _denied_within(h.resolve(), keep)) + return [path_rule(tool, p, windows, tree) for p, tree in found for tool in ("Read", "Edit")] + + +def settings_for(workspace: Path, domains: list[str], read_only: list[Path], found: dict, hidden: list[Path] | None = None, windows: bool | None = None) -> dict: + win = sys.platform in ("win32", "cygwin") if windows is None else windows + kept = [workspace, *read_only] + inside = [p for p in kept if any(_covers(h.resolve(), p.resolve()) for h in hidden or [])] + out: dict = {"permissions": {"disableBypassPermissionsMode": "disable", + "deny": [edit_rule(p, win) for p in read_only] + hidden_rules(hidden or [], kept, win), + "allow": [path_rule("Read", p.resolve(), win) for p in inside]}} + if not found["available"]: + return out + out["sandbox"] = { + "enabled": True, + "failIfUnavailable": True, + "autoAllowBashIfSandboxed": False, + "allowUnsandboxedCommands": False, + "excludedCommands": [], + "network": {"allowedDomains": list(domains), "strictAllowlist": True}, + "filesystem": {"allowWrite": [str(workspace)], "denyWrite": [str(p) for p in read_only], + "denyRead": [str(p) for p in hidden or []], "allowRead": [str(workspace), *(str(p) for p in read_only)]}, + } + return out + + +def check_args(args: list[str]) -> None: + for i, word in enumerate(args): + flag, eq, value = word.partition("=") + if flag in FORBIDDEN_FLAGS: + raise LaunchRefused(f"FormAT never starts Claude Code with {flag}") + if flag == "--permission-mode" and (value if eq else (args[i + 1] if i + 1 < len(args) else "")) in FORBIDDEN_MODES: + raise LaunchRefused("FormAT never starts Claude Code in bypass permissions mode") + + +def launch_dir() -> Path: + return config.data_dir() / "claude-code" + + +def write_launch(settings: dict) -> Path: + from app.engine import lan_cert + path = launch_dir() / f"launch-{secrets.token_hex(8)}.json" + lan_cert.write_private(path, json.dumps(settings, indent=2).encode("utf-8")) + return path + + +def status(settings: dict, found: dict | None = None) -> dict: + found = found or support() + domains = list(settings.get("claudeCodeDomains") or []) + if found["available"]: + reach = ("they have no network" if not domains else f"they reach only {', '.join(domains[:6])}{' and more' if len(domains) > 6 else ''}") + note = f"Claude Code runs sandboxed: its commands can change only the chat's folder, and {reach}." + else: + note = f"Claude Code runs without its sandbox here: its commands are not sandboxed ({found['said']}). In Ask mode each command still waits for your approval." + return {"sandboxed": bool(found["available"]), "kind": found["kind"], "domains": domains, "note": note} diff --git a/backend/app/engine/cmd_settings.py b/backend/app/engine/cmd_settings.py index 272ee82..f814de0 100644 --- a/backend/app/engine/cmd_settings.py +++ b/backend/app/engine/cmd_settings.py @@ -12,7 +12,7 @@ EFFORTS = EFFORT_ORDER DEFAULTS = {"model": "claude-opus-5-5", "effort": "medium", "thinking": True, "permissionMode": "ask", "autoCompact": True, "compactAt": 0.75, "webTools": True, "workspaceTools": True, "toolAllow": [], "toolDeny": [], "agentModel": "", "agentLimit": 4, "artifactNetwork": False, "memory": False, "outsideAgents": "ask", - "sandbox": True, "sandboxNetwork": False, "browserTools": True, "chatEngine": "auto"} + "sandbox": True, "sandboxNetwork": False, "browserTools": True, "chatEngine": "auto", "claudeCodeDomains": []} TOOL_NAMES = ["bash", "write", "edit", "browser"] CHOICES = {"effort": EFFORTS, "permissionMode": ["ask", "auto", "plan"], "outsideAgents": ["ask", "allowed", "blocked"], "chatEngine": ["auto", "api", "claude-code"]} @@ -62,8 +62,14 @@ def get() -> dict: @command("settings.set", "Change a setting", {"key": {"type": "string", "required": True, "enum": list(DEFAULTS)}, "value": {"required": True}}, - description="Sets one chat setting: model takes a model id from models.list, effort one of low, medium, high, xhigh, max, permissionMode ask, auto or plan, thinking (show Claude's thinking) true or false, autoCompact (summarize long chats) true or false, compactAt the share of the context window that triggers it, 0.05 to 0.95, webTools (web search and fetch) and workspaceTools (bash and files in the chat's folder) true or false, toolAllow and toolDeny lists of bash, write, edit, agentModel the sub-agents' model id (empty for the chat's model), agentLimit the most sub-agents in one reply, 0 to 10, artifactNetwork (let artifact pages load images and data from the internet) true or false, memory (Claude keeps notes across chats with the memory tool) true or false, outsideAgents (coding agents using Format over MCP) ask, allowed or blocked, sandbox (Claude's bash runs sandboxed: only the chat's folder writable, the home folder hidden) true or false, sandboxNetwork (let sandboxed commands reach the network) true or false, browserTools (Claude can use the built-in browser) true or false, chatEngine (who answers: auto uses the API key when set and otherwise the person's Claude Code sign-in, api, or claude-code) auto, api or claude-code.") + description="Sets one chat setting: model takes a model id from models.list, effort one of low, medium, high, xhigh, max, permissionMode ask, auto or plan, thinking (show Claude's thinking) true or false, autoCompact (summarize long chats) true or false, compactAt the share of the context window that triggers it, 0.05 to 0.95, webTools (web search and fetch) and workspaceTools (bash and files in the chat's folder) true or false, toolAllow and toolDeny lists of bash, write, edit, agentModel the sub-agents' model id (empty for the chat's model), agentLimit the most sub-agents in one reply, 0 to 10, artifactNetwork (let artifact pages load images and data from the internet) true or false, memory (Claude keeps notes across chats with the memory tool) true or false, outsideAgents (coding agents using Format over MCP) ask, allowed or blocked, sandbox (Claude's bash runs sandboxed: only the chat's folder writable, the home folder hidden) true or false, sandboxNetwork (let sandboxed commands reach the network) true or false, browserTools (Claude can use the built-in browser) true or false, chatEngine (who answers: auto uses the API key when set and otherwise the person's Claude Code sign-in, api, or claude-code) auto, api or claude-code, claudeCodeDomains (the only host names Claude Code's sandboxed commands may reach, such as example.com or *.example.com; empty for no network) a list.") def set_(key: str, value: object) -> dict: + if key == "claudeCodeDomains": + from app.engine import claude_code_sandbox + try: + value = claude_code_sandbox.clean_domains(value) + except ValueError as exc: + raise CommandError(f"settings.set: claudeCodeDomains {exc}") from None if key in ("thinking", "autoCompact", "webTools", "workspaceTools", "artifactNetwork", "memory", "sandbox", "sandboxNetwork", "browserTools") and not isinstance(value, bool): raise CommandError(f"settings.set: {key} takes true or false") if key == "agentModel" and not isinstance(value, str): diff --git a/backend/app/engine/cmd_skill.py b/backend/app/engine/cmd_skill.py index bda973c..6706e7e 100644 --- a/backend/app/engine/cmd_skill.py +++ b/backend/app/engine/cmd_skill.py @@ -2,15 +2,25 @@ from app.engine.commands import CommandError, command NAME = {"type": "string", "required": True, "description": "the skill's name"} +OVERWRITE = {"type": "boolean", "description": "true to replace a skill of the same name; without it a name already in use is refused with 409"} +SAVE_AS = {"type": "string", "description": "install under this name instead, to keep both skills (skill.clash suggests a free one)"} def _do(fn, *args): try: return fn(*args) + except skills.SkillExists as exc: + raise CommandError(str(exc), 409, {"clash": {"name": exc.name, "suggested": exc.suggested}}) from None except skills.SkillError as exc: raise CommandError(str(exc), exc.status) from None +@command("skill.clash", "Check a skill name", {"name": NAME}, mutates=False, + description="Whether a skill name is already in use: exists, suggested (a free name to keep both under) and plugin (the plugin it came with, if any).") +def clash(name: str) -> dict: + return skills.clash(name) + + @command("skill.list", "Skills", mutates=False, description="The skills installed in Format, with their description, whether they are on, and their file count.") def list_() -> dict: return {"skills": skills.list_()} @@ -27,16 +37,17 @@ def read(name: str, path: str) -> dict: return _do(skills.read_file, name, path) -@command("skill.add", "Add a skill", {"uploadId": {"type": "string", "required": True, "description": "a .zip of a skill folder, or a SKILL.md, from POST /api/uploads"}}, - description="Installs a skill from an uploaded .zip (its folder with SKILL.md) or SKILL.md file. A skill with the same name is replaced.") -def add(uploadId: str) -> dict: - return _do(skills.add_upload, uploadId) +@command("skill.add", "Add a skill", {"uploadId": {"type": "string", "required": True, "description": "a .zip of a skill folder, or a SKILL.md, from POST /api/uploads"}, + "overwrite": OVERWRITE, "name": SAVE_AS}, + description="Installs a skill from an uploaded .zip (its folder with SKILL.md) or SKILL.md file. If a skill with the same name exists, nothing changes and it answers 409 with data.clash (name, suggested), unless overwrite is true (replace it) or name gives a new name (keep both).") +def add(uploadId: str, overwrite: bool | None = None, name: str | None = None) -> dict: + return _do(skills.add_upload, uploadId, bool(overwrite), (name or "").strip().lower() or None) -@command("skill.create", "Write a skill", {"name": NAME, "description": {"type": "string", "required": True}, "instructions": {"type": "string", "required": True}}, - description="Creates a skill from a name, a description (when Claude should use it) and its instructions, written as its SKILL.md.") -def create(name: str, description: str, instructions: str) -> dict: - return _do(skills.create, name.strip().lower(), description, instructions) +@command("skill.create", "Write a skill", {"name": NAME, "description": {"type": "string", "required": True}, "instructions": {"type": "string", "required": True}, "overwrite": OVERWRITE}, + description="Creates a skill from a name, a description (when Claude should use it) and its instructions, written as its SKILL.md. A name already in use is refused with 409 unless overwrite is true.") +def create(name: str, description: str, instructions: str, overwrite: bool | None = None) -> dict: + return _do(skills.create, name.strip().lower(), description, instructions, bool(overwrite)) @command("skill.enable", "Turn a skill on or off", {"name": NAME, "enabled": {"type": "boolean", "required": True}}, diff --git a/backend/app/engine/commands.py b/backend/app/engine/commands.py index cc3ac3c..d378f81 100644 --- a/backend/app/engine/commands.py +++ b/backend/app/engine/commands.py @@ -4,9 +4,10 @@ class CommandError(Exception): - def __init__(self, message: str, status: int = 400): + def __init__(self, message: str, status: int = 400, data: dict | None = None): super().__init__(message) self.status = status + self.data = data @dataclass @@ -18,21 +19,27 @@ class Spec: group: str = "" mutates: bool = True description: str = "" + window_only: bool = False REGISTRY: dict[str, Spec] = {} _KINDS = {"string": str, "integer": int, "number": (int, float), "boolean": bool, "array": list, "object": dict} -def command(cid: str, label: str, params: dict[str, dict] | None = None, mutates: bool = True, description: str = "") -> Callable: +def command(cid: str, label: str, params: dict[str, dict] | None = None, mutates: bool = True, description: str = "", window_only: bool = False) -> Callable: def wrap(fn: Callable) -> Callable: if cid in REGISTRY: raise RuntimeError(f"command registered twice: {cid}") - REGISTRY[cid] = Spec(cid, label, fn, params or {}, cid.split(".")[0], mutates, description or label) + REGISTRY[cid] = Spec(cid, label, fn, params or {}, cid.split(".")[0], mutates, description or label, window_only) return fn return wrap +def window_only(cid: str) -> bool: + spec = REGISTRY.get(cid) + return spec is not None and spec.window_only + + def _check(spec: Spec, params: dict) -> dict: unknown = sorted(set(params) - set(spec.params)) if unknown: diff --git a/backend/app/engine/device_tokens.py b/backend/app/engine/device_tokens.py new file mode 100644 index 0000000..3fb7da6 --- /dev/null +++ b/backend/app/engine/device_tokens.py @@ -0,0 +1,90 @@ +import asyncio +import hashlib +import re +import secrets +import threading + +from app.engine import store + +COOKIE = "format_device" +SEEN_EVERY = 60.0 +_live_lock = threading.Lock() +_live: dict[str, set[tuple[asyncio.AbstractEventLoop, asyncio.Event]]] = {} +_PLATFORMS = (("iPhone", "iPhone"), ("iPad", "iPad"), ("Android", "Android"), ("CrOS", "ChromeOS"), ("Windows", "Windows"), ("Macintosh", "Mac"), ("Linux", "Linux")) +_BROWSERS = (("Edg/", "Edge"), ("Firefox/", "Firefox"), ("FxiOS", "Firefox"), ("CriOS", "Chrome"), ("Chrome/", "Chrome"), ("Safari/", "Safari")) + + +def _hash(token: str) -> str: + return hashlib.sha256(token.encode("utf-8")).hexdigest() + + +def label(user_agent: str) -> str: + ua = user_agent or "" + platform = next((name for mark, name in _PLATFORMS if mark in ua), "") + browser = next((name for mark, name in _BROWSERS if mark in ua), "") + text = ", ".join(p for p in (platform, browser) if p) or "A browser" + return re.sub(r"[^\w ,.-]", "", text)[:60] + + +def issue(name: str) -> tuple[str, str]: + token = secrets.token_urlsafe(32) + did = store.new_id() + now = store.now() + store.run("INSERT INTO paired_devices(id, name, token_hash, created, seen) VALUES (?, ?, ?, ?, ?)", (did, name, _hash(token), now, now)) + return did, token + + +def check(token: str | None) -> str | None: + if not token: + return None + found = store.row("SELECT id, seen FROM paired_devices WHERE token_hash = ?", (_hash(token),)) + if found is None: + return None + now = store.now() + if now - found["seen"] > SEEN_EVERY: + store.run("UPDATE paired_devices SET seen = ? WHERE id = ?", (now, found["id"])) + return found["id"] + + +def listing() -> list[dict]: + return store.rows("SELECT id, name, created, seen FROM paired_devices ORDER BY created") + + +def revoke(did: str) -> int: + n = store.run("DELETE FROM paired_devices WHERE id = ?", (did,)) + _cut([did]) + return n + + +def revoke_all() -> int: + ids = [r["id"] for r in listing()] + n = store.run("DELETE FROM paired_devices") + _cut(ids + list(_live)) + return n + + +def watch(did: str) -> asyncio.Event: + gone = asyncio.Event() + with _live_lock: + _live.setdefault(did, set()).add((asyncio.get_running_loop(), gone)) + return gone + + +def unwatch(did: str, gone: asyncio.Event) -> None: + with _live_lock: + held = _live.get(did) + if held is None: + return + held.difference_update({pair for pair in held if pair[1] is gone}) + if not held: + _live.pop(did, None) + + +def _cut(ids: list[str]) -> None: + with _live_lock: + targets = [pair for did in ids for pair in _live.get(did, ())] + for loop, gone in targets: + try: + loop.call_soon_threadsafe(gone.set) + except RuntimeError: + pass diff --git a/backend/app/engine/devices.py b/backend/app/engine/devices.py index bf23724..213ba42 100644 --- a/backend/app/engine/devices.py +++ b/backend/app/engine/devices.py @@ -1,23 +1,36 @@ import asyncio +import contextlib +import hashlib import hmac +import html import json import logging import os import re import secrets import socket +import threading +import time from http.cookies import SimpleCookie from pathlib import Path +from urllib.parse import parse_qs from fastapi import APIRouter from fastapi.responses import Response from app.core import config -from app.engine import artifacts, events, store +from app.engine import artifacts, device_tokens, events, lan_cert, store from app.engine.commands import CommandError, command LAN_PORT = int(os.environ.get("FORMAT_LAN_PORT") or 8492) -COOKIE = "format_pair" +COOKIE = device_tokens.COOKIE +WAIT_COOKIE = "format_pair_wait" +SECURE = ("https", "wss") +CODE_LIFE = 300.0 +REQUEST_LIFE = 300.0 +WAIT_REFRESH = 2 +_code_lock = threading.Lock() +_requests: dict[str, dict] = {} _server = None _task = None _loop: asyncio.AbstractEventLoop | None = None @@ -53,24 +66,109 @@ def bind(loop: asyncio.AbstractEventLoop) -> None: _loop = loop -def _secret_path() -> Path: +def _code_path() -> Path: return config.data_dir() / "pairing.json" -def _secret(rotate: bool = False) -> str: - p = _secret_path() - if not rotate and p.is_file(): - try: - return json.loads(p.read_text())["secret"] - except (ValueError, KeyError): - pass - s = secrets.token_urlsafe(24) - p.write_text(json.dumps({"secret": s})) +def _read_code() -> dict | None: try: - os.chmod(p, 0o600) - except OSError: - pass - return s + held = json.loads(_code_path().read_text()) + code, made = str(held["code"]), float(held["made"]) + except (OSError, ValueError, KeyError, TypeError): + return None + return {"code": code, "made": made} if 0 <= time.time() - made < CODE_LIFE else None + + +def _new_code() -> dict: + held = {"code": secrets.token_urlsafe(24), "made": time.time()} + lan_cert.write_private(_code_path(), json.dumps(held).encode("utf-8")) + return held + + +def _current_code(rotate: bool = False) -> dict: + with _code_lock: + held = None if rotate else _read_code() + return held or _new_code() + + +def _code(rotate: bool = False) -> str: + return _current_code(rotate)["code"] + + +def _spend(code: str) -> bool: + with _code_lock: + held = _read_code() + if held is None or not (code and hmac.compare_digest(code.encode("utf-8"), held["code"].encode("utf-8"))): + return False + _new_code() + return True + + +def _hash(value: str) -> str: + return hashlib.sha256(value.encode("utf-8")).hexdigest() + + +def _prune(now: float) -> None: + for rid in [rid for rid, r in _requests.items() if now - r["created"] >= REQUEST_LIFE]: + _requests.pop(rid, None) + + +def _ask(name: str) -> str: + secret = secrets.token_urlsafe(32) + now = time.time() + with _code_lock: + _prune(now) + rid = store.new_id() + _requests[rid] = {"id": rid, "name": name, "created": now, "check": f"{secrets.randbelow(10 ** 6):06d}", + "secret": _hash(secret), "state": "waiting"} + return secret + + +def _request_of(secret: str) -> dict | None: + if not secret: + return None + want = _hash(secret) + with _code_lock: + _prune(time.time()) + found = next((r for r in _requests.values() if hmac.compare_digest(r["secret"], want)), None) + return dict(found) if found else None + + +def _settle(rid: str) -> bool: + with _code_lock: + return _requests.pop(rid, None) is not None + + +def _collect(rid: str) -> str | None: + with _code_lock: + found = _requests.pop(rid, None) + if found is None or found["state"] != "allowed": + return None + return device_tokens.issue(found["name"])[1] + + +def pending() -> list[dict]: + with _code_lock: + _prune(time.time()) + return [{"id": r["id"], "name": r["name"], "check": r["check"], "created": r["created"]} + for r in sorted(_requests.values(), key=lambda r: r["created"]) if r["state"] == "waiting"] + + +def answer(rid: str, allow: bool) -> bool: + with _code_lock: + _prune(time.time()) + found = _requests.get(rid) + if found is None or found["state"] != "waiting": + return False + _requests[rid] = found | {"state": "allowed" if allow else "denied"} + return True + + +def _forget_requests(unpair: bool = False) -> None: + with _code_lock: + _requests.clear() + if unpair: + device_tokens.revoke_all() def lan_addresses() -> list[str]: @@ -97,20 +195,62 @@ def running() -> bool: def base_url() -> str: - return f"http://{lan_addresses()[0]}:{LAN_PORT}" if running() else f"http://127.0.0.1:{config.PORT}" + return f"https://{lan_addresses()[0]}:{LAN_PORT}" if running() else f"http://127.0.0.1:{config.PORT}" + +def _header(scope: dict, name: bytes) -> str: + return next((v.decode("latin-1") for k, v in scope.get("headers") or [] if k.lower() == name), "") -def _paired(scope: dict, secret: str) -> bool: + +def _cookies(scope: dict, name: str) -> list[str]: + found: list[str] = [] for k, v in scope.get("headers") or []: - if k == b"cookie": + if k.lower() == b"cookie": c = SimpleCookie() try: c.load(v.decode("latin-1")) except Exception: continue - if COOKIE in c and hmac.compare_digest(c[COOKIE].value, secret): - return True - return False + if name in c: + found.append(c[name].value) + return found + + +def _device_of(scope: dict) -> tuple[str, str] | None: + for token in _cookies(scope, COOKIE): + found = device_tokens.check(token) + if found: + return found, token + return None + + +_PAGE = "{}

FormAT

{}

" +NOT_PAIRED = "This device is not paired. On the computer running FormAT, open Settings, Other devices, and scan the code or open its link here." +STALE_LINK = "This pairing link has been used or is out of date. On the computer running FormAT, open Settings, Other devices, and scan the code shown there now." +TURNED_DOWN = "FormAT's window turned this device down. To try again, scan the code shown in Settings, Other devices, on the computer running FormAT." +WAITING = ("Waiting for FormAT's window. On the computer running FormAT, Settings, Other devices shows a request from {name} " + "with the check number {check}. Choose Allow there if it is this device; this page moves on by itself.

" + "

Certificate fingerprint (SHA-256), the same one this browser shows for this site's certificate and FormAT's window shows:" + "
{fp}") +_CLEAR_WAIT = f"{WAIT_COOKIE}=; Path=/pair; HttpOnly; Secure; SameSite=Lax; Max-Age=0".encode() + + +async def _page(send, status: int, text: str, headers: list | None = None, head: str = "") -> None: + await send({"type": "http.response.start", "status": status, "headers": [(b"content-type", b"text/html; charset=utf-8"), (b"cache-control", b"no-store"), *(headers or [])]}) + await send({"type": "http.response.body", "body": _PAGE.format(head, text).encode("utf-8")}) + + +async def _redirect(send, where: bytes, cookies: list[bytes]) -> None: + await send({"type": "http.response.start", "status": 303, "headers": [ + (b"location", where), (b"cache-control", b"no-store"), *((b"set-cookie", c) for c in cookies)]}) + await send({"type": "http.response.body", "body": b""}) + + +async def _refuse(scope, send) -> None: + if scope["type"] == "websocket": + await send({"type": "websocket.close", "code": 4401}) + return + await _page(send, 401, NOT_PAIRED) class Gate: @@ -118,49 +258,109 @@ def __init__(self, api, static): self.api = api self.static = static - async def inner(self, scope, receive, send): + async def inner(self, scope, receive, send, device: str | None = None): path = scope.get("path") or "/" target = self.api if path.startswith(("/api", "/mcp", "/s/")) or self.static is None else self.static - return await target(dict(scope) | {"format.paired": True}, receive, send) + return await target(dict(scope) | {"format.paired": True, "format.device": device}, receive, send) + + async def _held(self, scope, receive, send, device: str, token: str): + gone = device_tokens.watch(device) + if device_tokens.check(token) != device: + device_tokens.unwatch(device, gone) + return await _refuse(scope, send) + started = {"yes": False} + + async def tracked(message): + if message["type"] in ("http.response.start", "websocket.accept"): + started["yes"] = True + await send(message) + + work = asyncio.ensure_future(self.inner(scope, receive, tracked, device)) + cut = asyncio.ensure_future(gone.wait()) + try: + done, _ = await asyncio.wait({work, cut}, return_when=asyncio.FIRST_COMPLETED) + if work in done: + return work.result() + work.cancel() + with contextlib.suppress(BaseException): + await work + with contextlib.suppress(Exception): + if scope["type"] == "websocket": + await send({"type": "websocket.close", "code": 4401}) + elif not started["yes"]: + await _page(send, 401, NOT_PAIRED) + finally: + cut.cancel() + device_tokens.unwatch(device, gone) + + async def _pair(self, scope, send): + q = parse_qs((scope.get("query_string") or b"").decode("latin-1")) + fp = (q.get("fp") or [""])[0].lower().replace(":", "") + own = lan_cert.fingerprint() + if own is None or not hmac.compare_digest(fp.encode("utf-8"), own.encode("utf-8")) or not _spend((q.get("code") or [""])[0]): + return await _page(send, 401, STALE_LINK) + secret = _ask(device_tokens.label(_header(scope, b"user-agent"))) + _changed() + await _redirect(send, b"/pair/wait", [f"{WAIT_COOKIE}={secret}; Path=/pair; HttpOnly; Secure; SameSite=Lax; Max-Age={int(REQUEST_LIFE)}".encode()]) + + async def _wait(self, scope, send): + secret = next(iter(_cookies(scope, WAIT_COOKIE)), "") + found = _request_of(secret) + if found is None: + return await _page(send, 401, STALE_LINK, [(b"set-cookie", _CLEAR_WAIT)]) + if found["state"] == "denied": + _settle(found["id"]) + return await _page(send, 403, TURNED_DOWN, [(b"set-cookie", _CLEAR_WAIT)]) + if found["state"] == "waiting": + text = WAITING.format(name=html.escape(found["name"]), check=f"{found['check'][:3]} {found['check'][3:]}", + fp=html.escape(lan_cert.spaced(lan_cert.fingerprint()) or "")) + return await _page(send, 200, text, head=f"") + token = _collect(found["id"]) + if token is None: + return await _page(send, 401, STALE_LINK, [(b"set-cookie", _CLEAR_WAIT)]) + _changed() + await _redirect(send, b"/", [_CLEAR_WAIT, f"{COOKIE}={token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=31536000".encode()]) async def __call__(self, scope, receive, send): if scope["type"] not in ("http", "websocket"): return await self.api(scope, receive, send) + if scope.get("scheme") not in SECURE: + if scope["type"] == "websocket": + await send({"type": "websocket.close", "code": 4426}) + return + return await _page(send, 426, "FormAT answers other devices over https only.") path = scope.get("path") or "/" - secret = _secret() if (path.startswith("/s/") and "/" not in path[3:]) or path in ("/favicon.svg", "/favicon.png"): return await self.inner(scope, receive, send) if scope["type"] == "http" and path == "/pair": - q = dict(p.split("=", 1) for p in (scope.get("query_string") or b"").decode().split("&") if "=" in p) - if hmac.compare_digest(q.get("code", ""), secret): - await send({"type": "http.response.start", "status": 303, "headers": [ - (b"location", b"/"), (b"set-cookie", f"{COOKIE}={secret}; Path=/; HttpOnly; SameSite=Lax; Max-Age=31536000".encode())]}) - await send({"type": "http.response.body", "body": b""}) - return - if _paired(scope, secret): - return await self.inner(scope, receive, send) - if scope["type"] == "websocket": - await send({"type": "websocket.close", "code": 4401}) - return - body = b"

FormAT

This device is not paired. On the computer running FormAT, open Settings, Other devices, and scan the code or open its link here.

" - await send({"type": "http.response.start", "status": 401, "headers": [(b"content-type", b"text/html; charset=utf-8")]}) - await send({"type": "http.response.body", "body": body}) + return await self._pair(scope, send) + if scope["type"] == "http" and path == "/pair/wait": + return await self._wait(scope, send) + device = _device_of(scope) + if device: + return await self._held(scope, receive, send, *device) + await _refuse(scope, send) def _dist() -> Path: return config.frontend_dist() +def listener_config(asgi, port: int, host: str = "0.0.0.0"): + import uvicorn + cert, key = lan_cert.ensure(lan_addresses()) + return uvicorn.Config(asgi, host=host, port=port, lifespan="off", log_config=None, log_level=None, + ssl_certfile=str(cert), ssl_keyfile=str(key)) + + async def _serve() -> None: global _server - import contextlib - import uvicorn from starlette.staticfiles import StaticFiles from app.main import app redact_logs() - cfg = uvicorn.Config(Gate(app, StaticFiles(directory=str(_dist()), html=True)), host="0.0.0.0", port=LAN_PORT, lifespan="off", log_config=None, log_level=None) + cfg = listener_config(Gate(app, StaticFiles(directory=str(_dist()), html=True)), LAN_PORT) _server = uvicorn.Server(cfg) _server.capture_signals = contextlib.nullcontext await _server.serve() @@ -174,6 +374,10 @@ def _start() -> None: raise CommandError("The engine is still starting; try again", 503) if not (_dist() / "index.html").is_file(): raise CommandError("Build the window first with ./format build, so other devices can load it", 409) + try: + lan_cert.ensure(lan_addresses()) + except (OSError, ValueError) as exc: + raise CommandError(f"Could not make the certificate for other devices: {exc}", 500) from exc fut = asyncio.run_coroutine_threadsafe(_launch(), _loop) fut.result(10) @@ -192,6 +396,7 @@ async def _launch() -> None: def stop_server() -> None: global _server + _forget_requests() if _server is not None: _server.should_exit = True _server = None @@ -205,39 +410,75 @@ def _qr(url: str) -> str: def status() -> dict: on = running() - urls = [f"http://{ip}:{LAN_PORT}" for ip in lan_addresses()] if on else [] - out = {"on": on, "port": LAN_PORT, "urls": urls, "pairUrl": None, "qr": None} - if on and urls: - out["pairUrl"] = f"{urls[0]}/pair?code={_secret()}" + urls = [f"https://{ip}:{LAN_PORT}" for ip in lan_addresses()] if on else [] + fp = lan_cert.fingerprint() + out = {"on": on, "port": LAN_PORT, "urls": urls, "pairUrl": None, "qr": None, "pairExpiresIn": None, + "fingerprint": lan_cert.spaced(fp), "devices": device_tokens.listing(), "pending": pending() if on else []} + if on and urls and fp: + held = _current_code() + out["pairUrl"] = f"{urls[0]}/pair?code={held['code']}&fp={fp}" out["qr"] = _qr(out["pairUrl"]) + out["pairExpiresIn"] = max(0, round(held["made"] + CODE_LIFE - time.time())) return out +def _changed() -> None: + events.publish("devices.changed", devices={"on": running(), "paired": len(device_tokens.listing()), "waiting": len(pending())}) + + @command("devices.status", "Other devices", mutates=False, - description="Whether Format is reachable from other devices on this network (a phone or another computer), its addresses, and, when on, the pairing link and its QR code as SVG.") + description="Whether Format is reachable from other devices on this network (a phone or another computer), its https addresses, the listener certificate's SHA-256 fingerprint and the paired devices. Only FormAT's window also gets the pairing link, its QR code as SVG, how many seconds the code has left, and the devices waiting to be allowed.") def devices_status() -> dict: return status() -@command("devices.start", "Open to other devices", - description="Starts Format's network listener (port 8492) so a paired phone or computer on the same network can use Format, and shared links can be opened. Only paired devices reach chats; shared artifact links are read-only. Returns the pairing link and QR code.") +@command("devices.answer", "Allow or turn down a device", + {"id": {"type": "string", "required": True, "description": "request id from devices.status pending"}, + "allow": {"type": "boolean", "required": True, "description": "true pairs the device, false turns it down"}}, + description="Answers a device that opened the pairing link and is waiting: allow pairs it, otherwise it is turned down. Only FormAT's window can run this.", window_only=True) +def devices_answer(id: str, allow: bool) -> dict: + if not answer(id, allow): + raise CommandError("That device is no longer waiting; it may have given up or its request ran out of time", 404) + _changed() + return status() + + +@command("devices.start", "Open to other devices", window_only=True, + description="Starts Format's https network listener (port 8492; the first start makes this install's own certificate) so a paired phone or computer on the same network can use Format, and shared links can be opened. Only paired devices reach chats; shared artifact links are read-only. Only FormAT's window can run this; it gets the pairing link and QR code back.") def devices_start() -> dict: _start() - out = status() - events.publish("devices.changed", devices={k: v for k, v in out.items() if k != "qr"}) - return out + _changed() + return status() -@command("devices.stop", "Close to other devices", description="Stops the network listener; paired devices and shared links stop working until it starts again.") +@command("devices.stop", "Close to other devices", description="Stops the network listener; paired devices and shared links stop working until it starts again. Paired devices stay paired.") def devices_stop() -> dict: stop_server() - events.publish("devices.changed", devices={"on": False}) + _changed() return {"on": False} -@command("devices.forget", "Forget paired devices", description="Changes the pairing code, so every paired device has to pair again.") +@command("devices.list", "Paired devices", mutates=False, + description="The devices paired with Format: id, a name read from the device's browser, when it paired and when it was last seen.") +def devices_list() -> dict: + return {"devices": device_tokens.listing()} + + +@command("devices.revoke", "Unpair a device", {"id": {"type": "string", "required": True, "description": "device id from devices.list"}}, window_only=True, + description="Unpairs one device: its sign-in stops working at once, open connections from it close, and it has to pair again with a new code. Only FormAT's window can run this.") +def devices_revoke(id: str) -> dict: + if not device_tokens.revoke(id): + raise CommandError(f"No paired device {id}; devices.list gives the ids", 404) + _changed() + return status() + + +@command("devices.forget", "Forget paired devices", window_only=True, + description="Unpairs every device at once, turns down any device still waiting and changes the pairing code, so each one has to pair again. Only FormAT's window can run this.") def devices_forget() -> dict: - _secret(rotate=True) + _forget_requests(unpair=True) + _code(rotate=True) + _changed() return status() diff --git a/backend/app/engine/lan_cert.py b/backend/app/engine/lan_cert.py new file mode 100644 index 0000000..2a3a69c --- /dev/null +++ b/backend/app/engine/lan_cert.py @@ -0,0 +1,111 @@ +import datetime +import hashlib +import ipaddress +import os +import threading +from pathlib import Path + +from app.core import config + +LIFE_DAYS = 825 +RENEW_DAYS = 30 +_lock = threading.Lock() + + +def folder() -> Path: + return config.data_dir() / "devices" + + +def cert_path() -> Path: + return folder() / "listener.crt" + + +def key_path() -> Path: + return folder() / "listener.key" + + +def write_private(path: Path, data: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temp = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}") + fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + try: + with os.fdopen(fd, "wb") as out: + out.write(data) + os.replace(temp, path) + except BaseException: + temp.unlink(missing_ok=True) + raise + try: + os.chmod(path, 0o600) + except OSError: + pass + + +def _load(): + from cryptography import x509 + from cryptography.hazmat.primitives import serialization + try: + cert = x509.load_pem_x509_certificate(cert_path().read_bytes()) + key = serialization.load_pem_private_key(key_path().read_bytes(), password=None) + except (OSError, ValueError, TypeError): + return None + if cert.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo) != key.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo): + return None + left = cert.not_valid_after_utc - datetime.datetime.now(datetime.timezone.utc) + return cert if left > datetime.timedelta(days=RENEW_DAYS) else None + + +def _names(addresses: list[str]) -> list: + from cryptography import x509 + found: list = [x509.DNSName("localhost")] + for text in [*addresses, "127.0.0.1"]: + try: + ip = ipaddress.ip_address(text) + except ValueError: + continue + if x509.IPAddress(ip) not in found: + found.append(x509.IPAddress(ip)) + return found + + +def _make(addresses: list[str]) -> None: + from cryptography import x509 + from cryptography.hazmat.primitives import hashes, serialization + from cryptography.hazmat.primitives.asymmetric import ec + from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID + key = ec.generate_private_key(ec.SECP256R1()) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "FormAT paired devices")]) + now = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(minutes=5) + cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key()) + .serial_number(x509.random_serial_number()).not_valid_before(now).not_valid_after(now + datetime.timedelta(days=LIFE_DAYS)) + .add_extension(x509.SubjectAlternativeName(_names(addresses)), critical=False) + .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) + .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False) + .sign(key, hashes.SHA256())) + write_private(key_path(), key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())) + write_private(cert_path(), cert.public_bytes(serialization.Encoding.PEM)) + + +def ensure(addresses: list[str]) -> tuple[Path, Path]: + with _lock: + if _load() is None: + _make(addresses) + try: + os.chmod(key_path(), 0o600) + except OSError: + pass + return cert_path(), key_path() + + +def fingerprint() -> str | None: + from cryptography import x509 + from cryptography.hazmat.primitives import serialization + try: + cert = x509.load_pem_x509_certificate(cert_path().read_bytes()) + except (OSError, ValueError): + return None + return hashlib.sha256(cert.public_bytes(serialization.Encoding.DER)).hexdigest() + + +def spaced(fp: str | None) -> str | None: + return ":".join(fp[i:i + 2] for i in range(0, len(fp), 2)).upper() if fp else None diff --git a/backend/app/engine/marketplaces.py b/backend/app/engine/marketplaces.py index 639d869..fbd4353 100644 --- a/backend/app/engine/marketplaces.py +++ b/backend/app/engine/marketplaces.py @@ -430,7 +430,7 @@ def skill_offers() -> list[dict]: return out -def install_skill(market: str, path: str) -> dict: +def install_skill(market: str, path: str, overwrite: bool = False, rename: str | None = None) -> dict: from app.engine import skills e = _entry(market) folder = Path(e["folder"]).resolve() @@ -438,7 +438,9 @@ def install_skill(market: str, path: str) -> dict: if folder not in sk.parents or not (sk / "SKILL.md").is_file(): raise CommandError(f"No skill at {path} in the {market} marketplace", 404) try: - return skills.install_from(sk, {"marketplace": market, "official": _official(e)}) + return skills.install_from(sk, {"marketplace": market, "official": _official(e)}, overwrite, rename) + except skills.SkillExists as exc: + raise CommandError(str(exc), 409, {"clash": {"name": exc.name, "suggested": exc.suggested}}) from None except skills.SkillError as exc: raise CommandError(str(exc)) from None @@ -494,10 +496,12 @@ def skill_discover() -> dict: return {"skills": skill_offers()} -@command("skill.installFrom", "Add a skill from a marketplace", {"marketplace": {"type": "string", "required": True}, "path": {"type": "string", "required": True, "description": "the skill's path from skill.discover"}}, - description="Installs one skill from a marketplace on its own, without its plugin. It is listed under From Anthropic and partners when the marketplace is Anthropic's, otherwise From marketplaces.") -def skill_install_from(marketplace: str, path: str) -> dict: - return install_skill(marketplace, path) +@command("skill.installFrom", "Add a skill from a marketplace", {"marketplace": {"type": "string", "required": True}, "path": {"type": "string", "required": True, "description": "the skill's path from skill.discover"}, + "overwrite": {"type": "boolean", "description": "true to replace a skill of the same name"}, + "name": {"type": "string", "description": "install under this name instead, to keep both skills"}}, + description="Installs one skill from a marketplace on its own, without its plugin. It is listed under From Anthropic and partners when the marketplace is Anthropic's, otherwise From marketplaces. A name already in use is refused with 409 and data.clash unless overwrite is true or name gives a new one.") +def skill_install_from(marketplace: str, path: str, overwrite: bool | None = None, name: str | None = None) -> dict: + return install_skill(marketplace, path, bool(overwrite), (name or "").strip().lower() or None) @command("plugin.install", "Add a plugin from a marketplace", {"marketplace": {"type": "string", "required": True}, "plugin": {"type": "string", "required": True}, diff --git a/backend/app/engine/plugins.py b/backend/app/engine/plugins.py index 4ca5e97..3433401 100644 --- a/backend/app/engine/plugins.py +++ b/backend/app/engine/plugins.py @@ -129,6 +129,26 @@ def _servers(folder: Path, m: dict) -> dict: return spec if isinstance(spec, dict) else {} +def _skill_name(name: str, base: str) -> str: + return (base if base.startswith(f"{name}-") or base == name else f"{name}-{base}")[:64].strip("-") + + +def _planned(src: Path, m: dict, name: str) -> list[str]: + sdir = src / (m["skills"] if isinstance(m.get("skills"), str) else "skills") + out = [_skill_name(name, str(skills.parse(sk.read_text(encoding="utf-8", errors="replace"))[0].get("name") or sk.parent.name).strip().lower()) + for sk in (sorted(sdir.glob("*/SKILL.md")) if sdir.is_dir() else [])] + cdir = src / "commands" + return out + [f"{name}-{cmd.stem.lower()}"[:64].strip("-") for cmd in (sorted(cdir.glob("*.md")) if cdir.is_dir() else [])] + + +def _refuse_clashes(src: Path, m: dict, name: str) -> None: + have = {s["name"]: s.get("plugin") or "" for s in skills.list_()} + taken = sorted({s for s in _planned(src, m, name) if s in have and have[s] != name}) + if taken: + raise CommandError(f"The plugin was not added: it would replace {', '.join(taken)}, which you already have and which did not come with the {name} plugin. " + "Rename or delete those skills first.", 409, {"clash": {"names": taken}}) + + def install(src: Path, origin: dict | None = None) -> dict: src = _find(src) m = _manifest(src) or {} @@ -139,6 +159,7 @@ def install(src: Path, origin: dict | None = None) -> dict: raise CommandError("plugin.json needs a description: it is how you and Claude know what the plugin is for") if sum(1 for f in src.rglob("*") if f.is_file()) > MAX_FILES: raise CommandError(f"A plugin holds at most {MAX_FILES} files") + _refuse_clashes(src, m, name) dest = root() / name kept = {} if dest.exists(): @@ -153,14 +174,14 @@ def install(src: Path, origin: dict | None = None) -> dict: for sk in sorted(sdir.glob("*/SKILL.md")) if sdir.is_dir() else []: text = sk.read_text(encoding="utf-8", errors="replace") base = str(skills.parse(text)[0].get("name") or sk.parent.name).strip().lower() - sname = (base if base.startswith(f"{name}-") or base == name else f"{name}-{base}")[:64].strip("-") + sname = _skill_name(name, base) staged = skills.root() / f".plugin-{sname}" if staged.exists(): shutil.rmtree(staged) shutil.copytree(sk.parent, staged) (staged / "SKILL.md").write_text(_front_md(text, sname, f"From the {name} plugin"), encoding="utf-8") try: - got = skills._install(staged, sname) + got = skills._install(staged, sname, True) finally: shutil.rmtree(staged, ignore_errors=True) st["skills"].append(got["name"]) @@ -169,7 +190,7 @@ def install(src: Path, origin: dict | None = None) -> dict: text = cmd.read_text(encoding="utf-8", errors="replace") first = next((ln.strip("# ").strip() for ln in skills.parse(text)[1].splitlines() if ln.strip()), "") sname = f"{name}-{cmd.stem.lower()}"[:64].strip("-") - got = skills.create_from_text(_front_md(text, sname, f"The /{cmd.stem} command from the {name} plugin: {first}"[:300])) + got = skills.create_from_text(_front_md(text, sname, f"The /{cmd.stem} command from the {name} plugin: {first}"[:300]), True) st["skills"].append(got["name"]) st["commandSkills"].append(got["name"]) st["commands"] += 1 diff --git a/backend/app/engine/sandbox.py b/backend/app/engine/sandbox.py index 9eee0b5..076000a 100644 --- a/backend/app/engine/sandbox.py +++ b/backend/app/engine/sandbox.py @@ -8,10 +8,12 @@ @command("sandbox.status", "Code sandbox", mutates=False, - description="Whether Claude's bash commands run sandboxed on this computer (bubblewrap on Linux, sandbox-exec on macOS), whether the sandbox is on (setting sandbox) and whether it allows the network (setting sandboxNetwork).") + description="Whether Claude's bash commands run sandboxed on this computer (bubblewrap on Linux, sandbox-exec on macOS), whether the sandbox is on (setting sandbox) and whether it allows the network (setting sandboxNetwork). claudeCode says the same for chats answered through Claude Code, which use Claude Code's own sandbox (sandboxed, domains, note).") def status_command() -> dict: + from app.engine import claude_code_sandbox from app.engine.cmd_settings import current - return status(current()) + settings = current() + return status(settings) | {"claudeCode": claude_code_sandbox.status(settings)} def kind() -> str | None: diff --git a/backend/app/engine/skills.py b/backend/app/engine/skills.py index 7ea6975..9124053 100644 --- a/backend/app/engine/skills.py +++ b/backend/app/engine/skills.py @@ -18,6 +18,40 @@ def __init__(self, message: str, status: int = 400): self.status = status +class SkillExists(SkillError): + def __init__(self, name: str, suggested: str): + super().__init__(f"A skill named {name} already exists, so nothing was changed. Pass overwrite true to replace it, " + f"or a new name to keep both (for example {suggested}).", 409) + self.name, self.suggested = name, suggested + + +def free_name(name: str) -> str: + n = 2 + while True: + tail = f"-{n}" + candidate = name[:64 - len(tail)].rstrip("-") + tail + if not (root() / candidate).exists(): + return candidate + n += 1 + + +def clash(name: str) -> dict: + name = (name or "").strip().lower() + taken = bool(NAME.match(name)) and (root() / name / "SKILL.md").is_file() + from app.engine import plugins + return {"name": name, "exists": taken, "suggested": free_name(name) if taken else name, "plugin": plugins.owner_of_skill(name) if taken else ""} + + +def _renamed(text: str, name: str) -> str: + m = re.match(r"^---\s*\n(.*?)\n---\s*\n?", text, re.S) + if not m: + return f"---\nname: {name}\n---\n\n{text}" + front = m.group(1) + line = re.compile(r"^name:.*$", re.M) + front = line.sub(f"name: {name}", front, count=1) if line.search(front) else f"name: {name}\n{front}" + return f"---\n{front}\n---\n" + text[m.end():] + + def root() -> Path: p = config.data_dir() / "skills" p.mkdir(parents=True, exist_ok=True) @@ -75,8 +109,8 @@ def _summary(p: Path, off: set[str]) -> dict: ORIGIN = ".format-skill.json" -def install_from(src: Path, origin: dict) -> dict: - got = _install(src, src.name) +def install_from(src: Path, origin: dict, overwrite: bool = False, rename: str | None = None) -> dict: + got = _install(src, src.name, overwrite, rename) (root() / got["name"] / ORIGIN).write_text(json.dumps(origin), encoding="utf-8") _publish() return get(got["name"]) @@ -102,10 +136,10 @@ def _publish() -> None: events.publish("skills.changed", skills=list_()) -def _install(src: Path, fallback: str) -> dict: +def _install(src: Path, fallback: str, overwrite: bool = False, rename: str | None = None) -> dict: text = (src / "SKILL.md").read_text(encoding="utf-8", errors="replace") front, _ = parse(text) - name = (front.get("name") or fallback or "").strip().lower() + name = (rename or front.get("name") or fallback or "").strip().lower() if not NAME.match(name): raise SkillError(f"the skill's name {name!r} must be lowercase letters, digits and hyphens, up to 64; set name: in SKILL.md's frontmatter") if not front.get("description"): @@ -114,10 +148,14 @@ def _install(src: Path, fallback: str) -> dict: if len(files) > MAX_FILES: raise SkillError(f"a skill holds at most {MAX_FILES} files") dest = root() / name + if dest.exists() and not overwrite and dest.resolve() != src.resolve(): + raise SkillExists(name, free_name(name)) stamp = time.time_ns() incoming, previous = root() / f".{name}.incoming-{stamp}", root() / f".{name}.previous-{stamp}" try: shutil.copytree(src, incoming, ignore=shutil.ignore_patterns("__MACOSX", ".DS_Store", ".git")) + if rename: + (incoming / "SKILL.md").write_text(_renamed(text, name), encoding="utf-8") except OSError as exc: shutil.rmtree(incoming, ignore_errors=True) raise SkillError(f"the skill could not be copied, and any skill named {name} is unchanged: {exc}") from None @@ -135,7 +173,7 @@ def _install(src: Path, fallback: str) -> dict: return get(name) -def add_upload(upload_id: str) -> dict: +def add_upload(upload_id: str, overwrite: bool = False, rename: str | None = None) -> dict: meta = uploads.get(upload_id) if meta is None: raise SkillError(f"no uploaded file {upload_id}", 404) @@ -146,36 +184,34 @@ def add_upload(upload_id: str) -> dict: found = sorted((p.parent for p in base.rglob("SKILL.md") if "__MACOSX" not in p.parts), key=lambda p: len(p.parts)) if not found: raise SkillError("the zip has no SKILL.md") - return _install(found[0], found[0].name if found[0] != base else Path(meta["name"]).stem) + return _install(found[0], found[0].name if found[0] != base else Path(meta["name"]).stem, overwrite, rename) if Path(meta["name"]).name.upper() == "SKILL.MD" or meta["name"].lower().endswith(".md"): - return create_from_text(Path(meta["path"]).read_text(encoding="utf-8", errors="replace")) + return create_from_text(Path(meta["path"]).read_text(encoding="utf-8", errors="replace"), overwrite, rename) raise SkillError("add a skill as a .zip of its folder or as its SKILL.md") -def create_from_text(text: str) -> dict: +def create_from_text(text: str, overwrite: bool = False, rename: str | None = None) -> dict: if len(text.encode()) > MAX_SKILL_FILE: raise SkillError("SKILL.md is too large") front, _ = parse(text) name = (front.get("name") or "").strip().lower() if not NAME.match(name): raise SkillError("SKILL.md needs name: in its frontmatter, lowercase letters, digits and hyphens") - staging = root() / f".staging-{name}" - if staging.exists(): - shutil.rmtree(staging) + staging = root() / f".staging-{name}-{time.time_ns()}" staging.mkdir() (staging / "SKILL.md").write_text(text, encoding="utf-8") try: - return _install(staging, name) + return _install(staging, name, overwrite, rename) finally: shutil.rmtree(staging, ignore_errors=True) -def create(name: str, description: str, body: str) -> dict: +def create(name: str, description: str, body: str, overwrite: bool = False) -> dict: description = " ".join((description or "").split()) if not description: raise SkillError("a skill needs a description: when should Claude use it?") text = f"---\nname: {name}\ndescription: {description}\n---\n\n{(body or '').strip()}\n" - return create_from_text(text) + return create_from_text(text, overwrite) def set_enabled(name: str, on: bool) -> dict: diff --git a/backend/app/engine/store.py b/backend/app/engine/store.py index d5af765..1098e4e 100644 --- a/backend/app/engine/store.py +++ b/backend/app/engine/store.py @@ -106,6 +106,13 @@ created REAL NOT NULL ); CREATE INDEX IF NOT EXISTS shares_by_artifact ON shares(artifact_id); +CREATE TABLE IF NOT EXISTS paired_devices ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + token_hash TEXT NOT NULL UNIQUE, + created REAL NOT NULL, + seen REAL NOT NULL +); """ _lock = threading.RLock() @@ -153,8 +160,8 @@ def conn() -> sqlite3.Connection: if "demo" not in conv_cols: c.execute("ALTER TABLE conversations ADD COLUMN demo TEXT") c.execute("CREATE INDEX IF NOT EXISTS messages_by_parent ON messages(conversation_id, parent_id)") - c.execute("INSERT OR IGNORE INTO meta(key, value) VALUES ('schema', '8')") - c.execute("UPDATE meta SET value = '8' WHERE key = 'schema'") + c.execute("INSERT OR IGNORE INTO meta(key, value) VALUES ('schema', '9')") + c.execute("UPDATE meta SET value = '9' WHERE key = 'schema'") _conn = c return _conn diff --git a/backend/app/engine/tools.py b/backend/app/engine/tools.py index 6436ed4..4d07880 100644 --- a/backend/app/engine/tools.py +++ b/backend/app/engine/tools.py @@ -81,8 +81,9 @@ ] ADD_PLUGIN = {"name": "add_plugin", "description": "Install a Claude plugin you wrote in this chat's workspace into Format (the person approves first). folder is the plugin's folder, the one holding .claude-plugin/plugin.json. Calling it again with the same plugin name replaces the installed copy and keeps the connectors already added.", "input_schema": {"type": "object", "properties": {"folder": {"type": "string", "description": "Path of the plugin folder, relative to the workspace folder"}}, "required": ["folder"]}} -SAVE_SKILL = {"name": "save_skill", "description": "Install a skill you wrote or edited in this chat's workspace into Format (the person approves first). folder holds its SKILL.md; a skill with the same name is replaced. Skills that came with a plugin cannot be replaced.", - "input_schema": {"type": "object", "properties": {"folder": {"type": "string", "description": "Path of the skill folder, relative to the workspace folder"}}, "required": ["folder"]}} +SAVE_SKILL = {"name": "save_skill", "description": "Install a skill you wrote or edited in this chat's workspace into Format (the person approves first). folder holds its SKILL.md. If a skill with the same name exists it is refused; pass overwrite true only when the person wants that skill replaced, or give the new skill another name. Skills that came with a plugin cannot be replaced.", + "input_schema": {"type": "object", "properties": {"folder": {"type": "string", "description": "Path of the skill folder, relative to the workspace folder"}, + "overwrite": {"type": "boolean", "description": "true to replace the installed skill of the same name"}}, "required": ["folder"]}} NAMES = {d["name"] for d in DEFINITIONS} | {"memory", "skill", "browser", "add_plugin", "save_skill"} SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv"} @@ -327,7 +328,7 @@ def run(name: str, args: dict, conversation_id: str, on_output, cancel: threadin if plugins.owner_of_skill(want): return f"The {want} skill came with the {plugins.owner_of_skill(want)} plugin and is not replaced here; give the new skill another name.", True try: - got = skills._install(folder, folder.name) + got = skills._install(folder, folder.name, args.get("overwrite") is True) except skills.SkillError as exc: return f"The skill was not saved: {exc}", True return f"Saved the {got['name']} skill in Format; it is on and Claude can use it in any chat.", False diff --git a/backend/app/harness/prompt.py b/backend/app/harness/prompt.py index 2426343..fc4ced4 100644 --- a/backend/app/harness/prompt.py +++ b/backend/app/harness/prompt.py @@ -23,7 +23,7 @@ "doc": "The person chose Create, Document for this message: give the answer as a document with write_document kind doc. Write the title and an outline of ## sections first, then fill each section with its own write_document call (artifact_id and section), so the person watches it build and can comment on sections. Keep the chat reply to a few sentences about what you wrote.", "sheet": "The person chose Create, Spreadsheet for this message: give the answer as a spreadsheet with write_document kind sheet, CSV with a header row and one record per row, numbers without units or thousands separators so they export cleanly to Excel. Keep the chat reply to a few sentences about the sheet.", "plugin": "The person chose Create with Claude to make a Claude plugin in this chat. Ask what it should do in a few short questions if that is not clear, then build it as a folder in this chat's workspace named after the plugin (lowercase letters, digits and hyphens): .claude-plugin/plugin.json with name, description and version; one folder per skill under skills/ with a SKILL.md that starts with --- name and description --- front matter and then the instructions; commands/.md for any slash command; and .mcp.json only if it needs an MCP server. Keep skills focused and their descriptions specific about when to use them. Show the person what you wrote, and when they are happy call add_plugin with the folder, which asks them to approve and then installs it in Format. If they want changes later, edit the files and call add_plugin again; it replaces the installed copy.", - "skill": "The person is creating or editing a skill with you in this chat. If they named an existing skill, load it with the skill tool (SKILL.md and each of its files), copy it into a folder in this chat's workspace named after the skill, and make the changes there; otherwise ask what the skill should do in a few short questions if that is not clear, then write a folder named after it (lowercase letters, digits and hyphens) holding SKILL.md, which starts with --- name and description --- front matter and then the instructions, plus any reference files it points to. Keep the description specific about when Claude should use the skill. Show the person what you wrote, and when they are happy call save_skill with the folder, which asks them to approve and then installs it in Format, replacing a skill of the same name.", + "skill": "The person is creating or editing a skill with you in this chat. If they named an existing skill, load it with the skill tool (SKILL.md and each of its files), copy it into a folder in this chat's workspace named after the skill, and make the changes there; otherwise ask what the skill should do in a few short questions if that is not clear, then write a folder named after it (lowercase letters, digits and hyphens) holding SKILL.md, which starts with --- name and description --- front matter and then the instructions, plus any reference files it points to. Keep the description specific about when Claude should use the skill. Show the person what you wrote, and when they are happy call save_skill with the folder, which asks them to approve and then installs it in Format. A skill of the same name is not replaced unless you pass overwrite true: pass it when the person is editing that skill, and otherwise ask them whether to replace it or give the new one another name.", "deck": "The person chose Create, Slides for this message: give the answer as a slide deck with write_document kind deck, Markdown slides separated by lines of ---, each with a # title and three to five short bullets, a title slide first and a closing slide last. The person can export it to PowerPoint or PDF. Keep the chat reply to a few sentences about the deck.", } diff --git a/backend/app/routers/commands.py b/backend/app/routers/commands.py index bf0e70c..315bae5 100644 --- a/backend/app/routers/commands.py +++ b/backend/app/routers/commands.py @@ -16,7 +16,7 @@ def _run(cid: str, params: dict | None) -> tuple[int, dict]: try: result = dispatch(cid, params or {}) except CommandError as exc: - return exc.status, {"ok": False, "command": cid, "error": str(exc)} + return exc.status, {"ok": False, "command": cid, "error": str(exc)} | ({"data": exc.data} if exc.data else {}) except Exception as exc: log.exception("command %s failed", cid) return 500, {"ok": False, "command": cid, "error": f"{type(exc).__name__}: {exc}"} @@ -42,12 +42,15 @@ def describe(cid: str) -> Any: @router.post("/commands/{cid}") def run(request: Request, cid: str, params: dict | None = Body(default=None), x_format_agent: str | None = Header(default=None)) -> Any: outside = bool(x_format_agent) or not window_key.is_window(request.scope) - if outside: - try: + own = not x_format_agent and window_key.own_window(request.scope) + try: + if outside: agents.require_outside(x_format_agent or "", "stdio" if x_format_agent else "rest", cid, params) - except CommandError as exc: - return JSONResponse({"ok": False, "command": cid, "error": str(exc)}, status_code=exc.status) + if not own: + agents.refuse_window_only(cid) + except CommandError as exc: + return JSONResponse({"ok": False, "command": cid, "error": str(exc)}, status_code=exc.status) status, body = _run(cid, params) - if outside and status == 200: + if not own and status == 200: body = body | {"result": agents.outside_result(cid, body["result"])} return body if status == 200 else JSONResponse(body, status_code=status) diff --git a/backend/app/routers/mcp_http.py b/backend/app/routers/mcp_http.py index b0305e7..e66b8e5 100644 --- a/backend/app/routers/mcp_http.py +++ b/backend/app/routers/mcp_http.py @@ -13,6 +13,7 @@ async def _call(cid: str, params: dict, client: str): def run(): agents.require_outside(client, "http", cid, params) + agents.refuse_window_only(cid) return agents.outside_result(cid, dispatch(cid, params)) return await anyio.to_thread.run_sync(run) diff --git a/backend/requirements.txt b/backend/requirements.txt index 2782bfd..c8a5793 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -9,6 +9,7 @@ python-docx==1.2.0 openpyxl==3.1.5 reportlab==5.0.1 segno==1.6.6 +cryptography==50.0.2 keyring==25.7.0 ptyprocess==0.7.0; sys_platform != "win32" pywinpty==3.0.5; sys_platform == "win32" diff --git a/backend/requirements_macos.txt b/backend/requirements_macos.txt index c172efa..42d4582 100644 --- a/backend/requirements_macos.txt +++ b/backend/requirements_macos.txt @@ -9,5 +9,6 @@ python-docx==1.2.0 openpyxl==3.1.5 reportlab==5.0.1 segno==1.6.6 +cryptography==50.0.2 keyring==25.7.0 ptyprocess==0.7.0 diff --git a/backend/tests/test_artifacts_and_devices.py b/backend/tests/test_artifacts_and_devices.py index eb7793b..d976934 100644 --- a/backend/tests/test_artifacts_and_devices.py +++ b/backend/tests/test_artifacts_and_devices.py @@ -1,10 +1,19 @@ import asyncio +import hashlib +import http.client +import os +import socket +import ssl +import stat +import threading +import time +from urllib.parse import parse_qs, urlsplit import pytest from _format import run -from app.engine import devices +from app.engine import device_tokens, devices, lan_cert from app.engine.commands import dispatch PAGE = "t

artifact body

" @@ -68,11 +77,15 @@ async def __call__(self, scope, receive, send): await send({"type": "http.response.body", "body": b"inside"}) -def _through_gate(path, cookie=None, query=b"", kind="http"): +PHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Version/18.0 Mobile/15E148 Safari/604.1" + + +def _through_gate(path, cookie=None, query=b"", kind="http", scheme=None, agent=PHONE): api = _Recorder() gate = devices.Gate(api, None) sent = [] headers = [(b"cookie", cookie.encode())] if cookie else [] + headers.append((b"user-agent", agent.encode())) async def receive(): return {"type": "http.request" if kind == "http" else "websocket.connect"} @@ -80,13 +93,52 @@ async def receive(): async def send(message): sent.append(message) - asyncio.run(gate({"type": kind, "path": path, "query_string": query, "headers": headers}, receive, send)) + scheme = scheme or ("https" if kind == "http" else "wss") + asyncio.run(gate({"type": kind, "scheme": scheme, "path": path, "query_string": query, "headers": headers}, receive, send)) return api.called, sent -def test_the_devices_server_refuses_a_request_without_its_cookie(client): - secret = devices._secret() - for cookie in (None, "format_pair=wrong", f"other={secret}", "format_pair="): +def _cookies_set(message): + return [v.decode() for k, v in message["headers"] if k == b"set-cookie"] + + +def _ask(agent=PHONE): + lan_cert.ensure(["192.0.2.10"]) + query = f"code={devices._code()}&fp={lan_cert.fingerprint()}".encode() + called, sent = _through_gate("/pair", query=query, agent=agent) + assert not called and sent[0]["status"] == 303, sent + assert dict(sent[0]["headers"])[b"location"] == b"/pair/wait" + (cookie,) = _cookies_set(sent[0]) + assert not cookie.startswith(f"{devices.COOKIE}=") + return cookie.split(";", 1)[0] + + +def _poll(wait): + called, sent = _through_gate("/pair/wait", wait) + assert not called + return sent + + +def _pair(agent=PHONE): + wait = _ask(agent) + rid = devices.pending()[-1]["id"] + dispatch("devices.answer", {"id": rid, "allow": True}) + sent = _poll(wait) + assert sent[0]["status"] == 303, sent + cookie = next(c for c in _cookies_set(sent[0]) if c.startswith(f"{devices.COOKIE}=")) + return cookie, cookie.split(";", 1)[0] + + +@pytest.fixture +def no_devices(client): + run(client, "devices.forget") + yield + run(client, "devices.forget") + + +def test_the_devices_server_refuses_a_request_without_a_device_token(client, no_devices): + code = devices._code() + for cookie in (None, f"{devices.COOKIE}=wrong", f"other={code}", f"{devices.COOKIE}=", f"{devices.COOKIE}={code}", f"format_pair={code}"): called, sent = _through_gate("/api/commands", cookie) assert not called, cookie assert sent[0]["status"] == 401 @@ -94,19 +146,40 @@ def test_the_devices_server_refuses_a_request_without_its_cookie(client): assert not called and sent[0] == {"type": "websocket.close", "code": 4401} -def test_the_devices_server_lets_a_paired_device_in(client): - called, _ = _through_gate("/api/commands", f"{devices.COOKIE}={devices._secret()}") +def test_pairing_issues_a_token_for_this_device_only_and_spends_the_code(client, no_devices): + code = devices._code() + cookie, pair = _pair() + token = pair.split("=", 1)[1] + assert token != code and len(token) >= 40 + assert "HttpOnly" in cookie and "Secure" in cookie and "SameSite=Lax" in cookie + assert devices._code() != code + called, sent = _through_gate("/pair", query=f"code={code}&fp={lan_cert.fingerprint()}".encode()) + assert not called and sent[0]["status"] == 401 + called, _ = _through_gate("/api/commands", pair) assert called + listed = run(client, "devices.list")["devices"] + assert [d["name"] for d in listed] == ["iPhone, Safari"] + assert token not in str(listed) and "token_hash" not in listed[0] -def test_pairing_needs_the_code_and_sets_the_cookie(client): - secret = devices._secret() - called, sent = _through_gate("/pair", query=f"code={secret}".encode()) - assert not called and sent[0]["status"] == 303 - cookie = dict(sent[0]["headers"])[b"set-cookie"].decode() - assert cookie.startswith(f"{devices.COOKIE}={secret};") and "HttpOnly" in cookie - called, sent = _through_gate("/pair", query=b"code=guess") - assert not called and sent[0]["status"] == 401 +def test_pairing_needs_this_install_s_certificate_fingerprint(client, no_devices): + lan_cert.ensure(["192.0.2.10"]) + code = devices._code() + for query in (f"code={code}", f"code={code}&fp={'0' * 64}", f"code=guess&fp={lan_cert.fingerprint()}"): + called, sent = _through_gate("/pair", query=query.encode()) + assert not called and sent[0]["status"] == 401, query + assert devices._code() == code + assert run(client, "devices.list")["devices"] == [] + + +def test_the_devices_server_refuses_plain_http_even_with_a_token(client, no_devices): + _, pair = _pair() + called, sent = _through_gate("/api/commands", pair, scheme="http") + assert not called and sent[0]["status"] == 426 + called, sent = _through_gate("/s/anything", scheme="http") + assert not called and sent[0]["status"] == 426 + called, sent = _through_gate("/api/events", pair, kind="websocket", scheme="ws") + assert not called and sent[0]["type"] == "websocket.close" def test_share_links_pass_the_gate_without_pairing(client): @@ -114,10 +187,145 @@ def test_share_links_pass_the_gate_without_pairing(client): assert called -def test_forgetting_devices_changes_the_code(client): - before = devices._secret() +def test_unpairing_one_device_leaves_the_others_paired(client, no_devices): + _, phone = _pair() + _, laptop = _pair("Mozilla/5.0 (Macintosh; Intel Mac OS X 15_0) AppleWebKit/605.1.15 Version/18.0 Safari/605.1.15") + listed = run(client, "devices.list")["devices"] + assert [d["name"] for d in listed] == ["iPhone, Safari", "Mac, Safari"] + after = run(client, "devices.revoke", {"id": listed[0]["id"]}) + assert [d["name"] for d in after["devices"]] == ["Mac, Safari"] + assert not _through_gate("/api/commands", phone)[0] + assert _through_gate("/api/commands", laptop)[0] + + +def test_forgetting_devices_unpairs_every_device_and_changes_the_code(client, no_devices): + _, pair = _pair() + before = devices._code() run(client, "devices.forget") - after = devices._secret() - assert after != before - called, _ = _through_gate("/api/commands", f"{devices.COOKIE}={before}") - assert not called + assert devices._code() != before + assert run(client, "devices.list")["devices"] == [] + assert not _through_gate("/api/commands", pair)[0] + + +def test_a_device_unpaired_while_its_request_is_being_admitted_is_refused(client, no_devices, monkeypatch): + _, pair = _pair() + did = run(client, "devices.list")["devices"][0]["id"] + real_watch = device_tokens.watch + + def unpair_then_watch(device): + device_tokens.revoke(did) + return real_watch(device) + + monkeypatch.setattr(device_tokens, "watch", unpair_then_watch) + called, sent = _through_gate("/api/commands", pair) + assert not called and sent[0]["status"] == 401 + _, pair = _pair() + did = run(client, "devices.list")["devices"][0]["id"] + called, sent = _through_gate("/api/events", pair, kind="websocket") + assert not called and sent[0] == {"type": "websocket.close", "code": 4401} + assert device_tokens._live == {} + + +def test_unpairing_closes_a_connection_the_device_holds_open(client, no_devices): + _, pair = _pair() + did = run(client, "devices.list")["devices"][0]["id"] + sent = [] + + async def held(scope, receive, send): + await send({"type": "websocket.accept"}) + await asyncio.Event().wait() + + async def go(): + never = asyncio.Event() + + async def receive(): + await never.wait() + + async def send(message): + sent.append(message) + + gate = devices.Gate(held, None) + task = asyncio.create_task(gate({"type": "websocket", "scheme": "wss", "path": "/api/events", "query_string": b"", + "headers": [(b"cookie", pair.encode())]}, receive, send)) + await asyncio.sleep(0.05) + assert sent == [{"type": "websocket.accept"}] + await asyncio.to_thread(device_tokens.revoke, did) + await asyncio.wait_for(task, 2) + + asyncio.run(go()) + assert sent[-1] == {"type": "websocket.close", "code": 4401} + + +def test_the_certificate_is_made_once_with_a_private_key_only_the_owner_reads(client): + cert, key = lan_cert.ensure(["192.0.2.10"]) + first = lan_cert.fingerprint() + assert lan_cert.ensure(["192.0.2.99"]) == (cert, key) and lan_cert.fingerprint() == first + assert len(first) == 64 + if os.name != "nt": + assert stat.S_IMODE(key.stat().st_mode) == 0o600 + assert stat.S_IMODE(devices._code_path().stat().st_mode) == 0o600 + assert b"PRIVATE KEY" not in cert.read_bytes() + + +def test_the_pairing_link_carries_the_certificate_fingerprint(client, monkeypatch): + monkeypatch.setattr(devices, "running", lambda: True) + monkeypatch.setattr(devices, "lan_addresses", lambda: ["192.0.2.10"]) + lan_cert.ensure(["192.0.2.10"]) + got = run(client, "devices.status") + link = urlsplit(got["pairUrl"]) + assert link.scheme == "https" and link.netloc == f"192.0.2.10:{devices.LAN_PORT}" + assert parse_qs(link.query)["fp"] == [lan_cert.fingerprint()] + assert got["fingerprint"].replace(":", "").lower() == lan_cert.fingerprint() + assert got["urls"] == [f"https://192.0.2.10:{devices.LAN_PORT}"] + + +def test_a_paired_device_page_on_https_passes_the_engine_s_origin_check(app, client, no_devices): + from fastapi.testclient import TestClient + + _, pair = _pair() + origin = f"https://192.0.2.10:{devices.LAN_PORT}" + phone = TestClient(devices.Gate(app, None), base_url=origin) + r = phone.post("/api/commands/devices.list", json={}, headers={"cookie": pair, "origin": origin}) + assert r.status_code == 200, r.text + assert r.json()["result"]["devices"][0]["name"] == "iPhone, Safari" + + +def _free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def test_the_listener_speaks_only_tls_with_the_pinned_certificate(client): + import uvicorn + + async def hello(scope, receive, send): + await send({"type": "http.response.start", "status": 200, "headers": [(b"content-type", b"text/plain")]}) + await send({"type": "http.response.body", "body": b"hello"}) + + port = _free_port() + server = uvicorn.Server(devices.listener_config(hello, port, host="127.0.0.1")) + thread = threading.Thread(target=server.run, daemon=True) + thread.start() + try: + deadline = time.time() + 10 + while not server.started and time.time() < deadline: + time.sleep(0.05) + assert server.started + with socket.create_connection(("127.0.0.1", port), timeout=5) as plain: + plain.sendall(b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n") + try: + answer = plain.recv(64) + except (ConnectionResetError, socket.timeout): + answer = b"" + assert not answer.startswith(b"HTTP/") + pinned = ssl.create_default_context(cafile=str(lan_cert.cert_path())) + conn = http.client.HTTPSConnection("127.0.0.1", port, context=pinned, timeout=5) + conn.request("GET", "/") + r = conn.getresponse() + assert r.status == 200 and r.read() == b"hello" + assert hashlib.sha256(conn.sock.getpeercert(binary_form=True)).hexdigest() == lan_cert.fingerprint() + conn.close() + finally: + server.should_exit = True + thread.join(10) diff --git a/backend/tests/test_claude_code_sandbox.py b/backend/tests/test_claude_code_sandbox.py new file mode 100644 index 0000000..e95aa7a --- /dev/null +++ b/backend/tests/test_claude_code_sandbox.py @@ -0,0 +1,168 @@ +import json +from pathlib import Path + +import pytest + +from app.engine import claude_code, claude_code_sandbox as box +from app.engine.commands import CommandError, dispatch + + +def which_of(*present): + return lambda name: f"/usr/bin/{name}" if name in present else None + + +PLATFORMS = [ + ("darwin", ("sandbox-exec",), "24.0.0", True), + ("darwin", (), "24.0.0", False), + ("linux", ("bwrap", "socat"), "6.8.0-generic", True), + ("linux", ("bwrap",), "6.8.0-generic", False), + ("linux", ("bwrap", "socat"), "5.15.167.4-microsoft-standard-WSL2", True), + ("linux", ("bwrap", "socat"), "4.4.0-19041-Microsoft", False), + ("win32", ("bwrap", "socat", "sandbox-exec"), "10", False), + ("freebsd14", ("bwrap", "socat"), "14.1", False), +] + + +@pytest.mark.parametrize("plat,present,release,expected", PLATFORMS) +def test_the_sandbox_is_offered_only_where_claude_code_can_run_one(plat, present, release, expected): + assert box.support(plat, which_of(*present), release)["available"] is expected + + +@pytest.mark.parametrize("plat,present,release,expected", PLATFORMS) +def test_launch_settings_turn_the_sandbox_on_for_the_workspace_only(tmp_path, plat, present, release, expected): + found = box.support(plat, which_of(*present), release) + work, uploads = tmp_path / "chat", tmp_path / "uploads" + out = box.settings_for(work, ["example.com"], [uploads], found, [tmp_path], windows=False) + assert out["permissions"]["disableBypassPermissionsMode"] == "disable" + assert len(out["permissions"]["deny"]) == 1 and out["permissions"]["deny"][0].startswith("Edit(//") + if not expected: + assert "sandbox" not in out + return + sb = out["sandbox"] + assert sb["enabled"] is True and sb["failIfUnavailable"] is True + assert sb["allowUnsandboxedCommands"] is False and sb["autoAllowBashIfSandboxed"] is False and sb["excludedCommands"] == [] + assert sb["network"] == {"allowedDomains": ["example.com"], "strictAllowlist": True} + assert sb["filesystem"] == {"allowWrite": [str(work)], "denyWrite": [str(uploads)], "denyRead": [str(tmp_path)], "allowRead": [str(work), str(uploads)]} + + +@pytest.mark.parametrize("path,windows,rule", [ + ("/data/skills", False, "Edit(//data/skills/**)"), + ("/Users/a b/data/uploads", False, "Edit(//Users/a b/data/uploads/**)"), + ("C:\\Users\\a\\FormAT\\skills", True, "Edit(//c/Users/a/FormAT/skills/**)"), + ("d:\\data\\uploads", True, "Edit(//d/data/uploads/**)"), +]) +def test_claude_code_file_tools_cannot_change_the_read_only_folders(path, windows, rule): + assert box.edit_rule(path, windows) == rule + assert box.settings_for(Path("/w"), [], [Path(path)], {"available": False}, windows=windows)["permissions"]["deny"] == [rule] + + +def _hidden_tree(tmp_path): + data = tmp_path / "data" + work, uploads, skills = data / "workspace" / "chats" / "c1", data / "uploads", data / "skills" + for p in (work, uploads, skills, data / "workspace" / "chats" / "c2", tmp_path / "secrets"): + p.mkdir(parents=True) + for f in (data / "format.db", tmp_path / ".env", data / "workspace" / "notes.txt"): + f.write_text("x") + return data, work, uploads, skills + + +@pytest.mark.parametrize("plat,present,release,expected", PLATFORMS) +def test_claude_code_file_tools_cannot_read_hidden_paths_with_or_without_the_sandbox(tmp_path, plat, present, release, expected): + data, work, uploads, skills = _hidden_tree(tmp_path) + found = box.support(plat, which_of(*present), release) + perms = box.settings_for(work, [], [uploads, skills], found, [tmp_path], windows=False)["permissions"] + root = tmp_path.resolve() + for d in (root / "secrets", root / "data" / "workspace" / "chats" / "c2"): + assert f"Read(/{d.as_posix()}/**)" in perms["deny"] and f"Edit(/{d.as_posix()}/**)" in perms["deny"] + for f in (root / ".env", root / "data" / "format.db", root / "data" / "workspace" / "notes.txt"): + assert f"Read(/{f.as_posix()})" in perms["deny"] and f"Edit(/{f.as_posix()})" in perms["deny"] + for kept in (work, uploads, skills): + k = kept.resolve().as_posix() + covering = [r for r in perms["deny"] if r.startswith("Read(") and (k + "/").startswith(r[len("Read(/"):].removesuffix(")").removesuffix("/**") + "/")] + assert covering == [] + assert f"Read(/{k}/**)" in perms["allow"] + + +def test_a_hidden_path_with_nothing_allowed_inside_is_denied_whole(tmp_path): + work, other = tmp_path / "chat", tmp_path / "home" + work.mkdir() + other.mkdir() + deny = box.settings_for(work, [], [], {"available": False}, [other], windows=False)["permissions"]["deny"] + h = other.resolve().as_posix() + assert deny == [f"Read(/{h}/**)", f"Edit(/{h}/**)"] + + +def test_claude_code_hides_the_same_paths_as_the_engine_sandbox_plus_the_key_file(tmp_path, monkeypatch): + from app.core import config + home, data, backend = tmp_path / "home", tmp_path / "elsewhere" / "data", tmp_path / "app" / "backend" + for p in (home, data, backend): + p.mkdir(parents=True) + (backend / ".env").write_text("ANTHROPIC_API_KEY=x") + monkeypatch.setattr(Path, "home", classmethod(lambda cls: home)) + monkeypatch.setattr(config, "data_dir", lambda: data) + monkeypatch.setattr(config, "BACKEND_DIR", backend) + assert box.hidden_paths() == [home, data.resolve(), (backend / ".env").resolve()] + (backend / ".env").unlink() + assert box.hidden_paths() == [home, data.resolve(), backend.resolve()] + + +@pytest.mark.parametrize("plat,present,release,expected", PLATFORMS) +def test_the_panel_says_plainly_whether_claude_code_is_sandboxed(plat, present, release, expected): + said = box.status({"claudeCodeDomains": []}, box.support(plat, which_of(*present), release)) + assert said["sandboxed"] is expected + assert ("runs sandboxed" in said["note"]) is expected + assert ("not sandboxed" in said["note"]) is (not expected) + + +def test_no_allowed_addresses_means_no_network_for_commands(): + found = box.support("darwin", which_of("sandbox-exec"), "24.0.0") + assert box.settings_for(Path("/w"), [], [], found)["sandbox"]["network"] == {"allowedDomains": [], "strictAllowlist": True} + assert "no network" in box.status({}, found)["note"] + + +@pytest.mark.parametrize("mode", ["ask", "auto", "plan"]) +def test_launch_arguments_carry_the_settings_file_and_never_bypass(tmp_path, mode): + launch = tmp_path / "launch.json" + args = claude_code.launch_args("claude", "m", {"permissionMode": mode}, "system", launch, {}, [], None) + assert args[args.index("--settings") + 1] == str(launch) + assert args[args.index("--setting-sources") + 1] == "user" + assert args[args.index("--permission-mode") + 1] != "bypassPermissions" + assert not set(args) & set(box.FORBIDDEN_FLAGS) + + +@pytest.mark.parametrize("bad", [["--dangerously-skip-permissions"], ["--allow-dangerously-skip-permissions"], ["--permission-mode", "bypassPermissions"], + ["--permission-mode=bypassPermissions"], ["--dangerously-skip-permissions=true"]]) +def test_a_bypass_launch_is_refused(bad): + with pytest.raises(box.LaunchRefused): + box.check_args(["claude", "-p", *bad]) + + +def test_a_bypass_mode_in_the_mode_table_is_refused(tmp_path, monkeypatch): + monkeypatch.setitem(claude_code.MODES, "auto", "bypassPermissions") + with pytest.raises(box.LaunchRefused): + claude_code.launch_args("claude", "m", {"permissionMode": "auto"}, "s", tmp_path / "l.json", {}, [], None) + + +def test_the_launch_file_is_private_and_holds_the_settings(): + path = box.write_launch({"sandbox": {"enabled": True}}) + try: + assert json.loads(path.read_text(encoding="utf-8")) == {"sandbox": {"enabled": True}} + assert path.stat().st_mode & 0o077 == 0 + finally: + path.unlink() + + +def test_allowed_addresses_are_checked_when_saved(app): + try: + got = dispatch("settings.set", {"key": "claudeCodeDomains", "value": [" Example.com ", "*.pypi.org", "example.com"]}) + assert got["claudeCodeDomains"] == ["example.com", "*.pypi.org"] + for bad in (["http://example.com"], ["exa mple.com"], "example.com", ["*"], [""]): + with pytest.raises(CommandError): + dispatch("settings.set", {"key": "claudeCodeDomains", "value": bad}) + finally: + dispatch("settings.set", {"key": "claudeCodeDomains", "value": []}) + + +def test_claude_code_status_reports_the_sandbox(app): + said = dispatch("sandbox.status", {})["claudeCode"] + assert set(said) >= {"sandboxed", "note", "domains"} diff --git a/backend/tests/test_device_pairing_consent.py b/backend/tests/test_device_pairing_consent.py new file mode 100644 index 0000000..f4c8c9c --- /dev/null +++ b/backend/tests/test_device_pairing_consent.py @@ -0,0 +1,191 @@ +import json +import threading +from types import SimpleNamespace + +import pytest +from conftest import set_policy +from fastapi.testclient import TestClient +from test_artifacts_and_devices import PHONE, _ask, _cookies_set, _pair, _poll, _through_gate + +from _format import run +from app.engine import device_tokens, devices, lan_cert, store +from app.engine.commands import dispatch + +WINDOW_ONLY = ("devices.start", "devices.revoke", "devices.forget", "devices.answer") +ORIGIN = f"https://192.0.2.10:{devices.LAN_PORT}" + + +@pytest.fixture +def clean(client, monkeypatch): + monkeypatch.setattr(devices, "running", lambda: True) + monkeypatch.setattr(devices, "lan_addresses", lambda: ["192.0.2.10"]) + monkeypatch.setattr(devices, "_start", lambda: None) + lan_cert.ensure(["192.0.2.10"]) + run(client, "devices.forget") + yield + run(client, "devices.forget") + set_policy("ask") + + +def _phone(app, cookie): + return TestClient(devices.Gate(app, None), base_url=ORIGIN, headers={"cookie": cookie, "origin": ORIGIN}) + + +def _params(cid): + return {"devices.revoke": {"id": "x"}, "devices.answer": {"id": "x", "allow": True}}.get(cid, {}) + + +def test_a_paired_device_gets_no_pairing_link_code_or_waiting_devices(app, client, clean): + _, pair = _pair() + _ask("Mozilla/5.0 (Linux; Android 15) Chrome/140.0 Mobile Safari/537.36") + code = devices._code() + r = _phone(app, pair).post("/api/commands/devices.status", json={}) + assert r.status_code == 200, r.text + got = r.json()["result"] + assert got["on"] is True and got["fingerprint"] and got["devices"] + assert got["pairUrl"] is None and got["qr"] is None and got["pending"] == [] + assert "pairExpiresIn" not in got + assert code not in r.text + own = run(client, "devices.status") + assert code in own["pairUrl"] and own["qr"] and len(own["pending"]) == 1 + + +@pytest.mark.parametrize("cid", WINDOW_ONLY) +def test_a_paired_device_cannot_pair_unpair_forget_or_start(app, client, clean, cid): + _, pair = _pair() + before = run(client, "devices.list")["devices"] + r = _phone(app, pair).post(f"/api/commands/{cid}", json=_params(cid)) + assert r.status_code == 403, r.text + assert "Only the FormAT window" in r.json()["error"] + assert run(client, "devices.list")["devices"] == before + + +@pytest.mark.parametrize("cid", WINDOW_ONLY) +def test_an_outside_agent_cannot_pair_unpair_forget_or_start(client, bare, clean, cid): + from test_f3_mcp import call, session + + set_policy("allowed") + r = client.post(f"/api/commands/{cid}", json=_params(cid), headers={"x-format-agent": "some agent"}) + assert r.status_code == 403 and "Only the FormAT window" in r.json()["error"] + r = bare.post(f"/api/commands/{cid}", json=_params(cid)) + assert r.status_code == 403 + got = call(client, "run_command", {"id": cid, "params": _params(cid)}, session(client)) + assert got.get("isError") and "Only the FormAT window" in json.dumps(got) + + +def test_the_window_still_runs_the_window_only_commands(client, clean): + _, pair = _pair() + did = run(client, "devices.list")["devices"][0]["id"] + assert run(client, "devices.revoke", {"id": did})["devices"] == [] + assert run(client, "devices.start")["pairUrl"] + + +def test_a_pairing_code_runs_out_after_a_few_minutes(client, clean, monkeypatch): + clock = {"now": 1_000_000.0} + monkeypatch.setattr(devices, "time", SimpleNamespace(time=lambda: clock["now"])) + code = devices._code(rotate=True) + left = run(client, "devices.status")["pairExpiresIn"] + assert 0 < left <= devices.CODE_LIFE <= 600 + clock["now"] += devices.CODE_LIFE + 1 + called, sent = _through_gate("/pair", query=f"code={code}&fp={lan_cert.fingerprint()}".encode()) + assert not called and sent[0]["status"] == 401 + assert devices.pending() == [] + fresh = run(client, "devices.status") + assert code not in fresh["pairUrl"] and fresh["pairExpiresIn"] == devices.CODE_LIFE + + +def test_a_scan_waits_for_the_window_and_issues_no_token_before_it_allows(client, clean): + wait = _ask() + assert run(client, "devices.list")["devices"] == [] + (asked,) = run(client, "devices.status")["pending"] + assert asked["name"] == "iPhone, Safari" and len(asked["check"]) == 6 + assert "secret" not in asked and "state" not in asked + sent = _poll(wait) + assert sent[0]["status"] == 200 + assert not any(c.startswith(f"{devices.COOKIE}=") for c in _cookies_set(sent[0])) + page = sent[1]["body"].decode() + assert "http-equiv=refresh" in page and "iPhone, Safari" in page + assert f"{asked['check'][:3]} {asked['check'][3:]}" in page + assert lan_cert.spaced(lan_cert.fingerprint()) in page + called, sent = _through_gate("/api/commands", wait) + assert not called and sent[0]["status"] == 401 + run(client, "devices.answer", {"id": asked["id"], "allow": True}) + sent = _poll(wait) + assert sent[0]["status"] == 303 and dict(sent[0]["headers"])[b"location"] == b"/" + token = next(c for c in _cookies_set(sent[0]) if c.startswith(f"{devices.COOKIE}=")).split(";", 1)[0] + assert _through_gate("/api/commands", token)[0] + assert [d["name"] for d in run(client, "devices.list")["devices"]] == ["iPhone, Safari"] + assert run(client, "devices.status")["pending"] == [] + assert _poll(wait)[0]["status"] == 401 + + +def test_a_device_turned_down_in_the_window_is_not_paired(client, clean): + wait = _ask() + rid = run(client, "devices.status")["pending"][0]["id"] + run(client, "devices.answer", {"id": rid, "allow": False}) + sent = _poll(wait) + assert sent[0]["status"] == 403 + assert not any(c.startswith(f"{devices.COOKIE}=") for c in _cookies_set(sent[0])) + assert run(client, "devices.list")["devices"] == [] + assert _poll(wait)[0]["status"] == 401 + r = client.post("/api/commands/devices.answer", json={"id": rid, "allow": True}) + assert r.status_code == 404 + + +def test_a_waiting_device_runs_out_of_time_and_a_made_up_wait_cookie_is_refused(client, clean, monkeypatch): + clock = {"now": 2_000_000.0} + monkeypatch.setattr(devices, "time", SimpleNamespace(time=lambda: clock["now"])) + wait = _ask() + rid = devices.pending()[0]["id"] + assert _poll(f"{devices.WAIT_COOKIE}=made-up")[0]["status"] == 401 + clock["now"] += devices.REQUEST_LIFE + 1 + assert devices.pending() == [] + assert client.post("/api/commands/devices.answer", json={"id": rid, "allow": True}).status_code == 404 + assert _poll(wait)[0]["status"] == 401 + assert run(client, "devices.list")["devices"] == [] + + +def test_closing_or_forgetting_drops_waiting_devices(client, clean): + wait = _ask() + run(client, "devices.forget") + assert devices.pending() == [] and _poll(wait)[0]["status"] == 401 + wait = _ask() + devices.stop_server() + assert devices.pending() == [] and _poll(wait)[0]["status"] == 401 + + +def test_a_device_whose_token_changes_while_it_is_being_admitted_is_refused(client, clean, monkeypatch): + _, pair = _pair() + did = run(client, "devices.list")["devices"][0]["id"] + real_watch = device_tokens.watch + + def swap_then_watch(device): + store.run("UPDATE paired_devices SET token_hash = ? WHERE id = ?", ("0" * 64, did)) + return real_watch(device) + + monkeypatch.setattr(device_tokens, "watch", swap_then_watch) + called, sent = _through_gate("/api/commands", pair, agent=PHONE) + assert not called and sent[0]["status"] == 401 + assert device_tokens._live == {} + + +def test_forgetting_devices_while_an_allowed_device_collects_its_token_leaves_it_unpaired(client, clean, monkeypatch): + wait = _ask() + run(client, "devices.answer", {"id": devices.pending()[0]["id"], "allow": True}) + real_issue = device_tokens.issue + forgets: list[threading.Thread] = [] + + def forget_meanwhile(name): + forgets.append(threading.Thread(target=dispatch, args=("devices.forget", {}))) + forgets[-1].start() + forgets[-1].join(0.5) + return real_issue(name) + + monkeypatch.setattr(device_tokens, "issue", forget_meanwhile) + sent = _poll(wait) + for t in forgets: + t.join(5) + assert len(forgets) == 1 and not forgets[0].is_alive() + assert run(client, "devices.list")["devices"] == [] + token = next((c for c in _cookies_set(sent[0]) if c.startswith(f"{devices.COOKIE}=")), "").split(";", 1)[0] + assert not _through_gate("/api/commands", token or None)[0] diff --git a/backend/tests/test_device_pairing_link.py b/backend/tests/test_device_pairing_link.py index c9b8e57..8bd6e0a 100644 --- a/backend/tests/test_device_pairing_link.py +++ b/backend/tests/test_device_pairing_link.py @@ -11,7 +11,7 @@ def listening(monkeypatch): monkeypatch.setattr(devices, "running", lambda: True) monkeypatch.setattr(devices, "lan_addresses", lambda: ["192.0.2.10"]) set_policy("allowed") - yield devices._secret() + yield devices._code() def test_the_window_gets_the_pairing_link(client, listening): diff --git a/backend/tests/test_migrations.py b/backend/tests/test_migrations.py index b847899..ac568ee 100644 --- a/backend/tests/test_migrations.py +++ b/backend/tests/test_migrations.py @@ -86,7 +86,7 @@ def _open(data): return json.loads(proc.stdout.strip().splitlines()[-1]) -CURRENT_TABLES = ["artifact_versions", "artifacts", "connectors", "conversations", "messages", "meta", "project_files", "projects", "schedule_runs", "schedules", "shares"] +CURRENT_TABLES = ["artifact_versions", "artifacts", "connectors", "conversations", "messages", "meta", "paired_devices", "project_files", "projects", "schedule_runs", "schedules", "shares"] def _message(mid, cid, text, created, parent=None, with_meta=False): @@ -98,13 +98,13 @@ def _message(mid, cid, text, created, parent=None, with_meta=False): @pytest.mark.parametrize("populated", [False, True]) -def test_schema_1_opens_as_schema_8(tmp_path, populated): +def test_schema_1_opens_as_schema_9(tmp_path, populated): rows = [] if populated: rows.append(("INSERT INTO conversations(id, title, created, updated) VALUES (?, ?, ?, ?)", ("c1", "Old chat", 1.0, 4.0))) rows += [_message(f"m{i}", "c1", f"line {i}", float(i)) for i in range(1, 5)] got = _open(_db(tmp_path, SCHEMA_1, rows)) - assert got["schema"] == "8" + assert got["schema"] == "9" assert got["tables"] == CURRENT_TABLES assert {"meta", "parent_id"} <= set(got["cols"]["messages"]) assert {"leaf_id", "allow_all", "connectors_off"} <= set(got["cols"]["conversations"]) @@ -123,7 +123,7 @@ def test_schema_7_with_data_keeps_every_row(tmp_path): ("b2", "c7", "a1", "assistant", json.dumps([{"type": "text", "text": "other reply"}]), 3.0, "{}")), ("INSERT INTO connectors(id, name, kind, url, created, updated) VALUES (?, ?, ?, ?, ?, ?)", ("k1", "docs", "remote", "https://example.com/mcp", 1.0, 1.0))] got = _open(_db(tmp_path, SCHEMA_1 + SCHEMA_7_EXTRA, rows)) - assert got["schema"] == "8" + assert got["schema"] == "9" assert got["tables"] == CURRENT_TABLES assert got["leafs"] == {"c7": "b2"} assert got["paths"] == {"c7": ["first", "other reply"]} diff --git a/backend/tests/test_skill_names.py b/backend/tests/test_skill_names.py new file mode 100644 index 0000000..9ada2e6 --- /dev/null +++ b/backend/tests/test_skill_names.py @@ -0,0 +1,93 @@ +import shutil +import threading + +import pytest + +from app.engine import plugins, skills, tools +from app.engine.commands import CommandError, dispatch + +NAME = "clash-check" + + +def folder_with(path, name, body): + path.mkdir(parents=True) + (path / "SKILL.md").write_text(f"---\nname: {name}\ndescription: test skill\n---\n{body}\n", encoding="utf-8") + return path + + +def body_of(name): + return (skills.root() / name / "SKILL.md").read_text(encoding="utf-8") + + +@pytest.fixture +def existing(tmp_path): + skills._install(folder_with(tmp_path / "first", NAME, "first body"), NAME) + yield NAME + for p in skills.root().iterdir(): + if p.name.startswith(NAME) or p.name.startswith("clashplug"): + shutil.rmtree(p, ignore_errors=True) + shutil.rmtree(plugins.root() / "clashplug", ignore_errors=True) + + +def test_adding_a_skill_with_a_taken_name_is_refused_and_changes_nothing(tmp_path, existing): + with pytest.raises(skills.SkillExists) as got: + skills._install(folder_with(tmp_path / "second", NAME, "second body"), NAME) + assert got.value.status == 409 and got.value.suggested == f"{NAME}-2" + assert "first body" in body_of(NAME) + + +def test_overwrite_replaces_the_skill(tmp_path, existing): + skills._install(folder_with(tmp_path / "second", NAME, "second body"), NAME, overwrite=True) + assert "second body" in body_of(NAME) + + +def test_keep_both_installs_under_the_new_name_and_renames_its_front_matter(tmp_path, existing): + got = skills._install(folder_with(tmp_path / "second", NAME, "second body"), NAME, rename=f"{NAME}-2") + assert got["name"] == f"{NAME}-2" + assert "first body" in body_of(NAME) + assert skills.parse(body_of(f"{NAME}-2"))[0]["name"] == f"{NAME}-2" + assert skills.clash(NAME)["suggested"] == f"{NAME}-3" + + +def test_the_create_command_refuses_a_taken_name_with_the_clash_details(app, existing): + with pytest.raises(CommandError) as got: + dispatch("skill.create", {"name": NAME, "description": "d", "instructions": "new body"}) + assert got.value.status == 409 and got.value.data == {"clash": {"name": NAME, "suggested": f"{NAME}-2"}} + assert "overwrite" in str(got.value) + assert "first body" in body_of(NAME) + dispatch("skill.create", {"name": NAME, "description": "d", "instructions": "new body", "overwrite": True}) + assert "new body" in body_of(NAME) + + +def test_the_window_hears_the_clash_over_rest(client, existing): + r = client.post("/api/commands/skill.create", json={"name": NAME, "description": "d", "instructions": "x"}) + assert r.status_code == 409 + assert r.json()["data"]["clash"]["suggested"] == f"{NAME}-2" + assert client.post("/api/commands/skill.clash", json={"name": NAME}).json()["result"]["exists"] is True + + +def test_claude_saving_a_skill_needs_an_explicit_overwrite(tmp_path, existing, monkeypatch): + work = tmp_path / "work" + folder_with(work / "draft", NAME, "from the chat") + monkeypatch.setattr(tools, "workspace", lambda cid: work) + text, failed = tools.run("save_skill", {"folder": "draft"}, "clash-chat", lambda s: None, threading.Event()) + assert failed and "already exists" in text + assert "first body" in body_of(NAME) + text, failed = tools.run("save_skill", {"folder": "draft", "overwrite": True}, "clash-chat", lambda s: None, threading.Event()) + assert not failed and "from the chat" in body_of(NAME) + + +def test_a_plugin_does_not_replace_a_skill_it_did_not_bring(tmp_path, existing): + skills._install(folder_with(tmp_path / "own", "clashplug-tool", "mine"), "clashplug-tool") + plug = tmp_path / "plug" + (plug / ".claude-plugin").mkdir(parents=True) + (plug / ".claude-plugin" / "plugin.json").write_text('{"name": "clashplug", "description": "test plugin"}', encoding="utf-8") + folder_with(plug / "skills" / "tool", "tool", "from the plugin") + with pytest.raises(CommandError) as got: + plugins.install(plug) + assert got.value.status == 409 and "clashplug-tool" in str(got.value) + assert "mine" in body_of("clashplug-tool") + shutil.rmtree(skills.root() / "clashplug-tool") + plugins.install(plug) + plugins.install(plug) + assert "from the plugin" in body_of("clashplug-tool") diff --git a/backend/tests/test_skill_replace.py b/backend/tests/test_skill_replace.py index 4e0ad1b..08da7ab 100644 --- a/backend/tests/test_skill_replace.py +++ b/backend/tests/test_skill_replace.py @@ -24,13 +24,13 @@ def broken(src, dst, **kw): raise OSError("disk full") monkeypatch.setattr(skills.shutil, "copytree", broken) with pytest.raises(skills.SkillError): - skills._install(make(tmp_path / "second", "second body"), "replace-check") + skills._install(make(tmp_path / "second", "second body"), "replace-check", overwrite=True) assert "first body" in (installed / "SKILL.md").read_text(encoding="utf-8") assert not [p for p in skills.root().iterdir() if p.name.startswith(".replace-check")] def test_installing_again_replaces_the_skill_and_leaves_nothing_behind(tmp_path, installed): - skills._install(make(tmp_path / "second", "second body"), "replace-check") + skills._install(make(tmp_path / "second", "second body"), "replace-check", overwrite=True) assert "second body" in (installed / "SKILL.md").read_text(encoding="utf-8") assert not [p for p in skills.root().iterdir() if p.name.startswith(".replace-check")] diff --git a/docs/artifacts-and-documents.md b/docs/artifacts-and-documents.md index 0b83527..56c5b01 100644 --- a/docs/artifacts-and-documents.md +++ b/docs/artifacts-and-documents.md @@ -24,7 +24,7 @@ Ask for one, or use Create in the + menu. They open beside the chat in their own ## Share links -Share in the panel's header makes a read-only link to the latest version of the artifact, with Copy link, Open link and Stop sharing. While Other devices is off the link opens only on this computer; with it on, anyone on your network who has the link can open it. Stopped links answer "no longer shared". See [Other devices](other-devices.md). +Share in the panel's header makes a read-only link to the latest version of the artifact, with Copy link, Open link and Stop sharing. While Other devices is off the link opens only on this computer; with it on, anyone on your network who has the link can open it, over https with FormAT's own certificate, so their browser warns once. Stopped links answer "no longer shared". See [Other devices](other-devices.md). ## The chat's files diff --git a/docs/getting-started.md b/docs/getting-started.md index 1bed44c..b39a6d7 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -33,6 +33,7 @@ Two optional parts install separately: If Claude Code is installed (the `claude` command) and you have signed in to it once, FormAT needs no key: each reply runs through Claude Code on your Claude plan, in the chat's own folder, and streams into the chat like any other reply. The line under the composer says "through Claude Code", and so does the account line at the bottom of the sidebar. - Claude Code's tools show as FormAT's cards (Ran a command, Edited a file, Read a file), and Ask, Allow all and Plan work the same way: in Ask, a command or file change waits for Allow once, Always allow, Allow all or Deny; Allow all allows them; Plan blocks them. FormAT's skills are offered to Claude Code too. Claude Code's questions arrive as FormAT's question card, and its sub-agents show nested. +- FormAT always starts Claude Code with Claude Code's own sandbox turned on and never in its bypass permissions mode. In the sandbox, Claude Code's commands can change files only in the chat's folder and reach only the addresses you list in Settings, Tools, Sandbox, under "Addresses Claude Code's commands can reach" (none until you add some, such as `pypi.org` or `*.github.com`). Claude Code's sandbox runs on macOS, and on Linux and WSL 2 with bubblewrap and socat installed. Elsewhere, Windows included, the reply still runs, and the same Sandbox section says in plain words that Claude Code's commands are not sandboxed. Settings in the chat's folder cannot turn the sandbox off: FormAT reads only your own Claude Code settings beside the ones it passes. On every platform, Claude Code cannot read your home folder, FormAT's own data folder or FormAT's key file, apart from the chat's folder, uploads and skills: its file tools are refused there, and in the sandbox its commands are too. On every platform, Claude Code's file tools cannot change your uploads or installed skills, so a Claude Code chat never replaces a skill behind your back; add or replace skills in Customize, which asks before replacing one of the same name. - Each reply continues the chat's Claude Code session, so Claude remembers the chat. Editing an earlier message branches from the session at that point. - To choose, open the model menu, Answer through: Automatic (your API key when one is set, otherwise Claude Code), Anthropic API key, or Claude Code. The menu item appears once FormAT finds Claude Code. - If a reply says Claude Code is not signed in, run `claude` in a terminal (FormAT's terminal dock works), sign in with `/login`, then retry. diff --git a/docs/other-devices.md b/docs/other-devices.md index 8497d98..5f1a489 100644 --- a/docs/other-devices.md +++ b/docs/other-devices.md @@ -6,15 +6,33 @@ FormAT runs on one computer, but you can carry on from your phone or another com 1. On the computer running FormAT, open Settings, Other devices, and choose Open to other devices. 2. Scan the code with your phone's camera, or open the link shown under it on the other device. -3. The other device opens FormAT, paired. It sees the same chats, live, both ways: start a chat on the computer and continue it on the phone. +3. The other device's browser warns that it does not know the certificate. That is expected: FormAT makes its own certificate for this computer the first time you open it to other devices. Open the certificate details in the warning and check that its SHA-256 fingerprint matches the one Settings shows under the code, then continue. The browser remembers the certificate after that. +4. The other device shows a waiting page with its name (for example "iPhone, Safari"), a six-digit check number and the certificate fingerprint. On the computer, Settings, Other devices shows the same request with the same name, check number and fingerprint. If they match the device in your hand, choose Allow; otherwise choose Turn down. +5. The other device opens FormAT, paired, within a few seconds. It sees the same chats, live, both ways: start a chat on the computer and continue it on the phone. -A device that is not paired gets a page saying so. Forget paired devices unpairs every device at once (they pair again with the new code). Close to other devices stops FormAT listening on the network. +Nothing is paired until you choose Allow in FormAT's window on the computer. A device that is turned down, or that waits more than five minutes, has to scan a new code. -FormAT listens on your network (port 8492) only while this is on. The pairing link is a secret: anyone on your network who has it can use FormAT as you, with your API key. Share it only with your own devices. +Each code pairs one device and lasts five minutes; Settings shows a new code when it runs out and once a device has used it, so pair each phone or computer with its own scan. A link that was already used, that ran out, or that names a different certificate, shows a page saying so; scan the code shown now. + +Only FormAT's window on the computer shows the pairing code and link, and only it can open FormAT to other devices, allow a device, unpair one or forget them all. A paired phone sees the paired devices and the fingerprint, but not the code, and cannot pair, unpair or forget devices. Agents connected over MCP or the command line cannot either. + +A device that is not paired gets a page saying so. + +## Paired devices + +Settings, Other devices lists every paired device with the browser it paired from, when it paired and when it was last seen. Unpair beside a device stops that device at once, including a page it has open, and leaves the others paired. Forget paired devices unpairs every device at once and changes the code. Close to other devices stops FormAT listening on the network; paired devices stay paired and work again when you open it again. + +## How the connection is kept private + +FormAT listens on your network (port 8492) only while this is on, and only over https: a plain http request to that port gets no answer. The certificate and its private key stay in FormAT's data folder, readable by your user account only. The certificate lasts about two years; FormAT makes a new one shortly before it expires, and each browser warns once more. + +The code is a secret until it is used, and it runs out after five minutes. A device that uses it still needs you to choose Allow on the computer, so check the name and check number before you do: a request you did not expect, or one whose check number differs from your device's page, is not your device. Paired devices use FormAT as you, with your API key; unpair a device you no longer use or have lost. + +Devices paired with a version of FormAT before this change have to pair again once. ## Share links -An artifact's Share button makes a read-only link to its latest version. While other devices are open the link uses your network address, so anyone on your network with the link can open that one artifact, without being paired. Stop sharing makes the link answer "no longer shared". +An artifact's Share button makes a read-only link to its latest version. While other devices are open the link uses your network address over https, so anyone on your network with the link can open that one artifact, without being paired; their browser shows the same certificate warning. Stop sharing makes the link answer "no longer shared". ## On a phone diff --git a/docs/projects-memory-customize.md b/docs/projects-memory-customize.md index 2c8dbaf..874447a 100644 --- a/docs/projects-memory-customize.md +++ b/docs/projects-memory-customize.md @@ -35,7 +35,7 @@ A plugin's skills and commands appear under Skills, named after the plugin (`rel ### Skills -A skill is a folder with a SKILL.md whose name and description tell Claude when to use it. Claude sees every skill that is on and loads one when a task matches, through the API or through Claude Code. Name one in a message to load it for that message: type `/` and pick it, start the message with `/name`, or write "use the name skill"; you can also pick one from the + menu. Add, Upload a skill takes a .zip of its folder or its SKILL.md; Add, Write a skill takes a name, when to use it and the instructions. Open a skill to read SKILL.md and every other file in it before you use it, and Try in chat starts a new chat with it picked. Add, Create with Claude starts a chat where Claude writes a skill with you, and a skill's Edit with Claude starts one that changes it; Claude saves it when you approve its card. Discover lists the skills your marketplaces offer, each added on its own (Add Anthropic's skills marketplace brings in anthropics/skills). The list groups skills under Created by you, From Anthropic and partners, From marketplaces and From plugins; a plugin's skill is removed with its plugin. +A skill is a folder with a SKILL.md whose name and description tell Claude when to use it. Claude sees every skill that is on and loads one when a task matches, through the API or through Claude Code. Name one in a message to load it for that message: type `/` and pick it, start the message with `/name`, or write "use the name skill"; you can also pick one from the + menu. Add, Upload a skill takes a .zip of its folder or its SKILL.md; Add, Write a skill takes a name, when to use it and the instructions. Open a skill to read SKILL.md and every other file in it before you use it, and Try in chat starts a new chat with it picked. Add, Create with Claude starts a chat where Claude writes a skill with you, and a skill's Edit with Claude starts one that changes it; Claude saves it when you approve its card. Discover lists the skills your marketplaces offer, each added on its own (Add Anthropic's skills marketplace brings in anthropics/skills). When a skill you upload, write or add from Discover has the name of one you already have, FormAT asks first: Overwrite replaces the one you have, Keep both adds the new one under a free name such as `name-2`, and Cancel changes nothing. Claude asks before it saves over one of your skills too, and its approval card says it will replace it. An agent connected over MCP or the command line is refused with a plain message unless it says to overwrite or gives a new name. A plugin is not added when one of its skills would replace a skill that did not come with it; rename or delete that skill first. The list groups skills under Created by you, From Anthropic and partners, From marketplaces and From plugins; a plugin's skill is removed with its plugin. ### Connectors diff --git a/docs/settings.md b/docs/settings.md index 0b7e1eb..eaa44b2 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -36,7 +36,7 @@ The sections, in order: Account, API keys, Tools, Long chats, Memory, Voice, Oth ## Other devices -Open or close FormAT to your network, the pairing code and link, and Forget paired devices. See [Other devices](other-devices.md). +Open or close FormAT to your network, the pairing code and link (each code lasts five minutes), the certificate fingerprint to compare on the other device, devices waiting to pair with Allow and Turn down, the list of paired devices with Unpair beside each, and Forget paired devices. See [Other devices](other-devices.md). ## Outside agents diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 55fcac2..8854e3d 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -14,7 +14,12 @@ Start with `./format doctor`: it checks Node, Python, the installs, your key and | Dictation says ElevenLabs transcription failed (401) | the ElevenLabs key is wrong or lacks speech to text; save a new one in Settings, API keys | | The Browser pane says the browser is not installed | run `./format install-browser`, then restart FormAT | | Claude's commands fail to install packages | the sandbox has no network by default; allow it in Settings, Tools, or turn the sandbox off | -| A phone cannot open the pairing link | both devices must be on the same network, and a firewall must allow port 8492 on the computer | +| A phone cannot open the pairing link | both devices must be on the same network, and a firewall must allow port 8492 on the computer; the link starts with https, and typing http instead gets no answer | +| The phone's browser warns about the certificate | expected the first time: FormAT uses its own certificate; check that the fingerprint in the certificate details matches the one in Settings, Other devices, then continue | +| The pairing page says the link was used or is out of date | each code pairs one device and lasts five minutes; scan the code Settings shows now | +| The phone stays on the waiting page | choose Allow beside its request in Settings, Other devices, on the computer; a request runs out after five minutes | +| The phone says FormAT's window turned it down | Turn down was chosen on the computer; scan the code Settings shows now and choose Allow | +| A device that used to be paired asks to pair again | it was unpaired, or it paired with a version of FormAT before per-device pairing; scan the code again | | A share link says "no longer shared" | sharing was stopped; Share again makes a new link | | A plugin will not add | the .zip needs `.claude-plugin/plugin.json` with a name (lowercase, hyphens) and a description | | A connector shows an error | open it in Customize and Reconnect; the message says what failed | diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 4f58c4c..c6908d5 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -1215,3 +1215,31 @@ The note under Settings, Outside agents listed "Claude Code, Codex, Cursor and o - logged: v0.32.0 · 2026-11-20 The engine now answers `GET /api/browser/frame` only to the window (see the engine log's entry for 0.32.0), so `loadFrame` sends `keyHeaders()` with it. The pane fetches frames only after the events socket has delivered a browser status, and that socket opens only with a ticket taken after `loadWindowKey` has settled, so the key is always there by then. Seen in Chromium with the built window and the real engine: the pane's own frame requests answered 200 image/jpeg; the same read from a local program without the key, 403. + +### src/ui/views.ts, src/app.ts, src/styles/ft-shell.css · Settings, Other devices lists paired devices and shows the certificate fingerprint +- refers-to: src/ui/views.ts :: the Other devices section, `paintDevices`, `paintPaired`; src/app.ts :: the `devices.changed` branch; src/styles/ft-shell.css `.ft-dev-fp`, `.ft-dev-list`, `.ft-dev-row`, `.ft-dev-unpair` +- kind: feature +- logged: unreleased + +The engine now pairs each device with its own token and serves other devices over https with a per-install certificate (backend HASHOUT, same entry name). The pairing box gains one line with the certificate's SHA-256 fingerprint, filled with `setText` while the box is shown, so the person can compare it with the warning on the other device. A Paired devices group lists each device keyed by id: rows that are gone are removed, new ones appended, and the name and times written through `setText`, so a repaint of the same list touches nothing; Unpair is one delegated click handler that calls devices.revoke. The list is empty (hidden by `:empty`) with the "No devices are paired" note toggled only when its state changes. `devices.changed` no longer carries the pairing link; the window answers it with devices.status, which also repaints the code after a scan spends it. + +### src/ui/views.ts, src/styles/ft-shell.css · Settings, Other devices asks before it pairs a device +- refers-to: src/ui/views.ts :: `PairRequest`, `codeTimer`, the `.ft-dev-asks` click handler, `paintDevices`, `paintAsks`; src/styles/ft-shell.css `.ft-dev-asks`, `.ft-dev-ask`, `.ft-dev-answer` +- kind: feature +- logged: unreleased + +The engine no longer pairs a device on the scan; it waits for the window (backend HASHOUT, "Pairing asks the window, codes run out, and pairing is window-only"). Under the pairing box, `.ft-dev-asks` lists each waiting device keyed by id, with its name, its check number and the certificate fingerprint, and Allow and Turn down, which call devices.answer through one delegated handler. A row is built once and only removed when the request is gone, so a repaint touches nothing; the list is hidden by `:empty`, and a row appears only when a device asks. A refused answer (the request ran out) shows the engine's sentence and repaints from devices.status. The code now lasts five minutes: `paintDevices` sets one timer from `pairExpiresIn` and asks for status again when it runs out, so the QR changes in place; the timer is cleared on every paint. + +### src/ui/confirm.ts, src/ui/customize-view.ts, src/engine-client/api.ts · a skill name in use asks Overwrite, Keep both or Cancel +- refers-to: src/ui/confirm.ts :: askSkillClash, withSkillClash; src/ui/customize-view.ts :: upload, create, the Discover click handler; src/engine-client/api.ts :: EngineError.data; src/ui/tool-cards.ts :: the save_skill ask text +- kind: feature +- logged: unreleased + +The engine refuses a taken skill name with 409 and `data.clash` (backend HASHOUT, "A skill name already in use is never replaced without asking"). `EngineError` now carries the reply's `data`. `withSkillClash` runs the call once with no extra parameters; on that 409 it opens one alert sheet built once and reused (the same scrim and sheet classes as the confirm sheet, so no new styles), with Overwrite, "Keep both as " and Cancel, and runs the call again with `overwrite: true` or `name: `; Cancel returns null and the caller leaves its form as it was. Upload a skill, Write a skill and Discover's Add use it. The save_skill approval card says "replace your ... skill" when Claude set overwrite. tsc --noEmit and the build pass; not driven in a throttled browser. + +### src/ui/views.ts · Settings, Tools, Sandbox shows Claude Code's sandbox and the addresses it may reach +- refers-to: src/ui/views.ts :: the Sandbox section, `.ft-cc-domains`, `.ft-cc-sandbox-note`, fillTools; src/state/app-state.ts :: Settings.claudeCodeDomains +- kind: feature +- logged: unreleased + +The Sandbox section gains one field, the host names Claude Code's commands may reach (comma separated, saved on change through settings.set claudeCodeDomains, the engine's sentence shown under it when it refuses one), and one note line filled from `sandbox.status` `claudeCode.note`, which says either that Claude Code runs sandboxed and what it reaches or, in plain words, that its commands are not sandboxed here. Both elements are in the markup from the start with placeholder text, and are written through `setText` and a value check that skips the focused field, so nothing moves when the answer arrives. diff --git a/frontend/src/app.ts b/frontend/src/app.ts index c769344..3a63388 100644 --- a/frontend/src/app.ts +++ b/frontend/src/app.ts @@ -540,6 +540,8 @@ export class App { } else if (e.type === 'terminal.opened') { const t = e.terminal as { id: string; title: string; kind?: string }; if (t.kind === 'agent') this.dock.adopt(t); + } else if (e.type === 'devices.changed') { + void this.settingsView.refreshDevices(); } else if (e.type === 'agents.consent') { this.consent(String(e.client ?? 'An agent'), String(e.channel ?? '')); } else if (e.type === 'settings.changed') { diff --git a/frontend/src/engine-client/api.ts b/frontend/src/engine-client/api.ts index 4e7da59..2e15b4b 100644 --- a/frontend/src/engine-client/api.ts +++ b/frontend/src/engine-client/api.ts @@ -5,12 +5,13 @@ export interface CommandReply { command: string; result?: T; error?: string; + data?: Record; } export const NOT_ANSWERING = "FormAT's engine is not answering. Try again in a moment."; export class EngineError extends Error { - constructor(message: string, readonly command: string, readonly status: number) { + constructor(message: string, readonly command: string, readonly status: number, readonly data?: Record) { super(message); } } @@ -36,6 +37,6 @@ export async function run(id: string, params: Record = {}): } catch { throw new EngineError(`engine answered ${res.status} without JSON`, id, res.status); } - if (!res.ok || !body.ok) throw new EngineError(body.error || `engine answered ${res.status}`, id, res.status); + if (!res.ok || !body.ok) throw new EngineError(body.error || `engine answered ${res.status}`, id, res.status, body.data); return body.result as T; } diff --git a/frontend/src/state/app-state.ts b/frontend/src/state/app-state.ts index 8f47a92..7c16204 100644 --- a/frontend/src/state/app-state.ts +++ b/frontend/src/state/app-state.ts @@ -136,6 +136,7 @@ export interface Settings { webTools?: boolean; workspaceTools?: boolean; toolAllow?: string[]; + claudeCodeDomains?: string[]; agentLimit?: number; agentModel?: string; artifactNetwork?: boolean; diff --git a/frontend/src/styles/ft-shell.css b/frontend/src/styles/ft-shell.css index 2c9748e..611cc7e 100644 --- a/frontend/src/styles/ft-shell.css +++ b/frontend/src/styles/ft-shell.css @@ -594,7 +594,16 @@ textarea.ft-input { resize: vertical; line-height: 1.5; overflow-y: auto; } .ft-dev-qr { flex: none; width: 205px; height: 205px; line-height: 0; } .ft-dev-qr svg { width: 100%; height: 100%; border-radius: var(--radius-md); } .ft-dev-text { display: grid; gap: var(--space-1); min-width: 0; font-size: var(--fs-12); color: var(--text-secondary); } -.ft-dev-url { font: var(--fs-12) var(--font-mono); color: var(--text-primary); overflow-wrap: anywhere; user-select: all; } +.ft-dev-url, .ft-dev-fp { font: var(--fs-12) var(--font-mono); color: var(--text-primary); overflow-wrap: anywhere; user-select: all; } +.ft-dev-list, .ft-dev-asks { display: grid; gap: var(--space-2); margin: 0; padding: 0; list-style: none; } +.ft-dev-list:empty, .ft-dev-asks:empty, .ft-dev-none[hidden] { display: none; } +.ft-dev-asks { margin-top: var(--space-3); } +.ft-dev-ask { grid-template-rows: auto auto auto; border-color: var(--accent-color); } +.ft-dev-answer { grid-column: 2; grid-row: 1 / span 3; display: flex; flex-wrap: wrap; gap: var(--space-2); } +.ft-dev-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; grid-template-rows: auto auto; column-gap: var(--space-3); align-items: center; padding: var(--space-2) var(--space-3); border: 1px solid var(--line-1); border-radius: var(--radius-lg); background: var(--surface-1); } +.ft-dev-name { min-width: 0; font-size: var(--fs-13); color: var(--text-primary); overflow-wrap: anywhere; } +.ft-dev-seen { grid-column: 1; font-size: var(--fs-12); color: var(--text-muted); } +.ft-dev-unpair { grid-column: 2; grid-row: 1 / span 2; } .ft-br-head { padding-left: var(--space-2); } .ft-br-url { flex: 1; min-width: 0; margin: 0 var(--space-1); } diff --git a/frontend/src/ui/confirm.ts b/frontend/src/ui/confirm.ts index d6563a4..5dbe3b5 100644 --- a/frontend/src/ui/confirm.ts +++ b/frontend/src/ui/confirm.ts @@ -1,4 +1,4 @@ -import { run } from '../engine-client/api'; +import { EngineError, run } from '../engine-client/api'; import { el, q, setText } from './dom'; let sheet: HTMLElement | null = null; @@ -37,6 +37,55 @@ export function confirmSheet(title: string, note: string, action: string): Promi return new Promise((resolve) => { settle = resolve; }); } +export type ClashChoice = 'overwrite' | 'keep' | 'cancel'; + +let clashSheet: HTMLElement | null = null; +let clashSettle: ((v: ClashChoice) => void) | null = null; + +function clashFinish(v: ClashChoice): void { + if (!clashSheet || clashSheet.hidden) return; + clashSheet.hidden = true; + const done = clashSettle; + clashSettle = null; + done?.(v); +} + +export function askSkillClash(name: string, suggested: string): Promise { + if (!clashSheet) { + const box = el(``); + box.addEventListener('click', (e) => { + const v = (e.target as HTMLElement).closest('[data-c]')?.dataset.c as ClashChoice | undefined; + if (v) clashFinish(v); + }); + box.addEventListener('pointerdown', (e) => { if (e.target === box) clashFinish('cancel'); }); + document.addEventListener('keydown', (e) => { if (e.key === 'Escape') clashFinish('cancel'); }); + (document.getElementById('overlay-root') as HTMLElement).appendChild(box); + clashSheet = box; + } + clashFinish('cancel'); + setText(q(clashSheet, '.ft-set-note'), `A skill named "${name}" is already installed. Overwrite replaces it with this one and cannot be undone; Keep both adds this one as "${suggested}".`); + setText(q(clashSheet, '[data-c="keep"]'), `Keep both as ${suggested}`); + clashSheet.hidden = false; + q(clashSheet, '[data-c="cancel"]').focus(); + return new Promise((resolve) => { clashSettle = resolve; }); +} + +export async function withSkillClash(call: (extra: Record) => Promise): Promise { + try { + return await call({}); + } catch (err) { + const clash = err instanceof EngineError && err.status === 409 ? (err.data?.clash as { name?: string; suggested?: string } | undefined) : undefined; + if (!clash?.name || !clash.suggested) throw err; + const choice = await askSkillClash(clash.name, clash.suggested); + if (choice === 'cancel') return null; + return call(choice === 'overwrite' ? { overwrite: true } : { name: clash.suggested }); + } +} + export function askDeleteProject(name: string): Promise { return confirmSheet('Delete this project?', `"${name}" is deleted with its instructions, its list of files and its memory. Its chats are kept and move out of the project. This cannot be undone.`, 'Delete'); } diff --git a/frontend/src/ui/customize-view.ts b/frontend/src/ui/customize-view.ts index c71565b..ab6e2db 100644 --- a/frontend/src/ui/customize-view.ts +++ b/frontend/src/ui/customize-view.ts @@ -1,6 +1,7 @@ import { run } from '../engine-client/api'; import { keyHeaders } from '../engine-client/window-key'; import type { AppState, ConnectorInfo, FileInfo, MarketplaceInfo, PluginSummary, SkillSummary } from '../state/app-state'; +import { withSkillClash } from './confirm'; import { el, esc, q, setAttr, setText } from './dom'; import { ui } from './icons-ft'; import { renderMarkdown } from './markdown'; @@ -190,7 +191,8 @@ export class CustomizeView { if (!row || !t.closest('.ft-sk-get')) return; const [marketplace, path] = (row.dataset.skoffer ?? '').split('\n'); try { - const s = await run('skill.installFrom', { marketplace, path }); + const s = await withSkillClash((extra) => run('skill.installFrom', { marketplace, path, ...extra })); + if (!s) return; setText(this.msg, `Added the ${s.name} skill.`); void this.refreshSkillOffers(); } catch (err) { setText(this.msg, err instanceof Error ? err.message : String(err)); } @@ -1034,8 +1036,9 @@ export class CustomizeView { const res = await fetch('/api/uploads', { method: 'POST', body: form, headers: keyHeaders() }); const body = await res.json(); if (!res.ok || !body.ok) throw new Error(body.error || `upload failed (${res.status})`); - const s = await run('skill.add', { uploadId: (body.file as FileInfo).id }); - this.say(`Added ${s.name}.`); + const uploadId = (body.file as FileInfo).id; + const s = await withSkillClash((extra) => run('skill.add', { uploadId, ...extra })); + this.say(s ? `Added ${s.name}.` : `Did not add ${f.name}.`); } catch (err) { this.say(err instanceof Error ? err.message : String(err)); } @@ -1044,7 +1047,8 @@ export class CustomizeView { private async create(): Promise { const get = (k: string) => (q(this.writeForm, `[data-f=${k}]`)).value.trim(); try { - const s = await run('skill.create', { name: get('name').toLowerCase(), description: get('description'), instructions: get('instructions') }); + const s = await withSkillClash((extra) => run('skill.create', { name: get('name').toLowerCase(), description: get('description'), instructions: get('instructions'), ...extra })); + if (!s) return; this.writeForm.hidden = true; this.writeForm.querySelectorAll('[data-f]').forEach((x) => { x.value = ''; }); this.say(`Saved ${s.name}.`); diff --git a/frontend/src/ui/tool-cards.ts b/frontend/src/ui/tool-cards.ts index dc5aecc..3316fac 100644 --- a/frontend/src/ui/tool-cards.ts +++ b/frontend/src/ui/tool-cards.ts @@ -398,7 +398,7 @@ export class ToolCard { } if (waiting) { const c = connectorParts(this.name); - setText(q(this.ask, '.ft-tool-ask-text'), this.name === 'bash' ? 'Allow Claude to run this command?' : this.name === 'add_plugin' ? `Allow Claude to add the ${base(this.input.folder)} plugin to FormAT?` : this.name === 'save_skill' ? `Allow Claude to save the ${base(this.input.folder)} skill to FormAT?` : c ? `Allow Claude to use ${c.tool} from the ${c.connector} connector?` : `Allow Claude to ${this.name} ${base(this.input.path)}?`); + setText(q(this.ask, '.ft-tool-ask-text'), this.name === 'bash' ? 'Allow Claude to run this command?' : this.name === 'add_plugin' ? `Allow Claude to add the ${base(this.input.folder)} plugin to FormAT?` : this.name === 'save_skill' ? (this.input.overwrite === true ? `Allow Claude to replace your ${base(this.input.folder)} skill in FormAT with this one?` : `Allow Claude to save the ${base(this.input.folder)} skill to FormAT?`) : c ? `Allow Claude to use ${c.tool} from the ${c.connector} connector?` : `Allow Claude to ${this.name} ${base(this.input.path)}?`); const always = q(this.ask, '[data-d="always"]'); const word = ALWAYS_WORD[this.name] ?? (c ? c.tool : ''); setText(always, word ? `Always allow ${word}` : 'Always allow'); diff --git a/frontend/src/ui/views.ts b/frontend/src/ui/views.ts index 95eea85..567e33b 100644 --- a/frontend/src/ui/views.ts +++ b/frontend/src/ui/views.ts @@ -94,7 +94,9 @@ function sourceText(k: KeyStatus | undefined): string { return `Set ${k.hint ?? ''} · ${where}`; } -interface DevicesStatus { on: boolean; port: number; urls: string[]; pairUrl: string | null; qr: string | null } +interface PairedDevice { id: string; name: string; created: number; seen: number } +interface PairRequest { id: string; name: string; check: string; created: number } +interface DevicesStatus { on: boolean; port: number; urls: string[]; pairUrl: string | null; qr: string | null; pairExpiresIn?: number | null; fingerprint?: string | null; devices?: PairedDevice[]; pending?: PairRequest[] } export type SettingsSection = 'Account' | 'API keys' | 'Tools' | 'Long chats' | 'Memory' | 'Voice' | 'Other devices' | 'Outside agents' | 'About'; @@ -102,6 +104,7 @@ const SECTION_ORDER: SettingsSection[] = ['Account', 'API keys', 'Tools', 'Long export class SettingsView { private root: HTMLElement; + private codeTimer = 0; constructor(private state: AppState, prefs: PrefsWindow, memory: HTMLElement) { this.root = prefs.pages; @@ -141,6 +144,8 @@ export class SettingsView { checking the sandbox + + checking Claude Code's sandbox

Always allowed

@@ -154,11 +159,17 @@ export class SettingsView {
`); prefs.add('Other devices', 'devices', ` -

Continue on your phone or another computer on the same network: turn this on, then scan the code or open the link there. Paired devices see the same chats live; shared artifact links open for anyone who can reach this computer, read-only. Turn it off to keep FormAT on this computer only.

+

Continue on your phone or another computer on the same network: turn this on, then scan the code or open the link there. The connection is encrypted with this computer's own certificate, so the other browser warns once; check its fingerprint against the one shown here. Each code pairs one device and lasts five minutes, and FormAT asks here before it pairs a device that used it. Paired devices see the same chats live; shared artifact links open for anyone who can reach this computer, read-only. Turn it off to keep FormAT on this computer only.

Pairing

- + +
    +
    +
    +

    Paired devices

    +
      + No devices are paired.
      `); prefs.add('Outside agents', 'plug', `

      While FormAT runs it is an MCP server at http://127.0.0.1:8490/mcp, and ./format mcp serves the same over stdio, so Claude Code, Codex, Cursor, Antigravity and other agents on this computer can chat, publish artifacts and run any FormAT command. Ask shows a prompt here the first time an agent calls.

      @@ -233,6 +244,13 @@ export class SettingsView { this.root.querySelectorAll('[data-t]').forEach((box) => { box.addEventListener('change', () => void run('settings.set', { key: box.dataset.t, value: box.checked }).catch(() => undefined)); }); + const hosts = q(this.root, '.ft-cc-domains'); + hosts.addEventListener('change', () => { + const value = hosts.value.split(/[\s,]+/).filter(Boolean); + void run('settings.set', { key: 'claudeCodeDomains', value }) + .then(() => setText(q(this.root, '.ft-cc-domains-msg'), 'Saved; it applies from the next Claude Code reply.')) + .catch((err) => setText(q(this.root, '.ft-cc-domains-msg'), err instanceof Error ? err.message : String(err))); + }); q(this.root, '.ft-allowed-list').addEventListener('click', (e) => { const name = (e.target as HTMLElement).closest('[data-tool]')?.dataset.tool; if (!name) return; @@ -244,6 +262,19 @@ export class SettingsView { mod.addEventListener('change', () => void run('settings.set', { key: 'agentModel', value: mod.value }).catch(() => undefined)); q(this.root, '.ft-dev-toggle').addEventListener('click', () => void this.toggleDevices()); q(this.root, '.ft-dev-forget').addEventListener('click', () => void run('devices.forget').then((d) => this.paintDevices(d, 'Paired devices were forgotten; pair again with the new code.')).catch(() => undefined)); + q(this.root, '.ft-dev-list').addEventListener('click', (e) => { + const id = (e.target as HTMLElement).closest('[data-unpair]')?.dataset.unpair; + if (!id) return; + void run('devices.revoke', { id }).then((d) => this.paintDevices(d, 'That device was unpaired.')).catch((err) => setText(q(this.root, '.ft-dev-msg'), err instanceof Error ? err.message : String(err))); + }); + q(this.root, '.ft-dev-asks').addEventListener('click', (e) => { + const btn = (e.target as HTMLElement).closest('[data-answer]'); + if (!btn) return; + const allow = btn.dataset.allow === '1'; + void run('devices.answer', { id: btn.dataset.answer, allow }) + .then((d) => this.paintDevices(d, allow ? 'Allowed; the device finishes pairing by itself.' : 'That device was turned down.')) + .catch((err) => { setText(q(this.root, '.ft-dev-msg'), err instanceof Error ? err.message : String(err)); void this.refreshDevices(); }); + }); void this.refreshDevices(); const outside = q(this.root, '[data-g="outsideAgents"]'); outside.addEventListener('change', () => void run('settings.set', { key: 'outsideAgents', value: outside.value }).catch(() => undefined)); @@ -279,9 +310,46 @@ export class SettingsView { if (qr.dataset.v !== d.pairUrl) { qr.dataset.v = d.pairUrl ?? ''; qr.innerHTML = d.qr ?? ''; } setText(q(this.root, '.ft-dev-url'), d.pairUrl ?? ''); setText(q(this.root, '.ft-dev-also'), d.urls.length > 1 ? `Also reachable at ${d.urls.slice(1).join(', ')}` : `Listening on port ${d.port}`); + setText(q(this.root, '.ft-dev-fp'), d.fingerprint ?? ''); } if (pair.hidden === show) pair.hidden = !show; + this.paintAsks(d.on ? d.pending ?? [] : [], d.fingerprint ?? ''); + this.paintPaired(d.devices ?? []); setText(q(this.root, '.ft-dev-msg'), msg); + window.clearTimeout(this.codeTimer); + if (show && typeof d.pairExpiresIn === 'number') this.codeTimer = window.setTimeout(() => void this.refreshDevices(), (d.pairExpiresIn + 1) * 1000); + } + + private paintAsks(asks: PairRequest[], fingerprint: string): void { + const list = q(this.root, '.ft-dev-asks'); + const keep = new Set(asks.map((a) => a.id)); + list.querySelectorAll('[data-id]').forEach((row) => { if (!keep.has(row.dataset.id ?? '')) row.remove(); }); + asks.forEach((a) => { + if (list.querySelector(`[data-id="${CSS.escape(a.id)}"]`)) return; + const row = el(`
    • Its browser should show this certificate fingerprint:
    • `); + setText(q(row, '.ft-dev-name'), `${a.name} wants to pair`); + setText(q(row, '.ft-dev-seen'), `check number ${a.check.slice(0, 3)} ${a.check.slice(3)}, the same as on the device's page`); + setText(q(row, '.ft-dev-fp'), fingerprint); + list.append(row); + }); + } + + private paintPaired(devices: PairedDevice[]): void { + const list = q(this.root, '.ft-dev-list'); + const keep = new Set(devices.map((d) => d.id)); + list.querySelectorAll('[data-id]').forEach((row) => { if (!keep.has(row.dataset.id ?? '')) row.remove(); }); + devices.forEach((d) => { + let row = list.querySelector(`[data-id="${CSS.escape(d.id)}"]`); + if (!row) { + row = el(`
    • `); + list.append(row); + } + setText(q(row, '.ft-dev-name'), d.name); + setText(q(row, '.ft-dev-seen'), `paired ${when(d.created)}, last seen ${when(d.seen)}`); + }); + const none = q(this.root, '.ft-dev-none'); + if (none.hidden === !!devices.length) return; + none.hidden = !!devices.length; } fillOutside(): void { @@ -322,8 +390,12 @@ export class SettingsView { const on = box.dataset.off ? v === true : v !== false; if (box.checked !== on) box.checked = on; }); - void run<{ note: string; available: boolean }>('sandbox.status').then((sb) => { + const hosts = q(this.root, '.ft-cc-domains'); + const hostText = (s.claudeCodeDomains ?? []).join(', '); + if (document.activeElement !== hosts && hosts.value !== hostText) hosts.value = hostText; + void run<{ note: string; available: boolean; claudeCode?: { note: string } }>('sandbox.status').then((sb) => { setText(q(this.root, '.ft-sandbox-note'), sb.note); + if (sb.claudeCode) setText(q(this.root, '.ft-cc-sandbox-note'), sb.claudeCode.note); const box = q(this.root, '[data-t="sandbox"]'); if (box.disabled === sb.available) box.disabled = !sb.available; }).catch(() => undefined);