hum-cli 0.2.68__py3-none-any.whl → 0.2.70__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.
hum/__init__.py CHANGED
@@ -1,2 +1,2 @@
1
1
  """Hum — an agent harness built as an RL environment that humans can drive."""
2
- __version__ = "0.2.68"
2
+ __version__ = "0.2.70"
hum/client.py CHANGED
@@ -62,10 +62,9 @@ from hum.runtime.llm import DEFAULT_EFFORT, EFFORTS, ProviderError, failure_of
62
62
  from hum.runtime.lsp import Languages
63
63
  from hum.runtime.models import new_id, questions_of
64
64
  from hum.runtime.netproxy import NetProxy
65
- from hum.runtime.permissions import describe as describe_rule
65
+ from hum.runtime.permissions import add_entry, rule_words, shape
66
66
  from hum.runtime.permissions import load as load_rules
67
67
  from hum.runtime.permissions import record_to as record_rules
68
- from hum.runtime.permissions import shape
69
68
  from hum.runtime.prompt import (
70
69
  NestedInstructions,
71
70
  more_tools_note,
@@ -296,9 +295,14 @@ class Client:
296
295
  self.executor = LocalExecutor(cwd, sandbox=sandbox, env_pass=cfg.sandbox_env_pass)
297
296
  self.record: Session | None = None # the session open in this client, once one is: where what is learned
298
297
  # late goes (a refused host, the servers settling)
299
- if sandbox is not None and sandbox.on and not sandbox.network and cfg.sandbox_allow_hosts:
300
- # the network as a list of hosts: one proxy, the commands and the tool servers pointed at it
301
- self.executor.proxy = NetProxy(cfg.sandbox_allow_hosts, on_refused=self._network_refused)
298
+ # what the person says of a host the proxy has not seen: "session", "project" or "no" (the core asks them)
299
+ self.ask_host: Callable[[str, int], Awaitable[str]] | None = None
300
+ if sandbox is not None and sandbox.on and not sandbox.network and (cfg.sandbox_allow_hosts or sandbox.attended):
301
+ # the network as a list of hosts: one proxy, the commands (and, with a list, the tool servers) pointed at
302
+ # it; where someone can be asked, a host off the list is theirs to allow, as Claude Code's sandbox asks
303
+ self.executor.proxy = NetProxy(cfg.sandbox_allow_hosts, on_refused=self._network_refused,
304
+ ask=self._ask_host if sandbox.attended else None)
305
+ sandbox.ask_hosts = sandbox.attended
302
306
  # what the file tools have seen of this workspace, kept across a tool being rebuilt below
303
307
  self.files = FileState()
304
308
  # the plugins enabled here (the deployment's, the person's and the project's): their skills, agents, hooks,
@@ -395,39 +399,40 @@ class Client:
395
399
  self.gate: Any = None # a program's gate on tool calls (the wire's hook command), if any
396
400
  # [permissions]: what may run without asking, and what may not
397
401
  self.rules = load_rules(cwd, repo_root=repo_root(cwd))
402
+ self.rules.trusted = lambda: self.trust.allows # a repository's outside rules count once it is trusted
398
403
  # the dollars this session may spend, where it is running
399
404
  self.cfg.budget_usd = budget_usd(self.cfg, repo_root(cwd))
400
405
  self.tools.rules = self.rules
401
406
  for why in self.rules.problems:
402
407
  self.ui.warn(f"permissions: {why}")
403
408
 
404
- def shapes(self, turn: Turn) -> list[str]:
405
- """The rules that would settle calls like this proposal's — what a and p write."""
406
- out: list[str] = []
409
+ def shapes(self, turn: Turn) -> list[tuple[str, str]]:
410
+ """The rules that would settle calls like this proposal's — what a and p write: (entry, kind) each, kind
411
+ outside for a call that leaves the sandbox (it lets that command out without asking), allow for the rest."""
412
+ out: dict[str, str] = {}
407
413
  for c in turn.tool_calls:
408
- if not self.tools.needs_decision(c.name) or self.tools.escapes(c):
409
- continue # leaving the sandbox is asked every time; no rule buys it
410
- entry = shape(c, self.cwd)
411
- if entry and entry not in out:
412
- out.append(entry)
413
- return out
414
+ entry = shape(c, self.cwd) if self.tools.needs_decision(c.name) else None
415
+ if entry:
416
+ # one rule a shape: an outside rule allows inside too, so it stands for both
417
+ out[entry] = "outside" if self.tools.escapes(c) or out.get(entry) == "outside" else "allow"
418
+ return list(out.items())
414
419
 
415
- def remember(self, entries: list[str], scope: str, session: Session | None = None) -> list[Any]:
420
+ def remember(self, entries: list[tuple[str, str]], scope: str, session: Session | None = None) -> list[Any]:
416
421
  """Write those rules, for this session or for this project, and say so on the record."""
417
422
  written = []
418
- for entry in entries:
423
+ for entry, kind in entries:
419
424
  try:
420
- rule = (self.rules.add(entry, "allow", "session") if scope == "session"
421
- else self.rules.write_project(entry, "allow"))
425
+ rule = (self.rules.add(entry, kind, "session") if scope == "session"
426
+ else self.rules.write_project(entry, kind))
422
427
  except (ValueError, OSError) as e:
423
428
  self.ui.warn(f"could not remember {entry}: {e}")
424
429
  continue
425
430
  written.append(rule)
426
431
  if session is not None:
427
- session.event("rule_written", pattern=rule.text, decision="allow", scope=rule.scope)
432
+ session.event("rule_written", pattern=rule.text, decision=rule.decision, scope=rule.scope)
428
433
  if written:
429
434
  where = "this session" if scope == "session" else "this project"
430
- self.ui.info(f"allowed for {where}: {', '.join(describe_rule(r.text) for r in written)}")
435
+ self.ui.info(f"allowed for {where}: {', '.join(rule_words(r.text, r.decision) for r in written)}")
431
436
  return written
432
437
 
433
438
  def _hooks(self, session: Session) -> Any:
@@ -975,17 +980,41 @@ class Client:
975
980
  d.may_start = lambda a: self.trust.allows or not repo_trust.repository_agent(a, self.trust.root, self.plugins)
976
981
  return d
977
982
 
983
+ async def _ask_host(self, host: str, port: int) -> bool:
984
+ """A confined command asked for a host off the list: the person's word, kept for the session or, on p, in
985
+ this project's [sandbox] allow_hosts; nobody to ask is a no."""
986
+ word = await self.ask_host(host, port) if self.ask_host is not None else "no"
987
+ if self.record is not None:
988
+ self.record.event("network_decided", host=host, port=port, decision=word)
989
+ if word not in ("session", "project"):
990
+ return False
991
+ px = self.executor.proxy
992
+ if px is not None and host not in px.allow:
993
+ px.allow.append(host)
994
+ if word == "project":
995
+ path = Path(self.rules.project_root or self.cwd) / ".hum" / "config.toml"
996
+ try:
997
+ path.parent.mkdir(parents=True, exist_ok=True)
998
+ text = path.read_text(encoding="utf-8") if path.exists() else ""
999
+ path.write_text(add_entry(text, host, "allow_hosts", "sandbox"), encoding="utf-8")
1000
+ except (OSError, ValueError) as e:
1001
+ self.ui.warn(f"could not keep {host} for this project: {e}")
1002
+ where = "this project" if word == "project" else "this session"
1003
+ self.ui.info(f"network: {host} allowed for {where}")
1004
+ return True
1005
+
978
1006
  def _network_refused(self, host: str, port: int, via: str) -> None:
979
1007
  """A host the list does not name was asked for: on the transcript, and said to the person."""
980
1008
  if self.record is not None:
981
1009
  self.record.event("network_refused", host=host, port=port, via=via)
982
- self.ui.warn(f"network: {host} refused; not on [sandbox] allow_hosts")
1010
+ self.ui.warn(f"network: {host} refused" + ("" if self.executor.proxy and self.executor.proxy.ask
1011
+ else "; not on [sandbox] allow_hosts"))
983
1012
 
984
1013
  async def _proxy_env(self) -> dict[str, str]:
985
1014
  """The proxy's variables for a tool server's process, once the proxy listens; nothing without one."""
986
1015
  px = self.executor.proxy
987
- if px is None:
988
- return {}
1016
+ if px is None or not self.cfg.sandbox_allow_hosts:
1017
+ return {} # a tool server runs outside the sandbox: it is pointed at a list, never asked about each host
989
1018
  await px.start()
990
1019
  return px.env()
991
1020
 
hum/core.py CHANGED
@@ -61,6 +61,10 @@ Front-end → core (commands)
61
61
  {"cmd": "decide", "decision": "accept"|"reject", "note": "…", "remember"?: "session"|"project"} answer a proposal;
62
62
  remember also writes an allow rule for the shape of its calls
63
63
  {"cmd": "permissions"} → info: the rules in force here, and what each has settled
64
+ {"cmd": "network", "id": "…", "decision": "session"|"project"|"no"} answer a network_ask; project also keeps the
65
+ host in <repo>/.hum/config.toml [sandbox] allow_hosts
66
+ {"cmd": "add_dir", "path": "…"} let the model's commands and file tools write under one more directory,
67
+ for this session (as Claude Code's /add-dir)
64
68
  {"cmd": "gate", "mode": "off"|"approve"} approvals: whether mutating turns wait for a decision
65
69
  {"cmd": "agent", "agent": n, "text": "…" | "stop": true} the person's word to one running sub-agent: a message it
66
70
  reads at its next step, or the end of it (its caller gets what it had)
@@ -140,6 +144,9 @@ Core → front-end (events); every event has "type"
140
144
  proposal {content, calls[{id, name, desc, args, diff?, lines?}], remember[rule], remember_text} a gated turn waiting
141
145
  for a decision; remember = the rules "a" (session) and "p" (project) would write
142
146
  proposal_released approvals went off while one waited: it ran
147
+ network_ask {id, host, port} a confined command reached a host off the list: the connection waits
148
+ on the person's word (network cmd); nobody answering is a no
149
+ network_closed {id} that ask was answered, here or elsewhere, or ran out of time
143
150
  question {id, questions[{id, question, header, options[{label, description}], default, multi, secret}],
144
151
  kind?, summary?, evidence?, tree?} kind "review" = request_review (summary, files, evidence), "decision" = review_decision,
145
152
  "constraints" = discover_constraints (summary lists them)
@@ -222,7 +229,7 @@ from hum.runtime.config import Config, remote_mounts
222
229
  from hum.runtime.hooks import Outcome
223
230
  from hum.runtime.llm import ProviderError, describe_partial_call, error_text
224
231
  from hum.runtime.models import Node, ToolResult, questions_of
225
- from hum.runtime.permissions import describe as describe_rule
232
+ from hum.runtime.permissions import rule_words
226
233
  from hum.runtime.result import duration
227
234
  from hum.runtime.store import list_sessions, session_path
228
235
  from hum.runtime.tools import CARRIER_SUFFIXES, Reflector, change_of, still_out
@@ -246,6 +253,7 @@ MSG_MAX_BYTES = 100_000
246
253
  AGENT_COMMANDS = frozenset({"hello", "send", "stop", "noop"})
247
254
  SIGNIN_LINE_WAIT_S = 20.0 # mounts begin before the session opens its line to the deployment: a sign-in waits this long for one
248
255
  GATE_TIMEOUT_S = 60.0 # a program that holds a gate and does not answer: the call is denied, never run
256
+ HOST_ASK_S = 300.0 # a network ask nobody answers: the connection is refused and the command reads why
249
257
  # what of the way out is the model's own words to a Slack surface: a question to the thread, a review (the approval
250
258
  # gate) to the owner's DM. The notify moment, the turn-end words, goes from _run whole
251
259
  MOMENT_OF = {"question": "question", "proposal": "review"}
@@ -378,10 +386,12 @@ def on_contract(st: Any) -> bool:
378
386
  and isinstance(st.get("diagnostics"), list) and isinstance(st.get("files"), list))
379
387
 
380
388
 
381
- def mcp_call_desc(c: ToolCall) -> str | None:
389
+ def mcp_call_desc(c: ToolCall, width: int = 96) -> str | None:
382
390
  """A mounted tool's call as the person reads it: `mainframe · run_unit myunit` rather than
383
- the wire name — the server, the tool, and the one short argument that says what it is
384
- about (a path, a name), never a payload."""
391
+ the wire name — the server, the tool, and the short arguments that say what it is about, as
392
+ Claude Code heads an MCP call with its arguments: the one that names the thing bare (a path, a
393
+ name), the other short ones as `key: value`, as many as fit the width. Never a payload, never a
394
+ secret-named one."""
385
395
  if "__" not in c.name:
386
396
  return None
387
397
  server, tool = c.name.split("__", 1)
@@ -389,14 +399,20 @@ def mcp_call_desc(c: ToolCall) -> str | None:
389
399
  return isinstance(v, str) and 0 < len(v) <= 60 and "\n" not in v and " " not in v.strip()
390
400
  def secret(k: str) -> bool:
391
401
  return any(w in k.lower() for w in ("token", "key", "secret", "password", "auth", "credential"))
392
- # what the core packed for the call (a path), then an argument whose name says it names a thing
393
- for k, v in c.arguments.items():
394
- if k.endswith(CARRIER_SUFFIXES) and short(v) and not secret(k):
395
- return f"{server} · {tool} {v.strip()}"
396
- for k, v in c.arguments.items():
397
- if k.lower() in NAMING_ARGS and short(v) and not secret(k):
398
- return f"{server} · {tool} {v.strip()}"
399
- return f"{server} · {tool}"
402
+ head = f"{server} · {tool}"
403
+ args = [(k, v) for k, v in c.arguments.items() if not secret(k)]
404
+ # what the core packed for the call (a path), else an argument whose name says it names a thing: shown bare
405
+ named = next((k for k, v in args if k.endswith(CARRIER_SUFFIXES) and short(v)), None) or next(
406
+ (k for k, v in args if k.lower() in NAMING_ARGS and short(v)), None)
407
+ out = head + (f" {str(c.arguments[named]).strip()}" if named else "")
408
+ rest = [f"{k}: {str(v).strip() if isinstance(v, str) else json.dumps(v)}" for k, v in args
409
+ if k != named and (short(v) or (isinstance(v, (int, float)) and not isinstance(v, bool)))]
410
+ shown: list[str] = []
411
+ for part in rest:
412
+ if len(out) + len(" (" + ", ".join([*shown, part]) + ")") > width:
413
+ break
414
+ shown.append(part)
415
+ return out + (f" ({', '.join(shown)})" if shown else "")
400
416
 
401
417
 
402
418
  NAMING_ARGS = frozenset({"path", "file", "name", "case", "id", "unit", "job", "program", "member", "dsn", "table",
@@ -776,6 +792,7 @@ class Core:
776
792
  # side tasks (a clipboard read): referenced so they cannot vanish, cancelled on quit
777
793
  self._bg: set[asyncio.Task] = set()
778
794
  self._last_proposal: dict[str, Any] | None = None
795
+ self._host_asks: dict[str, tuple[str, int, asyncio.Future[str]]] = {} # network asks waiting, by id
779
796
  self._questions: asyncio.Task | None = None # the forwarder: an ask goes out as it is posted, nothing kept
780
797
  self.tool_names: list[str] = []
781
798
  self._ready = asyncio.Event() # the core can be looked at; hello waits for it, never for a tool server
@@ -828,6 +845,7 @@ class Core:
828
845
  self.client.arrived = lambda: self.arrived
829
846
  self.client.emit = self.wire.send # a routing decision reaches every front-end as it is recorded
830
847
  self.client.expect_signin = self._expect_signin # a sign-in that comes back through the deployment
848
+ self.client.ask_host = self._ask_host # a confined command reached a host off the list
831
849
  self.client.tools.background = self.background # a call that outlives its turn is watched, and wakes the model
832
850
 
833
851
  def wanted(self) -> tuple[str | None, list[dict[str, Any]]]:
@@ -1058,6 +1076,8 @@ class Core:
1058
1076
  self.wire.send("idle", to=to)
1059
1077
  if self.human.waiting is not None and self._last_proposal is not None:
1060
1078
  self.wire.send("proposal", to=to, **self._last_proposal)
1079
+ for hid, (host, port, _) in self._host_asks.items(): # a connection still waiting on the person's word
1080
+ self.wire.send("network_ask", to=to, id=hid, host=host, port=port)
1061
1081
  # every ask still open on the record, oldest first: a surface that reads one event at a time sees them all
1062
1082
  for q in opens:
1063
1083
  self.wire.send("question", to=to, **ask.for_wire(q))
@@ -1708,6 +1728,58 @@ class Core:
1708
1728
  else:
1709
1729
  self.wire.send("reasoning", items=self.client.effort_choices())
1710
1730
 
1731
+ async def _ask_host(self, host: str, port: int) -> str:
1732
+ """A host the proxy has not seen, put to whoever is at the terminal; nobody there, or nobody answering in
1733
+ HOST_ASK_S, is a no, and the command reads the refusal."""
1734
+ if self.wire.interactive == 0:
1735
+ return "no"
1736
+ hid = f"n{len(self._host_asks)}-{os.urandom(3).hex()}"
1737
+ fut: asyncio.Future[str] = asyncio.get_running_loop().create_future()
1738
+ self._host_asks[hid] = (host, port, fut)
1739
+ self.wire.send("network_ask", id=hid, host=host, port=port)
1740
+ self._notify("proposal", f"network: may commands reach {host}?")
1741
+ try:
1742
+ return await asyncio.wait_for(asyncio.shield(fut), HOST_ASK_S)
1743
+ except asyncio.TimeoutError:
1744
+ return "no"
1745
+ finally:
1746
+ self._host_asks.pop(hid, None)
1747
+ self.wire.send("network_closed", id=hid)
1748
+
1749
+ async def _cmd_network(self, cmd: dict[str, Any], w: Writer | None) -> None:
1750
+ ask = self._host_asks.get(str(cmd.get("id") or ""))
1751
+ decision = str(cmd.get("decision") or "no")
1752
+ if ask is None or ask[2].done():
1753
+ self.wire.send("warn", to=w, text="network: nothing is waiting on that")
1754
+ return
1755
+ ask[2].set_result(decision if decision in ("session", "project") else "no")
1756
+
1757
+ async def _cmd_add_dir(self, cmd: dict[str, Any], w: Writer | None) -> None:
1758
+ """One more directory the model may write under, for this session: its commands and its file tools."""
1759
+ sb = getattr(self.client.executor, "sandbox", None)
1760
+ raw = str(cmd.get("path") or "").strip()
1761
+ if not raw:
1762
+ self.wire.send("warn", to=w, text="/add-dir <directory>")
1763
+ return
1764
+ d = Path(os.path.expanduser(raw))
1765
+ d = (d if d.is_absolute() else self.cwd / d).resolve()
1766
+ if not d.is_dir():
1767
+ self.wire.send("warn", to=w, text=f"add-dir: {d} is not a directory")
1768
+ return
1769
+ if sb is None or not sb.on:
1770
+ self.ui.info(f"no sandbox here: the model can already write under {d}")
1771
+ return
1772
+ hidden = [h for h in sb.hidden_paths() if d == h or d.is_relative_to(h) or h.is_relative_to(d)]
1773
+ if hidden or d == Path.home().resolve() or d == Path(d.anchor):
1774
+ self.wire.send("warn", to=w, text=f"add-dir: {d} holds what the sandbox keeps from the model; name a "
1775
+ "directory inside it")
1776
+ return
1777
+ if d not in [Path(p) for p in sb.writable]:
1778
+ sb.writable.append(d)
1779
+ if self.session is not None:
1780
+ self.session.event("add_dir", path=str(d))
1781
+ self.ui.info(f"the model may now write under {d} for this session")
1782
+
1711
1783
  async def _cmd_decide(self, cmd: dict[str, Any], w: Writer | None) -> None:
1712
1784
  str(cmd.get("cmd"))
1713
1785
  note = str(cmd.get("note", "")).strip()
@@ -2425,6 +2497,8 @@ class Core:
2425
2497
  "model": _cmd_model,
2426
2498
  "reasoning": _cmd_reasoning,
2427
2499
  "decide": _cmd_decide,
2500
+ "network": _cmd_network,
2501
+ "add_dir": _cmd_add_dir,
2428
2502
  "gate": _cmd_gate,
2429
2503
  "agent": _cmd_agent,
2430
2504
  "hook": _cmd_hook,
@@ -2471,8 +2545,8 @@ class Core:
2471
2545
  calls.append({"id": c.id, "name": c.name, "args": {}, "desc": f"{c.name} (could not render: "
2472
2546
  f"{error_text(e)})"})
2473
2547
  remember = self.client.shapes(turn)
2474
- self._last_proposal = {"content": turn.content, "calls": calls, "remember": remember,
2475
- "remember_text": ", ".join(describe_rule(e) for e in remember),
2548
+ self._last_proposal = {"content": turn.content, "calls": calls, "remember": [e for e, _ in remember],
2549
+ "remember_text": ", ".join(rule_words(e, k) for e, k in remember),
2476
2550
  # a sub-agent's proposal says which sub-agent: its number, kind and job
2477
2551
  **({"agent": dict(self.human.asking)} if self.human.asking else {})}
2478
2552
  self.needs = "proposal"
hum/plain.py CHANGED
@@ -156,6 +156,7 @@ class Plain:
156
156
  self.asked: dict[str, Any] | None = None # the ask on screen, and the answers collected so far
157
157
  self.collected: dict[str, str] = {}
158
158
  self.proposal: dict[str, Any] | None = None # the proposal waiting for a decision
159
+ self.hosts: list[dict[str, Any]] = [] # network asks waiting on the person, oldest first
159
160
  self.trust: dict[str, Any] | None = None # the repository's word waiting for the person's
160
161
  self.rewinds: list[dict[str, Any]] = [] # what /rewind last listed
161
162
  self.busy = False
@@ -334,6 +335,14 @@ class Plain:
334
335
  self.changed.set()
335
336
  elif k == "proposal_released":
336
337
  self.proposal = None
338
+ elif k == "network_ask":
339
+ if not any(h.get("id") == ev.get("id") for h in self.hosts):
340
+ self.hosts.append(ev)
341
+ ui.info(f"? a command wants to reach {ev.get('host')} (it stays in the sandbox) · enter allows it for "
342
+ "this session · p always in this project · n refuses")
343
+ self.changed.set()
344
+ elif k == "network_closed":
345
+ self.hosts = [h for h in self.hosts if h.get("id") != ev.get("id")]
337
346
  elif k == "image":
338
347
  ref = {kk: ev.get(kk) for kk in ("id", "media_type", "bytes", "width", "height", "name", "data")}
339
348
  self.images.append(ref)
@@ -467,6 +476,11 @@ class Plain:
467
476
  s = line.strip()
468
477
  if s.split(" ", 1)[0] in QUIT_WORDS:
469
478
  return False
479
+ if self.hosts and s.lower() in ("", "y", "p", "n"):
480
+ h = self.hosts.pop(0)
481
+ self.fe.send(cmd="network", id=h["id"], decision={"": "session", "y": "session", "p": "project"}.get(
482
+ s.lower(), "no"))
483
+ return True
470
484
  if self.asked is not None and not s.startswith("/"):
471
485
  qs = questions_of(self.asked)
472
486
  q = qs[len(self.collected)]
hum/runtime/loop.py CHANGED
@@ -348,6 +348,7 @@ class Runner:
348
348
  self.interventions = 0
349
349
  self.approvals = 0 # accepted proposals: labels, not interventions — but the run was supervised
350
350
  self.settled: Any = None # the rule that settled the turn being recorded, if one did
351
+ self.ruled_out = False # an outside rule let the turn being run leave the sandbox (see _gated)
351
352
  self.task_class = self.cfg.task_class or session.task.get("task_class")
352
353
  self.workspace = workspace
353
354
  self.notify = notify # (event, fields) → the client, for acts the person cannot otherwise see
@@ -1188,6 +1189,7 @@ class Runner:
1188
1189
  then decided exactly as it would have been on its own, so writing a deny never lets the
1189
1190
  rest of a turn through unasked."""
1190
1191
  self.settled = None
1192
+ self.ruled_out = False # an outside rule settled this turn: its escape=true calls leave the sandbox
1191
1193
  rules = getattr(self.tools, "rules", None)
1192
1194
  calls, attended = list(turn.tool_calls), self.human is not None
1193
1195
  if rules is not None and calls:
@@ -1201,7 +1203,15 @@ class Runner:
1201
1203
  if not attended or not turn.acts:
1202
1204
  return False # terminal claims are never gated: the grader decides
1203
1205
  if any(self.tools.escapes(c) for c in calls):
1204
- return True # leaving the sandbox is the person's decision, whatever the gate mode
1206
+ # leaving the sandbox is the person's decision, whatever the gate mode: asked, or settled by an outside
1207
+ # rule they wrote (an allow speaks for a call that leaves only through one), which lets the calls out
1208
+ if decision == "allow" and rule is not None:
1209
+ self.settled = rule
1210
+ rules.settle(rule, rules.spoken_for(rule, calls), "allow")
1211
+ self.approvals += 1
1212
+ self.ruled_out = True
1213
+ return False
1214
+ return True
1205
1215
  if decision == "ask" and rule is not None:
1206
1216
  self.settled = rule # a rule that says ask asks, whatever the approvals setting is
1207
1217
  rules.settle(rule, rules.spoken_for(rule, calls), "ask")
@@ -1389,7 +1399,9 @@ class Runner:
1389
1399
  prompt_tokens = turn.usage.input_tokens
1390
1400
  if branch == self.branch:
1391
1401
  self.last_prompt_tokens = turn.usage.input_tokens
1392
- if self._gated(turn):
1402
+ if not self._gated(turn):
1403
+ approved = self.ruled_out # an outside rule the person wrote stands for their yes
1404
+ else:
1393
1405
  action = await human.review(turn) # type: ignore[union-attr]
1394
1406
  kind = action.intervention.kind if action.intervention else "accept"
1395
1407
  released = kind == "release"
hum/runtime/netproxy.py CHANGED
@@ -14,7 +14,7 @@ import os
14
14
  import sys
15
15
  import tempfile
16
16
  from pathlib import Path
17
- from typing import Callable
17
+ from typing import Awaitable, Callable
18
18
  from urllib.parse import urlsplit
19
19
 
20
20
  HEADER_MAX = 64 * 1024 # a request's headers; more than this is not a request
@@ -77,9 +77,15 @@ class NetProxy:
77
77
  """One per session, on this machine's loopback. ``allow`` is the list; ``on_refused(host, port, via)``
78
78
  is told about every host turned away, ``via`` being the method or the tool that asked."""
79
79
 
80
- def __init__(self, allow: list[str], on_refused: Callable[[str, int, str], None] | None = None):
80
+ def __init__(self, allow: list[str], on_refused: Callable[[str, int, str], None] | None = None,
81
+ ask: Callable[[str, int], Awaitable[bool]] | None = None):
81
82
  self.allow = [str(h) for h in allow if str(h).strip()]
83
+ self.listed = bool(self.allow) # a deployment named the hosts: a list to hold to, not only a proxy that asks
82
84
  self.on_refused = on_refused
85
+ # a host off the list is put to the person, as Claude Code's sandbox asks for a domain: the connection waits
86
+ # on their word, and every connection to that host while it is asked waits on the same one
87
+ self.ask = ask
88
+ self._asking: dict[str, asyncio.Future[bool]] = {}
83
89
  self.port: int = 0
84
90
  self.sock_path: str | None = None
85
91
  self._tcp: asyncio.AbstractServer | None = None
@@ -95,9 +101,31 @@ class NetProxy:
95
101
  return matches(host, self.allow)
96
102
 
97
103
  def refusal(self, host: str) -> str:
104
+ if self.ask is not None:
105
+ return (f"{normal(host)} was not allowed: the person was asked and said no, or nobody answered. Do not "
106
+ "work around it; say what you needed it for.")
98
107
  return (f"{normal(host)} is not on [sandbox] allow_hosts; the hosts this session may reach are "
99
108
  f"{', '.join(self.allow) if self.allow else 'none'}. Ask the person to add it to .hum/config.toml.")
100
109
 
110
+ async def permits(self, host: str, port: int) -> bool:
111
+ """On the list, or the person allows it now."""
112
+ if self.allows(host):
113
+ return True
114
+ if self.ask is None:
115
+ return False
116
+ h = normal(host)
117
+ fut = self._asking.get(h)
118
+ if fut is None:
119
+ fut = asyncio.get_running_loop().create_future()
120
+ self._asking[h] = fut
121
+ try:
122
+ fut.set_result(bool(await self.ask(h, int(port))))
123
+ except Exception:
124
+ fut.set_result(False)
125
+ finally:
126
+ self._asking.pop(h, None)
127
+ return await asyncio.shield(fut)
128
+
101
129
  def refused(self, host: str, port: int, via: str) -> None:
102
130
  if self.on_refused is not None:
103
131
  with contextlib.suppress(Exception):
@@ -160,7 +188,7 @@ class NetProxy:
160
188
  port = int(port_s) if port_s.isdigit() else 443
161
189
  if not host:
162
190
  host, port = target, 443
163
- if not self.allows(host):
191
+ if not await self.permits(host, port):
164
192
  self.refused(host, port, method)
165
193
  await self._answer(writer, REFUSED, self.refusal(host))
166
194
  return
@@ -180,7 +208,7 @@ class NetProxy:
180
208
  await self._answer(writer, 400, "a proxy request names a whole http:// URL")
181
209
  return
182
210
  host, port = u.hostname, u.port or 80
183
- if not self.allows(host):
211
+ if not await self.permits(host, port):
184
212
  self.refused(host, port, method)
185
213
  await self._answer(writer, REFUSED, self.refusal(host))
186
214
  return
@@ -1,9 +1,10 @@
1
1
  """Rules: what the agent may do without asking, and what it may never do. A rule is tool(pattern) under
2
- [permissions] allow/ask/deny in ~/.hum/config.toml and <repo>/.hum/config.toml; the strictest word wins, a session
3
- rule sits above the project's, the project's above the person's. A deny is refused as a tool result in every mode;
4
- an ask is the person's whatever the gate says, and refused when nobody is there. Patterns: bash(prefix:*) on word
5
- boundaries with every part of a chained line allowed, edit_file(glob), web_fetch(domain:host), delegate,
6
- server__tool(arg:value).
2
+ [permissions] allow/ask/deny/outside in ~/.hum/config.toml and <repo>/.hum/config.toml; the strictest word wins, a
3
+ session rule sits above the project's, the project's above the person's. A deny is refused as a tool result in every
4
+ mode; an ask is the person's whatever the gate says, and refused when nobody is there. An outside rule allows a
5
+ command to leave the sandbox (escape=true) without asking, and allows it inside too; a plain allow never lets a
6
+ command out. Patterns: bash(prefix:*) on word boundaries with every part of a chained line allowed,
7
+ edit_file(glob), web_fetch(domain:host), delegate, server__tool(arg:value).
7
8
  """
8
9
  from __future__ import annotations
9
10
 
@@ -19,7 +20,9 @@ from urllib.parse import urlparse
19
20
 
20
21
  from .redact import redact
21
22
 
22
- DECISIONS = ("deny", "ask", "allow")
23
+ DECISIONS = ("deny", "ask", "allow") # in the order a rule settles a call
24
+ # what a file may list: the decisions, and outside, an allow that also lets a command leave the sandbox
25
+ KINDS = (*DECISIONS, "outside")
23
26
  SCOPES = ("session", "project", "person")
24
27
  # one family: a rule written as bash(…) holds for whichever shell this machine gives the model
25
28
  SHELL = {"bash", "sh", "powershell", "cmd"}
@@ -54,8 +57,10 @@ def parse_entry(entry: str, decision: str, scope: str = "person", source: str =
54
57
  if not m:
55
58
  raise ValueError(f"{s!r} is not tool(pattern)")
56
59
  tool, pattern = m.group(1), (m.group(2) or "").strip()
57
- if decision not in DECISIONS:
58
- raise ValueError(f"{decision!r} is not one of {', '.join(DECISIONS)}")
60
+ if decision not in KINDS:
61
+ raise ValueError(f"{decision!r} is not one of {', '.join(KINDS)}")
62
+ if decision == "outside" and tool not in SHELL:
63
+ raise ValueError(f"{s!r}: only a shell command leaves the sandbox")
59
64
  if pattern and "*" in pattern and not _glob_tool(tool) and not pattern.endswith("*"):
60
65
  raise ValueError(f"{s!r}: * belongs at the end")
61
66
  return Rule(decision=decision, tool=tool, pattern=pattern, scope=scope, source=source)
@@ -147,6 +152,11 @@ def command_matches(pattern: str, command: str) -> bool:
147
152
  return bool(words) and (cmd == words or cmd.startswith(words + " "))
148
153
 
149
154
 
155
+ def escapes(call: Any) -> bool:
156
+ """A shell call that asks to run outside the sandbox: only an outside rule allows it."""
157
+ return call.name in SHELL and bool((call.arguments or {}).get("escape"))
158
+
159
+
150
160
  # -- reading a path --------------------------------------------------------------------
151
161
 
152
162
  @lru_cache(maxsize=512)
@@ -258,6 +268,11 @@ def shape(call: Any, cwd: Path | None = None) -> str | None:
258
268
  return call.name
259
269
 
260
270
 
271
+ def rule_words(entry: str, kind: str = "allow") -> str:
272
+ """A rule to be written, as the panel offers it: an outside rule says it leaves the sandbox."""
273
+ return describe(entry) + (" outside the sandbox" if kind == "outside" else "")
274
+
275
+
261
276
  def call_line(call: Any) -> str:
262
277
  """One line naming a call, for the record and for the panel. Scrubbed before it is cut
263
278
  short, never after: a key sliced in half by the cut is still most of a key, and the
@@ -305,6 +320,9 @@ class Rules:
305
320
  self.problems: list[str] = list(problems)
306
321
  self.counts: dict[Rule, int] = {}
307
322
  self.on_settle: Callable[[Rule, Any, str], None] | None = None
323
+ # whether the person has trusted this repository: a project's outside rule ships with the repository, and lets
324
+ # a command out of the sandbox, so it counts only on their word (their own and the session's always count)
325
+ self.trusted: Callable[[], bool] = lambda: False
308
326
 
309
327
  # -- what they say -----------------------------------------------------------------
310
328
  def explain(self, call: Any) -> Rule | None:
@@ -339,7 +357,7 @@ class Rules:
339
357
 
340
358
  def decide(self, call: Any) -> str | None:
341
359
  r = self.explain(call)
342
- return r.decision if r is not None else None
360
+ return None if r is None else "allow" if r.decision == "outside" else r.decision # outside is an allow
343
361
 
344
362
  def turn(self, calls: list[Any], needs_decision: Callable[[str], bool] | None = None) -> tuple[str | None,
345
363
  Rule | None]:
@@ -362,7 +380,10 @@ class Rules:
362
380
  return "allow", first
363
381
 
364
382
  def _first(self, decision: str, call: Any) -> Rule | None:
365
- rules = sorted((r for r in self.rules if r.decision == decision and same_tool(r.tool, call.name)),
383
+ # an allow is read from the outside rules too, and from them alone for a call that leaves the sandbox
384
+ kinds = {decision} if decision != "allow" else ({"outside"} if escapes(call) else {"allow", "outside"})
385
+ rules = sorted((r for r in self.rules if r.decision in kinds and same_tool(r.tool, call.name)
386
+ and (r.decision != "outside" or r.scope != "project" or self.trusted())),
366
387
  key=lambda r: SCOPES.index(r.scope) if r.scope in SCOPES else len(SCOPES))
367
388
  if not rules:
368
389
  return None
@@ -425,7 +446,7 @@ class Rules:
425
446
  """The rules in force, as ``/permissions`` shows them: nearest scope first."""
426
447
  out = []
427
448
  for scope in SCOPES:
428
- for decision in DECISIONS:
449
+ for decision in KINDS:
429
450
  for r in self.rules:
430
451
  if r.scope != scope or r.decision != decision:
431
452
  continue
@@ -458,7 +479,7 @@ def _read(path: Path, scope: str, out: list[Rule], problems: list[str]) -> None:
458
479
  if not isinstance(section, dict):
459
480
  problems.append(f"{path}: [permissions] is not a table")
460
481
  return
461
- for decision in DECISIONS:
482
+ for decision in KINDS:
462
483
  for entry in section.get(decision) or []:
463
484
  try:
464
485
  out.append(parse_entry(str(entry), decision, scope, str(path)))
@@ -484,20 +505,20 @@ def load(cwd: str | Path, *, repo_root: str | Path | None = None) -> Rules:
484
505
  return Rules(rules, cwd=d, project_root=root, problems=problems)
485
506
 
486
507
 
487
- def add_entry(text: str, entry: str, decision: str = "allow") -> str:
488
- """The text of a config.toml with one more entry under ``[permissions]``, and every
508
+ def add_entry(text: str, entry: str, decision: str = "allow", section: str = "permissions") -> str:
509
+ """The text of a config.toml with one more entry in the list ``decision`` under ``[section]``, and every
489
510
  other line of the file left where it was."""
490
511
  try:
491
512
  doc = tomllib.loads(text) if text.strip() else {}
492
513
  except ValueError as e:
493
514
  raise ValueError(f"the file is not valid TOML: {e}") from e
494
- have = (doc.get("permissions") or {}).get(decision) or []
515
+ have = (doc.get(section) or {}).get(decision) or []
495
516
  if entry in [str(x) for x in have]:
496
517
  return text
497
- header = re.search(r"^[ \t]*\[permissions\][ \t]*$", text, re.M)
518
+ header = re.search(rf"^[ \t]*\[{re.escape(section)}\][ \t]*$", text, re.M)
498
519
  if header is None:
499
520
  pad = "" if not text or text.endswith("\n\n") else ("\n" if text.endswith("\n") else "\n\n")
500
- return f'{text}{pad}[permissions]\n{decision} = ["{entry}"]\n'
521
+ return f'{text}{pad}[{section}]\n{decision} = ["{entry}"]\n'
501
522
  end = re.search(r"^[ \t]*\[", text[header.end():], re.M)
502
523
  stop = header.end() + (end.start() if end else len(text) - header.end())
503
524
  body = text[header.end():stop]
@@ -507,7 +528,7 @@ def add_entry(text: str, entry: str, decision: str = "allow") -> str:
507
528
  else:
508
529
  close = _closing(body, key.end() - 1)
509
530
  if close is None:
510
- raise ValueError(f"[permissions] {decision} is not a list Hum can add to")
531
+ raise ValueError(f"[{section}] {decision} is not a list Hum can add to")
511
532
  raw = body[key.end():close]
512
533
  inner = raw.strip()
513
534
  at = header.end() + close
@@ -518,7 +539,7 @@ def add_entry(text: str, entry: str, decision: str = "allow") -> str:
518
539
  out = head + ("," if inner and not inner.endswith(",") else "") + f'\n{pad}"{entry}",\n' + text[at:]
519
540
  else:
520
541
  out = text[:at] + (f'"{entry}"' if not inner or inner.endswith(",") else f', "{entry}"') + text[at:]
521
- if entry not in [str(x) for x in ((tomllib.loads(out).get("permissions") or {}).get(decision) or [])]:
542
+ if entry not in [str(x) for x in ((tomllib.loads(out).get(section) or {}).get(decision) or [])]:
522
543
  raise ValueError("the rule could not be written into the file")
523
544
  return out
524
545