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,371 @@
1
+ """Local companion: outbound connection to the hosted backend."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import re
7
+ import subprocess
8
+ import time
9
+ from pathlib import Path
10
+
11
+ import httpx
12
+
13
+ from . import device as devmod
14
+ from . import agents as agent_registry
15
+ from . import recovery
16
+ from . import codex_models
17
+ from . import local_models
18
+ from .windows_process import hidden_kwargs
19
+ from . import runtime
20
+ from . import codex_workspace
21
+ from .config import Settings
22
+
23
+ HEARTBEAT_INTERVAL = 30
24
+ JOBS_POLL_INTERVAL = 5
25
+ MODEL_REPORT_INTERVAL = 300
26
+ JOB_TIMEOUT = 900
27
+ JOB_PROGRESS_INTERVAL = 15 # liveness only; no stdout/stderr streaming
28
+ # Fixed command per supported agent: the server can never choose an arbitrary binary,
29
+ # and the prompt is passed as a single argv element (never through a shell).
30
+ AGENT_COMMANDS = {
31
+ "claude": lambda prompt: ["claude", "-p", prompt],
32
+ "codex": lambda prompt: ["codex", "exec", prompt],
33
+ "opencode": lambda prompt: ["opencode", "run", prompt],
34
+ }
35
+
36
+
37
+ def _cloud_url(settings) -> str:
38
+ return settings.get("CLOUD_URL", "https://agentnotifier.duckdns.org").rstrip("/")
39
+
40
+
41
+ def _companion_loop(settings) -> int:
42
+ dev = devmod._load_device()
43
+ if not dev or not dev.get("device_token"):
44
+ print("No paired device. Run `agent-notifier device pair` first.")
45
+ return 1
46
+ cloud = dev.get("cloud") or _cloud_url(settings)
47
+ token = dev["device_token"]
48
+ headers = {"Authorization": "Bearer " + token}
49
+ print(f"Companion connecting to {cloud} as device {dev['device_id']}")
50
+ backoff = 1
51
+ while True:
52
+ try:
53
+ # SSE stream
54
+ with httpx.stream("GET", cloud + "/api/companion/stream", headers=headers, timeout=None) as resp:
55
+ if resp.status_code == 401:
56
+ print("Device revoked or invalid. Re-pair.")
57
+ return 1
58
+ resp.raise_for_status()
59
+ # Read-only agent inventory. Never send executable paths, command templates
60
+ # or private workspace information to the hosted service.
61
+ def report_agents_and_models():
62
+ reports = [
63
+ {"name": a["name"], "version": a["version"], "installed": a["installed"]}
64
+ for a in agent_registry.detect(settings)
65
+ if a.get("name") in ("claude", "codex", "opencode")
66
+ ]
67
+ installed = {a["name"] for a in reports if a["installed"]}
68
+ catalogs = local_models.all_installed(installed)
69
+ httpx.post(cloud + "/api/companion/agents", headers=headers,
70
+ json={"agents": reports, "agent_models": catalogs,
71
+ "codex_models": catalogs.get("codex", [])}, timeout=15)
72
+ try:
73
+ report_agents_and_models()
74
+ except (httpx.HTTPError, OSError):
75
+ pass
76
+ backoff = 1
77
+ # Recovery is never permission to restart a claimed job.
78
+ _reconcile_saved_jobs(cloud, headers, dev["device_id"])
79
+ last_hb = 0
80
+ last_poll = 0
81
+ last_model_report = time.time()
82
+ for line in resp.iter_lines():
83
+ now = time.time()
84
+ if now - last_hb >= HEARTBEAT_INTERVAL:
85
+ try:
86
+ hb = httpx.post(cloud + "/api/companion/heartbeat", headers=headers, timeout=10)
87
+ if hb.status_code == 200 and hb.json().get("refresh_models"):
88
+ report_agents_and_models()
89
+ last_model_report = time.time()
90
+ except Exception:
91
+ pass
92
+ last_hb = now
93
+ if now - last_model_report >= MODEL_REPORT_INTERVAL:
94
+ try:
95
+ report_agents_and_models()
96
+ last_model_report = now
97
+ except (httpx.HTTPError, OSError):
98
+ pass
99
+ if now - last_poll >= JOBS_POLL_INTERVAL:
100
+ last_poll = now
101
+ _poll_and_run_job(cloud, headers, dev["device_id"])
102
+ # process SSE events (none actionable)
103
+ except KeyboardInterrupt:
104
+ print("Stopping companion.")
105
+ return 0
106
+ except Exception as exc:
107
+ print(f"Connection lost ({type(exc).__name__}). Reconnecting in {backoff}s...")
108
+ time.sleep(backoff)
109
+ backoff = min(backoff * 2, 60)
110
+
111
+
112
+ def cmd_companion_start(args) -> int:
113
+ """Foreground companion, optionally supervised so crashes restart it.
114
+
115
+ Exactly one companion may run per user account: two processes would poll
116
+ the same jobs and could execute the same approved task twice.
117
+ """
118
+ settings = Settings()
119
+ with runtime.instance_lock() as primary:
120
+ if not primary:
121
+ state = runtime.status()
122
+ detail = f" (pid {state['pid']})" if state["pid"] else ""
123
+ print(f"A companion is already running{detail}. Not starting a second one.")
124
+ print("Use `agent-notifier companion status` to inspect it.")
125
+ return 1
126
+ if getattr(args, "supervise", False):
127
+ from .autostart import supervise
128
+
129
+ print("Companion supervisor active; Ctrl+C stops it.")
130
+ return supervise(lambda: _companion_loop(settings))
131
+ return _companion_loop(settings)
132
+
133
+
134
+ def launch_argv(agent: str, prompt: str, model_id: str | None = None, *, skip_codex_git_check: bool = False) -> list[str] | None:
135
+ """Resolve the allowlisted adapter to an absolute executable path.
136
+
137
+ Windows resolves `opencode` to a `.CMD` shim that CreateProcess does not
138
+ find by bare name, so launching the name alone reports a false
139
+ "not installed" even when the agent works.
140
+ """
141
+ build = AGENT_COMMANDS.get(agent)
142
+ if not build:
143
+ return None
144
+ argv = list(build(prompt))
145
+ resolved = agent_registry._resolve(argv[0])
146
+ if resolved:
147
+ argv[0] = resolved
148
+ if model_id:
149
+ if not local_models.MODEL_ID.fullmatch(model_id):
150
+ return None
151
+ if model_id not in {m["id"] for m in local_models.discover(agent)}:
152
+ return None
153
+ if agent == "codex":
154
+ argv = [argv[0], "exec", "--model", model_id, prompt]
155
+ elif agent == "claude":
156
+ argv = [argv[0], "--model", model_id, "-p", prompt]
157
+ elif agent == "opencode":
158
+ argv = [argv[0], "run", "--model", model_id, prompt]
159
+ else:
160
+ return None
161
+ if agent == "codex" and skip_codex_git_check:
162
+ argv.insert(2, "--skip-git-repo-check")
163
+ return argv
164
+
165
+
166
+ def _allow_codex_no_repo(settings: Settings) -> bool:
167
+ """Only local owner settings may disable the repo check, never cloud jobs."""
168
+ return (settings.get("COMPANION_CODEX_SKIP_GIT_REPO_CHECK").lower()
169
+ in ("1", "yes", "true", "on") and bool(runtime.authorized_roots(settings)))
170
+
171
+
172
+ def _clean_cli_output(value: str) -> str:
173
+ """Strip ANSI color codes and control characters from chat text."""
174
+ value = re.sub(r"\x1b\][^\x07]*(?:\x07|\x1b\\)", "", value)
175
+ value = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", value)
176
+ return "".join(c for c in value if c in "\n\t" or ord(c) >= 32).strip()
177
+
178
+
179
+ def _send_job_progress(cloud: str, headers: dict, job_id: str, counter: int) -> bool:
180
+ """Return an authenticated owner's stop request, otherwise keep running."""
181
+ if not job_id:
182
+ return False
183
+ try:
184
+ response = httpx.post(
185
+ cloud + "/api/companion/jobs/" + job_id + "/progress",
186
+ headers=headers, json={"event_id": f"heartbeat_{counter:08d}"}, timeout=5,
187
+ )
188
+ requested=response.status_code == 200 and bool(response.json().get("stop_requested"))
189
+ if requested:
190
+ try:
191
+ httpx.post(cloud + "/api/companion/jobs/" + job_id + "/stop-ack",
192
+ headers=headers,timeout=5)
193
+ except httpx.HTTPError:
194
+ pass
195
+ return requested
196
+ except (httpx.HTTPError, ValueError, TypeError, AttributeError):
197
+ return False
198
+
199
+
200
+ def _stop_owned_process(proc: subprocess.Popen) -> None:
201
+ """Terminate only the process launched for this approved job."""
202
+ if proc.poll() is not None:
203
+ return
204
+ proc.terminate()
205
+ try:
206
+ proc.communicate(timeout=5)
207
+ except subprocess.TimeoutExpired:
208
+ proc.kill()
209
+ proc.communicate()
210
+
211
+
212
+ def _reconcile_saved_jobs(cloud: str, headers: dict, device_id: str) -> bool:
213
+ """Retry delivery only. Unknown execution outcomes are not retried."""
214
+ for entry in recovery.records("result", device_id):
215
+ jid=entry["job_id"]
216
+ try:
217
+ r=httpx.post(cloud+"/api/companion/jobs/result",
218
+ headers=headers,json=entry["payload"],timeout=20)
219
+ receipt=r.json() if r.status_code==200 else None
220
+ if r.status_code==200 and isinstance(receipt,dict) and receipt.get("ok") is True:
221
+ recovery.discard("result",jid)
222
+ recovery.discard("claim",jid)
223
+ except (httpx.HTTPError, ValueError, TypeError, AttributeError, OSError):
224
+ pass
225
+ for entry in recovery.records("claim",device_id):
226
+ jid=entry["job_id"]
227
+ if recovery.exists("result",jid):
228
+ continue
229
+ try:
230
+ r=httpx.post(cloud+"/api/companion/jobs/"+jid+"/interrupted",
231
+ headers=headers,timeout=15)
232
+ if r.status_code==200 and r.json().get("state") in ("running","terminal"):
233
+ recovery.discard("claim",jid)
234
+ except (httpx.HTTPError, ValueError, TypeError, AttributeError, OSError):
235
+ pass
236
+ # Unknown, corrupt or other-device records block new job claims.
237
+ return not recovery.has_unresolved()
238
+
239
+
240
+ def _run_job(cloud: str, headers: dict, job: dict, device_id: str = "local_test") -> None:
241
+ """Run one approved agent process; persist before posting result."""
242
+ agent = str(job.get("agent") or "")
243
+ prompt = str(job.get("prompt") or "")
244
+ job_id = str(job.get("id") or "")
245
+ payload: dict = {"job_id": job_id}
246
+ if not job_id or recovery.has_unresolved():
247
+ return
248
+ # Resolve the workspace before claiming, so an unusable configuration never
249
+ # leaves an orphaned claim blocking the queue.
250
+ try:
251
+ workdir = runtime.authorized_workdir(Settings())
252
+ except (ValueError, OSError):
253
+ print("No authorized working directory is configured; refusing this job.")
254
+ return
255
+ try:
256
+ recovery.save_claim(job_id,device_id)
257
+ except (OSError,ValueError):
258
+ print("Unable to persist claim; refusing to start this job.")
259
+ return
260
+ model_id = job.get("model_id") or None
261
+ settings = Settings()
262
+ non_git_codex = agent == "codex" and not codex_workspace.is_git_worktree(workdir)
263
+ allow_no_repo = non_git_codex and _allow_codex_no_repo(settings)
264
+ argv = launch_argv(agent, prompt, model_id, skip_codex_git_check=allow_no_repo) if prompt else None
265
+ if non_git_codex and not allow_no_repo:
266
+ payload["error"] = (
267
+ "Codex needs a trusted Git workspace. Set COMPANION_WORKDIRS in "
268
+ "~/.agent-notifier/.env to an existing Git repository and restart "
269
+ "the companion. For a dedicated non-repository workspace, the "
270
+ "owner can explicitly configure COMPANION_CODEX_SKIP_GIT_REPO_CHECK=1 "
271
+ "together with COMPANION_WORKDIRS.")
272
+ elif not argv:
273
+ payload["error"] = ("Selected agent model is unavailable on this computer"
274
+ if model_id else f"unsupported agent: {agent or 'none'}")
275
+ else:
276
+ proc = None
277
+ try:
278
+ proc = subprocess.Popen(
279
+ argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
280
+ cwd=str(workdir), stdin=subprocess.DEVNULL, encoding="utf-8", errors="replace", **hidden_kwargs(),
281
+ )
282
+ deadline = time.monotonic() + JOB_TIMEOUT
283
+ counter = 0
284
+ requested = _send_job_progress(cloud, headers, job_id, counter)
285
+ while True:
286
+ if requested:
287
+ _stop_owned_process(proc)
288
+ payload["exit_code"] = proc.returncode
289
+ payload["error"] = "Stopped by owner"
290
+ break
291
+ remaining = deadline - time.monotonic()
292
+ if remaining <= 0:
293
+ _stop_owned_process(proc)
294
+ payload["exit_code"] = proc.returncode
295
+ payload["error"] = f"timed out after {JOB_TIMEOUT}s"
296
+ break
297
+ try:
298
+ stdout, stderr = proc.communicate(
299
+ timeout=min(remaining, JOB_PROGRESS_INTERVAL),
300
+ )
301
+ except subprocess.TimeoutExpired:
302
+ counter += 1
303
+ requested = _send_job_progress(cloud, headers, job_id, counter)
304
+ continue
305
+ payload["exit_code"] = proc.returncode
306
+ payload["result"] = _clean_cli_output(stdout or "")[-20000:]
307
+ if proc.returncode != 0:
308
+ payload["error"] = (_clean_cli_output(stderr or "") or f"exit {proc.returncode}")[:2000]
309
+ break
310
+ except FileNotFoundError:
311
+ payload["error"] = f"{agent} is not installed on this computer"
312
+ except Exception as exc:
313
+ payload["error"] = type(exc).__name__
314
+ finally:
315
+ if proc is not None and proc.poll() is None:
316
+ _stop_owned_process(proc)
317
+ try:
318
+ recovery.save_result(job_id,device_id,payload)
319
+ except (OSError,ValueError):
320
+ print("Result could not be saved; this job requires operator investigation.")
321
+ return
322
+ _reconcile_saved_jobs(cloud,headers,device_id)
323
+
324
+
325
+ def _poll_and_run_job(cloud: str, headers: dict, device_id: str = "local_test") -> bool:
326
+ """Never claim new work with undelivered results or orphaned claims."""
327
+ if not _reconcile_saved_jobs(cloud,headers,device_id):
328
+ return False
329
+ try:
330
+ resp = httpx.post(cloud + "/api/companion/jobs/poll",
331
+ headers={**headers, "X-AN-Model-Selection": "1"}, timeout=15)
332
+ if resp.status_code != 200:
333
+ return False
334
+ job = (resp.json() or {}).get("job")
335
+ except (httpx.HTTPError, ValueError):
336
+ return False
337
+ if not job:
338
+ return False
339
+ print(f"Running {job.get('agent')} job {job.get('id')}...")
340
+ _run_job(cloud, headers, job, device_id=device_id)
341
+ return True
342
+
343
+
344
+ def cmd_companion_status(args) -> int:
345
+ from .autostart import status as autostart_status
346
+
347
+ dev = devmod._load_device()
348
+ auto = autostart_status()
349
+ print(f"Auto-start: {'installed' if auto['installed'] else 'not installed'} "
350
+ f"({auto['path']})")
351
+ if not dev:
352
+ print("No device paired. Run `agent-notifier device pair` first.")
353
+ return 1
354
+ print(runtime.describe(Settings()))
355
+ print(f"Device: {dev.get('name')} ({dev.get('device_id')})")
356
+ print(f"Cloud: {dev.get('cloud')}")
357
+ print("Status: unknown (heartbeat is tracked by the backend, not locally)")
358
+ try:
359
+ detected = [a["name"] for a in agent_registry.detect(Settings()) if a.get("installed")]
360
+ except Exception:
361
+ detected = []
362
+ print(f"Installed agents: {', '.join(detected) if detected else 'none detected'}")
363
+ print("Follow-up jobs start a new agent process with the saved conversation "
364
+ "context; no agent CLI is resumed natively.")
365
+ print("A sleeping or powered-off computer cannot be woken by the cloud.")
366
+ return 0
367
+
368
+
369
+ def cmd_companion_stop(args) -> int:
370
+ print("Stop the companion process (Ctrl+C) to disconnect.")
371
+ return 0
@@ -0,0 +1,68 @@
1
+ """Settings: .env files + real environment (env wins). No secrets are ever logged."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ from pathlib import Path
6
+
7
+ HOME = Path(os.environ.get("AGENT_NOTIFIER_HOME", Path.home() / ".agent-notifier"))
8
+ PACKAGE_ROOT = Path(__file__).resolve().parent.parent
9
+
10
+ SECRET_HINTS = ("TOKEN", "PASSWORD", "APIKEY", "API_KEY")
11
+
12
+
13
+ def _parse_env(path: Path) -> dict[str, str]:
14
+ out: dict[str, str] = {}
15
+ try:
16
+ text = path.read_text(encoding="utf-8")
17
+ except OSError:
18
+ return out
19
+ for line in text.splitlines():
20
+ line = line.strip()
21
+ if not line or line.startswith("#") or "=" not in line:
22
+ continue
23
+ key, value = line.split("=", 1)
24
+ value = value.strip()
25
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
26
+ value = value[1:-1]
27
+ out[key.strip()] = value
28
+ return out
29
+
30
+
31
+ def load_env() -> dict[str, str]:
32
+ merged: dict[str, str] = {}
33
+ for path in (PACKAGE_ROOT / ".env", HOME / ".env"):
34
+ merged.update(_parse_env(path))
35
+ merged.update({k: v for k, v in os.environ.items() if v != ""})
36
+ return merged
37
+
38
+
39
+ class Settings:
40
+ def __init__(self, env: dict[str, str] | None = None):
41
+ self.env = env if env is not None else load_env()
42
+
43
+ def get(self, key: str, default: str = "") -> str:
44
+ return (self.env.get(key) or default).strip()
45
+
46
+ @property
47
+ def default_channels(self) -> list[str]:
48
+ raw = self.get("NOTIFY_DEFAULT_CHANNELS", "telegram,ntfy")
49
+ return [c.strip().lower() for c in raw.split(",") if c.strip()]
50
+
51
+ @property
52
+ def min_seconds(self) -> int:
53
+ try:
54
+ return max(0, int(self.get("NOTIFY_MIN_SECONDS", "45")))
55
+ except ValueError:
56
+ return 45
57
+
58
+ def secrets(self) -> list[str]:
59
+ vals = []
60
+ for key, value in self.env.items():
61
+ if value and len(value) >= 6 and any(h in key.upper() for h in SECRET_HINTS):
62
+ vals.append(value)
63
+ return vals
64
+
65
+ def redact(self, text: str) -> str:
66
+ for secret in self.secrets():
67
+ text = text.replace(secret, "***")
68
+ return text
agent_notifier/core.py ADDED
@@ -0,0 +1,89 @@
1
+ """Dispatcher: routing, retry, fallback, secret redaction."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+
6
+ from . import channels as ch
7
+ from . import state
8
+ from .config import Settings
9
+ from . import redact as rd
10
+
11
+ PRIORITIES = ("low", "normal", "high", "urgent")
12
+
13
+
14
+ def norm_priority(value: str | None) -> str:
15
+ value = (value or "normal").strip().lower()
16
+ return value if value in PRIORITIES else "normal"
17
+
18
+
19
+ def _try(channel: ch.Channel, title: str, message: str, priority: str, settings: Settings) -> str | None:
20
+ """Return None on success, else a redacted error string. One retry on failure."""
21
+ last = ""
22
+ for attempt in range(2):
23
+ try:
24
+ channel.send(title, message, priority)
25
+ return None
26
+ except Exception as exc: # noqa: BLE001 - never leak a token through an exception
27
+ last = settings.redact(f"{exc.__class__.__name__}: {exc}")
28
+ if attempt == 0:
29
+ time.sleep(1.0)
30
+ return last
31
+
32
+
33
+ def notify(
34
+ message: str,
35
+ title: str = "Claude",
36
+ priority: str = "normal",
37
+ channels: list[str] | None = None,
38
+ settings: Settings | None = None,
39
+ ) -> dict:
40
+ """Send a notification.
41
+
42
+ Routing:
43
+ * explicit `channels` -> exactly those
44
+ * high/urgent -> every configured channel
45
+ * low/normal -> NOTIFY_DEFAULT_CHANNELS, falling back to the rest if all fail
46
+ """
47
+ settings = settings or Settings()
48
+ priority = norm_priority(priority)
49
+ message = rd.redact(message, settings)
50
+ title = rd.redact(title, settings)
51
+ available = ch.build(settings)
52
+ configured = [n for n, c in available.items() if c.configured()]
53
+ result: dict = {"sent": [], "failed": {}, "skipped": []}
54
+
55
+ if not configured:
56
+ result["error"] = "no channels configured - run `agent-notifier status`"
57
+ return result
58
+
59
+ if channels:
60
+ wanted = [c.lower() for c in channels]
61
+ unknown = [c for c in wanted if c not in available]
62
+ result["skipped"] += [f"{c} (unknown)" for c in unknown]
63
+ primary = [c for c in wanted if c in configured]
64
+ result["skipped"] += [f"{c} (not configured)" for c in wanted if c in available and c not in configured]
65
+ fallback: list[str] = []
66
+ elif priority in ("high", "urgent"):
67
+ primary, fallback = configured, []
68
+ else:
69
+ primary = [c for c in settings.default_channels if c in configured] or configured
70
+ fallback = [c for c in configured if c not in primary]
71
+
72
+ for name in primary:
73
+ err = _try(available[name], title, message, priority, settings)
74
+ if err is None:
75
+ result["sent"].append(name)
76
+ else:
77
+ result["failed"][name] = err
78
+
79
+ if not result["sent"] and fallback:
80
+ for name in fallback:
81
+ err = _try(available[name], title, message, priority, settings)
82
+ if err is None:
83
+ result["sent"].append(name)
84
+ result["fallback_used"] = True
85
+ break
86
+ result["failed"][name] = err
87
+
88
+ state.log(f"notify priority={priority} sent={result['sent']} failed={list(result['failed'])}")
89
+ return result
@@ -0,0 +1,134 @@
1
+ """Device pairing with the hosted Agent Notifier service."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import secrets
7
+ import time
8
+ from pathlib import Path
9
+
10
+ import httpx
11
+
12
+ from .config import HOME, Settings
13
+
14
+ DEVICE_FILE = HOME / "device.json"
15
+ PAIRING_TIMEOUT = 300
16
+
17
+
18
+ def _cloud_url(settings) -> str:
19
+ return settings.get("CLOUD_URL", "https://agentnotifier.duckdns.org").rstrip("/")
20
+
21
+
22
+ def _save_device(data: dict) -> None:
23
+ HOME.mkdir(parents=True, exist_ok=True)
24
+ DEVICE_FILE.write_text(json.dumps(data), encoding="utf-8")
25
+ try:
26
+ os.chmod(DEVICE_FILE, 0o600)
27
+ except OSError:
28
+ pass
29
+
30
+
31
+ def _load_device() -> dict | None:
32
+ try:
33
+ return json.loads(DEVICE_FILE.read_text(encoding="utf-8"))
34
+ except (OSError, ValueError):
35
+ return None
36
+
37
+
38
+ def cmd_device_pair(args) -> int:
39
+ settings = Settings()
40
+ cloud = _cloud_url(settings)
41
+ verifier = secrets.token_urlsafe(32)
42
+ device_name = getattr(args, "name", None) or os.uname().nodename if hasattr(os, "uname") else "device"
43
+ try:
44
+ import platform
45
+ device_name = platform.node() or "device"
46
+ except Exception:
47
+ device_name = "device"
48
+ print(f"Pairing device '{device_name}' with {cloud}")
49
+ try:
50
+ r = httpx.post(cloud + "/api/device-pairings/start", json={
51
+ "device_name": device_name,
52
+ "device_info": "agent-notifier companion",
53
+ "verifier": verifier,
54
+ }, timeout=15)
55
+ r.raise_for_status()
56
+ data = r.json()
57
+ except Exception as exc:
58
+ print(f"Failed to start pairing: {type(exc).__name__}")
59
+ return 1
60
+ code = data["code"]
61
+ pid = data["pairing_id"]
62
+ expires = data.get("expires_in", 300)
63
+ print(f"\nPairing code: {code}")
64
+ print(f"Open {cloud}/app and confirm this device, or visit:")
65
+ print(f" {cloud}/app?pair={code}")
66
+ print(f"\nWaiting up to {expires}s for approval...")
67
+ deadline = time.time() + expires
68
+ while time.time() < deadline:
69
+ try:
70
+ r = httpx.post(cloud + "/api/device-pairings/poll", json={
71
+ "pairing_id": pid, "verifier": verifier,
72
+ }, timeout=15)
73
+ res = r.json()
74
+ except Exception:
75
+ time.sleep(2)
76
+ continue
77
+ status = res.get("status")
78
+ if status == "approved":
79
+ dev_id = res.get("device_id")
80
+ token = res.get("device_token")
81
+ _save_device({"device_id": dev_id, "device_token": token, "cloud": cloud, "name": device_name, "paired_at": time.time()})
82
+ print(f"\nPaired successfully. Device id: {dev_id}")
83
+ if token:
84
+ print("Device credential saved locally (mode 600).")
85
+ return 0
86
+ if status in ("rejected", "expired", "invalid_verifier", "not_found"):
87
+ print(f"\nPairing failed: {status}")
88
+ return 1
89
+ time.sleep(2)
90
+ print("\nPairing timed out.")
91
+ return 1
92
+
93
+
94
+ def cmd_device_status(args) -> int:
95
+ dev = _load_device()
96
+ if not dev:
97
+ print("No device paired. Run `agent-notifier device pair`.")
98
+ return 1
99
+ print(f"Device: {dev.get('name')}")
100
+ print(f"Device id: {dev.get('device_id')}")
101
+ print(f"Cloud: {dev.get('cloud')}")
102
+ print(f"Paired at: {dev.get('paired_at')}")
103
+ return 0
104
+
105
+
106
+ def cmd_device_unpair(args) -> int:
107
+ dev = _load_device()
108
+ if not dev:
109
+ print("No device paired.")
110
+ return 0
111
+ cloud = dev.get("cloud", "")
112
+ token = dev.get("device_token")
113
+ if not cloud or not token:
114
+ print("Missing cloud credential. Revoke this device in the web dashboard.")
115
+ return 1
116
+ try:
117
+ r = httpx.post(
118
+ cloud + "/api/companion/unpair",
119
+ headers={"Authorization": "Bearer " + token},
120
+ timeout=15,
121
+ )
122
+ if r.status_code not in (200, 401):
123
+ print(f"Cloud revocation failed (HTTP {r.status_code}); local pairing retained.")
124
+ return 1
125
+ except httpx.HTTPError as exc:
126
+ print(f"Cloud unavailable ({type(exc).__name__}); local pairing retained.")
127
+ return 1
128
+ try:
129
+ DEVICE_FILE.unlink()
130
+ except OSError as exc:
131
+ print(f"Cloud access revoked, but local credential file could not be deleted ({type(exc).__name__}).")
132
+ return 1
133
+ print("Device unpaired; cloud access revoked or credential already invalid.")
134
+ return 0