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
phiward/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """phiward: keep protected data out of what an AI coding agent's tools print.
2
+
3
+ The core is the standard library only, with no network and no telemetry. An adapter turns a tool's
4
+ hook payload into an `Action`; the dispatcher runs every enabled guard on it and returns one
5
+ `Decision`; the adapter turns that into the tool's reply.
6
+ """
7
+
8
+ __version__ = "0.2.0b1"
phiward/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from phiward.cli import main
4
+
5
+ sys.exit(main())
phiward/_toml.py ADDED
@@ -0,0 +1,211 @@
1
+ """A small TOML reader for the config files (Python 3.9 and 3.10 have no tomllib).
2
+
3
+ It reads a subset: comments, `[table]` and `[a.b]` headers, `key = value` lines, and values that
4
+ are strings (basic or literal), integers, booleans, or arrays of these (over several lines too).
5
+ It uses the same parser on every Python version, so a file reads the same everywhere. Anything
6
+ outside the subset raises `TomlError`; the caller then fails closed.
7
+ """
8
+
9
+ import re
10
+ from typing import Any, Dict, List, Tuple
11
+
12
+
13
+ class TomlError(ValueError):
14
+ pass
15
+
16
+
17
+ _KEY = re.compile(r"[A-Za-z0-9_-]+")
18
+ _INT = re.compile(r"[+-]?(0|[1-9][0-9_]*)")
19
+ _ESC = {"b": "\b", "t": "\t", "n": "\n", "f": "\f", "r": "\r", '"': '"', "\\": "\\"}
20
+
21
+
22
+ def loads(text: str) -> Dict[str, Any]:
23
+ root: Dict[str, Any] = {}
24
+ table = root
25
+ seen_tables = set()
26
+ p = _Parser(text)
27
+ while True:
28
+ p.skip_blank_lines()
29
+ if p.at_end():
30
+ return root
31
+ line_no = p.line
32
+ if p.peek() == "[":
33
+ p.pos += 1
34
+ if p.peek() == "[":
35
+ raise TomlError(f"line {line_no}: arrays of tables are not supported")
36
+ names = p.dotted_key()
37
+ p.skip_ws()
38
+ p.expect("]")
39
+ p.end_of_line()
40
+ if tuple(names) in seen_tables:
41
+ raise TomlError(f"line {line_no}: table [{'.'.join(names)}] appears twice")
42
+ seen_tables.add(tuple(names))
43
+ table = root
44
+ for n in names:
45
+ nxt = table.setdefault(n, {})
46
+ if not isinstance(nxt, dict):
47
+ raise TomlError(f"line {line_no}: '{n}' is not a table")
48
+ table = nxt
49
+ continue
50
+ names = p.dotted_key()
51
+ p.skip_ws()
52
+ p.expect("=")
53
+ p.skip_ws()
54
+ value = p.value()
55
+ p.end_of_line()
56
+ target = table
57
+ for n in names[:-1]:
58
+ target = target.setdefault(n, {})
59
+ if not isinstance(target, dict):
60
+ raise TomlError(f"line {line_no}: '{n}' is not a table")
61
+ if names[-1] in target:
62
+ raise TomlError(f"line {line_no}: key '{names[-1]}' appears twice")
63
+ target[names[-1]] = value
64
+
65
+
66
+ class _Parser:
67
+ def __init__(self, text: str):
68
+ self.s = text.replace("\r\n", "\n")
69
+ self.pos = 0
70
+
71
+ @property
72
+ def line(self) -> int:
73
+ return self.s.count("\n", 0, self.pos) + 1
74
+
75
+ def at_end(self) -> bool:
76
+ return self.pos >= len(self.s)
77
+
78
+ def peek(self) -> str:
79
+ return self.s[self.pos] if self.pos < len(self.s) else ""
80
+
81
+ def expect(self, ch: str) -> None:
82
+ if self.peek() != ch:
83
+ raise TomlError(f"line {self.line}: expected '{ch}'")
84
+ self.pos += 1
85
+
86
+ def skip_ws(self) -> None:
87
+ while self.peek() in (" ", "\t") and self.peek():
88
+ self.pos += 1
89
+
90
+ def skip_comment(self) -> None:
91
+ if self.peek() == "#":
92
+ while self.peek() and self.peek() != "\n":
93
+ self.pos += 1
94
+
95
+ def skip_blank_lines(self) -> None:
96
+ while not self.at_end():
97
+ self.skip_ws()
98
+ self.skip_comment()
99
+ if self.peek() == "\n":
100
+ self.pos += 1
101
+ else:
102
+ return
103
+
104
+ def end_of_line(self) -> None:
105
+ self.skip_ws()
106
+ self.skip_comment()
107
+ if self.peek() not in ("\n", ""):
108
+ raise TomlError(f"line {self.line}: unexpected text after the value")
109
+ if self.peek() == "\n":
110
+ self.pos += 1
111
+
112
+ def key(self) -> str:
113
+ if self.peek() in ('"', "'"):
114
+ return self.string()
115
+ m = _KEY.match(self.s, self.pos)
116
+ if not m:
117
+ raise TomlError(f"line {self.line}: expected a key")
118
+ self.pos = m.end()
119
+ return m.group(0)
120
+
121
+ def dotted_key(self) -> List[str]:
122
+ self.skip_ws()
123
+ names = [self.key()]
124
+ while True:
125
+ self.skip_ws()
126
+ if self.peek() != ".":
127
+ return names
128
+ self.pos += 1
129
+ self.skip_ws()
130
+ names.append(self.key())
131
+
132
+ def string(self) -> str:
133
+ q = self.peek()
134
+ if self.s.startswith(q * 3, self.pos):
135
+ raise TomlError(f"line {self.line}: multi-line strings are not supported")
136
+ self.pos += 1
137
+ out = []
138
+ while True:
139
+ ch = self.peek()
140
+ if ch in ("", "\n"):
141
+ raise TomlError(f"line {self.line}: a string is not closed")
142
+ self.pos += 1
143
+ if ch == q:
144
+ return "".join(out)
145
+ if ch == "\\" and q == '"':
146
+ e = self.peek()
147
+ self.pos += 1
148
+ if e in _ESC:
149
+ out.append(_ESC[e])
150
+ elif e in ("u", "U"):
151
+ n = 4 if e == "u" else 8
152
+ hexs = self.s[self.pos:self.pos + n]
153
+ if not re.fullmatch(r"[0-9A-Fa-f]{%d}" % n, hexs):
154
+ raise TomlError(f"line {self.line}: bad unicode escape")
155
+ out.append(chr(int(hexs, 16)))
156
+ self.pos += n
157
+ else:
158
+ raise TomlError(f"line {self.line}: bad escape '\\{e}'")
159
+ else:
160
+ out.append(ch)
161
+
162
+ def value(self) -> Any:
163
+ ch = self.peek()
164
+ if ch in ('"', "'"):
165
+ return self.string()
166
+ if ch == "[":
167
+ return self.array()
168
+ for word, val in (("true", True), ("false", False)):
169
+ if self.s.startswith(word, self.pos):
170
+ self.pos += len(word)
171
+ return val
172
+ m = _INT.match(self.s, self.pos)
173
+ if m:
174
+ end = m.end()
175
+ if end < len(self.s) and self.s[end] not in " \t\n#,]":
176
+ raise TomlError(f"line {self.line}: only whole numbers are supported")
177
+ self.pos = end
178
+ return int(m.group(0).replace("_", ""))
179
+ raise TomlError(f"line {self.line}: unsupported value")
180
+
181
+ def array(self) -> List[Any]:
182
+ self.expect("[")
183
+ items: List[Any] = []
184
+ while True:
185
+ self._skip_array_space()
186
+ if self.peek() == "]":
187
+ self.pos += 1
188
+ return items
189
+ items.append(self.value())
190
+ self._skip_array_space()
191
+ if self.peek() == ",":
192
+ self.pos += 1
193
+ elif self.peek() != "]":
194
+ raise TomlError(f"line {self.line}: expected ',' or ']' in an array")
195
+
196
+ def _skip_array_space(self) -> None:
197
+ while True:
198
+ self.skip_ws()
199
+ self.skip_comment()
200
+ if self.peek() == "\n":
201
+ self.pos += 1
202
+ else:
203
+ return
204
+
205
+
206
+ def load_file(path: str, follow: bool = True) -> Tuple[Dict[str, Any], str]:
207
+ """Parse a file, read safely (safeio: no blocking, a regular file, bounded; with
208
+ `follow=False`, not a link)."""
209
+ from phiward import safeio
210
+ text = safeio.read_text(path, limit=1024 * 1024, follow=follow)
211
+ return loads(text), text
@@ -0,0 +1,105 @@
1
+ """Adapters: translate a tool's hook payload into an Action and a Decision into the tool's reply.
2
+ No policy lives here."""
3
+
4
+ import os
5
+ import sys
6
+ from dataclasses import replace
7
+ from typing import Dict, List
8
+
9
+ from phiward import config, pathid
10
+ from phiward.core import ALLOW, ASK, SHELL, Action, Decision, Guard, dispatch
11
+ from phiward.guards import protected_paths
12
+
13
+ GUARDS: Dict[str, Guard] = {protected_paths.NAME: protected_paths.check}
14
+
15
+
16
+ def decide(action: Action, claude_sandbox: bool = False) -> Decision:
17
+ """`claude_sandbox`: the call may run in Claude Code's sandbox (the only thing that confines
18
+ a shell call; phiward does not confine the shell itself)."""
19
+ cfg = config.load(action.cwd)
20
+ # only Claude Code's own shell tools run in its sandbox
21
+ claude_sandbox = claude_sandbox and action.tool in ("Bash", "Monitor")
22
+ # also before protected paths exist: the hidden list is guarded the same way
23
+ if claude_sandbox and action.kind == SHELL and not cfg.problem:
24
+ from phiward import claude_settings
25
+ home = pathid.home()
26
+ from phiward import hidden
27
+ secret = [h for h in hidden.paths(None, cfg, session=True) if os.path.lexists(h)]
28
+ # the named project must hold the call (otherwise the settings Claude Code reads may be
29
+ # in a folder that cannot be found from it), and it and every project folder in it
30
+ # above the call must confine it (claude_settings.confining_folders)
31
+ folders = claude_settings.confining_folders(action.cwd, home) or [None]
32
+ if not claude_settings.named_project_holds(action.cwd):
33
+ r = (claude_settings.Reason("Claude Code did not give the hook $CLAUDE_PROJECT_DIR",
34
+ claude_settings.NO_PROJECT_STEP)
35
+ if not os.environ.get("CLAUDE_PROJECT_DIR") else
36
+ claude_settings.Reason("the command runs outside the session's project "
37
+ "($CLAUDE_PROJECT_DIR), whose settings phiward checks",
38
+ claude_settings.OUTSIDE_PROJECT_STEP))
39
+ else:
40
+ r = None
41
+ for p in folders:
42
+ r = claude_settings.confinement_reason(p, home, cfg.all_roots, cfg.patterns,
43
+ config.guard_files(), hidden=secret)
44
+ if r is not None:
45
+ break
46
+ action = replace(action, confined=r is None, unconfined_why=r.text if r else "",
47
+ unconfined_step=r.step if r else "")
48
+ return dispatch(action, cfg, GUARDS)
49
+
50
+
51
+ HOOK_HELP = """usage: phiward hook claude
52
+
53
+ Read a Claude Code hook payload on stdin and reply as Claude Code expects. Claude Code runs it
54
+ before each tool call; `phiward install claude` writes the wiring. It refuses a tool call that
55
+ would read protected data. claude is the only tool for now.
56
+ """
57
+
58
+ CHECK_HELP = """usage: phiward check [--cwd DIR] -- COMMAND...
59
+
60
+ Options:
61
+ --cwd DIR decide as if the command ran in DIR (default: the current folder)
62
+ -h, --help show this help
63
+
64
+ Show what the guard decides for a shell command, and why, as if it ran in Claude Code's
65
+ sandbox (outside it, only gateway calls run). Nothing runs. The exit status is 0 when the
66
+ command is allowed, 1 when it would ask, and 2 when it is refused.
67
+ """
68
+
69
+
70
+ def run_hook(argv: List[str]) -> int:
71
+ if argv[:1] in (["-h"], ["--help"]):
72
+ sys.stdout.write(HOOK_HELP)
73
+ return 0
74
+ if argv[:1] != ["claude"]:
75
+ print("usage: phiward hook claude (claude is the only tool for now)", file=sys.stderr)
76
+ return 2
77
+ from phiward.adapters import claude
78
+ return claude.main(sys.stdin, sys.stdout, sys.stderr)
79
+
80
+
81
+ def run_check(argv: List[str]) -> int:
82
+ """`phiward check [--cwd DIR] -- COMMAND...`: the decision for a shell command."""
83
+ if argv[:1] in (["-h"], ["--help"]):
84
+ sys.stdout.write(CHECK_HELP)
85
+ return 0
86
+ cwd = os.getcwd()
87
+ args = list(argv)
88
+ if args[:1] == ["--cwd"] and len(args) > 1:
89
+ cwd, args = os.path.abspath(args[1]), args[2:]
90
+ if args[:1] == ["--"]:
91
+ args = args[1:]
92
+ if not args:
93
+ print("usage: phiward check [--cwd DIR] -- COMMAND", file=sys.stderr)
94
+ return 2
95
+ # as under Claude Code's sandbox: without it every shell call but the gateway is refused,
96
+ # and that answer would say nothing about the command
97
+ d = decide(Action(SHELL, cwd, command=" ".join(args), confined=True))
98
+ print(d.verdict + (f": {d.reason}" if d.reason else "") +
99
+ " (as in Claude Code's sandbox)")
100
+ return {ALLOW: 0, ASK: 1}.get(d.verdict, 2)
101
+
102
+
103
+ def run_install(argv: List[str]) -> int:
104
+ from phiward import install
105
+ return install.main(argv)