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.
- phiward/__init__.py +8 -0
- phiward/__main__.py +5 -0
- phiward/_toml.py +211 -0
- phiward/adapters/__init__.py +105 -0
- phiward/adapters/claude.py +429 -0
- phiward/broker.py +831 -0
- phiward/carryover.py +1613 -0
- phiward/claude_settings.py +1307 -0
- phiward/cli.py +110 -0
- phiward/config.py +936 -0
- phiward/confine.py +476 -0
- phiward/copying.py +533 -0
- phiward/core.py +105 -0
- phiward/data/agents-section.md +43 -0
- phiward/doctor.py +1132 -0
- phiward/fasthook.py +70 -0
- phiward/fsinfo.py +241 -0
- phiward/gateway.py +159 -0
- phiward/githooks.py +248 -0
- phiward/guards/__init__.py +0 -0
- phiward/guards/protected_paths.py +1138 -0
- phiward/hidden.py +281 -0
- phiward/init.py +155 -0
- phiward/install.py +828 -0
- phiward/inventory.py +173 -0
- phiward/mcp.py +186 -0
- phiward/mcp_config.py +1736 -0
- phiward/names.py +5 -0
- phiward/packs/dates.toml +17 -0
- phiward/packs/genomics.toml +51 -0
- phiward/packs/msk.toml +32 -0
- phiward/pathid.py +403 -0
- phiward/pathmatch.py +98 -0
- phiward/paths.py +942 -0
- phiward/pin.py +214 -0
- phiward/procinfo.py +73 -0
- phiward/remote.py +448 -0
- phiward/run.py +788 -0
- phiward/safeio.py +84 -0
- phiward/sanitize.py +691 -0
- phiward/selfcheck.py +1506 -0
- phiward/service.py +321 -0
- phiward/session_note.py +86 -0
- phiward/setup_cmd.py +886 -0
- phiward/shell.py +504 -0
- phiward/wholetool.py +1463 -0
- phiward-0.2.0b1.dist-info/METADATA +147 -0
- phiward-0.2.0b1.dist-info/RECORD +53 -0
- phiward-0.2.0b1.dist-info/WHEEL +5 -0
- phiward-0.2.0b1.dist-info/entry_points.txt +3 -0
- phiward-0.2.0b1.dist-info/licenses/LICENSE +662 -0
- phiward-0.2.0b1.dist-info/licenses/NOTICE +16 -0
- phiward-0.2.0b1.dist-info/top_level.txt +1 -0
phiward/setup_cmd.py
ADDED
|
@@ -0,0 +1,886 @@
|
|
|
1
|
+
"""`phiward setup`: first-time setup. It asks the operator questions and writes the user
|
|
2
|
+
config. The text users see is HELP below.
|
|
3
|
+
|
|
4
|
+
A prompt is safe here, unlike at run time, because nothing it answers is an approval of what
|
|
5
|
+
the agent asks for: the operator starts it in their own terminal, it writes only the user config
|
|
6
|
+
(which the agent cannot write once the guards are wired), and the result is a file the operator
|
|
7
|
+
reads before it is written and that `doctor` checks afterwards.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import difflib
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import sys
|
|
14
|
+
import tempfile
|
|
15
|
+
from typing import Tuple, Any, Callable, Dict, List, Optional, TextIO
|
|
16
|
+
|
|
17
|
+
from phiward import _toml, config, pathid, safeio
|
|
18
|
+
|
|
19
|
+
USAGE = ("usage: phiward setup [--from TEAM.toml]\n"
|
|
20
|
+
" phiward setup --first-run --root PATH [--root PATH]... [--remote HOST:/PATH]...\n")
|
|
21
|
+
HELP = USAGE + """
|
|
22
|
+
Options:
|
|
23
|
+
--from FILE start from a team template: a config file with shared settings (the
|
|
24
|
+
program list, packs, HPC hosts). Its settings fill in what your config does
|
|
25
|
+
not have; you see the whole file before anything is written
|
|
26
|
+
--first-run write the first user config without questions (see below)
|
|
27
|
+
--root PATH with --first-run: a protected root (a folder with protected data)
|
|
28
|
+
--remote HOST:/PATH with --first-run: a copy remote (a host and an absolute path prefix)
|
|
29
|
+
-h, --help show this help
|
|
30
|
+
|
|
31
|
+
`phiward setup` asks you questions and writes the user config. Run it in your own terminal,
|
|
32
|
+
never through an agent tool. It refuses to run without a terminal on stdin and stdout, and
|
|
33
|
+
the hook refuses it as an agent command.
|
|
34
|
+
|
|
35
|
+
It first asks how you will use phiward: real patient data (a results folder inside your first
|
|
36
|
+
protected folder, the @genomics program list plus your own scripts folder, no network), made-up
|
|
37
|
+
data (open defaults), or every setting (the protected roots, patterns, write places, programs,
|
|
38
|
+
network and copy remotes, one by one). For real data and every setting, it also asks whether
|
|
39
|
+
the shell commands of Claude Code sessions may reach only hosts you list ([network]). Then, if
|
|
40
|
+
you like, the HPC questions. Each answer is
|
|
41
|
+
checked as the config loader checks it; a refused answer is asked again. Then it shows the whole file and the difference from the old
|
|
42
|
+
one. It writes the file only after a yes (mode 0600; the old file is kept as `.bak`). Other
|
|
43
|
+
sections of an existing file are kept. Its comments are not kept (the backup has them).
|
|
44
|
+
|
|
45
|
+
`phiward setup --first-run` writes the first config without questions. An agent may run it
|
|
46
|
+
to set phiward up with you:
|
|
47
|
+
- It works only when no user config exists yet. To change a config later, run
|
|
48
|
+
`phiward setup` in your own terminal.
|
|
49
|
+
- It writes protected roots and copy remotes only. It never writes write places or network
|
|
50
|
+
grants: those stay yours.
|
|
51
|
+
- Give at least one --root. Each root must be an absolute path (or start with ~/), exist,
|
|
52
|
+
have no wildcard, and not be your home or a folder above it.
|
|
53
|
+
- Without a terminal, it refuses when PHIWARD_CONFIG, PHIWARD_SPOOL, XDG_CONFIG_HOME or
|
|
54
|
+
XDG_CACHE_HOME is set. The first config must go to the default place.
|
|
55
|
+
"""
|
|
56
|
+
_REMOTE = re.compile(r"[A-Za-z0-9_.@-]+:/[^\s]*")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ---- writing TOML (the config uses strings, lists of strings, whole numbers and true/false) ----
|
|
60
|
+
|
|
61
|
+
def _quote(v: str) -> str:
|
|
62
|
+
"""A TOML basic string: backslash and quote escaped, and every control character written as
|
|
63
|
+
\\uXXXX, so a value can neither break the file nor move the cursor on the screen."""
|
|
64
|
+
out = []
|
|
65
|
+
for ch in v:
|
|
66
|
+
if ch == "\\":
|
|
67
|
+
out.append("\\\\")
|
|
68
|
+
elif ch == '"':
|
|
69
|
+
out.append('\\"')
|
|
70
|
+
elif ord(ch) < 0x20 or ord(ch) == 0x7F:
|
|
71
|
+
out.append("\\u%04x" % ord(ch))
|
|
72
|
+
else:
|
|
73
|
+
out.append(ch)
|
|
74
|
+
return '"' + "".join(out) + '"'
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _value(v: Any) -> str:
|
|
78
|
+
if isinstance(v, bool):
|
|
79
|
+
return "true" if v else "false"
|
|
80
|
+
if isinstance(v, int):
|
|
81
|
+
return str(v)
|
|
82
|
+
if isinstance(v, str):
|
|
83
|
+
return _quote(v)
|
|
84
|
+
if isinstance(v, list):
|
|
85
|
+
if not v:
|
|
86
|
+
return "[]"
|
|
87
|
+
return "[\n" + "".join(f" {_value(x)},\n" for x in v) + "]"
|
|
88
|
+
raise ValueError(f"cannot write a {type(v).__name__}")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def dump(data: Dict[str, Dict[str, Any]]) -> str:
|
|
92
|
+
out = ["# phiward user config, written by `phiward setup`.",
|
|
93
|
+
"# The agent cannot write this file. See docs/configuration.md for every key.", ""]
|
|
94
|
+
for section in config.SCHEMA:
|
|
95
|
+
body = data.get(section)
|
|
96
|
+
if not body:
|
|
97
|
+
continue
|
|
98
|
+
out.append(f"[{section}]")
|
|
99
|
+
for key, v in body.items():
|
|
100
|
+
out.append(f"{key} = {_value(v)}")
|
|
101
|
+
out.append("")
|
|
102
|
+
return "\n".join(out)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# ---- checking one answer --------------------------------------------------------------------
|
|
106
|
+
|
|
107
|
+
def _expand(answer: str, home: str) -> str:
|
|
108
|
+
return os.path.normpath(home + answer[1:]) if answer == "~" or answer.startswith("~/") \
|
|
109
|
+
else os.path.normpath(answer) if answer.startswith("/") else answer
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def check_root(answer: str, home: str) -> str:
|
|
113
|
+
"""Why `answer` cannot be a protected root, or ""."""
|
|
114
|
+
p = _expand(answer, home)
|
|
115
|
+
if not p.startswith("/"):
|
|
116
|
+
return "it must be absolute (or start with ~/)"
|
|
117
|
+
if any(c in p for c in "*?["):
|
|
118
|
+
return "it has a wildcard; give it as a pattern instead"
|
|
119
|
+
if p == "/" or ".." in answer.split("/"):
|
|
120
|
+
return "it must be below / and have no '..'"
|
|
121
|
+
if not os.path.lexists(p):
|
|
122
|
+
return "it does not exist (create it first: on Linux the agent shell refuses to run " \
|
|
123
|
+
"while a root is missing)"
|
|
124
|
+
real_home = os.path.realpath(home)
|
|
125
|
+
if config.inside(real_home, os.path.realpath(p)):
|
|
126
|
+
return "it is the home folder or above it (the agent could not work at all)"
|
|
127
|
+
for g in config.guard_files():
|
|
128
|
+
if config.inside(os.path.realpath(g), os.path.realpath(p)):
|
|
129
|
+
return "it holds a phiward file or folder"
|
|
130
|
+
return ""
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def check_pattern(answer: str, home: str) -> str:
|
|
134
|
+
p = _expand(answer, home)
|
|
135
|
+
if not p.startswith("/"):
|
|
136
|
+
return "it must be absolute (or start with ~/)"
|
|
137
|
+
if not any(c in p for c in "*?["):
|
|
138
|
+
return "it has no wildcard; give it as a root instead"
|
|
139
|
+
if ".." in answer.split("/") or "$" in p:
|
|
140
|
+
return "it may not hold '..' or a variable"
|
|
141
|
+
from phiward import pathmatch
|
|
142
|
+
return pathmatch.problem(p) or ""
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def check_remote(answer: str) -> str:
|
|
146
|
+
if not _REMOTE.fullmatch(answer) or ".." in answer.split(":", 1)[1].split("/"):
|
|
147
|
+
return "it must look like host:/absolute/prefix, with no '..'"
|
|
148
|
+
from phiward.copying import remote_prefix_problem
|
|
149
|
+
return remote_prefix_problem(answer.split(":", 1)[1])
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# ---- the dialogue ---------------------------------------------------------------------------
|
|
153
|
+
|
|
154
|
+
class Ask:
|
|
155
|
+
def __init__(self, fin: TextIO, fout: TextIO):
|
|
156
|
+
self.fin, self.fout = fin, fout
|
|
157
|
+
|
|
158
|
+
def say(self, msg: str = "") -> None:
|
|
159
|
+
self.fout.write(msg + "\n")
|
|
160
|
+
self.fout.flush()
|
|
161
|
+
|
|
162
|
+
def line(self, prompt: str) -> str:
|
|
163
|
+
self.fout.write(prompt)
|
|
164
|
+
self.fout.flush()
|
|
165
|
+
got = self.fin.readline()
|
|
166
|
+
if not got:
|
|
167
|
+
raise EOFError
|
|
168
|
+
return got.strip()
|
|
169
|
+
|
|
170
|
+
def yes(self, question: str, default: bool = False) -> bool:
|
|
171
|
+
hint = "[Y/n]" if default else "[y/N]"
|
|
172
|
+
while True:
|
|
173
|
+
a = self.line(f"{question} {hint} ").lower()
|
|
174
|
+
if not a:
|
|
175
|
+
return default
|
|
176
|
+
if a in ("y", "yes", "n", "no"):
|
|
177
|
+
return a.startswith("y")
|
|
178
|
+
self.say(" Type y or n.")
|
|
179
|
+
|
|
180
|
+
def many(self, title: str, help_: str, have: List[str],
|
|
181
|
+
check: Callable[[str], str]) -> List[str]:
|
|
182
|
+
"""A list, one answer per line; an empty line ends it. Each answer is checked."""
|
|
183
|
+
self.say("")
|
|
184
|
+
self.say(title)
|
|
185
|
+
self.say(help_)
|
|
186
|
+
out = list(have)
|
|
187
|
+
if out:
|
|
188
|
+
self.say(f" Now: {len(out)} entr{'y' if len(out) == 1 else 'ies'}:")
|
|
189
|
+
for v in out:
|
|
190
|
+
self.say(f" {v}")
|
|
191
|
+
if self.yes(" Remove all of these and start again? (No keeps them)"):
|
|
192
|
+
out = []
|
|
193
|
+
while True:
|
|
194
|
+
a = self.line(" Add one (an empty line, or `none`, ends the list) > ")
|
|
195
|
+
if not a or a.strip().lower() in ("n", "no", "none", "skip", "done"):
|
|
196
|
+
return out
|
|
197
|
+
why = check(a)
|
|
198
|
+
if why:
|
|
199
|
+
self.say(f" Refused: {why}. Try again.")
|
|
200
|
+
continue
|
|
201
|
+
if a in out:
|
|
202
|
+
self.say(" Already in the list.")
|
|
203
|
+
continue
|
|
204
|
+
out.append(a)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
_SYSTEM_BIN = ("/usr/bin", "/bin", "/usr/sbin", "/sbin")
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def home_of(env: Dict[str, str]) -> str:
|
|
211
|
+
return pathid.home(env)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def approval(lines: List[str], home: str, before: bool) -> "Tuple[List[str], bool, int, int]":
|
|
215
|
+
"""How setup shows the programs to approve: (the lines, each program in the home folder that
|
|
216
|
+
shadows a system program of the same name marked; the question's default; how many are
|
|
217
|
+
found; how many are not installed). The default is Yes only on a first approval with nothing
|
|
218
|
+
changed and nothing shadowing a system program: a changed or shadowing program is what the
|
|
219
|
+
question is there to catch."""
|
|
220
|
+
shown: List[str] = []
|
|
221
|
+
shadows = False
|
|
222
|
+
found = missing = 0
|
|
223
|
+
h = os.path.realpath(home).rstrip("/") + "/"
|
|
224
|
+
for x in lines:
|
|
225
|
+
path = x.split(" ", 1)[0]
|
|
226
|
+
if x.endswith("(not installed)"):
|
|
227
|
+
missing += 1
|
|
228
|
+
continue
|
|
229
|
+
found += 1
|
|
230
|
+
name = os.path.basename(path)
|
|
231
|
+
hit = next((os.path.join(b, name) for b in _SYSTEM_BIN
|
|
232
|
+
if os.path.realpath(path).startswith(h) and os.path.isfile(os.path.join(b, name))),
|
|
233
|
+
"")
|
|
234
|
+
if hit:
|
|
235
|
+
shadows = True
|
|
236
|
+
x += f" (shadows {hit})"
|
|
237
|
+
shown.append(x)
|
|
238
|
+
changed = any(x.endswith("(changed)") for x in lines)
|
|
239
|
+
return shown, not before and not changed and not shadows, found, missing
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _read_existing(path: str) -> Dict[str, Dict[str, Any]]:
|
|
243
|
+
if not os.path.isfile(path):
|
|
244
|
+
return {}
|
|
245
|
+
raw, _ = _toml.load_file(path)
|
|
246
|
+
return {s: dict(b) for s, b in raw.items() if isinstance(b, dict)}
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _write(path: str, text: str) -> None:
|
|
250
|
+
folder = os.path.dirname(path)
|
|
251
|
+
os.makedirs(folder, mode=0o700, exist_ok=True)
|
|
252
|
+
if os.path.exists(path):
|
|
253
|
+
safeio.write_new(path + ".bak", safeio.read_text(path))
|
|
254
|
+
safeio.write_new(path, text)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
# what a team template may set: shared, non-grant settings. Never a write place, the network,
|
|
258
|
+
# a copy remote, an ssh config, names files, pack files by path, environment to pass on
|
|
259
|
+
TEAM_KEYS = {("broker", "commands"), ("sanitize", "packs"), ("remote", "hosts"),
|
|
260
|
+
("remote", "commands"), ("remote", "roots"), ("protected_paths", "patterns"),
|
|
261
|
+
("protected_paths", "snapshot_names"), ("copy", "push_limit_gib"),
|
|
262
|
+
("sanitize", "inventory_limit"), ("broker", "max_output_lines")}
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _ssh_entry(path: str, host: str) -> Dict[str, str]:
|
|
266
|
+
"""The HostName and User of `Host host` in an ssh config file, or {} (read only)."""
|
|
267
|
+
try:
|
|
268
|
+
with open(path, encoding="utf-8") as fh:
|
|
269
|
+
text = fh.read(1 << 20)
|
|
270
|
+
except OSError:
|
|
271
|
+
return {}
|
|
272
|
+
out: Dict[str, str] = {}
|
|
273
|
+
inside = False
|
|
274
|
+
for line in text.splitlines():
|
|
275
|
+
words = line.split()
|
|
276
|
+
if not words:
|
|
277
|
+
continue
|
|
278
|
+
key = words[0].lower()
|
|
279
|
+
if key in ("host", "match"):
|
|
280
|
+
inside = key == "host" and host in words[1:]
|
|
281
|
+
if inside:
|
|
282
|
+
out["found"] = "yes"
|
|
283
|
+
elif inside and key in ("hostname", "user") and len(words) > 1:
|
|
284
|
+
out[key] = words[1]
|
|
285
|
+
return out
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _in_project(path: str) -> bool:
|
|
289
|
+
"""Whether a file sits where an agent may have written it: in the current folder, or in a
|
|
290
|
+
folder with `.git`, `.claude` or `.phiward.toml` above it."""
|
|
291
|
+
here = os.path.realpath(os.getcwd())
|
|
292
|
+
if path == here or path.startswith(here.rstrip("/") + "/"):
|
|
293
|
+
return True
|
|
294
|
+
# a folder the agent's sandbox may write in every project (its allowWrite, the spool)
|
|
295
|
+
from phiward import claude_settings, pathid
|
|
296
|
+
for w in claude_settings.agent_writable_anywhere(pathid.home()):
|
|
297
|
+
r = os.path.realpath(w)
|
|
298
|
+
if path == r or path.startswith(r.rstrip("/") + "/"):
|
|
299
|
+
return True
|
|
300
|
+
d = os.path.dirname(path)
|
|
301
|
+
while d and d != "/":
|
|
302
|
+
if any(os.path.lexists(os.path.join(d, n)) for n in (".git", ".claude", ".phiward.toml")):
|
|
303
|
+
return True
|
|
304
|
+
d = os.path.dirname(d)
|
|
305
|
+
return False
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _team_problem(raw: Dict[str, Any]) -> str:
|
|
309
|
+
"""Why a team template cannot be used, or "": every value of the type the config expects,
|
|
310
|
+
no control characters, limits only lower than the defaults, no paths in the program list."""
|
|
311
|
+
limits = {("broker", "max_output_lines"): config.Config().max_output_lines,
|
|
312
|
+
("copy", "push_limit_gib"): config.Config().push_limit_gib,
|
|
313
|
+
("sanitize", "inventory_limit"): config.Config().inventory_limit}
|
|
314
|
+
for sec, keys in raw.items():
|
|
315
|
+
for k, v in keys.items():
|
|
316
|
+
want = config.SCHEMA[sec][k]
|
|
317
|
+
ok = {"list": isinstance(v, list) and all(isinstance(x, str) for x in v),
|
|
318
|
+
"bool": isinstance(v, bool), "str": isinstance(v, str),
|
|
319
|
+
"int": isinstance(v, int) and not isinstance(v, bool)}.get(want, False)
|
|
320
|
+
if not ok:
|
|
321
|
+
return f"{sec}.{k} must be a {want}" + (" of strings" if want == "list" else "")
|
|
322
|
+
for x in (v if isinstance(v, list) else [v]):
|
|
323
|
+
if isinstance(x, str) and any(not c.isprintable() for c in x):
|
|
324
|
+
# a control character, or one that turns text around (U+202E)
|
|
325
|
+
return (f"{sec}.{k} holds a control character or another character "
|
|
326
|
+
"that is not printable")
|
|
327
|
+
if (sec, k) in limits and v > limits[(sec, k)]:
|
|
328
|
+
return f"{sec}.{k} may only be lower than the default ({limits[(sec, k)]})"
|
|
329
|
+
if (sec, k) == ("broker", "commands") and any("/" in x for x in v):
|
|
330
|
+
return ("broker.commands names a place (a path); your own scripts are yours to "
|
|
331
|
+
"add")
|
|
332
|
+
return ""
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
PROFILES = ("Real patient data (recommended): a results folder, a list of programs, no network",
|
|
336
|
+
"Made-up data, to try phiward: any program may run, no network",
|
|
337
|
+
"Choose every setting yourself")
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _merge_team(data: Dict[str, Dict[str, Any]], team: Dict[str, Dict[str, Any]]) -> int:
|
|
341
|
+
"""A team template's settings, added where the operator's own config has none (lists are
|
|
342
|
+
joined). Returns how many keys it set."""
|
|
343
|
+
n = 0
|
|
344
|
+
for sec, keys in team.items():
|
|
345
|
+
if not isinstance(keys, dict):
|
|
346
|
+
continue
|
|
347
|
+
mine = data.setdefault(sec, {})
|
|
348
|
+
for k, v in keys.items():
|
|
349
|
+
if k not in mine:
|
|
350
|
+
mine[k] = v
|
|
351
|
+
n += 1
|
|
352
|
+
elif isinstance(v, list) and isinstance(mine[k], list):
|
|
353
|
+
extra = [x for x in v if x not in mine[k]]
|
|
354
|
+
if extra:
|
|
355
|
+
mine[k] = list(mine[k]) + extra
|
|
356
|
+
n += 1
|
|
357
|
+
return n
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def dialogue(ask: Ask, path: str, home: str, env: Dict[str, str],
|
|
361
|
+
team: Optional[Dict[str, Dict[str, Any]]] = None, team_name: str = "") -> int:
|
|
362
|
+
try:
|
|
363
|
+
data = _read_existing(path)
|
|
364
|
+
except (OSError, UnicodeDecodeError, _toml.TomlError) as exc:
|
|
365
|
+
ask.say(f"setup: the config at {path} cannot be read ({type(exc).__name__}); fix or move "
|
|
366
|
+
"it first.")
|
|
367
|
+
return 3
|
|
368
|
+
for sec, key in sorted(config.REMOVED): # iteration-4 keys: dropped, said so
|
|
369
|
+
if key in data.get(sec, {}):
|
|
370
|
+
del data[sec][key]
|
|
371
|
+
ask.say(f"Note: '{sec}.{key}' is no longer used (nothing asks at run time); it is "
|
|
372
|
+
"dropped from the new file.")
|
|
373
|
+
pp, br, cp = (data.setdefault(s, {}) for s in ("protected_paths", "broker", "copy"))
|
|
374
|
+
|
|
375
|
+
ask.say("phiward setup")
|
|
376
|
+
ask.say(f"User config: {path}")
|
|
377
|
+
ask.say("Answer each question. Nothing is written until you say yes at the end.")
|
|
378
|
+
ask.say("This terminal is yours: what you type here does not reach the agent.")
|
|
379
|
+
if team:
|
|
380
|
+
ask.say("")
|
|
381
|
+
ask.say(f"Team template {team_name} sets:")
|
|
382
|
+
for sec, keys in team.items():
|
|
383
|
+
for k, v in keys.items():
|
|
384
|
+
ask.say(f" [{sec}] {k} = {_value(v)}")
|
|
385
|
+
if (sec, k) in (("broker", "commands"), ("remote", "commands")):
|
|
386
|
+
launch = sorted({os.path.basename(str(x)) for x in v
|
|
387
|
+
if config.runs_other_code(str(x))})
|
|
388
|
+
if launch:
|
|
389
|
+
where_ = "on your data" if sec == "broker" else "on the cluster"
|
|
390
|
+
ask.say(f" WARNING: {', '.join(launch)} can run other code: with "
|
|
391
|
+
f"it, code the agent writes can run {where_}")
|
|
392
|
+
if isinstance(v, list) and (data.get(sec) or {}).get(k):
|
|
393
|
+
ask.say(" (added to your own list)")
|
|
394
|
+
if not ask.yes("Use these team settings?", False):
|
|
395
|
+
ask.say("Nothing was written.")
|
|
396
|
+
return 1
|
|
397
|
+
n = _merge_team(data, team)
|
|
398
|
+
pp, br, cp = (data.setdefault(s, {}) for s in ("protected_paths", "broker", "copy"))
|
|
399
|
+
ask.say(f"{n} team setting(s) used: added where you had none, lists joined with yours.")
|
|
400
|
+
ask.say("")
|
|
401
|
+
ask.say("How will you use phiward?")
|
|
402
|
+
for i, t in enumerate(PROFILES, 1):
|
|
403
|
+
ask.say(f" {i}. {t}")
|
|
404
|
+
while True:
|
|
405
|
+
a = ask.line("Choose 1, 2 or 3 [1] > ") or "1"
|
|
406
|
+
if a in ("1", "2", "3"):
|
|
407
|
+
profile = int(a)
|
|
408
|
+
break
|
|
409
|
+
ask.say(" Type 1, 2 or 3.")
|
|
410
|
+
created: List[str] = []
|
|
411
|
+
ssh_file: Optional[Tuple[str, str]] = None
|
|
412
|
+
hpc_lines: List[str] = []
|
|
413
|
+
|
|
414
|
+
pp["roots"] = ask.many(
|
|
415
|
+
"1. Protected roots",
|
|
416
|
+
" Folders that hold protected data. The agent cannot read them; only gateway commands\n"
|
|
417
|
+
" (phiward run|copy) can, and their output is masked. Use absolute paths or ~/.",
|
|
418
|
+
list(pp.get("roots", [])), lambda a: check_root(a, home))
|
|
419
|
+
if profile == 3:
|
|
420
|
+
pp["patterns"] = ask.many(
|
|
421
|
+
"2. Protected patterns (optional; prefer roots)",
|
|
422
|
+
" Glob patterns such as /data/runs/*/panel. On macOS, Claude Code's sandbox denies\n"
|
|
423
|
+
" them too (Claude Code 2.1.236 or newer); on Linux it cannot deny writes to them,\n"
|
|
424
|
+
" so there the hook refuses shell commands (use roots, or `phiward run`).",
|
|
425
|
+
list(pp.get("patterns", [])), lambda a: check_pattern(a, home))
|
|
426
|
+
else:
|
|
427
|
+
pp.setdefault("patterns", [])
|
|
428
|
+
probe = config.Config(roots=[_expand(r, home) for r in pp["roots"]],
|
|
429
|
+
patterns=[_expand(p, home) for p in pp["patterns"]],
|
|
430
|
+
derived_roots=[config.cache_dir(env)])
|
|
431
|
+
|
|
432
|
+
def check_write(a: str, may_create: bool = False) -> str:
|
|
433
|
+
p = _expand(a, home)
|
|
434
|
+
if not p.startswith("/"):
|
|
435
|
+
return "it must be absolute (or start with ~/)"
|
|
436
|
+
if may_create and not os.path.exists(p):
|
|
437
|
+
parent = os.path.realpath(os.path.dirname(p))
|
|
438
|
+
if not os.path.isdir(parent):
|
|
439
|
+
return "its folder does not exist"
|
|
440
|
+
full = os.path.join(parent, os.path.basename(p))
|
|
441
|
+
else:
|
|
442
|
+
full = os.path.realpath(p)
|
|
443
|
+
if not os.path.isdir(full):
|
|
444
|
+
return "it is not an existing folder (create it first)"
|
|
445
|
+
if full != p:
|
|
446
|
+
return f"a link is on its path; give the real folder instead: {full}"
|
|
447
|
+
if os.path.isdir(os.path.join(full, ".claude")):
|
|
448
|
+
return "it holds a .claude folder (choose a results folder, not a project folder)"
|
|
449
|
+
return config.grant_problem(full, probe, env)
|
|
450
|
+
|
|
451
|
+
if profile == 3:
|
|
452
|
+
br["write_to"] = ask.many(
|
|
453
|
+
"3. Write places for gateway commands ([broker] write_to)",
|
|
454
|
+
" Folders where gateway commands may write results; with one, it is the default\n"
|
|
455
|
+
" (no --write-to needed). Gateway commands write nowhere else: protected folders\n"
|
|
456
|
+
" are read only for them. What lands here is not masked, so the agent cannot read\n"
|
|
457
|
+
" these folders directly either. The simplest choice is a results folder inside a\n"
|
|
458
|
+
" protected folder, for example ~/data/patients/results.",
|
|
459
|
+
list(br.get("write_to", [])), check_write)
|
|
460
|
+
elif not br.get("write_to") and pp["roots"]:
|
|
461
|
+
# a results folder inside the first protected folder: the default write place
|
|
462
|
+
first = os.path.realpath(_expand(pp["roots"][0], home)) # the real folder, not a link
|
|
463
|
+
suggest = os.path.join(first.rstrip("/"), "phiward-results")
|
|
464
|
+
ask.say("")
|
|
465
|
+
ask.say("Results folder. Gateway commands write results only here (protected folders are")
|
|
466
|
+
ask.say("read only for them); what lands here stays protected, so the agent sees its name")
|
|
467
|
+
ask.say("masked and reads results through the gateway (`phiward run -- head`). Enter")
|
|
468
|
+
ask.say("accepts it, `none` skips it.")
|
|
469
|
+
while True:
|
|
470
|
+
a = ask.line(f" Results folder [{suggest}] > ") or suggest
|
|
471
|
+
if a.lower() in ("none", "n", "no", "skip"):
|
|
472
|
+
break
|
|
473
|
+
why = check_write(a, may_create=True)
|
|
474
|
+
if why:
|
|
475
|
+
ask.say(f" Refused: {why}. Try again.")
|
|
476
|
+
continue
|
|
477
|
+
br["write_to"] = [a]
|
|
478
|
+
if not os.path.exists(_expand(a, home)):
|
|
479
|
+
created.append(_expand(a, home))
|
|
480
|
+
break
|
|
481
|
+
|
|
482
|
+
def check_command(a: str) -> str:
|
|
483
|
+
if a.startswith("@"):
|
|
484
|
+
return "" if a[1:] in config.COMMAND_PRESETS else (
|
|
485
|
+
f"there is no list {a}; the lists are "
|
|
486
|
+
+ ", ".join("@" + k for k in config.COMMAND_PRESETS))
|
|
487
|
+
if "/" in a:
|
|
488
|
+
q = _expand(a, home)
|
|
489
|
+
if not q.startswith("/") or not os.path.exists(q):
|
|
490
|
+
return "a path must be absolute (or start with ~/) and exist"
|
|
491
|
+
return ""
|
|
492
|
+
return "" if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.+-]*", a) else "it must be a program name"
|
|
493
|
+
|
|
494
|
+
if profile == 1:
|
|
495
|
+
cmds = list(br.get("commands", [])) or ["@genomics"]
|
|
496
|
+
ask.say("")
|
|
497
|
+
ask.say("Programs. Gateway commands may run only listed programs, so code the agent")
|
|
498
|
+
ask.say("writes cannot run on your data. @genomics is samtools, bedtools, tabix, mosdepth,")
|
|
499
|
+
ask.say("seqkit, wc and other tools that run no other code.")
|
|
500
|
+
ask.say(f" Now: {', '.join(cmds)}")
|
|
501
|
+
ask.say("Add a folder of your own scripts, kept outside the projects the agent works in;")
|
|
502
|
+
ask.say("phiward protects it from agent writes. They run by full path, for example")
|
|
503
|
+
ask.say("`phiward run -- ~/pipelines/bin/count_reads.sh`. Enter skips.")
|
|
504
|
+
while True:
|
|
505
|
+
a = ask.line(" Your scripts folder (Enter for none) > ")
|
|
506
|
+
if not a or a.lower() in ("none", "n", "no", "skip"):
|
|
507
|
+
break
|
|
508
|
+
q = _expand(a, home)
|
|
509
|
+
if not os.path.isdir(q):
|
|
510
|
+
ask.say(" Refused: it is not an existing folder. Try again.")
|
|
511
|
+
continue
|
|
512
|
+
entry = a.rstrip("/") + "/"
|
|
513
|
+
if entry not in cmds:
|
|
514
|
+
cmds.append(entry)
|
|
515
|
+
break
|
|
516
|
+
br["commands"] = cmds
|
|
517
|
+
elif profile == 3:
|
|
518
|
+
br["commands"] = ask.many(
|
|
519
|
+
"4. Programs gateway commands may run ([broker] commands)",
|
|
520
|
+
" Empty: any program (code the agent writes can run on protected data). For real\n"
|
|
521
|
+
" data, list them: @genomics or @counts (built-in lists), program names, your own\n"
|
|
522
|
+
" scripts by path, or a folder of them ending in /. Interpreters and shells run any\n"
|
|
523
|
+
" code: list your scripts instead.",
|
|
524
|
+
list(br.get("commands", [])), check_command)
|
|
525
|
+
|
|
526
|
+
if profile == 3:
|
|
527
|
+
ask.say("")
|
|
528
|
+
ask.say("5. Network for gateway commands ([broker] net)")
|
|
529
|
+
ask.say(" With yes, `phiward run --net` gets the network. Code that reads protected\n"
|
|
530
|
+
" data could then send it anywhere. Against an agent you do not trust, say no.")
|
|
531
|
+
br["net"] = ask.yes(" Allow --net?", bool(br.get("net", False)))
|
|
532
|
+
cp["remotes"] = ask.many(
|
|
533
|
+
"6. Copy remotes ([copy] remotes)",
|
|
534
|
+
" host:/absolute/work/folder places that `phiward copy` may copy to or from. The\n"
|
|
535
|
+
" HPC questions below can fill this in. Leave empty if you do not use one.",
|
|
536
|
+
list(cp.get("remotes", [])), check_remote)
|
|
537
|
+
else:
|
|
538
|
+
br.setdefault("net", False)
|
|
539
|
+
|
|
540
|
+
if profile != 2:
|
|
541
|
+
nw = data.setdefault("network", {})
|
|
542
|
+
ask.say("")
|
|
543
|
+
ask.say(("7. " if profile == 3 else "") + "Network for shell commands in Claude Code "
|
|
544
|
+
"sessions ([network])")
|
|
545
|
+
ask.say(" With yes, the shell commands an agent runs reach only the hosts you list (Claude")
|
|
546
|
+
ask.say(" Code's own sandbox enforces it). Claude Code itself, WebFetch and MCP servers are")
|
|
547
|
+
ask.say(" not limited by it. Commands that need the network (git push, pip install) need")
|
|
548
|
+
ask.say(" their hosts listed, for example github.com or *.pypi.org. Each listed host is a")
|
|
549
|
+
ask.say(" way out: code the agent writes can send what it reads there. List few.")
|
|
550
|
+
if ask.yes(" Limit the network of shell commands?",
|
|
551
|
+
bool(nw.get("limit", profile == 1))):
|
|
552
|
+
nw["limit"] = True
|
|
553
|
+
|
|
554
|
+
def check_domain(a: str) -> str:
|
|
555
|
+
return config.domain_problem(a)
|
|
556
|
+
|
|
557
|
+
nw["allowed_domains"] = ask.many(
|
|
558
|
+
" Hosts shell commands may reach",
|
|
559
|
+
" One per line, for example github.com. None: no host at all.",
|
|
560
|
+
list(nw.get("allowed_domains", [])), check_domain)
|
|
561
|
+
else:
|
|
562
|
+
if nw.get("limit"):
|
|
563
|
+
ask.say(" Note: Claude Code keeps sandbox.network.strictAllowlist in "
|
|
564
|
+
"~/.claude/settings.json until you remove it there yourself.")
|
|
565
|
+
data.pop("network", None)
|
|
566
|
+
|
|
567
|
+
if profile != 2 and ask.yes("\nDo you work with an HPC cluster (copies, jobs)?", False):
|
|
568
|
+
ask.say(" phiward reaches it only through your own shared SSH connection (you log in;")
|
|
569
|
+
ask.say(" no request can read your key or ticket).")
|
|
570
|
+
rm0 = data.get("remote", {}) or {}
|
|
571
|
+
old_alias = (rm0.get("hosts") or ["hpc"])[0]
|
|
572
|
+
old_ssh = _expand(cp["ssh_config"], home) if cp.get("ssh_config") else ""
|
|
573
|
+
known = _ssh_entry(old_ssh, old_alias) if old_ssh else {}
|
|
574
|
+
old_work = next((r.split(":", 1)[1] for r in cp.get("remotes", [])
|
|
575
|
+
if r.startswith(old_alias + ":")), "")
|
|
576
|
+
while True:
|
|
577
|
+
alias = ask.line(f" Short name for the cluster, as you use it with ssh [{old_alias}] > ") \
|
|
578
|
+
or old_alias
|
|
579
|
+
if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", alias):
|
|
580
|
+
break
|
|
581
|
+
ask.say(" Refused: letters, digits, . _ - only. Try again.")
|
|
582
|
+
ask.say(" HostName and User must be the same as in your own ~/.ssh/config entry for")
|
|
583
|
+
ask.say(f" {alias}, or phiward cannot find your shared connection.")
|
|
584
|
+
while True:
|
|
585
|
+
dflt = known.get("hostname", "") if alias == old_alias else ""
|
|
586
|
+
login = ask.line(" Its login host, exactly as HostName in that entry"
|
|
587
|
+
+ (f" [{dflt}]" if dflt else "") + " > ") or dflt
|
|
588
|
+
if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", login or ""):
|
|
589
|
+
break
|
|
590
|
+
ask.say(" Refused: give the host name (letters, digits, . _ -). Try again.")
|
|
591
|
+
udflt = (known.get("user") if alias == old_alias else "") or os.environ.get("USER", "")
|
|
592
|
+
user = ask.line(f" Your user name there, as User in that entry [{udflt}] > ") or udflt
|
|
593
|
+
while True:
|
|
594
|
+
wdflt = old_work if alias == old_alias else ""
|
|
595
|
+
work = ask.line(" Your work folder there (absolute)"
|
|
596
|
+
+ (f" [{wdflt}]" if wdflt else "") + " > ") or wdflt
|
|
597
|
+
why = check_remote(f"{alias}:{work}") if work else "it is needed"
|
|
598
|
+
if not why:
|
|
599
|
+
break
|
|
600
|
+
ask.say(f" Refused: {why}. Try again.")
|
|
601
|
+
remotes = list(cp.get("remotes", []))
|
|
602
|
+
if f"{alias}:{work}" not in remotes:
|
|
603
|
+
remotes.append(f"{alias}:{work}")
|
|
604
|
+
cp["remotes"] = remotes
|
|
605
|
+
rm = data.setdefault("remote", {})
|
|
606
|
+
rm["hosts"] = sorted(set(rm.get("hosts", [])) | {alias})
|
|
607
|
+
rm.setdefault("commands", ["squeue", "sacct", "sinfo"])
|
|
608
|
+
masked = ask.line(f" Protected folders on the cluster, masked in remote output [{work}] > ")
|
|
609
|
+
rroots = list(rm.get("roots", []))
|
|
610
|
+
for r in ([masked] if masked else [work]):
|
|
611
|
+
if r.startswith("/") and r not in rroots:
|
|
612
|
+
rroots.append(r)
|
|
613
|
+
rm["roots"] = rroots
|
|
614
|
+
if cp.get("ssh_config") and _ssh_entry(_expand(cp["ssh_config"], home), alias):
|
|
615
|
+
ask.say(f" phiward's ssh config already has `Host {alias}`; nothing to add there.")
|
|
616
|
+
elif cp.get("ssh_config"):
|
|
617
|
+
ask.say(f" Kept your ssh config for phiward: {cp['ssh_config']}; add a `Host "
|
|
618
|
+
f"{alias}` entry to it with HostName, User and the ControlPath below.")
|
|
619
|
+
else:
|
|
620
|
+
ssh_path = os.path.join(os.path.dirname(path), "ssh_config")
|
|
621
|
+
cp["ssh_config"] = ssh_path.replace(home, "~", 1) if ssh_path.startswith(home + "/") \
|
|
622
|
+
else ssh_path
|
|
623
|
+
ssh_file = (ssh_path, f"Host {alias}\n HostName {login}\n User {user}\n"
|
|
624
|
+
f" ControlPath ~/.ssh/cm-%C\n ControlMaster no\n")
|
|
625
|
+
hpc_lines = [f"Host {alias}", f" HostName {login}", f" User {user}",
|
|
626
|
+
" ControlMaster auto", " ControlPath ~/.ssh/cm-%C", " ControlPersist 8h"]
|
|
627
|
+
ask.say("")
|
|
628
|
+
ask.say(f" In ~/.ssh/config (phiward does not edit it): if you have a `Host {alias}` entry,")
|
|
629
|
+
ask.say(" add only the three Control lines to it; otherwise add the whole block:")
|
|
630
|
+
for line in hpc_lines:
|
|
631
|
+
ask.say(" " + line)
|
|
632
|
+
|
|
633
|
+
for sec in ("protected_paths", "broker", "copy"):
|
|
634
|
+
for key in [k for k, v in data[sec].items() if v in ([], False)]:
|
|
635
|
+
del data[sec][key]
|
|
636
|
+
if data.get("network", {}).get("allowed_domains") == []:
|
|
637
|
+
del data["network"]["allowed_domains"] # limit = true with no host: none at all
|
|
638
|
+
text = dump(data)
|
|
639
|
+
old = ""
|
|
640
|
+
if os.path.exists(path):
|
|
641
|
+
with open(path, encoding="utf-8") as fh:
|
|
642
|
+
old = fh.read()
|
|
643
|
+
# the same checks as every later load: a file that would not load is not written. The trial
|
|
644
|
+
# file is in a new private folder, never next to the config
|
|
645
|
+
trial = tempfile.mkdtemp(prefix="phiward-setup-")
|
|
646
|
+
tmp = os.path.join(trial, "config.toml")
|
|
647
|
+
try:
|
|
648
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
|
649
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
650
|
+
fh.write(text)
|
|
651
|
+
cfg = config.load("/", env=dict(env, PHIWARD_CONFIG=tmp))
|
|
652
|
+
finally:
|
|
653
|
+
safeio.remove_tree(trial)
|
|
654
|
+
ask.say("")
|
|
655
|
+
ask.say("The new user config:")
|
|
656
|
+
ask.say("-" * 60)
|
|
657
|
+
ask.say(text.rstrip())
|
|
658
|
+
ask.say("-" * 60)
|
|
659
|
+
if old:
|
|
660
|
+
diff = list(difflib.unified_diff(old.splitlines(), text.splitlines(), "now", "new",
|
|
661
|
+
lineterm=""))
|
|
662
|
+
ask.say("Changes:" if diff else "No changes.")
|
|
663
|
+
for line in diff:
|
|
664
|
+
ask.say(" " + line)
|
|
665
|
+
if cfg.problem:
|
|
666
|
+
ask.say(f"This file cannot be used: {cfg.problem}")
|
|
667
|
+
ask.say("Nothing was written. Run setup again.")
|
|
668
|
+
return 3
|
|
669
|
+
if not cfg.roots and not cfg.patterns:
|
|
670
|
+
ask.say("Note: no protected paths. The guards will do nothing until you add some.")
|
|
671
|
+
if not ask.yes(f"Write it to {path}?"):
|
|
672
|
+
ask.say("Nothing was written.")
|
|
673
|
+
return 1
|
|
674
|
+
for folder in created: # the results folder, made only after the yes
|
|
675
|
+
os.makedirs(folder, mode=0o700, exist_ok=True)
|
|
676
|
+
ask.say(f"Made the results folder: {folder}")
|
|
677
|
+
_write(path, text)
|
|
678
|
+
ask.say(f"Written: {path} (mode 0600" + (", the old file is in .bak)" if old else ")"))
|
|
679
|
+
if ssh_file:
|
|
680
|
+
if os.path.lexists(ssh_file[0]):
|
|
681
|
+
ask.say(f"Kept phiward's ssh config as it is: {ssh_file[0]}")
|
|
682
|
+
else:
|
|
683
|
+
fd = os.open(ssh_file[0], os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
|
|
684
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
685
|
+
fh.write(ssh_file[1])
|
|
686
|
+
ask.say(f"Written phiward's ssh config: {ssh_file[0]}")
|
|
687
|
+
from phiward import pin
|
|
688
|
+
pinned_cfg = config.load(os.getcwd(), env=dict(env, PHIWARD_CONFIG=path))
|
|
689
|
+
if pinned_cfg.problem:
|
|
690
|
+
ask.say(f"Not pinned: the new config cannot be used: {pinned_cfg.problem}")
|
|
691
|
+
else:
|
|
692
|
+
approve = True
|
|
693
|
+
if pinned_cfg.command_lists:
|
|
694
|
+
pe = dict(env, PHIWARD_CONFIG=path)
|
|
695
|
+
lines = pin.describe(pinned_cfg, pe)
|
|
696
|
+
fresh = [x for x in lines if x.endswith(("(new)", "(changed)"))]
|
|
697
|
+
if fresh:
|
|
698
|
+
before = bool(pin.read_approved(pe))
|
|
699
|
+
shown, default, found, missing = approval(lines, home_of(env), before)
|
|
700
|
+
ask.say("")
|
|
701
|
+
ask.say(f"Programs of [broker] commands, as they are now ({found} found, "
|
|
702
|
+
f"{missing} not installed here); the broker runs only what you approve:")
|
|
703
|
+
for x in shown:
|
|
704
|
+
ask.say(f" {x}")
|
|
705
|
+
if missing:
|
|
706
|
+
ask.say(" (A program not installed here is added when you run `phiward pin` "
|
|
707
|
+
"from a terminal where it is found.)")
|
|
708
|
+
approve = ask.yes(f"Approve these {found} program(s) as they are now?", default)
|
|
709
|
+
if not approve:
|
|
710
|
+
ask.say("Kept your earlier approvals. While a listed program is not approved, "
|
|
711
|
+
"the broker refuses every gateway command: run `phiward pin`." if before
|
|
712
|
+
else
|
|
713
|
+
"Nothing is approved yet: gateway commands refuse every program "
|
|
714
|
+
"until you run `phiward pin`.")
|
|
715
|
+
try:
|
|
716
|
+
pin.write_pins(pinned_cfg, env=dict(env, PHIWARD_CONFIG=path), approve=approve)
|
|
717
|
+
except OSError as exc:
|
|
718
|
+
ask.say(f"Not pinned ({type(exc).__name__}); run `phiward pin` later")
|
|
719
|
+
else:
|
|
720
|
+
n = len(pin.pinnable(pinned_cfg))
|
|
721
|
+
if n:
|
|
722
|
+
ask.say(f"Recorded {n} folder(s) that phiward protects with your roots (git "
|
|
723
|
+
"folders, snapshots, other mounts), so a file planted later cannot hide "
|
|
724
|
+
"them.")
|
|
725
|
+
|
|
726
|
+
ask.say("")
|
|
727
|
+
wired = ask.yes("Wire Claude Code for every session (your user settings) now? It shows the "
|
|
728
|
+
"change it makes.", True)
|
|
729
|
+
if wired:
|
|
730
|
+
from phiward import install
|
|
731
|
+
if path != config.user_config_path(dict(env, PHIWARD_CONFIG="")):
|
|
732
|
+
os.environ["PHIWARD_CONFIG"] = path # only a non-default place
|
|
733
|
+
# the yes above is the one answer; wired only when install wrote it
|
|
734
|
+
wired = install.main(["claude", "--user", "--write", "--yes"]) == 0
|
|
735
|
+
ask.say("")
|
|
736
|
+
started = ask.yes("Start the broker at every login now, or restart it so it uses this "
|
|
737
|
+
"config? (This runs " + ("launchctl" if sys.platform == "darwin" else
|
|
738
|
+
"systemctl --user") + " now.)", True)
|
|
739
|
+
if started:
|
|
740
|
+
from phiward import service
|
|
741
|
+
service.main(["--write"])
|
|
742
|
+
ask.say("")
|
|
743
|
+
ask.say("Next steps:")
|
|
744
|
+
step = 1
|
|
745
|
+
if not wired:
|
|
746
|
+
ask.say(f" {step}. Wire Claude Code: (cd ~ && phiward install claude --user --write)")
|
|
747
|
+
step += 1
|
|
748
|
+
if not started:
|
|
749
|
+
ask.say(f" {step}. Start the broker: (cd ~ && phiward broker --service --write) (or "
|
|
750
|
+
"`phiward broker` in a terminal of its own); restart it after every config change")
|
|
751
|
+
step += 1
|
|
752
|
+
if hpc_lines:
|
|
753
|
+
ask.say(f" {step}. HPC: add the lines above to ~/.ssh/config; before each session that "
|
|
754
|
+
f"uses it, run kinit, then ssh -fN {hpc_lines[0].split()[1]}")
|
|
755
|
+
step += 1
|
|
756
|
+
from phiward import mcp_config
|
|
757
|
+
home = pathid.home()
|
|
758
|
+
bare = sorted(s.name for s in mcp_config.servers(os.getcwd(), home).values() if not s.wrapped)
|
|
759
|
+
if bare:
|
|
760
|
+
ask.say(f" {step}. Your MCP server(s) {', '.join(bare)} run with your full rights, outside "
|
|
761
|
+
"Claude Code's sandbox. Wrap them in phiward's kernel profile: "
|
|
762
|
+
"phiward mcp wrap --all")
|
|
763
|
+
step += 1
|
|
764
|
+
ask.say(f" {step}. In a project folder: phiward doctor; then open a new Claude Code session")
|
|
765
|
+
ask.say(f" {step + 1}. In each project with protected work: phiward init (docs/quickstart.md)")
|
|
766
|
+
return 0
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
def first_run(argv: List[str], fout: TextIO) -> int:
|
|
770
|
+
"""`setup --first-run`: the first config, without questions, for an agent that sets phiward
|
|
771
|
+
up with the operator. Only when no user config exists yet; after it the agent may not change
|
|
772
|
+
it. It writes protected roots and copy remotes only: no write places, no network (those are
|
|
773
|
+
grants, and stay the operator's). A root where your tools load code later stays read only
|
|
774
|
+
for the gateway, and a copy remote must name a work folder. The agent chooses what is
|
|
775
|
+
written here, so the docs recommend that the operator runs `phiward setup` instead."""
|
|
776
|
+
env = dict(os.environ)
|
|
777
|
+
home = pathid.home(env)
|
|
778
|
+
from phiward import install
|
|
779
|
+
why = install.agent_override_problem()
|
|
780
|
+
if why:
|
|
781
|
+
# the first config goes to the default place: one at a path the agent names would not
|
|
782
|
+
# be the config the operator's tools read
|
|
783
|
+
sys.stderr.write(f"setup --first-run: {why}. Nothing was written.\n")
|
|
784
|
+
return 2
|
|
785
|
+
path = config.user_config_path(env)
|
|
786
|
+
if os.path.lexists(path) or (not env.get("PHIWARD_CONFIG") and
|
|
787
|
+
os.path.lexists(config.legacy_user_config_path(env))):
|
|
788
|
+
sys.stderr.write("setup --first-run: a user config exists already; change it in your own "
|
|
789
|
+
"terminal with `(cd ~ && phiward setup)`. Nothing was written.\n")
|
|
790
|
+
return 2
|
|
791
|
+
roots: List[str] = []
|
|
792
|
+
remotes: List[str] = []
|
|
793
|
+
it = iter(argv)
|
|
794
|
+
for w in it:
|
|
795
|
+
if w in ("--root", "--remote"):
|
|
796
|
+
v = next(it, "")
|
|
797
|
+
why = check_root(v, home) if w == "--root" else check_remote(v)
|
|
798
|
+
if not v or why:
|
|
799
|
+
sys.stderr.write(f"setup --first-run: {w} {v!r}: {why or 'a value is needed'}. "
|
|
800
|
+
"Nothing was written.\n")
|
|
801
|
+
return 2
|
|
802
|
+
(roots if w == "--root" else remotes).append(v)
|
|
803
|
+
else:
|
|
804
|
+
sys.stderr.write(USAGE)
|
|
805
|
+
return 2
|
|
806
|
+
if not roots:
|
|
807
|
+
sys.stderr.write("setup --first-run: give at least one --root (a folder with protected "
|
|
808
|
+
"data). Nothing was written.\n")
|
|
809
|
+
return 2
|
|
810
|
+
data: Dict[str, Dict[str, Any]] = {"protected_paths": {"roots": roots}}
|
|
811
|
+
if remotes:
|
|
812
|
+
data["copy"] = {"remotes": remotes}
|
|
813
|
+
_write(path, dump(data))
|
|
814
|
+
fout.write(f"setup --first-run: wrote {path} with {len(roots)} protected root(s) and "
|
|
815
|
+
f"{len(remotes)} copy remote(s); no write places, no network. From now on only "
|
|
816
|
+
"you change it, with `(cd ~ && phiward setup)` in your own terminal.\n"
|
|
817
|
+
"Next, before real patient data: run `(cd ~ && phiward setup)` in your own terminal and "
|
|
818
|
+
"choose 1, which adds the list of programs gateway commands may run.\n")
|
|
819
|
+
return 0
|
|
820
|
+
|
|
821
|
+
|
|
822
|
+
def main(argv: List[str], fin: Optional[TextIO] = None, fout: Optional[TextIO] = None) -> int:
|
|
823
|
+
fin = sys.stdin if fin is None else fin
|
|
824
|
+
fout = sys.stdout if fout is None else fout
|
|
825
|
+
if argv[:1] in (["-h"], ["--help"]):
|
|
826
|
+
fout.write(HELP)
|
|
827
|
+
return 0
|
|
828
|
+
if argv[:1] == ["--first-run"]:
|
|
829
|
+
return first_run(argv[1:], fout)
|
|
830
|
+
team: Optional[Dict[str, Dict[str, Any]]] = None
|
|
831
|
+
team_name = ""
|
|
832
|
+
if argv[:1] == ["--from"] and len(argv) == 2:
|
|
833
|
+
team_name = argv[1]
|
|
834
|
+
try:
|
|
835
|
+
raw, _ = _toml.load_file(os.path.expanduser(argv[1]))
|
|
836
|
+
except (OSError, UnicodeDecodeError, _toml.TomlError) as exc:
|
|
837
|
+
sys.stderr.write(f"phiward setup: the team template cannot be read "
|
|
838
|
+
f"({type(exc).__name__}). Nothing was written.\n")
|
|
839
|
+
return 2
|
|
840
|
+
unknown = [f"{sec}.{k}" for sec, keys in raw.items() if isinstance(keys, dict)
|
|
841
|
+
for k in keys if sec not in config.SCHEMA or k not in config.SCHEMA[sec]]
|
|
842
|
+
if unknown or any(not isinstance(v, dict) for v in raw.values()):
|
|
843
|
+
sys.stderr.write("phiward setup: the team template has keys phiward does not know ("
|
|
844
|
+
+ ", ".join(unknown[:5]) + "). Nothing was written.\n")
|
|
845
|
+
return 2
|
|
846
|
+
mine = [f"{sec}.{k}" for sec, keys in raw.items() for k in keys
|
|
847
|
+
if (sec, k) not in TEAM_KEYS]
|
|
848
|
+
paths = [str(v) for v in raw.get("sanitize", {}).get("packs", []) if "/" in str(v)]
|
|
849
|
+
if mine or paths:
|
|
850
|
+
sys.stderr.write("phiward setup: a team template may set only shared settings ("
|
|
851
|
+
+ ", ".join(f"{a}.{b}" for a, b in sorted(TEAM_KEYS))
|
|
852
|
+
+ ", packs by built-in name). It sets "
|
|
853
|
+
+ ", ".join((mine + paths)[:5]) + ", which is yours to choose: "
|
|
854
|
+
"grants, files and places are never taken from a template. "
|
|
855
|
+
"Nothing was written.\n")
|
|
856
|
+
return 2
|
|
857
|
+
why = _team_problem(raw)
|
|
858
|
+
if why:
|
|
859
|
+
sys.stderr.write(f"phiward setup: the team template cannot be used: {why}. Nothing "
|
|
860
|
+
"was written.\n")
|
|
861
|
+
return 2
|
|
862
|
+
where = os.path.realpath(os.path.expanduser(argv[1]))
|
|
863
|
+
if _in_project(where):
|
|
864
|
+
sys.stderr.write("phiward setup: the team template is inside a project (a git work "
|
|
865
|
+
"tree), where an agent can change it. Read it, copy it to a folder "
|
|
866
|
+
"of your own, and give that copy. Nothing was written.\n")
|
|
867
|
+
return 2
|
|
868
|
+
team = raw
|
|
869
|
+
elif argv:
|
|
870
|
+
sys.stderr.write(USAGE)
|
|
871
|
+
return 2
|
|
872
|
+
try:
|
|
873
|
+
tty = fin.isatty() and fout.isatty()
|
|
874
|
+
except (AttributeError, ValueError):
|
|
875
|
+
tty = False
|
|
876
|
+
if not tty:
|
|
877
|
+
sys.stderr.write("phiward setup asks questions: run it in your own terminal, not "
|
|
878
|
+
"through an agent tool. Nothing was written.\n")
|
|
879
|
+
return 2
|
|
880
|
+
env = dict(os.environ)
|
|
881
|
+
home = pathid.home(env)
|
|
882
|
+
try:
|
|
883
|
+
return dialogue(Ask(fin, fout), config.user_config_path(env), home, env, team, team_name)
|
|
884
|
+
except (EOFError, KeyboardInterrupt):
|
|
885
|
+
fout.write("\nsetup stopped; nothing more was written.\n")
|
|
886
|
+
return 1
|