Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions app/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,13 @@ LLM_JUDGE_PROVIDER=
LLM_JUDGE_PROTOCOL=
# The model of the LLM judgement, as its provider names it (on OpenRouter, vendor/model). It is asked the same questions as Decision and answers them as JSON; its numbers are what it states, so a choice or a score carries no confidence.
LLM_JUDGE_MODEL=
# Additions to the OpenRouter provider, as a JSON object without the key: endpoints of protocols the preset does not list, {"endpoints": {"<protocol>": "/path" or "https://full/url"}}. In the environment, a partial object merged over this one.
# Unsupported overrides for OpenRouter. Use a Custom provider to configure endpoints.
OPENROUTER=
# Additions to the OpenAI provider, as a JSON object without the key: endpoints of protocols the preset does not list, {"endpoints": {"<protocol>": "/path" or "https://full/url"}}. In the environment, a partial object merged over this one.
# Unsupported overrides for OpenAI. Use a Custom provider to configure endpoints.
OPENAI=
# Additions to the Anthropic provider, as a JSON object without the key: endpoints of protocols the preset does not list, {"endpoints": {"<protocol>": "/path" or "https://full/url"}}. In the environment, a partial object merged over this one.
# Unsupported overrides for Anthropic. Use a Custom provider to configure endpoints.
ANTHROPIC=
# Additions to the TypeSafe provider, as a JSON object without the key: endpoints of protocols the preset does not list, {"endpoints": {"<protocol>": "/path" or "https://full/url"}}. In the environment, a partial object merged over this one.
# Unsupported overrides for TypeSafe. Use a Custom provider to configure endpoints.
TYPESAFE=

