first pass of merging in warp (doesn't build)

This commit is contained in:
Ryan Ward
2026-07-01 16:08:58 -05:00
parent 2f64909469
commit 4770ac06b5
3662 changed files with 414574 additions and 89772 deletions
+234
View File
@@ -0,0 +1,234 @@
# Summary
Warp ships a local control CLI, provisionally named `warpctrl`, that lets agents, developers, and scripts operate running Warp app processes through a typed, allowlisted command surface. `warpctrl` is an Oz-style wrapper script that invokes the existing channel-specific Warp binary in control mode rather than a separate standalone binary.
The public catalog contains exactly **84 default-authorized actions** organized around stable user-facing nouns. Close actions flow through Warp's normal close behavior so existing app warnings remain authoritative. `block.list` is intentionally absent from the catalog. Input-staging commands place text in the input buffer but never submit it.
All callers are external same-user processes. There is no inside-Warp/outside-Warp distinction, no verified-terminal invocation context, and no authenticated-user identity layer. Security relies on owner-only filesystem discovery, same-user Unix credential broker with kernel peer credentials, short-lived instance-bound exact-action credentials, loopback HTTP transport, and app-side enforcement.
## Problem
Warp has rich interactive actions reachable through UI, keybindings, menus, and deeplinks. Agents can use native tools for files, code, shell commands, and MCP calls, but they cannot reliably operate Warp's own product surfaces: arranging workspaces, focusing panes, opening Warp Drive views, presenting settings, or recovering from ambiguous UI state. Developers cannot compose those actions into shell scripts, demos, or automation workflows, and there is no general local protocol for addressing a specific running Warp instance, window, tab, pane, or session.
## Goals
- Provide a first-class, scriptable `warpctrl` command for controlling running Warp app processes.
- Make Warp's UI and app state available to agents through a typed, permissioned control plane instead of brittle screen automation.
- Keep CLI startup lightweight by avoiding GUI-app startup for routine control commands.
- Keep the surface allowlisted and finite: exactly 84 named actions, no arbitrary internal dispatch.
- Make targeting explicit and deterministic across multiple Warp processes, windows, tabs, panes, and sessions.
- Use a simple enabled/disabled Scripting setting rather than multi-mode invocation-context policies.
## Non-goals
- Replacing the Oz CLI or mixing cloud-agent management into this CLI.
- Exposing every internal app action, debug action, or privileged state mutation.
- Treating the CLI as a general RPC escape hatch into Warp internals.
- Replacing native agent tools for code editing, file operations, shell execution, or MCP calls.
- Providing an authenticated-user identity layer, verified-terminal invocation proof, or invocation-context distinction.
- Terminal command execution, accepted-command submission, or agent-prompt submission.
- Warp Drive data mutations, cloud-backed state mutations, or sharing operations.
- Local file content reads, writes, or filesystem-content mutations.
## Primary user stories
1. **Agent workspace orchestration.** An agent inspects current Warp state, creates or reuses an appropriate window/tab layout, splits panes, names and focuses targets, and leaves the workspace in a readable task-shaped state. The agent continues to use native tools for code edits, file I/O, shell execution, and MCP calls.
2. **Existing-session debugging and repair.** An agent understands Warp-specific UI and session structure before acting: which instance/window/tab/pane/session is active, whether the relevant pane still exists, which surface is focused, and which selector to use for follow-up actions.
3. **Deterministic demos and walkthroughs.** A script puts Warp into a known presentation state: theme, zoom, windows, tabs, panes, focused targets, panels, and surfaces. The walkthrough advances using structured target IDs and recovers from stale or missing targets.
4. **Personalization and preference migration.** An agent inspects settings, proposes Warp equivalents from other tools, applies allowlisted changes, and reports unsupported mappings explicitly.
## Behavior
1. The CLI operates only on running local Warp app processes from the same channel as the channel-specific CLI binary. If no compatible same-channel process is available, it exits non-zero with a structured error.
2. The CLI exposes only the 84 explicitly allowlisted actions. Unknown, unsupported, or non-allowlisted requests fail with structured errors and are never forwarded to arbitrary internal dispatch.
3. Every successful mutating request identifies the Warp process instance, resolved target, and a success payload suitable for JSON output.
4. Every failure identifies a stable machine-readable error code, a human-readable explanation, and any selector that was ambiguous, missing, stale, or invalid.
5. The CLI supports human-readable output by default and JSON output for scripts with stable field names.
6. Process discovery and instance selection:
- `warpctrl instance list` returns all reachable local Warp app processes from the CLI binary's channel.
- Each process has an opaque `instance_id`, channel/build identity, and display metadata.
- If exactly one compatible process is available, commands target it implicitly.
- If multiple compatible processes are available and no single clearly active instance exists, the CLI fails and asks for an explicit `--instance` selector.
- Explicit `--instance` and `--pid` selectors cannot target a process from another channel.
7. Target introspection:
- `warpctrl window list`, `warpctrl tab list`, `warpctrl pane list`, `warpctrl session list`, `warpctrl app active`.
- These return opaque protocol-facing IDs and metadata for subsequent commands.
8. The target selector model is hierarchical: instance → window → tab → pane → session. Non-hierarchical selectors (files, surfaces) resolve inside the selected instance.
9. Every selector family supports an ergonomic `active` form. For window-scoped mutations, an omitted window selector may fall back to the sole existing window. Zero windows returns `missing_target`; multiple windows without an active one returns `ambiguous_target`.
10. Every selector family supports explicit opaque IDs and may support scoped indices or titles for interactive use. IDs remain the preferred automation surface.
11. When a command omits lower-level selectors, it resolves them from the higher-level context using active defaults.
12. When an explicitly supplied target disappears between discovery and execution, the request fails with `stale_target`. The CLI never silently chooses a different target.
13. The protocol is command-oriented: each action has a named command, validated parameters, and defined target scope.
## Bundled agent skill
When Warp Control and bundled skills are enabled, Warp exposes a built-in `warpctrl` skill to the Warp agent. The skill tells the agent when to use Warp Control for actions that affect Warp itself, teaches a discovery-first targeting workflow, and documents the same manual commands available to users.
The skill is unavailable when the `WarpControlCli` feature flag is disabled. Disabled skills are omitted from agent skill discovery and cannot be read through a stale direct skill reference.
## Scripting setting
Warp adds a new top-level Settings pane page named **Scripting**. The page contains a single toggle for local control:
- **Enabled** (default on internal dogfood channels): same-user processes may request exact-action credentials from the broker and send control requests to the loopback listener.
- **Disabled** (default on Stable, Preview, OSS, and Integration channels): no same-user process can receive local-control credentials. The control listener does not accept requests. Discovery records contain no actionable endpoint.
The authoritative value is stored in protected local storage (macOS Keychain, or owner-only secure storage on Linux). It is never synced, never appears in `settings.toml` or generated schemas, and cannot be changed by `warpctrl`, config files, or direct protocol requests. Only the Warp app through Settings > Scripting can change it. The default is channel-based: enabled on internal dogfood builds, disabled on public channels until the user opts in. Disabling Scripting immediately prevents new credential issuance and invalidates outstanding credentials.
## Close behavior
`window.close`, `tab.close`, and `pane.close` execute after the same exact-action credential validation as the other 81 actions. They flow through Warp's normal close behavior, so existing warnings for unsaved files, running processes, shared sessions, and similar app state remain authoritative and may cancel the close.
## Input staging
The two input commands (`input.insert`, `input.replace`) only stage or edit text in the terminal input buffer. They never submit the buffer, press Enter, or execute a command. There is no `input.run`, `input.get`, `input.clear`, or `input.mode.set` action in the catalog. Terminal command execution is not part of this product surface.
## Action catalog
The public catalog contains exactly 84 actions. The Block, Auth, Drive, and History families are entirely absent. Input is limited to `input.insert` and `input.replace`. Actions are organized by noun and use the exact dotted names from the authoritative `ActionKind` catalog.
### Instance (2 actions)
All default-authorized.
- `instance.list` — list reachable Warp app processes from the CLI binary's channel.
- `instance.inspect` — metadata for one instance.
### App (4 actions)
All default-authorized.
- `app.ping` — health check for the selected instance.
- `app.version` — build/channel/version metadata.
- `app.active` — the active instance/window/tab/pane/session chain.
- `app.focus` — bring the selected Warp app to the foreground.
### Capability (2 actions)
All default-authorized.
- `capability.list` — list capabilities supported by the selected instance.
- `capability.inspect` — metadata for one capability.
### Window (5 actions)
All default-authorized.
- `window.list` — list windows in the selected instance.
- `window.inspect` — metadata for one window.
- `window.create` — create a new window.
- `window.focus` — focus a target window.
- `window.close` — close a target window. Uses normal Warp close behavior.
### Tab (10 actions)
All default-authorized.
- `tab.list` — list tabs in the selected window.
- `tab.inspect` — metadata for one tab.
- `tab.create` — create a new terminal tab.
- `tab.activate` — activate a target tab.
- `tab.move` — move a tab left or right.
- `tab.close` — close a target tab. Uses normal Warp close behavior.
- `tab.rename` — rename a tab.
- `tab.reset_name` — reset a tab title to the default.
- `tab.color.set` — set the active-tab color.
- `tab.color.clear` — clear the active-tab color.
### Pane (11 actions)
All default-authorized.
- `pane.list` — list panes in the selected tab.
- `pane.inspect` — metadata for one pane.
- `pane.split` — split a pane in a direction (left, right, up, down).
- `pane.focus` — focus a target pane.
- `pane.navigate` — navigate focus between panes (left, right, up, down).
- `pane.resize` — resize pane dividers in a direction.
- `pane.maximize` — toggle maximize for a pane.
- `pane.unmaximize` — restore a maximized pane.
- `pane.close` — close a target pane. Uses normal Warp close behavior.
- `pane.rename` — rename a pane.
- `pane.reset_name` — reset a pane title to the default.
### Session (6 actions)
All default-authorized.
- `session.list` — list sessions in the selected pane.
- `session.inspect` — metadata for one session.
- `session.activate` — activate a target session.
- `session.previous` — cycle to the previous session.
- `session.next` — cycle to the next session.
- `session.reopen_closed` — reopen the last closed session.
### Input (2 actions)
All default-authorized. **Input commands stage text only and never submit.**
- `input.insert` — insert text into the input buffer without executing.
- `input.replace` — replace the input buffer contents without executing.
### Theme (6 actions)
All default-authorized.
- `theme.list` — list available themes.
- `theme.get` — get the current theme.
- `theme.set` — set the current fixed theme.
- `theme.system.set` — toggle or set "follow system theme."
- `theme.light.set` — set the light-mode theme.
- `theme.dark.set` — set the dark-mode theme.
### Appearance (7 actions)
All default-authorized.
- `appearance.get` — get current appearance state (font size, zoom).
- `appearance.font_size.increase` — increase font size.
- `appearance.font_size.decrease` — decrease font size.
- `appearance.font_size.reset` — reset font size to default.
- `appearance.zoom.increase` — increase UI zoom.
- `appearance.zoom.decrease` — decrease UI zoom.
- `appearance.zoom.reset` — reset UI zoom to default.
### Setting (4 actions)
All default-authorized.
- `setting.list` — list allowlisted user-facing settings.
- `setting.get` — read an allowlisted setting value.
- `setting.set` — set an allowlisted setting to a validated value.
- `setting.toggle` — toggle an allowlisted boolean setting.
Private, debug-only, derived, and non-allowlisted settings are rejected with structured errors.
### Keybinding (2 actions)
All default-authorized.
- `keybinding.list` — list keybindings.
- `keybinding.get` — get a specific keybinding.
### Action (2 actions)
All default-authorized.
- `action.list` — list all 84 catalog actions with implementation status.
- `action.inspect` — metadata for one action.
### Surface (20 actions)
All default-authorized.
- `surface.list` — list available and unavailable tour destinations with stable names and reasons.
- `surface.settings.open` — open the settings surface, optionally to a specific page or search query.
- `surface.command_palette.open` — open or toggle the command palette with an optional initial query.
- `surface.command_search.open` — open or toggle command search.
- `surface.theme_picker.open` — idempotently open the theme picker.
- `surface.keybindings.open` — idempotently open keybinding settings.
- `surface.warp_drive.open` — open the Warp Drive panel.
- `surface.warp_drive.toggle` — toggle the Warp Drive panel.
- `surface.resource_center.toggle` — toggle the resource center.
- `surface.ai_assistant.toggle` — toggle the AI assistant panel.
- `surface.code_review.open` — idempotently open code review when the target terminal has an active repository.
- `surface.code_review.toggle` — toggle the code review panel.
- `surface.project_explorer.open` — idempotently open the project explorer.
- `surface.global_search.open` — idempotently open global file search.
- `surface.conversation_list.open` — idempotently open the conversation list.
- `surface.left_panel.toggle` — toggle the left panel.
- `surface.right_panel.toggle` — toggle the right panel.
- `surface.vertical_tabs.open` — idempotently open vertical tabs.
- `surface.vertical_tabs.toggle` — toggle vertical tabs.
- `surface.agent_management.open` — idempotently open agent management.
### File (1 action)
Default-authorized.
- `file.open` — open a file path in a Warp editor tab, optionally at a specific line and column. This is an app-state intent, not a filesystem-content operation.
### Excluded from the catalog
The following families and actions are entirely absent even when internal implementations exist:
- The entire Block family (`block.list`, `block.inspect`, `block.output`).
- The entire Auth family (`auth.status`, `auth.login`).
- The entire Drive family (all `drive.*` actions).
- The entire History family (`history.list`).
- `input.get`, `input.clear`, `input.mode.set`, `input.run`, and any form of terminal command execution or submission.
- `file.list` and any local file content reads, writes, or filesystem-content mutations.
- Accepted-command submission and agent-prompt submission.
- Crash, panic, heap-dump, token-copying, debug-reset, and developer/debug helpers.
- Arbitrary internal view dispatch by string.
- Arbitrary settings outside the allowlist.
## CLI command surface
Command names are noun-oriented and discoverable. Examples:
- `warpctrl instance list`
- `warpctrl app ping`
- `warpctrl app active`
- `warpctrl tab create`
- `warpctrl tab rename --tab <id> "Build logs"`
- `warpctrl window close --window <id>`
- `warpctrl pane split --direction right`
- `warpctrl input replace "cargo check"`
- `warpctrl theme set "Warp Dark"`
- `warpctrl setting set appearance.themes.system_theme true`
- `warpctrl file open src/main.rs --line 42`
### Targeting flags
- `--instance <instance_id>` and `--pid <pid>` select a running Warp process (mutually exclusive).
- `--window <active|opaque-id>`, `--window-index <n>`, and `--window-title <title>` select a window.
- `--tab <active|opaque-id>`, `--tab-index <n>`, and `--tab-title <title>` select a tab.
- `--pane <active|opaque-id>` and `--pane-index <n>` select a pane.
- `--session <active|opaque-id>` selects a session.
- `--output-format <pretty|json|ndjson|text>` controls output shape.
Within a selector family, specifying more than one form is invalid. Handlers reject selector forms that they cannot resolve safely.
### Wire protocol
A request contains an action name from the catalog, a structured target selector, and validated parameters. A response contains success/failure status, resolved instance and target metadata, and result data or structured error data. The protocol is versioned.
## Error model
Every protocol or runtime failure identifies a stable machine-readable error code:
- `local_control_disabled` — Scripting is disabled.
- `unauthorized_local_client` — missing, malformed, expired, or invalid credential.
- `insufficient_permissions` — credential grants a different action.
- `ambiguous_instance` — multiple instances, no unambiguous selection.
- `ambiguous_target` — multiple matching targets.
- `stale_target` — explicit target ID no longer exists.
- `missing_target` — no active or default target exists.
- `invalid_selector` — malformed selector syntax.
- `invalid_request` — malformed request body.
- `invalid_params` — invalid action-specific parameters.
- `unsupported_action` — action not implemented by this build.
- `not_allowlisted` — action intentionally excluded from public surface.
- `target_state_conflict` — target cannot support the requested action.
- `no_instance` — no reachable Warp instance found.
- `protocol_version_unsupported` — client and app protocol versions do not match.
- `transport_unavailable` — the local transport (broker socket or loopback HTTP) failed.
- `bridge_unavailable` — the app-side bridge cannot service requests.
- `internal` — unexpected internal failure.
## Unsupported platforms
On platforms where the owner-only filesystem discovery, Unix credential broker, or equivalent authenticated broker transport are not available, `warpctrl` fails closed. It does not fall back to unauthenticated control or weaker credential models. Windows local-control publication remains disabled until discovery-record ACL enforcement and an equivalent authenticated broker transport are implemented.
+112
View File
@@ -0,0 +1,112 @@
# warpctrl operator README
`warpctrl` is the provisional CLI entrypoint for controlling an already-running local Warp app instance. It is intended for scripts, demos, agent workflows, and developer automation that need to perform allowlisted Warp UI actions through the installed channel-specific Warp binary without launching the GUI.
The implemented command surface contains exactly 84 typed, allowlisted actions. All 84 actions execute after exact-action credential validation. Close actions flow through normal Warp close behavior, so existing app warnings remain authoritative. The Block, Auth, Drive, and History families are absent, and `input.insert` plus `input.replace` stage text without submitting it.
## Packaging model
`warpctrl` should be packaged as an Oz-style wrapper script rather than a standalone Rust binary. The wrapper should resolve the installed channel-specific Warp executable and invoke it with the hidden `--warpctrl` control-mode flag:
- `crates/local_control` owns discovery records, local authentication material, client transport, protocol envelopes, action names, and error types.
- `crates/warp_cli` owns command parsing conventions for local-control subcommands.
- the channel-specific app binary owns the hidden `--warpctrl` dispatch path and exits before normal GUI startup.
- the app-side bridge owns the per-process loopback listener and dispatches supported actions onto the live Warp UI context.
The control-mode path should initialize only the work needed for CLI parsing, instance discovery, local authentication loading, request serialization, HTTP transport, and output formatting. It should not initialize GUI state, terminal models, rendering, workspaces, or main-app startup paths.
During the provisional naming period, release artifacts and helper names may be channelized, but operator docs and examples should use `warpctrl` unless an integration branch explicitly documents a channel-specific alias.
This branch wires the core hidden dispatch contract through the existing Warp binary. Platform packaging should create wrapper scripts that call the channel binary with `--warpctrl` instead of producing or selecting a separate `warpctrl` binary.
## Install and invocation guidance
### macOS
For local development checks, build the local Warp binary and invoke it with the hidden control-mode flag:
```bash
cargo run -p warp --bin warp -- --warpctrl instance list
```
For distributable checks, use the installed `warpctrl` wrapper. The wrapper execs the app bundle's channel-specific executable with `--warpctrl`.
### Linux
For local development checks, build the local Warp binary and invoke it with the hidden control-mode flag:
```bash
cargo run -p warp --bin warp -- --warpctrl instance list
```
For distributable checks, use the packaged `warpctrl` wrapper. The wrapper execs the packaged channel-specific Warp executable with `--warpctrl`.
The standalone `script/linux/bundle --artifact warpctrl` validation artifact includes that wrapper and compiles the forwarded channel binary with `warp_control_cli`. Installing the wrapper into the normal Linux app package remains a separate packaging follow-up.
Run `warpctrl --version` after installation to confirm the shell is resolving the expected build.
### Windows
Until the wrapper installer lands, build the local Warp binary and invoke it with the hidden control-mode flag for development checks:
```powershell
cargo run -p warp --bin warp -- --warpctrl instance list
```
Installer helper creation and release-artifact wiring still need a later packaging change before docs can promise an installer-provided `warpctrl` command.
## End-to-end local test flow
Use matching app and CLI bits from the same branch or release artifact so the protocol version and action catalog agree.
1. Start Warp and leave at least one window open.
2. Open **Settings > Scripting**. Local control is enabled by default on internal dogfood builds and disabled by default on public channels (Stable, Preview, OSS). Verify that the Scripting toggle is set to **Enabled**, and enable it if needed. Enabling scripting allows for programmatic and agentic control of Warp; refer to the docs for more info.
3. Confirm that the local-control server registered the running same-channel process:
```bash
warpctrl instance list
```
4. Confirm app health and inspect protocol and build identity metadata:
```bash
warpctrl app ping
warpctrl app version
warpctrl surface list
```
5. If exactly one compatible same-channel instance is listed, create a new terminal tab:
```bash
warpctrl tab create
```
6. If multiple compatible same-channel instances are listed, copy the desired `instance_id` and target it explicitly:
```bash
warpctrl app ping --instance <instance_id>
warpctrl app version --instance <instance_id>
warpctrl tab create --instance <instance_id>
```
7. Verify the running app receives focus for the selected instance and a new terminal tab appears according to Warp's normal new-tab placement behavior. The success response includes the created tab's opaque ID.
8. Inspect state before and after the mutation:
```bash
warpctrl tab list --instance <instance_id>
```
Expected failures:
- `warpctrl instance list` with no running compatible app: exits zero with an empty list;
- a command that needs a selected app when no compatible app is running: exits non-zero with a no-instance error;
- multiple ambiguous instances: exits non-zero and asks for `--instance`;
- an explicit instance or PID from another channel: exits non-zero with a no-instance error;
- unsupported app build or stale discovery record: exits non-zero with a protocol, stale-target, or transport error;
## Security model
The local-control protocol is designed for same-user scripting, not cross-user or network access. The trust boundary is the local user account.
- **Loopback-only listener.** Each Warp process binds its control server to `127.0.0.1` on an ephemeral port. The listener is not reachable from the network.
- **Brokered scoped credentials.** Discovery records contain instance metadata, loopback control-endpoint information, and an instance-bound Unix-domain-socket broker reference when Scripting is enabled. The broker authenticates the connecting OS user with kernel peer credentials before decoding the credential request or issuing an action-scoped credential. Records do not contain bearer tokens or reusable full-access credentials.
- **Short-lived grants.** `warpctrl` requests an action-scoped credential over the owner-authenticated broker socket for the selected instance, then presents that credential to `/v1/control`. Grants are instance-bound, expired entries are pruned, and the in-memory grant set is capped. Missing, invalid, expired, revoked, or wrong-instance credentials are rejected before request decoding. After decoding identifies the requested action, insufficient-scope credentials are rejected before selector resolution or handler dispatch.
- **Protected local state.** The authoritative Scripting setting uses platform secure storage, never imports a value from ordinary or private preferences, and defaults to enabled only on internal dogfood channels (disabled by default on public channels). On POSIX platforms, discovery records and broker sockets use owner-only permissions. On Windows, local-control publication remains disabled until equivalent ACL and broker protections are implemented.
- **Channel-scoped discovery.** Each channel-specific CLI considers only records from its own Warp channel. Listing, implicit selection, and explicit instance or PID selection cannot target another channel.
- **Stale-record pruning.** On each `instance list` or implicit discovery call, same-channel records whose PID is no longer alive are deleted automatically. Candidates are also health-probed and accepted only when the live app reports the expected instance identity.
- **No CORS.** The control endpoints do not set permissive CORS headers, so browser-origin JavaScript cannot read responses even if it guesses the port. The credential requirement provides a second layer since browsers cannot read the brokered credential material.
```mermaid
sequenceDiagram
participant CLI as warpctrl
participant FS as ~/.warp/local-control/
participant Broker as Credential broker
participant HTTP as Warp loopback server<br/>(127.0.0.1:ephemeral)
participant Bridge as App bridge
CLI->>FS: Read discovery records (user-only permissions / ACL)
FS-->>CLI: instance_id, loopback endpoint, broker socket reference
CLI->>CLI: Prune stale PIDs, select instance
CLI->>Broker: Connect to Unix socket<br/>exact action + selected instance
Broker->>Broker: Authenticate peer OS user before decode;<br/>check Scripting enabled + catalog action
alt Disabled, invalid, or insufficient scope
Broker-->>CLI: Structured denial
else Grant allowed
Broker-->>CLI: Short-lived scoped credential
CLI->>HTTP: POST /v1/control<br/>Authorization: Bearer <scoped credential>
HTTP->>HTTP: Verify credential expiry + instance binding before decode
HTTP->>HTTP: Decode typed request; verify action scope
HTTP->>Bridge: Dispatch action to app context
Bridge-->>HTTP: Structured result or error
HTTP-->>CLI: JSON response envelope
end
```
**Known limitations and future hardening:**
- Windows local-control publication is disabled until discovery-record ACL creation and validation are implemented.
- Unexpired exact-action credentials may be reused for their granted action. Close actions flow through normal Warp close behavior and may trigger existing app warnings.
- Same-user malicious software can still invoke trusted wrappers or automate the desktop, so brokered credentials are least-privilege guardrails rather than a complete hostile same-user sandbox.
- Future catalog expansion should consider per-request nonces, stricter platform secure-storage constraints, and stronger approval or policy gates.
## Documentation review notes
- Treat `warpctrl` as provisional executable naming until packaging signs off on final artifact aliases.
- Keep examples scoped to the authoritative 84-action catalog and explicitly call out that close actions use normal Warp close behavior.
- Do not document excluded families or actions as usable just because internal app implementations exist.
- Windows packaging may initially follow the existing helper-wrapper pattern. Update this README when that decision is final.
+225
View File
@@ -0,0 +1,225 @@
# warpctrl security architecture
`warpctrl` is a local-control CLI for an already-running Warp app instance. The design is external-only: all callers are same-user processes. There is no inside-Warp/outside-Warp distinction, no verified-terminal invocation context, and no authenticated-user identity layer.
The security architecture has five layers:
1. **Protected enablement:** A single Scripting setting stored in protected local storage. It defaults to enabled on internal dogfood channels (Dev, Local) and to disabled on all other channels (Stable, Preview, OSS, Integration), where the user must opt in through Settings > Scripting.
2. **Owner-only discovery:** Per-user filesystem discovery with owner-only permissions finds compatible instances without granting control authority.
3. **Same-user credential broker:** A Unix-domain socket authenticates the OS user through kernel peer credentials and issues short-lived exact-action credentials. The broker authenticates the OS user, not the calling application.
4. **Loopback HTTP transport:** An instance-local listener on `127.0.0.1` carries typed requests with broker-issued credentials.
5. **App-side enforcement:** The running Warp app verifies the exact granted action and resolves targets deterministically. Close actions flow through normal Warp close behavior so existing app warnings remain authoritative.
Exact-action credentials are safety and intent mechanisms. They let a script or agent request only the specific operation it intends to perform so authority for a harmless UI action cannot accidentally be reused for a destructive close. They are not a hard security boundary against malicious same-user software.
## Security goals
- Allow same-user processes to control a running Warp instance through a typed, allowlisted interface when Scripting is enabled.
- Prevent unauthenticated localhost clients from invoking control actions.
- Prevent browser-origin JavaScript from becoming an ambient localhost control client.
- Prevent other OS users from controlling a Warp instance they do not own.
- Support multiple running Warp processes without a shared global port or credential.
- Separate discovery metadata from control authority.
- Require Scripting to be enabled before any control requests are accepted. Scripting defaults to enabled only on internal dogfood channels; public channels default to disabled and require explicit opt-in.
- Keep credentials out of plaintext discovery records and mint them only in memory.
- Authorize every action by its exact typed identity in the app bridge.
- Route close actions through normal Warp close behavior so existing app warnings for unsaved files, running processes, and shared sessions remain authoritative.
- Ensure the two input-staging commands (`input.insert`, `input.replace`) never submit the buffer. No other input actions exist.
- Keep the action surface at exactly 84 allowlisted actions. The Block, Auth, Drive, and History families are entirely absent.
- Fail closed on platforms without owner-only discovery and authenticated broker transport.
- Preserve deterministic targeting so a request never silently mutates or reads the wrong target.
## Honest same-user limitations
The broker authenticates the connecting process's OS user through kernel peer credentials. It does not prove that the caller is the official `warpctrl` binary, Warp-signed code, or a human-approved invocation. When Scripting is enabled, any process running as the same OS user can:
- Connect to the broker socket and request credentials for any of the 84 actions.
- Invoke `warpctrl` as a confused deputy.
The architecture therefore provides a **meaningful hard boundary** against:
- Other OS users.
- Browser-origin JavaScript.
- Network peers.
- Unauthenticated direct HTTP clients.
For same-user software, the protections are **intent guardrails**, not strong isolation:
- Protected enablement prevents silent activation.
- Short-lived credentials prevent ambient reuse.
- Exact-action grants prevent accidental overreach.
- Normal Warp close behavior preserves existing warnings for close actions.
- App-side revalidation catches stale or misused credentials.
A hostile same-user process that can automate the Warp UI, read local state, or invoke `warpctrl` is not made safe by this architecture. The value is preventing easy ambient paths (web-origin, other-user, unauthenticated localhost) and giving honest callers narrow, auditable grants.
## Threat model
### In scope
- Other local OS users attempting to control a Warp instance owned by the current user.
- Browser-origin JavaScript attempting to call localhost control endpoints.
- Same-user automation attempting an action without a credential for that exact action.
- Same-user processes attempting to extract plaintext credentials from local state.
- Stale discovery records from exited Warp processes.
- Multiple running Warp instances where ambiguous selection could target the wrong process.
- Malformed clients attempting unknown, unsupported, or non-allowlisted action payloads.
- Valid clients attempting actions other than the exact action granted by their credential.
- Explicit target IDs that become stale between discovery and execution.
### Out of scope
- A malicious same-user process with arbitrary filesystem and process access, except that exact-action credentials still reduce accidental over-granting.
- Kernel, hypervisor, or administrator-level compromise.
- Remote control over network transports (requires a separate security design).
## Protected enablement
Scripting has a single setting:
- **Enabled** (default on internal dogfood channels): same-user processes may request exact-action credentials and send control requests.
- **Disabled** (default on Stable, Preview, OSS, and Integration channels): no credentials are issued, no control requests are accepted, discovery records contain no actionable endpoint.
The authoritative value is stored in the most secure local storage available:
- **macOS:** Keychain, constrained to Warp-signed code where the platform supports it.
- **Linux:** Platform secret service where available; owner-only file fallback with the weaker same-user protection explicitly documented.
The setting is:
- Local-only: never synced through Settings Sync, Warp Drive, or server-backed preferences.
- Private: never appears in `settings.toml`, generated schemas, or any user-editable settings surface.
- App-controlled: only the running Warp app through Settings > Scripting can change it. `warpctrl`, shell scripts, config files, registry edits, `defaults write`, and direct protocol requests cannot enable or change it.
- Channel-default: when no valid protected value is available, the mode defaults to enabled on internal dogfood channels (Dev, Local) and disabled on all other channels.
Disabling Scripting immediately prevents new credential issuance and invalidates outstanding credentials. The control listener rejects all requests with `local_control_disabled`.
## Discovery registry
Each enabled Warp process writes a discovery record in a secure per-user directory.
A discovery record contains:
- Opaque `instance_id`.
- PID and process start timestamp.
- Channel and build metadata.
- Protocol version.
- Loopback endpoint for the control listener.
- Broker socket filename (inside the same owner-only directory).
A discovery record does **not** contain:
- Bearer tokens, raw credentials, or reusable control authority.
- Terminal contents, environment variables, or auth tokens.
Discovery rules:
- Records are readable only by the owning user.
- POSIX: owner-only permissions (`0600` for files, `0700` for the directory).
- When Scripting is disabled, no actionable record is published.
- The CLI prunes or ignores stale records whose PID is gone or whose health check fails.
- The CLI rejects records whose HTTP endpoint is not exactly `127.0.0.1` and whose broker socket is not the expected filename inside the owner-only directory.
- If multiple compatible instances are ambiguous, the CLI requires explicit `--instance` selection.
## Credential model
### Properties
A credential encodes:
- Issuing Warp instance.
- The one granted `ActionKind`.
- Issued-at time and expiry time.
- Unique credential ID for revocation.
### Issuance
The broker is a Unix-domain socket inside the owner-only discovery directory. Before reading any request, the broker calls the platform peer-credential API and verifies the connecting process's UID equals Warp's effective UID.
Issuance flow:
1. Client connects to the broker socket.
2. Broker verifies peer UID.
3. Client requests a credential naming one exact action.
4. Broker checks Scripting is enabled and the action is in the 84-action catalog.
5. Broker mints a short-lived credential in memory.
6. Client receives the credential.
Constraints:
- Credentials are never written to discovery records or persistent storage.
- There is no stored bootstrap secret or reusable token.
- The broker evaluates current Scripting state at issuance time.
- Every credential is bound to exactly one action and one instance.
- Issued credentials exist only in the app's process-local credential map and the client's memory.
### Exact-action grants
Every credential grants one exact typed action. The app bridge compares the requested action to the granted action before selector resolution or handler dispatch. A credential for `tab.create` cannot authorize `tab.close`, `setting.set`, or any other action. Similar actions do not inherit authority.
This prevents accidental overreach and gives Warp a structured point to deny sensitive actions. It does not make untrusted same-user software safe.
### Close behavior
The three destructive actions (`window.close`, `tab.close`, `pane.close`) execute after the same exact-action credential validation as every other action. They flow through normal Warp close behavior so existing app warnings remain authoritative.
### Confused-deputy mitigation
The broker authenticates the OS user, not the calling application. Any same-user process can request credentials. Mitigations:
- Exact-action credentials prevent accidental action overreach.
- Short expiry limits the window for credential reuse.
- Normal Warp close behavior preserves existing warnings for close actions.
- No `input.run` action exists, so `warpctrl` cannot be used to execute terminal commands.
- Protected enablement prevents silent activation of the control surface.
- App-side bridge enforcement re-checks every credential on every request.
These mitigations route operations through intentional flows. They do not guarantee that arbitrary same-user software cannot cause Warp-visible actions.
## Transport authentication
The control listener is bound to `127.0.0.1` on an ephemeral per-process port.
Required protections:
- No permissive CORS headers on control endpoints.
- Reject any request carrying an `Origin` header.
- Reject any request whose `Host` header is not exactly `127.0.0.1:<port>`.
- Require a bearer credential present in the instance's process-local credential map.
- Reject missing, malformed, expired, or wrong-instance credentials with structured errors.
- Decode the typed request only after transport authentication.
- No JSONP or browser-readable fallback formats.
- No GET endpoints for mutating actions.
These checks defend against browser-origin clients, network clients, unauthenticated clients that discover or guess the TCP port, stale records, and wrong-instance credentials.
## App-side enforcement
The app bridge is the final enforcement point. Direct protocol clients can bypass the CLI, so enforcement must happen in the app.
The bridge:
1. Authenticates the transport credential.
2. Parses the typed request envelope.
3. Verifies protocol version compatibility.
4. Compares the requested action to the granted action. Rejects mismatches with `insufficient_permissions`.
5. Resolves targets deterministically. Rejects ambiguous, missing, or stale targets with structured errors.
6. Invokes only the allowlisted typed handler.
## Target scoping
Targeting is part of security. The protocol never converts ambiguous or stale selectors into best-effort mutations.
Rules:
- Instance selection happens before request dispatch and must be explicit when ambiguous.
- `active` selectors resolve only when the target is unambiguous. For window-scoped mutations, the resolver falls back to the sole window if exactly one exists.
- Explicit opaque IDs resolve exactly or return `stale_target`.
- Index selectors resolve to concrete IDs before execution.
- Session-scoped requests against non-terminal panes return `target_state_conflict`.
## Input staging safety
The two input commands (`input.insert`, `input.replace`) only stage text in the terminal input buffer. They never submit the buffer, press Enter, or execute a command. No other input actions (`input.get`, `input.clear`, `input.mode.set`, `input.run`) exist in the 84-action catalog. Tests must prove no submission occurs.
## Catalog boundary
The catalog contains exactly 84 actions. The following families and actions are entirely absent:
- The entire Block family (`block.list`, `block.inspect`, `block.output`).
- The entire Auth family (`auth.status`, `auth.login`).
- The entire Drive family (all `drive.*` actions).
- The entire History family (`history.list`).
- `input.get`, `input.clear`, `input.mode.set`, `input.run`, and any form of terminal command execution.
- `file.list` and any local file content operations beyond the `file.open` app-state intent.
- Accepted-command submission and agent-prompt submission.
- Debug, crash, heap-dump, token-copying, and developer-only helpers.
- Arbitrary internal view dispatch by string.
Adding a new action requires extending the catalog, implementing validation, adding a handler, and adding tests for credential denial and success behavior.
## Error model
Structured errors are part of the security contract:
- `local_control_disabled` — Scripting is disabled.
- `unauthorized_local_client` — missing, malformed, expired, or invalid credential.
- `insufficient_permissions` — credential grants a different action.
- `ambiguous_instance` — multiple instances, no unambiguous selection.
- `ambiguous_target` — multiple matching targets.
- `stale_target` — explicit target ID no longer exists.
- `missing_target` — no active or default target exists.
- `invalid_selector` — malformed selector syntax.
- `invalid_request` — malformed request body.
- `invalid_params` — invalid action-specific parameters.
- `unsupported_action` — action not implemented by this build.
- `not_allowlisted` — action intentionally excluded from public surface.
- `target_state_conflict` — target cannot support the requested action.
- `no_instance` — no reachable Warp instance found.
- `protocol_version_unsupported` — client and app protocol versions do not match.
- `transport_unavailable` — the local transport (broker socket or loopback HTTP) failed.
- `bridge_unavailable` — the app-side bridge cannot service requests.
- `internal` — unexpected internal failure.
The app never downgrades these failures into broader default actions.
## Platform requirements
### macOS
- Discovery directory and records: owner-only permissions.
- Authoritative Scripting value: Keychain, constrained to Warp-signed code.
- Broker: Unix-domain socket with peer credential checks.
### Linux
- Discovery directory and records: owner-only permissions (`0700`/`0600`).
- Authoritative Scripting value: platform secret service where available; owner-only file fallback documented as weaker.
- Broker: Unix-domain socket with peer credential checks.
### Windows
Fails closed. `warpctrl` is not available on Windows until:
- Discovery-record ACL enforcement is implemented (current user, Administrators, SYSTEM).
- An equivalent authenticated broker transport replaces the Unix-domain socket.
- Protected Scripting storage uses Credential Manager, DPAPI, or equivalent.
Until these are implemented, the `warpctrl` wrapper on Windows returns a structured error and does not fall back to unauthenticated control.
## Remote control is separate
The local architecture assumes same-machine, same-user control over a loopback listener. Remote control requires a separate security design with transport encryption, remote identity, replay protection, explicit approval, and network exposure review. Remote support must not be enabled by pointing local credentials at an arbitrary URL.
## Auditing
Recommended audit fields for control requests:
- Timestamp.
- Instance ID.
- Credential ID.
- Action name.
- Target type and opaque target ID.
- Success or structured error code.
Avoid logging: bearer credentials, terminal output, command text, input buffer contents, or environment variable values. Error-level logs should be used only for conditions needing developer attention, not normal denied requests or user-caused selector failures.
## Required controls before catalog expansion
Before shipping each action family:
- Scripting must be enabled for any request to succeed.
- The action has a documented entry in the 84-action catalog.
- The bridge verifies the credential grants that exact action.
- Ambiguous, missing, and stale targets return structured errors.
- Close actions flow through normal Warp close behavior.
- Input actions never submit the buffer.
- Tests cover the allowed path and the wrong-action-credential denial path.
- Logs and errors do not expose credentials, terminal contents, or sensitive settings.
- The Block, Auth, Drive, and History families remain absent from the catalog.
- The catalog contains exactly 84 default-authorized actions.
+244
View File
@@ -0,0 +1,244 @@
# Context
`PRODUCT.md` defines a local Warp control CLI (`warpctrl`) with an allowlisted catalog of exactly 84 actions, deterministic addressing across multiple running Warp app processes, and a simple enabled/disabled Scripting setting. `SECURITY.md` is the normative security architecture. If this technical plan and `SECURITY.md` disagree, update the plan before implementing.
The design is external-only: all callers are same-user processes. There is no inside-Warp/outside-Warp distinction, no verified-terminal invocation context, and no authenticated-user identity layer. Security relies on owner-only filesystem discovery, same-user Unix credential broker with kernel peer credentials, short-lived instance-bound exact-action credentials, loopback HTTP transport, and app-side enforcement.
## Existing building blocks
- `crates/http_server/src/lib.rs` runs a native-only loopback Axum server on fixed port `9277`.
- `app/src/lib.rs` registers that HTTP server and currently merges only installation-detection and profiling routers.
- `app/src/workspace/action.rs` defines tab creation and workspace actions.
- `app/src/pane_group/mod.rs` shows pane creation/splitting semantics.
- `app/src/settings/theme.rs` and `app/src/themes/theme_chooser.rs` define theme settings behavior.
- `crates/warp_cli/src/lib.rs` defines existing CLI/parser conventions and channel-specific command naming.
- `app/src/lib.rs` routes CLI invocations into CLI execution before GUI launch.
- `script/macos/bundle` and `script/linux/bundle` show wrapper-script packaging patterns.
## Proposed changes
### 0. Security architecture dependency
Before implementing any local-control listener, CLI command, credential path, or action handler, the implementation must be checked against `SECURITY.md`. Required security gates:
- Scripting has a single setting: enabled (default) or disabled.
- The authoritative value lives in protected local storage, not ordinary preferences.
- When disabled, no credentials are issued, no control requests are accepted, and discovery records contain no actionable endpoint.
- When enabled, same-user processes may request exact-action credentials from the broker.
- The broker authenticates the OS user through kernel peer credentials, not the calling application.
- Every credential grants one exact action, is bound to the issuing instance, and has a short expiry.
- The app bridge verifies the exact granted action before selector resolution or handler dispatch.
- Close actions (`window.close`, `tab.close`, `pane.close`) flow through normal Warp close behavior so existing app warnings remain authoritative.
- Input-staging commands never submit the buffer. There is no `input.run` action.
- The Block, Auth, Drive, and History families are entirely absent from the 84-action catalog. Input is limited to `input.insert` and `input.replace`.
### 1. Protocol crate and stable envelope
Create a shared protocol crate used by both the app server and the `warpctrl` client. It defines:
- A request protocol version for defensive schema guarding.
- Discovery/health response types.
- The 84-action `ActionKind` enum with implementation status metadata. The Block, Auth, Drive, and History families are entirely absent; Input is limited to `input.insert` and `input.replace`.
- Selector types:
- `InstanceSelector`: `Active`, `Id(InstanceId)`, `Pid(u32)`.
- `WindowSelector`: `Active`, `Id(WindowId)`, `Index(u32)`, `Title(String)`.
- `TabSelector`: `Active`, `Id(TabId)`, `Index(u32)`, `Title(String)`.
- `PaneSelector`: `Active`, `Id(PaneId)`, `Index(u32)`.
- `SessionSelector`: `Active`, `Id(SessionId)`.
- Opaque protocol-facing ID newtypes for instance/window/tab/pane/session identifiers.
- Typed parameter payloads per action.
- Success/error envelopes with stable machine-readable error codes from `SECURITY.md`.
The protocol treats target IDs as opaque. Internal runtime IDs are implementation details.
Request shape for `tab.create`:
```json
{
"protocol_version": 1,
"request_id": "client-generated-id",
"target": { "window": "active" },
"action": { "kind": "tab.create", "params": {} }
}
```
Success response:
```json
{
"protocol_version": 1,
"request_id": "client-generated-id",
"response": { "status": "ok", "data": {} }
}
```
Error response:
```json
{
"protocol_version": 1,
"request_id": "client-generated-id",
"response": {
"status": "error",
"error": { "code": "missing_target", "message": "No active window is available", "details": null }
}
}
```
Error codes include: `local_control_disabled`, `unauthorized_local_client`, `insufficient_permissions`, `ambiguous_instance`, `ambiguous_target`, `stale_target`, `missing_target`, `invalid_request`, `invalid_selector`, `invalid_params`, `unsupported_action`, `not_allowlisted`, `target_state_conflict`, `no_instance`, `protocol_version_unsupported`, `transport_unavailable`, `bridge_unavailable`, `internal`.
### 2. Per-process discovery
Keep the existing fixed-port `9277` HTTP behavior intact. Add a separate local-control listener per process.
Design:
- Each Warp process creates a random opaque `instance_id` at startup.
- Each process binds a loopback control listener on an ephemeral port.
- Each process writes a discovery record into a secure per-user directory when Scripting is enabled.
- The record contains: `instance_id`, PID, channel/build metadata, control-listener endpoint, protocol version, start timestamp, and the filename of its instance-bound broker socket.
- The record does not contain bearer tokens, raw credentials, or control authority.
- The CLI passes its compiled channel into the shared discovery scan. The scan excludes records from other channels before returning candidates, rejects records whose endpoint is not exactly `127.0.0.1` or whose broker socket is not the expected filename, prunes stale same-channel records after health checks, and selects an instance using product selector rules. This same-channel boundary applies to listing, implicit selection, and explicit instance or PID selection.
- When Scripting is disabled, no discovery record is published.
Default discovery directory: `~/.warp/local-control/`. `$XDG_RUNTIME_DIR/warp/local-control` is preferred when available. On Unix, the directory is restricted to `0700` and records/sockets to `0600`.
### 3. Credential broker
The broker is a Unix-domain socket inside the owner-only discovery directory, one per instance. It is the protected path from discovery metadata to a short-lived exact-action credential.
Flow:
1. Client reads the discovery record to learn the broker socket filename.
2. Client connects to the socket.
3. Broker calls the platform peer-credential API and verifies the connecting process's UID equals Warp's effective UID. The broker authenticates the OS user, not the calling application.
4. Client sends a credential request naming one exact action.
5. Broker checks that Scripting is enabled and evaluates the requested action against the catalog.
6. Broker mints a short-lived credential in memory: instance-bound, one exact action, short expiry, unique credential ID.
7. Broker returns the credential to the client.
Properties:
- Credentials are never written to discovery records or disk.
- There is no stored bootstrap secret or reusable token.
- The broker evaluates current Scripting state at issuance time.
- Every credential is bound to exactly one action and one instance.
- Issued credentials exist only in the app's process-local credential map and the client's memory.
### 4. Transport: loopback HTTP
The control listener is an instance-local Axum server bound to `127.0.0.1` on an ephemeral port.
Before dispatch, the listener:
- Rejects requests carrying an `Origin` header.
- Requires the `Host` header to exactly match `127.0.0.1:<port>`.
- Requires a bearer credential present in the instance's process-local credential map.
- Rejects missing, malformed, expired, or wrong-instance credentials.
- Decodes the typed request only after transport authentication.
- Passes the request and credential to the app bridge for exact-action enforcement.
### 5. App-side request bridge
The HTTP handler runs on a Tokio runtime thread. It cannot directly access WarpUI state because all UI state is single-threaded on the main app event loop. The bridge transfers work to the main thread.
#### Thread model
- **Tokio thread (HTTP handler):** Owns the Axum router, validates transport credentials, deserializes the `RequestEnvelope`, hands the request to the bridge.
- **Main app thread:** Owns all WarpUI entities (`App`, `AppContext`, views, models). All UI state reads and mutations happen here.
- **Bridge:** Uses `ModelSpawner<LocalControlBridge>` to transfer a typed closure from the Tokio thread to the main thread, execute it with `&mut ModelContext`, and return the result.
#### Flow for `tab.create`
```
HTTP handler (Tokio thread)
├─ verify Scripting is enabled
├─ verify credential existence, expiry, instance binding
├─ deserialize RequestEnvelope
├─ call bridge_spawner.spawn(move |bridge, ctx| { ... }).await
└─ serialize ResponseEnvelope as JSON
LocalControlBridge::handle_request (main thread)
├─ verify the credential grants the exact requested action
├─ match request.action.kind
│ └─ ActionKind::TabCreate
│ ├─ resolve window: active window, or sole window, or missing_target/ambiguous_target
│ ├─ ctx.views_of_type::<Workspace>(window_id)
│ └─ workspace.update(ctx, |workspace, ctx| {
│ workspace.handle_action(&WorkspaceAction::AddTerminalTab { ... }, ctx)
│ })
└─ return ResponseEnvelope::ok(request_id, ...)
```
#### Adding new action handlers
1. Add an entry to the `ActionKind` catalog.
2. Add a match arm in `LocalControlBridge::handle_request`.
3. Verify the credential grants the exact action before selector resolution.
4. Resolve selectors and dispatch onto existing app types through `ctx`.
5. Return `ResponseEnvelope::ok(...)` or `ResponseEnvelope::error(...)`.
### 6. Target resolution
Implement target resolution as a reusable component.
Resolution order: instance → window → tab → pane → session.
Selector behavior:
- `active` resolves from current app focus state. For window-scoped mutations, a missing active window may fall back to the sole existing window.
- Explicit opaque IDs must resolve exactly or return `stale_target`.
- Index selectors resolve to a concrete opaque ID before execution.
- Title/name selectors are exact by default and return `ambiguous_target` on multiple matches.
- Session-scoped requests against non-terminal panes return `target_state_conflict`.
Target resolution happens after credential authentication and exact-action verification.
### 7. Close behavior
The 3 close actions (`window.close`, `tab.close`, `pane.close`) flow through normal Warp close behavior after exact-action credential validation and deterministic target resolution. Existing warnings for unsaved files, running processes, shared sessions, and similar app state remain authoritative and may cancel the close.
### 8. CLI parsing and output
The CLI uses the same libraries as the Oz CLI:
- **clap** (derive) for argument parsing and subcommand trees.
- **serde** / **serde_json** for JSON serialization.
- **clap_complete** for shell completion generation.
- `OutputFormat` enum (`Pretty`, `Json`, `Ndjson`, `Text`) shared from `warp_cli`.
New subcommand types live in `warp_cli::local_control` and follow existing `#[derive(Parser)]` patterns.
### 9. CLI packaging
The shipped product is a bundled `warpctrl` wrapper script that calls the channel-specific Warp binary with a hidden `--warpctrl` flag:
- **macOS:** `Resources/bin/warpctrl` wrapper in the app bundle, same pattern as the Oz wrapper.
- **Linux:** Small `warpctrl` wrapper or symlink in the app package.
- **Windows:** Fails closed until authenticated broker transport is implemented.
Startup: `app/src/lib.rs` recognizes `--warpctrl` before app launch and routes into `warp_cli::local_control`. The control-mode path initializes only command parsing, discovery, credential material, HTTP transport, and output formatting. It does not initialize GUI state, rendering, or terminal session models.
### 10. Feature flag
Gate behind `FeatureFlag::WarpControlCli` with Cargo feature `warp_control_cli`.
When disabled:
- No Scripting settings page.
- No `LocalControlBridge`, `LocalControlServer`, discovery records, broker sockets, or `/v1/control` endpoints.
- The `warpctrl` wrapper returns a structured `no_instance` or feature-disabled error.
When enabled:
- Settings > Scripting page is rendered.
- All local-control infrastructure starts when Scripting is enabled (the default on internal dogfood channels; public channels require explicit opt-in through Settings > Scripting).
- `resources/bundled/skills/warpctrl/SKILL.md` teaches the built-in agent and users how to discover and invoke the allowlisted CLI surface.
- The skill manager maps `warpctrl` to `FeatureFlag::WarpControlCli` through `BundledSkillActivation`. Both skill listing and direct bundled-skill reads enforce the activation state.
### 11. First slice: discovery + `tab.create`
The first implementation slice proves the end-to-end architecture:
- Shared protocol types and error envelopes.
- `FeatureFlag::WarpControlCli` and Cargo feature.
- Settings > Scripting page with enabled/disabled toggle.
- Protected local-only mode storage (channel-based default: enabled on dogfood channels, disabled on public channels).
- Discovery registry and CLI instance selection.
- `warpctrl` wrapper entrypoint with `--warpctrl` control-mode dispatch.
- Per-process credential broker (Unix socket, peer credential check).
- Loopback control listener.
- App-side request bridge with `ModelSpawner`.
- Exact-action credential issuance and enforcement.
- `app.ping`, `app.version`, `instance.list`, and `tab.create`.
- Structured success/error output in pretty and JSON formats.
### 12. Follow-up slices
After the first slice validates the architecture, add remaining catalog actions in family groups:
- Window/tab mutations (including close through normal Warp close behavior).
- Pane mutations (including close through normal Warp close behavior).
- Session actions.
- Input staging (insert and replace only, never submitting).
- Appearance/theme actions.
- Settings reads and writes.
- Surface availability, idempotent direct opens, and toggles.
- File open intent.
Each addition extends the `ActionKind` catalog, adds a handler, adds validation/tests, and adds CLI surface.
## End-to-end flow
```mermaid
sequenceDiagram
participant CLI as warpctrl
participant REG as Discovery registry
participant BROKER as Unix credential broker
participant HTTP as Loopback control listener
participant BRIDGE as App bridge
participant UI as Warp app state
CLI->>REG: Read same-channel instance discovery records
CLI->>HTTP: Health/protocol check (app.ping)
HTTP-->>CLI: Instance metadata
CLI->>CLI: Resolve instance selector
CLI->>BROKER: Connect to Unix socket
BROKER->>BROKER: Verify peer UID == Warp UID
BROKER->>BROKER: Check Scripting == enabled
CLI->>BROKER: Request credential for exact action
BROKER-->>CLI: Short-lived instance-bound credential
CLI->>HTTP: POST /v1/control with credential + typed request
HTTP->>HTTP: Validate credential, reject if expired/invalid
HTTP->>BRIDGE: Typed request + credential on main thread
BRIDGE->>BRIDGE: Verify exact action matches credential
BRIDGE->>BRIDGE: Resolve target selectors
BRIDGE->>UI: Execute allowlisted handler
UI-->>BRIDGE: Typed result
BRIDGE-->>HTTP: Response envelope
HTTP-->>CLI: JSON success/error
```
## Testing
- **Catalog invariant:** Every `ActionKind` with `Implemented` status has a parseable `warpctrl` CLI route, generated help/completion coverage, and an app-side bridge handler.
- **Scripting gate:** Disabled state rejects all credential requests and control requests. Enabled state allows them. Toggling invalidates outstanding credentials.
- **Credential model:** Raw credentials never appear in discovery records. Credentials are instance-bound, action-bound, and short-lived. A credential for one action fails with `insufficient_permissions` for any other action.
- **Selector resolution:** Tests for active, explicit ID, index, stale target, ambiguous target, missing target, and target-state-conflict cases.
- **Channel isolation:** Discovery tests prove that a CLI scan excludes records published by other Warp channels.
- **Input staging:** Only `input.insert` and `input.replace` exist. No `input.run`, `input.get`, `input.clear`, or `input.mode.set`. Tests prove no buffer submission occurs.
- **Excluded families:** The Block, Auth, Drive, and History families are entirely absent. The CLI rejects their command routes at parse time, the protocol rejects their action names at deserialization (`invalid_request`), and `action.inspect`/`capability.inspect` report non-catalog names as `not_allowlisted`.
- **Unsupported platforms:** Windows fails closed with no fallback.
- **Action count:** Tests verify the catalog contains exactly 84 uniformly authorized actions.
- **Bundled skill gate:** Tests verify the `warpctrl` bundled skill is discoverable and readable only while `FeatureFlag::WarpControlCli` is enabled, without affecting unrelated bundled skills.
## Risks and mitigations
- **Same-user residual risk:** The broker authenticates the OS user, not the calling application. Any process running as the same user can request credentials. Mitigated by: protected enablement, short expiry, exact-action grants, app-side revalidation, normal Warp close warnings for close actions.
- **Browser-to-localhost:** Mitigated by: no permissive CORS, Origin header rejection, Host header validation, credential requirement.
- **Fixed-port contention:** Mitigated by: leaving `9277` undisturbed, using per-process ephemeral ports for control.
- **Input execution risk:** Mitigated by: no `input.run` in the catalog, input commands stage text only, tests prove no submission.
- **Heavyweight CLI startup:** Mitigated by: `--warpctrl` routes before GUI launch, control-mode path initializes only what's needed.