hum-cli 0.2.69__py3-none-any.whl → 0.2.71__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 +1 -1
- hum/auth.py +40 -4
- hum/cli.py +8 -6
- hum/client.py +55 -27
- hum/core.py +120 -27
- hum/plain.py +14 -0
- hum/runtime/config.py +80 -0
- hum/runtime/loop.py +14 -2
- hum/runtime/netproxy.py +32 -4
- hum/runtime/permissions.py +40 -19
- hum/runtime/sandbox.py +10 -2
- hum/runtime/tools.py +4 -3
- hum/tui/cli.mjs +2213 -1283
- {hum_cli-0.2.69.dist-info → hum_cli-0.2.71.dist-info}/METADATA +8 -8
- {hum_cli-0.2.69.dist-info → hum_cli-0.2.71.dist-info}/RECORD +18 -18
- {hum_cli-0.2.69.dist-info → hum_cli-0.2.71.dist-info}/WHEEL +0 -0
- {hum_cli-0.2.69.dist-info → hum_cli-0.2.71.dist-info}/entry_points.txt +0 -0
- {hum_cli-0.2.69.dist-info → hum_cli-0.2.71.dist-info}/licenses/LICENSE +0 -0
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.
|
|
2
|
+
__version__ = "0.2.71"
|
hum/auth.py
CHANGED
|
@@ -39,7 +39,7 @@ def accounts_url(auth_url: str | None) -> str:
|
|
|
39
39
|
# what the server hands out is a cache stamped with the host that issued it, never used against another
|
|
40
40
|
# what is the server's word for this process alone, never written down: the gateway is asked at the call
|
|
41
41
|
# (hum.runtime.gateway), so a file from before a move cannot send a call to the gateway the person left
|
|
42
|
-
UNSAVED = ("stale", "gateway")
|
|
42
|
+
UNSAVED = ("stale", "stale_kind", "gateway")
|
|
43
43
|
ISSUED = ("api_base", "mcp", "plugins", "search_url", "routes", "models", "org", "project")
|
|
44
44
|
|
|
45
45
|
# Which client is asking, on every request to the deployment. The deployment keeps a floor of its own and answers
|
|
@@ -114,6 +114,11 @@ class Credentials:
|
|
|
114
114
|
org: dict[str, Any] | None = None # the organization this account is in, as the server names it
|
|
115
115
|
project: dict[str, Any] | None = None # the project the repository the refresh named is bound to, if any
|
|
116
116
|
stale: str | None = None # why the last refresh did not reach the server; never written to disk
|
|
117
|
+
# what kind of failure that was, which decides what the person is told: "unreachable" (the network, a timeout,
|
|
118
|
+
# the server erring or busy: nothing for the person to do, the last answer stands), "signin" (refused: hum
|
|
119
|
+
# login), "old" (this build is below the deployment's floor: hum update) or "other"; never written to disk
|
|
120
|
+
stale_kind: str | None = None
|
|
121
|
+
refreshed_at: float | None = None # when the server last answered a refresh (epoch seconds): the cache's age
|
|
117
122
|
|
|
118
123
|
@property
|
|
119
124
|
def logged_in(self) -> bool:
|
|
@@ -336,10 +341,12 @@ def refresh(c: Credentials | None = None, timeout: float = 3.0, client: Any = No
|
|
|
336
341
|
query = {"params": {"remote": remote}} if remote else {}
|
|
337
342
|
r = http.get(f"{c.auth_url}/me", headers=headers(c.access_token), **query)
|
|
338
343
|
if too_old(r):
|
|
339
|
-
c.stale = "this build is older than the deployment allows; run `hum update`"
|
|
344
|
+
c.stale, c.stale_kind = "this build is older than the deployment allows; run `hum update`", "old"
|
|
340
345
|
return c
|
|
341
346
|
if r.status_code != 200:
|
|
342
347
|
c.stale = f"HTTP {r.status_code}"
|
|
348
|
+
c.stale_kind = ("signin" if r.status_code in (401, 403)
|
|
349
|
+
else "unreachable" if r.status_code in (408, 429) or r.status_code >= 500 else "other")
|
|
343
350
|
return c
|
|
344
351
|
d = r.json()
|
|
345
352
|
m = d.get("model") or {}
|
|
@@ -357,17 +364,46 @@ def refresh(c: Credentials | None = None, timeout: float = 3.0, client: Any = No
|
|
|
357
364
|
c.org = dict(d["org"]) if isinstance(d.get("org"), dict) else None
|
|
358
365
|
c.project = dict(d["project"]) if isinstance(d.get("project"), dict) else None
|
|
359
366
|
c.issued_by = c.auth_url
|
|
360
|
-
c.stale = None
|
|
367
|
+
c.stale = c.stale_kind = None
|
|
368
|
+
c.refreshed_at = time.time()
|
|
361
369
|
if from_environment() is None:
|
|
362
370
|
save(c) # a hosted session's credentials are its environment: nothing of the job's goes on disk
|
|
363
371
|
except httpx.HTTPError as e:
|
|
364
372
|
c.stale = type(e).__name__.replace("Error", " error").lower() or "unreachable"
|
|
373
|
+
c.stale_kind = "unreachable"
|
|
365
374
|
except Exception as e: # not the network but this machine (an OpenSSL its policy refuses): its own words
|
|
366
|
-
c.stale = f"{type(e).__name__}: {e}"
|
|
375
|
+
c.stale, c.stale_kind = f"{type(e).__name__}: {e}", "other"
|
|
367
376
|
note("refresh_failed", c.stale, "refresh")
|
|
368
377
|
return c
|
|
369
378
|
|
|
370
379
|
|
|
380
|
+
def stale_line(c: Credentials, now: float | None = None) -> tuple[bool, str]:
|
|
381
|
+
"""What the person is told when a refresh did not land, and whether it is a warning. Only what the person can
|
|
382
|
+
act on is a warning, with the one step that mends it; a server that did not answer is a note: the last answer
|
|
383
|
+
stands, its age is said, and the next start asks again. A timeout is never mended by updating or signing in."""
|
|
384
|
+
host = urlsplit(c.auth_url).hostname or c.auth_url
|
|
385
|
+
if c.stale_kind == "old":
|
|
386
|
+
return True, f"{host}: {c.stale}"
|
|
387
|
+
if c.stale_kind == "signin":
|
|
388
|
+
return True, f"{host} refused your sign-in ({c.stale}) — run `hum login`"
|
|
389
|
+
if c.stale_kind == "unreachable":
|
|
390
|
+
age = f"from {ago(c.refreshed_at, now)}" if c.refreshed_at else "from your last sign-in"
|
|
391
|
+
chosen = "" if c.auth_url.rstrip("/") == BUILD_AUTH_URL and "HUM_AUTH_URL" not in os.environ \
|
|
392
|
+
else f" · {way_back(c.auth_url)}"
|
|
393
|
+
return False, f"{host} did not answer ({c.stale}) — using your model list and tool servers {age}{chosen}"
|
|
394
|
+
return True, f"{host}: {c.stale} — model list and tool servers not refreshed ({way_back(c.auth_url)})"
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def ago(t: float, now: float | None = None) -> str:
|
|
398
|
+
"""How long ago, in the one unit a person reads at a glance."""
|
|
399
|
+
s = max(0.0, (now if now is not None else time.time()) - t)
|
|
400
|
+
for unit, n in (("day", 86400), ("hour", 3600), ("minute", 60)):
|
|
401
|
+
if s >= n:
|
|
402
|
+
k = int(s // n)
|
|
403
|
+
return f"{k} {unit}{'s' if k != 1 else ''} ago"
|
|
404
|
+
return "just now"
|
|
405
|
+
|
|
406
|
+
|
|
371
407
|
def logout(client: Any = None, timeout: float = 5.0) -> str:
|
|
372
408
|
"""Forget the sign-in here AND revoke the token on the server. The local forget
|
|
373
409
|
always happens. Returns what the server said: "revoked", "unreachable", "refused"
|
hum/cli.py
CHANGED
|
@@ -786,13 +786,14 @@ def cmd_listen(ui: UI, cwd: Path, *, capacity: int, name: str | None, list_only:
|
|
|
786
786
|
|
|
787
787
|
|
|
788
788
|
def cmd_model(ui: UI, name: str | None) -> None:
|
|
789
|
-
|
|
789
|
+
from hum.runtime.config import keep
|
|
790
790
|
if name:
|
|
791
|
-
|
|
792
|
-
auth.save(c)
|
|
791
|
+
keep("name", None if name in ("default", "-") else name)
|
|
793
792
|
cfg = load_config()
|
|
794
|
-
|
|
795
|
-
|
|
793
|
+
source = {"HUM_MODEL": " (HUM_MODEL in your environment)", "server": " (the deployment's default)"}
|
|
794
|
+
ui.info(f"model: {cfg.model}" + source.get(cfg.model_from, "")
|
|
795
|
+
+ (f" via {cfg.api_base}" if cfg.api_base
|
|
796
|
+
else " (no host: `hum login`, or [model] api_base in config.toml)"))
|
|
796
797
|
|
|
797
798
|
|
|
798
799
|
def cmd_credits(ui: UI, code: str | None) -> int:
|
|
@@ -1533,7 +1534,8 @@ def _main(argv: list[str]) -> int:
|
|
|
1533
1534
|
# first and asks the server afterwards: nobody waits on the answer
|
|
1534
1535
|
c = auth.load() if a.cmd == "core" else auth.refresh()
|
|
1535
1536
|
if c is not None and c.logged_in and c.stale:
|
|
1536
|
-
|
|
1537
|
+
warning, line = auth.stale_line(c)
|
|
1538
|
+
(ui.warn if warning else ui.info)(line)
|
|
1537
1539
|
cfg = load_config()
|
|
1538
1540
|
if cfg.api_key is None and cfg.api_base is None and "/" in cfg.model and provider_of(cfg.model) in PROVIDER_ENV:
|
|
1539
1541
|
if (a.cmd in ("chat",
|
hum/client.py
CHANGED
|
@@ -51,7 +51,7 @@ from hum.runtime import team as teams
|
|
|
51
51
|
from hum.runtime import trust as repo_trust
|
|
52
52
|
from hum.runtime.agent_files import discover_agents, shell_name
|
|
53
53
|
from hum.runtime.ask import Asker
|
|
54
|
-
from hum.runtime.config import Config, MCPConfig, budget_usd, repository_servers
|
|
54
|
+
from hum.runtime.config import Config, MCPConfig, budget_usd, kept, repository_servers
|
|
55
55
|
from hum.runtime.constraints import Constraints
|
|
56
56
|
from hum.runtime.decision import DecisionReview
|
|
57
57
|
from hum.runtime.grader import PredicateGrader, mcp_grader
|
|
@@ -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
|
|
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
|
-
|
|
300
|
-
|
|
301
|
-
|
|
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
|
|
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
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
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,
|
|
421
|
-
else self.rules.write_project(entry,
|
|
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=
|
|
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(
|
|
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:
|
|
@@ -841,8 +846,7 @@ class Client:
|
|
|
841
846
|
"""What /model offers: every route the deployment gives this person (and the model in use, when it
|
|
842
847
|
is not one of them), each with the server's note; which one is in use, and which
|
|
843
848
|
is the default for new sessions (the person's choice, else the deployment's)."""
|
|
844
|
-
|
|
845
|
-
default = c.model or c.default_model
|
|
849
|
+
default = kept("name") or auth.load().default_model
|
|
846
850
|
by_name = {str(m.get("name")): m for m in self.cfg.models}
|
|
847
851
|
names = list(self.cfg.routes)
|
|
848
852
|
if self.cfg.model not in names:
|
|
@@ -867,7 +871,7 @@ class Client:
|
|
|
867
871
|
def effort_choices(self) -> list[dict[str, Any]]:
|
|
868
872
|
"""What /reasoning offers: every level, which one is in force (the deployment's default when
|
|
869
873
|
nothing was chosen), and which is the person's own default for new sessions."""
|
|
870
|
-
saved =
|
|
874
|
+
saved = kept("reasoning_effort")
|
|
871
875
|
current = self.cfg.reasoning_effort or DEFAULT_EFFORT
|
|
872
876
|
return [{"level": e, "current": e == current, "default": e == saved} for e in EFFORTS]
|
|
873
877
|
|
|
@@ -975,17 +979,41 @@ class Client:
|
|
|
975
979
|
d.may_start = lambda a: self.trust.allows or not repo_trust.repository_agent(a, self.trust.root, self.plugins)
|
|
976
980
|
return d
|
|
977
981
|
|
|
982
|
+
async def _ask_host(self, host: str, port: int) -> bool:
|
|
983
|
+
"""A confined command asked for a host off the list: the person's word, kept for the session or, on p, in
|
|
984
|
+
this project's [sandbox] allow_hosts; nobody to ask is a no."""
|
|
985
|
+
word = await self.ask_host(host, port) if self.ask_host is not None else "no"
|
|
986
|
+
if self.record is not None:
|
|
987
|
+
self.record.event("network_decided", host=host, port=port, decision=word)
|
|
988
|
+
if word not in ("session", "project"):
|
|
989
|
+
return False
|
|
990
|
+
px = self.executor.proxy
|
|
991
|
+
if px is not None and host not in px.allow:
|
|
992
|
+
px.allow.append(host)
|
|
993
|
+
if word == "project":
|
|
994
|
+
path = Path(self.rules.project_root or self.cwd) / ".hum" / "config.toml"
|
|
995
|
+
try:
|
|
996
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
997
|
+
text = path.read_text(encoding="utf-8") if path.exists() else ""
|
|
998
|
+
path.write_text(add_entry(text, host, "allow_hosts", "sandbox"), encoding="utf-8")
|
|
999
|
+
except (OSError, ValueError) as e:
|
|
1000
|
+
self.ui.warn(f"could not keep {host} for this project: {e}")
|
|
1001
|
+
where = "this project" if word == "project" else "this session"
|
|
1002
|
+
self.ui.info(f"network: {host} allowed for {where}")
|
|
1003
|
+
return True
|
|
1004
|
+
|
|
978
1005
|
def _network_refused(self, host: str, port: int, via: str) -> None:
|
|
979
1006
|
"""A host the list does not name was asked for: on the transcript, and said to the person."""
|
|
980
1007
|
if self.record is not None:
|
|
981
1008
|
self.record.event("network_refused", host=host, port=port, via=via)
|
|
982
|
-
self.ui.warn(f"network: {host} refused
|
|
1009
|
+
self.ui.warn(f"network: {host} refused" + ("" if self.executor.proxy and self.executor.proxy.ask
|
|
1010
|
+
else "; not on [sandbox] allow_hosts"))
|
|
983
1011
|
|
|
984
1012
|
async def _proxy_env(self) -> dict[str, str]:
|
|
985
1013
|
"""The proxy's variables for a tool server's process, once the proxy listens; nothing without one."""
|
|
986
1014
|
px = self.executor.proxy
|
|
987
|
-
if px is None:
|
|
988
|
-
return {}
|
|
1015
|
+
if px is None or not self.cfg.sandbox_allow_hosts:
|
|
1016
|
+
return {} # a tool server runs outside the sandbox: it is pointed at a list, never asked about each host
|
|
989
1017
|
await px.start()
|
|
990
1018
|
return px.env()
|
|
991
1019
|
|
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)
|
|
@@ -103,7 +107,7 @@ Front-end → core (commands)
|
|
|
103
107
|
{"cmd": "credits"} → info: the person's credits on the deployment; opens the page that adds more
|
|
104
108
|
|
|
105
109
|
Core → front-end (events); every event has "type"
|
|
106
|
-
hello {model, agents_model, user, cwd, tools, mcp, comms, version, byo, budget, compact_at, gate, images,
|
|
110
|
+
hello {model, model_from, agents_model, user, cwd, tools, mcp, comms, version, byo, budget, compact_at, gate, images,
|
|
107
111
|
run_id, session, instruction, goal, state, busy, phase, needs, needs_count, status_detail, questions}
|
|
108
112
|
state: new | idle | busy | waiting | paused
|
|
109
113
|
needs: what the session wants from a person: question | decision |
|
|
@@ -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)
|
|
@@ -219,10 +226,11 @@ from hum.runtime import team as teams
|
|
|
219
226
|
from hum.runtime import uploads as uploadsmod
|
|
220
227
|
from hum.runtime.background import Background
|
|
221
228
|
from hum.runtime.config import Config, remote_mounts
|
|
229
|
+
from hum.runtime.config import keep as keep_choice
|
|
222
230
|
from hum.runtime.hooks import Outcome
|
|
223
231
|
from hum.runtime.llm import ProviderError, describe_partial_call, error_text
|
|
224
232
|
from hum.runtime.models import Node, ToolResult, questions_of
|
|
225
|
-
from hum.runtime.permissions import
|
|
233
|
+
from hum.runtime.permissions import rule_words
|
|
226
234
|
from hum.runtime.result import duration
|
|
227
235
|
from hum.runtime.store import list_sessions, session_path
|
|
228
236
|
from hum.runtime.tools import CARRIER_SUFFIXES, Reflector, change_of, still_out
|
|
@@ -230,6 +238,11 @@ from hum.stream import Streamer
|
|
|
230
238
|
from hum.transport import MODES, InProcess, Reader, Socket, Writer
|
|
231
239
|
from hum.ui import UI
|
|
232
240
|
|
|
241
|
+
# the refresh at start runs after the surface is up, so its bound is how long to wait for an answer, not how long the
|
|
242
|
+
# person waits: generous, and a server that did not answer is asked again before anything is said
|
|
243
|
+
REFRESH_TIMEOUT_S = 10.0
|
|
244
|
+
REFRESH_RETRY_S = (2.0, 8.0)
|
|
245
|
+
|
|
233
246
|
# an idle session with nobody attached: the core leaves (hum resume comes back to the record)
|
|
234
247
|
IDLE_EXIT_S = float(os.environ.get("HUM_IDLE_EXIT_S") or 3600)
|
|
235
248
|
EMPTY_EXIT_S = float(os.environ.get("HUM_EMPTY_EXIT_S") or 60) # no session at all, nobody attached: sooner
|
|
@@ -246,6 +259,7 @@ MSG_MAX_BYTES = 100_000
|
|
|
246
259
|
AGENT_COMMANDS = frozenset({"hello", "send", "stop", "noop"})
|
|
247
260
|
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
261
|
GATE_TIMEOUT_S = 60.0 # a program that holds a gate and does not answer: the call is denied, never run
|
|
262
|
+
HOST_ASK_S = 300.0 # a network ask nobody answers: the connection is refused and the command reads why
|
|
249
263
|
# 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
264
|
# gate) to the owner's DM. The notify moment, the turn-end words, goes from _run whole
|
|
251
265
|
MOMENT_OF = {"question": "question", "proposal": "review"}
|
|
@@ -378,10 +392,12 @@ def on_contract(st: Any) -> bool:
|
|
|
378
392
|
and isinstance(st.get("diagnostics"), list) and isinstance(st.get("files"), list))
|
|
379
393
|
|
|
380
394
|
|
|
381
|
-
def mcp_call_desc(c: ToolCall) -> str | None:
|
|
395
|
+
def mcp_call_desc(c: ToolCall, width: int = 96) -> str | None:
|
|
382
396
|
"""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
|
|
384
|
-
|
|
397
|
+
the wire name — the server, the tool, and the short arguments that say what it is about, as
|
|
398
|
+
Claude Code heads an MCP call with its arguments: the one that names the thing bare (a path, a
|
|
399
|
+
name), the other short ones as `key: value`, as many as fit the width. Never a payload, never a
|
|
400
|
+
secret-named one."""
|
|
385
401
|
if "__" not in c.name:
|
|
386
402
|
return None
|
|
387
403
|
server, tool = c.name.split("__", 1)
|
|
@@ -389,14 +405,20 @@ def mcp_call_desc(c: ToolCall) -> str | None:
|
|
|
389
405
|
return isinstance(v, str) and 0 < len(v) <= 60 and "\n" not in v and " " not in v.strip()
|
|
390
406
|
def secret(k: str) -> bool:
|
|
391
407
|
return any(w in k.lower() for w in ("token", "key", "secret", "password", "auth", "credential"))
|
|
392
|
-
|
|
393
|
-
for k, v in c.arguments.items()
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
408
|
+
head = f"{server} · {tool}"
|
|
409
|
+
args = [(k, v) for k, v in c.arguments.items() if not secret(k)]
|
|
410
|
+
# what the core packed for the call (a path), else an argument whose name says it names a thing: shown bare
|
|
411
|
+
named = next((k for k, v in args if k.endswith(CARRIER_SUFFIXES) and short(v)), None) or next(
|
|
412
|
+
(k for k, v in args if k.lower() in NAMING_ARGS and short(v)), None)
|
|
413
|
+
out = head + (f" {str(c.arguments[named]).strip()}" if named else "")
|
|
414
|
+
rest = [f"{k}: {str(v).strip() if isinstance(v, str) else json.dumps(v)}" for k, v in args
|
|
415
|
+
if k != named and (short(v) or (isinstance(v, (int, float)) and not isinstance(v, bool)))]
|
|
416
|
+
shown: list[str] = []
|
|
417
|
+
for part in rest:
|
|
418
|
+
if len(out) + len(" (" + ", ".join([*shown, part]) + ")") > width:
|
|
419
|
+
break
|
|
420
|
+
shown.append(part)
|
|
421
|
+
return out + (f" ({', '.join(shown)})" if shown else "")
|
|
400
422
|
|
|
401
423
|
|
|
402
424
|
NAMING_ARGS = frozenset({"path", "file", "name", "case", "id", "unit", "job", "program", "member", "dsn", "table",
|
|
@@ -776,6 +798,7 @@ class Core:
|
|
|
776
798
|
# side tasks (a clipboard read): referenced so they cannot vanish, cancelled on quit
|
|
777
799
|
self._bg: set[asyncio.Task] = set()
|
|
778
800
|
self._last_proposal: dict[str, Any] | None = None
|
|
801
|
+
self._host_asks: dict[str, tuple[str, int, asyncio.Future[str]]] = {} # network asks waiting, by id
|
|
779
802
|
self._questions: asyncio.Task | None = None # the forwarder: an ask goes out as it is posted, nothing kept
|
|
780
803
|
self.tool_names: list[str] = []
|
|
781
804
|
self._ready = asyncio.Event() # the core can be looked at; hello waits for it, never for a tool server
|
|
@@ -828,6 +851,7 @@ class Core:
|
|
|
828
851
|
self.client.arrived = lambda: self.arrived
|
|
829
852
|
self.client.emit = self.wire.send # a routing decision reaches every front-end as it is recorded
|
|
830
853
|
self.client.expect_signin = self._expect_signin # a sign-in that comes back through the deployment
|
|
854
|
+
self.client.ask_host = self._ask_host # a confined command reached a host off the list
|
|
831
855
|
self.client.tools.background = self.background # a call that outlives its turn is watched, and wakes the model
|
|
832
856
|
|
|
833
857
|
def wanted(self) -> tuple[str | None, list[dict[str, Any]]]:
|
|
@@ -932,14 +956,19 @@ class Core:
|
|
|
932
956
|
latest is pushed to the surfaces; the rest stands until the next start."""
|
|
933
957
|
try:
|
|
934
958
|
remote = await self._workspace_remote()
|
|
935
|
-
c = await asyncio.to_thread(auth.refresh, remote=remote)
|
|
959
|
+
c = await asyncio.to_thread(auth.refresh, timeout=REFRESH_TIMEOUT_S, remote=remote)
|
|
960
|
+
for wait in REFRESH_RETRY_S: # nobody waits on this: a slow or busy server is asked again, not reported
|
|
961
|
+
if c is None or c.stale_kind != "unreachable":
|
|
962
|
+
break
|
|
963
|
+
await asyncio.sleep(wait)
|
|
964
|
+
c = await asyncio.to_thread(auth.refresh, timeout=REFRESH_TIMEOUT_S, remote=remote)
|
|
936
965
|
except Exception: # nothing here is worth a line: the last answer stands
|
|
937
966
|
return
|
|
938
967
|
if c is None or not c.logged_in:
|
|
939
968
|
return
|
|
940
969
|
if c.stale:
|
|
941
|
-
|
|
942
|
-
|
|
970
|
+
warning, line = auth.stale_line(c)
|
|
971
|
+
(self.ui.warn if warning else self.ui.info)(line)
|
|
943
972
|
return
|
|
944
973
|
self.cfg.latest_version, self.cfg.release_notes_url = c.latest_version, c.release_notes_url
|
|
945
974
|
self.cfg.routes = list(c.routes)
|
|
@@ -1029,7 +1058,8 @@ class Core:
|
|
|
1029
1058
|
every attached surface when the session under them changes — coming back to a session
|
|
1030
1059
|
is the same act whether it was still running or was read from the record."""
|
|
1031
1060
|
needs, opens = self.wanted()
|
|
1032
|
-
self.wire.send("hello", to=to, model=self.cfg.model,
|
|
1061
|
+
self.wire.send("hello", to=to, model=self.cfg.model, model_from=self.cfg.model_from,
|
|
1062
|
+
agents_model=self.cfg.agents_model, routes=self.cfg.routes,
|
|
1033
1063
|
user=self.cfg.user, cwd=str(self.cwd), tools=self.tool_names,
|
|
1034
1064
|
mcp=self.client.mounts, mounting=self.client.still_mounting, comms=self._comms_wire(),
|
|
1035
1065
|
version=__version__, latest_version=self.cfg.latest_version,
|
|
@@ -1058,6 +1088,8 @@ class Core:
|
|
|
1058
1088
|
self.wire.send("idle", to=to)
|
|
1059
1089
|
if self.human.waiting is not None and self._last_proposal is not None:
|
|
1060
1090
|
self.wire.send("proposal", to=to, **self._last_proposal)
|
|
1091
|
+
for hid, (host, port, _) in self._host_asks.items(): # a connection still waiting on the person's word
|
|
1092
|
+
self.wire.send("network_ask", to=to, id=hid, host=host, port=port)
|
|
1061
1093
|
# every ask still open on the record, oldest first: a surface that reads one event at a time sees them all
|
|
1062
1094
|
for q in opens:
|
|
1063
1095
|
self.wire.send("question", to=to, **ask.for_wire(q))
|
|
@@ -1656,15 +1688,25 @@ class Core:
|
|
|
1656
1688
|
self.ui.info("\n".join(f"{p['call_id']} {p['name']}" + (f" task {p['task_id']}" if p.get("task_id") else "")
|
|
1657
1689
|
+ f" {p['elapsed_s']:.0f}s" for p in out) if out else "no calls are out")
|
|
1658
1690
|
|
|
1691
|
+
def _keep(self, key: str, value: str) -> str:
|
|
1692
|
+
"""Keep a choice for new sessions (config.toml [model]) and say so; and when something the person set
|
|
1693
|
+
wins over it at the next start, name that too, so the next banner is never a surprise."""
|
|
1694
|
+
try:
|
|
1695
|
+
if keep_choice(key, value) is None:
|
|
1696
|
+
return "" # a hosted session: the job's machine keeps nothing
|
|
1697
|
+
except (OSError, ValueError) as e:
|
|
1698
|
+
return f" · not kept for new sessions: {e}"
|
|
1699
|
+
env = "HUM_MODEL" if key == "name" else "HUM_REASONING_EFFORT"
|
|
1700
|
+
if os.environ.get(env):
|
|
1701
|
+
return f" · kept for new sessions, but {env}={os.environ[env]} in your environment wins"
|
|
1702
|
+
return " · the default for new sessions"
|
|
1703
|
+
|
|
1659
1704
|
async def _cmd_model(self, cmd: dict[str, Any], w: Writer | None) -> None:
|
|
1660
1705
|
name = str(cmd.get("name", "")).strip()
|
|
1661
1706
|
if name:
|
|
1662
1707
|
text = self.client.switch_model(name, self.session, self.runner)
|
|
1663
1708
|
if cmd.get("default"):
|
|
1664
|
-
|
|
1665
|
-
c.model = name
|
|
1666
|
-
auth.save(c)
|
|
1667
|
-
text += " · the default for new sessions"
|
|
1709
|
+
text += self._keep("name", name)
|
|
1668
1710
|
self.ui.info(text)
|
|
1669
1711
|
else:
|
|
1670
1712
|
self.wire.send("models", items=self.client.model_choices(), via=self.cfg.api_base)
|
|
@@ -1700,14 +1742,63 @@ class Core:
|
|
|
1700
1742
|
self.ui.warn(f"{e.message} — {e.hint}")
|
|
1701
1743
|
return
|
|
1702
1744
|
if cmd.get("default"):
|
|
1703
|
-
|
|
1704
|
-
c.reasoning_effort = level
|
|
1705
|
-
auth.save(c)
|
|
1706
|
-
text += " · the default for new sessions"
|
|
1745
|
+
text += self._keep("reasoning_effort", level)
|
|
1707
1746
|
self.ui.info(text)
|
|
1708
1747
|
else:
|
|
1709
1748
|
self.wire.send("reasoning", items=self.client.effort_choices())
|
|
1710
1749
|
|
|
1750
|
+
async def _ask_host(self, host: str, port: int) -> str:
|
|
1751
|
+
"""A host the proxy has not seen, put to whoever is at the terminal; nobody there, or nobody answering in
|
|
1752
|
+
HOST_ASK_S, is a no, and the command reads the refusal."""
|
|
1753
|
+
if self.wire.interactive == 0:
|
|
1754
|
+
return "no"
|
|
1755
|
+
hid = f"n{len(self._host_asks)}-{os.urandom(3).hex()}"
|
|
1756
|
+
fut: asyncio.Future[str] = asyncio.get_running_loop().create_future()
|
|
1757
|
+
self._host_asks[hid] = (host, port, fut)
|
|
1758
|
+
self.wire.send("network_ask", id=hid, host=host, port=port)
|
|
1759
|
+
self._notify("proposal", f"network: may commands reach {host}?")
|
|
1760
|
+
try:
|
|
1761
|
+
return await asyncio.wait_for(asyncio.shield(fut), HOST_ASK_S)
|
|
1762
|
+
except asyncio.TimeoutError:
|
|
1763
|
+
return "no"
|
|
1764
|
+
finally:
|
|
1765
|
+
self._host_asks.pop(hid, None)
|
|
1766
|
+
self.wire.send("network_closed", id=hid)
|
|
1767
|
+
|
|
1768
|
+
async def _cmd_network(self, cmd: dict[str, Any], w: Writer | None) -> None:
|
|
1769
|
+
ask = self._host_asks.get(str(cmd.get("id") or ""))
|
|
1770
|
+
decision = str(cmd.get("decision") or "no")
|
|
1771
|
+
if ask is None or ask[2].done():
|
|
1772
|
+
self.wire.send("warn", to=w, text="network: nothing is waiting on that")
|
|
1773
|
+
return
|
|
1774
|
+
ask[2].set_result(decision if decision in ("session", "project") else "no")
|
|
1775
|
+
|
|
1776
|
+
async def _cmd_add_dir(self, cmd: dict[str, Any], w: Writer | None) -> None:
|
|
1777
|
+
"""One more directory the model may write under, for this session: its commands and its file tools."""
|
|
1778
|
+
sb = getattr(self.client.executor, "sandbox", None)
|
|
1779
|
+
raw = str(cmd.get("path") or "").strip()
|
|
1780
|
+
if not raw:
|
|
1781
|
+
self.wire.send("warn", to=w, text="/add-dir <directory>")
|
|
1782
|
+
return
|
|
1783
|
+
d = Path(os.path.expanduser(raw))
|
|
1784
|
+
d = (d if d.is_absolute() else self.cwd / d).resolve()
|
|
1785
|
+
if not d.is_dir():
|
|
1786
|
+
self.wire.send("warn", to=w, text=f"add-dir: {d} is not a directory")
|
|
1787
|
+
return
|
|
1788
|
+
if sb is None or not sb.on:
|
|
1789
|
+
self.ui.info(f"no sandbox here: the model can already write under {d}")
|
|
1790
|
+
return
|
|
1791
|
+
hidden = [h for h in sb.hidden_paths() if d == h or d.is_relative_to(h) or h.is_relative_to(d)]
|
|
1792
|
+
if hidden or d == Path.home().resolve() or d == Path(d.anchor):
|
|
1793
|
+
self.wire.send("warn", to=w, text=f"add-dir: {d} holds what the sandbox keeps from the model; name a "
|
|
1794
|
+
"directory inside it")
|
|
1795
|
+
return
|
|
1796
|
+
if d not in [Path(p) for p in sb.writable]:
|
|
1797
|
+
sb.writable.append(d)
|
|
1798
|
+
if self.session is not None:
|
|
1799
|
+
self.session.event("add_dir", path=str(d))
|
|
1800
|
+
self.ui.info(f"the model may now write under {d} for this session")
|
|
1801
|
+
|
|
1711
1802
|
async def _cmd_decide(self, cmd: dict[str, Any], w: Writer | None) -> None:
|
|
1712
1803
|
str(cmd.get("cmd"))
|
|
1713
1804
|
note = str(cmd.get("note", "")).strip()
|
|
@@ -2425,6 +2516,8 @@ class Core:
|
|
|
2425
2516
|
"model": _cmd_model,
|
|
2426
2517
|
"reasoning": _cmd_reasoning,
|
|
2427
2518
|
"decide": _cmd_decide,
|
|
2519
|
+
"network": _cmd_network,
|
|
2520
|
+
"add_dir": _cmd_add_dir,
|
|
2428
2521
|
"gate": _cmd_gate,
|
|
2429
2522
|
"agent": _cmd_agent,
|
|
2430
2523
|
"hook": _cmd_hook,
|
|
@@ -2471,8 +2564,8 @@ class Core:
|
|
|
2471
2564
|
calls.append({"id": c.id, "name": c.name, "args": {}, "desc": f"{c.name} (could not render: "
|
|
2472
2565
|
f"{error_text(e)})"})
|
|
2473
2566
|
remember = self.client.shapes(turn)
|
|
2474
|
-
self._last_proposal = {"content": turn.content, "calls": calls, "remember": remember,
|
|
2475
|
-
"remember_text": ", ".join(
|
|
2567
|
+
self._last_proposal = {"content": turn.content, "calls": calls, "remember": [e for e, _ in remember],
|
|
2568
|
+
"remember_text": ", ".join(rule_words(e, k) for e, k in remember),
|
|
2476
2569
|
# a sub-agent's proposal says which sub-agent: its number, kind and job
|
|
2477
2570
|
**({"agent": dict(self.human.asking)} if self.human.asking else {})}
|
|
2478
2571
|
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)]
|