Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Give official templates real revisions
Simon Flack108dfdf09a78
diff --git a/core/switch_core/official_templates/__init__.py b/core/switch_core/official_templates/__init__.pyindex a7b5a0249..f1d7a316f 100644--- a/core/switch_core/official_templates/__init__.py+++ b/core/switch_core/official_templates/__init__.py@@ -16,10 +16,19 @@ Switch Console runs itself), and ``AGENT.md``, the agent's instructions,written into the document's agent where it has none of its own. The Switchexpert's files are copies of ``switch-expert/`` at the repository root, keptequal by a test.++Each also has ``revisions.json``: every revision of it released, numbered+from 1, with a fingerprint of what each one served and set on its agents.+The last is the revision this release serves (its ``version``), and agents+created from an older one are brought up to it when the server starts+(``template_updates``). Changing a template means adding a revision, which+``python -m switch_core.official_templates.revisions record <slug>`` does; a+test fails while the files and the last revision disagree."""from __future__ import annotations+import jsonfrom dataclasses import dataclassfrom functools import cachefrom pathlib import Path@@ -29,6 +38,9 @@ import yamlOFFICIAL_PREFIX = "official:"+# Each template's revisions, next to its files: see ``revisions.py``.+REVISIONS_FILE = "revisions.json"+_HERE = Path(__file__).parent@@ -119,7 +131,13 @@ def _with_instructions(document: str, instructions: str) -> str:@cachedef _document(slug: str, agent_management: bool) -> str:- folder = _HERE / slug+ return document_in(_HERE / slug, agent_management)+++def document_in(folder: Path, agent_management: bool) -> str:+ """The document a template's folder serves: its ``template.yaml`` (or,+ without agent management, its ``template.console.yaml`` where it has+ one), with ``AGENT.md`` written in as its agents' instructions."""console = folder / "template.console.yaml"path = (folder / "template.yaml"@@ -146,12 +164,48 @@ def official_templates(description=shipped.description,kind=shipped.kind,content=_document(shipped.slug, agent_management),+ version=current_revision(shipped.slug),)for shipped in _SHIPPEDif (shipped.served == "buddy") == (agent_management and switch_buddy)]+@cache+def _revisions(slug: str) -> tuple[dict[str, Any], ...]:+ path = _HERE / slug / REVISIONS_FILE+ data = json.loads(path.read_text(encoding="utf-8"))+ revisions = tuple(data["revisions"])+ numbers = [entry["revision"] for entry in revisions]+ if numbers != list(range(1, len(numbers) + 1)):+ raise RuntimeError(+ f"{path} must list revisions 1, 2, 3… in order; it lists {numbers}"+ )+ return revisions+++def current_revision(slug: str) -> int:+ """The revision of an official template this release serves."""+ return int(_revisions(slug)[-1]["revision"])+++def slug_of(template_id: str) -> str:+ return template_id.removeprefix(OFFICIAL_PREFIX)+++def released_agent_fingerprints(+ slug: str,+) -> list[tuple[int, dict[str, dict[str, str]]]]:+ """Every revision of an official template ever released, newest first,+ with the fingerprints of what it set on each agent it creates, by key:+ how an agent created before installs were recorded is told apart from+ one somebody has changed."""+ return [+ (int(entry["revision"]), dict(entry["agents"]))+ for entry in reversed(_revisions(slug))+ ]++def is_official(template_id: str) -> bool:return template_id.startswith(OFFICIAL_PREFIX)diff --git a/core/switch_core/official_templates/revisions.py b/core/switch_core/official_templates/revisions.pynew file mode 100644index 000000000..280aca83a--- /dev/null+++ b/core/switch_core/official_templates/revisions.py@@ -0,0 +1,115 @@+"""The revisions of the templates that come with Switch.++``revisions.json`` beside each template's files lists every revision of it+released, oldest first. Each entry is a fingerprint of the documents the+template served at that revision (``document``) and of every value it set on+each agent it creates, by key (``agents``). Agents created before installs+were recorded are matched against the ``agents`` fingerprints of every+revision, so an old buddy nobody changed is recognised as the revision it+came from.++When a template's files change, record a revision::++ python -m switch_core.official_templates.revisions record switch-buddy++and ``check`` (or the test that runs it) says whether every template's last+revision is what its files serve now.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path+from typing import Any++import yaml++from switch_core.official_templates import _SHIPPED, REVISIONS_FILE, document_in+from switch_core.template_installs import fingerprint, fingerprints, render_agents++_HERE = Path(__file__).parent++# What the agents are rendered with to fingerprint what a revision sets on+# them. An official template's agent values do not depend on who runs it, so+# any inputs give the same fingerprints; a test holds them to that.+SAMPLE_INPUTS: dict[str, Any] = {"agent_name": "sample"}+SAMPLE_BUILTINS: dict[str, str] = {+ "$creator": "sample",+ "$creator_email": "[email protected]",+ "$date": "2000-01-01",+ "$timestamp": "0",+}+++def entry_for(folder: Path) -> dict[str, Any]:+ """What a revision records of the template in `folder`, as it is now."""+ managed = document_in(folder, agent_management=True)+ console = document_in(folder, agent_management=False)+ agents = render_agents(managed, _inputs_for(managed), SAMPLE_BUILTINS)+ return {+ "document": fingerprint(managed + "\n---\n" + console),+ "agents": {key: fingerprints(fields) for key, fields in agents.items()},+ }+++def _inputs_for(document: str) -> dict[str, Any]:+ """The sample inputs the document declares: one with no `agent_name`+ param is rendered without it."""+ params = yaml.safe_load(document).get("params") or {}+ return {name: value for name, value in SAMPLE_INPUTS.items() if name in params}+++def recorded(slug: str) -> list[dict[str, Any]]:+ path = _HERE / slug / REVISIONS_FILE+ if not path.exists():+ return []+ return list(json.loads(path.read_text(encoding="utf-8"))["revisions"])+++def stale(slug: str) -> bool:+ """Whether the template's files no longer serve its last revision."""+ revisions = recorded(slug)+ if not revisions:+ return True+ last = revisions[-1]+ return {k: last[k] for k in ("document", "agents")} != entry_for(_HERE / slug)+++def record(slug: str) -> int:+ """Add a revision for what the template's files serve now, unless the+ last one already is; return the revision they serve."""+ revisions = recorded(slug)+ if revisions and not stale(slug):+ return int(revisions[-1]["revision"])+ revision = len(revisions) + 1+ revisions.append({"revision": revision, **entry_for(_HERE / slug)})+ write(slug, revisions)+ return revision+++def write(slug: str, revisions: list[dict[str, Any]]) -> None:+ path = _HERE / slug / REVISIONS_FILE+ path.write_text(+ json.dumps({"revisions": revisions}, indent=2) + "\n", encoding="utf-8"+ )+++def main(argv: list[str]) -> int:+ if len(argv) == 2 and argv[0] == "record":+ print(f"{argv[1]}: revision {record(argv[1])}")+ return 0+ if argv == ["check"]:+ out = [shipped.slug for shipped in _SHIPPED if stale(shipped.slug)]+ for slug in out:+ print(+ f"{slug} changed since its last revision: run "+ f"python -m switch_core.official_templates.revisions record {slug}"+ )+ return 1 if out else 0+ print("usage: revisions record <slug> | revisions check", file=sys.stderr)+ return 2+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/core/switch_core/official_templates/switch-buddy/revisions.json b/core/switch_core/official_templates/switch-buddy/revisions.jsonnew file mode 100644index 000000000..1b9171407--- /dev/null+++ b/core/switch_core/official_templates/switch-buddy/revisions.json@@ -0,0 +1,100 @@+{+ "revisions": [+ {+ "revision": 1,+ "document": "36b3817f161c27662a5055fbc117ef7e",+ "agents": {+ "buddy": {+ "instructions": "f8021c80b58e9eecf8a6ffc275e02a36",+ "description": "7edad24274ce05e3932b5e712718e10a",+ "icon_url": "05ca6f0fb75b6abfd1d8b0bc7bcd9da4",+ "display_name": "74234e98afe7498fb5daf1f36ac2d78a"+ }+ }+ },+ {+ "revision": 2,+ "document": "3e863ed266e67d72c8fa7ab2996480c1",+ "agents": {+ "buddy": {+ "instructions": "ebb11bdf4e270674535096e2db8984d0",+ "description": "7edad24274ce05e3932b5e712718e10a",+ "icon_url": "05ca6f0fb75b6abfd1d8b0bc7bcd9da4",+ "display_name": "74234e98afe7498fb5daf1f36ac2d78a"+ }+ }+ },+ {+ "revision": 3,+ "document": "552f853ae50a7ef1b42df25d6af563f3",+ "agents": {+ "buddy": {+ "instructions": "9db487e2f0d924e80c61ee9288396485",+ "description": "7edad24274ce05e3932b5e712718e10a",+ "icon_url": "05ca6f0fb75b6abfd1d8b0bc7bcd9da4",+ "display_name": "74234e98afe7498fb5daf1f36ac2d78a"+ }+ }+ },+ {+ "revision": 4,+ "document": "d724772b091800a0897765e3a059b9e2",+ "agents": {+ "buddy": {+ "instructions": "5d9c41d901666e9b1fea7c7c868e9724",+ "description": "7edad24274ce05e3932b5e712718e10a",+ "icon_url": "05ca6f0fb75b6abfd1d8b0bc7bcd9da4",+ "display_name": "74234e98afe7498fb5daf1f36ac2d78a"+ }+ }+ },+ {+ "revision": 5,+ "document": "9fdd6963d0d2e9bb5f9efcd01a6e6d6e",+ "agents": {+ "buddy": {+ "instructions": "5d47e2da73496cbd9ad09db1fce309bd",+ "description": "7edad24274ce05e3932b5e712718e10a",+ "icon_url": "05ca6f0fb75b6abfd1d8b0bc7bcd9da4",+ "display_name": "74234e98afe7498fb5daf1f36ac2d78a"+ }+ }+ },+ {+ "revision": 6,+ "document": "a496046a2282d29172ac969e36574001",+ "agents": {+ "buddy": {+ "instructions": "cdc951a4f458be2066d17a1ac7d4f889",+ "description": "7edad24274ce05e3932b5e712718e10a",+ "icon_url": "05ca6f0fb75b6abfd1d8b0bc7bcd9da4",+ "display_name": "74234e98afe7498fb5daf1f36ac2d78a"+ }+ }+ },+ {+ "revision": 7,+ "document": "b27fec203f401b796c6a0e73bbc7906f",+ "agents": {+ "buddy": {+ "instructions": "f2fe090701164177694c14d50f82a707",+ "description": "7edad24274ce05e3932b5e712718e10a",+ "icon_url": "05ca6f0fb75b6abfd1d8b0bc7bcd9da4",+ "display_name": "74234e98afe7498fb5daf1f36ac2d78a"+ }+ }+ },+ {+ "revision": 8,+ "document": "c79aab859ba8858bfaf470a3759790cb",+ "agents": {+ "buddy": {+ "instructions": "dfb8a40306154516fa8b66dd863f7b23",+ "description": "7edad24274ce05e3932b5e712718e10a",+ "icon_url": "05ca6f0fb75b6abfd1d8b0bc7bcd9da4",+ "display_name": "74234e98afe7498fb5daf1f36ac2d78a"+ }+ }+ }+ ]+}diff --git a/core/switch_core/official_templates/switch-expert/revisions.json b/core/switch_core/official_templates/switch-expert/revisions.jsonnew file mode 100644index 000000000..0b249d73e--- /dev/null+++ b/core/switch_core/official_templates/switch-expert/revisions.json@@ -0,0 +1,16 @@+{+ "revisions": [+ {+ "revision": 1,+ "document": "5c744e733017f535604ecc770c916542",+ "agents": {+ "expert": {+ "instructions": "6a6d0e67b5343db20aa8b616d13d4197",+ "description": "4aedf8f613aa6cf04684e604470fec04",+ "icon_url": "74234e98afe7498fb5daf1f36ac2d78a",+ "display_name": "54423496af3307c6fbda3ff9390a89cb"+ }+ }+ }+ ]+}diff --git a/core/switch_core/template_installs.py b/core/switch_core/template_installs.pynew file mode 100644index 000000000..9dcbdd111--- /dev/null+++ b/core/switch_core/template_installs.py@@ -0,0 +1,93 @@+"""What a template sets on the agents it creates, and how to tell, later,+whether anyone has changed it since.++A template install (``db.models.TemplateInstall``) keeps, for each agent a+run created, a fingerprint of every value the template set on it. A value+whose fingerprint still matches is one nobody has changed, which a newer+revision of the template may replace; one that no longer matches was changed+by someone, and is theirs.++Only these fields are the template's to update. Who may address an agent,+whether it can manage agents, its provider, machine and directory are+settled when it is created and never touched by an update.+"""++from __future__ import annotations++import hashlib+import json+from typing import Any++from switch_core.agent_templates import plan_template+from switch_core.providers.registry import provider_ids+from switch_core.template_runs import NewAgentPlan+from switch_core.template_v2 import compile_v2, is_v2_text++AGENT_FIELDS: tuple[str, ...] = (+ "instructions",+ "description",+ "icon_url",+ "display_name",+)+++def fingerprint(value: str | None) -> str:+ """A value's fingerprint: equal for equal values, and short."""+ return hashlib.sha256(json.dumps(value).encode()).hexdigest()[:32]+++def agent_fields(plan: NewAgentPlan) -> dict[str, str | None]:+ """The values a template sets on an agent that an update may change."""+ return {+ "instructions": plan.instructions,+ "description": plan.description,+ "icon_url": plan.icon_url,+ "display_name": plan.display_name,+ }+++def fingerprints(fields: dict[str, str | None]) -> dict[str, str]:+ return {name: fingerprint(value) for name, value in fields.items()}+++def resource_keys(+ text: str, inputs: dict[str, Any], builtins: dict[str, str]+) -> dict[str, str]:+ """Each agent's name as a run creates it, with the key the template gives+ it: a version 2 resource's key, or for an older document the agent's own+ name."""+ if not is_v2_text(text):+ return {}+ compiled = compile_v2(text, inputs, builtins)+ return {name: key for key, name in compiled.names.items()}+++def key_of(plan: NewAgentPlan, keys: dict[str, str]) -> str:+ return keys.get(plan.name, plan.name)+++def render_agents(+ text: str, inputs: dict[str, Any], builtins: dict[str, str]+) -> dict[str, dict[str, str | None]]:+ """The values `text` sets on each agent it creates, by key, rendered with+ the inputs and builtins a run used.++ Where an agent runs does not change what it is told, so the run's machine+ stands in as the only one, ready for every provider: a machine since+ removed or offline must not stop a later revision from being read.+ """+ machine = str(inputs.get("machine") or "machine")+ machines = [+ {+ "id": machine,+ "name": machine,+ "state": "online",+ "providers": [+ {"provider": provider, "installed": True, "auth": "ok"}+ for provider in provider_ids()+ ],+ }+ ]+ plan = plan_template(text, {}, inputs, builtins=builtins, machines=machines)+ keys = resource_keys(text, inputs, builtins)+ return {key_of(agent, keys): agent_fields(agent) for agent in plan.new_agents}diff --git a/core/tests/switch_core/test_official_templates.py b/core/tests/switch_core/test_official_templates.pyindex b8bfc2855..f0dedfb59 100644--- a/core/tests/switch_core/test_official_templates.py+++ b/core/tests/switch_core/test_official_templates.py@@ -8,9 +8,14 @@ from pathlib import Pathimport yamlfrom switch_core.official_templates import (+ _SHIPPED,+ current_revision,official_template,official_templates,+ released_agent_fingerprints,+ revisions,)+from switch_core.template_installs import fingerprints, render_agentsfrom switch_core.template_lint import lint_template_REPO = Path(__file__).resolve().parents[3]@@ -129,3 +134,56 @@ def test_an_unknown_official_id_is_none():official_template("official:nope", agent_management=True, switch_buddy=True)is None)+++def test_every_template_s_last_revision_is_what_its_files_serve():+ """A change to an official template is a new revision: agents created+ from an older one are brought up to it, and only a new revision tells+ them there is something to bring."""+ for shipped in _SHIPPED:+ assert not revisions.stale(shipped.slug), (+ f"{shipped.slug} changed since its last revision. Record one: "+ f"python -m switch_core.official_templates.revisions record {shipped.slug}"+ )+++def test_a_template_is_served_at_its_last_revision():+ buddy = official_template("official:switch-buddy", True, switch_buddy=True)+ assert buddy is not None+ assert buddy.version == revisions.recorded("switch-buddy")[-1]["revision"]+ assert buddy.version == current_revision("switch-buddy")+++def test_what_a_revision_sets_on_its_agents_does_not_depend_on_who_runs_it():+ """Old agents are matched against the fingerprints of every revision,+ rendered with sample inputs; a person's own inputs must give the same."""+ for shipped in _SHIPPED:+ document = official_template(f"official:{shipped.slug}", True, True) or (+ official_template(f"official:{shipped.slug}", True, False)+ )+ assert document is not None+ sample = revisions.entry_for(_PACKAGED / shipped.slug)["agents"]+ inputs = {+ name: value+ for name, value in {"agent_name": "switch-buddy-zoe"}.items()+ if name in (yaml.safe_load(document.content).get("params") or {})+ }+ mine = render_agents(+ document.content,+ inputs,+ {+ "$creator": "zoe",+ "$creator_email": "[email protected]",+ "$date": "2026-10-26",+ "$timestamp": "1793000000",+ },+ )+ assert {k: fingerprints(v) for k, v in mine.items()} == sample, shipped.slug+++def test_released_fingerprints_list_every_revision_newest_first():+ released = released_agent_fingerprints("switch-buddy")+ assert [revision for revision, _ in released] == list(+ range(current_revision("switch-buddy"), 0, -1)+ )+ assert all("buddy" in agents for _, agents in released)