# --- Run hosts ---
Expand Down
32 changes: 11 additions & 21 deletions app/nullius/providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,8 @@
"decisions": {"label": "OpenRouter Decisions", "path": "/decisions", "auth": "authorization"},
"openai-decisions": {"label": "OpenAI Decisions", "path": "/decisions", "auth": "authorization"},
}
# A preset is a provider record whose name, base, key and known endpoints are fixed here. The user adds
# only endpoints of other protocols, in the setting ``setting`` (``settings.is_record``); its key is
# the secret setting ``key``. Its ``endpoints`` are also the protocols it serves.
# A preset has fixed name, base, key setting and endpoints. Custom providers configure their own
# endpoints. A preset's endpoints are also the protocols it serves.
PRESETS = {
"openrouter": {"name": "OpenRouter", "base": "https://openrouter.ai/api/v1", "key": "OPENROUTER_API_KEY",
"endpoints": {"chat": "/chat/completions", "responses": "/responses", "systemone": "/systemone",
Expand Down Expand Up @@ -72,14 +71,12 @@ def key_setting(choice: str) -> str:
return PRESETS[p]["key"] if p in PRESETS else endpoint_vars(e)[1]


def _entry_problem(entry, host: str = "") -> Optional[str]:
def _entry_problem(entry) -> Optional[str]:
"""Why ``entry`` cannot be an endpoint: a path starting with one slash, without a ``..`` segment, or a
full URL that passes the checks a base gets; on ``host`` only, when one is given (a preset's own)."""
full URL that passes the checks a base gets."""
if not isinstance(entry, str):
return "a path or a URL"
if entry.startswith(("http://", "https://")):
if host and urllib.parse.urlsplit(entry).hostname != host:
return f"a path, or a URL on {host}: the preset's key is sent there"
return settings.endpoint_url_problem(entry)
if not entry.startswith("/") or entry.startswith("//") or any(c.isspace() or ord(c) < 32 for c in entry):
return "a path that starts with / or an http(s) URL"
Expand All @@ -91,17 +88,15 @@ def _entry_problem(entry, host: str = "") -> Optional[str]:
def record_problem(name: str, value: str) -> Optional[str]:
"""Why ``value`` cannot be the record setting ``name``, or None. A JSON object of ``FIELDS``: a name, a
base the checks of an endpoint's URL pass, the key's setting name (only its own: never a key), and
endpoints by protocol, each a path, a full URL or null. A preset's fields and known endpoints are fixed;
a full URL it adds is on its own host, the one its key is for."""
endpoints by protocol, each a path, a full URL or null. Presets accept no overrides."""
rec = settings.json_object(value)
if rec is None:
return 'a JSON object, such as {"base": "https://…/v1"}'
preset = next((p for p in PRESETS if p.upper() == name), "")
if set(rec) - set(FIELDS):
return "an object of " + ", ".join(FIELDS)
fixed = [k for k in ("name", "base", "key") if preset and k in rec]
if fixed:
return f"a record without {', '.join(fixed)}: they are fixed for {PRESETS[preset]['name']}"
if preset and rec:
return f"a custom provider instead: endpoints and fields are fixed for {PRESETS[preset]['name']}"
if rec.get("name") is not None and (not isinstance(rec["name"], str) or not 0 < len(rec["name"]) <= 400
or any(ord(c) < 32 for c in rec["name"])):
return "a record whose name is one line of 400 characters at most"
Expand All @@ -117,9 +112,7 @@ def record_problem(name: str, value: str) -> Optional[str]:
for proto, entry in ends.items():
if proto not in PROTOCOLS:
return f"a record whose endpoints are some of {', '.join(PROTOCOLS)}"
if preset and proto in PRESETS[preset]["endpoints"]:
return f"a record without the {proto} endpoint: it is fixed for {PRESETS[preset]['name']}"
why = entry is not None and _entry_problem(entry, urllib.parse.urlsplit(PRESETS[preset]["base"]).hostname if preset else "")
why = entry is not None and _entry_problem(entry)
if why:
return f"a record whose {proto} endpoint is {why}"
return None
Expand All @@ -134,8 +127,8 @@ def join(base: str, entry: str) -> str:


def record(choice: str, env=None) -> dict:
"""A provider's record, the three layers merged field by field (the later wins): the preset in code,
the file's and then the environment's record setting (``settings.load`` merged those two). A custom
"""A preset's fixed record, or a custom record from file and environment (``settings.load`` merges
those two field by field, the environment winning). A custom
provider reads its old settings where its record says nothing (a null says: none): MODEL_<ID>_NAME as ``name``,
MODEL_<ID>_API_URL (MODEL_API_URL, unnamed) as ``base``; ``ignored`` names an old setting the record
overrides. ``{id, name, base, key, endpoints, preset, ignored}``, where ``key`` is a setting name only."""
Expand All @@ -145,10 +138,7 @@ def record(choice: str, env=None) -> dict:
own = settings.json_object(env.get(setting_of(choice))) if setting_of(choice) else None
if own is not None and record_problem(setting_of(choice), json.dumps(own)):
own = None # a record that does not validate is no record
rec = settings.merge_patch({k: v for k, v in (preset or {}).items()}, own or {})
if preset:
rec.update({k: preset[k] for k in ("name", "base", "key")},
endpoints={**(rec.get("endpoints") or {}), **preset["endpoints"]})
rec = dict(preset) if preset else dict(own or {})
ignored = []
if not preset:
old_name, old_url = (f"MODEL_{e}_NAME" if e else ""), endpoint_vars(e)[0]
Expand Down
3 changes: 1 addition & 2 deletions app/nullius/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,7 @@ def validate(self, value: str) -> Optional[str]:
Variable("LLM_JUDGE_PROVIDER", GROUPS[0], "The provider of the LLM judgement, the second judgement beside Decision: openrouter, openai, anthropic, custom (the endpoint at MODEL_API_URL) or custom:<ID> (a custom provider), asked with that provider's own key and base from the model providers above. local and local:<ID> are read as custom. Unset: the first of them that is set, Anthropic last.", "llmprovider"),
Variable("LLM_JUDGE_PROTOCOL", GROUPS[0], "The protocol the LLM judge is asked in, on a provider that serves both: chat (OpenAI Chat Completions) or messages (Anthropic Messages). Unset, or one the provider does not serve: the first the provider serves, chat before messages.", "llmprotocol"),
Variable("LLM_JUDGE_MODEL", GROUPS[0], "The model of the LLM judgement, as its provider names it (on OpenRouter, vendor/model). It is asked the same questions as Decision and answers them as JSON; its numbers are what it states, so a choice or a score carries no confidence.", "model"),
*(Variable(name, GROUPS[0], f"Additions to the {title} provider, as a JSON object without the key: endpoints of protocols the preset does not list, "
'{"endpoints": {"<protocol>": "/path" or "https://full/url"}}. In the environment, a partial object merged over this one.', "provider")
*(Variable(name, GROUPS[0], f"Unsupported overrides for {title}. Use a Custom provider to configure endpoints.", "provider")
for name, title in (("OPENROUTER", "OpenRouter"), ("OPENAI", "OpenAI"), ("ANTHROPIC", "Anthropic"), ("TYPESAFE", "TypeSafe"))),
Variable("AGENT_KEYS", GROUPS[2], "The names of the agent keys this file holds, comma-separated: the keys an agent needs of its own vendor, beside the model's (Cursor's CLI agent a CURSOR_API_KEY, Copilot's a GH_TOKEN). Each is a line of its own in this file. A Harbor run gets every one of them in its environment - over stdin to a host - and a Nullius standard run's never; none is ever written into a recipe or a log.", "envnames"),
Variable("HOSTS", GROUPS[1], "Machines a recipe can run on, over ssh: an alias from ~/.ssh/config, or user@host[:port][:/path/to/key]. Only the name is stored; keys stay where they are.", "hosts", "user@host[:port][:/path/to/key]"),
Expand Down
8 changes: 7 additions & 1 deletion app/tests/test_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ def test_a_run_on_a_named_endpoint_gets_its_url_and_key_alone(self):
that one's URL and key, never the default's or another endpoint's; a run
on one that is gone fails before it starts, and is never sent to another."""
held = {"MODEL_API_URL": "http://default/v1", "MODEL_API_KEY": "sk-held-default",
"MODEL_GPU_NAME": "GPU box", "MODEL_GPU_API_URL": "http://gpu/v1", "MODEL_GPU_API_KEY": "sk-held-gpu",
"MODEL_GPU_NAME": "GPU box", "MODEL_GPU_API_URL": "http://old-gpu/v1", "MODEL_GPU_API_KEY": "sk-held-gpu",
"MODEL_GPU": json.dumps({"base": "http://gpu/v1", "endpoints": {"messages": "/messages"}}),
"MODEL_LAPTOP_API_URL": "http://laptop/v1", "MODEL_LAPTOP_API_KEY": "sk-held-laptop"}
url_var, key_var = providers.endpoint_vars("GPU")
with mock.patch.dict(os.environ, held):
Expand All @@ -112,6 +113,11 @@ def test_a_run_on_a_named_endpoint_gets_its_url_and_key_alone(self):
env = dict(l.split("=", 1) for l in (self.tmp / "gpu" / "run-run.log").read_text().splitlines() if "=" in l)
self.assertEqual({k: v for k, v in env.items() if v.startswith("sk-held-")}, {n: "sk-held-gpu" for n in execution.KEY_NAMES})
self.assertEqual({k: v for k, v in env.items() if v.startswith("http://")}, {n: "http://gpu/v1" for n in execution.URL_NAMES})
from nullius.standard import cli
from nullius.standard.runner import run
handed = cli.run_env("custom", env)
self.assertEqual(run.provider_endpoint("custom", handed), ("http://gpu/v1", "sk-held-gpu"))
self.assertEqual(run.key_header("custom", {"model": {"apis": ["messages"]}}, handed), "x-api-key")
self.assertEqual((gone.state, gone.step), ("failed", "credentials"))
self.assertIn("MODEL_GONE_API_URL is not set in Settings", gone.error)

Expand Down
8 changes: 4 additions & 4 deletions app/tests/test_judge_decisions.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,11 @@ def test_a_chosen_protocol_wins_where_the_provider_serves_it_else_the_automatic_
self.assertEqual(got(dict(router, DECISION_PROTOCOL="openai-decisions")), ("systemone", "https://openrouter.ai/api/v1/systemone")) # not served: automatic
self.assertEqual(client.decision_judge_providers(dict(router, DECISION_PROTOCOL="decisions"))["openrouter"]["protocol"], "decisions")
self.assertEqual(client.decision_judge_providers(router)["openrouter"]["listed"], ["systemone", "decisions"])
both = {"ANTHROPIC_API_KEY": "k", "ANTHROPIC": '{"endpoints": {"chat": "/chat/completions"}}', "LLM_JUDGE_PROVIDER": "anthropic", "LLM_JUDGE_MODEL": "m"}
both = {"MODEL_GW_API_KEY": "k", "MODEL_GW": '{"base": "https://gw.example/v1", "endpoints": {"chat": "/custom/chat", "messages": "/custom/messages"}}', "LLM_JUDGE_PROVIDER": "custom:GW", "LLM_JUDGE_MODEL": "m"}
llm = lambda env: (client.llm_judge(env).protocol, client.llm_judge(env).url)
self.assertEqual(llm(both), ("chat", "https://api.anthropic.com/v1/chat/completions")) # unset: chat before messages
self.assertEqual(llm(dict(both, LLM_JUDGE_PROTOCOL="messages")), ("messages", "https://api.anthropic.com/v1/messages"))
self.assertEqual(client.llm_providers(both)["anthropic"]["listed"], ["chat", "messages"])
self.assertEqual(llm(both), ("chat", "https://gw.example/v1/custom/chat")) # unset: chat before messages
self.assertEqual(llm(dict(both, LLM_JUDGE_PROTOCOL="messages")), ("messages", "https://gw.example/v1/custom/messages"))
self.assertEqual(client.llm_providers(both)["custom:GW"]["listed"], ["chat", "messages"])
self.assertEqual(llm({"OPENROUTER_API_KEY": "k", "LLM_JUDGE_MODEL": "m", "LLM_JUDGE_PROTOCOL": "messages"}),
("chat", "https://openrouter.ai/api/v1/chat/completions")) # not served: automatic
for name, spoken in (("LLM_JUDGE_PROTOCOL", client.LLM_PROTOCOLS), ("DECISION_PROTOCOL", client.DECISION_PROTOCOLS)):
Expand Down
5 changes: 4 additions & 1 deletion app/tests/test_provider_pins.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,12 @@ def test_openrouter_protocol_checks_and_serving_pins_both_apply(self):
with self.assertRaisesRegex(run.Refused, "does not serve"):
run.Run(self.bench, self.agent, **options)
env["OPENROUTER"] = json.dumps({"endpoints": {"messages": "/messages"}})
with self.assertRaisesRegex(run.Refused, "does not serve"):
run.Run(self.bench, self.agent, **options)
self.agent["model"]["apis"] = ["chat"]
started = run.Run(self.bench, self.agent, **options)
self.assertEqual((started.base, started.key_header, started.serving),
(providers.PRESETS["openrouter"]["base"], "x-api-key", {"m": ["prov-a"]}))
(providers.PRESETS["openrouter"]["base"], "authorization", {"m": ["prov-a"]}))
with patch.dict(os.environ, env):
compiled = recipe.compile(recipes.a_recipe(model="m", served_by={"model": ["prov-a"]}), self.defs)
self.assertEqual(compiled["errors"], [])
Expand Down
46 changes: 28 additions & 18 deletions app/tests/test_provider_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,24 +20,20 @@


class Records(unittest.TestCase):
def test_a_preset_is_its_fixed_fields_and_the_user_adds_only_other_protocols(self):
env = {"OPENROUTER": json.dumps({"endpoints": {"messages": "/messages"}})}
rec = providers.record("openrouter", env)
self.assertEqual((rec["name"], rec["base"], rec["key"]), ("OpenRouter", "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY"))
self.assertEqual(providers.url(rec, "messages"), "https://openrouter.ai/api/v1/messages")
self.assertEqual(providers.url(rec, "decisions"), "https://openrouter.ai/api/alpha/decisions") # outside its base: a full URL
for fixed in ({"base": "https://proxy/v1"}, {"name": "X"}, {"key": "OTHER_API_KEY"}, {"endpoints": {"chat": "/x"}}):
self.assertIn("fixed", providers.record_problem("OPENROUTER", json.dumps(fixed)), fixed)
self.assertEqual(providers.record("openrouter", {"OPENROUTER": json.dumps(fixed)})["base"], "https://openrouter.ai/api/v1")

def test_a_preset_adds_a_full_url_only_on_its_own_host(self):
for name, proto, bad in (("TYPESAFE", "decisions", "https://evil.example/d"), ("OPENROUTER", "messages", "https://evil.example/m"),
("OPENAI", "messages", "https://api.openai.com.evil.example/m")):
why = providers.record_problem(name, json.dumps({"endpoints": {proto: bad}}))
self.assertIn("the preset's key is sent there", why or "", name)
self.assertNotIn("evil", providers.url(providers.record(name.lower(), {name: json.dumps({"endpoints": {proto: bad}})}), proto))
self.assertIsNone(providers.record_problem("OPENROUTER", json.dumps({"endpoints": {"messages": "https://openrouter.ai/api/v1/messages"}})))
self.assertIsNone(providers.record_problem("TYPESAFE", json.dumps({"endpoints": {"decisions": "/decisions"}})))
def test_presets_ignore_and_reject_overrides_for_every_protocol(self):
for provider, preset in providers.PRESETS.items():
for proto in providers.PROTOCOLS:
for entry in ("/other", "https://other.example/path", None):
with self.subTest(provider=provider, protocol=proto, entry=entry):
value = json.dumps({"endpoints": {proto: entry}})
self.assertIn("custom provider", providers.record_problem(provider.upper(), value))
rec = providers.record(provider, {provider.upper(): value})
self.assertEqual(rec["endpoints"], preset["endpoints"])
self.assertEqual(providers.serves(rec, proto), proto in preset["endpoints"])
for fixed in ({"base": "https://proxy/v1"}, {"name": "X"}, {"key": "OTHER_API_KEY"}):
self.assertIn("fixed", providers.record_problem("OPENROUTER", json.dumps(fixed)))
self.assertEqual(providers.record("openrouter", {"OPENROUTER": json.dumps(fixed)})["base"],
providers.PRESETS["openrouter"]["base"])

def test_a_custom_record_merges_per_protocol_and_null_removes(self):
file = {"name": "Gateway", "base": "https://gw.example/v1", "endpoints": {"chat": "/chat/completions", "decisions": "/alpha/decisions"}}
Expand Down Expand Up @@ -159,6 +155,20 @@ def setUp(self):
saved = kept.copy()
self.addCleanup(lambda k=kept, s=saved: (k.clear(), k.update(s)))

def test_saved_preset_overrides_are_reported_and_do_not_change_protocols(self):
for provider, preset in providers.PRESETS.items():
name = provider.upper()
with self.subTest(provider=provider), patch.dict(os.environ):
os.environ.pop(name, None)
value = json.dumps({"endpoints": {p: "/override" for p in providers.PROTOCOLS}})
Path(self.file).write_text(json.dumps({name: value}))
settings.load(self.file)
self.assertEqual(providers.record(provider)["endpoints"], preset["endpoints"])
state = settings.state(settings.BY_NAME[name], settings.in_file(self.file))
self.assertIn("custom provider", state["problem"])
with self.assertRaises(ValueError):
settings.save(self.file, name, value)

def test_the_environment_sets_only_its_fields(self):
Path(self.file).write_text(json.dumps({"MODEL_GW": json.dumps({"name": "Gateway", "base": "https://gw.example/v1",
"endpoints": {"chat": "/c", "decisions": "/d"}})}))
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading