link-assistant-router 1.25.4__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.
Files changed (79) hide show
  1. link_assistant_router/__init__.py +227 -0
  2. link_assistant_router/__init__.pyi +690 -0
  3. link_assistant_router/catalog.json +68422 -0
  4. link_assistant_router/py.typed +0 -0
  5. link_assistant_router/schemas/accounts-list.v1.json +323 -0
  6. link_assistant_router/schemas/accounts-pause.v1.json +97 -0
  7. link_assistant_router/schemas/accounts-policy.v1.json +214 -0
  8. link_assistant_router/schemas/accounts-resume.v1.json +97 -0
  9. link_assistant_router/schemas/auth-claude.v1.json +97 -0
  10. link_assistant_router/schemas/auth-clear.v1.json +97 -0
  11. link_assistant_router/schemas/auth-codex.v1.json +97 -0
  12. link_assistant_router/schemas/auth-gh.v1.json +97 -0
  13. link_assistant_router/schemas/auth-import.v1.json +167 -0
  14. link_assistant_router/schemas/auth-status.v1.json +387 -0
  15. link_assistant_router/schemas/cli-error.v1.json +97 -0
  16. link_assistant_router/schemas/clients-backup-create.v1.json +97 -0
  17. link_assistant_router/schemas/clients-backup-list.v1.json +234 -0
  18. link_assistant_router/schemas/clients-backup-restore.v1.json +97 -0
  19. link_assistant_router/schemas/clients-backup-verify.v1.json +125 -0
  20. link_assistant_router/schemas/clients-doctor.v1.json +249 -0
  21. link_assistant_router/schemas/clients-install.v1.json +164 -0
  22. link_assistant_router/schemas/clients-list.v1.json +194 -0
  23. link_assistant_router/schemas/clients-reinstall.v1.json +164 -0
  24. link_assistant_router/schemas/clients-remove.v1.json +97 -0
  25. link_assistant_router/schemas/clients-repair.v1.json +109 -0
  26. link_assistant_router/schemas/clients-reset.v1.json +113 -0
  27. link_assistant_router/schemas/clients-setup.v1.json +97 -0
  28. link_assistant_router/schemas/clients-show.v1.json +191 -0
  29. link_assistant_router/schemas/clients-update.v1.json +164 -0
  30. link_assistant_router/schemas/configure.v1.json +97 -0
  31. link_assistant_router/schemas/contracts.v1.json +106 -0
  32. link_assistant_router/schemas/data-backup.v1.json +32 -0
  33. link_assistant_router/schemas/deploy.v1.json +546 -0
  34. link_assistant_router/schemas/doctor.v1.json +324 -0
  35. link_assistant_router/schemas/local-deployment.v1.json +364 -0
  36. link_assistant_router/schemas/logs-anomalies.v1.json +112 -0
  37. link_assistant_router/schemas/logs-show.v1.json +127 -0
  38. link_assistant_router/schemas/logs-summary.v1.json +129 -0
  39. link_assistant_router/schemas/model-catalog.v1.json +117 -0
  40. link_assistant_router/schemas/models-explain.v1.json +325 -0
  41. link_assistant_router/schemas/preservation.v1.json +47 -0
  42. link_assistant_router/schemas/providers-add.v1.json +185 -0
  43. link_assistant_router/schemas/providers-import.v1.json +97 -0
  44. link_assistant_router/schemas/providers-list.v1.json +182 -0
  45. link_assistant_router/schemas/providers-remove.v1.json +97 -0
  46. link_assistant_router/schemas/providers-show.v1.json +179 -0
  47. link_assistant_router/schemas/serve.v1.json +97 -0
  48. link_assistant_router/schemas/server-claim.v1.json +97 -0
  49. link_assistant_router/schemas/server-reap.v1.json +97 -0
  50. link_assistant_router/schemas/server-remove.v1.json +97 -0
  51. link_assistant_router/schemas/server-start.v1.json +97 -0
  52. link_assistant_router/schemas/server-status.v1.json +197 -0
  53. link_assistant_router/schemas/server-stop.v1.json +97 -0
  54. link_assistant_router/schemas/server-use.v1.json +97 -0
  55. link_assistant_router/schemas/staging.v1.json +47 -0
  56. link_assistant_router/schemas/tls-ca.v1.json +97 -0
  57. link_assistant_router/schemas/tls-generate.v1.json +97 -0
  58. link_assistant_router/schemas/tokens-expire.v1.json +97 -0
  59. link_assistant_router/schemas/tokens-import.v1.json +192 -0
  60. link_assistant_router/schemas/tokens-issue.v1.json +94 -0
  61. link_assistant_router/schemas/tokens-list.v1.json +272 -0
  62. link_assistant_router/schemas/tokens-recover-admin.v1.json +116 -0
  63. link_assistant_router/schemas/tokens-revoke.v1.json +97 -0
  64. link_assistant_router/schemas/tokens-rotate.v1.json +94 -0
  65. link_assistant_router/schemas/tokens-show.v1.json +269 -0
  66. link_assistant_router/schemas/tunnel-down.v1.json +97 -0
  67. link_assistant_router/schemas/tunnel-status.v1.json +165 -0
  68. link_assistant_router/schemas/tunnel-up.v1.json +97 -0
  69. link_assistant_router/schemas/usage.v1.json +621 -0
  70. link_assistant_router/schemas/verification.v1.json +254 -0
  71. link_assistant_router/schemas/verify.v1.json +338 -0
  72. link_assistant_router/schemas/version.v1.json +103 -0
  73. link_assistant_router/schemas/with.v1.json +105 -0
  74. link_assistant_router/testing.py +72 -0
  75. link_assistant_router/testing.pyi +22 -0
  76. link_assistant_router-1.25.4.dist-info/METADATA +9 -0
  77. link_assistant_router-1.25.4.dist-info/RECORD +79 -0
  78. link_assistant_router-1.25.4.dist-info/WHEEL +5 -0
  79. link_assistant_router-1.25.4.dist-info/top_level.txt +1 -0
