phiward 0.2.0b1__py3-none-any.whl

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.
Files changed (53) hide show
  1. phiward/__init__.py +8 -0
  2. phiward/__main__.py +5 -0
  3. phiward/_toml.py +211 -0
  4. phiward/adapters/__init__.py +105 -0
  5. phiward/adapters/claude.py +429 -0
  6. phiward/broker.py +831 -0
  7. phiward/carryover.py +1613 -0
  8. phiward/claude_settings.py +1307 -0
  9. phiward/cli.py +110 -0
  10. phiward/config.py +936 -0
  11. phiward/confine.py +476 -0
  12. phiward/copying.py +533 -0
  13. phiward/core.py +105 -0
  14. phiward/data/agents-section.md +43 -0
  15. phiward/doctor.py +1132 -0
  16. phiward/fasthook.py +70 -0
  17. phiward/fsinfo.py +241 -0
  18. phiward/gateway.py +159 -0
  19. phiward/githooks.py +248 -0
  20. phiward/guards/__init__.py +0 -0
  21. phiward/guards/protected_paths.py +1138 -0
  22. phiward/hidden.py +281 -0
  23. phiward/init.py +155 -0
  24. phiward/install.py +828 -0
  25. phiward/inventory.py +173 -0
  26. phiward/mcp.py +186 -0
  27. phiward/mcp_config.py +1736 -0
  28. phiward/names.py +5 -0
  29. phiward/packs/dates.toml +17 -0
  30. phiward/packs/genomics.toml +51 -0
  31. phiward/packs/msk.toml +32 -0
  32. phiward/pathid.py +403 -0
  33. phiward/pathmatch.py +98 -0
  34. phiward/paths.py +942 -0
  35. phiward/pin.py +214 -0
  36. phiward/procinfo.py +73 -0
  37. phiward/remote.py +448 -0
  38. phiward/run.py +788 -0
  39. phiward/safeio.py +84 -0
  40. phiward/sanitize.py +691 -0
  41. phiward/selfcheck.py +1506 -0
  42. phiward/service.py +321 -0
  43. phiward/session_note.py +86 -0
  44. phiward/setup_cmd.py +886 -0
  45. phiward/shell.py +504 -0
  46. phiward/wholetool.py +1463 -0
  47. phiward-0.2.0b1.dist-info/METADATA +147 -0
  48. phiward-0.2.0b1.dist-info/RECORD +53 -0
  49. phiward-0.2.0b1.dist-info/WHEEL +5 -0
  50. phiward-0.2.0b1.dist-info/entry_points.txt +3 -0
  51. phiward-0.2.0b1.dist-info/licenses/LICENSE +662 -0
  52. phiward-0.2.0b1.dist-info/licenses/NOTICE +16 -0
  53. phiward-0.2.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,429 @@
