diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fea7dd..0437a70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,14 @@ Works with RateCue 0.2.0 and earlier. ### Added +- **Hosted models.** The agent can run against a hosted OpenAI-compatible endpoint as well as a private one. When an endpoint rejects a request option it does not support (`max_tokens`, `temperature`, the chat-template option that turns thinking off), the agent drops or renames that option and retries at once. When an endpoint refuses the API key, the agent stops instead of retrying. +- `LLM_AUTH=anthropic-login`. The agent takes a short-lived token from the Anthropic CLI's login (`ant auth login`) and renews it as it expires, so no key is stored in its settings. +- When a provider reports that the account has no credit, the agent stops as it does for a refused key, instead of retrying. +- `LLM_TEMPERATURE`. Unset, the agent sends a temperature of 0.4 to a model on its machine or network and none to a hosted one, since current hosted models accept only their own default. `none` sends no temperature anywhere. +- Token use. Each cycle's log line carries the input and output tokens the endpoint reported, and the report states the total for its knowledge base. On a hosted model that is the bill. +- `model_smoke_test.py` asks a hosted endpoint the way it accepts: Anthropic's model list with its own key header, no temperature or chat-template option, and room for a model that thinks before it answers. +- `LOG_SCOPE`. With `playback`, a `log show` result reaches the model with only Music's playback and audio subsystems and without URL query strings. Unset, it is `playback` for an endpoint that is not on this machine or a private network, and `all` otherwise. +- Track titles are replaced in Music's `mediaFormatinfo` record: by the collector before it stores a log line, by the gate in every result, and by the agent in everything the Mac returns. macOS only writes the title there when a log-privacy profile is installed. - `queue_prediction_metrics`: Music's own advance notice of a queue item's format, when it queues the item and when it starts buffering it, scored against the item's first decoder report. A database that predates the table is scored once from the log lines it already holds. - The gate allows RateCue's read-only `decoder-status` command. - The collector reads the displayed format from the explicit fields RateCue 0.2 publishes, and understands both the new (`96 kHz / 24-bit`) and the earlier (`96k / 24`) menu title. @@ -15,6 +23,7 @@ Works with RateCue 0.2.0 and earlier. ### Changed +- The `queued` stage of `queue_predictions` is read from Music's variant-selection record, whose fields are public, instead of the "highest eligible alternate" record, whose variant needs a log-privacy profile. - `track_formats` selects the decoder report by when it was logged, which is the audible boundary, instead of by when Music began buffering the item. - `ratecue_*` is the last snapshot taken while the track was current. - A decoder report with a rate and no depth is recorded as a lossy rendition. For such a play, displaying no depth is a `match` and displaying one is a `MISMATCH`. @@ -29,5 +38,5 @@ Works with RateCue 0.2.0 and earlier. First public release: the collector, the read-only SSH gate, the research agent, the three-way comparison, and best-effort sequence prediction metrics. -[0.2.0]: https://github.com/troylefevre65/StreamWatch/compare/df856e0...main +[0.2.0]: https://github.com/troylefevre65/StreamWatch/releases/tag/v0.2.0 [0.1.0]: https://github.com/troylefevre65/StreamWatch/commits/df856e0 diff --git a/MODEL-SELECTION.md b/MODEL-SELECTION.md index f567ed9..8c1519f 100644 --- a/MODEL-SELECTION.md +++ b/MODEL-SELECTION.md @@ -5,6 +5,20 @@ changing the agent to fit whichever model happens to be loaded. A private OpenAI-compatible host is used for evaluation; a separate appliance remains the collector and RateCue appliance. +## Switching models + +The agent takes five settings from its environment file: `LLM_BASE_URL`, `LLM_API_KEY`, `LLM_MODEL`, `NO_THINK` and `CYCLE_PAUSE`, plus `LOG_SCOPE` for what it may send and `LLM_AUTH` for how it signs in (`key`, or `anthropic-login` to use the Anthropic CLI's login with no stored key). Any OpenAI-compatible endpoint works: Ollama, LM Studio, a llama.cpp server, or a hosted API such as Claude (`https://api.anthropic.com/v1`), OpenAI or OpenRouter. Change them and restart the agent. + +When the agent runs on the Mac beside RateCue, RateCue does this for you. **Advanced Diagnostics → Developer Mode → Agent Model** keeps a list of models, holds API keys in the Keychain, rewrites those settings when you select one, and restarts the agent. `RateCue developer model list | add | use | models | remove` is the same thing from a shell. It does not touch `AGENT_DB` or `REPORT_PATH`, so a switched model continues the same knowledge base; give a comparison run its own database as described under [Prepare a repeatable evaluation](#prepare-a-repeatable-evaluation). + +A hosted model is sent no sampling temperature unless `LLM_TEMPERATURE` sets one, and a model that thinks before it answers needs room for that in `LLM_MAX_TOKENS`: 2048 suits a small local model with thinking turned off, and 8192 is a safer start for a hosted one. `llm-box/model_smoke_test.py` works against either kind. Through Anthropic's OpenAI-compatible endpoint there is no prompt caching, and Anthropic describes that endpoint as meant for testing and comparison. + +Each cycle's log line reports the tokens it used, and the report carries the running total, so the cost of a hosted run is measured and not guessed. + +Otherwise the agent sends each endpoint the same request and adjusts once if it is refused: it switches `max_tokens` to `max_completion_tokens`, stops sending a temperature, or stops sending the chat-template option behind `NO_THINK`, whichever the endpoint names. A refused key stops the agent. + +A hosted model changes two things that a local one does not: the agent's working context leaves your network, and every cycle costs money. Read [Hosted models](SECURITY.md#hosted-models) first. The rest of this guide is about choosing and proving a local model, and its scorecard applies to a hosted one unchanged. + ## Current host and baseline A private evaluation host can serve llama.cpp at an operator-configured endpoint: diff --git a/OPERATIONS.md b/OPERATIONS.md index 16c8f25..f05df65 100644 --- a/OPERATIONS.md +++ b/OPERATIONS.md @@ -220,6 +220,8 @@ This mode is for a remote-model test while a dedicated LLM box is being built. I chmod 600 ~/streamwatch/agent.env ``` + To use a different model later, change those settings and restart the agent, or select one in RateCue under **Developer Mode → Agent Model**. For an endpoint outside your network, read [Hosted models](SECURITY.md#hosted-models) first; the agent then defaults to `LOG_SCOPE=playback`. + 6. For a foreground smoke test, source that environment and run the checked-out `llm-box/agent.py` with the venv. For unattended use, wrap those commands in a `~/streamwatch/run-agent.sh` script and a LaunchAgent that logs under `~/streamwatch/`. Do not put the LaunchAgent plist in the Git repository; it contains local paths. 7. Confirm the forced-key query, OpenAI tool call, collector smoke test and completed agent cycle before leaving it unattended. diff --git a/SECURITY.md b/SECURITY.md index fc14b73..a8a4850 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -25,9 +25,28 @@ The Mac's forced SSH command is an execution boundary for the agent, not complet - Keep the remote endpoint HTTP on a trusted LAN or provide TLS; credentials sent over cleartext should be treated as equivalent to public on that network. - Limit GitHub tokens to read-only public-repository access. +## Hosted models + +A model on the agent's machine or a private network keeps the agent's working context there. A hosted endpoint receives it, and bills for it. Decide that deliberately. + +What a hosted endpoint is sent: the research prompt, playback times and formats, audio device details, the results of the agent's database queries and Mac commands, RateCue and other public source code, search results and the web pages the agent reads. + +What it is not sent: + +- Track titles, artists, albums and persistent identifiers. The gate's SQL authorizer denies those columns, and the title in Music's `mediaFormatinfo` log record is replaced by the collector, the gate and the agent. +- Most of Music's log. With `LOG_SCOPE=playback`, which is the default for any endpoint that is not local, the agent passes on only the `com.apple.coremedia`, `com.apple.coreaudio` and `com.apple.audio*` subsystems of a `log show` result and removes URL query strings. This matters on a Mac with a log-privacy profile installed: there, Music's store, account and network subsystems log account identifiers and addresses in the clear. In a 20-minute sample on such a Mac the playback and audio subsystems held no URL and no account identifier in 10,544 lines; the other subsystems held both. + +This filter is the agent's, so it protects only an agent new enough to have it. RateCue checks for it before it will select a hosted model. `LOG_SCOPE=all` with a hosted endpoint sends all of Music's log and is logged as a warning at start. + +It is a filter on known fields, not a guarantee. Playback times are a listening history without titles, and a line in an allowed subsystem could carry something unexpected. If that is unacceptable, use a local model. + +For Claude, `LLM_AUTH=anthropic-login` keeps any long-lived secret out of the agent's settings: the agent asks the Anthropic CLI for the access token of its login, which lasts hours, and asks again as it expires. The login itself is stored by the CLI under `~/.config/anthropic`, readable only by its owner. Anthropic intends that login for development on your own machine; a server should use an API key or workload identity federation. + +Use `https` for any endpoint outside a private network. Give a hosted provider a key with a spending limit where the provider offers one, and set `CYCLE_PAUSE` high: it is the only throttle on what an always-on agent spends. With the default limits one cycle is at most 14 model calls of about 12,000 input and 4,096 output tokens each. + ## Private data -The Mac database intentionally retains some local operator metadata so the collector can detect track transitions. The LLM-facing view and SSH authorizer omit track and device identity. Raw audio-log messages, device transport/rate, RateCue status and playback timing are still sensitive operational data. +The Mac database intentionally retains some local operator metadata so the collector can detect track transitions. The LLM-facing view and SSH authorizer omit track and device identity. Raw audio-log messages, device transport/rate, RateCue status and playback timing are still sensitive operational data. `log show` through the gate returns whatever Music logged in the requested window; see [Hosted models](#hosted-models) for what an agent with a hosted endpoint passes on. External search is blocked when a query contains obvious local paths, IP addresses, UUID-like IDs or email addresses. This is defense in depth, not perfect data-loss prevention. Do not paste private diagnostics into a model or public issue without review. diff --git a/llm-box/agent.py b/llm-box/agent.py index 3750f4e..0c6390b 100755 --- a/llm-box/agent.py +++ b/llm-box/agent.py @@ -26,6 +26,7 @@ import socket import sqlite3 import subprocess +import shutil import sys import time import urllib.request @@ -37,8 +38,16 @@ ENV = os.environ.get LLM_BASE_URL = ENV("LLM_BASE_URL", "http://127.0.0.1:11434/v1") LLM_API_KEY = ENV("LLM_API_KEY", "ollama") +# How the agent proves who it is. 'key' sends LLM_API_KEY. 'anthropic-login' asks the Anthropic CLI for +# the access token of its login ('ant auth login') and renews it as it expires, so no key is stored. +LLM_AUTH = ENV("LLM_AUTH", "key").strip().lower() +ANT_BIN = ENV("ANT_BIN", "") +LOGIN_TOKEN_MAX_AGE = 600.0 LLM_MODEL = ENV("LLM_MODEL", "qwen3:14b") LLM_MAX_TOKENS = int(ENV("LLM_MAX_TOKENS", "4096")) +# Sampling temperature. Unset: 0.4 for a model on this machine or network, and none for a hosted one, +# because hosted models increasingly accept only their own default. 'none' sends no temperature. +LLM_TEMPERATURE = ENV("LLM_TEMPERATURE", "").strip().lower() LLM_TIMEOUT = float(ENV("LLM_TIMEOUT", "900")) NO_THINK = ENV("NO_THINK", "0") == "1" MAC_SSH = ENV("MAC_SSH", "") # e.g. musicuser@mac-mini.local ; empty = Mac tools disabled @@ -53,6 +62,9 @@ SEARCH_MIN_INTERVAL = float(ENV("SEARCH_MIN_INTERVAL", "20")) SEARCH_BLOCK_BACKOFF = float(ENV("SEARCH_BLOCK_BACKOFF", "900")) # first cooldown after a rate limit; doubles, max 2 h CYCLE_PAUSE = float(ENV("CYCLE_PAUSE", "30")) +# What a `log show` result may carry to the model: 'all' of Music's log, or only its 'playback' and audio +# subsystems. Unset, it follows the endpoint: 'all' for a model on this machine or network, 'playback' otherwise. +LOG_SCOPE = ENV("LOG_SCOPE", "").strip().lower() IDLE_PAUSE = float(ENV("IDLE_PAUSE", "900")) MAX_LEAD_ATTEMPTS = int(ENV("MAX_LEAD_ATTEMPTS", "4")) MAX_CYCLES = int(ENV("MAX_CYCLES", "0")) # 0 = run forever @@ -543,6 +555,119 @@ def next_lead(self): "SELECT * FROM leads WHERE status='open' ORDER BY priority DESC, attempts ASC, id ASC LIMIT 1").fetchone() +def endpoint_is_local(url): + """True when the model endpoint is this machine or a private network, so nothing sent to it leaves.""" + host = (urlparse(url).hostname or "").lower() + if not host: + return False + try: + address = ipaddress.ip_address(host) + except ValueError: + return host == "localhost" or host.endswith(".local") or "." not in host + return (address.is_loopback or address.is_private or address.is_link_local + or address in ipaddress.ip_network("100.64.0.0/10")) + + +def temperature_setting(): + if LLM_TEMPERATURE: + return None if LLM_TEMPERATURE in ("none", "off", "default") else float(LLM_TEMPERATURE) + return 0.4 if endpoint_is_local(LLM_BASE_URL) else None + + +def anthropic_cli(): + # A service started by launchd or systemd has a short PATH; look where the CLI is usually installed. + for path in (ANT_BIN, shutil.which("ant"), "/opt/homebrew/bin/ant", "/usr/local/bin/ant", + os.path.expanduser("~/.local/bin/ant")): + if path and os.access(path, os.X_OK): + return path + return None + + +def login_token(): + """A current access token from the Anthropic CLI's login. The CLI renews it when it is close to expiry.""" + binary = anthropic_cli() + if not binary: + raise LLMRefused("LLM_AUTH=anthropic-login needs the Anthropic CLI ('ant'), which was not found") + # A key or token in the environment would be printed in place of the login's. + env = {k: v for k, v in os.environ.items() if k not in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN")} + try: + out = subprocess.run([binary, "auth", "print-credentials", "--access-token"], + capture_output=True, text=True, timeout=60, env=env) + except (OSError, subprocess.TimeoutExpired) as e: + raise LLMRefused(f"the Anthropic CLI could not be run ({e})") from e + token = out.stdout.strip() + if out.returncode != 0 or not token or any(c.isspace() for c in token): + raise LLMRefused("the Anthropic CLI has no usable login; run 'ant auth login'") + return token + + +def account_refusal(status, message): + """Why an endpoint will keep refusing this account whatever is sent, or None.""" + text = str(message).lower() + if status in (401, 403): + return f"the model endpoint refused the credentials (HTTP {status})" + if status == 402 or "credit balance" in text or "insufficient_quota" in text or "billing" in text: + return "the provider reports that the account has no credit left" + return None + + +def log_scope(): + return LOG_SCOPE if LOG_SCOPE in ("all", "playback") else ("all" if endpoint_is_local(LLM_BASE_URL) else "playback") + + +# The same record the collector's gate redacts. Repeated here because this process is the last stop before +# the model, and it may be newer than the gate it talks to. +TITLE_RE = re.compile(r"(mediaFormatinfo ')(.*?)(' , (?=[A-Za-z]+[,:])|$)", re.S) +PLAYBACK_SUBSYSTEMS = ("com.apple.coremedia", "com.apple.coreaudio", "com.apple.audio") +LOG_ENTRY_START = re.compile(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}") +URL_QUERY = re.compile(r"(https?://[^\s?'\"<>]+)\?[^\s'\"<>]*") + + +def redact_titles(text): + if not isinstance(text, str) or "mediaFormatinfo '" not in text: + return text + return TITLE_RE.sub(lambda m: m.group(1) + "" + m.group(3), text) + + +def scope_log_output(text): + """Keeps the playback and audio subsystems of a `log show` result and drops URL query strings. + Music also logs store, account and network activity; with a log-privacy profile installed those + lines hold account identifiers and addresses, and they are of no use for format research.""" + kept, withheld, keep = [], 0, False + for line in text.splitlines(): + stripped = line.lstrip() + if stripped.startswith("{"): + try: + keep = (json.loads(stripped).get("subsystem") or "").startswith(PLAYBACK_SUBSYSTEMS) + except (json.JSONDecodeError, AttributeError): + keep = False + withheld += not keep + elif LOG_ENTRY_START.match(line): + keep = any(f"[{subsystem}" in line for subsystem in PLAYBACK_SUBSYSTEMS) + withheld += not keep + # Any other line continues the entry above it and shares its fate. + if keep: + kept.append(line) + note = (f"[{withheld} entries from other subsystems withheld because the model endpoint is not local; " + "use --style compact or ndjson]") if withheld or not kept else "" + return URL_QUERY.sub(r"\1?<query>", "\n".join(kept + [note] if note else kept)) + + +def sanitize_gate_result(request, result, scope=None): + """Applied to everything the Mac returns before the model sees it.""" + if not isinstance(result, dict): + return result + if isinstance(result.get("rows"), list): + result["rows"] = [[redact_titles(cell) for cell in row] for row in result["rows"]] + if isinstance(result.get("output"), str): + output = redact_titles(result["output"]) + argv = request.get("argv") or [] + if (scope or log_scope()) == "playback" and argv[:1] == ["log"]: + output = scope_log_output(output) + result["output"] = output + return result + + class Mac: def __init__(self): self.enabled = bool(MAC_SSH) @@ -560,7 +685,7 @@ def call(self, request): if out.returncode != 0 and not out.stdout.strip(): return {"ok": False, "error": f"ssh failed ({out.returncode}): {out.stderr.strip()[:500]}"} try: - return json.loads(out.stdout.strip().splitlines()[-1]) + return sanitize_gate_result(request, json.loads(out.stdout.strip().splitlines()[-1])) except (json.JSONDecodeError, IndexError): return {"ok": False, "error": f"unexpected gate output: {out.stdout[:500]}"} @@ -708,7 +833,7 @@ class Agent: def __init__(self): self.kb = KB(AGENT_DB) self.mac = Mac() - self.llm = OpenAI(base_url=LLM_BASE_URL, api_key=LLM_API_KEY, timeout=LLM_TIMEOUT, max_retries=0) + self.connect() self.last_search = 0.0 self.last_github = 0.0 self.repos = Repos(WATCH_REPOS, REPOS_DIR) @@ -1303,21 +1428,86 @@ def size(): replacement = body + marker if marker_size else content[:keep] messages[index]["content"] = replacement + def _request_options(self): + options = getattr(self, "llm_options", None) + if options is None: + options = self.llm_options = { + "token_parameter": "max_tokens", "temperature": temperature_setting(), "no_think": NO_THINK} + return options + + def chat_request(self, messages, tools): + options = self._request_options() + request = dict(model=LLM_MODEL, messages=messages, tools=tools, tool_choice="auto") + request[options["token_parameter"]] = LLM_MAX_TOKENS + if options["temperature"] is not None: + request["temperature"] = options["temperature"] + if options["no_think"]: + request["extra_body"] = {"chat_template_kwargs": {"enable_thinking": False}} + return request + + def adapt_request(self, message): + """Model servers differ in the request options they accept. When a server refuses a request + and names one of the options this agent sends, stop sending it. Returns True if anything changed.""" + options, text = self._request_options(), str(message).lower() + if "max_completion_tokens" in text and options["token_parameter"] == "max_tokens": + options["token_parameter"] = "max_completion_tokens" + return True + if "chat_template_kwargs" in text and options["no_think"]: + options["no_think"] = False + return True + if "temperature" in text and options["temperature"] is not None: + options["temperature"] = None + return True + return False + + def connect(self): + """Builds the model client. With a login in place of a key this is repeated as its tokens expire.""" + if LLM_AUTH == "anthropic-login": + self.llm = OpenAI(base_url=LLM_BASE_URL, api_key=login_token(), timeout=LLM_TIMEOUT, max_retries=0, + default_headers={"anthropic-beta": "oauth-2025-04-20"}) + else: + self.llm = OpenAI(base_url=LLM_BASE_URL, api_key=LLM_API_KEY, timeout=LLM_TIMEOUT, max_retries=0) + self.llm_connected = time.time() + def chat(self, messages, tools): + renewed = False for attempt in range(5): + if LLM_AUTH == "anthropic-login" and time.time() - getattr(self, "llm_connected", 0) > LOGIN_TOKEN_MAX_AGE: + self.connect() try: - request = dict( - model=LLM_MODEL, messages=messages, temperature=0.4, max_tokens=LLM_MAX_TOKENS, - tools=tools, tool_choice="auto") - if NO_THINK: - request["extra_body"] = {"chat_template_kwargs": {"enable_thinking": False}} - return self.llm.chat.completions.create(**request) + response = self.llm.chat.completions.create(**self.chat_request(messages, tools)) + self.count_usage(response) + return response except Exception as e: + status = getattr(e, "status_code", None) + if status == 401 and LLM_AUTH == "anthropic-login" and not renewed: + # The token may have expired between renewals. Ask the CLI once more before giving up. + renewed = True + self.connect() + continue + refusal = account_refusal(status, e) + if refusal: + # Retrying a refused key or an empty account only repeats the refusal. + raise LLMRefused(refusal) from e + if status == 400 and self.adapt_request(e): + log.warning("LLM refused a request option (%s); adjusted, retrying now", e) + continue log.warning("LLM call failed (%s); retrying", e) time.sleep(min(30 * 2 ** attempt, 600)) raise RuntimeError("LLM unavailable") + def count_usage(self, response): + """Adds what the endpoint says a call used to the cycle's total. On a hosted model this is the bill.""" + usage, spent = getattr(response, "usage", None), getattr(self, "cycle_tokens", None) + if usage is None or spent is None: + return + for index, field in enumerate(("prompt_tokens", "completion_tokens")): + value = getattr(usage, field, None) + if isinstance(value, int) and not isinstance(value, bool): + spent[index] += value + def run_cycle(self, mode, lead, observations): + self.cycle_tokens = [0, 0] self.cycle_lead_id = lead["id"] if lead else None self.cycle_finished, self.cycle_new_leads, self.cycle_findings = None, 0, [] seen_tool_requests, tool_calls, duplicate_tool_calls = set(), 0, 0 @@ -1395,10 +1585,15 @@ def run_cycle(self, mode, lead, observations): "duplicate_tool_calls, finish_cycle_called) VALUES(?,?,?,?,?,?,?,?,?)", (time.time(), self.cycle_lead_id, mode, steps, summary, int(exhausted), tool_calls, duplicate_tool_calls, int(self.cycle_finished is not None))) + tokens_in, tokens_out = self.cycle_tokens + if tokens_in or tokens_out: + self.kb.set("tokens_in", int(self.kb.get("tokens_in", "0")) + tokens_in) + self.kb.set("tokens_out", int(self.kb.get("tokens_out", "0")) + tokens_out) log.info( - "cycle done (%s, lead=%s, steps=%d, tools=%d, duplicates=%d, finish_cycle=%s, new leads=%d): %s", + "cycle done (%s, lead=%s, steps=%d, tools=%d, duplicates=%d, finish_cycle=%s, new leads=%d, " + "tokens in=%d out=%d): %s", mode, self.cycle_lead_id, steps, tool_calls, duplicate_tool_calls, - self.cycle_finished is not None, self.cycle_new_leads, summary[:300]) + self.cycle_finished is not None, self.cycle_new_leads, tokens_in, tokens_out, summary[:300]) return exhausted # --------------------------------------------------------------- report @@ -1409,6 +1604,9 @@ def write_report(self): out.append(f"Cycles: {kb.q('SELECT count(*) FROM cycles')[0][0]} | Findings: " f"{kb.q('SELECT count(*) FROM findings')[0][0]} | Leads: {counts} | Searches: " f"{kb.q('SELECT count(*) FROM searches')[0][0]} | Pages read: {kb.q('SELECT count(*) FROM pages')[0][0]}\n") + tokens_in, tokens_out = int(kb.get("tokens_in", "0")), int(kb.get("tokens_out", "0")) + if tokens_in or tokens_out: + out.append(f"Model tokens used by this knowledge base: {tokens_in:,} in, {tokens_out:,} out.\n") out.append("## RateCue scorecard\n\nMusic's decoder report is the reference here; it is Music's own statement, " "not independent ground truth.\n\n" + self.scorecard().replace("\n", " \n") + "\n") out.append(f"## RateCue proposals\n\nDraft issues in `{PROPOSALS_DIR}`; nothing is filed automatically.\n") @@ -1497,10 +1695,23 @@ def run(self): time.sleep(pause) +class LLMRefused(RuntimeError): + """The model endpoint refused the credentials or the account. A restart cannot fix that.""" + + def main(): logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", stream=sys.stdout) - log.info("StreamWatch agent: model=%s llm=%s mac=%s db=%s", LLM_MODEL, LLM_BASE_URL, MAC_SSH or "(none)", AGENT_DB) - Agent().run() + log.info("StreamWatch agent: model=%s llm=%s mac=%s db=%s log scope=%s", + LLM_MODEL, LLM_BASE_URL, MAC_SSH or "(none)", AGENT_DB, log_scope()) + if log_scope() == "all" and not endpoint_is_local(LLM_BASE_URL): + log.warning("LOG_SCOPE=all with a model endpoint that is not local: all of Music's log can be sent to it") + try: + Agent().run() + except LLMRefused as e: + # The service manager restarts this process. Wait first, so a refused key is not retried every minute. + log.error("Stopping: %s. Correct that and restart the agent. Waiting %d s before exit.", e, IDLE_PAUSE) + time.sleep(IDLE_PAUSE) + raise SystemExit(1) if __name__ == "__main__": diff --git a/llm-box/model_smoke_test.py b/llm-box/model_smoke_test.py index 307c600..372e680 100644 --- a/llm-box/model_smoke_test.py +++ b/llm-box/model_smoke_test.py @@ -2,11 +2,26 @@ # SPDX-License-Identifier: GPL-3.0-only """Verify an OpenAI-compatible endpoint can run a StreamWatch tool cycle.""" import argparse +import ipaddress import json import os import sys import urllib.error import urllib.request +from urllib.parse import urlparse + + +def endpoint_is_local(url): + """True for a model on this machine or a private network. A hosted model is asked differently.""" + host = (urlparse(url).hostname or "").lower() + if not host: + return False + try: + address = ipaddress.ip_address(host) + except ValueError: + return host == "localhost" or host.endswith(".local") or "." not in host + return (address.is_loopback or address.is_private or address.is_link_local + or address in ipaddress.ip_network("100.64.0.0/10")) def request_json(url, *, body=None, api_key="", timeout=30): @@ -15,7 +30,10 @@ def request_json(url, *, body=None, api_key="", timeout=30): if body is not None: headers["Content-Type"] = "application/json" data = json.dumps(body).encode("utf-8") - if api_key: + if api_key and body is None and (urlparse(url).hostname or "").lower() == "api.anthropic.com": + # Anthropic's model list takes the key in its own header; its chat route takes a bearer token. + headers.update({"x-api-key": api_key, "anthropic-version": "2023-06-01"}) + elif api_key: headers["Authorization"] = f"Bearer {api_key}" request = urllib.request.Request(url, data=data, headers=headers, method="POST" if data else "GET") try: @@ -61,11 +79,16 @@ def run(base_url, model, api_key, timeout, no_think): }, }], "tool_choice": "auto", - "temperature": 0.2, "max_tokens": 512, } - if no_think: - body["chat_template_kwargs"] = {"enable_thinking": False} + if endpoint_is_local(base_url): + body["temperature"] = 0.2 + if no_think: + body["chat_template_kwargs"] = {"enable_thinking": False} + else: + # A hosted model may accept only its default sampling settings, does not know the chat-template + # option, and may think before it answers, which counts against the token limit. + body["max_tokens"] = 2048 response = request_json( f"{base_url}/chat/completions", diff --git a/mac/collector.py b/mac/collector.py index 5b62ed1..3c4a20d 100755 --- a/mac/collector.py +++ b/mac/collector.py @@ -58,6 +58,19 @@ r"audio\s?format|output\s?device|fpfs_StartTrackPlaying|fpfs_Report|AudioGroup audio-|Rendition" ) +# Music logs the track title inside its mediaFormatinfo record. macOS writes <private> there unless a +# log-privacy profile is installed; with one, the title is in the log. It is the only track metadata in +# the records StreamWatch reads, and it never needs to leave the collector. +TITLE_RE = re.compile(r"(mediaFormatinfo ')(.*?)(' , (?=[A-Za-z]+[,:])|$)", re.S) + + +def redact_titles(text): + """Replaces the track title in Music's mediaFormatinfo records with a placeholder.""" + if not isinstance(text, str) or "mediaFormatinfo '" not in text: + return text + return TITLE_RE.sub(lambda m: m.group(1) + "<title>" + m.group(3), text) + + SCHEMA = """ CREATE TABLE IF NOT EXISTS raw_log( id INTEGER PRIMARY KEY, ts REAL NOT NULL, subsystem TEXT, category TEXT, message TEXT); @@ -418,6 +431,8 @@ class FormatParser: REPORT = re.compile(r"\[SampleRate ([0-9]{4,6})\] \[BitDepth ([0-9]{1,2})\]") LOSSLESS_DEPTHS = (16, 20, 24, 32) LOSSLESS_VARIANT = re.compile(r"AudioGroup audio-alac-stereo-([0-9]{5,6})-(16|20|24|32)\]") + # The selection record names its item as "<pointer> I/XXX.NN:", not "<pointer|I/XXX.NN>". + SELECTION_ITEM = re.compile(r"<(0x[0-9A-Fa-f]+)> (I/[A-Z0-9.]+):") REPORT_FORMAT = re.compile(r"\[AudioFormat (\w+)") REPORT_RENDITION = re.compile(r"\[Rendition ([^\]]+)\]") AUDIO_GROUP = re.compile(r"AudioGroup audio-([a-z0-9]+)-([a-z0-9]+)-([0-9]{5,6})(?:-(8|16|20|24|32)(?![0-9]))?") @@ -467,12 +482,18 @@ def _lifecycle(self, ts, message): @classmethod def queue_prediction(cls, message, lifecycle): - """The lossless variant Music logged for a queue item before it played, if this line carries one.""" - if not lifecycle: - return None - if "fpfsi_logHighestEligibleAlternate" in message: - stage = "queued" - elif "fpfs_StartTrackPlaying" in message and "playback switches" in message: + """The lossless variant Music logged for a queue item before it played, if this line carries one. + + 'queued' comes from the variant-selection record, which Music logs as public. The neighbouring + "highest eligible alternate" record carries its variant as a private field, which reads <private> + unless a log-privacy profile is installed, so it is not used.""" + if "fpfs_ReportVariantSwitchStart" in message: + item = cls.SELECTION_ITEM.search(message) + target = message.find("] to [") + if not item or target < 0: + return None + stage, lifecycle, message = "queued", f"{item.group(1)}|{item.group(2)}", message[target:] + elif lifecycle and "fpfs_StartTrackPlaying" in message and "playback switches" in message: stage = "prebuffered" else: return None @@ -497,7 +518,7 @@ def feed(self, ts, message): p["bd"] = int(m.group(1)) elif "sdBitRate" in message: p["lossy"] = True - p["raw"].append(message[:500]) + p["raw"].append(redact_titles(message)[:500]) p["ts"] = ts if p["sr"] is not None and (p["bd"] is not None or p["lossy"]): events.append(dict(source="music.audioCapabilities", priority=1, sample_rate_hz=p["sr"], @@ -792,7 +813,7 @@ def backfill_queue_predictions(store): return 0 rows = store.conn.execute( "SELECT ts, message FROM raw_log WHERE message LIKE '%fpfs_StartTrackPlaying%' " - "OR message LIKE '%fpfsi_logHighestEligibleAlternate%' ORDER BY ts").fetchall() + "OR message LIKE '%fpfs_ReportVariantSwitchStart%' ORDER BY ts").fetchall() added = 0 for ts, message in rows: lifecycle = FormatParser.LIFECYCLE.search(message or "") @@ -857,7 +878,7 @@ def log_loop(self): self.store.insert(table, ts=ts, **row) if RAW_KEEP_RE.search(msg): self.store.insert("raw_log", ts=ts, subsystem=entry.get("subsystem"), - category=entry.get("category"), message=msg[:4000]) + category=entry.get("category"), message=redact_titles(msg)[:4000]) cutoff = time.time() - LOG_LOOKBACK - 10 seen = {signature: ts for signature, ts in seen.items() if ts >= cutoff} except (OSError, subprocess.TimeoutExpired, RuntimeError) as e: diff --git a/mac/readonly_gate.py b/mac/readonly_gate.py index c0458bf..b4f95c9 100755 --- a/mac/readonly_gate.py +++ b/mac/readonly_gate.py @@ -49,6 +49,20 @@ PRIVATE_SQL_FUNCTIONS = {"load_extension", "readfile", "writefile"} +# Music logs the track title inside its mediaFormatinfo record. macOS writes <private> there unless a +# log-privacy profile is installed; with one, the title is in the log. It is the only track metadata in +# the records StreamWatch reads, and it never needs to leave the collector. +TITLE_RE = re.compile(r"(mediaFormatinfo ')(.*?)(' , (?=[A-Za-z]+[,:])|$)", re.S) + + +def redact_titles(text): + """Replaces the track title in Music's mediaFormatinfo records with a placeholder.""" + if not isinstance(text, str) or "mediaFormatinfo '" not in text: + return text + return TITLE_RE.sub(lambda m: m.group(1) + "<title>" + m.group(3), text) + + + def _duration_seconds(text): m = re.fullmatch(r"(\d+)([smhd]?)", text or "") if not m: @@ -161,6 +175,7 @@ def run_cmd(argv): text = _safe_audio_profile(text) except (json.JSONDecodeError, TypeError, ValueError): return {"ok": False, "error": "system_profiler returned an unexpected audio report"} + text = redact_titles(text) truncated = len(text) > MAX_OUTPUT return {"ok": out.returncode == 0, "exit_code": out.returncode, "truncated": truncated, "output": text[:MAX_OUTPUT]} @@ -231,6 +246,8 @@ def authorize(action, table, column, database, source): return {"ok": False, "error": f"sqlite: {e}"} finally: conn.close() + # Rows the collector stored before it redacted titles itself still hold them. + rows = [tuple(redact_titles(cell) for cell in row) for row in rows[:MAX_ROWS + 1]] return {"ok": True, "columns": cols, "rows": rows[:MAX_ROWS], "truncated": len(rows) > MAX_ROWS} diff --git a/tests/test_streamwatch.py b/tests/test_streamwatch.py index 9a0a5f5..7bc0857 100644 --- a/tests/test_streamwatch.py +++ b/tests/test_streamwatch.py @@ -35,6 +35,7 @@ def load(name, path): sys.modules["openai"] = fake_openai agent = load("streamwatch_agent", "llm-box/agent.py") +smoke = load("streamwatch_smoke", "llm-box/model_smoke_test.py") model_eval_seed = load("streamwatch_model_eval_seed", "llm-box/model_eval_seed.py") @@ -365,10 +366,13 @@ def test_same_track_restart_is_recorded_only_once_a_second_poll_confirms_it(self class QueuePredictionTests(unittest.TestCase): """Music's own advance notice of a queue item's format, scored against the item's first report.""" - QUEUED = ("<<<< FigStreamPlayer >>>> fpfsi_logHighestEligibleAlternate: [QE Critical][0x7ba4dfe400|P/ZA]: " - "<0x7bb5e55c00|I/DSN.01>: Highest peak bitrate Alternate\n<FigAlternate( 1):[0x7bb66e2f80] " - "[Peak/Avg 1014500/915939] [AudioOnly] [AudioGroup audio-alac-stereo-192000-24] [alac] " - "[StableID 1qog90n7l]>") + QUEUED = ("<<<< FigStreamPlayer >>>> fpfs_ReportCriticalThroughFigLog: fpfs_ReportVariantSwitchStart: " + "[0x7ba4dfe400]: <0x7bb5e55c00> I/DSN.01: (2172): starting switch up from [<FigAlternate( 0):[0x0] " + "[Pathway (null)] [Score 0.000]>] to [<FigAlternate( 1):[0x7bb66e2f80] [Peak/Avg 1014500/915939] " + "[AudioOnly] [AudioGroup audio-alac-stereo-192000-24] [alac] [StableID 1qog90n7l]>]") + # The neighbouring record, as a Mac without a log-privacy profile writes it. + HIGHEST = ("<<<< FigStreamPlayer >>>> fpfsi_logHighestEligibleAlternate: [QE Critical][0x7ba4dfe400|P/ZA]: " + "<0x7bb5e55c00|I/DSN.01>: Highest peak bitrate Alternate <private> ") START = ("<<<< FigStreamPlayer >>>> fpfs_StartTrackPlaying: [QE Critical][0x7ba4dfe400|P/ZA]: " "<0x7bb5e55c00|I/DSN.01>: (2171): playback switches; startTime nan desiredRate is 1.000000 " "rate 0.000000 at currentTime 0.000000 track 1 first image 0 Variant [<FigAlternate( 1):" @@ -388,6 +392,12 @@ def test_parser_records_the_queued_and_the_chosen_variant(self): self.assertEqual(self.predictions(parser, 200.0, self.START), [dict( lifecycle="0x7bb5e55c00|I/DSN.01", stage="prebuffered", sample_rate_hz=48000.0, bit_depth=24)]) self.assertEqual(self.predictions(parser, 218.0, self.REPORT), []) + # The record whose variant is a private field is not read; a change of rendition takes the "to" variant. + self.assertEqual(self.predictions(parser, 11.0, self.HIGHEST), []) + stepped = self.QUEUED.replace( + "from [<FigAlternate( 0):[0x0] [Pathway (null)] [Score 0.000]>]", + "from [<FigAlternate( 2):[0x7bb4c9d400] [AudioOnly] [AudioGroup audio-alac-stereo-48000-24] [alac]>]") + self.assertEqual(self.predictions(parser, 12.0, stepped)[0]["sample_rate_hz"], 192000.0) # A lossy variant, a video item and the variant-less second start line predict nothing. self.assertEqual(self.predictions(parser, 1.0, self.START.replace( "audio-alac-stereo-48000-24] [alac]", "audio-stereo-256] [mp4a.40.2]")), []) @@ -451,6 +461,184 @@ def test_metrics_score_each_stage_against_the_first_report(self): self.assertTrue(gate.run_sql("SELECT lifecycle, stage FROM queue_predictions LIMIT 1")["ok"]) +class TitleRedactionTests(unittest.TestCase): + """Music logs the track title in one record. It must not reach the agent, whatever model it uses.""" + + PLAIN = ("play> cm>> mediaFormatinfo 'Heroes' , audioCapabilities: 0x0 -> 0x4, 0x0 -> 0x4, " + "asbdFormatID = qlac, lossless, asbdNumChannels = 2, asbdSampleRate = 44.1 kHz") + + def test_title_is_replaced_and_the_format_kept(self): + for redact in (collector.redact_titles, gate.redact_titles): + self.assertEqual(redact(self.PLAIN), self.PLAIN.replace("'Heroes'", "'<title>'")) + # Apostrophes and commas inside a title do not end it early. + tricky = self.PLAIN.replace("Heroes", "Rock 'n' , Roll (Isn't It Time)") + self.assertEqual(redact(tricky), self.PLAIN.replace("'Heroes'", "'<title>'")) + enhanced = self.PLAIN.replace("' , audioCapabilities", "' , songEnhanced, audioCapabilities") + self.assertEqual(redact(enhanced), enhanced.replace("'Heroes'", "'<title>'")) + # A record cut off inside the title is redacted to its end. + self.assertEqual(redact("play> cm>> mediaFormatinfo 'A Very Long Ti"), "play> cm>> mediaFormatinfo '<title>") + # Two records joined into one stored value are each redacted. + joined = self.PLAIN + " | " + self.PLAIN.replace("Heroes", "Ashes") + self.assertNotIn("Heroes", redact(joined)) + self.assertNotIn("Ashes", redact(joined)) + self.assertEqual(redact(joined).count("asbdSampleRate"), 2) + # Other records, and values that are not text, pass through. + other = "ACAppleLosslessDecoder.cpp:679 subType = 'alac', inputFormat = 0x0" + self.assertEqual(redact(other), other) + self.assertEqual(redact(None), None) + self.assertEqual(redact(44100.0), 44100.0) + + def test_collector_stores_and_gate_returns_no_title(self): + with tempfile.TemporaryDirectory() as temp: + path = str(pathlib.Path(temp) / "streamwatch.db") + store = collector.Store(path) + parser = collector.FormatParser() + # What the parser keeps for a format event is redacted, and the sample rate is still read. + events = [row for table, row in parser.feed(5.0, self.PLAIN + ", sdBitDepth = 16 bit") if table == "format_events"] + self.assertEqual(events[0]["sample_rate_hz"], 44100.0) + self.assertNotIn("Heroes", events[0]["raw_message"]) + # A row stored before the collector redacted titles is redacted on the way out. + store.insert("raw_log", ts=1.0, subsystem="com.apple.Music", category="ampplay", message=self.PLAIN) + store.conn.close() + with mock.patch.object(gate, "DB_PATH", path): + result = gate.run_sql("SELECT ts, message FROM raw_log") + self.assertTrue(result["ok"], result.get("error")) + self.assertNotIn("Heroes", json.dumps(result, default=str)) + self.assertIn("<title>", result["rows"][0][1]) + self.assertIn("asbdSampleRate = 44.1 kHz", result["rows"][0][1]) + + def test_command_output_is_redacted(self): + completed = subprocess.CompletedProcess([], 0, stdout=self.PLAIN + "\n", stderr="") + with mock.patch.object(gate, "validate_argv", return_value=(True, "")), \ + mock.patch.object(gate, "resolve_binary", return_value="/usr/bin/log"), \ + mock.patch.object(gate.subprocess, "run", return_value=completed): + result = gate.run_cmd(["log", "show"]) + self.assertTrue(result["ok"]) + self.assertNotIn("Heroes", result["output"]) + self.assertIn("<title>", result["output"]) + + +class HostedEndpointTests(unittest.TestCase): + """What the agent lets through when the model is not on this machine or network.""" + + COMPACT = "\n".join([ + "Timestamp Ty Process[PID:TID]", + "2026-11-29 10:00:00.100 Df Music[501:a1] [com.apple.coremedia:] fpfs_StartTrackPlaying <0x1|I/ABC.01>", + " continued detail of the coremedia entry", + "2026-11-29 10:00:00.200 Df Music[501:a2] [com.apple.AppleMediaServices:Account] DSID 1234567890", + " second line of the account entry", + "2026-11-29 10:00:00.300 Df Music[501:a3] [com.apple.coreaudio:HAL] device rate 96000", + "2026-11-29 10:00:00.400 Df Music[501:a4] [com.apple.network:connection] https://example.com/a?token=abc", + "2026-11-29 10:00:00.500 Df Music[501:a5] [com.apple.coremedia:] asset https://example.com/x.m3u8?sig=zzz&u=1 ok", + ]) + + def test_endpoint_location(self): + for url in ("http://127.0.0.1:11434/v1", "http://localhost:1234/v1", "http://192.168.0.20:8080/v1", + "http://10.0.0.4/v1", "http://[::1]:8080/v1", "http://studio.local:8080/v1", "http://llm-box/v1", + "http://100.100.4.2/v1"): + self.assertTrue(agent.endpoint_is_local(url), url) + for url in ("https://api.anthropic.com/v1", "https://api.openai.com/v1", "https://8.8.8.8/v1", "", "nonsense"): + self.assertFalse(agent.endpoint_is_local(url), url) + + def test_scope_follows_endpoint_unless_set(self): + with mock.patch.object(agent, "LOG_SCOPE", ""), mock.patch.object(agent, "LLM_BASE_URL", "https://api.openai.com/v1"): + self.assertEqual(agent.log_scope(), "playback") + with mock.patch.object(agent, "LOG_SCOPE", ""), mock.patch.object(agent, "LLM_BASE_URL", "http://192.168.0.20:8080/v1"): + self.assertEqual(agent.log_scope(), "all") + with mock.patch.object(agent, "LOG_SCOPE", "playback"), mock.patch.object(agent, "LLM_BASE_URL", "http://127.0.0.1/v1"): + self.assertEqual(agent.log_scope(), "playback") + with mock.patch.object(agent, "LOG_SCOPE", "everything"), mock.patch.object(agent, "LLM_BASE_URL", "https://api.openai.com/v1"): + self.assertEqual(agent.log_scope(), "playback") + + def test_playback_scope_keeps_only_playback_and_audio_entries(self): + out = agent.scope_log_output(self.COMPACT) + self.assertIn("fpfs_StartTrackPlaying", out) + self.assertIn("continued detail of the coremedia entry", out) + self.assertIn("device rate 96000", out) + self.assertNotIn("DSID", out) + self.assertNotIn("second line of the account entry", out) + self.assertNotIn("com.apple.network", out) + self.assertNotIn("Timestamp", out) + self.assertIn("https://example.com/x.m3u8?<query> ok", out) + self.assertNotIn("sig=zzz", out) + self.assertIn("[2 entries from other subsystems withheld", out) + + def test_playback_scope_reads_ndjson_and_withholds_what_it_cannot_parse(self): + lines = [json.dumps({"subsystem": "com.apple.coremedia", "eventMessage": "keep me"}), + json.dumps({"subsystem": "com.apple.amp.iTunesCloud", "eventMessage": "drop me"}), + json.dumps({"eventMessage": "no subsystem"})] + out = agent.scope_log_output("\n".join(lines)) + self.assertIn("keep me", out) + self.assertNotIn("drop me", out) + self.assertNotIn("no subsystem", out) + pretty = '[{\n "subsystem" : "com.apple.coremedia",\n "eventMessage" : "pretty"\n}]' + self.assertNotIn("pretty", agent.scope_log_output(pretty)) + self.assertIn("withheld", agent.scope_log_output(pretty)) + + def test_gate_results_are_sanitized_before_the_model_sees_them(self): + title = "mediaFormatinfo 'Secret Song' , channelCount: 2" + rows = agent.sanitize_gate_result({"op": "sql"}, {"ok": True, "columns": ["m"], "rows": [[title, 3]]}, "all") + self.assertEqual(rows["rows"], [["mediaFormatinfo '<title>' , channelCount: 2", 3]]) + request = {"op": "cmd", "argv": ["log", "show", "--last", "1m"]} + everything = agent.sanitize_gate_result(request, {"ok": True, "output": self.COMPACT + "\n" + title}, "all") + self.assertIn("DSID", everything["output"]) + self.assertNotIn("Secret Song", everything["output"]) + scoped = agent.sanitize_gate_result(request, {"ok": True, "output": self.COMPACT}, "playback") + self.assertNotIn("DSID", scoped["output"]) + other = agent.sanitize_gate_result({"op": "cmd", "argv": ["sw_vers"]}, {"ok": True, "output": "macOS 27"}, "playback") + self.assertEqual(other["output"], "macOS 27") + self.assertEqual(agent.sanitize_gate_result(request, {"ok": False, "error": "x"}, "playback"), {"ok": False, "error": "x"}) + + +class SmokeTestTests(unittest.TestCase): + """The endpoint check asks a hosted model the way it will accept.""" + + REPLY = {"choices": [{"finish_reason": "tool_calls", "message": {"tool_calls": [{"function": { + "name": "finish_cycle", "arguments": json.dumps({"summary": "ok", "exhausted": False})}}]}}], + "usage": {"prompt_tokens": 400, "completion_tokens": 60}} + + def run_against(self, base_url, model): + calls = [] + + def fake(url, *, body=None, api_key="", timeout=30): + calls.append((url, body)) + return {"data": [{"id": model}]} if body is None else self.REPLY + + with mock.patch.object(smoke, "request_json", fake), mock.patch("builtins.print"): + smoke.run(base_url, model, "key", 30, True) + return calls[1][1] + + def test_local_and_hosted_requests_differ(self): + local = self.run_against("http://192.168.0.20:8080/v1", "local-model") + self.assertEqual(local["temperature"], 0.2) + self.assertEqual(local["chat_template_kwargs"], {"enable_thinking": False}) + hosted = self.run_against("https://api.anthropic.com/v1/", "claude-haiku-5-5") + self.assertNotIn("temperature", hosted) + self.assertNotIn("chat_template_kwargs", hosted) + self.assertEqual(hosted["max_tokens"], 2048) + + def test_the_key_goes_in_the_header_each_route_expects(self): + seen = [] + + class Reply: + def __enter__(self): return self + def __exit__(self, *args): return False + def read(self): return b"{}" + + def opener(request, timeout=None): + seen.append({k.lower(): v for k, v in request.header_items()}) + return Reply() + + with mock.patch.object(smoke.urllib.request, "urlopen", opener): + smoke.request_json("https://api.anthropic.com/v1/models", api_key="k") + smoke.request_json("https://api.anthropic.com/v1/chat/completions", body={}, api_key="k") + smoke.request_json("https://api.openai.com/v1/models", api_key="k") + self.assertEqual(seen[0].get("x-api-key"), "k") + self.assertNotIn("authorization", seen[0]) + self.assertEqual(seen[1].get("authorization"), "Bearer k") + self.assertEqual(seen[2].get("authorization"), "Bearer k") + + class GateTests(unittest.TestCase): def test_installer_replaces_existing_unrestricted_key(self): with tempfile.TemporaryDirectory() as temp: @@ -667,6 +855,146 @@ def test_no_think_sends_openai_compatible_template_parameter(self): False, ) + @staticmethod + def refusal(status, message): + error = Exception(message) + error.status_code = status + return error + + def test_agent_stops_sending_an_option_a_model_server_refuses(self): + client = mock.Mock() + client.chat.completions.create.side_effect = [ + self.refusal(400, "Unsupported parameter: 'max_tokens' is not supported with this model. " + "Use 'max_completion_tokens' instead."), + self.refusal(400, "Unrecognized request argument supplied: chat_template_kwargs"), + self.refusal(400, "Unsupported value: 'temperature' does not support 0.4 with this model."), + "completion", + ] + instance = agent.Agent.__new__(agent.Agent) + instance.llm = client + with mock.patch.object(agent, "NO_THINK", True), mock.patch.object(agent.time, "sleep") as sleep: + self.assertEqual(instance.chat([{"role": "user", "content": "test"}], []), "completion") + # Each refusal was answered by changing the request, not by waiting. + sleep.assert_not_called() + request = client.chat.completions.create.call_args.kwargs + self.assertNotIn("max_tokens", request) + self.assertEqual(request["max_completion_tokens"], agent.LLM_MAX_TOKENS) + self.assertNotIn("extra_body", request) + self.assertNotIn("temperature", request) + self.assertEqual(request["tool_choice"], "auto") + # The adjustment is remembered for the next call. + client.chat.completions.create.side_effect = ["again"] + self.assertEqual(instance.chat([], []), "again") + self.assertIn("max_completion_tokens", client.chat.completions.create.call_args.kwargs) + + def test_a_hosted_model_is_sent_no_temperature_and_its_usage_is_counted(self): + instance = agent.Agent.__new__(agent.Agent) + with mock.patch.object(agent, "LLM_BASE_URL", "https://api.anthropic.com/v1"): + self.assertNotIn("temperature", instance.chat_request([], [])) + local = agent.Agent.__new__(agent.Agent) + with mock.patch.object(agent, "LLM_BASE_URL", "http://192.168.0.20:8080/v1"): + self.assertEqual(local.chat_request([], [])["temperature"], 0.4) + for setting, expected in (("0.7", 0.7), ("none", None)): + chosen = agent.Agent.__new__(agent.Agent) + with mock.patch.object(agent, "LLM_TEMPERATURE", setting), \ + mock.patch.object(agent, "LLM_BASE_URL", "https://api.anthropic.com/v1"): + self.assertEqual(chosen.chat_request([], []).get("temperature"), expected) + + counted = agent.Agent.__new__(agent.Agent) + counted.cycle_tokens = [0, 0] + counted.llm = mock.Mock() + counted.llm.chat.completions.create.side_effect = [ + types.SimpleNamespace(usage=types.SimpleNamespace(prompt_tokens=1200, completion_tokens=300)), + types.SimpleNamespace(usage=types.SimpleNamespace(prompt_tokens=1500, completion_tokens=None)), + types.SimpleNamespace(usage=None), + "a server that reports no usage", + ] + for _ in range(4): + counted.chat([], []) + self.assertEqual(counted.cycle_tokens, [2700, 300]) + + def test_a_login_supplies_tokens_and_is_renewed(self): + tokens = iter(["token-1", "token-2", "token-3"]) + built = [] + + def fake_openai(**kwargs): + built.append(kwargs) + client = mock.Mock() + client.chat.completions.create.side_effect = lambda **request: f"answered with {kwargs['api_key']}" + return client + + with mock.patch.object(agent, "LLM_AUTH", "anthropic-login"), \ + mock.patch.object(agent, "LLM_BASE_URL", "https://api.anthropic.com/v1"), \ + mock.patch.object(agent, "login_token", lambda: next(tokens)), \ + mock.patch.object(agent, "OpenAI", fake_openai): + instance = agent.Agent.__new__(agent.Agent) + instance.connect() + self.assertEqual(built[0]["api_key"], "token-1") + self.assertEqual(built[0]["default_headers"], {"anthropic-beta": "oauth-2025-04-20"}) + self.assertEqual(instance.chat([], []), "answered with token-1") + # An old token is replaced before the next request. + instance.llm_connected -= agent.LOGIN_TOKEN_MAX_AGE + 1 + self.assertEqual(instance.chat([], []), "answered with token-2") + # A token refused in between renewals is replaced once, and the request repeated. + instance.llm.chat.completions.create.side_effect = self.refusal(401, "expired") + self.assertEqual(instance.chat([], []), "answered with token-3") + self.assertEqual(len(built), 3) + + def test_the_login_token_comes_from_the_cli_and_never_from_the_environment(self): + ran = {} + + def fake_run(argv, **kwargs): + ran["argv"], ran["env"] = argv, kwargs["env"] + return types.SimpleNamespace(returncode=0, stdout="sk-ant-oat01-example\n", stderr="") + + with mock.patch.object(agent, "anthropic_cli", lambda: "/opt/homebrew/bin/ant"), \ + mock.patch.object(agent.subprocess, "run", fake_run), \ + mock.patch.dict(agent.os.environ, {"ANTHROPIC_API_KEY": "stale", "ANTHROPIC_AUTH_TOKEN": "stale"}): + self.assertEqual(agent.login_token(), "sk-ant-oat01-example") + self.assertEqual(ran["argv"], ["/opt/homebrew/bin/ant", "auth", "print-credentials", "--access-token"]) + self.assertNotIn("ANTHROPIC_API_KEY", ran["env"]) + self.assertNotIn("ANTHROPIC_AUTH_TOKEN", ran["env"]) + for result in (types.SimpleNamespace(returncode=1, stdout="", stderr="not logged in"), + types.SimpleNamespace(returncode=0, stdout='{"access_token": "x", "more": 1}', stderr="")): + with mock.patch.object(agent, "anthropic_cli", lambda: "/opt/homebrew/bin/ant"), \ + mock.patch.object(agent.subprocess, "run", lambda *a, **k: result): + with self.assertRaises(agent.LLMRefused): + agent.login_token() + with mock.patch.object(agent, "anthropic_cli", lambda: None): + with self.assertRaises(agent.LLMRefused): + agent.login_token() + + def test_an_account_without_credit_stops_the_agent_instead_of_retrying(self): + instance = agent.Agent.__new__(agent.Agent) + instance.llm = mock.Mock() + instance.llm.chat.completions.create.side_effect = self.refusal( + 400, "Your credit balance is too low to access the Anthropic API.") + with mock.patch.object(agent.time, "sleep") as sleep: + with self.assertRaises(agent.LLMRefused) as raised: + instance.chat([], []) + sleep.assert_not_called() + self.assertIn("no credit", str(raised.exception)) + self.assertEqual(instance.llm.chat.completions.create.call_count, 1) + self.assertIsNotNone(agent.account_refusal(402, "payment required")) + self.assertIsNotNone(agent.account_refusal(429, "insufficient_quota")) + self.assertIsNone(agent.account_refusal(429, "rate limit exceeded")) + self.assertIsNone(agent.account_refusal(400, "model not found")) + + def test_agent_does_not_retry_a_refused_key_or_adapt_to_an_unrelated_refusal(self): + instance = agent.Agent.__new__(agent.Agent) + instance.llm = mock.Mock() + instance.llm.chat.completions.create.side_effect = self.refusal(401, "Incorrect API key provided") + with mock.patch.object(agent.time, "sleep") as sleep: + with self.assertRaises(agent.LLMRefused): + instance.chat([], []) + sleep.assert_not_called() + self.assertEqual(instance.llm.chat.completions.create.call_count, 1) + # A refusal that names nothing this agent sends is an ordinary failure: wait and retry. + instance.llm.chat.completions.create.side_effect = [self.refusal(400, "model not found"), "completion"] + with mock.patch.object(agent.time, "sleep") as sleep: + self.assertEqual(instance.chat([], []), "completion") + sleep.assert_called_once() + def test_public_queries_reject_private_identifiers_and_local_paths(self): self.assertIsNotNone(agent.public_query_issue('"/Users/listener/Library/test"')) self.assertIsNotNone(agent.public_query_issue("device 00112233-4455-6677-8899-aabbccddeeff"))