@@ -0,0 +1,227 @@
1
+ """Official operations transport; Rust owns every operational decision."""
2
+ from __future__ import annotations
3
+ import hashlib
4
+ import json
5
+ import keyword
6
+ import math
7
+ import os
8
+ import shutil
9
+ import signal
10
+ import subprocess
11
+ import tarfile
12
+ import tempfile
13
+ import threading
14
+ import time
15
+ import urllib.request
16
+ from pathlib import Path
17
+ from types import SimpleNamespace
18
+ from typing import Any, Mapping, TypedDict
19
+ from jsonschema import Draft202012Validator
20
+
21
+ ROOT = Path(__file__).parent
22
+ catalog = json.loads((ROOT / 'catalog.json').read_text())
23
+ __version__: str = catalog['version']
24
+ operation_names: tuple[str, ...] = tuple(op['name'] for op in catalog['operations'])
25
+ _validators: dict[str, Draft202012Validator] = {}
26
+
27
+
28
+ class OperationResult(TypedDict):
29
+ schema: str
30
+ operation: str
31
+ success: bool
32
+ exit_code: int
33
+ data: Any
34
+ diagnostics: list[str]
35
+
36
+
37
+ class RouterError(RuntimeError):
38
+ """An operation, deadline, version, or schema failure with complete evidence."""
39
+ def __init__(self, message: str, *, code: str = 'operation', exit_code: int | None = None,
40
+ stderr: str = '', result: OperationResult | None = None):
41
+ super().__init__(message)
42
+ self.code, self.exit_code, self.stderr, self.result = code, exit_code, stderr, result
43
+
44
+
45
+ def _terminate(process: subprocess.Popen) -> None:
46
+ try:
47
+ if os.name == 'posix': os.killpg(process.pid, signal.SIGKILL)
48
+ else: process.kill()
49
+ except ProcessLookupError: pass
50
+
51
+
52
+ def run_process(binary: str, args: list[str], *, env: Mapping[str, str] | None = None,
53
+ stdin: str | bytes | None = None, deadline: float = 60,
54
+ cwd: str | Path | None = None, max_output_bytes: int = 8_388_608) -> tuple[int, str, str]:
55
+ """Finite subprocess with process-group cleanup and bounded output."""
56
+ if not math.isfinite(deadline) or not deadline > 0: raise RouterError('deadline must be positive', code='options')
57
+ try:
58
+ process = subprocess.Popen([binary, *args], env={**os.environ, **(env or {})}, cwd=cwd,
59
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
60
+ start_new_session=os.name == 'posix')
61
+ except OSError as error:
62
+ raise RouterError(f'Cannot execute {binary}: {error}', code='spawn') from error
63
+ buffers = [bytearray(), bytearray()]
64
+ failure: list[RouterError] = []
65
+ lock = threading.Lock()
66
+ def read(stream, index):
67
+ while chunk := stream.read(65536):
68
+ with lock:
69
+ if sum(map(len, buffers)) + len(chunk) > max_output_bytes:
70
+ failure.append(RouterError('Router output exceeds limit', code='output-limit'))
71
+ _terminate(process); break
72
+ buffers[index].extend(chunk)
73
+ stream.close()
74
+ readers = [threading.Thread(target=read, args=(stream, index), daemon=True)
75
+ for index, stream in enumerate([process.stdout, process.stderr])]
76
+ for reader in readers: reader.start()
77
+ def write():
78
+ try: process.stdin.write(stdin.encode() if isinstance(stdin, str) else stdin or b'')
79
+ except BrokenPipeError: pass
80
+ finally: process.stdin.close()
81
+ writer = threading.Thread(target=write, daemon=True); writer.start()
82
+ try: process.wait(timeout=deadline)
83
+ except subprocess.TimeoutExpired:
84
+ failure.append(RouterError('Router deadline exceeded', code='deadline'))
85
+ finally:
86
+ _terminate(process); process.wait()
87
+ for reader in readers: reader.join(timeout=1)
88
+ writer.join(timeout=1)
89
+ stdout, stderr = [bytes(buffer).decode(errors='replace') for buffer in buffers]
90
+ if failure:
91
+ error = failure[0]; error.exit_code, error.stderr = process.returncode, stderr
92
+ raise error
93
+ return process.returncode, stdout, stderr
94
+
95
+
96
+ def _validator(operation: str) -> Draft202012Validator:
97
+ if operation not in _validators:
98
+ schema = json.loads((ROOT / 'schemas' / (operation.replace('.', '-') + '.v1.json')).read_text())
99
+ Draft202012Validator.check_schema(schema)
100
+ _validators[operation] = Draft202012Validator(schema)
101
+ return _validators[operation]
102
+
103
+
104
+ def _validate(operation: str, result: Any, exit_code: int, stderr: str) -> OperationResult:
105
+ selected = 'cli-error' if isinstance(result, dict) and result.get('operation') == 'cli-error' else operation
106
+ errors = list(_validator(selected).iter_errors(result))
107
+ if errors: raise RouterError(f'Invalid {operation} response: {errors[0].message}', code='schema', exit_code=exit_code, stderr=stderr, result=result)
108
+ if result['exit_code'] != exit_code: raise RouterError('Exit status disagrees with result', code='schema', exit_code=exit_code, result=result, stderr=stderr)
109
+ if selected == 'cli-error' or not result['success']: raise RouterError('; '.join(result['diagnostics']) or operation + ' failed', exit_code=exit_code, result=result, stderr='\n'.join([stderr, *result['diagnostics']]))
110
+ return result
111
+
112
+
113
+ def _download_binary(cache: Path, deadline: float) -> str:
114
+ import platform
115
+ system = {'Linux': 'linux', 'Darwin': 'darwin'}.get(platform.system())
116
+ arch = {'x86_64': 'amd64', 'AMD64': 'amd64', 'aarch64': 'arm64', 'arm64': 'arm64'}.get(platform.machine())
117
+ if not system or not arch: raise RouterError('No verified asset for this platform; set ROUTER_BIN', code='platform')
118
+ destination = cache / __version__ / f'{system}-{arch}' / 'router'
119
+ try:
120
+ receipt = json.loads(destination.with_suffix('.verified.json').read_text())
121
+ if receipt['version'] == __version__ and receipt['sha256'] == hashlib.sha256(destination.read_bytes()).hexdigest(): return str(destination)
122
+ except (OSError, ValueError, KeyError): pass
123
+ destination.parent.mkdir(parents=True, exist_ok=True)
124
+ with tempfile.TemporaryDirectory(prefix='router-download-') as temporary:
125
+ work = Path(temporary)
126
+ asset = f'link-assistant-router-{__version__}-{system}-{arch}.tar.gz'
127
+ checksum = asset.replace('.tar.gz', '.sha256')
128
+ for name in [asset, checksum]:
129
+ url = f'https://github.com/link-assistant/router/releases/download/v{__version__}/{name}'
130
+ try:
131
+ with urllib.request.urlopen(url, timeout=deadline) as response, (work / name).open('wb') as target:
132
+ total = 0
133
+ while chunk := response.read(65536):
134
+ total += len(chunk)
135
+ if total > 150_000_000: raise RouterError('Release download exceeds limit', code='download')
136
+ target.write(chunk)
137
+ except OSError as error: raise RouterError(f'Download failed: {name}', code='download') from error
138
+ entries = [line.split() for line in (work / checksum).read_text().splitlines()]
139
+ digest = next((parts[0] for parts in entries if len(parts) == 2 and parts[1].lstrip('*') == asset), None)
140
+ if digest != hashlib.sha256((work / asset).read_bytes()).hexdigest(): raise RouterError('Release checksum mismatch', code='checksum')
141
+ code, _, stderr = run_process('gh', ['attestation', 'verify', str(work / asset), '--repo', 'link-assistant/router', '--source-ref', f'refs/tags/v{__version__}'], deadline=deadline)
142
+ if code: raise RouterError('Release attestation verification failed', code='attestation', exit_code=code, stderr=stderr)
143
+ with tarfile.open(work / asset) as archive:
144
+ member = next((entry for entry in archive if entry.name.lstrip('./') == 'router'), None)
145
+ if member is None or not member.isfile(): raise RouterError('No regular router binary in release', code='download')
146
+ source = archive.extractfile(member)
147
+ descriptor, temporary_binary = tempfile.mkstemp(prefix='router-staging-', dir=destination.parent)
148
+ os.close(descriptor); staging = Path(temporary_binary)
149
+ with staging.open('wb') as target: shutil.copyfileobj(source, target)
150
+ staging.chmod(0o755); staging.replace(destination)
151
+ destination.with_suffix('.verified.json').write_text(json.dumps({'version':__version__, 'sha256':hashlib.sha256(destination.read_bytes()).hexdigest()}))
152
+ return str(destination)
153
+
154
+
155
+ def resolve_binary(*, binary: str | None = None, allow_download: bool = True,
156
+ allow_version_mismatch: bool = False, env: Mapping[str, str] | None = None,
157
+ deadline: float = 60, cache_dir: str | Path | None = None) -> str:
158
+ candidate = binary or (env or {}).get('ROUTER_BIN') or os.environ.get('ROUTER_BIN') or 'router'
159
+ candidate = shutil.which(candidate, path=(env or {}).get('PATH', os.environ.get('PATH', ''))) or candidate
160
+ try: code, stdout, stderr = run_process(candidate, ['version', '--json'], env=env, deadline=deadline)
161
+ except RouterError as error:
162
+ if binary or (env or {}).get('ROUTER_BIN') or os.environ.get('ROUTER_BIN') or not allow_download or not isinstance(error.__cause__, FileNotFoundError): raise
163
+ candidate = _download_binary(Path(cache_dir or Path.home() / '.cache/link-assistant-router'), deadline)
164
+ code, stdout, stderr = run_process(candidate, ['version', '--json'], env=env, deadline=deadline)
165
+ try: result = json.loads(stdout)
166
+ except ValueError as error: raise RouterError('Binary does not implement version JSON', code='version', stderr=stderr) from error
167
+ result = _validate('version', result, code, stderr)
168
+ if not allow_version_mismatch and result['data']['version'] != __version__:
169
+ raise RouterError(f"Package {__version__} cannot use binary {result['data']['version']}; opt in with allow_version_mismatch", code='version', result=result)
170
+ return candidate
171
+
172
+
173
+ class Router:
174
+ """All catalog operations, e.g. router.tokens.issue(ttl_hours=24, env=...)."""
175
+ def __init__(self, *, binary: str | None = None, env: Mapping[str, str] | None = None,
176
+ deadline: float = 60, allow_download: bool = True, allow_version_mismatch: bool = False,
177
+ cache_dir: str | Path | None = None, cwd: str | Path | None = None):
178
+ self._binary: str | None = None
179
+ self._settings = dict(binary=binary, env=env, deadline=deadline, allow_download=allow_download,
180
+ allow_version_mismatch=allow_version_mismatch, cache_dir=cache_dir)
181
+ self._cwd = cwd
182
+ for operation in catalog['operations']:
183
+ namespace = self
184
+ names = [name.replace('-', '_') + ('_' if keyword.iskeyword(name.replace('-', '_')) else '') for name in operation['name'].split('.')]
185
+ for name in names[:-1]:
186
+ if not hasattr(namespace, name): setattr(namespace, name, SimpleNamespace())
187
+ namespace = getattr(namespace, name)
188
+ def call(_operation=operation['name'], **options): return self.invoke(_operation, **options)
189
+ setattr(namespace, names[-1], call)
190
+
191
+ def invoke(self, operation_name: str, /, *, env: Mapping[str, str] | None = None, stdin: str | bytes | None = None,
192
+ deadline: float | None = None, cwd: str | Path | None = None, options: Mapping[str, Any] | None = None, **arguments: Any) -> OperationResult:
193
+ name = operation_name
194
+ operation = next((operation for operation in catalog['operations'] if operation['name'] == name), None)
195
+ if operation is None: raise RouterError(f'Unknown operation: {name}', code='options')
196
+ allowed = {option['name']:option for option in operation['options']}
197
+ flags, positional = [], []
198
+ for key, value in {**(options or {}), **arguments}.items():
199
+ if value is None: continue
200
+ option = allowed.get(key)
201
+ if option is None: raise RouterError(f'Unknown {name} option: {key}', code='options')
202
+ if option['secret']: raise RouterError(f'{key} is secret; use env or stdin transport', code='secret-argv')
203
+ values = value if isinstance(value, (list, tuple)) else [value]
204
+ if option['positional']: positional.append((operation['options'].index(option), [str(item) for item in values]))
205
+ elif option['boolean']:
206
+ if not isinstance(value, bool): raise RouterError(f'{key} must be boolean', code='options')
207
+ if option.get('boolean_value'): flags.append('--' + option['flag'] + '=' + str(value).lower())
208
+ elif value: flags.append('--' + option['flag'])
209
+ else:
210
+ for item in values: flags.extend(['--' + option['flag'], str(item)])
211
+ args = [*operation['command'], '--json', *flags]
212
+ for _, values in sorted(positional): args.extend(values)
213
+ settings = {**self._settings, 'env':{**(self._settings['env'] or {}), **(env or {})}}
214
+ if deadline is not None: settings['deadline'] = deadline
215
+ if self._binary is None: self._binary = resolve_binary(**settings)
216
+ code, stdout, stderr = run_process(self._binary, args, env=settings['env'], stdin=stdin, deadline=settings['deadline'], cwd=cwd if cwd is not None else self._cwd)
217
+ try: result = json.loads(stdout)
218
+ except ValueError as error: raise RouterError(f'Invalid JSON from {name}', code='schema', exit_code=code, stderr=stderr) from error
219
+ return _validate(name, result, code, stderr)
220
+
221
+ def deploy_status(self, **options: Any) -> OperationResult:
222
+ """Read deployment status through the canonical deploy operation."""
223
+ return self.invoke('deploy', status=True, **options)
224
+
225
+
226
+ def create_router(**options: Any) -> Router:
227
+ return Router(**options)