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/ {}FormAT
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"
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/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 asContinue 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.
Certificate fingerprint (SHA-256), to compare with the one the other device's browser shows: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.