agent-notifiers 0.2.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.
@@ -0,0 +1,1384 @@
1
+ """Telegram wake-up bridge: a message starts a headless coding agent, the answer comes back.
2
+
3
+ Security model: narrow defaults, fixed workdir, no shell, one request at a time,
4
+ optional PIN, timeouts. Treat the Telegram account as potentially compromised.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import hashlib
10
+ import hmac
11
+ import json
12
+ import os
13
+ import shlex
14
+ import shutil
15
+ import signal
16
+ import subprocess
17
+ from .windows_process import hidden_kwargs
18
+ import tempfile
19
+ import threading
20
+ import time
21
+ from pathlib import Path
22
+
23
+ import httpx
24
+
25
+ from . import state
26
+ from .config import HOME, Settings
27
+
28
+ BRIDGE_LOG = HOME / "bridge.log"
29
+ TG_TIMEOUT = 15.0
30
+
31
+
32
+ def _log(event: str, **kw) -> None:
33
+ try:
34
+ HOME.mkdir(parents=True, exist_ok=True)
35
+ parts = [time.strftime("%Y-%m-%d %H:%M:%S"), event]
36
+ for k, v in kw.items():
37
+ parts.append(f"{k}={v}")
38
+ with open(BRIDGE_LOG, "a", encoding="utf-8") as fh:
39
+ fh.write(" ".join(parts) + "\n")
40
+ except OSError:
41
+ pass
42
+
43
+
44
+ def resolve_exe(name: str) -> str | None:
45
+ """Resolve an executable, handling Windows .cmd shims."""
46
+ path = shutil.which(name)
47
+ if path:
48
+ return path
49
+ # try common suffixes
50
+ for suffix in ("", ".exe", ".cmd", ".bat"):
51
+ p = shutil.which(name + suffix)
52
+ if p:
53
+ return p
54
+ return None
55
+
56
+
57
+ def _is_root_or_home(path: Path) -> tuple[bool, str]:
58
+ rp = path.resolve()
59
+ if rp.parent == rp:
60
+ return True, "filesystem root"
61
+ try:
62
+ if rp == Path.home().resolve():
63
+ return True, "home directory"
64
+ except Exception:
65
+ pass
66
+ return False, ""
67
+
68
+
69
+ def _inside(child: Path, root: Path) -> bool:
70
+ try:
71
+ child.resolve().relative_to(root.resolve())
72
+ return True
73
+ except ValueError:
74
+ return False
75
+
76
+
77
+ def _real(p: str) -> Path:
78
+ return Path(p).expanduser().resolve()
79
+
80
+
81
+ def build_env(settings: Settings) -> tuple[dict[str, str], list[str]]:
82
+ env = os.environ.copy()
83
+ extra_values: list[str] = []
84
+ env_file = settings.get("BRIDGE_AGENT_ENV_FILE")
85
+ if env_file:
86
+ p = Path(env_file).expanduser()
87
+ if p.is_file():
88
+ for line in p.read_text(encoding="utf-8").splitlines():
89
+ line = line.strip()
90
+ if not line or line.startswith("#") or "=" not in line:
91
+ continue
92
+ key, value = line.split("=", 1)
93
+ value = value.strip()
94
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
95
+ value = value[1:-1]
96
+ if key.strip():
97
+ env[key.strip()] = value
98
+ if value:
99
+ extra_values.append(value)
100
+ return env, extra_values
101
+
102
+
103
+ class Redactor:
104
+ def __init__(self, settings: Settings, env_values: list[str]):
105
+ self.settings = settings
106
+ self.env_values = env_values
107
+
108
+ def redact(self, text: str) -> str:
109
+ if not text:
110
+ return text
111
+ for secret in self.settings.secrets() + self.env_values:
112
+ if secret and len(secret) >= 4:
113
+ text = text.replace(secret, "***")
114
+ # Authorization: Bearer ...
115
+ import re
116
+
117
+ text = re.sub(r"(?i)Authorization:\s*Bearer\s+\S+", "Authorization: Bearer ***", text)
118
+ # PEM private key blocks
119
+ text = re.sub(
120
+ r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----",
121
+ "[REDACTED PRIVATE KEY]",
122
+ text,
123
+ flags=re.S,
124
+ )
125
+ # known key prefixes
126
+ text = re.sub(
127
+ r"\b(sk-[A-Za-z0-9_-]{10,}|AKIA[A-Z0-9]{12,}|gh[pousr]_[A-Za-z0-9]{20,}|xox[baprs]-[A-Za-z0-9-]{10,})\b",
128
+ "***",
129
+ text,
130
+ )
131
+ # keyword-adjacent values
132
+ def _repl(m: re.Match) -> str:
133
+ full = m.group(0)
134
+ val = m.group(2)
135
+ return full.replace(val, "***")
136
+
137
+ text = re.sub(
138
+ r"(?i)(key|token|secret|password)\s*[:=]\s*[\"']?([A-Za-z0-9+/=_-]{12,})[\"']?",
139
+ _repl,
140
+ text,
141
+ )
142
+ return text
143
+
144
+
145
+ def chunk_text(text: str, limit: int = 4000) -> list[str]:
146
+ text = (text or "").rstrip("\n")
147
+ if not text.strip():
148
+ return ["(the agent returned no text)"]
149
+ chunks: list[str] = []
150
+ buf = text
151
+ while len(buf) > limit:
152
+ window = buf[:limit]
153
+ idx = window.rfind("\n\n")
154
+ if idx == -1 or idx < limit // 3:
155
+ idx = window.rfind("\n")
156
+ if idx == -1 or idx < limit // 3:
157
+ idx = limit
158
+ else:
159
+ idx += 2 if window[idx : idx + 2] == "\n\n" else 1
160
+ chunks.append(buf[:idx].rstrip())
161
+ buf = buf[idx:].lstrip("\n")
162
+ if buf.strip():
163
+ chunks.append(buf)
164
+ if not chunks:
165
+ chunks = ["(the agent returned no text)"]
166
+ return chunks
167
+
168
+
169
+ def kill_process_tree(proc: subprocess.Popen) -> None:
170
+ if proc is None:
171
+ return
172
+ try:
173
+ if os.name == "nt":
174
+ subprocess.run(
175
+ ["taskkill", "/PID", str(proc.pid), "/T", "/F"],
176
+ stdout=subprocess.DEVNULL,
177
+ stderr=subprocess.DEVNULL,
178
+ **hidden_kwargs(),
179
+ )
180
+ else:
181
+ try:
182
+ os.killpg(proc.pid, signal.SIGKILL)
183
+ except ProcessLookupError:
184
+ pass
185
+ except Exception:
186
+ pass
187
+ try:
188
+ proc.kill()
189
+ except Exception:
190
+ pass
191
+
192
+
193
+ def fmt_duration(seconds: float) -> str:
194
+ seconds = int(seconds)
195
+ if seconds < 60:
196
+ return f"{seconds}s"
197
+ minutes, sec = divmod(seconds, 60)
198
+ if minutes < 60:
199
+ return f"{minutes}m {sec:02d}s"
200
+ hours, minutes = divmod(minutes, 60)
201
+ return f"{hours}h {minutes:02d}m"
202
+
203
+
204
+ # ---------------- Agent presets ----------------
205
+
206
+
207
+ class ClaudeAgent:
208
+ name = "claude"
209
+
210
+ def __init__(self, exe: str):
211
+ self.exe = exe
212
+ self._session: str | None = None
213
+
214
+ def build(self, message: str, session_id: str | None, permissions: str) -> list[str]:
215
+ cmd = [self.exe, "-p", message, "--output-format", "json"]
216
+ if session_id:
217
+ cmd += ["--resume", session_id]
218
+ if permissions == "readonly":
219
+ cmd += ["--allowedTools", "Read Grep Glob"]
220
+ elif permissions == "edit":
221
+ cmd += ["--allowedTools", "Read Grep Glob Edit Write"]
222
+ elif permissions == "full":
223
+ cmd += ["--dangerously-skip-permissions"]
224
+ return cmd
225
+
226
+ def parse(self, stdout: str, stderr: str, rc: int):
227
+ text = (stdout or "").strip()
228
+ sid = None
229
+ # try single JSON object
230
+ try:
231
+ data = json.loads(text)
232
+ if isinstance(data, dict):
233
+ sid = data.get("session_id") or data.get("sessionId")
234
+ result = data.get("result")
235
+ if result is not None:
236
+ text = result if isinstance(result, str) else json.dumps(result)
237
+ except (ValueError, json.JSONDecodeError):
238
+ # try JSONL: last event wins
239
+ for line in reversed((stdout or "").splitlines()):
240
+ line = line.strip()
241
+ if not line:
242
+ continue
243
+ try:
244
+ data = json.loads(line)
245
+ except (ValueError, json.JSONDecodeError):
246
+ continue
247
+ if isinstance(data, dict):
248
+ sid = data.get("session_id") or data.get("sessionId") or sid
249
+ if "result" in data and data.get("result") is not None:
250
+ r = data["result"]
251
+ text = r if isinstance(r, str) else json.dumps(r)
252
+ break
253
+ if text is None:
254
+ text = ""
255
+ return text, sid
256
+
257
+
258
+ class CodexAgent:
259
+ name = "codex"
260
+
261
+ def __init__(self, exe: str):
262
+ self.exe = exe
263
+ self._out_file: str | None = None
264
+
265
+ def build(self, message: str, session_id: str | None, permissions: str) -> list[str]:
266
+ fd, path = tempfile.mkstemp(prefix="codex-out-")
267
+ os.close(fd)
268
+ self._out_file = path
269
+ if session_id:
270
+ cmd = [self.exe, "exec", "resume", session_id, message, "--skip-git-repo-check"]
271
+ else:
272
+ cmd = [self.exe, "exec", message, "--skip-git-repo-check"]
273
+ if permissions == "readonly":
274
+ cmd += ["--sandbox", "read-only"]
275
+ elif permissions == "edit":
276
+ cmd += ["--sandbox", "workspace-write"]
277
+ elif permissions == "full":
278
+ cmd += ["--dangerously-bypass-approvals-and-sandbox"]
279
+ cmd += ["-o", path]
280
+ return cmd
281
+
282
+ def parse(self, stdout: str, stderr: str, rc: int):
283
+ text = ""
284
+ if self._out_file and os.path.exists(self._out_file):
285
+ try:
286
+ text = Path(self._out_file).read_text(encoding="utf-8", errors="replace").strip()
287
+ except OSError:
288
+ text = ""
289
+ if not text:
290
+ text = (stdout or "").strip()
291
+ # clean up
292
+ if self._out_file:
293
+ try:
294
+ os.remove(self._out_file)
295
+ except OSError:
296
+ pass
297
+ self._out_file = None
298
+ # codex has no session id in simple output; return None
299
+ return text, None
300
+
301
+
302
+ class OpenCodeAgent:
303
+ name = "opencode"
304
+
305
+ def __init__(self, exe: str, model: str = ""):
306
+ self.exe = exe
307
+ self._model: str = model or ""
308
+
309
+ def build(self, message: str, session_id: str | None, permissions: str) -> list[str]:
310
+ cmd = [self.exe, "run", message, "--format", "json"]
311
+ if self._model:
312
+ cmd += ["-m", self._model]
313
+ if session_id:
314
+ cmd += ["--session", session_id]
315
+ if permissions == "full":
316
+ cmd += ["--auto"]
317
+ return cmd
318
+
319
+ def parse(self, stdout: str, stderr: str, rc: int):
320
+ texts: list[str] = []
321
+ sid = None
322
+ model = ""
323
+ last_error = ""
324
+ for line in (stdout or "").splitlines():
325
+ line = line.strip()
326
+ if not line:
327
+ continue
328
+ try:
329
+ data = json.loads(line)
330
+ except (ValueError, json.JSONDecodeError):
331
+ # skip non-JSON lines
332
+ continue
333
+ if not isinstance(data, dict):
334
+ continue
335
+ sid = data.get("sessionID") or data.get("session_id") or sid
336
+ if data.get("type") == "text":
337
+ t = data.get("text")
338
+ if not isinstance(t, str):
339
+ part = data.get("part")
340
+ if isinstance(part, dict):
341
+ t = part.get("text")
342
+ if isinstance(t, str):
343
+ texts.append(t)
344
+ # capture model if present
345
+ m = data.get("model") or data.get("modelID")
346
+ if isinstance(m, str) and m:
347
+ model = m
348
+ # track last error-ish line
349
+ if data.get("type") in ("error",) or data.get("error"):
350
+ err = data.get("error") or data.get("message")
351
+ if isinstance(err, str):
352
+ last_error = err
353
+ if model:
354
+ self._model = model
355
+ if texts:
356
+ text = "".join(texts)
357
+ else:
358
+ text = "(opencode returned no text)"
359
+ if last_error:
360
+ text += f"\n{last_error}"
361
+ elif (stderr or "").strip():
362
+ text += f"\n{(stderr or '').strip()[-800:]}"
363
+ return text, sid
364
+
365
+
366
+ class CustomAgent:
367
+ name = "custom"
368
+
369
+ def __init__(self, template: str):
370
+ self.template = template
371
+ self._use_stdin = False
372
+ self._stdin_text: str | None = None
373
+
374
+ def build(self, message: str, session_id: str | None, permissions: str) -> list[str]:
375
+ posix = os.name != "nt"
376
+ try:
377
+ parts = shlex.split(self.template, posix=posix)
378
+ except ValueError:
379
+ parts = self.template.split()
380
+ # Windows shlex(posix=False) keeps quotes; strip them so paths work.
381
+ cleaned = []
382
+ for p in parts:
383
+ if len(p) >= 2 and p[0] == p[-1] and p[0] in "\"'":
384
+ p = p[1:-1]
385
+ cleaned.append(p)
386
+ parts = cleaned
387
+ if "{message}" in parts:
388
+ idx = parts.index("{message}")
389
+ parts[idx] = message
390
+ self._use_stdin = False
391
+ self._stdin_text = None
392
+ else:
393
+ self._use_stdin = True
394
+ self._stdin_text = message
395
+ return parts
396
+
397
+ @property
398
+ def uses_stdin(self) -> bool:
399
+ return self._use_stdin
400
+
401
+ def parse(self, stdout: str, stderr: str, rc: int):
402
+ return (stdout or "").strip(), None
403
+
404
+
405
+ def make_agent(name: str, template: str | None, settings=None):
406
+ if name == "claude":
407
+ exe = resolve_exe("claude")
408
+ if not exe:
409
+ return None
410
+ return ClaudeAgent(exe)
411
+ if name == "codex":
412
+ exe = resolve_exe("codex")
413
+ if not exe:
414
+ return None
415
+ return CodexAgent(exe)
416
+ if name == "opencode":
417
+ exe = resolve_exe("opencode")
418
+ if not exe:
419
+ known = Path.home() / ".dsh" / "opencode-xdbridge" / "runtime" / "1.19.5" / "opencode.exe"
420
+ if known.exists():
421
+ exe = str(known)
422
+ else:
423
+ return None
424
+ model = ""
425
+ if settings is not None:
426
+ st = state.load()
427
+ model = st.get("bridge_opencode_model") or settings.get("BRIDGE_OPENCODE_MODEL", "")
428
+ return OpenCodeAgent(exe, model)
429
+ if name == "custom":
430
+ return CustomAgent(template or "")
431
+ return None
432
+
433
+
434
+ def run_agent(agent, message, workdir, permissions, timeout, env, session_id):
435
+ cmd = agent.build(message, session_id, permissions)
436
+ use_stdin = False
437
+ stdin_data = None
438
+ if isinstance(agent, CustomAgent) and agent.uses_stdin:
439
+ use_stdin = True
440
+ stdin_data = agent._stdin_text
441
+ # resolve first token
442
+ if cmd and not os.path.isabs(cmd[0]) and not os.path.exists(cmd[0]):
443
+ resolved = resolve_exe(cmd[0]) or shutil.which(cmd[0])
444
+ if resolved:
445
+ cmd[0] = resolved
446
+ # windows shim
447
+ if os.name == "nt" and cmd and str(cmd[0]).lower().endswith((".cmd", ".bat")):
448
+ cmd = ["cmd", "/c", cmd[0]] + cmd[1:]
449
+ proc = None
450
+ stdout = ""
451
+ stderr = ""
452
+ timed_out = False
453
+ start = time.time()
454
+ try:
455
+ proc = subprocess.Popen(
456
+ cmd,
457
+ cwd=str(workdir),
458
+ env=env,
459
+ stdin=subprocess.PIPE if use_stdin else subprocess.DEVNULL,
460
+ stdout=subprocess.PIPE,
461
+ stderr=subprocess.PIPE,
462
+ text=True,
463
+ encoding="utf-8",
464
+ errors="replace",
465
+ start_new_session=(os.name != "nt"),
466
+ **hidden_kwargs(),
467
+ )
468
+ try:
469
+ stdout, stderr = proc.communicate(input=stdin_data, timeout=timeout)
470
+ except subprocess.TimeoutExpired:
471
+ timed_out = True
472
+ kill_process_tree(proc)
473
+ try:
474
+ stdout, stderr = proc.communicate(timeout=5)
475
+ except Exception:
476
+ stdout = stdout or ""
477
+ stderr = stderr or ""
478
+ except FileNotFoundError as exc:
479
+ return "", str(exc), 127, False, None
480
+ except Exception as exc:
481
+ return "", str(exc), 1, False, None
482
+ rc = proc.returncode if proc is not None else 1
483
+ if os.environ.get("BRIDGE_DEBUG_RAW") in ("1", "true", "yes"):
484
+ try:
485
+ HOME.mkdir(parents=True, exist_ok=True)
486
+ (HOME / "last_run_raw.txt").write_text(f"STDOUT:\n{stdout or ''}\n\nSTDERR:\n{stderr or ''}", encoding="utf-8")
487
+ except OSError:
488
+ pass
489
+ text, sid = agent.parse(stdout or "", stderr or "", rc)
490
+ return text, (stderr or ""), rc, timed_out, sid
491
+
492
+
493
+ # ---------------- Telegram helpers ----------------
494
+
495
+
496
+ def _tg_url(token: str, method: str) -> str:
497
+ return f"https://api.telegram.org/bot{token}/{method}"
498
+
499
+
500
+ def tg_call(token: str, method: str, payload: dict | None = None, timeout: float = TG_TIMEOUT) -> Any:
501
+ r = httpx.post(_tg_url(token, method), json=payload or {}, timeout=timeout)
502
+ if r.status_code >= 400:
503
+ raise RuntimeError(f"HTTP {r.status_code}")
504
+ data = r.json()
505
+ if not data.get("ok"):
506
+ raise RuntimeError(data.get("description", "telegram error"))
507
+ return data.get("result")
508
+
509
+
510
+ def tg_get_updates(token: str, offset: int | None, timeout: int = 30) -> list[dict]:
511
+ payload: dict[str, Any] = {"timeout": timeout, "allowed_updates": ["message", "callback_query"]}
512
+ if offset:
513
+ payload["offset"] = offset
514
+ r = httpx.post(_tg_url(token, "getUpdates"), json=payload, timeout=timeout + 5)
515
+ if r.status_code == 409:
516
+ raise httpx.HTTPStatusError("conflict", request=r.request, response=r)
517
+ r.raise_for_status()
518
+ data = r.json()
519
+ if not data.get("ok"):
520
+ raise RuntimeError(data.get("description", "getUpdates failed"))
521
+ return data.get("result", []) or []
522
+
523
+
524
+ def tg_send_message(token: str, chat_id: str, text: str) -> None:
525
+ tg_call(token, "sendMessage", {"chat_id": chat_id, "text": text})
526
+
527
+
528
+ def tg_send_chat_action(token: str, chat_id: str, action: str = "typing") -> None:
529
+ try:
530
+ tg_call(token, "sendChatAction", {"chat_id": chat_id, "action": action}, timeout=10)
531
+ except Exception:
532
+ pass
533
+
534
+
535
+ # ---------------- Commands helpers ----------------
536
+
537
+
538
+ def cmd_bridge_id(_: argparse.Namespace) -> int:
539
+ settings = Settings()
540
+ token = settings.get("BRIDGE_TG_TOKEN")
541
+ if not token:
542
+ print("Set BRIDGE_TG_TOKEN first (from @BotFather), then message your bot once.")
543
+ return 1
544
+ try:
545
+ updates = tg_get_updates(token, None, timeout=5)
546
+ except Exception as exc:
547
+ print(f"Failed to reach Telegram: {type(exc).__name__}")
548
+ return 1
549
+ seen: dict[str, str] = {}
550
+ for upd in updates:
551
+ msg = upd.get("message") or {}
552
+ chat = msg.get("chat") or {}
553
+ if "id" in chat:
554
+ name = chat.get("username") or chat.get("first_name") or chat.get("title") or ""
555
+ seen[str(chat["id"])] = name
556
+ if not seen:
557
+ print("No messages found. Send any message to your bridge bot in Telegram, then run again.")
558
+ return 1
559
+ for cid, name in seen.items():
560
+ print(f"BRIDGE_TG_CHAT_ID={cid} ({name})")
561
+ return 0
562
+
563
+
564
+ def cmd_install_bridge_service(_: argparse.Namespace) -> int:
565
+ python = sys.executable
566
+ home = str(HOME)
567
+ print("=== Agent Notifier: bridge service install instructions ===")
568
+ print()
569
+ print("These are instructions only. Nothing is installed automatically.")
570
+ print()
571
+ print("--- Windows (Task Scheduler) ---")
572
+ print("1. Open Task Scheduler -> Create Task.")
573
+ print(" General: Name 'AgentNotifierBridge', 'Run whether user is logged on or not' optional, 'Hidden' checked.")
574
+ print(" Triggers: 'At log on' (your user).")
575
+ print(" Actions: Start a program:")
576
+ print(f" Program: {python}")
577
+ print(f" Arguments: -m agent_notifier listen")
578
+ print(f" Start in: {os.path.dirname(python)}")
579
+ print(" Settings: 'Restart on failure' every 1 minute, 3 times; 'Stop if runs longer than' unchecked.")
580
+ print(" Conditions: uncheck 'Start only if on AC power' if on a laptop.")
581
+ print()
582
+ print("--- macOS (launchd) ---")
583
+ print(f"Create ~/Library/LaunchAgents/com.agentnotifier.bridge.plist with:")
584
+ plist = f"""<?xml version="1.0" encoding="UTF-8"?>
585
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
586
+ <plist version="1.0">
587
+ <dict>
588
+ <key>Label</key><string>com.agentnotifier.bridge</string>
589
+ <key>ProgramArguments</key>
590
+ <array>
591
+ <string>{python}</string>
592
+ <string>-m</string>
593
+ <string>agent_notifier</string>
594
+ <string>listen</string>
595
+ </array>
596
+ <key>RunAtLoad</key><true/>
597
+ <key>KeepAlive</key><true/>
598
+ <key>StandardOutPath</key><string>{home}/bridge-stdout.log</string>
599
+ <key>StandardErrorPath</key><string>{home}/bridge-stderr.log</string>
600
+ </dict>
601
+ </plist>"""
602
+ print(plist)
603
+ print("Then: launchctl load ~/Library/LaunchAgents/com.agentnotifier.bridge.plist")
604
+ print()
605
+ print("--- Linux (systemd user unit) ---")
606
+ unit = f"""[Unit]
607
+ Description=Agent Notifier Telegram bridge
608
+ After=network-online.target
609
+
610
+ [Service]
611
+ Type=simple
612
+ ExecStart={python} -m agent_notifier listen
613
+ Restart=always
614
+ RestartSec=5
615
+
616
+ [Install]
617
+ WantedBy=default.target
618
+ """
619
+ print(f"Create ~/.config/systemd/user/agent-notifier-bridge.service with:")
620
+ print(unit)
621
+ print("Then: systemctl --user daemon-reload && systemctl --user enable --now agent-notifier-bridge")
622
+ print()
623
+ print("Ensure BRIDGE_WORKDIR and all keys are set in ~/.agent-notifier/.env before starting.")
624
+ return 0
625
+
626
+
627
+ # ---------------- listen implementation ----------------
628
+
629
+
630
+ def cmd_listen(args: argparse.Namespace) -> int:
631
+ settings = Settings()
632
+ if settings.get("BRIDGE_DEBUG_RAW"):
633
+ os.environ["BRIDGE_DEBUG_RAW"] = settings.get("BRIDGE_DEBUG_RAW")
634
+ token = settings.get("BRIDGE_TG_TOKEN")
635
+ chat_id = settings.get("BRIDGE_TG_CHAT_ID")
636
+ agent_name = (args.agent or settings.get("BRIDGE_AGENT", "claude")).strip().lower()
637
+ workdir_str = args.workdir or settings.get("BRIDGE_WORKDIR")
638
+ permissions = args.permissions or settings.get("BRIDGE_PERMISSIONS", "edit")
639
+ roots_raw = settings.get("BRIDGE_ROOTS")
640
+ # parse roots: JSON array or separator list
641
+ roots: list[Path] = []
642
+ roots_raw = roots_raw.strip()
643
+ if roots_raw:
644
+ try:
645
+ arr = json.loads(roots_raw)
646
+ if isinstance(arr, list):
647
+ roots = [Path(str(x)).expanduser() for x in arr]
648
+ except (ValueError, json.JSONDecodeError):
649
+ sep = ";" if os.name == "nt" else ":"
650
+ roots = [Path(x.strip()).expanduser() for x in roots_raw.split(sep) if x.strip()]
651
+ roots = [r.resolve() for r in roots if r.exists()]
652
+ if not roots:
653
+ print("BRIDGE_ROOTS is required (semicolon-separated folders).")
654
+ return 1
655
+ try:
656
+ timeout = int(args.timeout if args.timeout is not None else settings.get("BRIDGE_TIMEOUT", "900"))
657
+ except ValueError:
658
+ timeout = 900
659
+ try:
660
+ queue_max = int(settings.get("BRIDGE_QUEUE_MAX", "5"))
661
+ except ValueError:
662
+ queue_max = 5
663
+ try:
664
+ full_ttl = int(settings.get("BRIDGE_FULL_TTL", "120"))
665
+ except ValueError:
666
+ full_ttl = 120
667
+ allow_shell = settings.get("BRIDGE_ALLOW_SHELL", "false").lower() in ("1", "true", "yes")
668
+ try:
669
+ shell_timeout = int(settings.get("BRIDGE_SHELL_TIMEOUT", "120"))
670
+ except ValueError:
671
+ shell_timeout = 120
672
+ pin = settings.get("BRIDGE_PIN")
673
+ agent_cmd = settings.get("BRIDGE_AGENT_CMD")
674
+ dry_run = bool(args.dry_run)
675
+ i_understand = bool(getattr(args, "i_understand_the_risk", False))
676
+
677
+ if not token:
678
+ print("BRIDGE_TG_TOKEN is required. Set it in ~/.agent-notifier/.env (or env).")
679
+ return 1
680
+ if not chat_id:
681
+ print("BRIDGE_TG_CHAT_ID is required. Run `agent-notifier bridge-id` to learn it.")
682
+ return 1
683
+ if not workdir_str:
684
+ print("BRIDGE_WORKDIR is required and must be an existing directory.")
685
+ return 1
686
+ workdir = Path(workdir_str).expanduser()
687
+ try:
688
+ workdir = workdir.resolve(strict=True)
689
+ except FileNotFoundError:
690
+ print(f"BRIDGE_WORKDIR does not exist: {workdir_str}")
691
+ return 1
692
+ if not workdir.is_dir():
693
+ print("BRIDGE_WORKDIR must be a directory.")
694
+ return 1
695
+ bad, reason = _is_root_or_home(workdir)
696
+ if bad:
697
+ print(f"Refusing workdir that is the {reason}. Use a subfolder.")
698
+ return 1
699
+ # require inside a root
700
+ if not any(_inside(workdir, r) for r in roots):
701
+ print("BRIDGE_WORKDIR must be inside one of BRIDGE_ROOTS.")
702
+ return 1
703
+ if permissions not in ("readonly", "edit", "full"):
704
+ permissions = "readonly"
705
+ if agent_name not in ("claude", "codex", "opencode", "custom"):
706
+ print(f"Unknown agent: {agent_name}")
707
+ return 1
708
+ if agent_name == "custom" and not agent_cmd:
709
+ print("BRIDGE_AGENT_CMD is required when --agent custom.")
710
+ return 1
711
+
712
+ if permissions == "full" and not dry_run and not i_understand:
713
+ print("WARNING: 'full' permissions let the agent run shell commands without approval.")
714
+ print("This is dangerous if your Telegram account is compromised.")
715
+ try:
716
+ answer = input("Type 'yes' to continue: ").strip().lower()
717
+ except EOFError:
718
+ answer = ""
719
+ if answer != "yes":
720
+ print("Aborted.")
721
+ return 1
722
+
723
+ agent = make_agent(agent_name, agent_cmd, settings)
724
+ if agent is None:
725
+ print(f"Agent CLI not found for '{agent_name}'. Is it installed and on PATH?")
726
+ return 1
727
+
728
+ env, env_values = build_env(settings)
729
+ redactor = Redactor(settings, env_values)
730
+
731
+ if dry_run:
732
+ print(f"Would listen. agent={agent_name} workdir={workdir.name} permissions={permissions} timeout={timeout}s")
733
+ try:
734
+ sample = agent.build("HELLO", None, permissions)
735
+ print("Sample command:", redactor.redact(" ".join(sample)))
736
+ except Exception as exc:
737
+ print("Sample command: (build failed)", type(exc).__name__)
738
+ return 0
739
+
740
+ # state containers
741
+ st0 = state.load()
742
+ offset_box = {"v": st0.get("bridge_offset")}
743
+ sessions0 = st0.get("bridge_sessions", {})
744
+ active_agent = {"v": args.agent or settings.get("BRIDGE_AGENT", "claude")}
745
+ _key0 = f"{active_agent['v']}|{workdir}"
746
+ session_box = {"v": sessions0.get(_key0)}
747
+ active_folder = {"v": workdir}
748
+ permission = {"v": permissions}
749
+ recent_folders = {"v": list(st0.get("bridge_recent_folders", []))}
750
+ full_until = {"v": st0.get("bridge_full_until", 0) or 0}
751
+ remote_proc = {"p": None}
752
+ running = {"v": False}
753
+ queue: list[str] = []
754
+ lock = threading.Lock()
755
+ current_proc = {"p": None}
756
+ start_time = time.time()
757
+ wrong_attempts: list[float] = []
758
+ ignored_counter = {"n": 0}
759
+
760
+ def send(text: str) -> None:
761
+ for chunk in chunk_text(redactor.redact(text)):
762
+ try:
763
+ tg_send_message(token, chat_id, chunk)
764
+ except Exception as exc:
765
+ _log("send_error", type=type(exc).__name__)
766
+
767
+ def handle_command(text: str, msg_id=None) -> None:
768
+ parts = text.split()
769
+ cmd = parts[0].lower().split("@")[0] if parts else ""
770
+ if cmd == "/help":
771
+ send("Commands: /agents /agent <name> /pwd /folders /cd <name> /mkdir <name> /mode [readonly|edit|full <pin>] /lock /status /new /stop /remote [/remote stop] /sh <cmd> (if enabled) /auth <pin> /models [/models filter] /model [name] /doctor /debug /help")
772
+ elif cmd == "/agents":
773
+ from . import agents as ag
774
+ ags = ag.detect(settings)
775
+ lines = ["Agents:"]
776
+ for a in ags:
777
+ mark = " (selected)" if a["name"] == active_agent["v"] else ""
778
+ inst = "installed" if a["installed"] else "MISSING"
779
+ lines.append(f" {a['name']}: {inst} {a['version']} bridge={running['v'] and active_agent['v']==a['name']} other={a['others']}{mark}")
780
+ send("\n".join(lines))
781
+ btns = [[{"text": f"Use {a['name']}", "callback_data": f"agent:{a['name']}"}] for a in ags if a["installed"]]
782
+ if btns:
783
+ try:
784
+ tg_call(token, "sendMessage", {"chat_id": chat_id, "text": "Pick an agent:", "reply_markup": {"inline_keyboard": btns}})
785
+ except Exception:
786
+ pass
787
+ elif cmd == "/agent":
788
+ if len(parts) < 2:
789
+ send("Usage: /agent <name>")
790
+ return
791
+ name = parts[1].strip()
792
+ from . import agents as ag
793
+ ags = {a["name"]: a for a in ag.detect(settings)}
794
+ if name not in ags or not ags[name]["installed"]:
795
+ send(f"Agent not installed: {name}")
796
+ return
797
+ key = f"{active_agent['v']}|{active_folder['v']}"
798
+ st = state.load()
799
+ sessions = st.setdefault("bridge_sessions", {})
800
+ if session_box["v"]:
801
+ sessions[key] = session_box["v"]
802
+ active_agent["v"] = name
803
+ new_key = f"{name}|{active_folder['v']}"
804
+ session_box["v"] = sessions.get(new_key)
805
+ st["bridge_agent"] = name
806
+ state.save(st)
807
+ send(f"Switched to {name}.")
808
+ elif cmd == "/pwd":
809
+ rootname = next((r.name for r in roots if _inside(active_folder["v"], r)), "?")
810
+ send(f"folder: {active_folder['v'].name}\nroot: {rootname}")
811
+ elif cmd == "/folders":
812
+ root = next((r for r in roots if _inside(active_folder["v"], r)), roots[0])
813
+ subs = []
814
+ try:
815
+ for p in sorted(root.iterdir()):
816
+ if p.is_dir():
817
+ subs.append(p)
818
+ except OSError:
819
+ pass
820
+ subs = subs[:20]
821
+ btns = [[{"text": p.name, "callback_data": f"cd:{p.name}"}] for p in subs]
822
+ btns.append([{"text": "Up", "callback_data": "up:1"}, {"text": "Recent", "callback_data": "recent:1"}])
823
+ send(f"Root: {root.name}\nCurrent: {active_folder['v'].name}")
824
+ try:
825
+ tg_call(token, "sendMessage", {"chat_id": chat_id, "text": "Folders:", "reply_markup": {"inline_keyboard": btns}})
826
+ except Exception:
827
+ pass
828
+ elif cmd == "/cd":
829
+ if len(parts) < 2:
830
+ send("Usage: /cd <name or path>")
831
+ return
832
+ if running["v"]:
833
+ send("A job is running; folder change applies to the next request.")
834
+ target = parts[1]
835
+ if os.path.isabs(target) or (os.name == "nt" and len(target) > 1 and target[1] == ":"):
836
+ cand = Path(target)
837
+ else:
838
+ cand = active_folder["v"] / target
839
+ try:
840
+ cand = cand.resolve(strict=True)
841
+ except FileNotFoundError:
842
+ send("Folder not found.")
843
+ return
844
+ if not cand.is_dir():
845
+ send("Not a directory.")
846
+ return
847
+ if not any(_inside(cand, r) for r in roots):
848
+ send("Rejected: outside allowed roots.")
849
+ return
850
+ active_folder["v"] = cand
851
+ rec = [str(cand)] + [x for x in recent_folders["v"] if x != str(cand)]
852
+ recent_folders["v"] = rec[:5]
853
+ st = state.load()
854
+ st["bridge_recent_folders"] = rec[:5]
855
+ st["bridge_folder"] = str(cand)
856
+ state.save(st)
857
+ send(f"Changed to {cand.name}.")
858
+ elif cmd == "/mkdir":
859
+ if len(parts) < 2:
860
+ send("Usage: /mkdir <name>")
861
+ return
862
+ name = parts[1]
863
+ if ("/" in name or "\\" in name or ".." in name or name in ("", ".", "..")):
864
+ send("Invalid folder name.")
865
+ return
866
+ newp = active_folder["v"] / name
867
+ try:
868
+ newp.mkdir(parents=False, exist_ok=False)
869
+ send(f"Created {name}.")
870
+ except Exception:
871
+ send("Could not create folder.")
872
+ elif cmd == "/mode":
873
+ if len(parts) == 1:
874
+ send(f"Mode: {permission['v']}")
875
+ return
876
+ lvl = parts[1].lower()
877
+ if lvl in ("readonly", "edit"):
878
+ permission["v"] = lvl
879
+ full_until["v"] = 0
880
+ st = state.load(); st["bridge_permission"] = lvl; st["bridge_full_until"] = 0; state.save(st)
881
+ send(f"Mode set to {lvl}.")
882
+ elif lvl == "full":
883
+ if len(parts) < 3:
884
+ send("Usage: /mode full <pin>")
885
+ return
886
+ configured_pin = settings.get("BRIDGE_PIN")
887
+ if not configured_pin:
888
+ send("No PIN configured.")
889
+ return
890
+ submitted = parts[2]
891
+ now = time.time()
892
+ st = state.load()
893
+ wrong = st.get("bridge_wrong_pins", [])
894
+ wrong = [t for t in wrong if now - t < 600]
895
+ if len(wrong) >= 5:
896
+ send("Too many wrong attempts. Try later.")
897
+ return
898
+ import hmac as _hmac
899
+ if not _hmac.compare_digest(submitted, configured_pin):
900
+ wrong.append(now)
901
+ st["bridge_wrong_pins"] = wrong
902
+ state.save(st)
903
+ send("Wrong PIN.")
904
+ _log("wrong_pin")
905
+ return
906
+ try:
907
+ tg_call(token, "deleteMessage", {"chat_id": chat_id, "message_id": msg_id}, timeout=5)
908
+ except Exception:
909
+ pass
910
+ permission["v"] = "full"
911
+ ttl = full_ttl
912
+ until = (now + ttl * 60) if ttl > 0 else 0
913
+ full_until["v"] = until
914
+ st = state.load()
915
+ st["bridge_permission"] = "full"
916
+ st["bridge_full_until"] = until
917
+ st["bridge_wrong_pins"] = []
918
+ state.save(st)
919
+ send(f"Full mode enabled" + (f" for {ttl} min." if ttl > 0 else "."))
920
+ _log("full_enable")
921
+ else:
922
+ send("Unknown mode. Use readonly, edit, or full <pin>.")
923
+ elif cmd == "/lock":
924
+ permission["v"] = "readonly"
925
+ full_until["v"] = 0
926
+ st = state.load(); st["bridge_permission"] = "readonly"; st["bridge_full_until"] = 0; state.save(st)
927
+ send("Locked to readonly. PIN required to raise level.")
928
+ elif cmd == "/new":
929
+ key = f"{active_agent['v']}|{active_folder['v']}"
930
+ st = state.load()
931
+ sessions = st.get("bridge_sessions", {})
932
+ sessions.pop(key, None)
933
+ st["bridge_sessions"] = sessions
934
+ state.save(st)
935
+ session_box["v"] = None
936
+ send("Session cleared. Next message starts fresh.")
937
+ elif cmd == "/stop":
938
+ p = current_proc["p"]
939
+ if p is not None:
940
+ kill_process_tree(p)
941
+ current_proc["p"] = None
942
+ rp = remote_proc["p"]
943
+ if rp is not None:
944
+ kill_process_tree(rp)
945
+ remote_proc["p"] = None
946
+ with lock:
947
+ queue.clear()
948
+ send("Stopped. Queue cleared.")
949
+ elif cmd == "/remote":
950
+ if active_agent["v"] not in ("claude", "opencode"):
951
+ send("Remote Control is Claude Code only (OpenCode has no mobile remote).")
952
+ return
953
+ if active_agent["v"] == "opencode":
954
+ # OpenCode has no mobile remote control; offer its web UI instead.
955
+ exe = resolve_exe("opencode")
956
+ if not exe:
957
+ send("opencode not installed.")
958
+ return
959
+ send("OpenCode has no mobile remote control. Start its web UI by hand:\n opencode web\n (or: opencode serve --port 4096)\nThen open the printed URL in a browser. The session link belongs to your account; do not forward it.")
960
+ return
961
+ if len(parts) > 1 and parts[1].lower() == "stop":
962
+ rp = remote_proc["p"]
963
+ if rp is not None:
964
+ kill_process_tree(rp)
965
+ remote_proc["p"] = None
966
+ send("Remote Control stopped.")
967
+ else:
968
+ send("Remote Control not running.")
969
+ return
970
+ if remote_proc["p"] is not None:
971
+ send("Remote Control already running.")
972
+ return
973
+ import shutil as _sh
974
+ exe = _sh.which("claude")
975
+ if not exe:
976
+ send("Claude CLI not found.")
977
+ return
978
+ send("Remote Control requires an interactive terminal. Run this by hand:\nclaude --remote-control\n(in folder " + active_folder["v"].name + ")\nThe session link belongs to your Claude account; do not forward it.")
979
+ elif cmd == "/sh":
980
+ if not allow_shell:
981
+ send("Shell disabled (BRIDGE_ALLOW_SHELL=false).")
982
+ return
983
+ if permission["v"] != "full":
984
+ send("Shell requires full mode (/mode full <pin>).")
985
+ return
986
+ command = text[len(parts[0]):].strip()
987
+ if not command:
988
+ send("Usage: /sh <command>")
989
+ return
990
+ import subprocess as _sp
991
+ proc = None
992
+ try:
993
+ proc = _sp.Popen(command, shell=True, cwd=str(active_folder["v"]), stdout=_sp.PIPE, stderr=_sp.PIPE, text=True)
994
+ current_proc["p"] = proc
995
+ try:
996
+ out, err = proc.communicate(timeout=shell_timeout)
997
+ except _sp.TimeoutExpired:
998
+ kill_process_tree(proc)
999
+ out, err = proc.communicate()
1000
+ send(redactor.redact(f"Timed out.\n{(out or '')[-1700:]}\n{(err or '')[-800:]}")[:3500])
1001
+ current_proc["p"] = None
1002
+ return
1003
+ combined = (out or "") + (("\n" + err) if err else "")
1004
+ combined = redactor.redact(combined)
1005
+ if len(combined) > 3500:
1006
+ combined = combined[:3500] + "\n... (truncated)"
1007
+ if not combined.strip():
1008
+ combined = "(no output)"
1009
+ send(combined)
1010
+ except Exception:
1011
+ send("Shell command failed.")
1012
+ finally:
1013
+ current_proc["p"] = None
1014
+ _log("shell", exit=getattr(proc, "returncode", "?"), duration=0)
1015
+ elif cmd == "/auth":
1016
+ if not pin:
1017
+ send("No PIN configured.")
1018
+ return
1019
+ if len(parts) < 2:
1020
+ send("Usage: /auth <pin>")
1021
+ return
1022
+ now = time.time()
1023
+ st = state.load()
1024
+ wrong = st.get("bridge_wrong_pins", [])
1025
+ wrong = [t for t in wrong if now - t < 600]
1026
+ if len(wrong) >= 5:
1027
+ send("Too many wrong attempts. Try later.")
1028
+ return
1029
+ import hmac as _hmac
1030
+ if not _hmac.compare_digest(parts[1], pin):
1031
+ wrong.append(now)
1032
+ st["bridge_wrong_pins"] = wrong
1033
+ state.save(st)
1034
+ send("Wrong PIN.")
1035
+ _log("wrong_pin")
1036
+ return
1037
+ try:
1038
+ tg_call(token, "deleteMessage", {"chat_id": chat_id, "message_id": msg_id}, timeout=5)
1039
+ except Exception:
1040
+ pass
1041
+ st["bridge_wrong_pins"] = []
1042
+ st["bridge_auth_until"] = time.time() + 8 * 3600
1043
+ st["bridge_pin_hash"] = __import__("hashlib").sha256(pin.encode()).hexdigest()
1044
+ state.save(st)
1045
+ send("PIN accepted.")
1046
+ elif cmd == "/debug":
1047
+ send(f"BRIDGE_DEBUG_RAW={'on' if os.environ.get('BRIDGE_DEBUG_RAW') in ('1','true','yes') else 'off'}")
1048
+ elif cmd == "/models":
1049
+ # get model list from opencode models
1050
+ import subprocess as _sp
1051
+ exe = None
1052
+ if isinstance(agent, OpenCodeAgent):
1053
+ exe = agent.exe
1054
+ else:
1055
+ exe = resolve_exe("opencode")
1056
+ if not exe:
1057
+ send("opencode not installed.")
1058
+ return
1059
+ # cache
1060
+ now = time.time()
1061
+ cache = state.load().get("bridge_models_cache", {})
1062
+ if not cache or now - cache.get("ts", 0) > 600:
1063
+ try:
1064
+ r = _sp.run([exe, "models"], capture_output=True, text=True, timeout=15)
1065
+ lines = [l.strip() for l in (r.stdout or "").splitlines() if l.strip()]
1066
+ cache = {"ts": now, "lines": lines}
1067
+ st = state.load(); st["bridge_models_cache"] = cache; state.save(st)
1068
+ except Exception:
1069
+ send("Failed to list models.")
1070
+ return
1071
+ lines = cache.get("lines", [])
1072
+ # filter
1073
+ filt = parts[1].lower() if len(parts) > 1 else ""
1074
+ if filt:
1075
+ lines = [l for l in lines if filt in l.lower()]
1076
+ # group by provider
1077
+ groups: dict[str, list[str]] = {}
1078
+ for l in lines:
1079
+ prov = l.split("/", 1)[0] if "/" in l else "other"
1080
+ groups.setdefault(prov, []).append(l)
1081
+ # BRIDGE_OPENCODE_MODELS filter
1082
+ allowed = settings.get("BRIDGE_OPENCODE_MODELS", "").strip()
1083
+ if allowed:
1084
+ allow_set = set(x.strip() for x in allowed.split(",") if x.strip())
1085
+ groups = {k: [m for m in v if m in allow_set] for k, v in groups.items()}
1086
+ groups = {k: v for k, v in groups.items() if v}
1087
+ # pagination: 10 per page
1088
+ page = 0
1089
+ if len(parts) > 2 and parts[-1].isdigit():
1090
+ page = int(parts[-1])
1091
+ flat = []
1092
+ for prov in sorted(groups):
1093
+ for m in groups[prov]:
1094
+ flat.append((prov, m))
1095
+ per = 10
1096
+ total = len(flat)
1097
+ start = page * per
1098
+ chunk = flat[start:start+per]
1099
+ out_lines = [f"Models (page {page+1}/{(total+per-1)//per or 1}):"]
1100
+ cur_prov = None
1101
+ for prov, m in chunk:
1102
+ if prov != cur_prov:
1103
+ out_lines.append(f"[{prov}]")
1104
+ cur_prov = prov
1105
+ marker = " *" if m == getattr(agent, "_model", "") else ""
1106
+ out_lines.append(f" {m}{marker}")
1107
+ if total > per:
1108
+ out_lines.append(f"Use /models <filter> <page> e.g. /models opencode 2")
1109
+ send("\n".join(out_lines))
1110
+ elif cmd == "/model":
1111
+ if len(parts) == 1:
1112
+ m = getattr(agent, "_model", "") or settings.get("BRIDGE_OPENCODE_MODEL", "")
1113
+ send(f"Current model: {m or '(default)'}")
1114
+ return
1115
+ # switch
1116
+ name = parts[1].strip()
1117
+ # validate against cached list
1118
+ cache = state.load().get("bridge_models_cache", {})
1119
+ lines = cache.get("lines", [])
1120
+ if lines and name not in lines:
1121
+ # maybe number
1122
+ if name.isdigit():
1123
+ idx = int(name) - 1
1124
+ if 0 <= idx < len(lines):
1125
+ name = lines[idx]
1126
+ else:
1127
+ send("Invalid model number.")
1128
+ return
1129
+ else:
1130
+ send("Model not in list. Run /models first.")
1131
+ return
1132
+ if not lines:
1133
+ # no cache; accept if looks like provider/model
1134
+ if "/" not in name:
1135
+ send("Run /models first to populate the list.")
1136
+ return
1137
+ # persist
1138
+ st = state.load()
1139
+ st["bridge_opencode_model"] = name
1140
+ state.save(st)
1141
+ if isinstance(agent, OpenCodeAgent):
1142
+ agent._model = name
1143
+ send(f"Model set to {name}.")
1144
+ elif cmd == "/doctor":
1145
+ if not isinstance(agent, OpenCodeAgent):
1146
+ send("Doctor is for opencode.")
1147
+ return
1148
+ import subprocess as _sp
1149
+ model = getattr(agent, "_model", "") or settings.get("BRIDGE_OPENCODE_MODEL", "")
1150
+ exe = agent.exe
1151
+ try:
1152
+ r = _sp.run([exe, "run", "Reply with OK only.", "--format", "json"] + (["-m", model] if model else []), capture_output=True, text=True, timeout=15)
1153
+ ok = r.returncode == 0 and "OK" in (r.stdout or "")
1154
+ send(f"Doctor: {'PASS' if ok else 'FAIL'}" + ("" if ok else f"\n{redactor.redact((r.stderr or r.stdout or '')[-500:])}"))
1155
+ except Exception as exc:
1156
+ send(f"Doctor: FAIL\n{redactor.redact(str(exc))}")
1157
+ elif cmd == "/status":
1158
+ with lock:
1159
+ qlen = len(queue)
1160
+ is_running = running["v"]
1161
+ uptime = fmt_duration(time.time() - start_time)
1162
+ lines = [
1163
+ f"agent: {active_agent['v']}",
1164
+ f"folder: {active_folder['v'].name}",
1165
+ f"mode: {permission['v']}",
1166
+ f"running: {is_running}",
1167
+ f"queue: {qlen}",
1168
+ f"uptime: {uptime}",
1169
+ f"remote: {'running' if remote_proc['p'] is not None else 'stopped'}",
1170
+ f"session: {'yes' if session_box['v'] else 'none'}",
1171
+ ]
1172
+ send("\n".join(lines))
1173
+ else:
1174
+ send("Unknown command. Send /help for the list.")
1175
+
1176
+ def process_job(message: str) -> None:
1177
+ stop_typing = threading.Event()
1178
+ stop_status = threading.Event()
1179
+
1180
+ def typing_loop():
1181
+ while not stop_typing.wait(4):
1182
+ tg_send_chat_action(token, chat_id, "typing")
1183
+
1184
+ def status_loop():
1185
+ start = time.time()
1186
+ last = start
1187
+ while not stop_status.wait(30):
1188
+ if time.time() - start >= 60 and time.time() - last >= 120:
1189
+ try:
1190
+ send(f"Still working ({int((time.time() - start) // 60)}m)")
1191
+ except Exception:
1192
+ pass
1193
+ last = time.time()
1194
+
1195
+ tt = threading.Thread(target=typing_loop, daemon=True)
1196
+ ts = threading.Thread(target=status_loop, daemon=True)
1197
+ tt.start()
1198
+ ts.start()
1199
+
1200
+ run_start = time.time()
1201
+ text, stderr, rc, timed_out, sid = run_agent(
1202
+ agent, message, workdir, permissions, timeout, env, session_box["v"]
1203
+ )
1204
+ if sid:
1205
+ session_box["v"] = sid
1206
+ key = f"{active_agent['v']}|{active_folder['v']}"
1207
+ st = state.load()
1208
+ sessions = st.setdefault("bridge_sessions", {})
1209
+ sessions[key] = sid
1210
+ state.save(st)
1211
+
1212
+ stop_typing.set()
1213
+ stop_status.set()
1214
+ tt.join(timeout=2)
1215
+ ts.join(timeout=2)
1216
+
1217
+ duration = int(time.time() - run_start)
1218
+ if timed_out:
1219
+ err = redactor.redact(f"Timed out after {timeout}s. Last stderr:\n{stderr[-800:]}")
1220
+ send(err)
1221
+ _log("run_timeout", duration=duration, exit=-1)
1222
+ elif rc != 0:
1223
+ err = redactor.redact(f"Agent exited with code {rc}. Last stderr:\n{stderr[-800:]}")
1224
+ send(err)
1225
+ _log("run_fail", duration=duration, exit=rc)
1226
+ else:
1227
+ out = redactor.redact(text)
1228
+ if getattr(agent, "name", "") == "opencode":
1229
+ model = getattr(agent, "_model", "") or "default"
1230
+ out = out.rstrip() + f"\n\n[opencode | {model} | {active_folder['v'].name}]"
1231
+ for chunk in chunk_text(out):
1232
+ send(chunk)
1233
+ _log("run_ok", duration=duration, exit=0)
1234
+
1235
+ current_proc["p"] = None
1236
+
1237
+ def worker(first: str) -> None:
1238
+ running["v"] = True
1239
+ current = first
1240
+ while current is not None:
1241
+ process_job(current)
1242
+ with lock:
1243
+ current = queue.pop(0) if queue else None
1244
+ running["v"] = False
1245
+
1246
+ print(f"Bridge listening. agent={agent.name} workdir={workdir.name} permissions={permissions}")
1247
+ print("Commands: /agents /agent /pwd /folders /cd /mkdir /mode /lock /status /new /stop /remote /sh /auth /help")
1248
+ print("Press Ctrl+C to stop.")
1249
+ _log("start", version="0.1.0", agent=agent.name, permissions=permissions, commands="/agents /agent /pwd /folders /cd /mkdir /mode /lock /status /new /stop /remote /sh /auth /help")
1250
+
1251
+ backoff = 1
1252
+ try:
1253
+ while True:
1254
+ try:
1255
+ updates = tg_get_updates(token, offset_box["v"], timeout=30)
1256
+ backoff = 1
1257
+ except httpx.HTTPStatusError as exc:
1258
+ if exc.response is not None and exc.response.status_code == 409:
1259
+ print("This bot has a webhook or another poller; use a dedicated bot.")
1260
+ return
1261
+ _log("http_error", code=getattr(exc.response, "status_code", "?"))
1262
+ time.sleep(backoff)
1263
+ backoff = min(backoff * 2, 60)
1264
+ continue
1265
+ except Exception as exc:
1266
+ _log("net_error", type=type(exc).__name__)
1267
+ time.sleep(backoff)
1268
+ backoff = min(backoff * 2, 60)
1269
+ continue
1270
+
1271
+ # full-mode TTL revert
1272
+ if permission["v"] == "full" and full_ttl > 0 and full_until["v"] and time.time() > full_until["v"]:
1273
+ permission["v"] = "edit"
1274
+ full_until["v"] = 0
1275
+ st = state.load()
1276
+ st["bridge_permission"] = "edit"
1277
+ st["bridge_full_until"] = 0
1278
+ state.save(st)
1279
+ send("Full mode expired; reverted to edit.")
1280
+ _log("full_revert")
1281
+ for upd in updates or []:
1282
+ try:
1283
+ offset_box["v"] = max(offset_box["v"] or 0, upd["update_id"] + 1)
1284
+ # callback queries (inline buttons)
1285
+ cq = upd.get("callback_query")
1286
+ if cq:
1287
+ cq_from = str((cq.get("from") or {}).get("id", ""))
1288
+ if cq_from != str(chat_id):
1289
+ continue
1290
+ data = cq.get("data") or ""
1291
+ # answer callback
1292
+ try:
1293
+ tg_call(token, "answerCallbackQuery", {"callback_query_id": cq.get("id", "")}, timeout=5)
1294
+ except Exception:
1295
+ pass
1296
+ if data.startswith("agent:"):
1297
+ name = data.split(":", 1)[1]
1298
+ # validate installed
1299
+ from . import agents as ag
1300
+ ags = {a["name"]: a for a in ag.detect(settings)}
1301
+ if name in ags and ags[name]["installed"]:
1302
+ # save current session
1303
+ key = f"{active_agent['v']}|{active_folder['v']}"
1304
+ st = state.load()
1305
+ sessions = st.setdefault("bridge_sessions", {})
1306
+ if session_box["v"]:
1307
+ sessions[key] = session_box["v"]
1308
+ active_agent["v"] = name
1309
+ new_key = f"{name}|{active_folder['v']}"
1310
+ session_box["v"] = sessions.get(new_key)
1311
+ st["bridge_agent"] = name
1312
+ state.save(st)
1313
+ send(f"Switched to {name}.")
1314
+ elif data.startswith("cd:"):
1315
+ name = data.split(":", 1)[1]
1316
+ cand = active_folder["v"] / name
1317
+ try:
1318
+ cand = cand.resolve(strict=True)
1319
+ except Exception:
1320
+ cand = None
1321
+ if cand and cand.is_dir() and any(_inside(cand, r) for r in roots):
1322
+ active_folder["v"] = cand
1323
+ rec = [str(cand)] + [x for x in recent_folders["v"] if x != str(cand)]
1324
+ recent_folders["v"] = rec[:5]
1325
+ st = state.load()
1326
+ st["bridge_recent_folders"] = rec[:5]
1327
+ st["bridge_folder"] = str(cand)
1328
+ state.save(st)
1329
+ send(f"Changed to {cand.name}.")
1330
+ continue
1331
+ st = state.load()
1332
+ st["bridge_offset"] = offset_box["v"]
1333
+ state.save(st)
1334
+
1335
+ msg = upd.get("message") or {}
1336
+ chat = msg.get("chat") or {}
1337
+ if chat.get("type") != "private":
1338
+ ignored_counter["n"] += 1
1339
+ continue
1340
+ if str(chat.get("id")) != str(chat_id):
1341
+ ignored_counter["n"] += 1
1342
+ if ignored_counter["n"] % 10 == 0:
1343
+ _log("ignored", count=ignored_counter["n"])
1344
+ continue
1345
+ text = msg.get("text")
1346
+ if not text:
1347
+ continue
1348
+
1349
+ if text.startswith("/"):
1350
+ handle_command(text, msg.get("message_id"))
1351
+ continue
1352
+
1353
+ # PIN gate
1354
+ if pin:
1355
+ st = state.load()
1356
+ auth_until = st.get("bridge_auth_until", 0) or 0
1357
+ pin_hash = st.get("bridge_pin_hash")
1358
+ current_hash = hashlib.sha256(pin.encode()).hexdigest()
1359
+ if not (time.time() < auth_until and pin_hash == current_hash):
1360
+ _log("locked_ignore")
1361
+ continue
1362
+
1363
+ with lock:
1364
+ if running["v"]:
1365
+ if len(queue) >= queue_max:
1366
+ send("Busy, try again shortly.")
1367
+ _log("busy")
1368
+ continue
1369
+ queue.append(text)
1370
+ pos = len(queue)
1371
+ queued = True
1372
+ else:
1373
+ queued = False
1374
+ if running["v"] and queued:
1375
+ send(f"Queued (position {pos}).")
1376
+ continue
1377
+ if not running["v"]:
1378
+ threading.Thread(target=worker, args=(text,), daemon=True).start()
1379
+ except Exception as exc:
1380
+ _log("update_error", type=type(exc).__name__)
1381
+ except KeyboardInterrupt:
1382
+ print("\nStopping bridge.")
1383
+ _log("stop", reason="keyboard")
1384
+ return 0