agent-link-mcp 0.1.0__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.
agent_link/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """agent-link: let coding agents on different computers work on one repo together."""
3
+
4
+ __version__ = "0.1.0"
agent_link/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ from .cli import main
3
+
4
+ main()
agent_link/claims.py ADDED
@@ -0,0 +1,112 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """Claims: before working on files, folders or a task, an agent claims them, and nobody else can
3
+ claim anything overlapping until they're released or run out.
4
+
5
+ Items are paths relative to the repo root ("src/parser.py", "docs/", "." for the whole repo) or
6
+ tasks ("task:release notes"). A folder covers everything inside it. Paths are compared without
7
+ regard to case, since a friend's machine may have a case-insensitive file system: a needless
8
+ conflict is cheap, two agents editing one file is not.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ import time
15
+
16
+ MAX_MINUTES = 8 * 60
17
+ MAX_ITEMS = 50
18
+
19
+
20
+ def norm_item(item: str) -> str:
21
+ """The canonical form of a claimed item; raises ValueError for one that can't be claimed."""
22
+ item = str(item).strip()
23
+ if item[:5].lower() == "task:":
24
+ name = re.sub(r"\s+", " ", item[5:]).strip().lower()
25
+ if not name:
26
+ raise ValueError("a task needs a name, like task:release-notes")
27
+ return "task:" + name[:120]
28
+ parts = [p for p in item.replace("\\", "/").split("/") if p not in ("", ".")]
29
+ if ".." in parts:
30
+ raise ValueError(f"{item!r} leaves the repo")
31
+ return "/".join(parts)[:400] or "."
32
+
33
+
34
+ def _key(item: str) -> str:
35
+ return item.casefold()
36
+
37
+
38
+ def overlaps(a: str, b: str) -> bool:
39
+ """Whether two canonical items cover any of the same thing."""
40
+ a, b = _key(a), _key(b)
41
+ if a.startswith("task:") or b.startswith("task:"):
42
+ return a == b
43
+ return a == b or "." in (a, b) or a.startswith(b + "/") or b.startswith(a + "/")
44
+
45
+
46
+ def covers(outer: str, inner: str) -> bool:
47
+ o, i = _key(outer), _key(inner)
48
+ if o.startswith("task:") or i.startswith("task:"):
49
+ return o == i
50
+ return o in (i, ".") or i.startswith(o + "/")
51
+
52
+
53
+ class ClaimTable:
54
+ def __init__(self) -> None:
55
+ self.claims: list[dict] = []
56
+
57
+ def _expire(self, now: float) -> None:
58
+ self.claims = [c for c in self.claims if c["expires"] > now]
59
+
60
+ def active(self, now: float | None = None) -> list[dict]:
61
+ self._expire(time.time() if now is None else now)
62
+ return list(self.claims)
63
+
64
+ def claim(self, session: str, name: str, items: list[str], note: str = "",
65
+ minutes: float = 30, now: float | None = None) -> dict:
66
+ """All or nothing: either every item is granted (renewing ones the session already
67
+ holds), or none is and the conflicts say who holds what."""
68
+ now = time.time() if now is None else now
69
+ self._expire(now)
70
+ if not items:
71
+ raise ValueError("nothing to claim")
72
+ if len(items) > MAX_ITEMS:
73
+ raise ValueError(f"at most {MAX_ITEMS} items at once; claim a folder instead")
74
+ wanted = list(dict.fromkeys(norm_item(i) for i in items))
75
+ minutes = min(max(float(minutes), 1), MAX_MINUTES)
76
+ conflicts = [
77
+ {"item": it, "holder": c["name"], "their_item": c["item"], "note": c["note"],
78
+ "minutes_left": round((c["expires"] - now) / 60, 1)}
79
+ for it in wanted for c in self.claims
80
+ if c["session"] != session and overlaps(c["item"], it)
81
+ ]
82
+ if conflicts:
83
+ return {"granted": [], "conflicts": conflicts}
84
+ for it in wanted:
85
+ self.claims = [c for c in self.claims
86
+ if not (c["session"] == session and _key(c["item"]) == _key(it))]
87
+ self.claims.append({"session": session, "name": name, "item": it,
88
+ "note": note.strip()[:300], "since": now, "expires": now + minutes * 60})
89
+ return {"granted": wanted, "conflicts": [], "minutes": minutes}
90
+
91
+ def release(self, session: str, items: list[str] | None = None) -> list[str]:
92
+ """Release the session's claims covered by `items` (a folder releases what's inside it),
93
+ or all of them when `items` is None."""
94
+ targets = None if items is None else [norm_item(i) for i in items]
95
+ dropped, kept = [], []
96
+ for c in self.claims:
97
+ if c["session"] == session and (targets is None or any(covers(t, c["item"]) for t in targets)):
98
+ dropped.append(c["item"])
99
+ else:
100
+ kept.append(c)
101
+ self.claims = kept
102
+ return dropped
103
+
104
+ def drop_session(self, session: str) -> list[str]:
105
+ dropped = [c["item"] for c in self.claims if c["session"] == session]
106
+ self.claims = [c for c in self.claims if c["session"] != session]
107
+ return dropped
108
+
109
+ def rename(self, session: str, name: str) -> None:
110
+ for c in self.claims:
111
+ if c["session"] == session:
112
+ c["name"] = name
agent_link/cli.py ADDED
@@ -0,0 +1,69 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """The `agent-link` command: the MCP server (stdio), plus saving the ngrok authtoken."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import getpass
8
+ import os
9
+ import signal
10
+ import sys
11
+
12
+ import anyio
13
+
14
+ from . import __version__
15
+
16
+
17
+ async def _serve() -> None:
18
+ import logging
19
+
20
+ from .server import create_server
21
+
22
+ for noisy in ("httpx2", "httpx", "uvicorn.error"): # stderr is the MCP client's log; keep it useful
23
+ logging.getLogger(noisy).setLevel(logging.WARNING)
24
+
25
+ mcp, me = create_server()
26
+
27
+ # MCP clients (Claude Code, opencode) usually stop servers with a signal rather than by
28
+ # closing stdin. Leave the hub (freeing our claims) and stop hosting before going.
29
+ def on_signal(signum: int, _frame: object) -> None:
30
+ me.close_now()
31
+ os._exit(128 + signum)
32
+
33
+ for name in ("SIGTERM", "SIGHUP", "SIGINT", "SIGBREAK"):
34
+ if hasattr(signal, name):
35
+ signal.signal(getattr(signal, name), on_signal)
36
+ try:
37
+ await mcp.run_stdio_async()
38
+ finally:
39
+ with anyio.CancelScope(shield=True):
40
+ await me.close() # leave the hub (releasing claims) and stop hosting
41
+
42
+
43
+ def main(argv: list[str] | None = None) -> None:
44
+ parser = argparse.ArgumentParser(
45
+ prog="agent-link",
46
+ description="MCP server that lets coding agents on different computers work on one repo together. "
47
+ "Without a command it serves MCP on stdio: claude mcp add agent-link -- agent-link")
48
+ parser.add_argument("--version", action="version", version=f"agent-link {__version__}")
49
+ sub = parser.add_subparsers(dest="command")
50
+ tok = sub.add_parser("set-token", help="save the ngrok authtoken used for hosting")
51
+ tok.add_argument("token", nargs="?", help="the token (asked for when left out, so it stays out of shell history)")
52
+ args = parser.parse_args(argv)
53
+
54
+ if args.command == "set-token":
55
+ from .host import save_ngrok_token, token_file
56
+
57
+ print("Your authtoken is at https://dashboard.ngrok.com/get-started/your-authtoken", file=sys.stderr)
58
+ token = args.token or getpass.getpass("ngrok authtoken: ")
59
+ try:
60
+ save_ngrok_token(token)
61
+ except ValueError as exc:
62
+ sys.exit(f"agent-link: {exc}")
63
+ print(f"Saved to {token_file()}.", file=sys.stderr)
64
+ return
65
+ anyio.run(_serve)
66
+
67
+
68
+ if __name__ == "__main__":
69
+ main()
agent_link/client.py ADDED
@@ -0,0 +1,209 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """Talking to a hub from an agent's machine, and what that machine knows about its repo."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ import socket
8
+ import subprocess
9
+ import sys
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+
13
+ import anyio
14
+ import httpx2
15
+
16
+ from . import __version__
17
+ from .host import summary_store
18
+ from .hub import MAX_WAIT, PROTOCOL
19
+ from .summary import SummaryStore, from_list
20
+
21
+
22
+ class NotConnected(Exception):
23
+ pass
24
+
25
+
26
+ class HubUnreachable(Exception):
27
+ pass
28
+
29
+
30
+ # git --------------------------------------------------------------------------------------
31
+ # No console window flashing up for every git call when the MCP client runs us without one.
32
+ _NO_WINDOW = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
33
+
34
+
35
+ def git(cwd: str, *args: str) -> str:
36
+ try:
37
+ return subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, timeout=5,
38
+ encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL,
39
+ creationflags=_NO_WINDOW).stdout.strip()
40
+ except (OSError, subprocess.SubprocessError):
41
+ return ""
42
+
43
+
44
+ def repo_identity(cwd: str) -> str:
45
+ """The repo as everyone would name it: its origin URL without scheme, user or .git (so
46
+ https and ssh clones match), or the folder name without a remote."""
47
+ url = git(cwd, "config", "--get", "remote.origin.url")
48
+ if not url:
49
+ top = git(cwd, "rev-parse", "--show-toplevel")
50
+ return os.path.basename(top) if top else ""
51
+ url = url.strip().removesuffix("/").removesuffix(".git")
52
+ if "://" not in url and ":" in url: # scp-like: git@host:owner/repo
53
+ url = url.replace(":", "/", 1)
54
+ url = url.split("://", 1)[-1]
55
+ return url.split("@", 1)[-1].lower()
56
+
57
+
58
+ def default_name(cwd: str) -> str:
59
+ return (git(cwd, "config", "user.name") or os.environ.get("USER") or os.environ.get("USERNAME")
60
+ or socket.gethostname()).strip()[:40]
61
+
62
+
63
+ @dataclass
64
+ class Workspace:
65
+ """The directory the agent works in."""
66
+
67
+ cwd: str = field(default_factory=os.getcwd)
68
+
69
+ @property
70
+ def root(self) -> str:
71
+ return os.path.realpath(git(self.cwd, "rev-parse", "--show-toplevel") or self.cwd)
72
+
73
+ def presence(self) -> dict:
74
+ return {"repo": repo_identity(self.cwd), "branch": git(self.cwd, "rev-parse", "--abbrev-ref", "HEAD"),
75
+ "commit": git(self.cwd, "rev-parse", "--short", "HEAD")}
76
+
77
+ def relative(self, item: str) -> str:
78
+ """A claimed path as the others see it: relative to the repo root, whatever the agent's
79
+ current directory. Tasks pass through."""
80
+ item = str(item).strip()
81
+ if item[:5].lower() == "task:":
82
+ return item
83
+ root = self.root
84
+ path = os.path.realpath(os.path.join(os.path.realpath(self.cwd), os.path.expanduser(item)))
85
+ try:
86
+ rel = os.path.relpath(path, root)
87
+ except ValueError: # Windows: another drive
88
+ rel = ".."
89
+ if rel == ".." or rel.startswith(".." + os.sep) or os.path.isabs(rel):
90
+ raise ValueError(f"{item} is outside the repo ({root})")
91
+ return Path(rel).as_posix()
92
+
93
+
94
+ # the hub ----------------------------------------------------------------------------------
95
+ @dataclass
96
+ class HubClient:
97
+ url: str
98
+ key: str
99
+ session: str
100
+ name: str
101
+ workspace: Workspace
102
+ joined_name: str = ""
103
+ project: str = ""
104
+ footer: dict = field(default_factory=dict)
105
+ state: Path | None = None # where the summary copy is kept (default: the state dir)
106
+ store: SummaryStore | None = None
107
+ _summary_v: str = ""
108
+ _http: httpx2.AsyncClient | None = None
109
+
110
+ @property
111
+ def headers(self) -> dict:
112
+ return {
113
+ "Authorization": f"Bearer {self.key}",
114
+ "ngrok-skip-browser-warning": "1", # no ngrok interstitial page
115
+ "User-Agent": f"agent-link/{__version__}",
116
+ }
117
+
118
+ async def _post(self, op: str, body: dict, timeout: float) -> dict:
119
+ if self._http is None:
120
+ self._http = httpx2.AsyncClient(headers=self.headers)
121
+ presence = await anyio.to_thread.run_sync(self.workspace.presence)
122
+ payload = {"protocol": PROTOCOL, "session": self.session, **presence, **body}
123
+ try:
124
+ r = await self._http.post(f"{self.url}/api/{op}", json=payload, timeout=timeout)
125
+ except httpx2.HTTPError as exc:
126
+ raise HubUnreachable(
127
+ f"can't reach the hub ({exc.__class__.__name__}: {exc}). If the host's session ended, anyone can "
128
+ "`host` again (the summary carries over) and share the new link.") from None
129
+ try:
130
+ data = r.json()
131
+ except ValueError:
132
+ data = {}
133
+ if r.status_code == 409 and op != "hello":
134
+ raise _Rejoin()
135
+ if r.status_code != 200:
136
+ if r.status_code in (404, 502, 503, 504) and not data:
137
+ raise HubUnreachable(f"the hub isn't there (HTTP {r.status_code}); has the host stopped?")
138
+ raise RuntimeError(data.get("error") or f"the hub answered HTTP {r.status_code}")
139
+ return data
140
+
141
+ async def call(self, op: str, http_timeout: float = 20, **body) -> dict:
142
+ try:
143
+ data = await self._post(op, body, http_timeout)
144
+ except _Rejoin: # the hub restarted or forgot us: join again, transparently
145
+ await self.hello()
146
+ data = await self._post(op, body, http_timeout)
147
+ self.footer = data.pop("_", {})
148
+ if self.footer.get("summary_v") and self.footer["summary_v"] != self._summary_v and op not in ("sync", "summary"):
149
+ await self.pull_summary()
150
+ return data
151
+
152
+ async def hello(self) -> dict:
153
+ res = await self._post("hello", {"name": self.name, "machine": socket.gethostname()}, 20)
154
+ self.footer = res.pop("_", {})
155
+ self.joined_name, self.project = res["name"], res["project"]
156
+ self.store = summary_store(self.project, self.state)
157
+ await self.push_summary()
158
+ return res
159
+
160
+ async def push_summary(self) -> dict:
161
+ """Send our copy of the summary to the hub (so nothing anyone added is lost) and keep the
162
+ merged result."""
163
+ assert self.store is not None
164
+ local = await anyio.to_thread.run_sync(self.store.load)
165
+ res = await self._post("sync", {"entries": list(local.values())}, 30)
166
+ return await self._keep(res)
167
+
168
+ async def pull_summary(self) -> dict:
169
+ return await self._keep(await self._post("summary", {}, 30))
170
+
171
+ async def _keep(self, res: dict) -> dict:
172
+ self.footer = res.pop("_", self.footer)
173
+ self._summary_v = self.footer.get("summary_v", "")
174
+ entries = from_list(res.get("entries"))
175
+ if self.store is not None:
176
+ entries = await anyio.to_thread.run_sync(self.store.save, entries)
177
+ return entries
178
+
179
+ async def wait(self, timeout: float, thread: str = "") -> dict:
180
+ """Long-poll in rounds the tunnel won't cut, until a message comes or time runs out."""
181
+ deadline = anyio.current_time() + timeout
182
+ while True:
183
+ left = deadline - anyio.current_time()
184
+ res = await self.call("wait", http_timeout=min(left, MAX_WAIT) + 15,
185
+ timeout=max(0.0, min(left, MAX_WAIT)), thread=thread)
186
+ if res["messages"] or left <= MAX_WAIT:
187
+ return res
188
+
189
+ def leave_now(self) -> None:
190
+ """Leave without the event loop (from a signal handler), best effort."""
191
+ try:
192
+ httpx2.post(f"{self.url}/api/leave", json={"protocol": PROTOCOL, "session": self.session},
193
+ headers=self.headers, timeout=3)
194
+ except Exception:
195
+ pass
196
+
197
+ async def close(self, leave: bool = True) -> None:
198
+ if leave:
199
+ try:
200
+ await self._post("leave", {}, 5)
201
+ except Exception:
202
+ pass
203
+ if self._http is not None:
204
+ await self._http.aclose()
205
+ self._http = None
206
+
207
+
208
+ class _Rejoin(Exception):
209
+ pass
agent_link/host.py ADDED
@@ -0,0 +1,214 @@
1
+ # SPDX-License-Identifier: GPL-3.0-or-later
2
+ """Hosting: running a hub on this machine and publishing it through an ngrok tunnel."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ import re
8
+ import secrets
9
+ import sys
10
+ import threading
11
+ import time
12
+ from pathlib import Path
13
+ from urllib.parse import parse_qs, urlparse
14
+
15
+ from .hub import Hub
16
+ from .paths import config_dir, slug, state_dir, write_private
17
+ from .summary import SummaryStore
18
+
19
+ NO_TOKEN = """\
20
+ Hosting needs an ngrok authtoken (only the host needs one; joining doesn't). Once:
21
+ 1. Sign up for a free ngrok account: https://dashboard.ngrok.com/signup
22
+ 2. Copy your authtoken: https://dashboard.ngrok.com/get-started/your-authtoken
23
+ 3. Either run `agent-link set-token` in a terminal and paste it there (it stays out of this chat),
24
+ or call `host` again with authtoken=<token>. It's saved either way, so this is needed once.
25
+ Setting NGROK_AUTHTOKEN in the environment works too."""
26
+
27
+
28
+ def token_file() -> Path:
29
+ return config_dir() / "ngrok-authtoken"
30
+
31
+
32
+ def _ngrok_config_files() -> list[Path]:
33
+ home = Path.home()
34
+ files = [Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config") / "ngrok" / "ngrok.yml",
35
+ home / "Library" / "Application Support" / "ngrok" / "ngrok.yml",
36
+ home / ".ngrok2" / "ngrok.yml"]
37
+ if sys.platform == "win32" and os.environ.get("LOCALAPPDATA"):
38
+ files.append(Path(os.environ["LOCALAPPDATA"]) / "ngrok" / "ngrok.yml")
39
+ return files
40
+
41
+
42
+ def ngrok_token() -> str | None:
43
+ """NGROK_AUTHTOKEN, the token agent-link saved, or the one the ngrok agent is set up with."""
44
+ if tok := os.environ.get("NGROK_AUTHTOKEN", "").strip():
45
+ return tok
46
+ try:
47
+ if tok := token_file().read_text(encoding="utf-8").strip():
48
+ return tok
49
+ except OSError:
50
+ pass
51
+ if os.environ.get("AGENT_LINK_HOME"): # isolated (tests): don't look at the real ngrok config
52
+ return None
53
+ for cfg in _ngrok_config_files():
54
+ try:
55
+ m = re.search(r"^\s*authtoken:\s*['\"]?([\w-]+)", cfg.read_text(encoding="utf-8"), re.M)
56
+ except OSError:
57
+ continue
58
+ if m:
59
+ return m.group(1)
60
+ return None
61
+
62
+
63
+ def save_ngrok_token(token: str) -> None:
64
+ token = token.strip()
65
+ if not re.fullmatch(r"[\w-]{20,}", token):
66
+ raise ValueError("that doesn't look like an ngrok authtoken")
67
+ write_private(token_file(), token + "\n")
68
+
69
+
70
+ def link_key(project: str, rotate: bool = False, state: Path | None = None) -> str:
71
+ """The secret in this project's join link. It's kept, so a restarted hub keeps its link
72
+ (ngrok gives free accounts a fixed domain); rotating it locks out everyone with the old link."""
73
+ path = (state or state_dir()) / "keys" / f"{slug(project)}.key"
74
+ if not rotate:
75
+ try:
76
+ if key := path.read_text(encoding="utf-8").strip():
77
+ return key
78
+ except OSError:
79
+ pass
80
+ key = secrets.token_urlsafe(24)
81
+ write_private(path, key + "\n")
82
+ return key
83
+
84
+
85
+ def _joined_file(repo: str, state: Path | None) -> Path:
86
+ return (state or state_dir()) / "joined" / f"{slug(repo)}.link"
87
+
88
+
89
+ def remember_link(repo: str, link: str, state: Path | None = None) -> None:
90
+ """Keep the last link joined from this repo, so the next session can join without asking."""
91
+ write_private(_joined_file(repo, state), link.strip() + "\n")
92
+
93
+
94
+ def remembered_link(repo: str, state: Path | None = None) -> str | None:
95
+ try:
96
+ return _joined_file(repo, state).read_text(encoding="utf-8").strip() or None
97
+ except OSError:
98
+ return None
99
+
100
+
101
+ def make_link(url: str, key: str) -> str:
102
+ return f"{url.rstrip('/')}/?key={key}"
103
+
104
+
105
+ def parse_link(link: str) -> tuple[str, str]:
106
+ """A join link -> (hub URL, key)."""
107
+ link = link.strip().strip("<>\"'")
108
+ u = urlparse(link)
109
+ key = (parse_qs(u.query).get("key") or [""])[0]
110
+ if u.scheme not in ("http", "https") or not u.netloc or not key:
111
+ raise ValueError("that isn't an agent-link join link (it looks like https://....ngrok-free.dev/?key=...)")
112
+ return f"{u.scheme}://{u.netloc}{u.path.rstrip('/')}", key
113
+
114
+
115
+ def _outside_loop(fn, *args, **kwargs):
116
+ """Call an ngrok SDK function in a thread without an event loop. Inside a running loop the
117
+ SDK returns a task instead of doing the work, which nobody would await."""
118
+ out: dict = {}
119
+
120
+ def run() -> None:
121
+ try:
122
+ out["value"] = fn(*args, **kwargs)
123
+ except BaseException as exc: # noqa: BLE001 (re-raised in the caller's thread)
124
+ out["error"] = exc
125
+
126
+ t = threading.Thread(target=run, daemon=True, name="agent-link-ngrok")
127
+ t.start()
128
+ t.join(60)
129
+ if "error" in out:
130
+ raise out["error"]
131
+ if t.is_alive():
132
+ raise RuntimeError("ngrok didn't answer within 60 s")
133
+ return out.get("value")
134
+
135
+
136
+ def summary_store(project: str, state: Path | None = None) -> SummaryStore:
137
+ return SummaryStore((state or state_dir()) / "summaries" / f"{slug(project)}.json", project)
138
+
139
+
140
+ class HostedHub:
141
+ """A hub served on 127.0.0.1 in a background thread and, with tunnel=True, published
142
+ through ngrok."""
143
+
144
+ def __init__(self, project: str, tunnel: bool = True, authtoken: str | None = None, rotate_key: bool = False,
145
+ state: Path | None = None):
146
+ self.project = project
147
+ self.tunnel = tunnel
148
+ self.authtoken = authtoken
149
+ self.store = summary_store(project, state)
150
+ self.hub = Hub(link_key(project, rotate_key, state), project, self.store.load(), on_summary=self.store.save)
151
+ self.local_url = ""
152
+ self.public_url: str | None = None
153
+ self._server = None
154
+ self._thread: threading.Thread | None = None
155
+
156
+ @property
157
+ def link(self) -> str:
158
+ return make_link(self.public_url or self.local_url, self.hub.key)
159
+
160
+ def start(self) -> str:
161
+ """Start serving and return the join link. Blocking (run it in a worker thread from async code)."""
162
+ token = None
163
+ if self.tunnel:
164
+ token = self.authtoken or ngrok_token()
165
+ if not token:
166
+ raise RuntimeError(NO_TOKEN)
167
+
168
+ import uvicorn
169
+
170
+ config = uvicorn.Config(self.hub.app(), host="127.0.0.1", port=0, log_level="warning",
171
+ access_log=False, lifespan="off",
172
+ timeout_graceful_shutdown=2) # don't wait out long-polls
173
+ self._server = uvicorn.Server(config)
174
+ self._thread = threading.Thread(target=self._server.run, daemon=True, name="agent-link-hub")
175
+ self._thread.start()
176
+ deadline = time.monotonic() + 15
177
+ while not self._server.started:
178
+ if time.monotonic() > deadline or not threading.main_thread().is_alive():
179
+ raise RuntimeError("the hub didn't start")
180
+ time.sleep(0.02)
181
+ port = self._server.servers[0].sockets[0].getsockname()[1]
182
+ self.local_url = f"http://127.0.0.1:{port}"
183
+ if not self.tunnel:
184
+ return self.link
185
+
186
+ import ngrok
187
+
188
+ try:
189
+ listener = _outside_loop(ngrok.forward, port, authtoken=token)
190
+ except Exception as exc: # the SDK raises (summary, details, ERR_NGROK_code) tuples
191
+ self.stop()
192
+ parts = [str(a).strip() for a in exc.args] or [str(exc)]
193
+ detail = " ".join(parts[1:2] or parts[:1]) + (f" ({parts[2]})" if len(parts) > 2 else "")
194
+ hint = ("\nCheck the authtoken; `agent-link set-token` or host(authtoken=...) replaces it."
195
+ if re.search(r"authtoken|ERR_NGROK_(105|106|107|4018)\b", str(exc), re.I) else "")
196
+ raise RuntimeError(f"ngrok refused the tunnel: {detail}{hint}") from None
197
+ if self.authtoken: # it works: keep it for next time
198
+ save_ngrok_token(self.authtoken)
199
+ self.public_url = listener.url()
200
+ return self.link
201
+
202
+ def stop(self) -> None:
203
+ if self.public_url:
204
+ try:
205
+ import ngrok
206
+
207
+ _outside_loop(ngrok.disconnect, self.public_url)
208
+ except Exception:
209
+ pass
210
+ self.public_url = None
211
+ if self._server is not None:
212
+ self._server.should_exit = True
213
+ if self._thread is not None and self._thread is not threading.current_thread():
214
+ self._thread.join(10) # gone for good before we return