portzilla 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +368 -0
- package/npm/bin.js +26 -0
- package/npm/install.js +148 -0
- package/package.json +36 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 portzilla contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
# portzilla
|
|
2
|
+
|
|
3
|
+
[](https://github.com/011010/portzilla/actions/workflows/ci.yml)
|
|
4
|
+
|
|
5
|
+
`portzilla` is a lease registry for localhost ports. It exists because AI coding agents (Claude Code, Cursor, and similar tools) increasingly run several parallel sessions on one machine — each in its own git worktree, each starting its own dev server — and today those sessions have no way to coordinate. An agent that finds port 3000 busy typically just kills whatever is on it, which can be a sibling session's dev server. `portzilla` gives processes a way to claim a port with an owner PID and a purpose tag, gives conflicting claims the next free port instead of stealing, lets anyone ask who owns a port before killing it, and prunes leases whose owning process has died. All output is available as JSON so agents can consume it directly, and the tool works the same way for a human typing commands in a terminal.
|
|
6
|
+
|
|
7
|
+
This is coordination, not diagnostics: existing tools like `witr`, `kill-port`, and ServerSlayer tell you what is on a port or kill it after the fact. `portzilla` is the layer that prevents the conflict in the first place.
|
|
8
|
+
|
|
9
|
+
For maintainers, the complete release procedure is documented in [`docs/RELEASING.md`](docs/RELEASING.md).
|
|
10
|
+
|
|
11
|
+
## 30-second demo
|
|
12
|
+
|
|
13
|
+
```console
|
|
14
|
+
$ portzilla claim 3000 --tag next-dev --pid 57107
|
|
15
|
+
claimed port 3000 for pid 57107 (tag: next-dev)
|
|
16
|
+
|
|
17
|
+
$ portzilla claim 3000 --tag vite-dev --pid 57108
|
|
18
|
+
port 3000 is busy; claimed port 3001 instead for pid 57108 (tag: vite-dev)
|
|
19
|
+
|
|
20
|
+
$ portzilla who 3001
|
|
21
|
+
port: 3001
|
|
22
|
+
pid: 57108
|
|
23
|
+
tag: vite-dev
|
|
24
|
+
session: (none)
|
|
25
|
+
age: 3s
|
|
26
|
+
status: alive
|
|
27
|
+
|
|
28
|
+
$ portzilla who 3001 --json
|
|
29
|
+
{"port":3001,"pid":57108,"tag":"vite-dev","created_at":1785959877,"session":null,"age_secs":3,"alive":true}
|
|
30
|
+
|
|
31
|
+
$ portzilla ls
|
|
32
|
+
PORT PID STATUS AGE TAG
|
|
33
|
+
3000 57107 alive 5s next-dev
|
|
34
|
+
3001 57108 alive 3s vite-dev
|
|
35
|
+
|
|
36
|
+
$ portzilla release 3001
|
|
37
|
+
warning: released port 3001 whose owning pid 57108 is still alive
|
|
38
|
+
port: 3001
|
|
39
|
+
pid: 57108
|
|
40
|
+
tag: vite-dev
|
|
41
|
+
session: (none)
|
|
42
|
+
age: 3s
|
|
43
|
+
status: alive
|
|
44
|
+
|
|
45
|
+
$ portzilla prune
|
|
46
|
+
no dead leases to prune
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The output above is real: it was captured by running the built binary with `PORTZILLA_DATA_DIR` pointed at a temporary directory holding two genuinely live processes.
|
|
50
|
+
|
|
51
|
+
## Install
|
|
52
|
+
|
|
53
|
+
### Cargo
|
|
54
|
+
|
|
55
|
+
```console
|
|
56
|
+
$ cargo install portzilla
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
To install from a local checkout:
|
|
60
|
+
|
|
61
|
+
```console
|
|
62
|
+
$ cargo install --path .
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### curl
|
|
66
|
+
|
|
67
|
+
Downloads a prebuilt binary from GitHub Releases into `~/.local/bin`:
|
|
68
|
+
|
|
69
|
+
```console
|
|
70
|
+
$ curl --proto '=https' --tlsv1.2 -LsSf https://raw.githubusercontent.com/011010/portzilla/main/scripts/install.sh | sh
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
To install a specific version or directory:
|
|
74
|
+
|
|
75
|
+
```console
|
|
76
|
+
$ curl --proto '=https' --tlsv1.2 -LsSf https://raw.githubusercontent.com/011010/portzilla/main/scripts/install.sh | PORTZILLA_VERSION=0.1.0 PORTZILLA_INSTALL_DIR=/usr/local/bin sh
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
If a release asset is unavailable, the installer falls back to `cargo install portzilla`.
|
|
80
|
+
|
|
81
|
+
### npm
|
|
82
|
+
|
|
83
|
+
```console
|
|
84
|
+
$ npm install -g portzilla
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
The npm package installs the same native `portzilla` binary. It downloads a GitHub Release asset when available and falls back to Cargo when needed.
|
|
88
|
+
|
|
89
|
+
Release binaries are currently available for Linux x86_64/ARM64, macOS Intel/Apple Silicon, and Windows x86_64/ARM64. Each release asset includes a `.sha256` checksum file.
|
|
90
|
+
|
|
91
|
+
## Command reference
|
|
92
|
+
|
|
93
|
+
Every command accepts `--json` to print a single JSON value on stdout instead of human-readable text. Every command reads and writes the same file-locked JSON state file, so concurrent invocations from different processes are serialized safely.
|
|
94
|
+
|
|
95
|
+
### `portzilla claim <PORT> --tag <TAG> [--pid <PID>] [--session <SESSION>] [--json]`
|
|
96
|
+
|
|
97
|
+
Claims `<PORT>` for the given (or default) PID and tag.
|
|
98
|
+
|
|
99
|
+
- `--tag <TAG>` — required. Human-readable description of what the port is for.
|
|
100
|
+
- `--pid <PID>` — optional. Defaults to the PID of the parent process (the shell or agent invoking `portzilla`); falls back to `portzilla`'s own PID if the parent cannot be determined.
|
|
101
|
+
- `--session <SESSION>` — optional. Groups related leases under a session identifier.
|
|
102
|
+
- `--json` — print the outcome as JSON instead of a one-line summary.
|
|
103
|
+
|
|
104
|
+
Conflict resolution:
|
|
105
|
+
|
|
106
|
+
- No lease on the requested port, or the existing lease's owning PID is dead: the port is claimed (or re-taken) directly. Not reassigned.
|
|
107
|
+
- A live lease on the requested port already owned by the same PID: the lease is updated in place (idempotent re-claim — tag and session can change, the port does not). Not reassigned.
|
|
108
|
+
- A live lease on the requested port owned by a different PID: `portzilla` finds the next free port at or after `requested_port + 1` (skipping ports with a live lease and ports the OS reports as bound) and claims that instead. Reassigned.
|
|
109
|
+
|
|
110
|
+
### `portzilla ls [--json]`
|
|
111
|
+
|
|
112
|
+
Lists every recorded lease. Human output is a table (`PORT PID STATUS AGE TAG`); JSON output is an array of lease objects (see shape below).
|
|
113
|
+
|
|
114
|
+
### `portzilla who <PORT> [--json]`
|
|
115
|
+
|
|
116
|
+
Shows the lease recorded on `<PORT>`. Exits with code `2` and prints nothing to stdout if no lease exists on that port.
|
|
117
|
+
|
|
118
|
+
### `portzilla release <PORT> [--json]`
|
|
119
|
+
|
|
120
|
+
Removes the lease recorded on `<PORT>` and prints the removed lease. Exits with code `2` if no lease exists on that port. If the owning PID is still alive at the time of release, a warning is printed to stderr (`release` always wins — it does not check ownership or refuse to act).
|
|
121
|
+
|
|
122
|
+
### `portzilla prune [--json]`
|
|
123
|
+
|
|
124
|
+
Removes every lease whose owning PID is no longer alive and prints each one that was removed. Human output prints `no dead leases to prune` if nothing was pruned; JSON output prints `[]`.
|
|
125
|
+
|
|
126
|
+
## Exit codes
|
|
127
|
+
|
|
128
|
+
| Code | Meaning |
|
|
129
|
+
|------|---------|
|
|
130
|
+
| `0` | Success |
|
|
131
|
+
| `1` | Unexpected error (I/O failure, corrupt state file, lock failure) |
|
|
132
|
+
| `2` | Requested lease not found (`who` / `release` on a port with no lease) |
|
|
133
|
+
|
|
134
|
+
## JSON output shapes
|
|
135
|
+
|
|
136
|
+
### Lease object (`ls`, `who`, `release`, `prune`)
|
|
137
|
+
|
|
138
|
+
Used as a single object by `who` and `release`, and as an array of these objects by `ls` and `prune`:
|
|
139
|
+
|
|
140
|
+
```json
|
|
141
|
+
{
|
|
142
|
+
"port": 3001,
|
|
143
|
+
"pid": 57108,
|
|
144
|
+
"tag": "vite-dev",
|
|
145
|
+
"created_at": 1785959877,
|
|
146
|
+
"session": null,
|
|
147
|
+
"age_secs": 3,
|
|
148
|
+
"alive": true
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
`created_at` is a Unix timestamp in seconds. `session` is `null` unless `--session` was given at claim time. `alive` reflects a live PID-table check at the moment of the query, not a cached value.
|
|
153
|
+
|
|
154
|
+
### Claim outcome (`claim --json`)
|
|
155
|
+
|
|
156
|
+
```json
|
|
157
|
+
{
|
|
158
|
+
"port": 3001,
|
|
159
|
+
"pid": 57285,
|
|
160
|
+
"tag": "vite-dev",
|
|
161
|
+
"created_at": 1785959898,
|
|
162
|
+
"session": null,
|
|
163
|
+
"requested_port": 3000,
|
|
164
|
+
"reassigned": true
|
|
165
|
+
}
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`requested_port` is the port that was originally asked for; `port` is the port actually leased. `reassigned` is `true` only when `port != requested_port` because of a live conflicting claim.
|
|
169
|
+
|
|
170
|
+
## MCP server
|
|
171
|
+
|
|
172
|
+
`portzilla serve --mcp` runs an [MCP](https://modelcontextprotocol.io) server over stdio, exposing `claim`, `who`, `ls`, `release`, and `prune` as MCP tools (those are the registered tool names — no `portzilla_` prefix). This is for AI coding agents with MCP tool access (Claude Code, and any other MCP client): they call `who` the same way they call any other structured tool — typed JSON in, typed JSON out — instead of shelling out to the CLI and parsing text.
|
|
173
|
+
|
|
174
|
+
Register it with Claude Code:
|
|
175
|
+
|
|
176
|
+
```console
|
|
177
|
+
$ claude mcp add portzilla -- portzilla serve --mcp
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Every tool's description is written to make the intended behavior explicit to the calling agent — the `claim` tool description, for example, says outright to use it *instead of* killing whatever occupies a port. Tool results use the exact same flat JSON shapes documented above for `--json` output (see [JSON output shapes](#json-output-shapes)), so anything already written against the CLI's JSON recognizes MCP results too.
|
|
181
|
+
|
|
182
|
+
- **`claim(port, tag, pid?, session?)`** — same semantics as `portzilla claim`. `pid` is optional here for a different reason than on the CLI: there is no meaningful "parent process" to default to (the MCP client, not a shell, owns the session), so an omitted `pid` falls back to the portzilla server process's own PID — almost never what you want — and the result carries an extra `note` field saying so. Always pass the PID of the process you started (or are about to start) on that port when you have it.
|
|
183
|
+
- **`who(port)`** — same semantics as `portzilla who`.
|
|
184
|
+
- **`ls()`** — same semantics as `portzilla ls`, no arguments.
|
|
185
|
+
- **`release(port)`** — same semantics as `portzilla release`, including the still-alive warning (surfaced as a `was_alive` field on the result instead of a stderr line).
|
|
186
|
+
- **`prune()`** — same semantics as `portzilla prune`, no arguments.
|
|
187
|
+
|
|
188
|
+
**Errors**: a missing lease (`who`/`release` on a port with no lease) comes back as a *tool-level* error — the JSON-RPC call still succeeds, but the tool result is flagged `isError: true` with a structured `{"error": "not_found", "port": ..., "message": ...}` body. This mirrors the CLI's exit code `2`: it is an expected, well-formed outcome the calling agent should see and act on, not a protocol failure. Actual portzilla failures (I/O errors, corrupt state, lock failures — the CLI's exit code `1`) come back as real JSON-RPC protocol errors instead, since those mean the server itself couldn't do its job.
|
|
189
|
+
|
|
190
|
+
The MCP server reads and writes the exact same locked `leases.json` the CLI does (respecting `PORTZILLA_DATA_DIR`) — it is a second front end onto the same on-disk state, not a separate store.
|
|
191
|
+
|
|
192
|
+
## Kill guard
|
|
193
|
+
|
|
194
|
+
MCP tool access (above) makes it *possible* for an agent to check ownership before acting. The kill guard is what makes checking the *default*: it intercepts kill-shaped commands before they run and blocks the ones that would kill another session's live, leased process — instead of relying on the agent to remember to run `who` first.
|
|
195
|
+
|
|
196
|
+
The guard itself (`src/guard.rs`) is harness-agnostic: it takes a shell command string and the current lease list and returns a verdict, with no knowledge of Claude Code, Cursor, Gemini CLI, Codex CLI, Kimi CLI, OpenCode, Windsurf, or any other tool. Each harness gets a thin adapter over the same core (`src/claude_code.rs`, `src/cursor.rs`, `src/gemini.rs`, `src/codex.rs`, `src/kimi.rs`, `src/opencode.rs`, `src/windsurf.rs`) that only translates the harness's hook payload in and its response shape out — adding a new harness means writing another adapter like these, never touching the guard itself.
|
|
197
|
+
|
|
198
|
+
It recognizes:
|
|
199
|
+
|
|
200
|
+
- `kill <pid>` / `kill -9 <pid>` — explicit PIDs, including `sudo kill ...`, `FOO=1 kill ...` (leading env-var assignments), and `/usr/bin/kill ...` (matched by basename)
|
|
201
|
+
- `pkill <name>` / `killall <name>` — process names (can't be resolved to a specific lease, so this only ever warns, never denies)
|
|
202
|
+
- `lsof -ti:<port> | xargs kill` (and the `lsof -ti :<port>` / `-9` variants) — only when actually piped together, not merely run one after another with `;`/`&&`
|
|
203
|
+
- `fuser -k <port>/tcp` (and `/udp`) — a bare `fuser -k <port>` with no protocol suffix is not treated as a port kill, matching real `fuser`'s own argument parsing
|
|
204
|
+
- `npx kill-port <port>` / `kill-port <port>` (including `npx -y kill-port ...` / `npx --yes kill-port ...`)
|
|
205
|
+
|
|
206
|
+
Leading wrapper prefixes are stripped before the verb is read, so the kill intent is detected whether it appears directly or behind one of `env`, `command`, `exec`, `nohup`, `builtin`, or any combination with `sudo` — `sudo env FOO=1 command kill <pid>` resolves to `kill <pid>`. A leading `sh -c '<payload>'` invocation is also unwrapped (the same shape the universal `guard` wrapper handles for argv), so a kill hidden inside the payload is detected through the hook adapters too.
|
|
207
|
+
|
|
208
|
+
For each, it resolves the target PID or port against the lease registry and decides:
|
|
209
|
+
|
|
210
|
+
- **Allow** — no kill intent detected, the target has no live lease, the lease is dead, or the lease is yours (you're allowed to kill/restart your own claimed process — see "Session ownership" below).
|
|
211
|
+
- **Deny** — the target has a live lease owned by someone else. The explanation names the port, PID, and tag, and says what to do instead: check `portzilla who <port>`, claim a different port, or ask before proceeding if the lease looks stale.
|
|
212
|
+
- **Warn** — a kill intent was detected but can't be resolved to a specific port/PID (killing by process name). portzilla can't verify safety here, so it surfaces a warning instead of silently allowing or incorrectly denying.
|
|
213
|
+
|
|
214
|
+
This is intentionally not a real shell parser — see the module doc comment in `src/guard.rs` for the exact approximation (split on `|`/`;`/`&&`/`||`, look at each segment's first word) and its tested boundaries, e.g. `killall-whatever` doesn't trigger `killall` detection, and `echo "kill 123"` doesn't trigger `kill` detection. False negatives are an accepted tradeoff; false positives are not.
|
|
215
|
+
|
|
216
|
+
### Support matrix
|
|
217
|
+
|
|
218
|
+
| Harness | Mechanism | Deny reason reaches the model? | Own-lease recognition? |
|
|
219
|
+
|---|---|---|---|
|
|
220
|
+
| **Claude Code** | `PreToolUse` hook, `portzilla hook claude-code` | Yes — `permissionDecisionReason` | **Yes** — `--session "$CLAUDE_CODE_SESSION_ID"` |
|
|
221
|
+
| **Cursor** | `beforeShellExecution` hook, `portzilla hook cursor` | Likely — `agent_message` is documented for this event without a deny-only qualifier (unlike some other Cursor hook events' docs); delivery on `permission: "allow"` is not positively confirmed, only not ruled out — needs a live Cursor smoke test | No — `conversation_id` isn't exposed to the agent's shell commands |
|
|
222
|
+
| **Gemini CLI** | `BeforeTool` hook on `run_shell_command`, `portzilla hook gemini` | Yes for Deny (`reason`); **no non-blocking channel for Warn** (human-only, `systemMessage`) | No — the shell tool only sets `GEMINI_CLI=1`, not a session id |
|
|
223
|
+
| **Codex CLI** | `PreToolUse` hook, `portzilla hook codex` | Yes — `permissionDecisionReason` on deny; **yes for Warn** — `additionalContext` is added as extra developer context the model sees | No — `session_id` reaches the hook payload but not the agent's shell commands |
|
|
224
|
+
| **Kimi CLI** | `PreToolUse` hook, `portzilla hook kimi` | Yes — stderr on exit 2 is fed back to the model; **yes for Warn** — exit-0 stdout is added to the model's context | No — `session_id` reaches the hook payload but not the agent's shell commands |
|
|
225
|
+
| **OpenCode** | Plugin shim (`portzilla init opencode` prints `portzilla.js`) shelling out to `portzilla hook opencode` | Yes for Deny — throwing surfaces the reason as a tool error; **yes for Warn** — appended to the tool result via `tool.execute.after` | **Yes** — the shim injects `PORTZILLA_SESSION` into bash subprocess env via `shell.env`, and the guard gets the session id from `tool.execute.before` |
|
|
226
|
+
| **Windsurf** | `pre_run_command` hook, `portzilla hook windsurf` | Yes for Deny — stderr on exit 2 is shown to the Cascade agent; **no non-blocking channel for Warn** (stderr on exit 0 is human-visible only; with `show_output: true`) | No — `trajectory_id` reaches the hook payload but not the agent's shell commands |
|
|
227
|
+
| **Anything else** (Aider, scripts, a human) | `portzilla guard -- <command...>` | N/A — the command is simply not run (exit 2); there's no model in the loop to explain to | **Yes** — `--session <S>` or `PORTZILLA_SESSION` |
|
|
228
|
+
|
|
229
|
+
"Own-lease recognition" means: a lease claimed with the right session identifier is recognized as *yours*, so the guard lets you kill/restart your own process. Without it, the guard still protects you from killing *other* sessions' processes — it just can't yet tell your own process apart from a stranger's, so it protects everyone equally, including you.
|
|
230
|
+
|
|
231
|
+
### Claude Code setup
|
|
232
|
+
|
|
233
|
+
```console
|
|
234
|
+
$ portzilla init claude-code
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
prints the exact `.claude/settings.json` snippet to add (project-level `.claude/settings.json` or user-level `~/.claude/settings.json`), registering `portzilla hook claude-code` as a `PreToolUse` hook on the `Bash` tool. This only prints instructions — it never writes to your settings file.
|
|
238
|
+
|
|
239
|
+
For session ownership to resolve end to end, claim with the session id Claude Code exposes to Bash tool subprocesses (verified against the Claude Code environment variables reference — `CLAUDE_CODE_SESSION_ID` "matches the `session_id` field in the hook JSON input" for Bash, PowerShell, and hook subprocesses):
|
|
240
|
+
|
|
241
|
+
```console
|
|
242
|
+
$ portzilla claim 3000 --tag "vite dev" --session "$CLAUDE_CODE_SESSION_ID"
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
### Cursor setup
|
|
246
|
+
|
|
247
|
+
```console
|
|
248
|
+
$ portzilla init cursor
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
prints the `.cursor/hooks.json` snippet (project `.cursor/hooks.json` or user `~/.cursor/hooks.json`), registering `portzilla hook cursor` as a `beforeShellExecution` hook. Cursor's own hook runner already fails open by default on a hook crash/timeout/invalid-JSON (unless `failClosed: true` is set, which this setup does not ask for).
|
|
252
|
+
|
|
253
|
+
Cursor does not currently expose `conversation_id` to the shell commands it runs — only to the hook payload itself (verified: the hooks doc's own "Environment Variables" table lists `CURSOR_PROJECT_DIR`, `CURSOR_VERSION`, `CURSOR_USER_EMAIL`, `CURSOR_TRANSCRIPT_PATH`, `CURSOR_CODE_REMOTE`, and `CLAUDE_PROJECT_DIR` — none of them a session/conversation id, and that table is explicitly scoped to what the hook script receives, not the agent's own commands). So there is currently no `--session` value a Cursor-driven claim can use to be recognized as its own later. Foreign-lease protection still works fully; own-lease recognition doesn't yet, pending Cursor documenting such a variable.
|
|
254
|
+
|
|
255
|
+
### Gemini CLI setup
|
|
256
|
+
|
|
257
|
+
```console
|
|
258
|
+
$ portzilla init gemini
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
prints the `.gemini/settings.json` snippet (project `.gemini/settings.json`, user `~/.gemini/settings.json`, or system `/etc/gemini-cli/settings.json`), registering `portzilla hook gemini` as a `BeforeTool` hook matched on the `run_shell_command` tool.
|
|
262
|
+
|
|
263
|
+
Two things are worth knowing here, both found during verification rather than assumed: first, hook registration lives in `settings.json`, not a standalone `hooks/hooks.json` file inside an extension directory — the current reference documents only the `settings.json`-based mechanism. Second, `run_shell_command`'s own subprocess (the agent's actual shell commands) is only ever given `GEMINI_CLI=1` — a bare presence flag, not a session id (`GEMINI_SESSION_ID` exists, but is documented as available to hook script subprocesses, not shell-tool subprocesses) — so, same as Cursor, own-lease recognition isn't available yet.
|
|
264
|
+
|
|
265
|
+
### Codex CLI setup
|
|
266
|
+
|
|
267
|
+
```console
|
|
268
|
+
$ portzilla init codex
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
prints the exact `.codex/hooks.json` snippet to add (project-level `.codex/hooks.json` or user-level `~/.codex/hooks.json`), registering `portzilla hook codex` as a `PreToolUse` hook matched on `Bash`. Codex's hooks are [generally available](https://developers.openai.com/codex/hooks); project-level hooks are only loaded once the project's `.codex/` layer is trusted (Codex asks you to review/trust new hooks — see its `/hooks` command).
|
|
272
|
+
|
|
273
|
+
Codex's own env-vars reference does not expose the session id to the shell commands the agent runs — only to the hook payload itself — so, same as Cursor and Gemini CLI, own-lease recognition isn't available yet. Deny reasons do reach the model (`permissionDecisionReason`), and `Warn` verdicts ride the `additionalContext` field Codex adds to the model's context.
|
|
274
|
+
|
|
275
|
+
### Kimi CLI setup
|
|
276
|
+
|
|
277
|
+
```console
|
|
278
|
+
$ portzilla init kimi
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
prints the exact `~/.kimi/config.toml` snippet to add, registering `portzilla hook kimi` as a `[[hooks]]` entry on `PreToolUse` matched on `Shell`. Kimi's hooks are Beta (implementation details may change), and Kimi CLI is being [wound down in favor of Kimi Code CLI](https://github.com/MoonshotAI/kimi-cli) — re-verify this integration when adopting the successor.
|
|
282
|
+
|
|
283
|
+
Kimi's `PreToolUse` contract is exit-code driven rather than JSON-response driven: `portzilla hook kimi` exits 2 (with the reason on stderr, which Kimi feeds back to the model) to deny, and prints `Warn` explanations as plain text on stdout, which Kimi adds to the model's context on allow. As with Cursor/Gemini/Codex, the session id reaches the hook payload but not the agent's own shell commands, so own-lease recognition isn't available yet.
|
|
284
|
+
|
|
285
|
+
### OpenCode setup
|
|
286
|
+
|
|
287
|
+
```console
|
|
288
|
+
$ portzilla init opencode
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
prints the full source of the `portzilla.js` plugin shim to save as `.opencode/plugin/portzilla.js` (project) or `~/.config/opencode/plugin/portzilla.js` (user), then restart OpenCode — plugins load once at startup, not hot-reloaded. Your editor needs `portzilla` on PATH. OpenCode hooks run in-process as JS/TS plugin modules, which is why this harness uses a shim instead of running `portzilla` as the hook directly.
|
|
292
|
+
|
|
293
|
+
The shim hooks `tool.execute.before` for the `bash` tool, shells out to `portzilla hook opencode`, and throws with the deny reason (OpenCode surfaces it to the model as a tool error) or defers a warn to `tool.execute.after` so the model sees it on the tool result without blocking. Because the shim also adds a `shell.env` hook that injects `PORTZILLA_SESSION` into every bash subprocess, this is the only non-Claude harness where end-to-end own-lease recognition works:
|
|
294
|
+
|
|
295
|
+
```console
|
|
296
|
+
$ portzilla claim 3000 --tag "vite dev" --session "$PORTZILLA_SESSION"
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
### Windsurf setup
|
|
300
|
+
|
|
301
|
+
```console
|
|
302
|
+
$ portzilla init windsurf
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
prints the exact `.windsurf/hooks.json` snippet to add, registering `portzilla hook windsurf` as a `pre_run_command` hook. Cascade Hooks' contract is exit-code driven: exit 2 blocks and the message on stderr reaches the agent, exit 0 allows, and Windsurf treats any other exit code as allow (fail-open). Windsurf has no non-blocking model-visible warn channel, so `Verdict::Warn` rides stderr on exit 0 — never blocks, and is visible to a human when `show_output: true` is set. `trajectory_id` reaches the hook payload but not the agent's own shell commands, so own-lease recognition isn't available yet. Note that Cascade hooks don't load at all while a workspace is open in Restricted Mode.
|
|
306
|
+
|
|
307
|
+
### Anything else: `portzilla guard`
|
|
308
|
+
|
|
309
|
+
For harnesses with no hook mechanism (Aider), and for a human or a script that just wants the guard in front of a command:
|
|
310
|
+
|
|
311
|
+
```console
|
|
312
|
+
$ portzilla guard -- kill 57107
|
|
313
|
+
portzilla guard: blocked — Port 3000 is leased to pid 57107 (tag: "next-dev") — a live process owned by another session, not a stale one. ...
|
|
314
|
+
$ echo $?
|
|
315
|
+
2
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
- **Deny** — the command is not executed at all; the explanation goes to stderr and `portzilla guard` exits `2`.
|
|
319
|
+
- **Warn** — a warning goes to stderr, then the command runs.
|
|
320
|
+
- **Allow** — the command runs with no extra output.
|
|
321
|
+
- `--session <S>`, or the `PORTZILLA_SESSION` environment variable if `--session` is omitted, enables own-lease recognition the same way `--session` does for `claim`.
|
|
322
|
+
- The command after `--` is executed directly — no shell, so pipes and compounds are not interpreted by `portzilla guard` itself. On Unix this replaces the current process via `exec`, so exit codes pass straight through as if `portzilla guard` were never there (and if the command itself can't be started, `portzilla guard` exits with the same POSIX convention a shell would: `127` if it wasn't found, `126` for any other reason — not executable, permission denied, etc.). For a pipe or compound command, wrap it in `sh -c`:
|
|
323
|
+
|
|
324
|
+
```console
|
|
325
|
+
$ portzilla guard -- sh -c 'lsof -ti:3000 | xargs kill'
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
`portzilla guard` recognizes an `sh`/`bash`/`zsh`/`dash` invocation with a `-c`-family flag (combined, like `-lc`, or separate, like `-x -c` or `--norc -c`) ahead of the payload, and analyzes the raw payload directly instead of the literal `sh -c ...` text — including recursively through a nested `sh -c "sh -c '...'"`, up to 8 levels deep. This is a targeted unwrap for that specific shape, not a shell parser: it does not follow `$(...)` command substitution, variable expansion, or backslash escaping inside the payload, and only recognizes `sh`/`bash`/`zsh`/`dash` by name (not `ksh`, `fish`, `python3 -c`, PowerShell's `-Command`, etc.) — see `src/guard_cmd.rs`'s module doc comment for the complete, current list of what it does and doesn't catch.
|
|
329
|
+
|
|
330
|
+
### Fail-open, always
|
|
331
|
+
|
|
332
|
+
A guard that can crash or hang and take the user's session down with it is worse than no guard. Every adapter (`hook claude-code`, `hook cursor`, `hook gemini`) and `guard` fails open at every step: unreadable stdin, malformed hook JSON, an unreadable lease store, even an internal panic — all of it is caught and turned into "allow, note it on stderr" rather than ever blocking or crashing. For the hook adapters this means the harness's own normal permission flow applies unmodified, exactly as if the hook weren't installed; a portzilla-side problem never denies a command, only the command itself looking unsafe does.
|
|
333
|
+
|
|
334
|
+
### Fail-closed mode (opt-in)
|
|
335
|
+
|
|
336
|
+
Set `PORTZILLA_FAIL_CLOSED=1` to flip the tradeoff: when portzilla can't verify a command's safety (corrupt store, oversized payload, unparseable input, missing command, internal panic), the hook adapters emit their harness's deny shape with the reason going to the model, and `portzilla guard` exits 2 without running the command. Default is fail-open; this is for users who specifically prefer "block when unverified" over "let it through." The shape and channel of each deny match the harness's own conventions (Claude Code's `permissionDecisionReason`, Cursor's `agent_message`, Gemini's `reason`).
|
|
337
|
+
|
|
338
|
+
## Input validation
|
|
339
|
+
|
|
340
|
+
- `claim` rejects port 0 (clap range 1..=65535); the same check exists in `Store::claim` so any other caller (MCP, direct library use) hits it too.
|
|
341
|
+
- `tag` is capped at 1024 characters and `session` at 512; oversized values are rejected with a clear error before the store is touched.
|
|
342
|
+
- Hook runners cap stdin at 1 MiB; over-cap inputs are treated like a malformed payload.
|
|
343
|
+
|
|
344
|
+
## Data file location
|
|
345
|
+
|
|
346
|
+
`portzilla` resolves its data directory in this order:
|
|
347
|
+
|
|
348
|
+
1. `PORTZILLA_DATA_DIR` environment variable, used directly as the data directory.
|
|
349
|
+
2. `$XDG_DATA_HOME/portzilla`.
|
|
350
|
+
3. `$HOME/.local/share/portzilla`.
|
|
351
|
+
|
|
352
|
+
The state lives at `<data_dir>/leases.json`, a pretty-printed JSON array of lease objects, written atomically (write to a temp file, then rename) and guarded by an exclusive file lock at `<data_dir>/leases.json.lock` for the duration of every read-modify-write operation.
|
|
353
|
+
|
|
354
|
+
Set `PORTZILLA_DATA_DIR` to isolate tests, CI runs, or throwaway experiments from your real lease store.
|
|
355
|
+
|
|
356
|
+
## Limitations
|
|
357
|
+
|
|
358
|
+
**PID reuse.** Liveness is determined by asking the OS process table "does a process with this PID exist right now?" (via `sysinfo`). Operating systems recycle PIDs. If a leased process dies and, before that lease is pruned or released, a new unrelated process happens to be assigned the same PID, `portzilla` will report the old lease as `alive` — a false positive. This is a known tradeoff of not running a background daemon: there is no process to actively watch for exit events, only a point-in-time PID check on each query. `portzilla prune` mitigates this by letting you sweep dead leases on demand; an active daemon is on the [roadmap](docs/ROADMAP.md) to close this gap for good.
|
|
359
|
+
|
|
360
|
+
`portzilla` does not manage processes (it will not start or stop a dev server for you), does not enforce a firewall or sandbox, and does not coordinate ports across machines — see [`docs/PRD.md`](docs/PRD.md) for the full list of non-goals.
|
|
361
|
+
|
|
362
|
+
## Roadmap
|
|
363
|
+
|
|
364
|
+
v0.1 covers `claim`, `ls`, `who`, `release`, `prune`, JSON output, and locked local state. v0.1.x adds the MCP server (`serve --mcp`, documented above) so agents can call `portzilla` natively instead of shelling out. v0.2 adds the kill guard: a harness-agnostic core plus adapters for Claude Code, Cursor, Gemini CLI, Codex CLI, Kimi CLI, OpenCode, and Windsurf, plus a universal `portzilla guard` wrapper for everything else (all documented above). See [`docs/ROADMAP.md`](docs/ROADMAP.md) for the full versioned plan.
|
|
365
|
+
|
|
366
|
+
## License
|
|
367
|
+
|
|
368
|
+
MIT. See [`LICENSE`](LICENSE).
|
package/npm/bin.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
const { spawnSync } = require("node:child_process");
|
|
4
|
+
const { existsSync } = require("node:fs");
|
|
5
|
+
const { join } = require("node:path");
|
|
6
|
+
|
|
7
|
+
const exe = process.platform === "win32" ? "portzilla.exe" : "portzilla";
|
|
8
|
+
const localBinary = join(__dirname, "vendor", exe);
|
|
9
|
+
|
|
10
|
+
if (!existsSync(localBinary)) {
|
|
11
|
+
console.error("portzilla binary is missing. Reinstall the package with: npm install -g portzilla");
|
|
12
|
+
process.exit(1);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const result = spawnSync(localBinary, process.argv.slice(2), { stdio: "inherit" });
|
|
16
|
+
|
|
17
|
+
if (result.error) {
|
|
18
|
+
console.error(result.error.message);
|
|
19
|
+
process.exit(1);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (typeof result.status === "number") {
|
|
23
|
+
process.exit(result.status);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
process.exit(1);
|
package/npm/install.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
const { copyFileSync, createWriteStream, existsSync, mkdirSync, chmodSync, rmSync, readFileSync } = require("node:fs");
|
|
4
|
+
const { tmpdir } = require("node:os");
|
|
5
|
+
const { join } = require("node:path");
|
|
6
|
+
const { spawnSync } = require("node:child_process");
|
|
7
|
+
const https = require("node:https");
|
|
8
|
+
|
|
9
|
+
const pkg = require("../package.json");
|
|
10
|
+
|
|
11
|
+
const repo = "011010/portzilla";
|
|
12
|
+
const version = process.env.PORTZILLA_VERSION || `v${pkg.version}`;
|
|
13
|
+
const binName = process.platform === "win32" ? "portzilla.exe" : "portzilla";
|
|
14
|
+
const vendorDir = join(__dirname, "vendor");
|
|
15
|
+
const vendorBinary = join(vendorDir, binName);
|
|
16
|
+
|
|
17
|
+
function targetTriple() {
|
|
18
|
+
const arch = process.arch === "x64" ? "x86_64" : process.arch === "arm64" ? "aarch64" : null;
|
|
19
|
+
const os =
|
|
20
|
+
process.platform === "linux"
|
|
21
|
+
? "unknown-linux-gnu"
|
|
22
|
+
: process.platform === "darwin"
|
|
23
|
+
? "apple-darwin"
|
|
24
|
+
: process.platform === "win32"
|
|
25
|
+
? "pc-windows-msvc"
|
|
26
|
+
: null;
|
|
27
|
+
|
|
28
|
+
if (!arch || !os) return null;
|
|
29
|
+
return `${arch}-${os}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function download(url, destination) {
|
|
33
|
+
return new Promise((resolve, reject) => {
|
|
34
|
+
const request = https.get(url, (response) => {
|
|
35
|
+
if ([301, 302, 303, 307, 308].includes(response.statusCode)) {
|
|
36
|
+
response.resume();
|
|
37
|
+
download(response.headers.location, destination).then(resolve, reject);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (response.statusCode !== 200) {
|
|
42
|
+
response.resume();
|
|
43
|
+
reject(new Error(`HTTP ${response.statusCode}`));
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const file = createWriteStream(destination);
|
|
48
|
+
response.pipe(file);
|
|
49
|
+
file.on("finish", () => file.close(resolve));
|
|
50
|
+
file.on("error", reject);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
request.on("error", reject);
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function run(command, args, options = {}) {
|
|
58
|
+
return spawnSync(command, args, { stdio: "inherit", ...options });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function verifyChecksum(checksumPath, archivePath) {
|
|
62
|
+
const expected = readFileSync(checksumPath, "utf8").trim().split(/\s+/)[0].toLowerCase();
|
|
63
|
+
const actual = require("node:crypto")
|
|
64
|
+
.createHash("sha256")
|
|
65
|
+
.update(readFileSync(archivePath))
|
|
66
|
+
.digest("hex");
|
|
67
|
+
if (!/^[a-f0-9]{64}$/.test(expected) || expected !== actual) {
|
|
68
|
+
throw new Error("release checksum mismatch");
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function installWithCargo() {
|
|
73
|
+
const cargo = run("cargo", ["--version"], { stdio: "ignore" });
|
|
74
|
+
if (cargo.status !== 0) {
|
|
75
|
+
console.warn("portzilla npm install: no release asset found and cargo is not installed.");
|
|
76
|
+
console.warn("Install Rust from https://rustup.rs, or install via: cargo install portzilla");
|
|
77
|
+
process.exit(1);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const cargoRoot = join(__dirname, "cargo-root");
|
|
81
|
+
rmSync(cargoRoot, { recursive: true, force: true });
|
|
82
|
+
|
|
83
|
+
const cargoArgs = ["install", "portzilla", "--root", cargoRoot];
|
|
84
|
+
if (version !== "latest") cargoArgs.push("--version", version.replace(/^v/, ""));
|
|
85
|
+
|
|
86
|
+
const result = run("cargo", cargoArgs);
|
|
87
|
+
if (result.status !== 0) process.exit(result.status ?? 1);
|
|
88
|
+
|
|
89
|
+
const cargoBinary = join(cargoRoot, "bin", binName);
|
|
90
|
+
if (!existsSync(cargoBinary)) {
|
|
91
|
+
console.error(`portzilla npm install: cargo succeeded but did not create ${cargoBinary}`);
|
|
92
|
+
process.exit(1);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
mkdirSync(vendorDir, { recursive: true });
|
|
96
|
+
copyFileSync(cargoBinary, vendorBinary);
|
|
97
|
+
if (process.platform !== "win32") chmodSync(vendorBinary, 0o755);
|
|
98
|
+
rmSync(cargoRoot, { recursive: true, force: true });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function main() {
|
|
102
|
+
const triple = targetTriple();
|
|
103
|
+
if (!triple) {
|
|
104
|
+
console.warn(`portzilla npm install: unsupported platform ${process.platform}/${process.arch}; falling back to cargo.`);
|
|
105
|
+
installWithCargo();
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const ext = process.platform === "win32" ? "zip" : "tar.gz";
|
|
110
|
+
const archive = join(tmpdir(), `portzilla-${process.pid}.${ext}`);
|
|
111
|
+
const checksum = `${archive}.sha256`;
|
|
112
|
+
const tag = version === "latest" ? "latest" : version.startsWith("v") ? version : `v${version}`;
|
|
113
|
+
const url =
|
|
114
|
+
tag === "latest"
|
|
115
|
+
? `https://github.com/${repo}/releases/latest/download/portzilla-${triple}.${ext}`
|
|
116
|
+
: `https://github.com/${repo}/releases/download/${tag}/portzilla-${triple}.${ext}`;
|
|
117
|
+
|
|
118
|
+
try {
|
|
119
|
+
await download(url, archive);
|
|
120
|
+
await download(`${url}.sha256`, checksum);
|
|
121
|
+
verifyChecksum(checksum, archive);
|
|
122
|
+
mkdirSync(vendorDir, { recursive: true });
|
|
123
|
+
|
|
124
|
+
if (process.platform === "win32") {
|
|
125
|
+
const result = run("powershell", [
|
|
126
|
+
"-NoProfile",
|
|
127
|
+
"-Command",
|
|
128
|
+
`Expand-Archive -LiteralPath '${archive.replace(/'/g, "''")}' -DestinationPath '${vendorDir.replace(/'/g, "''")}' -Force`,
|
|
129
|
+
]);
|
|
130
|
+
if (result.status !== 0) throw new Error("failed to extract zip archive");
|
|
131
|
+
} else {
|
|
132
|
+
const result = run("tar", ["-xzf", archive, "-C", vendorDir]);
|
|
133
|
+
if (result.status !== 0) throw new Error("failed to extract tar archive");
|
|
134
|
+
chmodSync(vendorBinary, 0o755);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
rmSync(archive, { force: true });
|
|
138
|
+
rmSync(checksum, { force: true });
|
|
139
|
+
if (!existsSync(vendorBinary)) throw new Error(`missing extracted binary: ${vendorBinary}`);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
rmSync(archive, { force: true });
|
|
142
|
+
rmSync(checksum, { force: true });
|
|
143
|
+
console.warn(`portzilla npm install: ${error.message}; falling back to cargo.`);
|
|
144
|
+
installWithCargo();
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
main();
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "portzilla",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Port and process lease coordinator for parallel AI coding-agent sessions",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"homepage": "https://github.com/011010/portzilla",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/011010/portzilla.git"
|
|
10
|
+
},
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/011010/portzilla/issues"
|
|
13
|
+
},
|
|
14
|
+
"bin": {
|
|
15
|
+
"portzilla": "npm/bin.js"
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"postinstall": "node npm/install.js"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"npm/bin.js",
|
|
22
|
+
"npm/install.js",
|
|
23
|
+
"README.md",
|
|
24
|
+
"LICENSE"
|
|
25
|
+
],
|
|
26
|
+
"keywords": [
|
|
27
|
+
"port",
|
|
28
|
+
"cli",
|
|
29
|
+
"agent",
|
|
30
|
+
"dev-tools",
|
|
31
|
+
"process"
|
|
32
|
+
],
|
|
33
|
+
"engines": {
|
|
34
|
+
"node": ">=18"
|
|
35
|
+
}
|
|
36
|
+
}
|