返回 last30days-skill
hosted.py
根目录 / skills / last30days / scripts / lib / hosted.py
1 """Remote API client for last30days (optional hosted-backend mode).
2
3 When both LAST30DAYS_API_KEY and LAST30DAYS_API_BASE are set, the engine
4 submits the topic to the configured remote API, polls until the run reaches a
5 terminal status, streams narration progress to stderr, and renders the
6 server's report. No local provider keys are required in this mode. The
7 endpoint comes only from LAST30DAYS_API_BASE - there is no built-in default.
8
9 Contract (API v1):
10 POST {base}/search Authorization: Bearer <key>
11 {"query": ..., "depth": "quick"|"default"|"deep",
12 "register"?: "exec"|"dev"|"creator"|"eli5",
13 "clarify"?: {"angle": str} | {"run_broadly": true}}
14 -> 200 {"search_id": "<uuid>", "status": "running"}
15 -> 200 clarify payload {"needs_clarification": true, ...}
16 -> 401 {"error"} / 402 {"error","requires_credits",
17 "balance","needed"} / 429 {"error"}
18 GET {base}/search?id=<uuid> same auth header; poll until status is
19 terminal ("complete" | "error"). Running rows carry
20 "stderr" (narration + engine lines) and "eta_ms";
21 terminal complete rows carry "synthesis_text" and
22 "raw_markdown" (stderr stripped); error rows may carry
23 "error" and/or "synthesis_text" (the failure reason).
24 Terminal rows may carry "engine_version", the engine
25 that wrote the run.
26
27 This module carries ZERO pricing, rate-card, cost, or billing logic.
28 Balance/credit numbers are only ever displayed verbatim from API responses.
29 The API key is never printed, logged, or persisted by this module.
30 """
31
32 from __future__ import annotations
33
34 import json
35 import os
36 import re
37 import sys
38 import time
39 from urllib.parse import urlsplit, urlunsplit
40
41 from . import env, http, library, providers, usage
42 from .log import source_log
43
44 # Distinct exit code for the clarify gate so the invoking model can tell
45 # "re-run with a chosen angle" apart from a plain failure (1).
46 EXIT_CLARIFY = 3
47
48 POLL_INITIAL_DELAY = 3.0
49 POLL_MAX_DELAY = 10.0
50 POLL_TIMEOUT_SECONDS = 15 * 60
51 # GET is idempotent: retry a few times across network blips before giving up.
52 POLL_NETWORK_RETRIES = 3
53 # Cadence for the compact elapsed/eta progress line (seconds).
54 PROGRESS_LINE_INTERVAL = 15.0
55
56 NARRATE_PREFIX = "[narrate] step="
57 TERMINAL_STATUSES = {"complete", "error"}
58
59
60 _URL_USERINFO_RE = re.compile(r"(https?://)[^\s/?#]+@", re.IGNORECASE)
61
62
63 def _err(msg: str) -> None:
64 source_log("hosted", msg, tty_only=False)
65
66
67 def _scrub_url_userinfo(url: str) -> str:
68 """Return ``url`` with any embedded authority userinfo removed."""
69 try:
70 parts = urlsplit(url)
71 except ValueError:
72 return _URL_USERINFO_RE.sub(r"\1", url)
73 if parts.username is None and parts.password is None and "@" not in parts.netloc:
74 return url
75 hostport = parts.netloc.rsplit("@", 1)[-1]
76 return urlunsplit((parts.scheme, hostport, parts.path, parts.query, parts.fragment))
77
78
79 def _scrub_error_text(text: str) -> str:
80 """Remove embedded URL credentials and the configured API key from log text."""
81 scrubbed = _URL_USERINFO_RE.sub(r"\1", text)
82 raw_key = env.read_secret_env("LAST30DAYS_API_KEY") or ""
83 for candidate in {raw_key, raw_key.strip()}:
84 if candidate and candidate.strip():
85 scrubbed = scrubbed.replace(candidate, "[REDACTED]")
86 return scrubbed
87
88
89 def _api_base() -> str:
90 # Endpoint comes only from the environment - no built-in default. Hosted
91 # mode is gated on this being set (see last30days.py), so by the time this
92 # is called it is populated; an empty value means "not configured".
93 raw = (os.environ.get("LAST30DAYS_API_BASE") or "").strip()
94 if any(ord(ch) < 0x20 or ord(ch) == 0x7F or ch.isspace() for ch in raw):
95 raise ValueError(
96 "LAST30DAYS_API_BASE must not contain control characters or whitespace."
97 )
98 if not providers.allowed_base_url_override(raw):
99 raise ValueError(
100 "LAST30DAYS_API_BASE must use https:// "
101 "(http:// is allowed only for loopback hosts)."
102 )
103 parts = urlsplit(raw)
104 if "\\" in parts.netloc:
105 raise ValueError(
106 "LAST30DAYS_API_BASE must not contain backslashes in the authority."
107 )
108 try:
109 _ = parts.port
110 except ValueError:
111 raise ValueError("LAST30DAYS_API_BASE contains an invalid port.") from None
112 if parts.username is not None or parts.password is not None or "@" in parts.netloc:
113 raise ValueError(
114 "LAST30DAYS_API_BASE must not include embedded credentials (userinfo)."
115 )
116 if parts.query or parts.fragment or "?" in raw or "#" in raw:
117 raise ValueError(
118 "LAST30DAYS_API_BASE must not include a query string or fragment."
119 )
120 return raw.rstrip("/")
121
122
123 def _billing_url() -> str:
124 """Derive a billing link from the configured base, so no URL is hardcoded.
125 Convention: the base is the API-version root (e.g. ends in /api/v1); drop
126 that segment and point at the account's billing page."""
127 base = _scrub_url_userinfo(_api_base())
128 root = re.sub(r"/api/v\d+$", "", base)
129 return f"{root}/dashboard/billing"
130
131
132 def _auth_headers() -> dict[str, str]:
133 # Key is read at call time and placed only in the request header;
134 # it must never be interpolated into any log or output line.
135 raw = env.read_secret_env("LAST30DAYS_API_KEY") or ""
136 key = raw.strip()
137 if not key:
138 raise ValueError("LAST30DAYS_API_KEY is empty or missing.")
139 if any(ord(ch) < 0x20 or ord(ch) >= 0x7F for ch in key):
140 raise ValueError(
141 "LAST30DAYS_API_KEY contains invalid characters for an HTTP header."
142 )
143 return {"Authorization": f"Bearer {key}"}
144
145
146 def _same_origin_redirect_guard(base: str):
147 expected_origin = http._request_origin(base)
148 return lambda newurl: http._request_origin(newurl) == expected_origin
149
150
151 def submit(query: str, depth: str, register: str = "default", clarify: dict | None = None) -> dict:
152 """POST the search. retries=1: a blind POST retry could double-submit."""
153 base = _api_base()
154 headers = _auth_headers()
155 payload = {"query": query, "depth": depth}
156 if register != "default":
157 payload["register"] = register
158 if clarify:
159 payload["clarify"] = clarify
160 usage.begin("hosted")
161 try:
162 return http.post(
163 f"{base}/search",
164 json_data=payload,
165 headers=headers,
166 retries=1,
167 bypass_proxy=providers.is_loopback_http_endpoint(base),
168 redirect_guard=_same_origin_redirect_guard(base),
169 )
170 except ValueError:
171 raise ValueError("Invalid hosted API request header or URL.") from None
172
173
174 def poll(search_id: str) -> dict:
175 """GET the search row once. Callers own the retry loop (GET is idempotent)."""
176 base = _api_base()
177 headers = _auth_headers()
178 try:
179 return http.get(
180 f"{base}/search",
181 headers=headers,
182 params={"id": search_id},
183 retries=1,
184 bypass_proxy=providers.is_loopback_http_endpoint(base),
185 redirect_guard=_same_origin_redirect_guard(base),
186 )
187 except ValueError:
188 raise ValueError("Invalid hosted API request header or URL.") from None
189
190
191 def _parse_error_body(exc: http.HTTPError) -> dict:
192 if not exc.body:
193 return {}
194 try:
195 parsed = json.loads(exc.body)
196 except (json.JSONDecodeError, TypeError):
197 return {}
198 return parsed if isinstance(parsed, dict) else {}
199
200
201 def _handle_http_error(exc: http.HTTPError) -> int:
202 body = _parse_error_body(exc)
203 if exc.status_code == 401:
204 _err(
205 "API key rejected: invalid or revoked. Check "
206 "LAST30DAYS_API_KEY (and LAST30DAYS_API_BASE), or unset them "
207 "to fall back to local sources."
208 )
209 return 1
210 if exc.status_code == 402:
211 _err(f"API: {_scrub_error_text(str(body.get('error') or 'insufficient credits.'))}")
212 if body.get("balance") is not None or body.get("needed") is not None:
213 _err(
214 _scrub_error_text(
215 f"Balance: {body.get('balance')} credits. "
216 f"Needed for this search: {body.get('needed')} credits."
217 )
218 )
219 _err(f"Add credits at {_billing_url()}")
220 return 1
221 if exc.status_code == 429:
222 _err(
223 f"API rate limit hit: "
224 f"{_scrub_error_text(str(body.get('error') or 'too many requests.'))} "
225 "Wait a minute and re-run."
226 )
227 return 1
228 _err(f"API request failed: {_scrub_error_text(str(exc))}")
229 return 1
230
231
232 def _angle_queries(resp: dict) -> dict[int, str]:
233 """Option index -> the sharpened query the API pairs with that option."""
234 queries: dict[int, str] = {}
235 angles = resp.get("angles")
236 if not isinstance(angles, list):
237 return queries
238 for index, angle in enumerate(angles, 1):
239 if isinstance(angle, dict) and isinstance(angle.get("query"), str) and angle["query"].strip():
240 queries[index] = angle["query"].strip()
241 return queries
242
243
244 def _handle_clarify(resp: dict) -> int:
245 question = resp.get("question") or "The API needs a clarification before searching."
246 options = resp.get("options") or []
247 queries = _angle_queries(resp)
248 _err(f"Clarification needed before this search runs: {question}")
249 for index, option in enumerate(options, 1):
250 label = option if isinstance(option, str) else json.dumps(option)
251 line = f" {index}. {label}"
252 if index in queries:
253 line += f" (--clarify-angle {json.dumps(queries[index])})"
254 sys.stderr.write(f"{line}\n")
255 sys.stderr.flush()
256 _err(
257 "No search was started. Re-run last30days with the same topic plus "
258 "--clarify-angle \"<chosen option's query>\", or --clarify-broadly to "
259 "run the topic as asked."
260 )
261 return EXIT_CLARIFY
262
263
264 def _failure_reason(row: dict) -> str:
265 for key in ("error", "synthesis_text"):
266 value = row.get(key)
267 if isinstance(value, str) and value.strip():
268 return value.strip()
269 return "unknown server error"
270
271
272 def _major(version) -> int | None:
273 if not isinstance(version, str):
274 return None
275 match = re.match(r"\s*v?(\d+)\.", version)
276 return int(match.group(1)) if match else None
277
278
279 def _local_engine_version() -> str | None:
280 try:
281 from . import render
282
283 version = render._skill_version()
284 except Exception:
285 return None
286 return None if not version or version == "?" else version
287
288
289 def _note_engine_version(row: dict) -> None:
290 """One stderr line when the server engine's major differs from this one."""
291 remote = row.get("engine_version")
292 local = _local_engine_version()
293 remote_major, local_major = _major(remote), _major(local)
294 if remote_major is None or local_major is None or remote_major == local_major:
295 return
296 _err(
297 f"This report came from engine v{remote} on the hosted backend; "
298 f"this skill is v{local}. Results may differ from a local run."
299 )
300
301
302 def _print_new_narration(stderr_blob: str, seen: set[str]) -> bool:
303 """Print each '[narrate] step=' line once, verbatim. Returns True if any new."""
304 printed = False
305 for line in stderr_blob.splitlines():
306 if line.startswith(NARRATE_PREFIX) and line not in seen:
307 seen.add(line)
308 sys.stderr.write(f"{line}\n")
309 printed = True
310 if printed:
311 sys.stderr.flush()
312 return printed
313
314
315 def _print_progress_line(elapsed: float, eta_ms) -> None:
316 line = f"elapsed {int(elapsed)}s"
317 if isinstance(eta_ms, (int, float)) and eta_ms > 0:
318 line += f", eta ~{int(eta_ms / 1000)}s"
319 _err(line)
320
321
322 def _poll_with_retry(search_id: str) -> dict | None:
323 """Poll once, retrying transient network failures. None means give up
324 (a user-facing message has already been printed)."""
325 last_error: http.HTTPError | None = None
326 for attempt in range(POLL_NETWORK_RETRIES):
327 try:
328 return poll(search_id)
329 except ValueError as exc:
330 _err(_scrub_error_text(str(exc)))
331 return None
332 except http.HTTPError as exc:
333 if exc.status_code is not None and 400 <= exc.status_code < 500 and exc.status_code != 429:
334 _handle_http_error(exc)
335 return None
336 # Network blip / timeout / 5xx / 429: GET is idempotent, retry.
337 last_error = exc
338 if attempt < POLL_NETWORK_RETRIES - 1:
339 time.sleep(POLL_INITIAL_DELAY)
340 _err(
341 f"API unreachable while polling search {search_id} "
342 f"after {POLL_NETWORK_RETRIES} attempts: {_scrub_error_text(str(last_error))}"
343 )
344 return None
345
346
347 def _slugify(value: str) -> str:
348 return library.filename_slug(library.slugify(value))
349
350
351 def _sanitize_suffix(suffix: str) -> str:
352 """Sanitize --save-suffix to a path-safe token (same policy as the local
353 save path): lowercase, fold non [a-z0-9] runs to a single hyphen, strip
354 edge hyphens. Unlike _slugify there is no fallback token - a suffix that
355 sanitizes to empty simply drops, so a suffix can never contribute path
356 separators or parent references to the saved filename."""
357 return re.sub(r"[^a-z0-9]+", "-", suffix.lower()).strip("-")
358
359
360 def _save_output(topic: str, content: str, emit: str, save_dir: str, suffix: str):
361 """Mirror local save_output() naming: <slug>-raw[-suffix].<ext>."""
362 from datetime import datetime
363 from pathlib import Path
364
365 path = Path(save_dir).expanduser().resolve()
366 path.mkdir(parents=True, exist_ok=True)
367 slug = _slugify(topic)
368 extension = "json" if emit == "json" else "md"
369 sanitized_suffix = _sanitize_suffix(suffix or "")
370 suffix_part = f"-{sanitized_suffix}" if sanitized_suffix else ""
371 base = path / f"{slug}-raw{suffix_part}.{extension}"
372 date_str = datetime.now().strftime('%Y-%m-%d')
373 candidates = [base]
374 candidates.append(path / f"{slug}-raw{suffix_part}-{date_str}.{extension}")
375 for i in range(1, 100):
376 candidates.append(path / f"{slug}-raw{suffix_part}-{date_str}-{i}.{extension}")
377 encoded = content.encode("utf-8")
378 for candidate in candidates:
379 try:
380 fd = os.open(candidate, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
381 except FileExistsError:
382 continue
383 with os.fdopen(fd, "wb") as f:
384 f.write(encoded)
385 return candidate
386 # Fallback: all 101 candidates existed (extremely unlikely).
387 raise RuntimeError(
388 f"_save_output: could not find a unique filename after 101 attempts in {path}"
389 )
390
391
392 def _render_complete(row: dict, topic: str, emit: str, save_dir, save_suffix: str) -> int:
393 synthesis = row.get("synthesis_text") or ""
394 raw_markdown = row.get("raw_markdown") or ""
395 if emit == "json":
396 payload = {
397 key: row.get(key)
398 for key in ("id", "status", "synthesis_text", "raw_markdown")
399 if key in row
400 }
401 rendered = json.dumps(payload, indent=2, sort_keys=True)
402 save_content = rendered
403 else:
404 # The server report is the content source; it already synthesized.
405 # All markdown-ish emit modes print the synthesis text as-is.
406 rendered = synthesis or raw_markdown
407 save_content = raw_markdown or synthesis
408 if save_dir:
409 out_path = _save_output(topic, save_content, emit, save_dir, save_suffix)
410 sys.stderr.write(f"[last30days] Saved output to {out_path}\n")
411 sys.stderr.flush()
412 print(rendered)
413 return 0
414
415
416 def run_hosted(
417 topic: str,
418 depth: str,
419 *,
420 emit: str = "compact",
421 save_dir=None,
422 save_suffix: str = "",
423 register: str = "default",
424 clarify: dict | None = None,
425 ) -> int:
426 """Submit topic to the remote API, poll to terminal status, render report."""
427 try:
428 base = _api_base()
429 except ValueError as exc:
430 _err(_scrub_error_text(str(exc)))
431 return 1
432 _err(f"Running via last30days API ({_scrub_url_userinfo(base)}), depth={depth}")
433 try:
434 resp = submit(topic, depth, register=register, clarify=clarify)
435 except ValueError as exc:
436 _err(_scrub_error_text(str(exc)))
437 return 1
438 except http.HTTPError as exc:
439 return _handle_http_error(exc)
440
441 if resp.get("needs_clarification"):
442 return _handle_clarify(resp)
443
444 search_id = resp.get("search_id")
445 if not search_id:
446 _err(f"Unexpected API response (no search_id): {_scrub_error_text(json.dumps(resp))[:200]}")
447 return 1
448 _err(f"Search submitted (id: {search_id}). Polling for results...")
449
450 started = time.monotonic()
451 delay = POLL_INITIAL_DELAY
452 seen_narration: set[str] = set()
453 last_progress_line = 0.0
454 while True:
455 elapsed = time.monotonic() - started
456 if elapsed > POLL_TIMEOUT_SECONDS:
457 _err(
458 f"Search did not finish within "
459 f"{POLL_TIMEOUT_SECONDS // 60} minutes (id: {search_id}). "
460 "It may still complete server-side; check the dashboard."
461 )
462 return 1
463 time.sleep(delay)
464 delay = min(delay * 2, POLL_MAX_DELAY)
465
466 row = _poll_with_retry(search_id)
467 if row is None:
468 return 1
469
470 status = row.get("status")
471 narrated = _print_new_narration(row.get("stderr") or "", seen_narration)
472 elapsed = time.monotonic() - started
473 if status not in TERMINAL_STATUSES and (
474 narrated or elapsed - last_progress_line >= PROGRESS_LINE_INTERVAL or last_progress_line == 0.0
475 ):
476 _print_progress_line(elapsed, row.get("eta_ms"))
477 last_progress_line = elapsed
478
479 if status in TERMINAL_STATUSES:
480 _note_engine_version(row)
481 if status == "error":
482 _err(f"Search failed: {_scrub_error_text(_failure_reason(row))}")
483 return 1
484 if status == "complete":
485 _err(f"Search complete in {int(elapsed)}s.")
486 return _render_complete(row, topic, emit, save_dir, save_suffix)
487 # pending | running -> keep polling
488
488 lines PYTHON