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
Let agents find, run and save workspace templates (CHOO-2923) (#554)
Abel Dantas6c5ce2945084
diff --git a/connectors/antigravity-cli/skills/switch/SKILL.md b/connectors/antigravity-cli/skills/switch/SKILL.mdindex 584d4da10..ff15bf541 100644--- a/connectors/antigravity-cli/skills/switch/SKILL.md+++ b/connectors/antigravity-cli/skills/switch/SKILL.md@@ -810,6 +810,13 @@ failure-mode tools are covered in the sections just above.- `get_room_group_detail` — one group's rooms and child groups.- `create_room_group` — provision a new room group.- `create_room_from_yaml` — provision a room or group from a YAML template.+- `get_template_guide`: how to write a template, and the schema it is checked against.+- `list_templates`: the saved templates you can use.+- `get_template`: one template's document, inputs and agent slots.+- `run_template`: create the rooms a saved template describes.+- `save_template`: save a template, private or shared.+- `update_template`: change a template you saved.+- `delete_template`: delete a template you saved.- `list_agents` — every agent on the instance, with optional filters.- `get_agent_detail` — one agent's config, capabilities and sessions.- `update_agent_detail` — change an agent you own.diff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.mdindex f98212bef..7b8ee7a2c 100644--- a/connectors/claude-code-plugin/skills/switch/SKILL.md+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md@@ -833,6 +833,13 @@ failure-mode tools are covered in the sections just above.- `get_room_group_detail` — one group's rooms and child groups.- `create_room_group` — provision a new room group.- `create_room_from_yaml` — provision a room or group from a YAML template.+- `get_template_guide`: how to write a template, and the schema it is checked against.+- `list_templates`: the saved templates you can use.+- `get_template`: one template's document, inputs and agent slots.+- `run_template`: create the rooms a saved template describes.+- `save_template`: save a template, private or shared.+- `update_template`: change a template you saved.+- `delete_template`: delete a template you saved.- `list_agents` — every agent on the instance, with optional filters.- `get_agent_detail` — one agent's config, capabilities and sessions.- `update_agent_detail` — change an agent you own.diff --git a/connectors/codex-plugin/skills/switch/SKILL.md b/connectors/codex-plugin/skills/switch/SKILL.mdindex c9e56f91c..af6157f85 100644--- a/connectors/codex-plugin/skills/switch/SKILL.md+++ b/connectors/codex-plugin/skills/switch/SKILL.md@@ -831,6 +831,13 @@ failure-mode tools are covered in the sections just above.- `get_room_group_detail` — one group's rooms and child groups.- `create_room_group` — provision a new room group.- `create_room_from_yaml` — provision a room or group from a YAML template.+- `get_template_guide`: how to write a template, and the schema it is checked against.+- `list_templates`: the saved templates you can use.+- `get_template`: one template's document, inputs and agent slots.+- `run_template`: create the rooms a saved template describes.+- `save_template`: save a template, private or shared.+- `update_template`: change a template you saved.+- `delete_template`: delete a template you saved.- `list_agents` — every agent on the instance, with optional filters.- `get_agent_detail` — one agent's config, capabilities and sessions.- `update_agent_detail` — change an agent you own.diff --git a/connectors/cursor-cli/skills/switch/SKILL.md b/connectors/cursor-cli/skills/switch/SKILL.mdindex 2d1806af8..d5872f898 100644--- a/connectors/cursor-cli/skills/switch/SKILL.md+++ b/connectors/cursor-cli/skills/switch/SKILL.md@@ -800,6 +800,13 @@ failure-mode tools are covered in the sections just above.- `get_room_group_detail` — one group's rooms and child groups.- `create_room_group` — provision a new room group.- `create_room_from_yaml` — provision a room or group from a YAML template.+- `get_template_guide`: how to write a template, and the schema it is checked against.+- `list_templates`: the saved templates you can use.+- `get_template`: one template's document, inputs and agent slots.+- `run_template`: create the rooms a saved template describes.+- `save_template`: save a template, private or shared.+- `update_template`: change a template you saved.+- `delete_template`: delete a template you saved.- `list_agents` — every agent on the instance, with optional filters.- `get_agent_detail` — one agent's config, capabilities and sessions.- `update_agent_detail` — change an agent you own.diff --git a/connectors/opencode-plugin/skills/switch/SKILL.md b/connectors/opencode-plugin/skills/switch/SKILL.mdindex fdbc0c0db..d3cb10b6a 100644--- a/connectors/opencode-plugin/skills/switch/SKILL.md+++ b/connectors/opencode-plugin/skills/switch/SKILL.md@@ -834,6 +834,13 @@ failure-mode tools are covered in the sections just above.- `get_room_group_detail` — one group's rooms and child groups.- `create_room_group` — provision a new room group.- `create_room_from_yaml` — provision a room or group from a YAML template.+- `get_template_guide`: how to write a template, and the schema it is checked against.+- `list_templates`: the saved templates you can use.+- `get_template`: one template's document, inputs and agent slots.+- `run_template`: create the rooms a saved template describes.+- `save_template`: save a template, private or shared.+- `update_template`: change a template you saved.+- `delete_template`: delete a template you saved.- `list_agents` — every agent on the instance, with optional filters.- `get_agent_detail` — one agent's config, capabilities and sessions.- `update_agent_detail` — change an agent you own.diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.tsindex ff872e675..ad69b5054 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts@@ -87,10 +87,12 @@ import {deleteTemplate,updateTemplate,fetchTemplateDetail,+ fetchTemplateRuns,fetchTemplates,GatewayError,ownsOwnerAddressedAgent,releaseBridgeIdentity,+ changeTemplateRun,createRoomFromTemplate,exportRoomYaml,fetchTemplateSchema,@@ -99,6 +101,7 @@ import {type StoredTemplateSummary,type TemplateVisibility,type ProvisionFromTemplateResult,+ type TemplateRun,updateAddressingPolicy,updateAgentIcon,updateRoom,@@ -537,9 +540,23 @@ export const switchServersController = createRPCController({createRoomFromTemplate: async (serverId: string,yamlText: string,- inputs: Record<string, string | number | boolean>+ inputs: Record<string, string | number | boolean>,+ templateName?: string): Promise<ProvisionFromTemplateResult> =>- createRoomFromTemplate(await requireServer(serverId), yamlText, inputs),+ createRoomFromTemplate(await requireServer(serverId), yamlText, inputs, templateName),++ /** The runs the user may see, or null when the server does not record runs. */+ listTemplateRuns: async (params: { serverId: string }): Promise<TemplateRun[] | null> =>+ fetchTemplateRuns(await requireServer(params.serverId)),++ stopTemplateRun: async (params: { serverId: string; rootRoomId: string }): Promise<TemplateRun> =>+ changeTemplateRun(await requireServer(params.serverId), params.rootRoomId, 'stop'),++ continueTemplateRun: async (params: {+ serverId: string;+ rootRoomId: string;+ }): Promise<TemplateRun> =>+ changeTemplateRun(await requireServer(params.serverId), params.rootRoomId, 'continue'),listTemplates: async (params: {serverId: string;diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.tsindex e12000267..31fdcd62b 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts@@ -1120,12 +1120,14 @@ function toRoomResult(json: RoomJson): TemplateProvisionResult {export async function createRoomFromTemplate(server: SwitchServer,yamlText: string,- inputs: Record<string, string | number | boolean>+ inputs: Record<string, string | number | boolean>,+ /** The template's display name, so the run it starts says where it came from. */+ templateName?: string): Promise<ProvisionFromTemplateResult> {const res = await gatewayFetch(server, '/rooms/from-yaml', {authenticated: true,method: 'POST',- body: { yaml: yamlText, inputs },+ body: { yaml: yamlText, inputs, ...(templateName ? { template_name: templateName } : {}) },});const json = (await res.json()) as| RoomJson@@ -1147,6 +1149,142 @@ export async function createRoomFromTemplate(return { kind: 'room', ...toRoomResult(json) };}+// ── Template runs ───────────────────────────────────────────────────────────++/** `paused` waits for its owner to continue it; `stopped` refuses further+ * agent room creation for good. */+export type TemplateRunState = 'running' | 'paused' | 'stopped';++/** One room of a run, the root included. */+export type TemplateRunRoom = {+ id: string;+ name: string;+ /** Null for the root room. */+ parentRoomId: string | null;+ /** Null when a person created the room. */+ createdByAgentId: string | null;+ createdByAgentName: string | null;+ templateName: string | null;+ createdAt: string;+ archived: boolean;+};++/**+ * A chain of rooms that started in one room a person made: every room an+ * agent created from there, and every room those rooms' agents created.+ */+export type TemplateRun = {+ rootRoomId: string;+ rootRoomName: string;+ /** The person who made the root room, or the agent that did. */+ startedByName: string | null;+ /** The first template used in the run. */+ templateName: string | null;+ startedAt: string;+ lastActivityAt: string;+ state: TemplateRunState;+ /** An agent is mid-turn in one of the run's rooms right now. */+ working: boolean;+ /** Why the run is paused or stopped, as a sentence. */+ reason: string | null;+ /** Who stopped or continued it. Null when the server paused it. */+ changedByName: string | null;+ /** The room a paused request would have repeated. */+ pausedRepeatOf: string | null;+ /** Whether the signed-in user may stop or continue it. */+ canControl: boolean;+ /** In creation order, the root first. */+ rooms: TemplateRunRoom[];+};++type TemplateRunRoomJson = {+ id: string;+ name: string;+ parent_room_id: string | null;+ created_by_agent_id: string | null;+ created_by_agent_name: string | null;+ template_name: string | null;+ created_at: string;+ archived: boolean;+};++type TemplateRunJson = {+ root_room_id: string;+ root_room_name: string;+ started_by_name: string | null;+ template_name: string | null;+ started_at: string;+ last_activity_at: string;+ state: TemplateRunState;+ working?: boolean;+ reason: string | null;+ changed_by_name: string | null;+ paused_repeat_of: string | null;+ can_control: boolean;+ rooms: TemplateRunRoomJson[];+};++function toTemplateRun(json: TemplateRunJson): TemplateRun {+ return {+ rootRoomId: json.root_room_id,+ rootRoomName: json.root_room_name,+ startedByName: json.started_by_name ?? null,+ templateName: json.template_name,+ startedAt: json.started_at,+ lastActivityAt: json.last_activity_at,+ state: json.state,+ working: json.working ?? false,+ reason: json.reason,+ changedByName: json.changed_by_name,+ pausedRepeatOf: json.paused_repeat_of,+ canControl: json.can_control,+ rooms: (json.rooms ?? []).map((r) => ({+ id: r.id,+ name: r.name,+ parentRoomId: r.parent_room_id,+ createdByAgentId: r.created_by_agent_id,+ createdByAgentName: r.created_by_agent_name,+ templateName: r.template_name,+ createdAt: r.created_at,+ archived: r.archived,+ })),+ };+}++/**+ * The runs the signed-in user may see, newest activity first+ * (`GET /template-runs`). Null when the server does not support the endpoint+ * (404): a server from before runs were recorded.+ */+export async function fetchTemplateRuns(server: SwitchServer): Promise<TemplateRun[] | null> {+ try {+ const res = await gatewayFetch(server, '/template-runs', { authenticated: true });+ const json = (await res.json()) as TemplateRunJson[];+ return json.map(toTemplateRun);+ } catch (e) {+ if (e instanceof GatewayError && e.status === 404) return null;+ throw e;+ }+}++/**+ * Stop or continue a run (`POST /template-runs/{root}/stop` or `/continue`).+ * The server answers 403 when the user may not control it, 404 for an unknown+ * run and 409 for one already stopped; the `detail` says which.+ */+export async function changeTemplateRun(+ server: SwitchServer,+ rootRoomId: string,+ action: 'stop' | 'continue'+): Promise<TemplateRun> {+ const res = await gatewayFetch(+ server,+ `/template-runs/${encodeURIComponent(rootRoomId)}/${action}`,+ { authenticated: true, method: 'POST' }+ );+ return toTemplateRun((await res.json()) as TemplateRunJson);+}+// ── Stored templates (template registry) ────────────────────────────────────export type StoredTemplateSummary = {diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-runs-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/template-runs-list.tsxnew file mode 100644index 000000000..edf72ff13--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-runs-list.tsx@@ -0,0 +1,196 @@+import { Boxes, DoorOpen, Play, Square } from 'lucide-react';+import { useCallback, useEffect, useRef, useState } from 'react';+import type { TemplateRun } from '@main/core/switch-servers/gateway-client';+import { openRoom } from '@renderer/features/switch-rooms/open-room';+import { failureText } from '@renderer/lib/errors/describe-failure';+import { toast } from '@renderer/lib/hooks/use-toast';+import { rpc } from '@renderer/lib/ipc';+import { Button } from '@renderer/lib/ui/button';+import { StatusBadge } from '@renderer/lib/ui/status-badge';+import { formatTimeAgo, isLiveRun, runAuthor, runLabel } from './template-runs';++/** How often shown runs are asked for again while one of them can still change. */+const LIVE_RUN_POLL_MS = 15_000;++/**+ * The runs the server records for this workspace, loaded when the listing+ * opens and again when the window regains focus, and polled while any of+ * them is running or paused.+ *+ * Quiet on failure: an older server without runs answers 404 and the list+ * stays empty, and a failed refresh keeps what was already shown.+ */+export function useTemplateRuns(serverId: string): {+ runs: TemplateRun[];+ replace: (run: TemplateRun) => void;+} {+ const [runs, setRuns] = useState<TemplateRun[]>([]);+ // An answer that lands after the listing moved to another server belongs+ // to the old one and is dropped.+ const shownServer = useRef(serverId);+ shownServer.current = serverId;++ const load = useCallback(async () => {+ try {+ const list = await rpc.switchServers.listTemplateRuns({ serverId });+ if (shownServer.current === serverId) setRuns(list ?? []);+ } catch {+ // The runs are an addition to the recents; the section renders without them.+ }+ }, [serverId]);++ useEffect(() => {+ setRuns([]);+ void load();+ const onFocus = () => void load();+ window.addEventListener('focus', onFocus);+ return () => window.removeEventListener('focus', onFocus);+ }, [load]);++ const live = runs.some(isLiveRun);+ useEffect(() => {+ if (!live) return;+ const timer = setInterval(() => {+ if (document.hidden) return;+ void load();+ }, LIVE_RUN_POLL_MS);+ return () => clearInterval(timer);+ }, [live, load]);++ const replace = useCallback(+ (run: TemplateRun) =>+ setRuns((prev) => prev.map((r) => (r.rootRoomId === run.rootRoomId ? run : r))),+ []+ );++ return { runs, replace };+}++/** The columns every row of Recently used shares, runs and documents alike:+ * name, status, size, when, and one action slot. */+export const RECENT_ROW =+ 'grid grid-cols-[minmax(0,1fr)_6.5rem_4.5rem_4.5rem_11rem] items-center gap-x-3 px-3 py-1.5 min-h-10 text-sm';++/** The one button style of the action column. */+export const RECENT_ACTION = 'h-7 px-2.5 text-xs';++function RunState({ run }: { run: TemplateRun }) {+ if (run.state === 'paused')+ return (+ <span title={run.reason ?? undefined}>+ <StatusBadge tone="warning">Paused</StatusBadge>+ </span>+ );+ if (run.state === 'stopped') return <StatusBadge tone="neutral">Stopped</StatusBadge>;+ if (!run.working) return null;+ return (+ <span className="inline-flex items-center gap-1.5 text-xs text-foreground-muted">+ <span className="size-1.5 animate-pulse rounded-full bg-emerald-500" />+ Working+ </span>+ );+}++/**+ * One run in "Recently used", in the shared columns: what it came from and+ * who made its rooms, its state, how many rooms, when it last moved, and+ * Continue or Stop when something can still happen in it. The name opens the+ * room the run started from.+ */+export function TemplateRunRow({+ serverId,+ run,+ onChanged,+}: {+ serverId: string;+ run: TemplateRun;+ onChanged: (run: TemplateRun) => void;+}) {+ const [busy, setBusy] = useState<'stop' | 'continue' | null>(null);+ const [confirmStop, setConfirmStop] = useState(false);+ const Icon = run.rooms.length > 1 ? Boxes : DoorOpen;+ const rooms = run.rooms.length;+ const paused = run.state === 'paused';+ const canStop = run.canControl && (paused || (run.state === 'running' && run.working));++ const change = async (action: 'stop' | 'continue') => {+ setBusy(action);+ try {+ const params = { serverId, rootRoomId: run.rootRoomId };+ onChanged(+ action === 'stop'+ ? await rpc.switchServers.stopTemplateRun(params)+ : await rpc.switchServers.continueTemplateRun(params)+ );+ } catch (error) {+ toast({+ title:+ action === 'stop'+ ? `Could not stop "${runLabel(run)}"`+ : `Could not continue "${runLabel(run)}"`,+ description: failureText(error, 'The server did not accept the change.'),+ variant: 'destructive',+ });+ } finally {+ setBusy(null);+ setConfirmStop(false);+ }+ };++ return (+ <div className={RECENT_ROW}>+ <button+ type="button"+ onClick={() => void openRoom(run.rootRoomId)}+ className="flex min-w-0 cursor-pointer items-center gap-2 text-left hover:underline"+ >+ <Icon className="size-3.5 shrink-0 text-foreground-muted" />+ <span className="truncate">{runLabel(run)}</span>+ <span className="shrink-0 text-xs text-foreground-passive">{runAuthor(run)}</span>+ </button>+ <span>+ <RunState run={run} />+ </span>+ <span className="text-xs text-foreground-passive">+ {rooms} {rooms === 1 ? 'room' : 'rooms'}+ </span>+ <span className="text-xs text-foreground-passive">+ {formatTimeAgo(Date.parse(run.lastActivityAt))}+ </span>+ <span className="flex justify-end gap-1.5">+ {run.canControl && paused && (+ <Button+ type="button"+ variant="outline"+ size="sm"+ className={RECENT_ACTION}+ disabled={busy !== null}+ onClick={() => void change('continue')}+ >+ <Play className="size-3.5" />+ {busy === 'continue' ? 'Continuing…' : 'Continue'}+ </Button>+ )}+ {canStop && (+ <Button+ type="button"+ variant="outline"+ size="sm"+ className={RECENT_ACTION}+ disabled={busy !== null}+ title="Agents can no longer create rooms in this run. The rooms stay."+ onClick={() => {+ // A stopped run cannot be started again, so the first click asks.+ if (confirmStop) void change('stop');+ else setConfirmStop(true);+ }}+ onBlur={() => setConfirmStop(false)}+ >+ <Square className="size-3.5" />+ {busy === 'stop' ? 'Stopping…' : confirmStop ? 'Sure?' : 'Stop'}+ </Button>+ )}+ </span>+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-runs.ts b/console/apps/switch-console-desktop/src/renderer/features/templates/template-runs.tsnew file mode 100644index 000000000..46ef769c3--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-runs.ts@@ -0,0 +1,47 @@+import type { TemplateRun } from '@main/core/switch-servers/gateway-client';++export function formatTimeAgo(ms: number): string {+ const seconds = Math.floor((Date.now() - ms) / 1000);+ if (seconds < 60) return 'just now';+ const minutes = Math.floor(seconds / 60);+ if (minutes < 60) return `${minutes}m ago`;+ const hours = Math.floor(minutes / 60);+ if (hours < 24) return `${hours}h ago`;+ return `${Math.floor(hours / 24)}d ago`;+}++/** What a run is listed as: the template it came from, else its first room. */+export function runLabel(run: TemplateRun): string {+ return run.templateName ?? run.rootRoomName;+}++/**+ * Who made the run's rooms, for the row's "by" line. The agents that created+ * rooms in it, by name, or whoever started it when no agent has: a run with+ * only its root room is a template someone ran.+ */+export function runAuthor(run: TemplateRun): string {+ const names: string[] = [];+ for (const room of run.rooms) {+ const name = room.createdByAgentName;+ if (room.createdByAgentId !== null && name && !names.includes(name)) names.push(name);+ }+ if (names.length === 0) return run.startedByName ?? 'someone';+ if (names.length === 1) return names[0];+ return `${names[0]} and ${names.length - 1} more`;+}++/** Whether the run can still change, so its row is worth refreshing: an idle+ * run starts working again when someone addresses an agent in its rooms. */+export function isLiveRun(run: TemplateRun): boolean {+ return run.state === 'running' || run.state === 'paused';+}++/** Whether the run matches the listing's search text, by its label or any room name. */+export function runMatches(run: TemplateRun, needle: string): boolean {+ if (needle.length === 0) return true;+ return (+ runLabel(run).toLowerCase().includes(needle) ||+ run.rooms.some((r) => r.name.toLowerCase().includes(needle))+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsxindex 9a3822dc2..15f65c9aa 100644--- a/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx@@ -995,7 +995,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {}const result =createdRoom.current ??- (await rpc.switchServers.createRoomFromTemplate(serverId, coreYaml, inputs));+ (await rpc.switchServers.createRoomFromTemplate(serverId, coreYaml, inputs, loaded.name));createdRoom.current = result;setRoomStatus('created');// The room exists whether or not the sidebar refreshes.diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsxindex 21f5a9178..3cef4e4f3 100644--- a/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx@@ -33,8 +33,11 @@ import { Button } from '@renderer/lib/ui/button';import { SearchInput } from '@renderer/lib/ui/search-input';import { SegmentedControl } from '@renderer/lib/ui/segmented-control';import { Toggle } from '@renderer/lib/ui/toggle';+import { cn } from '@renderer/utils/utils';import { prefillForSave } from './agent-template-data';import { bundledTemplates } from './bundled-templates';+import { formatTimeAgo, runMatches } from './template-runs';+import { RECENT_ACTION, RECENT_ROW, TemplateRunRow, useTemplateRuns } from './template-runs-list';function useServerId(): string {return useParams('templates').params.serverId;@@ -251,19 +254,11 @@ function Section({);}-function formatTimeAgo(ms: number): string {- const seconds = Math.floor((Date.now() - ms) / 1000);- if (seconds < 60) return 'just now';- const minutes = Math.floor(seconds / 60);- if (minutes < 60) return `${minutes}m ago`;- const hours = Math.floor(minutes / 60);- if (hours < 24) return `${hours}h ago`;- return `${Math.floor(hours / 24)}d ago`;-}-/**- * Documents used from this Console, kept locally per workspace. Each can be- * used again or saved to the workspace, where everyone can find it.+ * What was used lately: the template runs the server records for this+ * workspace, newest first, then the documents used from this Console, kept+ * locally per workspace. A run opens to show the rooms it made; a document can+ * be used again or saved to the workspace, where everyone can find it.*/function RecentsSection({serverId,@@ -287,6 +282,7 @@ function RecentsSection({// Each recent with its kind, classified by the same parser as the listing.const [recents, setRecents] = useState<(RecentTemplate & { kind: TemplateKind })[] | null>(null);const [saving, setSaving] = useState<string | null>(null);+ const { runs, replace: replaceRun } = useTemplateRuns(serverId);useEffect(() => {let cancelled = false;@@ -342,7 +338,9 @@ function RecentsSection({(kind === 'all' || r.kind === kind) &&(needle.length === 0 || r.name.toLowerCase().includes(needle)));- if (shown.length === 0) return null;+ // A run creates rooms, so an agents-only listing leaves them out.+ const shownRuns = kind === 'agent' ? [] : runs.filter((r) => runMatches(r, needle));+ if (shown.length === 0 && shownRuns.length === 0) return null;return (<section>@@ -351,51 +349,66 @@ function RecentsSection({Recently used</h3><p className="mt-0.5 mb-3 text-xs text-foreground-muted">- Documents you used from this Console. Kept here only; Save to workspace makes one a template- everyone on the workspace can find.+ Template runs on this workspace, and documents you used from this Console. Documents are+ kept here only; Save to workspace makes one a template everyone on the workspace can find.</p>- <div className="flex flex-col gap-1">- {shown.map((r) => (- <div key={r.yamlText} className="flex items-center gap-1">- <button- type="button"- onClick={() =>- navigate('templateImport', {- serverId,- yamlText: r.yamlText,- sourceName: r.name,- })- }- className="flex flex-1 cursor-pointer items-center justify-between rounded-md border border-border px-3 py-2 text-left text-sm transition-colors hover:bg-[var(--sel-soft)]"- >- <span className="flex items-center gap-2 truncate">- {(() => {- const Icon = KIND_ICON[r.kind];- return <Icon className="size-3.5 shrink-0 text-foreground-muted" />;- })()}- {r.name}- </span>- <span className="shrink-0 text-xs text-foreground-passive">- {formatTimeAgo(r.usedAt)}- </span>- </button>- {onWorkspace.has(r.name) ? (- <span className="px-3 text-xs text-foreground-passive">On the workspace</span>- ) : (- <Button+ <div className="divide-y divide-border rounded-md border border-border">+ <div className={cn(RECENT_ROW, 'text-[11px] font-medium text-foreground-passive')}>+ <span>Name</span>+ <span>Status</span>+ <span>Size</span>+ <span>When</span>+ <span />+ </div>+ {shownRuns.map((run) => (+ <TemplateRunRow+ key={run.rootRoomId}+ serverId={serverId}+ run={run}+ onChanged={replaceRun}+ />+ ))}+ {shown.map((r) => {+ const Icon = KIND_ICON[r.kind];+ const saved = onWorkspace.has(r.name);+ return (+ <div key={r.yamlText} className={RECENT_ROW}>+ <buttontype="button"- variant="ghost"- size="sm"- title="Save to the workspace, so everyone on it can use it"- disabled={saving === r.yamlText}- onClick={() => void saveToWorkspace(r)}+ onClick={() =>+ navigate('templateImport', {+ serverId,+ yamlText: r.yamlText,+ sourceName: r.name,+ })+ }+ className="flex min-w-0 cursor-pointer items-center gap-2 text-left hover:underline">- <Save className="size-3.5" />- Save to workspace- </Button>- )}- </div>- ))}+ <Icon className="size-3.5 shrink-0 text-foreground-muted" />+ <span className="truncate">{r.name}</span>+ </button>+ <span className="text-xs text-foreground-passive">{saved ? 'Saved' : ''}</span>+ <span />+ <span className="text-xs text-foreground-passive">{formatTimeAgo(r.usedAt)}</span>+ <span className="flex justify-end">+ {!saved && (+ <Button+ type="button"+ variant="outline"+ size="sm"+ className={RECENT_ACTION}+ title="Save to the workspace, so everyone on it can use it"+ disabled={saving === r.yamlText}+ onClick={() => void saveToWorkspace(r)}+ >+ <Save className="size-3.5" />+ Save to workspace+ </Button>+ )}+ </span>+ </div>+ );+ })}</div></section>);diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.mdindex 30c4f7972..a4d583f8f 100644--- a/console/packages/plugins/src/switch-skill/SKILL.md+++ b/console/packages/plugins/src/switch-skill/SKILL.md@@ -421,6 +421,28 @@ carrying a display name addresses no one.of, and reverse it. Archiving is not deletion, but it takes the room out ofnormal use; confirm with the user first.+### Templates++Templates saved on the workspace can be found, read, run and saved by you.+Before writing one, call **`get_template_guide`**: the template language and+the schema the server checks documents against.++- **`list_templates`**: what you can use, every shared template plus your+ owner's private ones. Each row says who saved it and `can_edit`.+- **`get_template`**: one template's document, its `params` (the inputs to+ fill) and `agent_slots` (the agents it would create).+- **`run_template`**: create the rooms a saved template describes, like+ `create_room_from_yaml`. You cannot create agents; an agent or team+ template runs when you fill each slot with an existing agent, in+ `agents: {slot name: agent name}`.+- **`save_template`**: save a template for your owner, `private` or+ `shared`. Only you can change or delete it afterwards.+- **`update_template`** / **`delete_template`**: only for templates you saved.++A refusal says why (a template you did not save, a slot that needs a new+agent, a name your owner already uses). Tell the person who asked, and what+they can do instead.+### Room documents and attached resources`connect_to_room` advertises the room's `references`, `documents` and@@ -791,6 +813,13 @@ Every Switch tool you call in normal operation, one line each.- `get_room_group_detail` — one group's rooms and child groups.- `create_room_group` — provision a new room group.- `create_room_from_yaml` — provision a room or group from a YAML template.+- `get_template_guide`: how to write a template, and the schema it is checked against.+- `list_templates`: the saved templates you can use.+- `get_template`: one template's document, inputs and agent slots.+- `run_template`: create the rooms a saved template describes.+- `save_template`: save a template, private or shared.+- `update_template`: change a template you saved.+- `delete_template`: delete a template you saved.- `list_agents` — every agent on the instance, with optional filters.- `get_agent_detail` — one agent's config, capabilities and sessions.- `update_agent_detail` — change an agent you own.diff --git a/core/switch_core/agent_refusals.py b/core/switch_core/agent_refusals.pynew file mode 100644index 000000000..be74b65fe--- /dev/null+++ b/core/switch_core/agent_refusals.py@@ -0,0 +1,91 @@+"""Requests the server refuses an agent, and how the refusal is reported.++An agent acts for its owner, but not with everything the owner may do: it may+change only the templates it saved, it cannot create agents, and the run+guards in ``agent_runs`` refuse rooms that cannot work. When one of those+rules says no, the agent gets a sentence it can act on, and the refusal is+reported. Nobody yet knows which of these rules people will run into, so the+counts are what a finer rights model should be designed from.++Each refusal goes two places: a log line naming the agent, and a telemetry+event that carries only the operation and the reason code, since product+telemetry never carries a name or an id.+"""++from __future__ import annotations++import logging+from typing import TYPE_CHECKING, Literal++from switch_core.telemetry import emit_safely++if TYPE_CHECKING:+ from switch_core.telemetry import TelemetryService++logger = logging.getLogger(__name__)++RefusalReason = Literal[+ # Templates+ "not_found",+ "not_yours",+ "name_taken",+ "visibility_not_allowed",+ "invalid",+ "too_large",+ "missing_agents",+ "agent_creation_console_only",+ # Rooms an agent creates (see `agent_runs`)+ "busy",+ "run_paused",+ "run_stopped",+ "repeat",+ "kickoff_ignored",+]++REFUSAL_REASONS: tuple[str, ...] = RefusalReason.__args__ # type: ignore[attr-defined]++# The agent operations whose refusals are reported.+OPERATIONS = (+ "list_templates",+ "get_template",+ "run_template",+ "save_template",+ "update_template",+ "delete_template",+ "create_room",+ "create_room_from_yaml",+)+++class AgentRefused(ValueError):+ """A request refused on purpose, with a reason code and a sentence for+ the agent. A ValueError, so it reaches the agent the way every other+ operation error does."""++ def __init__(self, reason: RefusalReason, message: str) -> None:+ super().__init__(message)+ self.reason: RefusalReason = reason+++def record_refusal(+ telemetry: TelemetryService | None,+ *,+ agent_id: str,+ agent_name: str,+ operation: str,+ refusal: AgentRefused,+) -> None:+ """Report a refusal in the log and as a telemetry event."""+ logger.info(+ "Refused agent %s (%s) %s: %s. %s",+ agent_name,+ agent_id,+ operation,+ refusal.reason,+ refusal,+ )+ emit_safely(+ telemetry,+ "agent_request_refused",+ {"operation": operation, "reason": refusal.reason},+ )diff --git a/core/switch_core/agent_runs.py b/core/switch_core/agent_runs.pynew file mode 100644index 000000000..9560345c9--- /dev/null+++ b/core/switch_core/agent_runs.py@@ -0,0 +1,474 @@+"""Runs: the rooms agents create, kept as a tree a person can see and stop.++Every room an agent creates records the room it was working in and the root+of its run. Before anything is created, the server refuses what cannot work:+a second creation while one is in flight, a room in a paused or stopped run,+a kickoff a mentioned agent would ignore, and the same kickoff again on one+path, which pauses the run until someone lets it continue. A kickoff an+agent posts carries the run so far, so the agents it wakes can decline to+repeat a step.+"""++from __future__ import annotations++import hashlib+import logging+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from dataclasses import dataclass, replace+from datetime import datetime+from typing import TYPE_CHECKING, Literal, cast++from pydantic import BaseModel+from sqlalchemy import func, select++from switch_core.addressing import can_address, parse_policy+from switch_core.agent_refusals import AgentRefused+from switch_core.clients.admin_client import AdminClient+from switch_core.clients.admin_messages import OnBehalfOf+from switch_core.clients.mentions import mention_regex, strip_emphasis++if TYPE_CHECKING:+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++ from switch_core.clients.client_lifecycle_service import ClientLifecycleService+ from switch_core.db.models import Agent, Room+ from switch_core.db.stores.agent_store import AgentStore+ from switch_core.db.stores.room_store import RoomStore++logger = logging.getLogger(__name__)++RunState = Literal["running", "paused", "stopped"]+++class RunRefused(AgentRefused):+ """A room an agent asked for that was not created, and why. The message+ is written for the agent: it says what happened and what to do next."""+++class RunControl(BaseModel):+ """The state kept on a run's root. Absent means running."""++ state: RunState+ reason: str | None = None+ # Who changed it last; None when the server paused the run itself.+ by_user_id: str | None = None+ by_name: str | None = None+ at: datetime+ # When a person last let a paused run continue. A repeat is only a repeat+ # of a room made after this, so each Continue allows one more round.+ resumed_at: datetime | None = None+ # The room the paused request would have repeated, and where the agent+ # that made it was working: Continue wakes that agent there to go on.+ repeat_of: str | None = None+ paused_in: str | None = None+ paused_agent_name: str | None = None+++def run_control(room: Room) -> RunControl | None:+ return RunControl.model_validate(room.run_control) if room.run_control else None+++@dataclass(frozen=True)+class AgentOrigin:+ """An agent creating rooms, and where they go in its run.++ ``parent_room_id`` is the room the agent is working in, and ``run_id`` the+ root of that room's run. Both are None for an agent working in no room:+ what it creates starts a run of its own. ``trace`` is the run so far, as+ the agents a kickoff wakes are shown it.+ """++ agent_id: str+ agent_name: str+ owner_id: str | None+ owner_name: str | None+ parent_room_id: str | None+ run_id: str | None+ trace: str | None = None++ @property+ def headline_name(self) -> str:+ """How a kickoff names who it speaks for: the agent, and whose it is,+ without an @ so the agent does not wake on its own kickoff."""+ if self.owner_name is None:+ return self.agent_name+ return f"{self.agent_name}, {self.owner_name}'s agent"++ @property+ def owner_label(self) -> str:+ return self.owner_name or "The agent's owner"+++# How the run so far starts when it is appended to a kickoff (see `_trace`).+TRACE_OPENING = "This room is part of a run that started in "+++def kickoff_fingerprint(text: str) -> str:+ """The same request, however it is spaced or capitalised, and without the+ run history an agent may have copied from the kickoff it received."""+ request = text.split(TRACE_OPENING, 1)[0]+ normalised = " ".join(request.split()).casefold()+ return hashlib.sha256(normalised.encode()).hexdigest()+++def mentioned(text: str, name: str, alias: str | None) -> bool:+ body = strip_emphasis(text)+ if mention_regex(name).search(body):+ return True+ return alias is not None and mention_regex(alias).search(body) is not None+++def _run_of(parent: Room) -> str | None:+ """The run a room created from inside ``parent`` joins: the parent's run,+ or the parent itself when it roots one (a template a person ran, or a room+ an agent created). None for an ordinary room a person made: the new room+ starts a run of its own."""+ if parent.run_id is not None:+ return parent.run_id+ if parent.template_name is not None or parent.created_by_agent_id is not None:+ return parent.id+ return None+++class RunService:+ """Keeps runs: checks an agent's request against its run, records where+ the room goes, and lets a person pause, continue or stop a run."""++ def __init__(+ self,+ *,+ room_store: RoomStore,+ agent_store: AgentStore,+ session_factory: async_sessionmaker[AsyncSession],+ client_lifecycle: ClientLifecycleService | None = None,+ ) -> None:+ self._room_store = room_store+ self._agent_store = agent_store+ self._session_factory = session_factory+ self._client_lifecycle = client_lifecycle++ # ── An agent creating rooms ───────────────────────────────────────────++ @asynccontextmanager+ async def agent_creating(+ self,+ agent: Agent,+ *,+ owner_name: str | None,+ from_room_id: str | None,+ kickoffs: list[tuple[str, list[str], dict[str, str]]] | None = None,+ ) -> AsyncIterator[AgentOrigin]:+ """Hold the agent's one creation slot while its rooms are made.++ Everything that can refuse the request is checked here, before the+ caller creates anything, so a request is made whole or not at all.+ ``kickoffs`` lists each kickoff the request would post, with the+ agents in its room and their aliases (agent name to alias).+ """+ async with self._one_at_a_time(agent.id):+ origin = await self._origin(agent, owner_name, from_room_id)+ await self._check_open(origin)+ hashes = [kickoff_fingerprint(text) for text, _, _ in kickoffs or []]+ await self._check_repeat(origin, hashes)+ await self._check_audience(agent, kickoffs or [])+ if kickoffs:+ origin = replace(origin, trace=await self._trace(origin))+ yield origin++ @asynccontextmanager+ async def _one_at_a_time(self, agent_id: str) -> AsyncIterator[None]:+ """At most one room creation per agent at once, across every server+ process. A session-level advisory lock, held on one connection for as+ long as the creation runs and released with it, or with the+ connection if the process dies."""+ key = func.hashtext(f"agent-room-create:{agent_id}")+ async with self._session_factory() as session:+ got = (+ await session.execute(select(func.pg_try_advisory_lock(key)))+ ).scalar()+ if not got:+ raise RunRefused(+ "busy",+ "You are already creating a room. Wait for it to finish, "+ "then try again.",+ )+ try:+ yield+ finally:+ await session.execute(select(func.pg_advisory_unlock(key)))++ async def _origin(+ self, agent: Agent, owner_name: str | None, from_room_id: str | None+ ) -> AgentOrigin:+ parent = None+ if from_room_id is not None:+ async with self._session_factory() as session:+ parent = await self._room_store.get(session, from_room_id)+ return AgentOrigin(+ agent_id=agent.id,+ agent_name=agent.name,+ owner_id=agent.owner_id,+ owner_name=owner_name,+ parent_room_id=parent.id if parent else None,+ run_id=_run_of(parent) if parent else None,+ )++ async def _check_open(self, origin: AgentOrigin) -> None:+ if origin.run_id is None:+ return+ async with self._session_factory() as session:+ root = await self._room_store.get(session, origin.run_id)+ control = run_control(root) if root is not None else None+ if control is None or control.state == "running":+ return+ if control.state == "paused":+ raise RunRefused(+ "run_paused",+ f"Nothing was created: this run is paused. {control.reason} "+ f"The owner can let it continue from Templates in Switch Console.",+ )+ raise RunRefused(+ "run_stopped",+ f"Nothing was created: this run was stopped by "+ f"{control.by_name or 'its owner'}. No more rooms can be created in it.",+ )++ async def _check_repeat(self, origin: AgentOrigin, hashes: list[str]) -> None:+ if origin.parent_room_id is None or origin.run_id is None or not hashes:+ return+ async with self._session_factory() as session:+ path = await self._room_store.path_to_root(session, origin.parent_room_id)+ root = await self._room_store.get(session, origin.run_id)+ control = run_control(root) if root is not None else None+ resumed_at = control.resumed_at if control else None+ repeated = next(+ (+ room+ for room in path+ if room.created_by_agent_id == origin.agent_id+ and room.kickoff_hash in hashes+ and (+ resumed_at is None+ or cast(datetime, room.created_at) > resumed_at+ )+ ),+ None,+ )+ if repeated is None:+ return+ reason = (+ f"{origin.agent_name} asked for a room with the same kickoff as "+ f'"{repeated.name}", which it already created on this path.'+ )+ await self._room_store.set_run_control(+ session,+ origin.run_id,+ RunControl(+ state="paused",+ reason=reason,+ at=(+ await session.execute(select(func.clock_timestamp()))+ ).scalar_one(),+ resumed_at=resumed_at,+ repeat_of=repeated.id,+ paused_in=origin.parent_room_id,+ paused_agent_name=origin.agent_name,+ ).model_dump(mode="json"),+ )+ await session.commit()+ parent = await self._room_store.get(session, origin.parent_room_id)+ if parent is not None:+ await self._notice(+ parent,+ f"Paused this run: {reason} {origin.owner_label} can let it "+ f"continue from Templates in Switch Console.",+ )+ raise RunRefused(+ "repeat",+ f"Nothing was created, and the run is paused: {reason} If this is a "+ f"new step, say how it differs and ask {origin.owner_name or 'your owner'} "+ f"to let the run continue from Templates in Switch Console.",+ )++ async def _check_audience(+ self, agent: Agent, kickoffs: list[tuple[str, list[str], dict[str, str]]]+ ) -> None:+ """Every agent a kickoff mentions must accept this agent, or the room+ would be made and nobody would start work in it."""+ refused: list[str] = []+ async with self._session_factory() as session:+ for text, names, aliases in kickoffs:+ for name in names:+ if name == agent.name or not mentioned(+ text, name, aliases.get(name)+ ):+ continue+ target = await self._agent_store.get_by_name(session, name)+ if target is None:+ continue+ policy = parse_policy(target.addressing_policy)+ if policy.is_open() or can_address(+ policy,+ # A rule scoped to a room or group cannot name a room+ # that does not exist yet.+ room_id="",+ group_id=None,+ sender_kind="agent",+ sender_id=agent.id,+ sender_user_ids=[],+ sender_owner_user_id=agent.owner_id,+ owner_user_id=target.owner_id,+ ):+ continue+ if name not in refused:+ refused.append(name)+ if refused:+ listed = ", ".join(refused)+ raise RunRefused(+ "kickoff_ignored",+ f"Nothing was created: the kickoff mentions {listed}, and "+ f"{'it does' if len(refused) == 1 else 'they do'} not accept "+ f"messages from {agent.name}, so nobody would start work in the "+ f"room. Ask their owner to let {agent.name} address them (in "+ f"Switch Console, the agent's 'Who can talk to your agent'), or "+ f"leave them out of the kickoff.",+ )++ async def _trace(self, origin: AgentOrigin) -> str | None:+ """The run so far, top down, as the woken agents are shown it."""+ if origin.parent_room_id is None:+ return None+ async with self._session_factory() as session:+ path = list(+ reversed(+ await self._room_store.path_to_root(session, origin.parent_room_id)+ )+ )+ agent_ids = {r.created_by_agent_id for r in path if r.created_by_agent_id}+ names = {+ a.id: a.name+ for a in [await self._agent_store.get(session, i) for i in agent_ids]+ if a is not None+ }+ lines = []+ for i, room in enumerate(path, start=1):+ who = (+ f"created by {names.get(room.created_by_agent_id, 'an agent')}"+ if room.created_by_agent_id+ else "a person's room"+ )+ about = f": {room.description}" if room.description else ""+ lines.append(f"{i}. {room.name} ({who}){about}")+ lines.append(f"{len(path) + 1}. this room (created by {origin.agent_name})")+ return (+ f"{TRACE_OPENING}{path[0].name}. So far:\n"+ + "\n".join(lines)+ + "\nIf you are asked to repeat a step that already ran, say so here "+ "and stop, rather than creating another room."+ )++ # ── A person controlling a run ────────────────────────────────────────++ async def may_control(+ self, session: AsyncSession, root_id: str, *, user_id: str, is_admin: bool+ ) -> bool:+ """Admins, the owner of an agent that created rooms in the run, and+ the person who ran the template that started it."""+ if is_admin:+ return True+ return any(+ room.created_by == user_id+ and (room.created_by_agent_id is not None or room.template_name is not None)+ for room in await self._room_store.run_rooms(session, root_id)+ )++ async def set_state(+ self,+ root_id: str,+ state: Literal["running", "stopped"],+ *,+ user_id: str,+ user_name: str,+ ) -> None:+ """Continue a paused run, or stop a run. Stopping keeps its rooms."""+ async with self._session_factory() as session:+ root = await self._room_store.get(session, root_id)+ if root is None:+ raise LookupError(root_id)+ current = run_control(root)+ if current is not None and current.state == "stopped":+ raise RunRefused("run_stopped", "This run is already stopped.")+ # The database's clock, the one rooms are stamped with: a room made+ # after this Continue must compare as later, whatever the app+ # server's clock says.+ now = (await session.execute(select(func.clock_timestamp()))).scalar_one()+ control = RunControl(+ state=state,+ reason=None,+ by_user_id=user_id,+ by_name=user_name,+ at=now,+ resumed_at=now+ if state == "running"+ else (current.resumed_at if current else None),+ )+ await self._room_store.set_run_control(+ session, root_id, control.model_dump(mode="json")+ )+ await session.commit()+ rooms = await self._room_store.run_rooms(session, root_id)+ if state == "stopped":+ text = (+ f"{user_name} stopped this run. Agents can no longer create rooms "+ "in it; the rooms stay as they are."+ )+ for room in rooms:+ if room.archived_at is None:+ await self._notice(room, text)+ elif current is not None and current.state == "paused":+ paused_in = next((r for r in rooms if r.id == current.paused_in), None)+ if paused_in is not None and current.paused_agent_name:+ await self._resume(+ paused_in,+ current.paused_agent_name,+ user_id=user_id,+ user_name=user_name,+ )++ async def _resume(+ self, room: Room, agent_name: str, *, user_id: str, user_name: str+ ) -> None:+ """Wake the agent whose request paused the run, in the room it was+ working in, so the sequence carries on without anyone asking it+ again. Said with the authority of the person who let it continue, so+ the agent's addressing judges them, not the platform."""+ text = (+ f"@{agent_name} {user_name} let this run continue. Go ahead with "+ "the room you asked for."+ )+ admin = self._admin(room)+ if admin is None:+ return+ try:+ await admin.send_platform_message(+ room.matrix_room_id, text, on_behalf_of=OnBehalfOf(user_id, user_name)+ )+ except Exception: # noqa: BLE001 - the run is running either way+ logger.warning("Could not wake the agent in %s", room.id, exc_info=True)++ def _admin(self, room: Room) -> AdminClient | None:+ if self._client_lifecycle is None:+ return None+ admins = self._client_lifecycle.get_by_type("admin", room.tenant_id)+ return next((c for c in admins if isinstance(c, AdminClient)), None)++ async def _notice(self, room: Room, text: str) -> None:+ """Best effort: the state has changed whether or not the note lands."""+ admin = self._admin(room)+ if admin is None:+ return+ try:+ await admin.send_notice(room.matrix_room_id, text)+ except Exception: # noqa: BLE001 - a note is not worth failing a stop+ logger.warning("Could not post a run notice in %s", room.id, exc_info=True)diff --git a/core/switch_core/agent_template_ops.py b/core/switch_core/agent_template_ops.pynew file mode 100644index 000000000..b195d7531--- /dev/null+++ b/core/switch_core/agent_template_ops.py@@ -0,0 +1,300 @@+"""The template registry as an agent sees it.++An agent reads what its owner can read: every shared template and the+owner's private ones. An owner's admin standing does not come along, so an+admin's agent does not see other people's private templates. Writing is+narrower than the owner's rights: an agent changes or deletes only what it+saved itself, never its owner's templates or another agent's, because an+agent takes instructions from whoever can address it and should not be a way+to rewrite templates other people or agents depend on.++Every "no" here is an ``AgentRefused`` with a reason code, which the+operation layer reports (see ``agent_refusals``).+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import TYPE_CHECKING, Any, Literal++import yaml++from switch_core.agent_refusals import AgentRefused+from switch_core.agent_templates import agent_slots, template_kind+from switch_core.authz import Principal, can+from switch_core.db.models import Agent, Template, User+from switch_core.db.stores.template_store import TemplateNameTaken, TemplateStore+from switch_core.template_lint import lint_template++if TYPE_CHECKING:+ from sqlalchemy.ext.asyncio import AsyncSession++Visibility = Literal["private", "shared"]++# How an agent's word for who may see a template maps onto the registry's+# pair. "Shared" is read by everyone and changed only by the saver; a+# template anyone may change is not something an agent may make.+_VISIBILITY: dict[str, tuple[str, str]] = {+ "private": ("private", "private"),+ "shared": ("public", "private"),+}+++@dataclass(frozen=True)+class ActingFor:+ """The agent making the request and the owner it acts for."""++ agent: Agent+ owner: User++ @property+ def reader(self) -> Principal:+ return Principal(self.owner.id, False)+++def _visibility(template: Template | Any) -> str:+ return "shared" if template.read_visibility == "public" else "private"+++async def _saved_by(session: AsyncSession, template: Template | Any) -> str:+ if template.created_by_agent_id:+ agent = await session.get(Agent, template.created_by_agent_id)+ return f"agent {agent.name}" if agent else "an agent that no longer exists"+ owner = await session.get(User, template.owner_id)+ return owner.name if owner else "someone"+++def _params(content: str) -> list[dict[str, Any]]:+ """The inputs a document declares, as far as it declares them properly.+ A stored document may be malformed (saving checks only what would block+ it), and an agent still needs to read it to repair it."""+ try:+ doc = yaml.safe_load(content)+ except yaml.YAMLError:+ return []+ raw = doc.get("params") if isinstance(doc, dict) else None+ if not isinstance(raw, dict):+ return []+ return [+ {+ "name": name,+ "type": spec.get("type", "string"),+ "description": spec.get("description"),+ "default": spec.get("default"),+ "required": spec.get("required"),+ }+ for name, spec in raw.items()+ if isinstance(spec, dict)+ ]+++class AgentTemplates:+ def __init__(self, store: TemplateStore, *, max_bytes: int) -> None:+ self._store = store+ self._max_bytes = max_bytes++ # ── Reading ───────────────────────────────────────────────────────────++ async def listing(+ self,+ session: AsyncSession,+ acting: ActingFor,+ *,+ query: str | None,+ kind: str | None,+ ) -> list[dict[str, Any]]:+ rows = await self._store.list_all(+ session, viewer_id=acting.owner.id, is_admin=False, query=query, kind=kind+ )+ return [+ {+ "id": row.id,+ "name": row.name,+ "description": row.description,+ "kind": row.kind,+ "visibility": _visibility(row),+ "saved_by": await _saved_by(session, row),+ "can_edit": row.created_by_agent_id == acting.agent.id,+ }+ for row in rows+ ]++ async def load(+ self, session: AsyncSession, acting: ActingFor, template_id: str+ ) -> Template:+ """A template the agent may read, or ``not_found``: one it may not+ read does not exist for it, as for a person."""+ template = await self._store.get(session, template_id)+ if template is None or not can(acting.reader, "read", template):+ raise AgentRefused(+ "not_found",+ f"No template with id {template_id} that you can see. "+ "list_templates shows the ones you can use.",+ )+ return template++ async def describe(+ self, session: AsyncSession, acting: ActingFor, template_id: str+ ) -> dict[str, Any]:+ template = await self.load(session, acting, template_id)+ try:+ slots = [+ {"name": s.name, "description": s.description}+ for s in agent_slots(template.content)+ ]+ except ValueError:+ slots = []+ return {+ "id": template.id,+ "name": template.name,+ "description": template.description,+ "kind": template.kind,+ "visibility": _visibility(template),+ "saved_by": await _saved_by(session, template),+ "can_edit": template.created_by_agent_id == acting.agent.id,+ "params": _params(template.content),+ "agent_slots": slots,+ "content": template.content,+ }++ # ── Writing ───────────────────────────────────────────────────────────++ def _check_content(self, content: str) -> str:+ size = len(content.encode("utf-8"))+ if size > self._max_bytes:+ raise AgentRefused(+ "too_large",+ f"The template is {size} bytes, over this server's limit of "+ f"{self._max_bytes}.",+ )+ lint = lint_template(content)+ if lint.blocked:+ raise AgentRefused(+ "invalid",+ "The template cannot be saved: "+ + "; ".join(f.message for f in lint.errors if f.blocking),+ )+ try:+ return template_kind(content)+ except ValueError as e:+ raise AgentRefused("invalid", str(e)) from e++ @staticmethod+ def _pair(visibility: str) -> tuple[str, str]:+ pair = _VISIBILITY.get(visibility)+ if pair is None:+ raise AgentRefused(+ "visibility_not_allowed",+ f"Visibility '{visibility}' is not one an agent can set. Use "+ "'private' (only your owner sees it) or 'shared' (everyone "+ "sees it, only you change it). A template anyone may change "+ "can be made in Switch Console.",+ )+ return pair++ @staticmethod+ def _name_taken(name: str) -> AgentRefused:+ return AgentRefused(+ "name_taken",+ f"Your owner already has a template named '{name}', saved by them "+ "or one of their agents. Pick another name.",+ )++ async def save(+ self,+ session: AsyncSession,+ acting: ActingFor,+ *,+ name: str,+ description: str,+ content: str,+ visibility: str,+ ) -> Template:+ read, write = self._pair(visibility)+ kind = self._check_content(content)+ try:+ template = await self._store.create(+ session,+ Template(+ owner_id=acting.owner.id,+ created_by_agent_id=acting.agent.id,+ name=name,+ description=description,+ kind=kind,+ content=content,+ read_visibility=read,+ write_visibility=write,+ ),+ )+ except TemplateNameTaken as e:+ raise self._name_taken(name) from e+ return template++ async def _own(+ self, session: AsyncSession, acting: ActingFor, template_id: str+ ) -> Template:+ template = await self.load(session, acting, template_id)+ if template.created_by_agent_id != acting.agent.id:+ raise AgentRefused(+ "not_yours",+ f"'{template.name}' was saved by {await _saved_by(session, template)}. "+ "An agent can change or delete only the templates it saved "+ "itself. Ask whoever saved it, or save your own version under "+ "another name.",+ )+ return template++ async def update(+ self,+ session: AsyncSession,+ acting: ActingFor,+ template_id: str,+ *,+ name: str | None,+ description: str | None,+ content: str | None,+ visibility: str | None,+ ) -> Template:+ template = await self._own(session, acting, template_id)+ label = name or template.name+ read, write = self._pair(visibility) if visibility is not None else (None, None)+ kind = self._check_content(content) if content is not None else None+ try:+ return await self._store.update_fields(+ session,+ template.id,+ name=name,+ description=description,+ kind=kind,+ content=content,+ read_visibility=read,+ write_visibility=write,+ guard=lambda locked: self._still_own(acting, locked),+ )+ except TemplateNameTaken as e:+ raise self._name_taken(label) from e++ @staticmethod+ def _still_own(acting: ActingFor, locked: Template) -> None:+ """The saver check again, on the row once it is locked: the agent+ could have been deleted, clearing the mark, since it was read."""+ if locked.created_by_agent_id != acting.agent.id:+ raise AgentRefused(+ "not_yours",+ f"'{locked.name}' is no longer yours to change: an agent can "+ "change or delete only the templates it saved itself.",+ )++ async def delete(+ self, session: AsyncSession, acting: ActingFor, template_id: str+ ) -> str:+ template = await self._own(session, acting, template_id)+ locked = await session.get(+ Template, template.id, with_for_update=True, populate_existing=True+ )+ if locked is None:+ raise AgentRefused("not_found", f"No template with id {template_id}.")+ self._still_own(acting, locked)+ name = locked.name+ await self._store.delete(session, locked.id)+ return namediff --git a/core/switch_core/agent_templates.py b/core/switch_core/agent_templates.pynew file mode 100644index 000000000..9a114101b--- /dev/null+++ b/core/switch_core/agent_templates.py@@ -0,0 +1,286 @@+"""Stored templates as the server reads them for an agent.++The registry keeps documents verbatim and never parses them. When an agent+asks what a template is, or asks to run one, something has to: this module+says which kind a document is, which agents it would create, and how to turn+an agent or team template into a room document the server can provision.++The server never creates agents; the Console does, on the machine the agent+runs on. So an agent or team template is runnable here only when every agent+it describes is swapped for an agent that already exists, the way the+Console's Use page does it for "Existing agent". The ``agent:``/``agents:``+block is then dropped and the room half runs like any room template.+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from typing import Any, Literal++import yaml+from pydantic import ValidationError++from switch_core.agent_refusals import AgentRefused+from switch_core.rooms_yaml import (+ CONSOLE_PARAM_TYPES,+ ENTITY_PARAM_TYPES,+ PLACEHOLDER_RE,+ ParamSpec,+ coerce_param,+ interpolate,+)++TemplateKind = Literal["room", "group", "agent"]+++def _load(text: str) -> dict[str, Any]:+ try:+ data = yaml.safe_load(text)+ except yaml.YAMLError as e:+ raise ValueError(f"Invalid YAML: {e}") from e+ if not isinstance(data, dict):+ raise ValueError("A template is a YAML mapping")+ return data+++def _agents(data: dict[str, Any]) -> list[dict[str, Any]]:+ if isinstance(data.get("agent"), dict):+ return [data["agent"]]+ return [a for a in data.get("agents") or [] if isinstance(a, dict)]+++def template_kind(text: str) -> TemplateKind:+ """The kind the registry files a document under, by the Console's rule+ (``kindOf``): a ``group:`` or ``rooms:`` makes a group, then several+ agents a group, one agent an agent template, anything else a room."""+ data = _load(text)+ if "group" in data or isinstance(data.get("rooms"), list):+ return "group"+ agents = _agents(data)+ if agents:+ return "agent" if len(agents) == 1 else "group"+ return "room"+++# Past this a display name is not slugged, as in the Console's agent-slug.+_MAX_SLUG_INPUT = 128+++def _slug(value: str) -> str:+ """An agent name from a display name, the Console's+ ``slugifyAgentNamePart``: what an unnamed agent is created under."""+ if len(value) > _MAX_SLUG_INPUT:+ return ""+ slug = re.sub(r"[^a-z0-9._]+", "-", value.lower())+ return re.sub(r"^[._-]+|[._-]+$", "", slug)+++def _written_name(agent: dict[str, Any]) -> str:+ """How a slot is named in the template: its ``name``, or for an agent+ that has none, its ``display_name``."""+ return str(agent.get("name") or agent.get("display_name") or "")+++def _resolved_name(agent: dict[str, Any], values: dict[str, Any]) -> str:+ """The name the agent would be created under once the inputs are in."""+ if agent.get("name"):+ return str(interpolate(str(agent["name"]), values))+ return _slug(str(interpolate(str(agent.get("display_name") or ""), values)))+++@dataclass(frozen=True)+class AgentSlot:+ """An agent a template would create, which a run fills with an agent+ that already exists. ``name`` is as the template writes it, placeholders+ and all."""++ name: str+ description: str | None+++def agent_slots(text: str) -> list[AgentSlot]:+ return [+ AgentSlot(+ name=_written_name(a),+ description=str(a["description"]) if a.get("description") else None,+ )+ for a in _agents(_load(text))+ ]+++def _known_values(data: dict[str, Any], inputs: dict[str, Any]) -> dict[str, Any]:+ """The values that can be filled in before the server sees the document:+ each given input, else each plain (non-list) default, checked and coerced+ exactly as the server would. A chain or a value nobody gave is left for+ the server to resolve."""+ raw = data.get("params") or {}+ if not isinstance(raw, dict):+ raise ValueError("'params' must be a mapping of param name to its spec")+ try:+ declared = {name: ParamSpec.model_validate(spec) for name, spec in raw.items()}+ except ValidationError as e:+ raise ValueError(f"Invalid param spec: {e}") from e+ undeclared = set(inputs) - set(declared)+ if undeclared:+ raise ValueError(f"Undeclared input(s): {', '.join(sorted(undeclared))}")+ values: dict[str, Any] = {}+ for name, spec in declared.items():+ # An agent, room, bridge or user is left for the server, which checks+ # that it exists; only a slot it names is swapped (see room_document).+ if spec.type in ENTITY_PARAM_TYPES:+ continue+ if inputs.get(name) is not None:+ values[name] = coerce_param(inputs[name], spec, name)+ elif spec.default is not None and not isinstance(spec.default, list):+ values[name] = coerce_param(spec.default, spec, name)+ return values+++def _name_pattern(names: list[str]) -> re.Pattern[str] | None:+ """A mention of any of ``names``, the longest first, counted only when+ neither neighbour could continue an agent name: `my-helper` is not+ `helper`, and "@helper." at the end of a sentence still is. A name inside+ a `{placeholder}` is left alone."""+ if not names:+ return None+ ordered = sorted(names, key=len, reverse=True)+ alternatives = "|".join(re.escape(n) for n in ordered)+ return re.compile(+ rf"(?<![A-Za-z0-9_.{{-])({alternatives})(?![A-Za-z0-9_}}-]|\.[A-Za-z0-9_-])"+ )+++def _placeholders(node: Any, into: set[str]) -> set[str]:+ if isinstance(node, str):+ into.update(m.group(1) for m in PLACEHOLDER_RE.finditer(node))+ elif isinstance(node, dict):+ for k, v in node.items():+ _placeholders(k, into)+ _placeholders(v, into)+ elif isinstance(node, list):+ for item in node:+ _placeholders(item, into)+ return into+++def room_document(+ text: str, filled: dict[str, str], inputs: dict[str, Any]+) -> tuple[str, dict[str, Any]]:+ """The room half of an agent or team template, each agent it would+ create replaced by the existing agent that fills its slot.++ ``filled`` maps a slot, by the name the template writes or the name it+ resolves to with ``inputs``, to an existing agent's name. Returns the+ document and the inputs to run it with. A document with no agents is+ returned as it is. A slot left empty is refused: creating an agent is the+ Console's to do.+ """+ data = _load(text)+ agents = _agents(data)+ if not agents:+ return text, inputs++ values = _known_values(data, inputs)+ replacements: dict[str, str] = {}+ unfilled: list[str] = []+ for agent in agents:+ written = _written_name(agent)+ resolved = _resolved_name(agent, values)+ chosen = filled.get(written) or filled.get(resolved)+ if not chosen:+ unfilled.append(resolved or written or "an unnamed agent")+ continue+ for key in (written, resolved):+ if key:+ replacements[key] = chosen+ if unfilled:+ raise AgentRefused(+ "agent_creation_console_only",+ "Nothing was created: this template creates "+ f"{', '.join(unfilled)}, and creating agents happens in Switch "+ "Console. To run it here, fill each with an agent that already "+ "exists, in `agents`: {slot name: agent name}.",+ )++ room_part = {+ k: data[k] for k in ("room", "group", "rooms", "links", "kickoff") if k in data+ }+ if (+ not room_part.get("room")+ and "group" not in room_part+ and "rooms" not in room_part+ ):+ raise AgentRefused(+ "agent_creation_console_only",+ "Nothing was created: this template only creates an agent, with no "+ "room to run. Creating agents happens in Switch Console.",+ )+ if isinstance(data.get("agent"), dict):+ # A one-agent template names its agent `{agent}` in the room, a value+ # the Console supplies. Here it is the agent that fills the slot.+ values["agent"] = next(iter(replacements.values()))+ # Every value already known is filled in before names are swapped, so a+ # slot reached through a param (`agents: ["{member}"]` with `member`+ # defaulting to a slot) is swapped too. What is left, a chain or an input+ # nobody gave, stays for the server to resolve.+ room_part = interpolate(room_part, values)+ declared = {+ name: spec+ for name, spec in (data.get("params") or {}).items()+ if not (isinstance(spec, dict) and spec.get("type") in CONSOLE_PARAM_TYPES)+ }+ still_used = _placeholders(room_part, set())+ params = {name: spec for name, spec in declared.items() if name in still_used}+ run_inputs = {k: v for k, v in inputs.items() if k in params}+ for name, spec in list(params.items()):+ # An agent param that names a slot, as its input, its default or a+ # candidate in its default list, now names the agent filling it.+ # Only agent params: a bridge or room that shares a slot's name is+ # something else.+ if not isinstance(spec, dict) or spec.get("type") != "agent":+ continue+ given = inputs.get(name)+ if isinstance(given, str) and given in replacements:+ run_inputs[name] = replacements[given]+ default = spec.get("default")+ if isinstance(default, str) and default in replacements:+ params[name] = {**spec, "default": replacements[default]}+ elif isinstance(default, list):+ params[name] = {+ **spec,+ "default": [+ replacements.get(c, c) if isinstance(c, str) else c for c in default+ ],+ }++ pattern = _name_pattern(list(replacements))++ def in_text(value: Any) -> Any:+ if not isinstance(value, str) or pattern is None:+ return value+ return pattern.sub(lambda m: replacements[m.group(1)], value)++ def rename(name: Any) -> Any:+ return replacements.get(name, name) if isinstance(name, str) else name++ rooms = [room_part.get("room")] + list(room_part.get("rooms") or [])+ for room in rooms:+ if not isinstance(room, dict):+ continue+ if isinstance(room.get("agents"), list):+ room["agents"] = [rename(a) for a in room["agents"]]+ if isinstance(room.get("aliases"), dict):+ room["aliases"] = {rename(k): v for k, v in room["aliases"].items()}+ if "kickoff" in room:+ room["kickoff"] = in_text(room["kickoff"])+ if "kickoff" in room_part:+ room_part["kickoff"] = in_text(room_part["kickoff"])++ out: dict[str, Any] = {}+ if isinstance(data.get("version"), int):+ out["version"] = data["version"]+ if params:+ out["params"] = params+ out.update(room_part)+ return yaml.safe_dump(out, sort_keys=False, allow_unicode=True), run_inputsdiff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.pyindex 1abfa2b29..64edffc89 100644--- a/core/switch_core/bridges/agent/operations/definitions.py+++ b/core/switch_core/bridges/agent/operations/definitions.py@@ -12,8 +12,13 @@ and room come from `operations.context`.from __future__ import annotationsimport logging+from collections.abc import AsyncIterator+from contextlib import asynccontextmanagerfrom typing import Any+from switch_core.agent_refusals import AgentRefused, record_refusal+from switch_core.agent_template_ops import ActingFor, AgentTemplates+from switch_core.agent_templates import room_documentfrom switch_core.bridges.agent.api.handlers import parse_timestamp_msfrom switch_core.bridges.agent.operations.context import (bound_rooms,@@ -35,7 +40,9 @@ from switch_core.bridges.agent.protocol.instructions import build_room_instructifrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.protocol.types import IntegrationProfilefrom switch_core.db.models import CollaborationBridge, User-from switch_core.rooms_yaml import GroupSpec+from switch_core.db.stores.template_store import TemplateStore+from switch_core.rooms_yaml import GroupSpec, template_json_schema+from switch_core.template_guide import TEMPLATE_GUIDElogger = logging.getLogger(__name__)@@ -1120,29 +1127,31 @@ async def create_room("""agent_id = get_agent_id()protocol = get_protocol()- result = await protocol.create_moderation_room(- agent_id=agent_id,- name=name,- description=description,- agent_names=agent_names,- include_subagents_for=include_subagents_for,- join_event_listeners=join_event_listeners,- user_names=user_names,- channel_type=channel_type,- bridge_id=bridge_id,- internal_only=internal_only,- admin_mode=admin_mode,- security_config=security_config,- instructions=instructions,- reference_ids=reference_ids,- package_ids=package_ids,- linked_rooms=linked_rooms,- read_visibility=read_visibility,- write_visibility=write_visibility,- group_name=group_name,- roles=roles,- aliases=aliases,- )+ async with _refusals_reported("create_room"):+ result = await protocol.create_moderation_room(+ agent_id=agent_id,+ name=name,+ description=description,+ agent_names=agent_names,+ include_subagents_for=include_subagents_for,+ join_event_listeners=join_event_listeners,+ user_names=user_names,+ channel_type=channel_type,+ bridge_id=bridge_id,+ internal_only=internal_only,+ admin_mode=admin_mode,+ security_config=security_config,+ instructions=instructions,+ reference_ids=reference_ids,+ package_ids=package_ids,+ linked_rooms=linked_rooms,+ read_visibility=read_visibility,+ write_visibility=write_visibility,+ group_name=group_name,+ roles=roles,+ aliases=aliases,+ from_room_id=await connected_room(),+ )return {"id": result.room.id,"name": result.room.name,@@ -1671,6 +1680,15 @@ async def create_room_from_yaml(result provisioned as the calling agent's owner (an ownerless agentcannot provision rooms). Server-provided ``{$creator}`` names the owner.+ A ``kickoff:`` is posted with your authority, not your owner's, and with+ the run so far appended: the rooms that led here and who made them. The+ call is refused, with nothing created, when the kickoff mentions an agent+ that does not accept messages from you, when you ask for a room with the+ same kickoff as one you already made further up the same path (the run is+ then paused until your owner lets it continue), when the run was paused+ or stopped, or while another room you asked for is still being created.+ The refusal says which, and what to do.+Args:yaml: The template text. A top-level ``room:`` makes one room; a``group:`` with a ``rooms:`` list (and optional ``links:``) makes@@ -1685,55 +1703,343 @@ async def create_room_from_yaml(failed_attachments}``. For a group: ``{group_id, group_name,rooms: [...], errors: [...]}``."""+ async with _refusals_reported("create_room_from_yaml"):+ return await _provision_as_agent(yaml, inputs)+++async def _acting_for() -> ActingFor:+ """The calling agent and the owner it acts for, or a clear error for an+ agent with no owner."""agent_id = get_agent_id()protocol = get_protocol()-async with protocol.session_factory() as session:agent = await protocol.agent_store.get(session, agent_id)if agent is None:raise ValueError(f"Unknown agent: {agent_id}")- if agent.owner_id is None:- raise ValueError(- f"Agent {agent_id} has no owner and cannot provision rooms"- )- owner = await session.get(User, agent.owner_id)+ owner = await session.get(User, agent.owner_id) if agent.owner_id else Noneif owner is None:raise ValueError(f"Agent {agent_id} has no owner and cannot provision rooms")- owner_id = owner.id- owner_name = owner.name- owner_email = owner.email- # The owner's standing in this tenant, the same bit the gateway's- # from-yaml route derives, so a document provisions the same way- # whichever way it arrives.- owner_is_admin = await protocol.user_store.administers(session, owner)+ return ActingFor(agent=agent, owner=owner)+++@asynccontextmanager+async def _refusals_reported(operation_name: str) -> AsyncIterator[None]:+ """Report a request refused on purpose, then let the refusal reach the+ agent as it would have anyway (see ``agent_refusals``)."""+ try:+ yield+ except AgentRefused as refusal:+ protocol = get_protocol()+ agent_id = get_agent_id()+ async with protocol.session_factory() as session:+ agent = await protocol.agent_store.get(session, agent_id)+ record_refusal(+ getattr(protocol, "telemetry", None),+ agent_id=agent_id,+ agent_name=agent.name if agent else agent_id,+ operation=operation_name,+ refusal=refusal,+ )+ raise+++async def _provision_as_agent(+ yaml: str,+ inputs: dict[str, Any] | None,+ *,+ template_name: str | None = None,+) -> dict[str, Any]:+ """Create the rooms a document describes, as the calling agent: the one+ path for a document an agent writes and a template it runs, so the run+ guards in ``agent_runs`` apply the same to both."""+ protocol = get_protocol()+ acting = await _acting_for()+ agent, owner = acting.agent, acting.owner+ # An agent acts for its owner but not with the owner's admin reach: a+ # document it writes or a template it runs attaches only what the owner+ # could attach as a member, never another person's private reference.rooms_yaml = protocol.room_yaml_service()inputs = await rooms_yaml.resolve_defaults(yaml, inputs)builtins = await rooms_yaml.builtins_for(- user_id=owner_id, name=owner_name, email=owner_email, text=yaml, inputs=inputs+ user_id=owner.id, name=owner.name, email=owner.email, text=yaml, inputs=inputs)parsed = rooms_yaml.parse_template(yaml, inputs=inputs, builtins=builtins)await rooms_yaml.check_entity_params(parsed)- if isinstance(parsed.spec, GroupSpec):- group_result = await rooms_yaml.provision_group(+ room_specs = (+ [(r, r.kickoff) for r in parsed.spec.rooms]+ if isinstance(parsed.spec, GroupSpec)+ else [(parsed.spec, parsed.kickoff)]+ )+ await _require_agents_exist([n for spec, _ in room_specs for n in spec.agents])+ kickoffs = [+ (text, list(spec.agents), dict(spec.aliases or {}))+ for spec, text in room_specs+ if text+ ]+ async with protocol.run_service().agent_creating(+ agent,+ owner_name=owner.name,+ from_room_id=await connected_room(),+ kickoffs=kickoffs,+ ) as origin:+ if isinstance(parsed.spec, GroupSpec):+ group_result = await rooms_yaml.provision_group(+ parsed.spec,+ user_id=owner.id,+ is_admin=False,+ creator_name=builtins["$creator"],+ origin=origin,+ template_name=template_name,+ )+ return group_result.model_dump()+ result = await rooms_yaml.provision(parsed.spec,- user_id=owner_id,- is_admin=owner_is_admin,+ kickoff=parsed.kickoff,+ user_id=owner.id,+ is_admin=False,creator_name=builtins["$creator"],+ origin=origin,+ template_name=template_name,)- return group_result.model_dump()- result = await rooms_yaml.provision(- parsed.spec,- kickoff=parsed.kickoff,- user_id=owner_id,- is_admin=owner_is_admin,- creator_name=builtins["$creator"],- )return result.model_dump()+async def _require_agents_exist(names: list[str]) -> None:+ """Every agent the rooms name must exist, checked before anything is+ created and reported all at once rather than one per try."""+ protocol = get_protocol()+ wanted = list(dict.fromkeys(names))+ async with protocol.session_factory() as session:+ found = {+ a.name for a in await protocol.agent_store.get_by_names(session, wanted)+ }+ missing = [n for n in wanted if n not in found]+ if missing:+ raise AgentRefused(+ "missing_agents",+ "Nothing was created: no agent is called "+ f"{', '.join(missing)}. list_agents shows the ones that exist.",+ )+++def _agent_templates() -> AgentTemplates:+ protocol = get_protocol()+ return AgentTemplates(TemplateStore(), max_bytes=protocol.config.template_max_bytes)+++@operation+async def get_template_guide() -> dict[str, Any]:+ """How to write a template: the language, and the schema this server+ checks documents against.++ Read it before writing a document for ``create_room_from_yaml`` or+ ``save_template``. ``guide`` explains the keys, params, placeholders and+ kickoff with an example; ``schema`` is the JSON Schema of the room and+ group documents the server accepts.++ Returns:+ ``{guide, schema}``.+ """+ return {"guide": TEMPLATE_GUIDE, "schema": template_json_schema()}+++@operation+async def list_templates(+ query: str | None = None,+ kind: str | None = None,+) -> list[dict[str, Any]]:+ """List the templates saved on this workspace that you can use.++ That is every shared template plus your owner's private ones. Each row+ says who saved it (a person, or which agent) and ``can_edit``: whether+ you may change or delete it, which is true only for templates you saved.++ Args:+ query: Only templates whose name or description contains this.+ kind: Only this kind: ``room``, ``group`` or ``agent``.++ Returns:+ ``[{id, name, description, kind, visibility, saved_by, can_edit}]``,+ newest first.+ """+ protocol = get_protocol()+ async with _refusals_reported("list_templates"):+ acting = await _acting_for()+ async with protocol.session_factory() as session:+ return await _agent_templates().listing(+ session, acting, query=query, kind=kind+ )+++@operation+async def get_template(template_id: str) -> dict[str, Any]:+ """Read one saved template: the document, the inputs it takes, and the+ agents it would create.++ Use it before ``run_template`` to know what to fill in. ``params`` are+ the inputs (``required`` is as the template writes it; a param with no+ default usually needs a value). ``agent_slots`` lists the agents an agent+ or team template would create: the server cannot create agents, so to run+ one you fill each slot with an existing agent.++ Args:+ template_id: The id from ``list_templates``.++ Returns:+ ``{id, name, description, kind, visibility, saved_by, can_edit,+ params: [{name, type, description, default, required}],+ agent_slots: [{name, description}], content}``.+ """+ protocol = get_protocol()+ async with _refusals_reported("get_template"):+ acting = await _acting_for()+ async with protocol.session_factory() as session:+ return await _agent_templates().describe(session, acting, template_id)+++@operation+async def run_template(+ template_id: str,+ inputs: dict[str, Any] | None = None,+ agents: dict[str, str] | None = None,+) -> dict[str, Any]:+ """Create the rooms a saved template describes, as you, the same way+ ``create_room_from_yaml`` does with a document you write.++ Everything ``create_room_from_yaml`` says about kickoffs and refusals+ applies here too, and the run is listed under the template's name in+ Switch Console. An agent or team template runs only when each agent it+ would create is filled with an agent that already exists: creating agents+ happens in Switch Console.++ Args:+ template_id: The id from ``list_templates``.+ inputs: Values for the template's params (see ``get_template``).+ agents: For an agent or team template, which existing agent fills+ each slot: ``{slot name: agent name}``, the slot named as+ ``get_template`` lists it or as it reads with your inputs.++ Returns:+ As ``create_room_from_yaml``: for a room ``{room_id, room_name, ...}``,+ for a group ``{group_id, group_name, rooms, errors}``.+ """+ protocol = get_protocol()+ async with _refusals_reported("run_template"):+ acting = await _acting_for()+ async with protocol.session_factory() as session:+ template = await _agent_templates().load(session, acting, template_id)+ content, name = template.content, template.name+ document, run_inputs = room_document(content, agents or {}, inputs or {})+ return await _provision_as_agent(+ document, run_inputs or None, template_name=name+ )+++@operation+async def save_template(+ name: str,+ description: str,+ yaml: str,+ visibility: str = "private",+) -> dict[str, Any]:+ """Save a template to this workspace, so it can be found and run again.++ It is saved for your owner and marked as saved by you; only you can+ change or delete it afterwards. Its kind (room, group or agent) is read+ from the document.++ Args:+ name: A name your owner does not already use for a template.+ description: One line on what it creates.+ yaml: The template document, as ``create_room_from_yaml`` takes it.+ visibility: ``private`` (only your owner sees it) or ``shared``+ (everyone on the workspace sees it, only you change it).++ Returns:+ ``{id, name, kind, visibility}``.+ """+ protocol = get_protocol()+ async with _refusals_reported("save_template"):+ acting = await _acting_for()+ async with protocol.session_factory() as session:+ template = await _agent_templates().save(+ session,+ acting,+ name=name,+ description=description,+ content=yaml,+ visibility=visibility,+ )+ await session.commit()+ return {+ "id": template.id,+ "name": template.name,+ "kind": template.kind,+ "visibility": visibility,+ }+++@operation+async def update_template(+ template_id: str,+ name: str | None = None,+ description: str | None = None,+ yaml: str | None = None,+ visibility: str | None = None,+) -> dict[str, Any]:+ """Change a template you saved. Only the fields you pass change.++ Templates saved by a person, or by another agent, cannot be changed by+ you; save your own version under another name instead.++ Returns:+ ``{id, name, kind, visibility, version}``.+ """+ protocol = get_protocol()+ async with _refusals_reported("update_template"):+ acting = await _acting_for()+ async with protocol.session_factory() as session:+ template = await _agent_templates().update(+ session,+ acting,+ template_id,+ name=name,+ description=description,+ content=yaml,+ visibility=visibility,+ )+ await session.commit()+ return {+ "id": template.id,+ "name": template.name,+ "kind": template.kind,+ "visibility": "shared"+ if template.read_visibility == "public"+ else "private",+ "version": template.version,+ }+++@operation+async def delete_template(template_id: str) -> dict[str, Any]:+ """Delete a template you saved. Templates saved by a person or another+ agent cannot be deleted by you.++ Returns:+ ``{id, name}`` of the deleted template.+ """+ protocol = get_protocol()+ async with _refusals_reported("delete_template"):+ acting = await _acting_for()+ async with protocol.session_factory() as session:+ name = await _agent_templates().delete(session, acting, template_id)+ await session.commit()+ return {"id": template_id, "name": name}++@operationasync def list_agents(name_contains: str | None = None,diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.pyindex ad551d5bf..5b738ae11 100644--- a/core/switch_core/bridges/agent/protocol/service.py+++ b/core/switch_core/bridges/agent/protocol/service.py@@ -112,6 +112,7 @@ from switch_core.transport import (if TYPE_CHECKING:from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+ from switch_core.agent_runs import RunServicefrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)@@ -2450,10 +2451,15 @@ class ProtocolService:include_subagents_for: list[str] | None = None,join_event_listeners: list[str] | None = None,aliases: dict[str, str] | None = None,+ from_room_id: str | None = None,) -> RoomCreateResult:"""Create a room. The caller agent's owner_id is used as the actinguser for attachment authorization and as the new room's owner.+ `from_room_id` is the room the agent is working in: the new room goes+ into that room's run (see `agent_runs`), and is refused if the run is+ paused or stopped or the agent is already creating a room.+`group_name`, when given, files the room under an existing room group;it is resolved to a group id here (agents work in names, not ids)."""from switch_core.room_service import (@@ -2467,49 +2473,60 @@ class ProtocolService:session, agent_id)group_id = await self._resolve_group_name(session, group_name)+ owner = await session.get(User, agent.owner_id) if agent.owner_id else Noneif (reference_ids or package_ids) and agent.owner_id is None:raise ValueError(f"Agent {agent_id} has no owner_id and cannot attach references ""or packages on creation")- config = RoomCreateConfig(- name=name,- description=description,- agent_names=agent_names,- include_subagents_for=include_subagents_for,- join_event_listeners=join_event_listeners,- user_names=user_names,- channel_type=channel_type, # type: ignore[arg-type]- bridge_id=bridge_id,- internal_only=internal_only,- admin_mode=admin_mode,- protection_config=security_config,- instructions=instructions,- created_by=agent.owner_id,- created_by_kind="agent",- owner_id=agent.owner_id,- group_id=group_id,- read_visibility=read_visibility,- write_visibility=write_visibility,- reference_ids=reference_ids,- package_ids=package_ids,- linked_rooms=(- [LinkedRoomSpec(**lr) for lr in linked_rooms] if linked_rooms else None- ),- roles=([RoleSpec(**r) for r in roles] if roles else None),- aliases=aliases,- acting_user_id=agent.owner_id,- acting_is_admin=owner_is_admin,- )- try:- result = await self.room_service.create_room(config)- except ValueError as e:- raise ValueError(f"Failed to create room: {str(e)}") from e- except PermissionError as e:- raise PermissionError(str(e)) from e- except RuntimeError as e:- raise RuntimeError(f"Room service error: {str(e)}") from e+ async with self.run_service().agent_creating(+ agent,+ owner_name=owner.name if owner else None,+ from_room_id=from_room_id,+ ) as origin:+ config = RoomCreateConfig(+ name=name,+ description=description,+ agent_names=agent_names,+ include_subagents_for=include_subagents_for,+ join_event_listeners=join_event_listeners,+ user_names=user_names,+ channel_type=channel_type, # type: ignore[arg-type]+ bridge_id=bridge_id,+ internal_only=internal_only,+ admin_mode=admin_mode,+ protection_config=security_config,+ instructions=instructions,+ created_by=agent.owner_id,+ created_by_kind="agent",+ created_by_agent_id=agent.id,+ parent_room_id=origin.parent_room_id,+ run_id=origin.run_id,+ owner_id=agent.owner_id,+ group_id=group_id,+ read_visibility=read_visibility,+ write_visibility=write_visibility,+ reference_ids=reference_ids,+ package_ids=package_ids,+ linked_rooms=(+ [LinkedRoomSpec(**lr) for lr in linked_rooms]+ if linked_rooms+ else None+ ),+ roles=([RoleSpec(**r) for r in roles] if roles else None),+ aliases=aliases,+ acting_user_id=agent.owner_id,+ acting_is_admin=owner_is_admin,+ )+ try:+ result = await self.room_service.create_room(config)+ except ValueError as e:+ raise ValueError(f"Failed to create room: {str(e)}") from e+ except PermissionError as e:+ raise PermissionError(str(e)) from e+ except RuntimeError as e:+ raise RuntimeError(f"Room service error: {str(e)}") from ereturn resultasync def _resolve_group_name(@@ -2611,6 +2628,17 @@ class ProtocolService:except ValueError as e:raise ValueError(f"Failed to add users: {str(e)}") from e+ def run_service(self) -> RunService:+ """Runs over this service's stores; see ``agent_runs``."""+ from switch_core.agent_runs import RunService++ return RunService(+ room_store=self.room_store,+ agent_store=self.agent_store,+ session_factory=self.session_factory,+ client_lifecycle=self.client_lifecycle,+ )+def room_yaml_service(self) -> RoomYamlService:"""The template engine over this service's collaborators.diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.pyindex 2e64cfba9..f22df2487 100644--- a/core/switch_core/bridges/collaboration/bridge_core.py+++ b/core/switch_core/bridges/collaboration/bridge_core.py@@ -1823,9 +1823,9 @@ class BridgeCore:if (person is not Noneand not _is_thread_reply(event_content)- and f"@{person.name}" not in body+ and person.label not in body):- body = f"On behalf of @{person.name}:\n\n{body}"+ body = f"On behalf of {person.label}:\n\n{body}"message_ref = await self._adapter.admin_message(channel_id,body,diff --git a/core/switch_core/clients/admin_client.py b/core/switch_core/clients/admin_client.pyindex 8eefd8547..b50ac07b8 100644--- a/core/switch_core/clients/admin_client.py+++ b/core/switch_core/clients/admin_client.py@@ -152,6 +152,11 @@ class AdminClient(ClientBase[ClientConfig]):marker_value["on_behalf_of"] = {"user_id": on_behalf_of.user_id,"name": on_behalf_of.name,+ **(+ {"agent_id": on_behalf_of.agent_id}+ if on_behalf_of.agent_id is not None+ else {}+ ),}if reply_in_channel:# Only meaningful for a threaded message: the agents it addresses@@ -167,6 +172,17 @@ class AdminClient(ClientBase[ClientConfig]):# ── Admin notices ─────────────────────────────────────────────────────────+ async def send_notice(self, room_id: str, body: str) -> None:+ """Post a system notice about the room's run: that it was paused,+ continued or stopped. Like every admin message it addresses nobody,+ so no agent wakes on it."""+ await self._send_admin(+ room_id,+ body,+ message_type=AdminMessageType.RUN_NOTICE,+ thread_root_id=None,+ )+async def _warn_unreachable_roles(self,room: RoomRef,diff --git a/core/switch_core/clients/admin_messages.py b/core/switch_core/clients/admin_messages.pyindex 18a585681..d355aca5b 100644--- a/core/switch_core/clients/admin_messages.py+++ b/core/switch_core/clients/admin_messages.py@@ -24,17 +24,33 @@ ADMIN_MARKER = "com.switch.admin"## Value: {} for the platform's own message, or {"on_behalf_of": {"user_id",# "name"}} when it speaks with a person's authority (a template's kickoff).-# The authority is per message: the addressed agent's policy is evaluated-# for that person when the event arrives, and nothing is granted beyond it.-# Only server-side code writes the marker.+# With an "agent_id" as well, the message speaks for that agent: a kickoff in+# a room an agent created. The authority is per message: the addressed+# agent's policy is evaluated for that person or agent when the event+# arrives, and nothing is granted beyond it. Only server-side code writes+# the marker.PLATFORM_MARKER = "com.switch.platform"class OnBehalfOf(NamedTuple):- """The person a platform message carries the authority of."""+ """Whose authority a platform message carries.++ A person, or an agent when ``agent_id`` is set. For an agent, ``user_id``+ is its owner and ``name`` is the agent's name. The distinction matters to+ addressing: a message for an agent is judged as that agent speaking, so+ it cannot wake an agent that answers only its owner.+ """user_id: strname: str+ agent_id: str | None = None++ @property+ def label(self) -> str:+ """How a message names whom it speaks for. A person is written as a+ mention. An agent is not: the mention would address it, and it would+ wake on the kickoff of the room it has just created."""+ return self.name if self.agent_id is not None else f"@{self.name}"def platform_replies_in_channel(content: Mapping[str, object]) -> bool:@@ -60,7 +76,12 @@ def platform_on_behalf_of(content: Mapping[str, object]) -> OnBehalfOf | None:name = person.get("name")if not isinstance(user_id, str) or not user_id:return None- return OnBehalfOf(user_id, name if isinstance(name, str) and name else user_id)+ agent_id = person.get("agent_id")+ return OnBehalfOf(+ user_id,+ name if isinstance(name, str) and name else user_id,+ agent_id if isinstance(agent_id, str) and agent_id else None,+ )class AdminMessageType(StrEnum):@@ -73,6 +94,7 @@ class AdminMessageType(StrEnum):COMMAND_RESULT = "command_result"SELF_MENTION_UNALIASED = "self_mention_unaliased"NO_AGENTS = "no_agents"+ RUN_NOTICE = "run_notice"def admin_extra_content(message_type: AdminMessageType | None) -> dict[str, object]:diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex c31d70019..0a175260a 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -639,6 +639,9 @@ class Room(TenantScoped, Base):# and the ON DELETE SET NULL when a group is removed both scan the# table. Mirrors ix_agents_parent_agent_id.Index("ix_rooms_group_id", "group_id"),+ # A run is listed, checked and stopped by its root on every agent+ # create and every look at Recently used.+ Index("ix_rooms_run_id", "run_id"),UniqueConstraint("tenant_id", "matrix_room_id", name="uq_rooms_tenant_matrix_room_id"),@@ -654,6 +657,18 @@ class Room(TenantScoped, Base):name="fk_rooms_group",ondelete="SET NULL (group_id)",),+ ForeignKeyConstraint(+ ["tenant_id", "created_by_agent_id"],+ ["agents.tenant_id", "agents.id"],+ name="fk_rooms_created_by_agent",+ ondelete="SET NULL (created_by_agent_id)",+ ),+ ForeignKeyConstraint(+ ["tenant_id", "parent_room_id"],+ ["rooms.tenant_id", "rooms.id"],+ name="fk_rooms_parent_room",+ ondelete="SET NULL (parent_room_id)",+ ),)id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)@@ -672,6 +687,23 @@ class Room(TenantScoped, Base):created_by: Mapped[str | None] = mapped_column(Text, ForeignKey("users.id"), nullable=True)+ # The agent that created the room through an agent operation. NULL for a+ # room a person created. `created_by` is the agent's owner in both cases.+ created_by_agent_id: Mapped[str | None] = mapped_column(Text, nullable=True)+ # Where an agent-created room sits in its run (see `agent_runs`): the+ # room the agent was working in when it asked, and the root of the chain,+ # a room a person made. NULL for a person's room, which is its own root.+ parent_room_id: Mapped[str | None] = mapped_column(Text, nullable=True)+ run_id: Mapped[str | None] = mapped_column(Text, nullable=True)+ # The template the room came from, when it came from one: its registry+ # name, or the name the creator gave a pasted document.+ template_name: Mapped[str | None] = mapped_column(Text, nullable=True)+ # A fingerprint of the kickoff an agent posted here. Never shown; it is+ # how the same request made twice on one path is recognised.+ kickoff_hash: Mapped[str | None] = mapped_column(Text, nullable=True)+ # On a run's root only: whether agents may keep creating rooms in the+ # run. NULL means running. See `agent_runs.RunControl`.+ run_control: Mapped[dict | None] = mapped_column(JSONB, nullable=True)group_id: Mapped[str | None] = mapped_column(Text, nullable=True)owner_id: Mapped[str | None] = mapped_column(Text, ForeignKey("users.id"), nullable=True@@ -981,6 +1013,12 @@ class Template(TenantScoped, Base):# scoping the name to the owner already scopes it to the tenant.UniqueConstraint("owner_id", "name", name="uq_templates_owner_name"),UniqueConstraint("id", "tenant_id", name="uq_templates_id_tenant"),+ ForeignKeyConstraint(+ ["tenant_id", "created_by_agent_id"],+ ["agents.tenant_id", "agents.id"],+ name="fk_templates_created_by_agent",+ ondelete="SET NULL (created_by_agent_id)",+ ),)id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)@@ -999,6 +1037,10 @@ class Template(TenantScoped, Base):)content: Mapped[str] = mapped_column(Text, nullable=False)version: Mapped[int] = mapped_column(Integer, nullable=False, server_default="1")+ # The agent that saved it through an agent operation, NULL for a person.+ # ``owner_id`` is the agent's owner either way; only this agent may change+ # or delete what it saved (see ``agent_template_ops``).+ created_by_agent_id: Mapped[str | None] = mapped_column(Text, nullable=True)created_at: Mapped[str] = mapped_column(DateTime(timezone=True), server_default=func.now(), nullable=False)diff --git a/core/switch_core/db/stores/room_store.py b/core/switch_core/db/stores/room_store.pyindex 65c135aaa..f742cb772 100644--- a/core/switch_core/db/stores/room_store.py+++ b/core/switch_core/db/stores/room_store.py@@ -76,6 +76,69 @@ class RoomStore:)return result.scalar_one_or_none()+ async def run_rooms(self, session: AsyncSession, root_id: str) -> list[Room]:+ """Every room of the run rooted at ``root_id``, the root first, then in+ the order they were created. Archived rooms are included: a run is a+ record of what happened."""+ result = await session.execute(+ select(Room)+ .where(or_(Room.id == root_id, Room.run_id == root_id))+ .order_by(Room.run_id.is_not(None), Room.created_at)+ )+ return list(result.scalars().all())++ async def path_to_root(self, session: AsyncSession, room_id: str) -> list[Room]:+ """``room_id`` and each room above it, up to the root of its run.++ Parents are set when a room is created and never change, so the walk+ cannot loop; the bound is only there so a corrupted row cannot hang a+ request."""+ path: list[Room] = []+ current: str | None = room_id+ while current is not None and len(path) < 1000:+ room = await session.get(Room, current)+ if room is None:+ break+ path.append(room)+ current = room.parent_room_id+ return path++ async def set_run_control(+ self, session: AsyncSession, root_id: str, control: dict[str, object] | None+ ) -> None:+ await session.execute(+ update(Room).where(Room.id == root_id).values(run_control=control)+ )++ async def recent_run_roots(+ self, session: AsyncSession, *, user_id: str | None, limit: int+ ) -> list[str]:+ """The roots of the runs most recently added to, newest first.++ A run is a template a person ran or a room an agent created, with+ everything agents created below it. With ``user_id`` only the runs that+ user took part in count: a template they ran, or a room one of their+ agents created (``created_by`` is the agent's owner on that path).+ Without it, every run, which is what an admin sees."""+ root = sa_func.coalesce(Room.run_id, Room.id)+ in_run = or_(+ Room.run_id.is_not(None),+ Room.template_name.is_not(None),+ Room.created_by_agent_id.is_not(None),+ )+ stmt = select(root).where(in_run)+ if user_id is not None:+ stmt = stmt.where(+ Room.created_by == user_id,+ or_(+ Room.created_by_agent_id.is_not(None),+ Room.template_name.is_not(None),+ ),+ )+ stmt = stmt.group_by(root).order_by(sa_func.max(Room.created_at).desc())+ result = await session.execute(stmt.limit(limit))+ return [row[0] for row in result.all()]+async def get_all(self, session: AsyncSession, *, include_archived: bool = False) -> list[Room]:diff --git a/core/switch_core/db/stores/template_store.py b/core/switch_core/db/stores/template_store.pyindex d6c43bfe6..89301c22b 100644--- a/core/switch_core/db/stores/template_store.py+++ b/core/switch_core/db/stores/template_store.py@@ -49,6 +49,7 @@ class TemplateListing:size_bytes: intcreated_at: objectupdated_at: object+ created_by_agent_id: str | None = Noneclass TemplateStore:@@ -131,6 +132,7 @@ class TemplateStore:func.octet_length(Template.content).label("size_bytes"),Template.created_at,Template.updated_at,+ Template.created_by_agent_id,).where(*conditions).order_by(Template.created_at.desc(), Template.id.asc())diff --git a/core/switch_core/delivery/addressing.py b/core/switch_core/delivery/addressing.pyindex 2f9d81097..8ae2cb93e 100644--- a/core/switch_core/delivery/addressing.py+++ b/core/switch_core/delivery/addressing.py@@ -417,6 +417,14 @@ class AddressingResolver:return SenderPrincipal("user", external_user.id, claimants, None)if client.type == "admin":person = platform_on_behalf_of(content or {})+ if person is not None and person.agent_id is not None:+ # The message speaks for an agent, so the policy is asked what+ # it would say to that agent. An agent that no longer exists+ # leaves a bare platform message, which is denied by default.+ speaker = await self._agent_store.get(session, person.agent_id)+ if speaker is not None:+ return SenderPrincipal("agent", speaker.id, [], speaker.owner_id)+ person = Nonereturn SenderPrincipal("platform",client.id,diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.pyindex 038baf073..83d4ea3c4 100644--- a/core/switch_core/gateway/app.py+++ b/core/switch_core/gateway/app.py@@ -46,6 +46,7 @@ from switch_core.gateway.references import router as references_routerfrom switch_core.gateway.room_groups import router as room_groups_routerfrom switch_core.gateway.room_links import router as room_links_routerfrom switch_core.gateway.rooms import router as rooms_router+from switch_core.gateway.template_runs import router as template_runs_routerfrom switch_core.gateway.templates import router as templates_routerfrom switch_core.gateway.tenants import router as tenants_routerfrom switch_core.room_service import RoomService@@ -134,6 +135,7 @@ def create_gateway_app(app.include_router(documents_router, tags=["documents"])app.include_router(packages_router, tags=["packages"])app.include_router(templates_router, tags=["templates"])+ app.include_router(template_runs_router, tags=["templates"])app.include_router(ecosystem_router, prefix="/ecosystem", tags=["ecosystem"])app.include_router(messaging_installs_router,diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.pyindex 409ada3e3..ed992f00f 100644--- a/core/switch_core/gateway/rooms.py+++ b/core/switch_core/gateway/rooms.py@@ -402,8 +402,9 @@ async def create_room_from_yaml(body is the template text. Only defaults-only templates work here(no way to pass inputs).* **JSON** (``application/json``): ``{"yaml": "<template text>",- "inputs": {...}}`` where ``inputs`` supplies values for declared- ``params:``.+ "inputs": {...}, "template_name": "..."}`` where ``inputs`` supplies+ values for declared ``params:`` and ``template_name`` is what the run is+ listed under in Recently used (the document's own name when absent)."""content_type = request.headers.get("content-type", "")try:@@ -415,9 +416,13 @@ async def create_room_from_yaml(if not isinstance(text, str):raise ValueError("'yaml' must be a string")inputs = payload.get("inputs")+ template_name = payload.get("template_name")+ if template_name is not None and not isinstance(template_name, str):+ raise ValueError("'template_name' must be a string")else:text = (await request.body()).decode("utf-8")inputs = None+ template_name = Noneinputs = await rooms_yaml.resolve_defaults(text, inputs)builtins = await rooms_yaml.builtins_for(user_id=user.id, name=user.name, email=user.email, text=text, inputs=inputs@@ -430,6 +435,7 @@ async def create_room_from_yaml(user_id=user.id,is_admin=is_admin,creator_name=builtins["$creator"],+ template_name=template_name or parsed.spec.group.name,)return await rooms_yaml.provision(parsed.spec,@@ -437,6 +443,7 @@ async def create_room_from_yaml(user_id=user.id,is_admin=is_admin,creator_name=builtins["$creator"],+ template_name=template_name or parsed.spec.name,)except ValueError as e:raise HTTPException(status_code=400, detail=str(e)) from ediff --git a/core/switch_core/gateway/template_runs.py b/core/switch_core/gateway/template_runs.pynew file mode 100644index 000000000..fcaa5b925--- /dev/null+++ b/core/switch_core/gateway/template_runs.py@@ -0,0 +1,270 @@+"""Runs, as a person sees them: the rooms a template or an agent created, as+a tree, with the controls to let a paused run continue or stop one.++What a run is, and when the server pauses one, is in ``agent_runs``. This is+the read and control surface the Console's Recently used list is built on.+"""++from __future__ import annotations++from datetime import datetime+from typing import Annotated++from fastapi import APIRouter, Depends, HTTPException+from pydantic import BaseModel+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.agent_runs import RunRefused, RunState, run_control+from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.db.models import Room, SessionActivityItem, User+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.db.stores.session_activity_store import TURN_ITEM_ID+from switch_core.gateway.auth import get_current_user, get_tenant_is_admin+from switch_core.gateway.dependencies import (+ get_agent_store,+ get_protocol,+ get_room_store,+ get_session,+)+from switch_core.sessions.contract import TURN_ENDED++router = APIRouter()++# Recently used shows a handful of runs, not a history.+RECENT_RUNS = 20+++class TemplateRunRoom(BaseModel):+ id: str+ name: str+ parent_room_id: str | None+ created_by_agent_id: str | None+ created_by_agent_name: str | None+ template_name: str | None+ created_at: datetime+ archived: bool+++class TemplateRun(BaseModel):+ root_room_id: str+ root_room_name: str+ # Who started it: the person who made the root room, or the agent that+ # did when the run began with an agent working in no room.+ started_by_name: str | None+ template_name: str | None+ started_at: datetime+ last_activity_at: datetime+ state: RunState+ # An agent is mid-turn in one of the run's rooms right now.+ working: bool+ reason: str | None+ changed_by_name: str | None+ paused_repeat_of: str | None+ can_control: bool+ rooms: list[TemplateRunRoom]+++async def _run(+ session: AsyncSession,+ protocol: ProtocolService,+ room_store: RoomStore,+ agent_store: AgentStore,+ root_id: str,+ *,+ user: User,+ is_admin: bool,+) -> TemplateRun | None:+ rooms = await room_store.run_rooms(session, root_id)+ root = next((r for r in rooms if r.id == root_id), None)+ if root is None:+ return None+ agent_names: dict[str, str] = {}+ for agent_id in {r.created_by_agent_id for r in rooms if r.created_by_agent_id}:+ agent = await agent_store.get(session, agent_id)+ if agent is not None:+ agent_names[agent_id] = agent.name+ control = run_control(root)+ if root.created_by_agent_id is not None:+ started_by = agent_names.get(root.created_by_agent_id)+ else:+ person = await session.get(User, root.created_by) if root.created_by else None+ started_by = person.name if person else None++ def entry(room: Room) -> TemplateRunRoom:+ return TemplateRunRoom(+ id=room.id,+ name=room.name,+ parent_room_id=room.parent_room_id if room.id != root_id else None,+ created_by_agent_id=room.created_by_agent_id,+ created_by_agent_name=agent_names.get(room.created_by_agent_id or ""),+ template_name=room.template_name,+ created_at=room.created_at, # type: ignore[arg-type]+ archived=room.archived_at is not None,+ )++ return TemplateRun(+ root_room_id=root.id,+ root_room_name=root.name,+ started_by_name=started_by,+ template_name=next((r.template_name for r in rooms if r.template_name), None),+ started_at=root.created_at, # type: ignore[arg-type]+ last_activity_at=max(r.created_at for r in rooms), # type: ignore[type-var]+ state=control.state if control else "running",+ working=await _working(session, protocol, [r.id for r in rooms]),+ reason=control.reason if control else None,+ changed_by_name=control.by_name if control else None,+ paused_repeat_of=(+ control.repeat_of if control and control.state == "paused" else None+ ),+ can_control=await protocol.run_service().may_control(+ session, root_id, user_id=user.id, is_admin=is_admin+ ),+ rooms=[entry(r) for r in rooms],+ )+++async def _working(+ session: AsyncSession, protocol: ProtocolService, room_ids: list[str]+) -> bool:+ """Whether a turn is open in any of these rooms, for an agent that is+ still connected: a turn whose session died never records its end."""+ live = protocol.connections.live_agent_ids()+ if not live or not room_ids:+ return False+ open_turn = await session.execute(+ select(SessionActivityItem.agent_id)+ .where(+ SessionActivityItem.room_id.in_(room_ids),+ SessionActivityItem.item_id == TURN_ITEM_ID,+ SessionActivityItem.status.not_in(TURN_ENDED),+ SessionActivityItem.agent_id.in_(live),+ )+ .limit(1)+ )+ return open_turn.first() is not None++[email protected]("/template-runs")+async def list_template_runs(+ session: Annotated[AsyncSession, Depends(get_session)],+ protocol: Annotated[ProtocolService, Depends(get_protocol)],+ room_store: Annotated[RoomStore, Depends(get_room_store)],+ agent_store: Annotated[AgentStore, Depends(get_agent_store)],+ user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],+) -> list[TemplateRun]:+ """The viewer's recent runs, newest first: templates they ran and rooms+ their agents created. An admin sees every run in the workspace, so a run+ can be stopped by someone whose Console never saw it start."""+ roots = await room_store.recent_run_roots(+ session, user_id=None if is_admin else user.id, limit=RECENT_RUNS+ )+ runs = [+ await _run(+ session,+ protocol,+ room_store,+ agent_store,+ root_id,+ user=user,+ is_admin=is_admin,+ )+ for root_id in roots+ ]+ return [r for r in runs if r is not None]+++async def _control(+ root_id: str,+ state: RunState,+ session: AsyncSession,+ protocol: ProtocolService,+ room_store: RoomStore,+ agent_store: AgentStore,+ user: User,+ is_admin: bool,+) -> TemplateRun:+ service = protocol.run_service()+ if await room_store.get(session, root_id) is None:+ raise HTTPException(status_code=404, detail="No such run")+ if not await service.may_control(+ session, root_id, user_id=user.id, is_admin=is_admin+ ):+ raise HTTPException(+ status_code=403,+ detail=(+ "Only the owner of an agent in this run, the person who ran its "+ "template, or an admin can do that."+ ),+ )+ try:+ await service.set_state(+ root_id,+ "stopped" if state == "stopped" else "running",+ user_id=user.id,+ user_name=user.name,+ )+ except RunRefused as e:+ raise HTTPException(status_code=409, detail=str(e)) from e+ run = await _run(+ session,+ protocol,+ room_store,+ agent_store,+ root_id,+ user=user,+ is_admin=is_admin,+ )+ assert run is not None+ return run++[email protected]("/template-runs/{root_room_id}/stop")+async def stop_template_run(+ root_room_id: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ protocol: Annotated[ProtocolService, Depends(get_protocol)],+ room_store: Annotated[RoomStore, Depends(get_room_store)],+ agent_store: Annotated[AgentStore, Depends(get_agent_store)],+ user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],+) -> TemplateRun:+ """Stop a run: agents can no longer create rooms in it, and each of its+ rooms gets a note saying so. The rooms themselves stay as they are."""+ return await _control(+ root_room_id,+ "stopped",+ session,+ protocol,+ room_store,+ agent_store,+ user,+ is_admin,+ )++[email protected]("/template-runs/{root_room_id}/continue")+async def continue_template_run(+ root_room_id: str,+ session: Annotated[AsyncSession, Depends(get_session)],+ protocol: Annotated[ProtocolService, Depends(get_protocol)],+ room_store: Annotated[RoomStore, Depends(get_room_store)],+ agent_store: Annotated[AgentStore, Depends(get_agent_store)],+ user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],+) -> TemplateRun:+ """Let a paused run go on. The agent whose request paused it is woken in+ the room it was working in to carry on. The request may now be made once+ more; making it again after that pauses the run again."""+ return await _control(+ root_room_id,+ "running",+ session,+ protocol,+ room_store,+ agent_store,+ user,+ is_admin,+ )diff --git a/core/switch_core/migrations/versions/a3c9e1f7b2d4_rooms_created_by_agent.py b/core/switch_core/migrations/versions/a3c9e1f7b2d4_rooms_created_by_agent.pynew file mode 100644index 000000000..0886ca118--- /dev/null+++ b/core/switch_core/migrations/versions/a3c9e1f7b2d4_rooms_created_by_agent.py@@ -0,0 +1,70 @@+"""record which agent created a room and where it sits in its run++Revision ID: a3c9e1f7b2d4+Revises: c4e9a1f7b203+Create Date: 2026-09-17 00:00:00.000000++A room an agent creates records the agent, the room it was working in when+it asked (``parent_room_id``) and the root of the chain (``run_id``), a room+a person made. Together they give each run as a tree, which is what lets a+person see how a template ran and stop it. ``template_name`` and+``kickoff_hash`` say what the room was for, closely enough to tell a new step+from the same request made again. ``run_control`` is set on a run's root when+the run is paused or stopped.+"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op+from sqlalchemy.dialects.postgresql import JSONB++revision: str = "a3c9e1f7b2d4"+down_revision: str | None = "c4e9a1f7b203"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column(+ "rooms",+ sa.Column("created_by_agent_id", sa.Text(), nullable=True),+ )+ # Carries tenant_id like every foreign key between tenant-scoped tables.+ # Only the agent column is cleared when the agent goes; tenant_id stays.+ op.create_foreign_key(+ "fk_rooms_created_by_agent",+ "rooms",+ "agents",+ ["tenant_id", "created_by_agent_id"],+ ["tenant_id", "id"],+ ondelete="SET NULL (created_by_agent_id)",+ )+ op.add_column("rooms", sa.Column("parent_room_id", sa.Text(), nullable=True))+ op.create_foreign_key(+ "fk_rooms_parent_room",+ "rooms",+ "rooms",+ ["tenant_id", "parent_room_id"],+ ["tenant_id", "id"],+ ondelete="SET NULL (parent_room_id)",+ )+ op.add_column("rooms", sa.Column("run_id", sa.Text(), nullable=True))+ op.add_column("rooms", sa.Column("template_name", sa.Text(), nullable=True))+ op.add_column("rooms", sa.Column("kickoff_hash", sa.Text(), nullable=True))+ op.add_column("rooms", sa.Column("run_control", JSONB(), nullable=True))+ # A run is listed, checked and stopped by its root on every agent create+ # and every look at Recently used.+ op.create_index("ix_rooms_run_id", "rooms", ["run_id"])+++def downgrade() -> None:+ op.drop_index("ix_rooms_run_id", table_name="rooms")+ op.drop_column("rooms", "run_control")+ op.drop_column("rooms", "kickoff_hash")+ op.drop_column("rooms", "template_name")+ op.drop_column("rooms", "run_id")+ op.drop_constraint("fk_rooms_parent_room", "rooms", type_="foreignkey")+ op.drop_column("rooms", "parent_room_id")+ op.drop_constraint("fk_rooms_created_by_agent", "rooms", type_="foreignkey")+ op.drop_column("rooms", "created_by_agent_id")diff --git a/core/switch_core/migrations/versions/d7a2e4c91b35_templates_created_by_agent.py b/core/switch_core/migrations/versions/d7a2e4c91b35_templates_created_by_agent.pynew file mode 100644index 000000000..a6ce03663--- /dev/null+++ b/core/switch_core/migrations/versions/d7a2e4c91b35_templates_created_by_agent.py@@ -0,0 +1,39 @@+"""record which agent saved a template++Revision ID: d7a2e4c91b35+Revises: a3c9e1f7b2d4++Agents can now save templates. ``templates.created_by_agent_id`` records which+agent saved one, the same way ``rooms.created_by_agent_id`` does for rooms;+``owner_id`` stays the agent's owner, so tenancy and visibility are unchanged.+Only that agent may change or delete what it saved.+"""++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "d7a2e4c91b35"+down_revision: str | Sequence[str] | None = "a3c9e1f7b2d4"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column(+ "templates", sa.Column("created_by_agent_id", sa.Text(), nullable=True)+ )+ op.create_foreign_key(+ "fk_templates_created_by_agent",+ "templates",+ "agents",+ ["tenant_id", "created_by_agent_id"],+ ["tenant_id", "id"],+ ondelete="SET NULL (created_by_agent_id)",+ )+++def downgrade() -> None:+ op.drop_constraint("fk_templates_created_by_agent", "templates", type_="foreignkey")+ op.drop_column("templates", "created_by_agent_id")diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.pyindex 3d79de278..199ae4d18 100644--- a/core/switch_core/room_service.py+++ b/core/switch_core/room_service.py@@ -95,6 +95,13 @@ class RoomCreateConfig(BaseModel):observe_config: dict[str, object] | None = Noneadmin_mode: bool = Falsecreated_by: str | None = None+ # Set when an agent operation creates the room; see the `Room` columns.+ created_by_agent_id: str | None = None+ parent_room_id: str | None = None+ run_id: str | None = None+ kickoff_hash: str | None = None+ # The template the room came from, for runs to show; see `Room`.+ template_name: str | None = None# Optional group to file the room under at creation (navigation layer).group_id: str | None = None# Authorization owner (the acting user, or an agent's owner for MCP-created@@ -533,6 +540,11 @@ class RoomService:protection_config=config.protection_config,observe_config=config.observe_config,created_by=config.created_by,+ created_by_agent_id=config.created_by_agent_id,+ parent_room_id=config.parent_room_id,+ run_id=config.run_id,+ kickoff_hash=config.kickoff_hash,+ template_name=config.template_name,owner_id=config.owner_id,read_visibility=config.read_visibility,write_visibility=config.write_visibility,diff --git a/core/switch_core/rooms_yaml.py b/core/switch_core/rooms_yaml.pyindex 616d27f9e..899dd32e7 100644--- a/core/switch_core/rooms_yaml.py+++ b/core/switch_core/rooms_yaml.py@@ -39,6 +39,7 @@ from typing import TYPE_CHECKING, Any, Literal, castimport yamlfrom pydantic import BaseModel, Field, TypeAdapter, ValidationError, model_validator+from switch_core.agent_runs import AgentOrigin, kickoff_fingerprintfrom switch_core.bridges.collaboration.models import ChannelTypefrom switch_core.bridges.resource.registry import validate_reference_valuefrom switch_core.clients.admin_client import AdminClient@@ -196,7 +197,7 @@ class ParamSpec(BaseModel):return self-def _coerce(value: Any, spec: ParamSpec, name: str) -> str | int | float | bool:+def coerce_param(value: Any, spec: ParamSpec, name: str) -> str | int | float | bool:"""Coerce a raw input value to the declared type."""t = spec.typeif t == "string":@@ -266,9 +267,9 @@ def resolve_params(missing: list[str] = []for name, spec in declared.items():if name in inputs and inputs[name] is not None:- resolved[name] = _coerce(inputs[name], spec, name)+ resolved[name] = coerce_param(inputs[name], spec, name)elif spec.default is not None and not isinstance(spec.default, list):- resolved[name] = _coerce(spec.default, spec, name)+ resolved[name] = coerce_param(spec.default, spec, name)elif spec.is_required:missing.append(name)elif spec.type == "string":@@ -973,6 +974,8 @@ class RoomYamlService:kickoff: str | None = None,creator_name: str | None = None,group_id: str | None = None,+ origin: AgentOrigin | None = None,+ template_name: str | None = None,) -> ProvisionResult:"""Create the room and everything the spec attaches to it.@@ -980,6 +983,12 @@ class RoomYamlService:creator's behalf (see ``_send_kickoff``); ``creator_name`` is how themessage names them. ``group_id`` files the room under a group thatalready exists (see ``provision_group``).++ With ``origin`` an agent is creating the room: it is recorded in that+ agent's run (see ``agent_runs``), and the kickoff carries the agent's+ authority, not its owner's, with the run so far appended. The checks+ that can refuse an agent's room have run before this is called.+ ``template_name`` is what the room's run is listed under."""bridge_id = await self._resolve_bridge_id(spec.bridge)if spec.users and bridge_id is None:@@ -1003,6 +1012,11 @@ class RoomYamlService:group_id=group_id,created_by=user_id,from_template=True,+ created_by_agent_id=origin.agent_id if origin else None,+ parent_room_id=origin.parent_room_id if origin else None,+ run_id=origin.run_id if origin else None,+ kickoff_hash=kickoff_fingerprint(kickoff) if origin and kickoff else None,+ template_name=template_name,owner_id=user_id,acting_user_id=user_id,acting_is_admin=is_admin,@@ -1033,6 +1047,7 @@ class RoomYamlService:agent_names=spec.agents,user_id=user_id,user_name=creator_name,+ origin=origin,failures=failures,)except Exception as e: # noqa: BLE001 - reported on the result@@ -1055,6 +1070,8 @@ class RoomYamlService:user_id: str,is_admin: bool,creator_name: str | None = None,+ origin: AgentOrigin | None = None,+ template_name: str | None = None,) -> GroupProvisionResult:"""Provision a room group, its rooms, and the links between them.@@ -1086,6 +1103,8 @@ class RoomYamlService:is_admin=is_admin,kickoff=room_spec.kickoff,creator_name=creator_name,+ origin=origin,+ template_name=template_name,group_id=group_id,)except Exception as e: # noqa: BLE001 - reported, not swallowed@@ -1264,6 +1283,7 @@ class RoomYamlService:user_id: str,user_name: str | None,failures: list[dict[str, Any]],+ origin: AgentOrigin | None = None,) -> None:"""Post the kickoff into the room the template just created.@@ -1298,8 +1318,14 @@ class RoomYamlService:if "the platform" in late:return- person = OnBehalfOf(user_id, user_name or user_id)- headline = f"Template kickoff on behalf of @{person.name}"+ if origin is not None:+ person = OnBehalfOf(user_id, origin.agent_name, origin.agent_id)+ headline = f"Kickoff from {origin.headline_name}"+ if origin.trace:+ text = f"{text}\n\n{origin.trace}"+ else:+ person = OnBehalfOf(user_id, user_name or user_id)+ headline = f"Template kickoff on behalf of {person.label}"try:root_id = await admin.send_platform_message(room.matrix_room_id, headline, on_behalf_of=persondiff --git a/core/switch_core/telemetry/catalogue.py b/core/switch_core/telemetry/catalogue.pyindex 20f48a017..a52c68f7d 100644--- a/core/switch_core/telemetry/catalogue.py+++ b/core/switch_core/telemetry/catalogue.py@@ -362,6 +362,36 @@ CATALOGUE: Mapping[str, Mapping[str, PropertyType]] = {"reference_type_deleted": {"age_days": NUMBER},"template_created": {"template_kind": TEMPLATE_KIND},"template_deleted": {"template_kind": TEMPLATE_KIND, "age_days": NUMBER},+ # An agent asked for something and was told no, on purpose. Which rule+ # people run into is what a finer rights model is designed from; who and+ # what stays in the server log (see `agent_refusals`).+ "agent_request_refused": {+ "operation": one_of(+ "list_templates",+ "get_template",+ "run_template",+ "save_template",+ "update_template",+ "delete_template",+ "create_room",+ "create_room_from_yaml",+ ),+ "reason": one_of(+ "not_found",+ "not_yours",+ "name_taken",+ "visibility_not_allowed",+ "invalid",+ "too_large",+ "missing_agents",+ "agent_creation_console_only",+ "busy",+ "run_paused",+ "run_stopped",+ "repeat",+ "kickoff_ignored",+ ),+ },"room_link_created": {},"room_link_removed": {},"room_role_defined": {"exclusive": BOOLEAN},diff --git a/core/switch_core/template_guide.py b/core/switch_core/template_guide.pynew file mode 100644index 000000000..80b48428a--- /dev/null+++ b/core/switch_core/template_guide.py@@ -0,0 +1,99 @@+"""The template language, as an agent needs it to write a document.++A condensed ``docs/TEMPLATES.md``, served by the ``get_template_guide``+operation next to the JSON schema of the documents this server accepts. It+covers what the server creates (rooms and groups) and how an agent uses the+agent and team templates the Console creates. Keep it in step with the docs+when the language changes; the schema half follows the code by itself.+"""++TEMPLATE_GUIDE = """\+# Switch templates, for agents++A template is one YAML document. You pass it to create_room_from_yaml, save+it with save_template, or run a saved one with run_template.++## Top-level keys++- version: the format version, 1.+- params: the inputs, each written as {name} anywhere else in the document.+- room: one room to create.+- group + rooms (+ links): a room group, its rooms, and links between them.+- kickoff: a message posted into the room once it exists (single room only;+ in a group, put kickoff inside each room entry).+- agent / agents: agents to create. Only Switch Console creates agents. To+ run such a template yourself, fill every agent it describes with an agent+ that already exists: run_template(agents={slot name: agent name}).++## A room++room:+ name: text+ description: text # required+ instructions: text # standing brief for the room's agents+ bridge: messaging app display name, or "{param}"+ channel_type: channel_public | channel_private+ agents: [agent names that exist on the server]+ users: [usernames on the room's messaging app; "{$creator}" is the deployer]+ aliases: {agent name: alias} # @alias addresses that agent in this room++Without bridge the room goes on the server's default messaging app. users+needs the room to be on a messaging app.++## A group++group: {name: text, description: text}+rooms:+ - {name: ..., description: ..., agents: [...], kickoff: "@agent start"}+links:+ - {from: room name, to: room name, label: text}++## Params++params:+ <name>:+ type: string | number | boolean | enum | agent | bridge | room | user+ description: text+ default: a value, or for agent/bridge/room a list of candidates tried in+ order, where $first means the first one the server has+ required: true | false # default: false with a single default value,+ # true with none or with a list of candidates+ enum: [choices] # enum only+ pattern: regex # string only, whole value must match+ min: number, max: number # number only++provider, location and directory params are the Console's. run_template+drops them from an agent or team template; in a document you write yourself,+leave them out, since the server reads them as text and requires a value+like any other param. Give values in the inputs argument; a required param+with no value is refused with its name.++## Placeholders++{param} is replaced by the param's value; a field that is exactly one+placeholder keeps the value's type. Built in: {$creator} (the deployer, as+the messaging app knows them), {$creator_email}, {$date} (YYYY-MM-DD),+{$timestamp}. A {word} that names nothing is left as written.++## Kickoff++An agent starts working when a message addresses it, so mention each agent+the room needs: kickoff: "@helper start on the brief."+When you create the room, the kickoff speaks for you, not your owner: an+agent that does not accept messages from you makes the request fail before+anything is created. The kickoff also carries the run so far. Asking again+for a room with the same kickoff you already used further up the same path+pauses the run until your owner lets it continue.++## Example++version: 1+params:+ topic: {type: string, description: What the room is about}+room:+ name: "{topic} review"+ description: "Reviewing {topic}"+ agents: [reviewer]+ users: ["{$creator}"]+kickoff: "@reviewer read the brief and list three risks in {topic}."+"""diff --git a/core/tests/switch_core/bridges/agent/operations/conftest.py b/core/tests/switch_core/bridges/agent/operations/conftest.pynew file mode 100644index 000000000..140d62cea--- /dev/null+++ b/core/tests/switch_core/bridges/agent/operations/conftest.py@@ -0,0 +1,231 @@+"""The agent operations that create rooms and use templates, over a fake+protocol: real PostgreSQL and the real template engine and run guards, no+Matrix. Shared by the create_room_from_yaml and template tool tests.+"""++from __future__ import annotations++import uuid+from functools import partial+from types import SimpleNamespace+from typing import Any++import pytest_asyncio+from sqlalchemy import insert+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.agent.operations import context as op_context+from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.resource.service import ResourceService+from switch_core.clients.admin_client import AdminClient+from switch_core.db.models import (+ Agent,+ ApiKey,+ Client,+ Room,+ User,+ room_agents,+)+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore+from switch_core.db.stores.document_store import DocumentStore+from switch_core.db.stores.external_user_store import ExternalUserStore+from switch_core.db.stores.package_store import PackageStore+from switch_core.db.stores.reference_store import ReferenceStore+from switch_core.db.stores.reference_type_store import ReferenceTypeStore+from switch_core.db.stores.room_group_store import RoomGroupStore+from switch_core.db.stores.room_link_store import RoomLinkStore+from switch_core.db.stores.room_role_store import RoomRoleStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.db.stores.user_store import UserStore+from switch_core.room_service import RoomCreateConfig, RoomCreateResult+from switch_core.rooms_yaml import RoomYamlService+++class FakeRoomService:+ """DB-only stand-in, the same as test_rooms_yaml.py's."""++ def __init__(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ agent_store: AgentStore,+ ) -> None:+ self._sf = session_factory+ self._agents = agent_store++ async def create_room(self, config: RoomCreateConfig) -> RoomCreateResult:+ async with self._sf() as session:+ agent_ids: list[str] = []+ if config.agent_names:+ agents = await self._agents.get_by_names(session, config.agent_names)+ name_to_id = {a.name: a.id for a in agents}+ missing = [n for n in config.agent_names if n not in name_to_id]+ if missing:+ raise ValueError(f"Unknown agents: {', '.join(missing)}")+ agent_ids = [name_to_id[n] for n in config.agent_names]++ room = Room(+ matrix_room_id=f"!{uuid.uuid4().hex}:test.local",+ name=config.name,+ description=config.description,+ channel_type=config.channel_type or "channel_public",+ bridge_id=config.bridge_id,+ instructions=config.instructions,+ created_by=config.created_by,+ created_by_agent_id=config.created_by_agent_id,+ parent_room_id=config.parent_room_id,+ run_id=config.run_id,+ kickoff_hash=config.kickoff_hash,+ template_name=config.template_name,+ owner_id=config.owner_id,+ read_visibility=config.read_visibility,+ write_visibility=config.write_visibility,+ group_id=config.group_id,+ )+ session.add(room)+ await session.flush()+ for aid in agent_ids:+ await session.execute(+ insert(room_agents).values(room_id=room.id, agent_id=aid)+ )+ await session.commit()+ return RoomCreateResult(room=room, failed_attachments=[])+++async def _make_agent(+ session: AsyncSession, name: str, user_id: str, owner_id: str | None+) -> Agent:+ api_key = ApiKey(+ user_id=user_id,+ key_hash=f"hash-{name}",+ encrypted_key="enc",+ label=name,+ type="agent",+ )+ client = Client(+ matrix_user_id=f"@{name}:test.local",+ display_name=name,+ type="agent",+ )+ session.add_all([api_key, client])+ await session.flush()+ agent = Agent(+ name=name,+ description=f"{name} desc",+ agent_type="always_on",+ connector_type="claude_code",+ integration_profile={"connection_model": "always_on"},+ client_id=client.id,+ api_key_id=api_key.id,+ owner_id=owner_id,+ )+ session.add(agent)+ await session.flush()+ return agent+++class RecordingAdminClient(AdminClient):+ """Records the platform messages a kickoff sends; has no transport."""++ def __init__(self) -> None: # noqa: D107 - test double, no super().__init__+ self.sent: list[dict[str, Any]] = []+ self.notices: list[dict[str, Any]] = []++ async def wait_joined(self, room_id: str, timeout: float) -> bool:+ return True++ async def send_platform_message( # type: ignore[override]+ self,+ room_id: str,+ body: str,+ *,+ thread_root_id=None,+ on_behalf_of=None,+ reply_in_channel=False,+ ) -> str | None:+ self.sent.append({"body": body, "on_behalf_of": on_behalf_of})+ return "$kickoff"++ async def send_notice(self, room_id: str, body: str) -> None:+ self.notices.append({"room": room_id, "body": body})+++class FakeLifecycle:+ def __init__(self, admin: AdminClient) -> None:+ self.admin = admin++ def get_by_type(self, client_type: str, tenant_id: str) -> list[Any]:+ return [self.admin] if client_type == "admin" else []++ def get_by_agent_id(self, agent_id: str) -> None:+ return None+++@pytest_asyncio.fixture+async def env(session_factory: async_sessionmaker[AsyncSession]):+ """Seed a user and two agents, and wire a fake protocol for the operation."""+ agent_store = AgentStore()+ resource_service = ResourceService(+ reference_store=ReferenceStore(),+ reference_type_store=ReferenceTypeStore(),+ document_store=DocumentStore(),+ package_store=PackageStore(),+ room_link_store=RoomLinkStore(),+ session_factory=session_factory,+ )+ admin = RecordingAdminClient()+ fake_protocol = SimpleNamespace(+ client_lifecycle=FakeLifecycle(admin),+ session_factory=session_factory,+ agent_store=agent_store,+ user_store=UserStore(),+ room_service=FakeRoomService(session_factory, agent_store),+ resource_service=resource_service,+ room_store=RoomStore(),+ bridge_store=CollaborationBridgeStore(),+ external_user_store=ExternalUserStore(),+ room_group_store=RoomGroupStore(),+ room_role_store=RoomRoleStore(),+ connections={},+ )+ # Runs are the real service's; only its collaborators are fakes.+ fake_protocol.run_service = partial(ProtocolService.run_service, fake_protocol)+ # The same wiring `ProtocolService.room_yaml_service` does, over the fakes.+ fake_protocol.room_yaml_service = lambda: RoomYamlService(+ room_service=fake_protocol.room_service,+ resource_service=fake_protocol.resource_service,+ room_store=fake_protocol.room_store,+ agent_store=fake_protocol.agent_store,+ bridge_store=fake_protocol.bridge_store,+ external_user_store=fake_protocol.external_user_store,+ room_role_store=fake_protocol.room_role_store,+ session_factory=fake_protocol.session_factory,+ room_group_store=fake_protocol.room_group_store,+ client_lifecycle=fake_protocol.client_lifecycle,+ )++ async with session_factory() as session:+ user = User(name="alice", email="[email protected]", role="member")+ session.add(user)+ await session.flush()+ user_id = user.id+ agent = await _make_agent(session, "claude-code.alice", user_id, user_id)+ await _make_agent(session, "claude-code.bob", user_id, user_id)+ orphan = await _make_agent(session, "orphan", user_id, None)+ await session.commit()+ agent_id = agent.id+ orphan_id = orphan.id++ old_protocol = op_context._protocol+ op_context.init_operations_protocol(fake_protocol) # type: ignore[arg-type]+ try:+ yield {+ "agent_id": agent_id,+ "orphan_id": orphan_id,+ "user_id": user_id,+ "session_factory": session_factory,+ "admin": admin,+ "protocol": fake_protocol,+ }+ finally:+ op_context._protocol = old_protocoldiff --git a/core/tests/switch_core/bridges/agent/operations/test_agent_template_tools.py b/core/tests/switch_core/bridges/agent/operations/test_agent_template_tools.pynew file mode 100644index 000000000..31a90bdfd--- /dev/null+++ b/core/tests/switch_core/bridges/agent/operations/test_agent_template_tools.py@@ -0,0 +1,766 @@+"""The template tools an agent has: finding, reading, running and saving+templates, and the refusals when it asks for what it may not do.++Over the same fake protocol as the create_room_from_yaml tests: real+PostgreSQL, the real template engine and run guards, no Matrix.+"""++from __future__ import annotations++import logging+from types import SimpleNamespace+from typing import Any++import pytest+import pytest_asyncio+import yaml+from sqlalchemy import select, update++from switch_core.agent_refusals import AgentRefused+from switch_core.agent_template_ops import ActingFor, AgentTemplates+from switch_core.agent_templates import agent_slots, room_document, template_kind+from switch_core.bridges.agent.operations.callctx import (+ CallContext,+ reset_call_context,+ set_call_context,+)+from switch_core.bridges.agent.operations.definitions import (+ create_room_from_yaml,+ delete_template,+ get_template,+ get_template_guide,+ list_templates,+ run_template,+ save_template,+ update_template,+)+from switch_core.db.models import Agent, Room, Template, User+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.template_store import TemplateStore++ROOM_TEMPLATE = """\+version: 1+params:+ topic: { type: string, description: What the room is about }+room:+ name: "{topic} room"+ description: "A room about {topic}"+ agents: ["claude-code.alice"]+"""++TEAM_TEMPLATE = """\+version: 1+params:+ team: { type: string }+ provider: { type: provider, default: claude }+agents:+ - name: "{team}-triager"+ description: Routes reports+ provider: "{provider}"+ instructions: Route reports.+ - name: "{team}-repro"+ description: Reproduces bugs+ instructions: Reproduce bugs.+room:+ name: "{team}-triage"+ description: The triage room+ agents: ["{team}-triager", "{team}-repro"]+kickoff: "@{team}-triager say hello to @{team}-repro."+"""++AGENT_TEMPLATE = """\+version: 1+agent:+ name: jq-expert+ description: Answers jq questions+ instructions: Answer jq questions.+room:+ name: "Ask {agent}"+ description: "Ask {agent} about jq"+ agents: ["{agent}"]+kickoff: "@{agent} introduce yourself."+"""+++@pytest_asyncio.fixture+async def tools(env):+ env["protocol"].config = SimpleNamespace(template_max_bytes=64 * 1024)+ env["protocol"].telemetry = None+ async with env["session_factory"]() as session:+ stranger = User(name="mallory", email="[email protected]", role="member")+ session.add(stranger)+ await session.commit()+ env["stranger_id"] = stranger.id+ return env+++async def _as(agent_id: str, fn: Any, **kwargs: Any) -> Any:+ token = set_call_context(+ CallContext(agent_id=agent_id, session_key=None, session=None)+ )+ try:+ return await fn(**kwargs)+ finally:+ reset_call_context(token)+++async def _stored(+ env: dict[str, Any], owner_id: str, name: str, content: str, **kw: Any+) -> str:+ async with env["session_factory"]() as session:+ template = Template(+ owner_id=owner_id,+ name=name,+ description=f"{name} description",+ kind=kw.pop("kind", "room"),+ content=content,+ **kw,+ )+ session.add(template)+ await session.commit()+ return template.id+++async def _bob_id(env: dict[str, Any]) -> str:+ async with env["session_factory"]() as session:+ bob = await AgentStore().get_by_name(session, "claude-code.bob")+ assert bob is not None+ return bob.id++[email protected](autouse=True)+def _refusal_log(caplog: pytest.LogCaptureFixture) -> None:+ caplog.set_level(logging.INFO, logger="switch_core.agent_refusals")+++def _refusals(caplog: pytest.LogCaptureFixture) -> list[tuple[str, str]]:+ """Each reported refusal, as (operation, reason), from its log line."""+ return [+ (str(r.args[2]), str(r.args[3]))+ for r in caplog.records+ if r.name == "switch_core.agent_refusals" and isinstance(r.args, tuple)+ ]+++# ── Reading a document ────────────────────────────────────────────────────+++def test_kinds_and_slots_are_read_from_the_document():+ assert template_kind(ROOM_TEMPLATE) == "room"+ assert template_kind(AGENT_TEMPLATE) == "agent"+ assert template_kind(TEAM_TEMPLATE) == "group"+ assert [s.name for s in agent_slots(TEAM_TEMPLATE)] == [+ "{team}-triager",+ "{team}-repro",+ ]+++def test_a_team_template_becomes_a_room_with_the_chosen_agents():+ document, inputs = room_document(+ TEAM_TEMPLATE,+ {"red-triager": "claude-code.alice", "{team}-repro": "claude-code.bob"},+ {"team": "red", "provider": "codex"},+ )+ doc = yaml.safe_load(document)+ assert "agents" not in doc+ assert doc["room"]["agents"] == ["claude-code.alice", "claude-code.bob"]+ assert doc["kickoff"] == "@claude-code.alice say hello to @claude-code.bob."+ # Every value is filled in and checked here, and the Console-only+ # provider never reaches the server.+ assert "params" not in doc+ assert inputs == {}+++def test_an_unfilled_slot_is_refused_with_the_console_message():+ with pytest.raises(+ AgentRefused, match="creating agents happens in Switch Console"+ ) as e:+ room_document(+ TEAM_TEMPLATE, {"red-triager": "claude-code.alice"}, {"team": "red"}+ )+ assert e.value.reason == "agent_creation_console_only"+ assert "red-repro" in str(e.value)+++# ── The tools ─────────────────────────────────────────────────────────────+++async def test_list_shows_shared_and_the_owners_private_templates(tools):+ await _stored(+ tools,+ tools["user_id"],+ "mine-private",+ ROOM_TEMPLATE,+ read_visibility="private",+ )+ await _stored(tools, tools["stranger_id"], "theirs-shared", ROOM_TEMPLATE)+ await _stored(+ tools,+ tools["stranger_id"],+ "theirs-private",+ ROOM_TEMPLATE,+ read_visibility="private",+ )++ rows = await _as(tools["agent_id"], list_templates)++ assert {r["name"] for r in rows} == {"mine-private", "theirs-shared"}+ assert all(r["can_edit"] is False for r in rows)+ assert {r["saved_by"] for r in rows} == {"alice", "mallory"}+++async def test_get_describes_inputs_and_agent_slots(tools):+ template_id = await _stored(+ tools, tools["user_id"], "team", TEAM_TEMPLATE, kind="group"+ )++ detail = await _as(tools["agent_id"], get_template, template_id=template_id)++ assert [p["name"] for p in detail["params"]] == ["team", "provider"]+ assert [s["name"] for s in detail["agent_slots"]] == [+ "{team}-triager",+ "{team}-repro",+ ]+ assert detail["content"] == TEAM_TEMPLATE+++async def test_a_private_template_of_someone_else_does_not_exist_for_the_agent(+ tools, caplog+):+ template_id = await _stored(+ tools, tools["stranger_id"], "secret", ROOM_TEMPLATE, read_visibility="private"+ )++ with pytest.raises(AgentRefused, match="No template"):+ await _as(tools["agent_id"], get_template, template_id=template_id)+ assert _refusals(caplog) == [("get_template", "not_found")]+++async def test_run_creates_the_room_under_the_templates_name(tools):+ template_id = await _stored(+ tools, tools["stranger_id"], "Topic room", ROOM_TEMPLATE+ )++ result = await _as(+ tools["agent_id"], run_template, template_id=template_id, inputs={"topic": "jq"}+ )++ async with tools["session_factory"]() as session:+ room = await session.get(Room, result["room_id"])+ assert room is not None+ assert (room.name, room.template_name) == ("jq room", "Topic room")+ assert room.created_by_agent_id == tools["agent_id"]+++async def test_run_a_team_template_with_existing_agents(tools):+ template_id = await _stored(+ tools, tools["user_id"], "team", TEAM_TEMPLATE, kind="group"+ )++ result = await _as(+ tools["agent_id"],+ run_template,+ template_id=template_id,+ inputs={"team": "red"},+ agents={"red-triager": "claude-code.alice", "red-repro": "claude-code.bob"},+ )++ assert result["room_name"] == "red-triage"+ assert (+ tools["admin"]+ .sent[-1]["body"]+ .startswith("@claude-code.alice say hello to @claude-code.bob.")+ )+++async def test_run_an_agent_template_with_an_existing_agent(tools):+ template_id = await _stored(+ tools, tools["user_id"], "jq", AGENT_TEMPLATE, kind="agent"+ )++ result = await _as(+ tools["agent_id"],+ run_template,+ template_id=template_id,+ agents={"jq-expert": "claude-code.bob"},+ )++ assert result["room_name"] == "Ask claude-code.bob"+++async def test_run_that_would_create_an_agent_is_refused_and_reported(tools, caplog):+ template_id = await _stored(+ tools, tools["user_id"], "jq", AGENT_TEMPLATE, kind="agent"+ )++ with pytest.raises(AgentRefused, match="Switch Console"):+ await _as(tools["agent_id"], run_template, template_id=template_id)++ assert _refusals(caplog) == [("run_template", "agent_creation_console_only")]+ assert "Refused agent claude-code.alice" in caplog.text+++async def test_missing_agents_are_named_all_at_once_and_nothing_is_created(tools):+ template_id = await _stored(+ tools, tools["user_id"], "team", TEAM_TEMPLATE, kind="group"+ )++ with pytest.raises(AgentRefused, match="ghost-one, ghost-two"):+ await _as(+ tools["agent_id"],+ run_template,+ template_id=template_id,+ inputs={"team": "red"},+ agents={"red-triager": "ghost-one", "red-repro": "ghost-two"},+ )+ async with tools["session_factory"]() as session:+ assert (await session.execute(select(Room))).scalars().all() == []+++async def test_save_is_owned_by_the_owner_and_marked_with_the_agent(tools):+ saved = await _as(+ tools["agent_id"],+ save_template,+ name="standup",+ description="Daily standup room",+ yaml=ROOM_TEMPLATE,+ visibility="shared",+ )++ async with tools["session_factory"]() as session:+ template = await session.get(Template, saved["id"])+ assert template is not None+ assert template.owner_id == tools["user_id"]+ assert template.created_by_agent_id == tools["agent_id"]+ assert (template.read_visibility, template.write_visibility) == (+ "public",+ "private",+ )+ assert saved["kind"] == "room"+ rows = await _as(tools["agent_id"], list_templates)+ assert [(r["name"], r["can_edit"], r["saved_by"]) for r in rows] == [+ ("standup", True, "agent claude-code.alice")+ ]+++async def test_save_refuses_a_template_anyone_could_change(tools, caplog):+ with pytest.raises(AgentRefused, match="not one an agent can set"):+ await _as(+ tools["agent_id"],+ save_template,+ name="open",+ description="",+ yaml=ROOM_TEMPLATE,+ visibility="open",+ )+ assert _refusals(caplog) == [("save_template", "visibility_not_allowed")]+++async def test_save_refuses_a_name_the_owner_already_uses(tools, caplog):+ await _stored(tools, tools["user_id"], "standup", ROOM_TEMPLATE)++ with pytest.raises(AgentRefused, match="already has a template named 'standup'"):+ await _as(+ tools["agent_id"],+ save_template,+ name="standup",+ description="",+ yaml=ROOM_TEMPLATE,+ )+ assert _refusals(caplog) == [("save_template", "name_taken")]+++async def test_an_agent_changes_and_deletes_what_it_saved(tools):+ saved = await _as(+ tools["agent_id"],+ save_template,+ name="standup",+ description="",+ yaml=ROOM_TEMPLATE,+ )++ updated = await _as(+ tools["agent_id"],+ update_template,+ template_id=saved["id"],+ yaml=ROOM_TEMPLATE.replace("A room about", "Talk about"),+ visibility="shared",+ )+ assert (updated["version"], updated["visibility"]) == (2, "shared")+ deleted = await _as(tools["agent_id"], delete_template, template_id=saved["id"])+ assert deleted["name"] == "standup"+++async def test_an_agent_cannot_change_its_owners_template(tools, caplog):+ template_id = await _stored(tools, tools["user_id"], "owners", ROOM_TEMPLATE)++ with pytest.raises(AgentRefused, match="saved by alice"):+ await _as(+ tools["agent_id"], update_template, template_id=template_id, description="x"+ )+ with pytest.raises(AgentRefused, match="saved by alice"):+ await _as(tools["agent_id"], delete_template, template_id=template_id)+ assert _refusals(caplog) == [+ ("update_template", "not_yours"),+ ("delete_template", "not_yours"),+ ]+++async def test_an_agent_cannot_change_another_agents_template_of_the_same_owner(tools):+ saved = await _as(+ await _bob_id(tools),+ save_template,+ name="bobs",+ description="",+ yaml=ROOM_TEMPLATE,+ visibility="shared",+ )++ with pytest.raises(AgentRefused, match="saved by agent claude-code.bob"):+ await _as(tools["agent_id"], delete_template, template_id=saved["id"])+++GROUP_TEAM_TEMPLATE = """\+version: 1+params:+ team: { type: string }+agents:+ - name: "{team}-lead"+ instructions: Lead.+ - name: "{team}-helper"+ instructions: Help.+group:+ name: "{team}"+rooms:+ - name: "{team}-lobby"+ description: Where people arrive+ agents: ["{team}-lead"]+ aliases: { "{team}-lead": boss }+ kickoff: "@{team}-lead welcome people."+ - name: "{team}-work"+ description: Where the work happens+ agents: ["{team}-lead", "{team}-helper"]+ kickoff: "@{team}-helper start, and tell @{team}-lead."+"""+++def test_a_team_template_with_a_group_fills_every_room():+ document, inputs = room_document(+ GROUP_TEAM_TEMPLATE,+ {"blue-lead": "claude-code.alice", "blue-helper": "claude-code.bob"},+ {"team": "blue"},+ )++ doc = yaml.safe_load(document)+ lobby, work = doc["rooms"]+ assert lobby["agents"] == ["claude-code.alice"]+ assert lobby["aliases"] == {"claude-code.alice": "boss"}+ assert lobby["kickoff"] == "@claude-code.alice welcome people."+ assert work["agents"] == ["claude-code.alice", "claude-code.bob"]+ assert work["kickoff"] == "@claude-code.bob start, and tell @claude-code.alice."+ assert inputs == {}+++async def test_run_a_team_template_that_makes_a_group(tools):+ template_id = await _stored(+ tools, tools["user_id"], "blue team", GROUP_TEAM_TEMPLATE, kind="group"+ )++ result = await _as(+ tools["agent_id"],+ run_template,+ template_id=template_id,+ inputs={"team": "blue"},+ agents={"blue-lead": "claude-code.alice", "blue-helper": "claude-code.bob"},+ )++ assert result["errors"] == []+ assert {r["room_name"] for r in result["rooms"]} == {"blue-lobby", "blue-work"}+ async with tools["session_factory"]() as session:+ names = {+ r.template_name+ for r in (await session.execute(select(Room))).scalars().all()+ }+ assert names == {"blue team"}+++def test_a_slot_reached_through_a_param_is_swapped_too():+ template = """\+params:+ member: { type: string, default: worker }+agents:+ - name: worker+ instructions: Work.+room:+ name: shop+ description: The shop+ agents: ["{member}"]+ aliases: { "{member}": w }+kickoff: "@{member} start"+"""+ document, _ = room_document(template, {"worker": "claude-code.bob"}, {})++ doc = yaml.safe_load(document)+ assert doc["room"]["agents"] == ["claude-code.bob"]+ assert doc["room"]["aliases"] == {"claude-code.bob": "w"}+ assert doc["kickoff"] == "@claude-code.bob start"+++def test_a_slot_named_agent_does_not_touch_the_agent_placeholder():+ template = """\+agent:+ name: agent+ instructions: Help.+room:+ name: "Ask {agent}"+ description: "Ask {agent}"+ agents: ["{agent}"]+kickoff: "@{agent} start"+"""+ document, _ = room_document(template, {"agent": "claude-code.bob"}, {})++ doc = yaml.safe_load(document)+ assert doc["room"]["name"] == "Ask claude-code.bob"+ assert doc["room"]["agents"] == ["claude-code.bob"]+ assert doc["kickoff"] == "@claude-code.bob start"+++async def test_the_saver_check_holds_when_the_mark_is_cleared_after_reading(tools):+ saved = await _as(+ tools["agent_id"],+ save_template,+ name="mine",+ description="",+ yaml=ROOM_TEMPLATE,+ )+ templates = AgentTemplates(TemplateStore(), max_bytes=64 * 1024)+ async with tools["session_factory"]() as session:+ agent = await session.get(Agent, tools["agent_id"])+ owner = await session.get(User, tools["user_id"])+ acting = ActingFor(agent=agent, owner=owner)+ stale = await templates._own(session, acting, saved["id"])++ async def read_before_the_change(*_: Any) -> Template:+ return stale++ templates._own = read_before_the_change # type: ignore[method-assign]+ # Between the read and the lock the mark goes, as when the agent+ # that saved it is deleted.+ async with tools["session_factory"]() as other:+ await other.execute(+ update(Template)+ .where(Template.id == saved["id"])+ .values(created_by_agent_id=None)+ )+ await other.commit()+ with pytest.raises(AgentRefused, match="no longer yours"):+ await templates.update(+ session,+ acting,+ saved["id"],+ name=None,+ description="changed",+ content=None,+ visibility=None,+ )+++SLOTTED_ROOM = """\+params:+ code: {{ type: string, pattern: "[a-z]+", default: {default} }}+ size: {{ type: number, min: 1, max: 5, default: {size} }}+agents:+ - name: worker+ instructions: Work.+room:+ name: "{{code}}"+ description: "Room of {{size}}"+ agents: [worker]+"""+++def test_values_filled_early_are_checked_as_the_server_would():+ with pytest.raises(ValueError, match="does not match the pattern"):+ room_document(SLOTTED_ROOM.format(default="BAD", size=2), {"worker": "b"}, {})+ with pytest.raises(ValueError, match="above the maximum"):+ room_document(SLOTTED_ROOM.format(default="ok", size=9), {"worker": "b"}, {})+++def test_a_string_input_that_looks_like_a_number_stays_a_string():+ document, _ = room_document(+ SLOTTED_ROOM.format(default="ok", size=2), {"worker": "b"}, {"code": "abc"}+ )+ assert yaml.safe_load(document)["room"]["name"] == "abc"+ template = SLOTTED_ROOM.format(default="ok", size=2).replace(+ 'pattern: "[a-z]+", ', ""+ )+ document, _ = room_document(template, {"worker": "b"}, {"code": 123})+ assert yaml.safe_load(document)["room"]["name"] == "123"+++def test_an_undeclared_input_is_still_an_error():+ with pytest.raises(ValueError, match="Undeclared input"):+ room_document(+ SLOTTED_ROOM.format(default="ok", size=2), {"worker": "b"}, {"nope": 1}+ )+++def test_entity_inputs_are_left_for_the_server_to_check():+ template = """\+params:+ target: { type: room }+ helper: { type: agent, default: worker }+agents:+ - name: worker+ instructions: Work.+room:+ name: shop+ description: "Work in {target}"+ agents: ["{helper}"]+"""+ document, inputs = room_document(+ template, {"worker": "claude-code.bob"}, {"target": "nowhere"}+ )++ doc = yaml.safe_load(document)+ # Still params, so the server checks the room and the agent exist.+ assert set(doc["params"]) == {"target", "helper"}+ assert doc["room"]["description"] == "Work in {target}"+ assert inputs == {"target": "nowhere"}+ # The agent default that named the slot now names the agent filling it.+ assert doc["params"]["helper"]["default"] == "claude-code.bob"+++async def test_the_guide_describes_the_language_and_the_example_in_it_is_valid(tools):+ result = await _as(tools["agent_id"], get_template_guide)++ assert "## Params" in result["guide"]+ assert result["schema"]+ # The guide's own example is a document the server accepts. This test+ # server has no messaging app, which `users:` needs, so that line goes.+ example = (+ result["guide"]+ .split("## Example\n\n", 1)[1]+ .replace("[reviewer]", '["claude-code.alice"]')+ .replace("@reviewer", "@claude-code.alice")+ .replace(' users: ["{$creator}"]\n', "")+ )+ created = await _as(+ tools["agent_id"],+ create_room_from_yaml,+ yaml=example,+ inputs={"topic": "billing"},+ )+ assert created["room_name"] == "billing review"+++def test_an_agent_param_whose_candidates_name_a_slot_follows_the_swap():+ template = """\+params:+ member: { type: agent, default: [worker, $first] }+agents:+ - name: worker+ instructions: Work.+room:+ name: shop+ description: The shop+ agents: ["{member}"]+"""+ document, _ = room_document(template, {"worker": "claude-code.bob"}, {})++ assert yaml.safe_load(document)["params"]["member"]["default"] == [+ "claude-code.bob",+ "$first",+ ]+++def test_only_agent_params_follow_the_swap():+ template = """\+params:+ bridge: { type: bridge, default: worker }+ helper: { type: agent }+agents:+ - name: worker+ instructions: Work.+room:+ name: shop+ description: The shop+ bridge: "{bridge}"+ agents: ["{helper}"]+"""+ document, inputs = room_document(+ template, {"worker": "claude-code.bob"}, {"helper": "worker"}+ )++ doc = yaml.safe_load(document)+ assert doc["params"]["bridge"]["default"] == "worker"+ assert inputs == {"helper": "claude-code.bob"}+++def test_unnamed_agents_are_slots_named_after_their_display_name():+ template = """\+agents:+ - display_name: Lead Reviewer+ instructions: Lead.+ - display_name: Second Reviewer+ instructions: Help.+room:+ name: review+ description: Reviews+ agents: [lead-reviewer, second-reviewer]+kickoff: "@lead-reviewer start with @second-reviewer."+"""+ assert [s.name for s in agent_slots(template)] == [+ "Lead Reviewer",+ "Second Reviewer",+ ]++ document, _ = room_document(+ template,+ {"Lead Reviewer": "claude-code.alice", "second-reviewer": "claude-code.bob"},+ {},+ )++ doc = yaml.safe_load(document)+ assert doc["room"]["agents"] == ["claude-code.alice", "claude-code.bob"]+ assert doc["kickoff"] == "@claude-code.alice start with @claude-code.bob."+++async def test_a_template_with_malformed_params_can_still_be_read(tools):+ content = "params: [not, a, mapping]\nroom:\n name: r\n description: d\n"+ template_id = await _stored(tools, tools["user_id"], "broken", content)++ detail = await _as(tools["agent_id"], get_template, template_id=template_id)++ assert detail["params"] == []+ assert detail["content"] == content+++def test_a_group_with_one_agent_is_a_group_as_the_console_says():+ template = """\+agent:+ name: lead+ instructions: Lead.+group: { name: team }+rooms:+ - { name: lobby, description: Lobby, agents: [lead] }+"""+ assert template_kind(template) == "group"diff --git a/core/tests/switch_core/bridges/agent/operations/test_create_room_from_yaml.py b/core/tests/switch_core/bridges/agent/operations/test_create_room_from_yaml.pyindex a504ed741..0d43d0a04 100644--- a/core/tests/switch_core/bridges/agent/operations/test_create_room_from_yaml.py+++ b/core/tests/switch_core/bridges/agent/operations/test_create_room_from_yaml.py@@ -7,225 +7,22 @@ Same FakeRoomService pattern as test_rooms_yaml.py: real PostgreSQL, no Matrix.from __future__ import annotations-import uuid-from types import SimpleNamespacefrom typing import Anyimport pytest-import pytest_asyncio-from sqlalchemy import insert, select-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from sqlalchemy import select-from switch_core.bridges.agent.operations import context as op_contextfrom switch_core.bridges.agent.operations.callctx import (CallContext,reset_call_context,set_call_context,)from switch_core.bridges.agent.operations.definitions import create_room_from_yaml-from switch_core.bridges.resource.service import ResourceService-from switch_core.clients.admin_client import AdminClientfrom switch_core.db.models import (- Agent,- ApiKey,- Client,Room,RoomGroup,RoomLink,- User,- room_agents,)-from switch_core.db.stores.agent_store import AgentStore-from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore-from switch_core.db.stores.document_store import DocumentStore-from switch_core.db.stores.external_user_store import ExternalUserStore-from switch_core.db.stores.package_store import PackageStore-from switch_core.db.stores.reference_store import ReferenceStore-from switch_core.db.stores.reference_type_store import ReferenceTypeStore-from switch_core.db.stores.room_group_store import RoomGroupStore-from switch_core.db.stores.room_link_store import RoomLinkStore-from switch_core.db.stores.room_role_store import RoomRoleStore-from switch_core.db.stores.room_store import RoomStore-from switch_core.db.stores.user_store import UserStore-from switch_core.room_service import RoomCreateConfig, RoomCreateResult-from switch_core.rooms_yaml import RoomYamlService---class FakeRoomService:- """DB-only stand-in, the same as test_rooms_yaml.py's."""-- def __init__(- self,- session_factory: async_sessionmaker[AsyncSession],- agent_store: AgentStore,- ) -> None:- self._sf = session_factory- self._agents = agent_store-- async def create_room(self, config: RoomCreateConfig) -> RoomCreateResult:- async with self._sf() as session:- agent_ids: list[str] = []- if config.agent_names:- agents = await self._agents.get_by_names(session, config.agent_names)- name_to_id = {a.name: a.id for a in agents}- missing = [n for n in config.agent_names if n not in name_to_id]- if missing:- raise ValueError(f"Unknown agents: {', '.join(missing)}")- agent_ids = [name_to_id[n] for n in config.agent_names]-- room = Room(- matrix_room_id=f"!{uuid.uuid4().hex}:test.local",- name=config.name,- description=config.description,- channel_type=config.channel_type or "channel_public",- bridge_id=config.bridge_id,- instructions=config.instructions,- created_by=config.created_by,- owner_id=config.owner_id,- read_visibility=config.read_visibility,- write_visibility=config.write_visibility,- group_id=config.group_id,- )- session.add(room)- await session.flush()- for aid in agent_ids:- await session.execute(- insert(room_agents).values(room_id=room.id, agent_id=aid)- )- await session.commit()- return RoomCreateResult(room=room, failed_attachments=[])---async def _make_agent(- session: AsyncSession, name: str, user_id: str, owner_id: str | None-) -> Agent:- api_key = ApiKey(- user_id=user_id,- key_hash=f"hash-{name}",- encrypted_key="enc",- label=name,- type="agent",- )- client = Client(- matrix_user_id=f"@{name}:test.local",- display_name=name,- type="agent",- )- session.add_all([api_key, client])- await session.flush()- agent = Agent(- name=name,- description=f"{name} desc",- agent_type="always_on",- connector_type="claude_code",- integration_profile={"connection_model": "always_on"},- client_id=client.id,- api_key_id=api_key.id,- owner_id=owner_id,- )- session.add(agent)- await session.flush()- return agent---class RecordingAdminClient(AdminClient):- """Records the platform messages a kickoff sends; has no transport."""-- def __init__(self) -> None: # noqa: D107 - test double, no super().__init__- self.sent: list[dict[str, Any]] = []-- async def wait_joined(self, room_id: str, timeout: float) -> bool:- return True-- async def send_platform_message( # type: ignore[override]- self,- room_id: str,- body: str,- *,- thread_root_id=None,- on_behalf_of=None,- reply_in_channel=False,- ) -> str | None:- self.sent.append({"body": body, "on_behalf_of": on_behalf_of})- return "$kickoff"---class FakeLifecycle:- def __init__(self, admin: AdminClient) -> None:- self.admin = admin-- def get_by_type(self, client_type: str, tenant_id: str) -> list[Any]:- return [self.admin] if client_type == "admin" else []-- def get_by_agent_id(self, agent_id: str) -> None:- return None---@pytest_asyncio.fixture-async def env(session_factory: async_sessionmaker[AsyncSession]):- """Seed a user and two agents, and wire a fake protocol for the operation."""- agent_store = AgentStore()- resource_service = ResourceService(- reference_store=ReferenceStore(),- reference_type_store=ReferenceTypeStore(),- document_store=DocumentStore(),- package_store=PackageStore(),- room_link_store=RoomLinkStore(),- session_factory=session_factory,- )- admin = RecordingAdminClient()- fake_protocol = SimpleNamespace(- client_lifecycle=FakeLifecycle(admin),- session_factory=session_factory,- agent_store=agent_store,- user_store=UserStore(),- room_service=FakeRoomService(session_factory, agent_store),- resource_service=resource_service,- room_store=RoomStore(),- bridge_store=CollaborationBridgeStore(),- external_user_store=ExternalUserStore(),- room_group_store=RoomGroupStore(),- room_role_store=RoomRoleStore(),- )- # The same wiring `ProtocolService.room_yaml_service` does, over the fakes.- fake_protocol.room_yaml_service = lambda: RoomYamlService(- room_service=fake_protocol.room_service,- resource_service=fake_protocol.resource_service,- room_store=fake_protocol.room_store,- agent_store=fake_protocol.agent_store,- bridge_store=fake_protocol.bridge_store,- external_user_store=fake_protocol.external_user_store,- room_role_store=fake_protocol.room_role_store,- session_factory=fake_protocol.session_factory,- room_group_store=fake_protocol.room_group_store,- client_lifecycle=fake_protocol.client_lifecycle,- )-- async with session_factory() as session:- user = User(name="alice", email="[email protected]", role="member")- session.add(user)- await session.flush()- user_id = user.id- agent = await _make_agent(session, "claude-code.alice", user_id, user_id)- await _make_agent(session, "claude-code.bob", user_id, user_id)- orphan = await _make_agent(session, "orphan", user_id, None)- await session.commit()- agent_id = agent.id- orphan_id = orphan.id-- old_protocol = op_context._protocol- op_context.init_operations_protocol(fake_protocol) # type: ignore[arg-type]- try:- yield {- "agent_id": agent_id,- "orphan_id": orphan_id,- "user_id": user_id,- "session_factory": session_factory,- "admin": admin,- }- finally:- op_context._protocol = old_protocol-SINGLE_ROOM_YAML = """\version: 0@@ -323,13 +120,13 @@ kickoff: "Start on the brief."@pytest.mark.asyncio-async def test_kickoff_is_posted_on_behalf_of_the_owner(env):+async def test_kickoff_is_posted_on_behalf_of_the_agent(env):result = await _call(env["agent_id"], yaml=KICKOFF_YAML)assert result["failed_attachments"] == []sent = env["admin"].sentassert [m["body"] for m in sent][-1] == "Start on the brief."- assert all(m["on_behalf_of"].name == "alice" for m in sent)+ assert all(m["on_behalf_of"].agent_id == env["agent_id"] for m in sent)@pytest.mark.asynciodiff --git a/core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py b/core/tests/switch_core/bridges/agent/test_mcp_tool_surface.pyindex c0c88f47c..f1b340a95 100644--- a/core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py+++ b/core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py@@ -79,6 +79,13 @@ async def test_documented_tools_exist(tool_names: set[str]) -> None:"create_room_group","get_room_group_detail","create_room_from_yaml",+ "get_template_guide",+ "list_templates",+ "get_template",+ "run_template",+ "save_template",+ "update_template",+ "delete_template","list_agents","get_agent_detail","update_agent_detail",@@ -143,9 +150,9 @@ def _indexed_tools(skill: Path) -> list[str]:assert bullets, f"no tool bullets under '## Tool index' in {skill}"names = []for bullet in bullets:- match = re.fullmatch(r"- `([a-z_]+)` — .*", bullet)+ match = re.fullmatch(r"- `([a-z_]+)`(?: —|:) .*", bullet)assert match is not None, (- f"{skill}: tool-index bullet is not `- \\`name\\` — description`, so "+ f"{skill}: tool-index bullet is not `- \\`name\\`: description`, so "f"the tool it names would not be checked: {bullet!r}")names.append(match.group(1))diff --git a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py b/core/tests/switch_core/db/test_tenant_exemption_allowlist.pyindex 8335a7005..baeb6ec01 100644--- a/core/tests/switch_core/db/test_tenant_exemption_allowlist.py+++ b/core/tests/switch_core/db/test_tenant_exemption_allowlist.py@@ -119,6 +119,9 @@ _RAW_SESSION_FACTORY_MODULES = {"switch_core.bridges.agent.mediation",# Reached only from the gateway's rooms endpoints, so the same holds."switch_core.rooms_yaml",+ # Runs: reached from the gateway's run endpoints and from an agent's room+ # creation, both of which have bound the caller's tenant.+ "switch_core.agent_runs",# ── Reached only from inside a unit of work that has already bound the# tenant of the row it is acting on — an inbound bridge event, a delivery,# a sweep row, an authenticated agent operation.diff --git a/docs/TEMPLATES.md b/docs/TEMPLATES.mdindex 529f4edbf..608a6ee39 100644--- a/docs/TEMPLATES.md+++ b/docs/TEMPLATES.md@@ -23,8 +23,9 @@ root is the worked example, and `examples/` holds more.8. [Kickoff](#kickoff)9. [Where an agent works](#where-an-agent-works)10. [The form block](#the-form-block)-11. [Validation](#validation)-12. [Versioning](#versioning)+11. [Agents and saved templates](#agents-and-saved-templates)+12. [Validation](#validation)+13. [Versioning](#versioning)## A first template@@ -358,6 +359,25 @@ its members have joined. An agent starts working when a message addressesit, so mention the agent here or it sits in the room without answering.Needs a `room:`; on a group document it goes inside each room entry.+**When an agent runs the template.** The kickoff speaks for that agent, not+its owner, so the agents it mentions wake only if their addressing admits+it. The server checks this before creating anything: if a mentioned agent+would ignore the kickoff, nothing is created and the agent is told which+one and why. The kickoff also carries the run so far, the rooms that led to+this one and who made them, so the agents it wakes can see what already+happened.++**Runs.** Every room an agent creates is recorded in a run: the room it was+working in, and the room the run started from. A template a person runs is+a run of its own; an agent creating a room from an ordinary room, such as a+lobby, starts a new run with that room. Runs are listed in Switch Console+under Templates, Recently used, as a tree, and the owner of an agent in the+run, the person who ran its template, or an admin can stop one. A stopped+run keeps its rooms; agents just cannot create more in it. An agent creates+one room at a time, and when it asks for a room with the same kickoff as one+it already made further up the same path, the run is paused. Continuing it+wakes that agent where it stopped, so the run carries on.+## Where an agent worksThree shapes cover the cases, each one line of template.@@ -426,6 +446,32 @@ it starts open. Folded, it shows its values on one line with a Changebutton, and it opens by itself when something inside it is empty or wrong.The block is the Console's; the server ignores it.+## Agents and saved templates++Agents can use the templates saved on a workspace through their Switch+tools: `list_templates`, `get_template`, `run_template`, `save_template`,+`update_template` and `delete_template`. `get_template_guide` gives an agent+a condensed version of this document and the schema the server checks+documents against (`core/switch_core/template_guide.py`; keep it in step).++- **What an agent sees.** Every shared template, and its owner's private+ ones. An owner's admin rights do not carry over to their agents.+- **Running.** A room or group template runs the way it does from the+ Console, through the same checks as an agent's own rooms (see+ [Kickoff](#kickoff)). An agent cannot create agents, so an agent or team+ template runs only when every agent it describes is replaced by one that+ already exists: `run_template` takes `agents: {slot: existing agent}`,+ and `get_template` lists the slots. The `agent:`/`agents:` block and the+ Console-only params are dropped, and the room half runs.+- **Saving.** An agent saves for its owner, `private` or `shared` (everyone+ reads it, only the saver changes it), and the template records which+ agent saved it. A name the owner already uses is refused.+- **Changing and deleting.** Only the agent that saved a template may change+ or delete it; not its owner's templates, and not another agent's.++A refusal tells the agent why. The server logs it, naming the agent, and+counts it in telemetry by operation and reason.+## ValidationThe server checks a document on upload and before provisioning, and thediff --git a/docs/official/internals/agent-protocol.md b/docs/official/internals/agent-protocol.mdindex fcf35dfad..970390ca6 100644--- a/docs/official/internals/agent-protocol.md+++ b/docs/official/internals/agent-protocol.md@@ -289,6 +289,7 @@ The connection id header is optional and binds the call to a room: it is what th| **Resources** | `list_references`, `list_reference_types`, `create_reference`, `attach_reference_to_room`, `load_internal_documents`, `create_room_document`, `update_room_document`, `delete_room_document` || **Roles** | `list_roles`, `get_role_detail`, `define_role`, `edit_role`, `delete_role`, `assume_role`, `release_role` || **Links and groups** | `list_linked_rooms`, `link_rooms`, `unlink_rooms`, `list_room_groups`, `create_room_group`, `get_room_group_detail` |+| **Templates** | `create_room_from_yaml`, `get_template_guide`, `list_templates`, `get_template`, `run_template`, `save_template`, `update_template`, `delete_template` || **Agents and bridges** | `list_agents`, `get_agent_detail`, `update_agent_detail`, `list_bridges` || **Tasks** | `delegate_task`, `accept_task`, `update_task`, `finalise_task`, `cancel_task`, `list_tasks` — present but not ready for use |diff --git a/docs/old/telemetry-events.md b/docs/old/telemetry-events.mdindex 814599e61..a80f7f4a0 100644--- a/docs/old/telemetry-events.md+++ b/docs/old/telemetry-events.md@@ -734,6 +734,10 @@ reason.which is an owner extending what Switch can point at, not making a reference.- `template_created` / `template_deleted` — `template_kind` names the three theproduct uses and reports anything an operator invents as `other`.+- `agent_request_refused`: an agent asked for something a rule says no to:+ a template it did not save, a run that would need a new agent, a room in a+ paused or stopped run. `operation` and `reason` are fixed lists; which agent+ and which template stay in the server log.- `room_link_created` / `room_link_removed`, `room_role_defined` /`room_role_deleted`, `room_users_added`.- `reference_detached_from_room` / `document_detached_from_room` /