1
+ """The Claude Code adapter (PreToolUse). It also reads the payloads of Copilot, which runs the
2
+ hooks in a repository's `.claude/settings.json` with its own tool names and camelCase fields.
3
+
4
+ Reply: allow is silence (exit 0, no output: "staying silent doesn't approve" the call); deny is
5
+ exit 2 with the reason on stderr, which wins over any JSON; ask is the tool's JSON ask reply.
6
+ Any fault in here denies (exit 2): a bug must not let an action through.
7
+ """
8
+
9
+ import json
10
+ import re
11
+ import os
12
+ from typing import Any, Dict, Iterable, List, Optional, TextIO, Tuple
13
+
14
+ from phiward import pathid
15
+ from phiward.core import (ASK, DENY, FILE_READ, FILE_SEARCH, FILE_WRITE, OTHER, SHELL,
16
+ Action)
17
+
18
+ # phiward's own MCP tools, as a user server (`phiward`) or from the plugin
19
+ PHIWARD_MCP = re.compile(r"mcp__(?:plugin_phiward_)?phiward__phiward_(?:run|copy|remote|check|doctor)")
20
+ # Monitor runs shell commands too (Claude Code's sandbox covers it like Bash)
21
+ SHELL_TOOLS = {"Bash", "bash", "Monitor"}
22
+ # tools with a shell in their name that run no command: they read or stop one already started
23
+ NOT_SHELLS = {"bashoutput", "killshell", "killbash", "read_bash", "stop_bash", "list_bash"}
24
+ # a tool outside Claude Code's sandbox that runs commands, by the words of its name (its last
25
+ # part, split on `_`, `-` and camelCase): a shell word, or an action with what it acts on
26
+ SHELL_WORDS = {"bash", "shell", "pwsh", "powershell", "terminal", "exec", "execute", "eval",
27
+ "sh", "zsh", "repl", "osascript", "applescript", "subprocess"}
28
+ EXEC_WORDS = {"exec", "execute", "eval"}
29
+ RUN_VERBS = {"run", "start", "spawn", "launch", "create", "invoke"}
30
+ RUN_OBJECTS = {"command", "commands", "cmd", "script", "scripts", "process", "program", "code",
31
+ "python", "node"}
32
+ IO_VERBS = {"interact", "send", "write"} # input to a running process or terminal
33
+ IO_OBJECTS = {"process", "keys", "stdin", "terminal"}
34
+ # a first word that only reads or stops (`read_terminal`, `search_shell_history`), unless an
35
+ # action follows (`list_and_execute`)
36
+ READ_VERBS = {"read", "list", "get", "show", "kill", "stop", "close", "clear", "tail", "search"}
37
+ # JavaScript in a browser page runs there, not in this machine's shell: only by the names the
38
+ # operator's tools carry (the tool's or its server's), never by the agent's input
39
+ JS_WORDS = {"javascript", "js"}
40
+ PAGE_WORDS = {"browser", "page", "tab", "chrome", "playwright", "puppeteer", "firefox"}
41
+ LOCAL_RUNNERS = {"bash", "shell", "terminal", "command", "commands", "cmd", "script", "process",
42
+ "python", "node", "repl", "subprocess", "osascript", "applescript"}
43
+ # the fields a tool that only names a terminal may take and still run nothing
44
+ TERMINAL_FIELDS = {"cwd", "title", "name", "profile"}
45
+ # the one form such a tool may take for a gateway call: one command field, or one argv list,
46
+ # and nothing that changes what runs; other fields only from this list, each of its type
47
+ COMMAND_FIELDS = ("command", "cmd", "script", "input")
48
+ HARMLESS_FIELDS = {"description": str, "explanation": str, "title": str,
49
+ "timeout": (int, float), "timeout_ms": (int, float),
50
+ "isBackground": bool, "is_background": bool}
51
+
52
+
53
+ def _name_words(tool: str) -> List[str]:
54
+ part = tool.rsplit("__", 1)[-1] if tool.startswith("mcp__") else tool
55
+ part = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", part)
56
+ return [w.casefold() for w in re.split(r"[_\-\s.]+", part) if w]
57
+
58
+
59
+ APP_FLAGS = {"_consent"} # the app's own yes-or-no fields that run nothing
60
+
61
+
62
+ def _app_flag(key: Any, value: Any) -> bool:
63
+ """A field the app adds for itself (`_consent`), holding only a yes or no. Any other field,
64
+ `_`-prefixed or not, may change what runs."""
65
+ return key in APP_FLAGS and isinstance(value, bool)
66
+
67
+
68
+ def says_shell(tool: str, inp: Optional[Dict[str, Any]] = None) -> bool:
69
+ """Whether a tool's name says it runs commands on this machine (Copilot's `run_in_terminal`
70
+ and `write_bash`, an MCP server's `run_command`, `execute_command`, `executeCode`,
71
+ `start_process`, `run_python`, `send_keys`). `inp`: the tool's input, which decides for a
72
+ name that only names a terminal (`open_terminal_tab` runs a command only when given one)."""
73
+ inp = inp or {}
74
+ if tool.lower() in NOT_SHELLS:
75
+ return False
76
+ words = _name_words(tool)
77
+ if not words:
78
+ return False
79
+ ws, rest = set(words), set(words[1:])
80
+ acts = RUN_VERBS | IO_VERBS | EXEC_WORDS
81
+ if words[0] in READ_VERBS and not rest & acts:
82
+ return False
83
+ server = set(_name_words(tool.split("__")[1])) if tool.startswith("mcp__") and \
84
+ tool.count("__") >= 2 else set()
85
+ if ws & JS_WORDS and (ws | server) & PAGE_WORDS and not ws & LOCAL_RUNNERS:
86
+ return False
87
+ shell = ws & SHELL_WORDS
88
+ if shell:
89
+ given = {k for k in inp if not _app_flag(k, inp[k])}
90
+ if shell <= {"terminal"} and not ws & acts and given <= TERMINAL_FIELDS:
91
+ return False # names a terminal and is given nothing to run (`open_terminal_tab`)
92
+ return True
93
+ return bool(ws & RUN_VERBS and ws & RUN_OBJECTS) or bool(ws & IO_VERBS and ws & IO_OBJECTS)
94
+
95
+
96
+ def exact_command(inp: Dict[str, Any], cwd: str) -> Tuple[str, str]:
97
+ """(the command, "") when a shell tool's input has the one exact form; else ("", why)."""
98
+ import shlex
99
+ found: List[str] = []
100
+ for k, v in inp.items():
101
+ if k in COMMAND_FIELDS:
102
+ if not isinstance(v, str):
103
+ return "", f"its `{k}` is not one string"
104
+ found.append(v)
105
+ elif k == "argv":
106
+ if not (isinstance(v, list) and v and all(isinstance(a, str) for a in v)):
107
+ return "", "its `argv` is not one list of strings"
108
+ found.append(shlex.join(v))
109
+ elif k == "cwd":
110
+ if not (isinstance(v, str) and os.path.normpath(v) == os.path.normpath(cwd)):
111
+ return "", "it names another folder to run in (`cwd`)"
112
+ elif _app_flag(k, v):
113
+ continue # the app's own flag (`_consent`): a yes or no, it runs nothing
114
+ elif k not in HARMLESS_FIELDS:
115
+ return "", f"it has a field that can change what runs (`{k}`)"
116
+ elif isinstance(v, bool) and HARMLESS_FIELDS[k] is not bool or \
117
+ not isinstance(v, HARMLESS_FIELDS[k]):
118
+ return "", f"its `{k}` is not of the expected type"
119
+ if len(found) != 1:
120
+ return "", "it does not hold exactly one command"
121
+ body = found[0][:-1] if found[0].endswith("\n") else found[0]
122
+ items = inp["argv"] if isinstance(inp.get("argv"), list) else [body]
123
+ if any(re.search(r"[\x00-\x1f\x7f\x85\u2028\u2029]", x) for x in items):
124
+ # a server may run each line on its own, or join argv into a shell line
125
+ return "", "its command holds a line break or another control character"
126
+ return found[0], ""
127
+
128
+
129
+ READ_TOOLS = {"Read", "NotebookRead", "view"}
130
+ SEARCH_TOOLS = {"Grep", "Glob", "LS", "grep", "glob"}
131
+ WRITE_TOOLS = {"Edit", "MultiEdit", "Write", "NotebookEdit", "create", "edit"}
132
+ # the modes in which Claude Code is known to show the person an "ask" (its docs): in any other
133
+ # (auto, a missing or a future mode) an ask is refused, so it never passes unseen
134
+ ASK_MODES = {"default", "acceptEdits", "plan"}
135
+ # Claude Code's built-in tools that run nothing and read no file: their input is text for the
136
+ # model, the person or a subagent (a subagent's own tool calls reach the hook), so a path in it
137
+ # is not checked. Closed, exact names; a Claude Code payload only.
138
+ TEXT_ONLY_TOOLS = {"Agent", "Task", "TodoWrite", "TaskCreate", "TaskUpdate", "TaskList",
139
+ "TaskGet", "AskUserQuestion", "EnterPlanMode", "ExitPlanMode",
140
+ "SubagentHandback", "SendMessage", "ToolSearch"}
141
+
142
+
143
+ # the app's own tools that start the project's code outside Claude Code's sandbox (checked in the
144
+ # desktop app: the preview ran `launch.json`'s command unsandboxed), by exact name, and for the
145
+ # simulator's `control` by its action. What each one starts goes into the prompt. Decided name by
146
+ # name from the app's tool list; a tool that only steers a page or a session is not here
147
+ APP_STARTERS = {
148
+ "mcp__Claude_Browser__preview_start": "the command that .claude/launch.json names",
149
+ "mcp__Claude_Code_iOS_Simulator__build": "the project's build, with its build scripts",
150
+ "mcp__ccd_directory__change_directory": "a session in another folder, which phiward's "
151
+ "settings checks do not see",
152
+ "mcp__ccd_directory__request_directory": "a session in another folder, which phiward's "
153
+ "settings checks do not see",
154
+ }
155
+ APP_STARTER_ACTIONS = {("mcp__Claude_Code_iOS_Simulator__control", "launch"):
156
+ "an app built from the project"}
157
+ # tools that name files or folders by these keys: the app's browsers (a `file:` URL) and tools
158
+ # that are not MCP tools (Copilot's `list_dir`, `str_replace_editor`). Judged as a search: a
159
+ # folder above protected data is refused, as for Grep
160
+ APP_FILE_SERVERS = {"Claude_Browser", "claude-in-chrome", "Control_Chrome"}
161
+ PATH_KEYS = ("path", "filePath", "file_path", "dir", "directory", "uri", "url")
162
+ PATH_LIST_KEYS = ("paths", "filePaths", "files")
163
+ # Copilot's workspace searches, which take no folder: they search the working folder
164
+ WORKSPACE_SEARCHES = {"grep_search", "file_search", "semantic_search"}
165
+
166
+
167
+ def _named_paths(inp: Dict[str, Any], urls_only: bool = False) -> List[str]:
168
+ """The paths a tool's input names by PATH_KEYS and PATH_LIST_KEYS: plain paths, and the path
169
+ of a `file:` URL (also behind `view-source:`), percent-decoded, spelled as a browser reads
170
+ it (tabs and line breaks dropped, control characters and spaces at the ends stripped, `\\`
171
+ as `/`). A web URL names no path; `urls_only` (a browser): only `file:` URLs count."""
172
+ from urllib.parse import unquote, urlparse
173
+ vals: List[str] = []
174
+ if urls_only:
175
+ # a browser: every URL field at any depth (a batch's actions[].input.url)
176
+ vals = list(_url_fields(inp))
177
+ for k in PATH_KEYS:
178
+ if isinstance(inp.get(k), str):
179
+ vals.append(inp[k])
180
+ for k in PATH_LIST_KEYS:
181
+ if isinstance(inp.get(k), list):
182
+ vals += [v for v in inp[k] if isinstance(v, str)]
183
+ out: List[str] = []
184
+ for v in vals:
185
+ # a URL as a browser reads it: tabs and line breaks dropped, control characters and
186
+ # spaces at the ends stripped, `\\` as `/`. A plain path is taken as it is
187
+ url = re.sub(r"[\t\r\n]", "", v).strip("".join(chr(c) for c in range(0x21)))
188
+ low = url.lower()
189
+ while low.startswith("view-source:"):
190
+ url = url[len("view-source:"):].strip("".join(chr(c) for c in range(0x21)))
191
+ low = url.lower()
192
+ if low.startswith("file:"):
193
+ path = unquote(urlparse(url.replace("\\", "/")).path) or "/"
194
+ out.append(path if path.startswith("/") else "/" + path) # always absolute
195
+ continue
196
+ if urls_only or re.match(WEB_SCHEMES, v.strip().lower()):
197
+ continue # https:, about:, data: name no file here; a browser's plain value either
198
+ if v:
199
+ out.append(v)
200
+ return out
201
+
202
+
203
+ # URL schemes that name no file on this machine; anything else with a colon (`k:v`) is a name
204
+ WEB_SCHEMES = r"^(https?|ftps?|wss?|data|about|mailto|chrome|edge|blob|javascript):"
205
+ URL_KEYS = ("url", "uri", "href", "src", "target", "path", "filePath", "file_path")
206
+
207
+
208
+ def _url_fields(value: Any) -> Iterable[str]:
209
+ """The values of URL_KEYS at any depth of a tool's input (not every string: a search
210
+ pattern or a page's text is no address)."""
211
+ if isinstance(value, dict):
212
+ for k, v in value.items():
213
+ if k in URL_KEYS and isinstance(v, str):
214
+ yield v
215
+ else:
216
+ yield from _url_fields(v)
217
+ elif isinstance(value, list):
218
+ for v in value:
219
+ yield from _url_fields(v)
220
+
221
+
222
+ def _strings(value: Any) -> Iterable[str]:
223
+ if isinstance(value, str):
224
+ yield value
225
+ elif isinstance(value, dict):
226
+ for v in value.values():
227
+ yield from _strings(v)
228
+ elif isinstance(value, list):
229
+ for v in value:
230
+ yield from _strings(v)
231
+
232
+
233
+ def to_action(payload: Dict[str, Any]) -> Tuple[Action, bool]:
234
+ """The Action, and whether the payload is Copilot's camelCase form."""
235
+ camel = "toolName" in payload and "tool_name" not in payload
236
+ tool = payload.get("tool_name") or payload.get("toolName") or ""
237
+ inp = payload.get("tool_input")
238
+ if inp is None:
239
+ inp = payload.get("toolArgs", {})
240
+ if isinstance(inp, str):
241
+ inp = json.loads(inp) if inp.strip() else {}
242
+ if not isinstance(inp, dict):
243
+ raise ValueError("tool input is not an object")
244
+ cwd = payload.get("cwd") or os.getcwd()
245
+ # Copilot's payload has no mode and shows its ask; Claude Code's, only in ASK_MODES
246
+ can_ask = camel or payload.get("permission_mode") in ASK_MODES
247
+ text = tuple(_strings(inp))
248
+ if not camel and tool in TEXT_ONLY_TOOLS:
249
+ return Action(OTHER, cwd, text=(), tool=tool, can_ask=can_ask), camel
250
+ if tool in SHELL_TOOLS:
251
+ return Action(SHELL, cwd, command=str(inp.get("command", "")), tool=tool,
252
+ can_ask=can_ask), camel
253
+ # every path field a file tool's input holds (a payload with two is judged by both)
254
+ named = tuple(dict.fromkeys(str(inp[k]) for k in ("file_path", "notebook_path", "path")
255
+ if isinstance(inp.get(k), str) and inp.get(k)))
256
+ if tool in READ_TOOLS:
257
+ return Action(FILE_READ, cwd, paths=named, text=text, tool=tool,
258
+ can_ask=can_ask), camel
259
+ if tool in SEARCH_TOOLS:
260
+ base = inp.get("path") or cwd
261
+ # what the search reads: Grep, the folder it walks; Glob, only what its pattern lists
262
+ # below the folder (a Glob limited to `src/**` never lists the rest of the folder)
263
+ ps: List[str] = [base]
264
+ if tool in ("Glob", "glob") and inp.get("pattern"):
265
+ ps = [os.path.join(base, inp["pattern"])]
266
+ return Action(FILE_SEARCH, cwd, paths=tuple(ps), text=text, tool=tool,
267
+ can_ask=can_ask), camel
268
+ if tool in WRITE_TOOLS:
269
+ return Action(FILE_WRITE, cwd, paths=named, text=text, tool=tool,
270
+ can_ask=can_ask, claude_code=not camel), camel
271
+ # the paths a tool names by its path fields: one more check of the action, never another
272
+ # kind of action (a shell or a writer keeps its own rules)
273
+ searches: Tuple[str, ...] = ()
274
+ app_server = (tool or "").split("__")[1] if (tool or "").count("__") >= 2 else ""
275
+ if not (tool or "").startswith("mcp__") or app_server in APP_FILE_SERVERS:
276
+ named_any = _named_paths(inp, urls_only=app_server in APP_FILE_SERVERS)
277
+ if not named_any and tool in WORKSPACE_SEARCHES:
278
+ named_any = [cwd] # a search with no folder searches the working folder
279
+ searches = tuple(named_any)
280
+ starts = APP_STARTERS.get(tool or "") or APP_STARTER_ACTIONS.get(
281
+ (tool or "", inp.get("action") if isinstance(inp.get("action"), str) else ""), "")
282
+ if starts:
283
+ return Action(OTHER, cwd, text=text, tool=tool, can_ask=can_ask, starts=starts,
284
+ searches=searches), camel
285
+ if PHIWARD_MCP.fullmatch(tool or ""):
286
+ # phiward's own gateway tools: they name protected paths by design, as a
287
+ # `phiward run` command does; the broker checks them. An MCP server that only pretends
288
+ # to be phiward is code with the operator's rights already (Mode A) or confined (Mode B)
289
+ return Action(OTHER, cwd, text=(), tool=tool, can_ask=can_ask), camel
290
+ # a tool of an MCP server wrapped in `phiward launch --` runs in the kernel profile: only the
291
+ # text check. A shell-named tool of any other server (or Copilot's terminal tools) runs
292
+ # commands with the operator's rights: one exact gateway call at most
293
+ from phiward import mcp_config
294
+ home = pathid.home()
295
+ project = os.environ.get("CLAUDE_PROJECT_DIR") or cwd
296
+ # which server: by the source Claude Code names (2.1.274 and newer), else by name in the
297
+ # operator's own config only
298
+ sourced = "mcp_server" in payload and (tool or "").startswith("mcp__")
299
+ if sourced:
300
+ configured: Optional[mcp_config.Server] = mcp_config.classify(
301
+ payload.get("mcp_server"), tool or "", project, home)
302
+ else:
303
+ configured = mcp_config.server_of(tool or "", project, home, trust_project=False)
304
+ # wrapped only when it really runs wrapped: a live launcher of its command, a child of this
305
+ # Claude Code (a server wrapped in the config after it started still runs bare)
306
+ server = mcp_config.trusted(configured, project, home)
307
+ if (server is None or not server.wrapped) and says_shell(tool or "", inp):
308
+ cmd, why = exact_command(inp, cwd)
309
+ return Action(SHELL, cwd, command=cmd, text=text, tool=tool, can_ask=can_ask,
310
+ shape=why, advice=_advice(tool or "", configured, sourced,
311
+ _states(configured, project, home)),
312
+ searches=searches), camel
313
+ # anything else (MCP tools, web tools): its text is checked
314
+ return Action(OTHER, cwd, text=text, tool=tool, can_ask=can_ask,
315
+ remote=bool(server is not None and server.remote), searches=searches), camel
316
+
317
+
318
+ def _states(configured: Any, project: str, home: str) -> Tuple[set, List[str]]:
319
+ """The states of a server's entries (`mcp_config.entry_state`), and what changes what runs in
320
+ a `changed` one: from the entries Claude Code named, else the operator's own scopes."""
321
+ from phiward import mcp_config
322
+ if configured is None:
323
+ return set(), []
324
+ specs: List[Any] = []
325
+ for text in configured.specs:
326
+ try:
327
+ specs.append(json.loads(text))
328
+ except ValueError:
329
+ pass
330
+ if not configured.specs:
331
+ specs = [e.spec for e in mcp_config.entries(project, home)
332
+ if e.name == configured.name and e.scope in ("user", "local")]
333
+ states = {mcp_config.placed_state(x, project, home) for x in specs}
334
+ keys: List[str] = []
335
+ for x in specs:
336
+ if mcp_config.entry_state(x) == "changed":
337
+ keys += [k for k in mcp_config._changed_by(x) if k not in keys]
338
+ return states, keys
339
+
340
+
341
+ def _advice(tool: str, configured: Any, sourced: bool,
342
+ states: Tuple[set, List[str]] = (set(), [])) -> str:
343
+ """What the operator can do about a refused shell-named tool, by where its server is from and
344
+ what its entries are (`_states`): the same answer as `phiward mcp list` gives."""
345
+ from phiward import mcp_config
346
+ found, keys = states
347
+ if not tool.startswith("mcp__"):
348
+ return "Work on protected data through the gateway."
349
+ old = ("" if sourced else
350
+ " (This Claude Code does not say which server a tool belongs to, so a server of "
351
+ f"`.mcp.json` counts as bare: update Claude Code to "
352
+ f"{'.'.join(map(str, mcp_config.MIN_SOURCE_VERSION))} or newer.)")
353
+ if configured is None:
354
+ return ("phiward cannot see this server's command (a plugin's, a managed or a connector "
355
+ "server), so it cannot be wrapped: use a gateway call in Bash (`phiward run -- "
356
+ "CMD`) instead." + old)
357
+ name = mcp_config.shown(configured.name)
358
+ src = configured.source
359
+ if getattr(configured, "untrusted", False) and not sourced:
360
+ return (f"`{name}` is defined in the project's `.mcp.json`, which counts as bare when "
361
+ "Claude Code does not say which server a tool belongs to: its command tools may "
362
+ "make only gateway calls: use one in Bash (`phiward run -- CMD`)." + old)
363
+ if getattr(configured, "here", False):
364
+ return (f"`{name}` listens on this machine (its URL): it runs outside Claude Code, so "
365
+ "phiward cannot wrap it. Its command tools may make only gateway calls: use one "
366
+ "in Bash (`phiward run -- CMD`)." + old)
367
+ if getattr(configured, "unwrappable", False):
368
+ return (f"`{name}` has no command phiward can read, so it cannot be wrapped. Its command "
369
+ "tools may make only gateway calls: use one in Bash (`phiward run -- CMD`)." + old)
370
+ if "changed" in found:
371
+ return (f"`{name}` runs under `phiward launch`, but its entry sets {', '.join(keys)}, "
372
+ "which changes what runs, so it counts as not wrapped: the operator can remove "
373
+ "that from its entry, then start Claude Code again." + old)
374
+ stuck = mcp_config.cannot_wrap_why(found) if found else ""
375
+ if stuck:
376
+ # as `phiward mcp list` says it: no entry of the name that `wrap` can change
377
+ return (f"`{name}` {stuck}, so it cannot be wrapped. Its command tools may make only "
378
+ "gateway calls: use one in Bash (`phiward run -- CMD`)." + old)
379
+ if "copied" in found:
380
+ return (f"`{name}` has an entry id that another entry has too (a copy), so phiward cannot "
381
+ f"tell their launchers apart: the operator gives it its own (`phiward mcp wrap "
382
+ f"{name}`), then starts Claude Code again." + old)
383
+ if configured.wrapped:
384
+ return ("Its server is wrapped in the config, but it still runs as it was started, or "
385
+ "its profile was built from other settings (its entry's `env`, or the phiward "
386
+ "config or your credentials changed since it started): the operator starts "
387
+ "Claude Code again." + old)
388
+ if sourced and src == "plugin" and configured.specs:
389
+ return (f"`{name}` is a plugin's server, which phiward does not wrap (an update replaces "
390
+ "the plugin's files): use a gateway call in Bash (`phiward run -- CMD`) instead.")
391
+ if (sourced and src in mcp_config.CONFIG_SOURCES and configured.specs) or not sourced:
392
+ return (f"The operator can wrap its server (`phiward mcp wrap {name}`), then start Claude "
393
+ "Code again." + old)
394
+ return (f"phiward cannot see this server's command (`{name}`, source `{mcp_config.shown(src)}`"
395
+ "), so it cannot be wrapped: use a gateway call in Bash (`phiward run -- CMD`) "
396
+ "instead.")
397
+
398
+
399
+ def main(fin: TextIO, fout: TextIO, ferr: TextIO) -> int:
400
+ try:
401
+ from phiward.adapters import decide
402
+ payload = json.load(fin)
403
+ if not isinstance(payload, dict):
404
+ raise ValueError("payload is not an object")
405
+ action, camel = to_action(payload)
406
+ # Only Claude Code's own payload (it carries permission_mode) can be confined by Claude
407
+ # Code's sandbox; Copilot runs the same hooks without it.
408
+ # A call that asks to run outside the sandbox is judged as unconfined, whatever the
409
+ # settings say.
410
+ ti = payload.get("tool_input") if isinstance(payload.get("tool_input"), dict) else {}
411
+ leaves = ti.get("dangerouslyDisableSandbox") not in (None, False)
412
+ claude_code = not camel and "permission_mode" in payload
413
+ d = decide(action, claude_sandbox=claude_code and not leaves)
414
+ except Exception as exc: # noqa: BLE001 - fail closed
415
+ ferr.write(f"phiward: the hook could not decide ({type(exc).__name__}), so the "
416
+ "action is refused. Run `phiward doctor`.\n")
417
+ return 2
418
+ if d.verdict == DENY:
419
+ ferr.write(f"phiward [{d.guard}]: {d.reason}\n")
420
+ return 2
421
+ if d.verdict == ASK:
422
+ if camel:
423
+ reply = {"permissionDecision": "ask", "permissionDecisionReason": d.reason}
424
+ else:
425
+ reply = {"hookSpecificOutput": {"hookEventName": "PreToolUse",
426
+ "permissionDecision": "ask",
427
+ "permissionDecisionReason": d.reason}}
428
+ fout.write(json.dumps(reply) + "\n")
429
+ return 0