Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Implement Templates (CHOO-2665)

Abel Dantas056a87411dc8
diff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.md
index b323084b3..deaf00d3d 100644
--- a/connectors/claude-code-plugin/skills/switch/SKILL.md
+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md
@@ -822,6 +822,7 @@ failure-mode tools are covered in the sections just above.
- `list_room_groups` — the group tree rooms are organised into.
- `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.
- `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.md
index a0b3e73a9..348844d05 100644
--- a/connectors/codex-plugin/skills/switch/SKILL.md
+++ b/connectors/codex-plugin/skills/switch/SKILL.md
@@ -819,6 +819,7 @@ failure-mode tools are covered in the sections just above.
- `list_room_groups` — the group tree rooms are organised into.
- `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.
- `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.md
index 757a978fd..3c9c08a69 100644
--- a/connectors/opencode-plugin/skills/switch/SKILL.md
+++ b/connectors/opencode-plugin/skills/switch/SKILL.md
@@ -822,6 +822,7 @@ failure-mode tools are covered in the sections just above.
- `list_room_groups` — the group tree rooms are organised into.
- `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.
- `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/electron.vite.config.ts b/console/apps/switch-console-desktop/electron.vite.config.ts
index b471b950f..7ce88c869 100644
--- a/console/apps/switch-console-desktop/electron.vite.config.ts
+++ b/console/apps/switch-console-desktop/electron.vite.config.ts
@@ -61,6 +61,10 @@ export default defineConfig({
// Per-instance so two dev builds from different worktrees can run at
// once; the main process follows through ELECTRON_RENDERER_URL.
port: Number(process.env.SWITCH_CONSOLE_RENDERER_PORT) || 3000,
+ // The bundled Switch expert template is read from `switch-expert/` at
+ // the repository root, outside this app's directory, so the dev server
+ // has to be allowed to serve it; the production build inlines it.
+ fs: { allow: [resolve('../../..')] },
},
},
});
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-templates/agent-template-format.ts b/console/apps/switch-console-desktop/src/main/core/agent-templates/agent-template-format.ts
new file mode 100644
index 000000000..475195bc0
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agent-templates/agent-template-format.ts
@@ -0,0 +1,85 @@
+import { basename, join } from 'node:path';
+
+/**
+ * An agent template is a YAML document with an `agent:` block and, optionally,
+ * a `room:` and `kickoff:` in the room-template shape. The format is described
+ * field by field in `switch-expert/template.yaml` at the repository root.
+ */
+export type AgentTemplateSource = { url: string; label: string | null };
+
+/** Who may address the agent: only its owner, its owner and their agents, or anyone in its rooms. */
+export type AgentTemplateAddressing = 'owner' | 'owner-agents' | 'anyone';
+
+export type ParsedAgentTemplate = {
+ /** The agent name from the template's `name` field. The deployer can change it before creating. */
+ name: string | null;
+ /** Null when the template has no `addressing` field; the Console's default applies (only its owner). */
+ addressing: AgentTemplateAddressing | null;
+ description: string;
+ instructions: string;
+ /** Repository the agent works from. The Console offers to clone it into the
+ * agent's directory; when that is off or fails, the agent clones it itself. */
+ repoUrl: string | null;
+ /** Pages the agent should read. Shown to the deployer; the agent fetches them itself. */
+ sources: AgentTemplateSource[];
+ /** The room the agent is put in once it exists, when the template declares one. */
+ room: { name: string | null; kickoff: string | null } | null;
+ /** A provider id (`claude`, `codex`, `opencode`) or a `{param}` whose value is one. Null when the template has no `provider` field. */
+ provider: string | null;
+ warnings: string[];
+};
+
+export function asRecord(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : null;
+}
+
+export function optionalString(value: unknown): string | null {
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
+}
+
+export function extractSources(raw: unknown): AgentTemplateSource[] {
+ if (!Array.isArray(raw)) return [];
+ return raw.flatMap((entry) => {
+ if (typeof entry === 'string')
+ return optionalString(entry) ? [{ url: entry, label: null }] : [];
+ const record = asRecord(entry);
+ const url = record ? optionalString(record.url) : null;
+ if (!url) return [];
+ return [{ url, label: record ? optionalString(record.label) : null }];
+ });
+}
+
+/**
+ * Remove a leading YAML front matter block from instructions. Claude Code
+ * agent files start with one, and the Console writes its own when it
+ * renders the agent's definition file, so one inside the instructions
+ * would be written twice.
+ */
+export function stripFrontMatter(instructions: string): string {
+ const match = /^---\r?\n[\s\S]*?\r?\n---\r?\n?/.exec(instructions);
+ return match ? instructions.slice(match[0].length).replace(/^\s*\n/, '') : instructions;
+}
+
+/** A folder named after the repository, inside `dir`. */
+export function cloneDirectory(dir: string, repoUrl: string): string {
+ const name = basename(repoUrl.replace(/\/+$/, '')).replace(/\.git$/, '');
+ return join(dir, name || 'repo');
+}
+
+/**
+ * `base`, or the first of `base-2`, `base-3`, … that does not already hold
+ * an agent (a `.switch/` directory). A directory left behind by a removed
+ * agent still holds that agent's credentials, and creating an agent refuses
+ * to overwrite them, so the suggestion moves to a free directory instead of
+ * failing at creation time.
+ */
+export async function firstFreeDirectory(
+ base: string,
+ isTaken: (dir: string) => Promise<boolean>
+): Promise<string> {
+ let candidate = base;
+ for (let i = 2; await isTaken(candidate); i++) candidate = `${base}-${i}`;
+ return candidate;
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-templates/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-templates/controller.test.ts
new file mode 100644
index 000000000..b02dc0f52
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agent-templates/controller.test.ts
@@ -0,0 +1,167 @@
+import { load } from 'js-yaml';
+import { describe, expect, it } from 'vitest';
+import { cloneDirectory, firstFreeDirectory, stripFrontMatter } from './agent-template-format';
+import { composeTemplateDocument, parseAgentTemplate, serverDocument } from './template-document';
+
+const SWITCH_EXPERT = `
+version: 1
+agent:
+ name: switch-expert
+ description: Answers questions about Switch.
+ instructions: |
+ You are switch-expert.
+ repo: https://github.com/sandbox-quantum/switch
+ sources:
+ - label: Stand up a Switch expert
+ url: https://docs.flintai.dev/flintai/switch/getting-started/switch-expert
+ - https://docs.flintai.dev
+room:
+ name: "Ask {agent}"
+ agents: ["{agent}"]
+ users: ["{$creator}"]
+kickoff: |
+ @{agent} hi.
+`;
+
+describe('parseAgentTemplate', () => {
+ it('reads the agent block, the repo and the sources', () => {
+ const t = parseAgentTemplate(SWITCH_EXPERT);
+ expect(t.name).toBe('switch-expert');
+ expect(t.description).toBe('Answers questions about Switch.');
+ expect(t.instructions).toContain('You are switch-expert.');
+ expect(t.repoUrl).toBe('https://github.com/sandbox-quantum/switch');
+ expect(t.sources).toEqual([
+ {
+ label: 'Stand up a Switch expert',
+ url: 'https://docs.flintai.dev/flintai/switch/getting-started/switch-expert',
+ },
+ { label: null, url: 'https://docs.flintai.dev' },
+ ]);
+ expect(t.room).toEqual({ name: 'Ask {agent}', kickoff: '@{agent} hi.' });
+ expect(t.warnings).toEqual([]);
+ });
+
+ it('is fine without a room, a repo or sources', () => {
+ const t = parseAgentTemplate('agent:\n description: d\n instructions: i\n');
+ expect(t.name).toBeNull();
+ expect(t.repoUrl).toBeNull();
+ expect(t.sources).toEqual([]);
+ expect(t.room).toBeNull();
+ });
+
+ it('reads who may address the agent, and warns about a value it does not know', () => {
+ expect(parseAgentTemplate('agent:\n instructions: i\n addressing: anyone\n').addressing).toBe(
+ 'anyone'
+ );
+ expect(parseAgentTemplate('agent:\n instructions: i\n').addressing).toBeNull();
+ const odd = parseAgentTemplate('agent:\n instructions: i\n addressing: everyone\n');
+ expect(odd.addressing).toBeNull();
+ expect(odd.warnings[0]).toMatch(/addressing/);
+ });
+
+ it('refuses a document with no agent block', () => {
+ expect(() => parseAgentTemplate('room:\n name: r\n')).toThrow(/"agent:" block/);
+ });
+
+ it('refuses an agent with no instructions', () => {
+ expect(() => parseAgentTemplate('agent:\n name: a\n description: d\n')).toThrow(
+ /instructions/
+ );
+ });
+
+ it('refuses text that is not YAML', () => {
+ expect(() => parseAgentTemplate('agent: [')).toThrow(/Invalid YAML/);
+ });
+
+ it('warns about a kickoff with no room to land in', () => {
+ const t = parseAgentTemplate('agent:\n instructions: i\nkickoff: hi\n');
+ expect(t.warnings).toHaveLength(1);
+ expect(t.warnings[0]).toMatch(/kickoff/);
+ });
+});
+
+describe('stripFrontMatter', () => {
+ it('drops a leading front matter block and keeps the body', () => {
+ expect(stripFrontMatter('---\nname: x\ndescription: y\n---\n\nYou are x.\n')).toBe(
+ 'You are x.\n'
+ );
+ });
+
+ it('leaves instructions without front matter alone', () => {
+ expect(stripFrontMatter('You are x.\n---\nnot front matter\n')).toBe(
+ 'You are x.\n---\nnot front matter\n'
+ );
+ });
+
+ it('applies to the fallback instructions too', () => {
+ const t = parseAgentTemplate('agent:\n description: d\n', '---\nname: a\n---\nBody.\n');
+ expect(t.instructions).toBe('Body.\n');
+ });
+});
+
+describe('serverDocument', () => {
+ it('turns the room half into a room template with the agent as a declared param', () => {
+ const yaml = serverDocument(SWITCH_EXPERT);
+ expect(yaml).not.toBeNull();
+ const doc = load(yaml!) as Record<string, unknown>;
+ expect(Object.keys(doc).sort()).toEqual(['kickoff', 'params', 'room', 'version']);
+ expect((doc.params as Record<string, unknown>).agent).toMatchObject({ type: 'string' });
+ expect(doc.room).toEqual({
+ name: 'Ask {agent}',
+ agents: ['{agent}'],
+ users: ['{$creator}'],
+ });
+ expect(doc.kickoff).toBe('@{agent} hi.\n');
+ expect(doc).not.toHaveProperty('agent');
+ });
+
+ it('keeps params the template declares itself', () => {
+ const yaml = serverDocument(
+ 'agent:\n instructions: i\nparams:\n topic:\n type: string\nroom:\n name: "{topic}"\n'
+ );
+ const doc = load(yaml!) as { params: Record<string, unknown> };
+ expect(Object.keys(doc.params).sort()).toEqual(['agent', 'topic']);
+ });
+
+ it('is null when the template has no room', () => {
+ expect(serverDocument('agent:\n instructions: i\n')).toBeNull();
+ });
+});
+
+describe('composeTemplateDocument', () => {
+ it('inlines the persona, minus its front matter, and keeps the rest of the document', () => {
+ const out = composeTemplateDocument(
+ 'agent:\n name: a\n repo: https://x/y\nroom:\n name: r\n',
+ '---\nname: a\n---\nBody.\n'
+ );
+ const doc = load(out) as { agent: Record<string, unknown>; room: Record<string, unknown> };
+ expect(doc.agent.instructions).toBe('Body.\n');
+ expect(doc.agent.repo).toBe('https://x/y');
+ expect(doc.room).toEqual({ name: 'r' });
+ expect(parseAgentTemplate(out).instructions).toBe('Body.\n');
+ });
+
+ it('leaves inline instructions alone', () => {
+ const out = composeTemplateDocument('agent:\n instructions: mine\n', 'other');
+ expect((load(out) as { agent: { instructions: string } }).agent.instructions).toBe('mine');
+ });
+});
+
+describe('cloneDirectory', () => {
+ it('names the clone after the repository', () => {
+ expect(cloneDirectory('/w/switch-expert', 'https://github.com/sandbox-quantum/switch')).toBe(
+ '/w/switch-expert/switch'
+ );
+ expect(cloneDirectory('/w', 'https://github.com/jqlang/jq.git')).toBe('/w/jq');
+ expect(cloneDirectory('/w', '[email protected]:jqlang/jq.git')).toBe('/w/jq');
+ expect(cloneDirectory('/w', 'https://example.com/repo/')).toBe('/w/repo');
+ });
+});
+
+describe('firstFreeDirectory', () => {
+ it('keeps the base when nothing lives there, and steps past folders that hold an agent', async () => {
+ expect(await firstFreeDirectory('/w/a', async () => false)).toBe('/w/a');
+ const taken = new Set(['/w/a', '/w/a-2']);
+ expect(await firstFreeDirectory('/w/a', async (d) => taken.has(d))).toBe('/w/a-3');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-templates/controller.ts b/console/apps/switch-console-desktop/src/main/core/agent-templates/controller.ts
new file mode 100644
index 000000000..15dea5a47
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agent-templates/controller.ts
@@ -0,0 +1,244 @@
+import { execFile } from 'node:child_process';
+import { mkdir, stat } from 'node:fs/promises';
+import { join } from 'node:path';
+import { promisify } from 'node:util';
+import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';
+import type { IExecutionContext } from '@main/core/execution-context/types';
+import { sshConnectionIdForHost } from '@main/core/locations/location-transport';
+import { appSettingsService } from '@main/core/settings/settings-service';
+import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';
+import { resolveRemoteHome } from '@main/core/ssh/lifecycle/remote-shell-profile';
+import { getGitExecutable } from '@main/core/utils/exec';
+import { buildExternalToolEnv } from '@main/utils/childProcessEnv';
+import { createRPCController } from '@shared/lib/ipc/rpc';
+import {
+ cloneDirectory,
+ firstFreeDirectory,
+ type ParsedAgentTemplate,
+} from './agent-template-format';
+import {
+ composeTemplateDocument,
+ type FormOptions,
+ formOptions,
+ parseAgentTemplate,
+ serverDocument,
+ parseTemplateAgents,
+ substituteAgentSlots,
+ type TemplateAgents,
+ templateKind,
+ type TemplateKind,
+} from './template-document';
+import { summarizeTemplate, type TemplateSummary } from './template-summary';
+
+const execFileAsync = promisify(execFile);
+
+// Only URL forms git can clone. A value starting with `-` would be read by
+// git as a command-line option, not a URL.
+const CLONEABLE_URL = /^(https?:\/\/|git@|ssh:\/\/)[^\s-]/;
+
+export type PrepareWorkspaceResult = {
+ dir: string;
+ /** The outcome of the clone, when the template has a `repo` field. */
+ repo: {
+ target: string;
+ outcome: 'cloned' | 'present' | 'failed';
+ error: string | null;
+ } | null;
+};
+
+async function isDirectory(path: string): Promise<boolean> {
+ try {
+ return (await stat(path)).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+async function remoteContext(sshHost: string): Promise<IExecutionContext> {
+ const proxy = await ensureSshConnected(sshConnectionIdForHost(sshHost), sshHost);
+ return new SshExecutionContext(proxy);
+}
+
+// On a host, agents get the same one-folder-per-agent layout as on this
+// machine, under the host's home. The Console's default on this machine is
+// `~/.switch/agents`.
+const REMOTE_LOCATIONS_DIR = '.switch/agents';
+
+function failedRepo(dir: string, target: string, e: unknown): PrepareWorkspaceResult {
+ const stderr = (e as { stderr?: string }).stderr;
+ const message =
+ typeof stderr === 'string' && stderr.trim().length > 0
+ ? stderr.trim()
+ : e instanceof Error
+ ? e.message
+ : String(e);
+ return { dir, repo: { target, outcome: 'failed', error: message } };
+}
+
+/** Make the directory and put a shallow clone inside, on a host reached over SSH. */
+async function prepareRemoteWorkspace(
+ sshHost: string,
+ dir: string,
+ repoUrl: string | null
+): Promise<PrepareWorkspaceResult> {
+ const ctx = await remoteContext(sshHost);
+ try {
+ await ctx.exec('mkdir', ['-p', dir]);
+ if (!repoUrl) return { dir, repo: null };
+ const target = cloneDirectory(dir, repoUrl);
+ const probe = await ctx.exec('sh', [
+ '-c',
+ `test -d "$1" && echo present || echo absent`,
+ 'sh',
+ target,
+ ]);
+ if (probe.stdout.trim() === 'present') {
+ return { dir, repo: { target, outcome: 'present', error: null } };
+ }
+ if (!CLONEABLE_URL.test(repoUrl)) {
+ return {
+ dir,
+ repo: {
+ target,
+ outcome: 'failed',
+ error: `Not a URL git can clone: ${repoUrl}`,
+ },
+ };
+ }
+ try {
+ await ctx.exec('git', ['clone', '--quiet', '--depth', '1', '--', repoUrl, target]);
+ return { dir, repo: { target, outcome: 'cloned', error: null } };
+ } catch (e) {
+ return failedRepo(dir, target, e);
+ }
+ } finally {
+ ctx.dispose();
+ }
+}
+
+export const agentTemplatesController = createRPCController({
+ parse: (params: { yamlText: string; instructions?: string | null }): ParsedAgentTemplate =>
+ parseAgentTemplate(params.yamlText, params.instructions ?? null),
+
+ /** What a document of any known shape creates, for a listing card. */
+ summarize: (params: { yamlText: string }): TemplateSummary => summarizeTemplate(params.yamlText),
+
+ /** Classify a document as an agent, room or group template. */
+ kind: (params: { yamlText: string }): TemplateKind => templateKind(params.yamlText),
+
+ /** The agents a document creates. Empty for a room template. */
+ parseAgents: (params: { yamlText: string; instructions?: string | null }): TemplateAgents =>
+ parseTemplateAgents(params.yamlText, params.instructions ?? null),
+
+ /** The layout choices the document's `form:` block makes for the Use page. */
+ form: (params: { yamlText: string }): FormOptions => formOptions(params.yamlText),
+
+ /** The room part of a document as the server receives it, or null when the document has no rooms. */
+ serverDocument: (params: { yamlText: string; keepConsoleParams?: boolean }): string | null =>
+ serverDocument(params.yamlText, { keepConsoleParams: params.keepConsoleParams }),
+
+ /** The server document with agent names replaced (see `substituteAgentSlots`). */
+ substituteSlots: (params: { coreYaml: string; replacements: Record<string, string> }): string =>
+ substituteAgentSlots(params.coreYaml, params.replacements),
+
+ /** The document with every agent's instructions inlined, ready to store on a server. */
+ compose: (params: { yamlText: string; instructions: string }): string =>
+ composeTemplateDocument(params.yamlText, params.instructions),
+
+ /** The directory agents are kept under, on this machine or on `sshHost`:
+ * the `{$agents_dir}` a template's `directory` field may refer to. */
+ agentsDirectory: async (params: { sshHost?: string | null }): Promise<string> => {
+ if (params.sshHost) {
+ const ctx = await remoteContext(params.sshHost);
+ try {
+ const home = await resolveRemoteHome(ctx);
+ return `${home.replace(/\/+$/, '')}/${REMOTE_LOCATIONS_DIR}`;
+ } finally {
+ ctx.dispose();
+ }
+ }
+ const { defaultLocationsDirectory } = await appSettingsService.get('localLocation');
+ return defaultLocationsDirectory;
+ },
+
+ /** The default working directory for an agent of this name: a folder named
+ * after it under the Console's locations directory, or under the host's
+ * home when `sshHost` is given. */
+ suggestDirectory: async (params: {
+ agentName: string;
+ sshHost?: string | null;
+ }): Promise<string> => {
+ if (params.sshHost) {
+ const ctx = await remoteContext(params.sshHost);
+ try {
+ const home = await resolveRemoteHome(ctx);
+ const base = `${home.replace(/\/+$/, '')}/${REMOTE_LOCATIONS_DIR}/${params.agentName}`;
+ // `return await`, not `return`: with a bare `return` the `finally`
+ // below would dispose the SSH context before the probes finished.
+ return await firstFreeDirectory(base, async (dir) => {
+ // Both outcomes exit 0. The runner treats a non-zero exit as a
+ // failed command, and "free" is an answer, not a failure.
+ const probe = await ctx.exec('sh', [
+ '-c',
+ 'test -e "$1/.switch" && echo taken || echo free',
+ 'sh',
+ dir,
+ ]);
+ return probe.stdout.trim() === 'taken';
+ });
+ } finally {
+ ctx.dispose();
+ }
+ }
+ const { defaultLocationsDirectory } = await appSettingsService.get('localLocation');
+ return firstFreeDirectory(join(defaultLocationsDirectory, params.agentName), (dir) =>
+ isDirectory(join(dir, '.switch'))
+ );
+ },
+
+ /**
+ * Create the working directory and, when the template has a `repo` field,
+ * put a shallow clone of it inside. A failed clone is reported in the
+ * result rather than thrown, so the agent is still created and clones the
+ * repository itself.
+ */
+ prepareWorkspace: async (params: {
+ dir: string;
+ repoUrl: string | null;
+ sshHost?: string | null;
+ }): Promise<PrepareWorkspaceResult> => {
+ if (params.sshHost) return prepareRemoteWorkspace(params.sshHost, params.dir, params.repoUrl);
+ await mkdir(params.dir, { recursive: true });
+ if (!params.repoUrl) return { dir: params.dir, repo: null };
+ const target = cloneDirectory(params.dir, params.repoUrl);
+ if (await isDirectory(target)) {
+ return {
+ dir: params.dir,
+ repo: { target, outcome: 'present', error: null },
+ };
+ }
+ if (!CLONEABLE_URL.test(params.repoUrl)) {
+ return {
+ dir: params.dir,
+ repo: {
+ target,
+ outcome: 'failed',
+ error: `Not a URL git can clone: ${params.repoUrl}`,
+ },
+ };
+ }
+ try {
+ await execFileAsync(
+ getGitExecutable(),
+ ['clone', '--quiet', '--depth', '1', '--', params.repoUrl, target],
+ { env: buildExternalToolEnv(), timeout: 5 * 60 * 1000 }
+ );
+ return {
+ dir: params.dir,
+ repo: { target, outcome: 'cloned', error: null },
+ };
+ } catch (e) {
+ return failedRepo(params.dir, target, e);
+ }
+ },
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-templates/template-document.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-templates/template-document.test.ts
new file mode 100644
index 000000000..5c515e0bd
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agent-templates/template-document.test.ts
@@ -0,0 +1,241 @@
+import { load } from 'js-yaml';
+import { describe, expect, it } from 'vitest';
+import {
+ composeTemplateDocument,
+ formOptions,
+ serverDocument,
+ parseAgentTemplate,
+ parseTemplateAgents,
+ substituteAgentSlots,
+ templateKind,
+} from './template-document';
+
+const TRIAGE_PAIR = `
+version: 1
+params:
+ team:
+ type: string
+ description: Prefix for every name this creates
+ provider:
+ type: provider
+ default: claude
+ bridge:
+ type: bridge
+agents:
+ - name: "{team}-triager"
+ description: Reads reports, files and routes them
+ instructions: You triage.
+ provider: "{provider}"
+ - name: "{team}-repro"
+ description: Reproduces what the triager routes to it
+ instructions: You reproduce.
+ repo: https://github.com/sandbox-quantum/switch
+room:
+ name: "{team}-triage"
+ bridge: "{bridge}"
+ agents: ["{team}-triager", "{team}-repro"]
+ aliases:
+ "{team}-triager": triager
+kickoff: Start.
+`;
+
+const SOLO = `
+agent:
+ name: jq-expert
+ instructions: You know jq.
+room:
+ name: "Ask {agent}"
+ agents: ["{agent}"]
+`;
+
+describe('templateKind', () => {
+ it('tells the three shapes apart', () => {
+ expect(templateKind(TRIAGE_PAIR)).toBe('group');
+ expect(templateKind(SOLO)).toBe('agent');
+ expect(templateKind('room:\n name: r\n')).toBe('room');
+ expect(templateKind('group:\n name: g\nrooms:\n - name: a\n')).toBe('group');
+ });
+});
+
+describe('parseTemplateAgents', () => {
+ it('reads every agent of a list, provider included', () => {
+ const { agents, warnings } = parseTemplateAgents(TRIAGE_PAIR);
+ expect(warnings).toEqual([]);
+ expect(agents.map((a) => a.name)).toEqual(['{team}-triager', '{team}-repro']);
+ expect(agents[0].provider).toBe('{provider}');
+ expect(agents[1].provider).toBeNull();
+ expect(agents[1].repoUrl).toBe('https://github.com/sandbox-quantum/switch');
+ });
+
+ it('reads a lone agent and fills its instructions from the fallback', () => {
+ const { agents } = parseTemplateAgents('agent:\n name: x\n', 'Persona.');
+ expect(agents).toHaveLength(1);
+ expect(agents[0].instructions).toBe('Persona.');
+ });
+
+ it('tells a lone agent: from a one-entry list', () => {
+ expect(parseTemplateAgents('agent:\n name: a\n instructions: i\n').singular).toBe(true);
+ expect(parseTemplateAgents('agents:\n - name: a\n instructions: i\n').singular).toBe(false);
+ });
+
+ it('gives a room template no agents', () => {
+ expect(parseTemplateAgents('room:\n name: r\n').agents).toEqual([]);
+ });
+
+ it('refuses a listed agent with nothing to go on', () => {
+ expect(() =>
+ parseTemplateAgents('agents:\n - name: a\n instructions: ok\n - name: b\n')
+ ).toThrow(/agent 2 needs "instructions:"/);
+ });
+});
+
+describe('serverDocument', () => {
+ it('keeps the server half and drops agents and provider params', () => {
+ const doc = load(serverDocument(TRIAGE_PAIR) ?? '') as Record<string, unknown>;
+ expect(Object.keys(doc).sort()).toEqual(['kickoff', 'params', 'room', 'version']);
+ expect(Object.keys(doc.params as object)).toEqual(['team', 'bridge']);
+ expect((doc.room as { agents: string[] }).agents).toEqual(['{team}-triager', '{team}-repro']);
+ });
+
+ it('keeps provider params when asked, for the form', () => {
+ const doc = load(serverDocument(TRIAGE_PAIR, { keepConsoleParams: true }) ?? '') as {
+ params: Record<string, unknown>;
+ };
+ expect(Object.keys(doc.params)).toEqual(['team', 'provider', 'bridge']);
+ });
+
+ it('drops params only an agent entry reads, and every Console type', () => {
+ const doc = load(
+ serverDocument(
+ [
+ 'params:',
+ ' name:',
+ ' type: string',
+ ' default: Expert',
+ ' where:',
+ ' type: room',
+ ' default: [$new]',
+ ' location:',
+ ' type: location',
+ ' default: local',
+ ' bridge:',
+ ' type: bridge',
+ ' default: [$first]',
+ 'agent:',
+ ' display_name: "{name}"',
+ ' location: "{location}"',
+ ' join: ["{where}"]',
+ 'room:',
+ ' name: "Ask {agent}"',
+ ' bridge: "{bridge}"',
+ ].join('\n')
+ ) ?? ''
+ ) as { params: Record<string, unknown> };
+ expect(Object.keys(doc.params)).toEqual(['agent', 'bridge']);
+ expect(doc.params.bridge).toEqual({ type: 'bridge', default: ['$first'] });
+ });
+
+ it('declares {agent} for a lone agent', () => {
+ const doc = load(serverDocument(SOLO) ?? '') as { params: Record<string, unknown> };
+ expect(Object.keys(doc.params)).toEqual(['agent']);
+ });
+
+ it('keeps a group document whole', () => {
+ const text =
+ 'group:\n name: g\nrooms:\n - name: a\n kickoff: hi\nlinks: []\nagents:\n - name: x\n instructions: i\n';
+ const doc = load(serverDocument(text) ?? '') as Record<string, unknown>;
+ expect(Object.keys(doc).sort()).toEqual(['group', 'links', 'rooms']);
+ });
+
+ it('keeps a misplaced group kickoff for the server to refuse', () => {
+ const doc = load(
+ serverDocument('group:\n name: g\nrooms:\n - name: a\nkickoff: hi\n') ?? ''
+ ) as Record<string, unknown>;
+ expect(doc.kickoff).toBe('hi');
+ });
+
+ it('is null without a room half', () => {
+ expect(serverDocument('agent:\n name: a\n instructions: i\n')).toBeNull();
+ });
+});
+
+describe('substituteAgentSlots', () => {
+ it('renames agents in every room, aliases included', () => {
+ const core = serverDocument(TRIAGE_PAIR) ?? '';
+ const out = load(substituteAgentSlots(core, { '{team}-triager': 'claude-code.alice' })) as {
+ room: { agents: string[]; aliases: Record<string, string> };
+ };
+ expect(out.room.agents).toEqual(['claude-code.alice', '{team}-repro']);
+ expect(out.room.aliases).toEqual({ 'claude-code.alice': 'triager' });
+ });
+});
+
+describe('substituteAgentSlots kickoffs', () => {
+ it('renames the mentions in a kickoff too', () => {
+ const core =
+ 'room:\n name: r\n agents: ["{team}-a"]\n kickoff: "@{team}-a go"\nkickoff: "@{team}-a hi"\n';
+ const out = load(substituteAgentSlots(core, { '{team}-a': 'alpha-a-2' })) as {
+ room: { kickoff: string };
+ kickoff: string;
+ };
+ expect(out.kickoff).toBe('@alpha-a-2 hi');
+ expect(out.room.kickoff).toBe('@alpha-a-2 go');
+ });
+});
+
+describe('composeTemplateDocument', () => {
+ it('fills every agent missing instructions', () => {
+ const out = load(
+ composeTemplateDocument('agents:\n - name: a\n - name: b\n instructions: own\n', 'P')
+ ) as { agents: { instructions: string }[] };
+ expect(out.agents.map((a) => a.instructions)).toEqual(['P', 'own']);
+ });
+});
+
+describe('substituteAgentSlots: whole names', () => {
+ it('leaves a longer name alone when a shorter one that starts it is renamed', () => {
+ const core =
+ 'room:\n name: r\n agents: [helper, helper-bot]\nkickoff: "@helper-bot please brief @helper."\n';
+ const out = load(substituteAgentSlots(core, { helper: 'bob' })) as {
+ room: { agents: string[] };
+ kickoff: string;
+ };
+ expect(out.room.agents).toEqual(['bob', 'helper-bot']);
+ expect(out.kickoff).toBe('@helper-bot please brief @bob.');
+ });
+
+ it('renames both when both change, whichever order the map lists them', () => {
+ const core = 'room:\n name: r\n agents: ["{t}-a", "{t}-ab"]\nkickoff: "@{t}-a and @{t}-ab"\n';
+ for (const map of [
+ { '{t}-a': 'x-a', '{t}-ab': 'x-ab' },
+ { '{t}-ab': 'x-ab', '{t}-a': 'x-a' },
+ ]) {
+ const out = load(substituteAgentSlots(core, map)) as { kickoff: string };
+ expect(out.kickoff).toBe('@x-a and @x-ab');
+ }
+ });
+
+ it('leaves a name that ends in the renamed one alone, and a dotted one too', () => {
+ const core =
+ 'room:\n name: r\n agents: [helper]\nkickoff: "@my-helper, @helper._bot and @helper."\n';
+ const out = load(substituteAgentSlots(core, { helper: 'bob' })) as { kickoff: string };
+ expect(out.kickoff).toBe('@my-helper, @helper._bot and @bob.');
+ });
+
+ it('has no single-agent view of a document with several agents', () => {
+ expect(() => parseAgentTemplate('agents:\n - name: a\n instructions: i\n')).toThrow(
+ /several agents/
+ );
+ });
+});
+
+describe('formOptions', () => {
+ it('reads the advanced fold settings and falls back to a folded "Advanced"', () => {
+ expect(
+ formOptions('form:\n advanced:\n label: More\n open: true\nroom:\n name: r\n')
+ ).toEqual({ advanced: { label: 'More', open: true } });
+ expect(formOptions('room:\n name: r\n')).toEqual({
+ advanced: { label: 'Advanced', open: false },
+ });
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-templates/template-document.ts b/console/apps/switch-console-desktop/src/main/core/agent-templates/template-document.ts
new file mode 100644
index 000000000..5ee401ba9
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agent-templates/template-document.ts
@@ -0,0 +1,386 @@
+import { dump, load } from 'js-yaml';
+import {
+ CONSOLE_PARAM_TYPES,
+ type ConsoleParamType,
+} from '@shared/core/switch-servers/room-template-params';
+import {
+ type AgentTemplateAddressing,
+ type AgentTemplateSource,
+ extractSources,
+ optionalString,
+ type ParsedAgentTemplate,
+ stripFrontMatter,
+} from './agent-template-format';
+
+/**
+ * Helpers for a template document.
+ *
+ * The Console creates the agents listed under `agent:` or `agents:`, because
+ * an agent runs on a machine the Console can reach and the server cannot.
+ * The server creates the rooms under `room:`, or `group:` with `rooms:`,
+ * through `POST /rooms/from-yaml`.
+ *
+ * A room's `agents:` list refers to those agents by the text written in the
+ * template, `{team}-triager` for example, before any `{param}` is filled in.
+ * The helpers here compare that unfilled text to match a room entry with
+ * the agent it refers to.
+ *
+ * `switch-expert/template.yaml` at the repository root documents every field.
+ */
+export type TemplateKind = 'agent' | 'room' | 'group';
+
+export type ParsedAgentEntry = {
+ /** The name as written in the template, with any `{param}` still unfilled. */
+ name: string | null;
+ /** How the agent is shown to people, when the template gives one. */
+ displayName: string | null;
+ description: string;
+ instructions: string;
+ repoUrl: string | null;
+ sources: AgentTemplateSource[];
+ addressing: AgentTemplateAddressing | null;
+ /**
+ * Which coding agent runs it. Either a provider id (`claude`, `codex`,
+ * `opencode`) or a `{param}` whose value is one. Null when the template
+ * has no `provider` field; the Use page asks for one.
+ */
+ provider: string | null;
+ /** Where it runs: `local`, an ssh host, or a `{param}`. Null when the template has no `location` field. */
+ location: string | null;
+ /** Its working directory, or a `{param}`. Null when the template has no `directory` field. */
+ directory: string | null;
+ /** Rooms the agent is added to once it exists, by name or `{param}`. */
+ join: string[];
+};
+
+export type TemplateAgents = {
+ agents: ParsedAgentEntry[];
+ /**
+ * True when the document uses the singular `agent:` form. That form has
+ * one extra convention: its room refers to the agent as `{agent}`, and the
+ * Console fills that in with the agent's final name.
+ */
+ singular: boolean;
+ warnings: string[];
+};
+
+const ADDRESSING_VALUES: ReadonlySet<string> = new Set(['owner', 'owner-agents', 'anyone']);
+
+export function parseYaml(yamlText: string): Record<string, unknown> {
+ let doc: unknown;
+ try {
+ doc = load(yamlText);
+ } catch (e) {
+ throw new Error(`Invalid YAML: ${e instanceof Error ? e.message : String(e)}`);
+ }
+ if (doc === null || typeof doc !== 'object' || Array.isArray(doc)) {
+ throw new Error('Template must be a YAML mapping');
+ }
+ return doc as Record<string, unknown>;
+}
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : null;
+}
+
+/** The agent entries as parsed YAML objects, from `agents:` (a list) or `agent:` (a single entry). */
+function rawAgents(doc: Record<string, unknown>): Record<string, unknown>[] {
+ if (Array.isArray(doc.agents)) {
+ return doc.agents.map((a) => asRecord(a)).filter((a): a is Record<string, unknown> => !!a);
+ }
+ const one = asRecord(doc.agent);
+ return one ? [one] : [];
+}
+
+/**
+ * Classify a document. `group`: it has `group:` or `rooms:`, or more than
+ * one agent. `agent`: one agent, with or without a room. `room`: a room and
+ * no agents.
+ */
+export function templateKind(yamlText: string): TemplateKind {
+ return kindOf(parseYaml(yamlText));
+}
+
+export function kindOf(doc: Record<string, unknown>): TemplateKind {
+ const agents = rawAgents(doc);
+ if (doc.group !== undefined || Array.isArray(doc.rooms)) return 'group';
+ if (agents.length > 1) return 'group';
+ if (agents.length === 1) return 'agent';
+ return 'room';
+}
+
+/**
+ * Parse every agent entry of a document.
+ *
+ * `fallbackInstructions` is used when a single `agent:` has no
+ * `instructions:` of its own. The bundled Switch expert is the case: its
+ * instructions live in `AGENT.md` next to the template rather than inside
+ * it, and the Console passes that file's content here.
+ */
+export function parseTemplateAgents(
+ yamlText: string,
+ fallbackInstructions: string | null = null
+): TemplateAgents {
+ const doc = parseYaml(yamlText);
+ const entries = rawAgents(doc);
+ const warnings: string[] = [];
+ if (Array.isArray(doc.agents) && entries.length !== doc.agents.length) {
+ warnings.push('Every entry of `agents:` must be a mapping with a `name:`.');
+ }
+ const hasRoom = asRecord(doc.room) !== null || Array.isArray(doc.rooms);
+ if (typeof doc.kickoff === 'string' && !hasRoom) {
+ warnings.push('`kickoff:` needs a `room:` to be posted into; without one it is ignored.');
+ }
+ const agents = entries.map((agent, i) => {
+ const label = entries.length === 1 ? '`agent:`' : `agent ${i + 1}`;
+ const inline =
+ typeof agent.instructions === 'string' && agent.instructions.trim().length > 0
+ ? agent.instructions
+ : entries.length === 1
+ ? (fallbackInstructions ?? '')
+ : '';
+ const instructions = stripFrontMatter(inline);
+ if (instructions.trim().length === 0) {
+ throw new Error(`${label} needs "instructions:" — the agent has nothing to go on.`);
+ }
+ if (typeof agent.kickoff === 'string' || typeof agent.room === 'object') {
+ warnings.push('`room:` and `kickoff:` belong at the top level, beside `agent:`.');
+ }
+ const addressing = optionalString(agent.addressing);
+ if (addressing !== null && !ADDRESSING_VALUES.has(addressing)) {
+ warnings.push(
+ `\`addressing: ${addressing}\` is not one of owner, owner-agents, anyone; the agent will answer only its owner.`
+ );
+ }
+ return {
+ name: optionalString(agent.name),
+ displayName: optionalString(agent.display_name),
+ description: typeof agent.description === 'string' ? agent.description.trim() : '',
+ instructions,
+ repoUrl: optionalString(agent.repo),
+ sources: extractSources(agent.sources),
+ addressing: ADDRESSING_VALUES.has(addressing ?? '')
+ ? (addressing as AgentTemplateAddressing)
+ : null,
+ provider: optionalString(agent.provider),
+ location: optionalString(agent.location),
+ directory: optionalString(agent.directory),
+ join: Array.isArray(agent.join)
+ ? agent.join.filter((r): r is string => typeof r === 'string' && r.trim().length > 0)
+ : [],
+ };
+ });
+ return { agents, singular: !Array.isArray(doc.agents) && agents.length === 1, warnings };
+}
+
+/** How the Use page lays out what the template folds away. From the document's `form:` block. */
+export type FormOptions = {
+ advanced: {
+ /** The heading of the fold that holds the `input: advanced` and `input: fixed` params. */
+ label: string;
+ /** Whether the fold starts open. */
+ open: boolean;
+ };
+};
+
+export function formOptions(yamlText: string): FormOptions {
+ const form = asRecord(parseYaml(yamlText).form);
+ const advanced = asRecord(form?.advanced);
+ return {
+ advanced: {
+ label: optionalString(advanced?.label) ?? 'Advanced',
+ open: advanced?.open === true,
+ },
+ };
+}
+
+/**
+ * The single-agent view of a document: the first agent entry and the room it
+ * is put in. What the agent's settings page reads when it offers the
+ * template's current instructions. Same parse as `parseTemplateAgents`.
+ */
+export function parseAgentTemplate(
+ yamlText: string,
+ fallbackInstructions: string | null = null
+): ParsedAgentTemplate {
+ const doc = parseYaml(yamlText);
+ if (asRecord(doc.agent) === null) {
+ throw new Error(
+ Array.isArray(doc.agents)
+ ? 'This template creates several agents, so it has no single set of instructions to offer.'
+ : 'Template must have an "agent:" block.'
+ );
+ }
+ const { agents, warnings } = parseTemplateAgents(yamlText, fallbackInstructions);
+ const [agent] = agents;
+ if (!agent) throw new Error('Template must have an "agent:" block.');
+ const room = asRecord(doc.room);
+ return {
+ name: agent.name,
+ addressing: agent.addressing,
+ description: agent.description,
+ instructions: agent.instructions,
+ repoUrl: agent.repoUrl,
+ sources: agent.sources,
+ room: room ? { name: optionalString(room.name), kickoff: optionalString(doc.kickoff) } : null,
+ provider: agent.provider,
+ warnings,
+ };
+}
+
+function isConsoleParam(spec: unknown): boolean {
+ const record = asRecord(spec);
+ return record !== null && CONSOLE_PARAM_TYPES.includes(record.type as ConsoleParamType);
+}
+
+/** Every `{name}` placeholder written anywhere inside `node`. */
+function placeholdersIn(node: unknown, into: Set<string> = new Set()): Set<string> {
+ if (typeof node === 'string') {
+ for (const match of node.matchAll(/\{(\$?\w+)\}/g)) into.add(match[1]);
+ } else if (Array.isArray(node)) {
+ for (const item of node) placeholdersIn(item, into);
+ } else if (node !== null && typeof node === 'object') {
+ for (const [key, value] of Object.entries(node)) {
+ placeholdersIn(key, into);
+ placeholdersIn(value, into);
+ }
+ }
+ return into;
+}
+
+/**
+ * Build the document the server receives: the room part only, in the shape
+ * `POST /rooms/from-yaml` validates.
+ *
+ * Kept: `room:` (or `group:`, `rooms:`, `links:`), `kickoff:`, `version:`,
+ * and the params the room part refers to. Dropped: the agent entries, which
+ * the server does not understand; the params of a Console type (`provider`,
+ * `location`, `directory`), which only the Console can answer; and any
+ * param used only by an agent entry, such as the agent's name or a room it
+ * joins, which the Console has already resolved. For the singular `agent:`
+ * form, an `agent` param is added so the room's `{agent}` reference resolves
+ * on the server.
+ *
+ * With `keepConsoleParams`, every declared param is kept: the Use page
+ * parses this document to build its form and must see them all.
+ *
+ * Returns null when the document has no room part.
+ */
+export function serverDocument(
+ yamlText: string,
+ options: { keepConsoleParams?: boolean } = {}
+): string | null {
+ const doc = parseYaml(yamlText);
+ const room = asRecord(doc.room);
+ const isGroup = doc.group !== undefined || Array.isArray(doc.rooms);
+ if (!room && !isGroup) return null;
+
+ const usedByRooms = placeholdersIn({
+ room: doc.room,
+ group: doc.group,
+ rooms: doc.rooms,
+ links: doc.links,
+ kickoff: doc.kickoff,
+ });
+ const declared = Object.fromEntries(
+ Object.entries(asRecord(doc.params) ?? {}).filter(
+ ([name, spec]) =>
+ options.keepConsoleParams || (!isConsoleParam(spec) && usedByRooms.has(name))
+ )
+ );
+ const params: Record<string, unknown> =
+ asRecord(doc.agent) !== null && !Array.isArray(doc.agents)
+ ? { agent: { type: 'string', description: 'The agent this room is for' }, ...declared }
+ : declared;
+
+ const out: Record<string, unknown> = {};
+ if (typeof doc.version === 'number') out.version = doc.version;
+ if (Object.keys(params).length > 0) out.params = params;
+ if (isGroup) {
+ if (doc.group !== undefined) out.group = doc.group;
+ out.rooms = doc.rooms ?? [];
+ if (doc.links !== undefined) out.links = doc.links;
+ } else {
+ out.room = room;
+ }
+ // A top-level kickoff on a group document is a mistake the server reports
+ // with a clear message. Passing it through lets the deployer see that message.
+ if (doc.kickoff !== undefined) out.kickoff = doc.kickoff;
+ return dump(out, { lineWidth: -1 });
+}
+
+/**
+ * Replace agent names in the server document.
+ *
+ * `replacements` maps a name as written in the template (`{team}-triager`)
+ * to the name the agent has, for the slots whose name differs: the deployer
+ * chose an existing agent for that slot instead of creating one, or the
+ * name carried a param the Console filled in itself.
+ *
+ * Every place a room refers to an agent is updated: the `agents:` list, the
+ * keys of `aliases:`, and mentions inside `kickoff:` text. In kickoff text a
+ * name is replaced only as a whole word, with or without a leading `@`, so
+ * renaming `helper` leaves `helper-bot` alone and a mention still names an
+ * agent that exists.
+ */
+export function substituteAgentSlots(
+ coreYaml: string,
+ replacements: Record<string, string>
+): string {
+ const doc = parseYaml(coreYaml);
+ const rename = (name: unknown) =>
+ typeof name === 'string' && Object.hasOwn(replacements, name) ? replacements[name] : name;
+ // One pass over the text, longest name first so `{team}-ab` is matched
+ // before `{team}-a`, and a name only counts when neither neighbour can
+ // continue an agent name: `my-helper` is not `helper`. A dot continues a
+ // name only when a name character follows it, so "@helper." at the end of
+ // a sentence still matches and `helper._bot` is left alone.
+ const names = Object.keys(replacements).sort((a, b) => b.length - a.length);
+ const pattern =
+ names.length > 0
+ ? new RegExp(
+ `(?<![A-Za-z0-9_.-])(${names.map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})(?![A-Za-z0-9_-]|\\.[A-Za-z0-9_-])`,
+ 'g'
+ )
+ : null;
+ const inText = (text: unknown) => {
+ if (typeof text !== 'string' || pattern === null) return text;
+ return text.replace(pattern, (name) => replacements[name]);
+ };
+ const rooms = [asRecord(doc.room), ...(Array.isArray(doc.rooms) ? doc.rooms.map(asRecord) : [])];
+ for (const room of rooms) {
+ if (!room) continue;
+ if (Array.isArray(room.agents)) room.agents = room.agents.map(rename);
+ const aliases = asRecord(room.aliases);
+ if (aliases) {
+ room.aliases = Object.fromEntries(
+ Object.entries(aliases).map(([name, alias]) => [String(rename(name)), alias])
+ );
+ }
+ if (room.kickoff !== undefined) room.kickoff = inText(room.kickoff);
+ }
+ if (doc.kickoff !== undefined) doc.kickoff = inText(doc.kickoff);
+ return dump(doc, { lineWidth: -1 });
+}
+
+/**
+ * Inline `instructions` into every agent entry that lacks them.
+ *
+ * Used when saving a bundled template to a server. The bundled Switch expert
+ * keeps its instructions in a separate file; a copy stored on the server
+ * must be self-contained. YAML comments are lost in the process, field
+ * values are kept.
+ */
+export function composeTemplateDocument(yamlText: string, instructions: string): string {
+ const doc = parseYaml(yamlText);
+ const entries = rawAgents(doc);
+ if (entries.length === 0) throw new Error('Template must have an "agent:" block.');
+ for (const agent of entries) {
+ if (typeof agent.instructions !== 'string' || agent.instructions.trim().length === 0) {
+ agent.instructions = stripFrontMatter(instructions);
+ }
+ }
+ return dump(doc, { lineWidth: -1 });
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-templates/template-summary.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-templates/template-summary.test.ts
new file mode 100644
index 000000000..9a925e88a
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agent-templates/template-summary.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from 'vitest';
+import { summarizeTemplate, type TemplateSummary } from './template-summary';
+
+const counts = ({ creates: _creates, ...rest }: TemplateSummary) => rest;
+
+describe('summarizeTemplate', () => {
+ it('counts an agent template with a companion room as one of each', () => {
+ const s = summarizeTemplate(`
+agent:
+ name: switch-expert
+room:
+ name: "Ask {agent}"
+ agents: ["{agent}", helper]
+`);
+ expect(counts(s)).toEqual({ kind: 'agent', rooms: 1, agents: 1, inputs: 0 });
+ });
+
+ it('counts an agent template without a room as one agent', () => {
+ expect(counts(summarizeTemplate('agent:\n name: jq-expert\n'))).toEqual({
+ kind: 'agent',
+ rooms: 0,
+ agents: 1,
+ inputs: 0,
+ });
+ });
+
+ it('counts a room template by its rooms and params, not the agents it names', () => {
+ const s = summarizeTemplate(`
+params:
+ red: { type: agent }
+ blue: { type: agent }
+ topic: { type: string }
+room:
+ name: "{topic}"
+ agents: ["{red}", "{blue}", judge]
+`);
+ expect(counts(s)).toEqual({ kind: 'room', rooms: 1, agents: 0, inputs: 3 });
+ });
+
+ it('counts a rooms-only group by its rooms', () => {
+ const s = summarizeTemplate(`
+params:
+ lead: { type: agent }
+rooms:
+ - name: plan
+ agents: ["{lead}", scribe]
+ - name: build
+ agents: ["{lead}", coder]
+`);
+ expect(counts(s)).toEqual({ kind: 'group', rooms: 2, agents: 0, inputs: 1 });
+ });
+
+ it('does not throw on a document that is not YAML', () => {
+ expect(counts(summarizeTemplate('{{{'))).toEqual({
+ kind: 'room',
+ rooms: 1,
+ agents: 0,
+ inputs: 0,
+ });
+ });
+});
+
+describe('summarizeTemplate creates', () => {
+ it('lists rooms then agents, with the template spelling', () => {
+ const s = summarizeTemplate(`
+agents:
+ - name: "{team}-triager"
+ description: Reads reports
+ - name: "{team}-repro"
+room:
+ name: "{team}-triage"
+ agents: ["{team}-triager", "{team}-repro"]
+`);
+ expect(s.kind).toBe('group');
+ expect(s.creates.map((c) => [c.kind, c.name])).toEqual([
+ ['room', '{team}-triage'],
+ ['agent', '{team}-triager'],
+ ['agent', '{team}-repro'],
+ ]);
+ expect(s.creates[0].description).toBe('With {team}-triager, {team}-repro');
+ expect(s.creates[1].description).toBe('Reads reports');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-templates/template-summary.ts b/console/apps/switch-console-desktop/src/main/core/agent-templates/template-summary.ts
new file mode 100644
index 000000000..947a25292
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agent-templates/template-summary.ts
@@ -0,0 +1,115 @@
+import { load } from 'js-yaml';
+
+/**
+ * What a template document creates: the counts a listing card shows
+ * ("Creates 1 room and 1 agent · 4 inputs") and the rooms and agents a
+ * template page lists under "What it creates".
+ */
+export type TemplateSummary = {
+ kind: 'agent' | 'room' | 'group';
+ rooms: number;
+ agents: number;
+ inputs: number;
+ /** Each room and agent it creates, rooms first. */
+ creates: TemplateEntity[];
+};
+
+export type TemplateEntity = {
+ kind: 'room' | 'agent';
+ /** As written in the template, with any `{param}` still unfilled. */
+ name: string;
+ /** From the template, or a generated line when it has none. */
+ description: string;
+};
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : null;
+}
+
+function str(value: unknown): string {
+ return typeof value === 'string' ? value.trim() : '';
+}
+
+function agentsOf(room: Record<string, unknown> | null): string[] {
+ if (!room) return [];
+ const raw = room.agents;
+ if (!Array.isArray(raw)) return [];
+ return raw.map((a) => {
+ const r = asRecord(a);
+ return String(r?.name ?? a);
+ });
+}
+
+function roomThing(room: Record<string, unknown>): TemplateEntity {
+ const members = agentsOf(room);
+ const description =
+ str(room.description) ||
+ (members.length > 0 ? `With ${members.join(', ')}` : 'A room with nobody in it yet');
+ return { kind: 'room', name: str(room.name) || 'Unnamed room', description };
+}
+
+export function summarizeTemplate(yamlText: string): TemplateSummary {
+ // Text that is not YAML is summarized as one empty room, so the listing
+ // card still renders; the Use page reports the parse error.
+ let doc: unknown;
+ try {
+ doc = load(yamlText);
+ } catch {
+ doc = null;
+ }
+ const root = asRecord(doc) ?? {};
+ // Only params the deployer has to answer: no default to prefill from, and
+ // not marked optional. A chain default counts as a default here, since a
+ // server with the first candidate set up asks nothing.
+ const inputs = Object.values(asRecord(root.params) ?? {}).filter((spec) => {
+ const record = asRecord(spec);
+ return record?.default === undefined && record?.required !== false;
+ }).length;
+
+ const agentEntries: Record<string, unknown>[] = Array.isArray(root.agents)
+ ? root.agents.map(asRecord).filter((a): a is Record<string, unknown> => !!a)
+ : asRecord(root.agent)
+ ? [asRecord(root.agent) as Record<string, unknown>]
+ : [];
+ const roomEntries: Record<string, unknown>[] = Array.isArray(root.rooms)
+ ? root.rooms.map(asRecord).filter((r): r is Record<string, unknown> => !!r)
+ : asRecord(root.room)
+ ? [asRecord(root.room) as Record<string, unknown>]
+ : [];
+ const isGroup = root.group !== undefined || Array.isArray(root.rooms) || agentEntries.length > 1;
+
+ const creates: TemplateEntity[] = [
+ ...roomEntries.map(roomThing),
+ ...agentEntries.map((a) => ({
+ kind: 'agent' as const,
+ name: str(a.name) || 'Named when created',
+ description: str(a.description) || 'An agent with its own instructions',
+ })),
+ ];
+
+ if (agentEntries.length > 0) {
+ // Only the entries under `agent:` or `agents:` are created. Other names in
+ // a room's list refer to agents the server must already have.
+ return {
+ kind: isGroup ? 'group' : 'agent',
+ rooms: roomEntries.length,
+ agents: agentEntries.length,
+ inputs,
+ creates,
+ };
+ }
+ // A room or group document without `agents:` creates no agents. The names
+ // in its rooms refer to agents the server already has.
+ if (isGroup) {
+ return { kind: 'group', rooms: roomEntries.length, agents: 0, inputs, creates };
+ }
+ return {
+ kind: 'room',
+ rooms: 1,
+ agents: 0,
+ inputs,
+ creates: roomEntries.length > 0 ? creates : [],
+ };
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
index f86c988c9..97232a6e7 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
@@ -20,6 +20,7 @@ import type { AgentProviderId } from '@shared/core/providers/agent-provider-regi
import type { UiEntryPoint } from '@shared/core/telemetry/reporting';
import { basenameFromAnyPath } from '@shared/path-name';
import { writeAgentConfigFile } from './agent-config-file';
+import type { AgentTemplateOrigin } from './agent-config-file';
import { syncAgentConfig } from './agent-config-sync';
import { foreignCredentialsOwner, sameEndpointAgentId } from './agent-credentials-slot';
import { agentEvents } from './agent-events';
@@ -68,6 +69,9 @@ export type AddAgentParams = {
providerConfig?: AgentProviderConfig | null;
/** Which control the user opened the add-agent form from, for reporting. */
entryPoint: UiEntryPoint;
+ /** The template the agent is created from, if any. Recorded so the agent's
+ * settings page can offer the template's current instructions later. */
+ templateOrigin?: AgentTemplateOrigin | null;
};
export type AddAgentResult =
@@ -240,6 +244,7 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {
await writeAgentConfigFile(workspace.fs, params.name, {
instructions: params.instructions,
settings: params.definitionAttributes,
+ ...(params.templateOrigin ? { template: params.templateOrigin } : {}),
});
await syncAgentConfig({
workspaceFs: workspace.fs,
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.test.ts
index f5d3bf15d..28254ff84 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.test.ts
@@ -208,3 +208,24 @@ describe('decideArtifactSync', () => {
).toBe('adopt');
});
});
+
+describe('template origin', () => {
+ it('round-trips the template an agent was created from', () => {
+ const text = serialiseAgentConfigFile({
+ instructions: 'i',
+ template: { id: 'bundled:switch-expert', name: 'Switch expert', source: 'bundled' },
+ });
+ expect(parseAgentConfigFile(text).template).toEqual({
+ id: 'bundled:switch-expert',
+ name: 'Switch expert',
+ source: 'bundled',
+ });
+ });
+
+ it('drops an origin it cannot make sense of', () => {
+ expect(parseAgentConfigFile('{"template": {"id": 1}}').template).toBeUndefined();
+ expect(
+ parseAgentConfigFile('{"template": {"id": "x", "name": "y", "source": "elsewhere"}}').template
+ ).toBeUndefined();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts
index e47817de3..4c3b06e1d 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts
@@ -47,8 +47,31 @@ export type AgentConfigFile = {
* read back in.
*/
rendered?: Record<string, string>;
+ /**
+ * The template this agent was created from. Absent for an agent created
+ * without one. Holds what is needed to load the template again later, so
+ * the agent's settings page can offer the template's current instructions:
+ * a bundled template is found by id in this Console, a server one on its
+ * server.
+ */
+ template?: AgentTemplateOrigin;
+};
+
+export type AgentTemplateOrigin = {
+ id: string;
+ name: string;
+ source: 'bundled' | 'server';
+ serverId?: string;
};
+function parseTemplateOrigin(value: unknown): AgentTemplateOrigin | undefined {
+ if (!isPlainObject(value)) return undefined;
+ const { id, name, source, serverId } = value;
+ if (typeof id !== 'string' || typeof name !== 'string') return undefined;
+ if (source !== 'bundled' && source !== 'server') return undefined;
+ return { id, name, source, ...(typeof serverId === 'string' ? { serverId } : {}) };
+}
+
/**
* Parse an agent config file's text.
*
@@ -72,6 +95,8 @@ export function parseAgentConfigFile(raw: string): AgentConfigFile {
const config: AgentConfigFile = {};
if (typeof record.instructions === 'string') config.instructions = record.instructions;
if (isPlainObject(record.settings)) config.settings = record.settings as RepoAgentAttributes;
+ const template = parseTemplateOrigin(record.template);
+ if (template) config.template = template;
if (isPlainObject(record.rendered)) {
const rendered: Record<string, string> = {};
for (const [path, digest] of Object.entries(record.rendered)) {
@@ -101,6 +126,7 @@ export function serialiseAgentConfigFile(
delete out.instructions;
delete out.settings;
delete out.rendered;
+ delete out.template;
// Blank is how the owner says "none", and none is the absent state — the
// value itself is written exactly as given, never trimmed, because trimming
@@ -113,6 +139,7 @@ export function serialiseAgentConfigFile(
if (Object.keys(settings).length > 0) out.settings = settings;
if (config.rendered && Object.keys(config.rendered).length > 0) out.rendered = config.rendered;
+ if (config.template) out.template = config.template;
return `${JSON.stringify(out, null, 2)}\n`;
}
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts
index 96905fb50..c1c37ccb3 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts
@@ -3,7 +3,7 @@ import { getPlugin } from '@main/core/providers/plugin-registry';
import { providerConfigFromAttributes } from '@shared/core/agents/agent-provider-config';
import type { Agent } from '@shared/core/agents/agents';
import type { AgentConfigFile } from './agent-config-file';
-import { writeAgentConfigFile } from './agent-config-file';
+import { writeAgentConfigFile, type AgentTemplateOrigin } from './agent-config-file';
import { syncAgentConfig } from './agent-config-sync';
import { withAgentWorkspace } from './agent-launch-config';
import { getAgentById } from './getAgentById';
@@ -52,6 +52,13 @@ export async function writeAgentConfig(params: {
});
}
+/** The template the agent was created from, or null for an agent created without one. */
+export async function readAgentTemplateOrigin(
+ agentId: string
+): Promise<AgentTemplateOrigin | null> {
+ return (await readAgentConfig(agentId)).template ?? null;
+}
+
/** The agent's instructions, or empty when it has none. */
export async function readAgentInstructions(agentId: string): Promise<string> {
return (await readAgentConfig(agentId)).instructions ?? '';
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts b/console/apps/switch-console-desktop/src/main/core/agents/controller.ts
index 0c762dfcf..32d894c96 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/controller.ts
@@ -11,7 +11,11 @@ import {
readAgentAdvancedConfig,
updateAgentAdvancedConfig,
} from './agent-advanced-config';
-import { readAgentInstructions, setAgentInstructions } from './agent-config';
+import {
+ readAgentInstructions,
+ readAgentTemplateOrigin,
+ setAgentInstructions,
+} from './agent-config';
import { readAgentDefinition, updateAgentDefinition } from './agent-definition';
import { getAgentModelCatalogue, getProviderReadiness } from './agent-model-catalogue';
import { assignAgentServer } from './assignAgentServer';
@@ -82,6 +86,7 @@ export const agentsController = createRPCController({
* the agent rather than one of its provider's settings.
*/
readInstructions: (params: { agentId: string }) => readAgentInstructions(params.agentId),
+ readTemplateOrigin: (params: { agentId: string }) => readAgentTemplateOrigin(params.agentId),
updateInstructions: (params: { agentId: string; instructions: string }): Promise<void> =>
setAgentInstructions(params).then(() => undefined),
readAdvancedConfig: (params: { agentId: string }) => readAgentAdvancedConfig(params.agentId),
diff --git a/console/apps/switch-console-desktop/src/main/core/app/controller.ts b/console/apps/switch-console-desktop/src/main/core/app/controller.ts
index 14e119606..d34c171a7 100644
--- a/console/apps/switch-console-desktop/src/main/core/app/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/app/controller.ts
@@ -67,6 +67,8 @@ export const appController = createRPCController({
},
openSelectDirectoryDialog: (args: { title: string; message: string; defaultPath?: string }) =>
appService.openSelectDirectoryDialog(args),
+ saveTextFile: (args: { title: string; defaultPath?: string; content: string }) =>
+ appService.saveTextFile(args),
openSelectAudioFileDialog: (args: { title: string; message: string }) =>
appService.openSelectAudioFileDialog(args),
readAudioFileDataUrl: async (filePath: string) => {
diff --git a/console/apps/switch-console-desktop/src/main/core/app/service.ts b/console/apps/switch-console-desktop/src/main/core/app/service.ts
index 066b1f870..bc83bafd3 100644
--- a/console/apps/switch-console-desktop/src/main/core/app/service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/app/service.ts
@@ -1,5 +1,5 @@
import { exec } from 'node:child_process';
-import { readFile, realpath, stat } from 'node:fs/promises';
+import { readFile, realpath, stat, writeFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { extname, isAbsolute, join, resolve, sep } from 'node:path';
import type { IDisposable, IInitializable } from '@switch-console/shared';
@@ -309,6 +309,21 @@ class AppService implements IInitializable, IDisposable {
return result.filePaths[0];
}
+ /** Write `content` to the path the user picks in the OS save dialog. Null when the user cancels. */
+ async saveTextFile(args: {
+ title: string;
+ defaultPath?: string;
+ content: string;
+ }): Promise<string | null> {
+ const result = await dialog.showSaveDialog(getMainWindow()!, {
+ title: args.title,
+ defaultPath: args.defaultPath,
+ });
+ if (result.canceled || !result.filePath) return null;
+ await writeFile(result.filePath, args.content, 'utf8');
+ return result.filePath;
+ }
+
async openSelectAudioFileDialog(args: {
title: string;
message: string;
diff --git a/console/apps/switch-console-desktop/src/main/core/room-templates/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/room-templates/controller.test.ts
index 46bf212e7..cf0e5a6fc 100644
--- a/console/apps/switch-console-desktop/src/main/core/room-templates/controller.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/room-templates/controller.test.ts
@@ -194,7 +194,7 @@ describe('roomTemplatesController.parse: kickoff and creator', () => {
expect(result.usesCreator).toBe(true);
});
- it('warns about the stale room-level kickoff form and ignores it', () => {
+ it('warns about the room-level kickoff form, which the server refuses', () => {
const result = roomTemplatesController.parse({
yamlText: ['room:', ' name: n', ' description: d', ' kickoff: go'].join('\n'),
});
@@ -255,3 +255,76 @@ describe('roomTemplatesController.parse: multiline params', () => {
expect(result.params[0].multiline).toBe(false);
});
});
+
+describe('roomTemplatesController.params: policy fields', () => {
+ it('reads a chain default on a chain type, and a plain default elsewhere', () => {
+ const params = roomTemplatesController.params({
+ yamlText: [
+ 'params:',
+ ' bridge:',
+ ' type: bridge',
+ ' default: [Slack, $first]',
+ ' topic:',
+ ' type: string',
+ ' default: [a, b]',
+ ' reviewer:',
+ ' type: agent',
+ ' default: alice',
+ ].join('\n'),
+ });
+ const byName = Object.fromEntries(params.map((p) => [p.name, p.default]));
+ expect(byName).toEqual({ bridge: ['Slack', '$first'], topic: null, reviewer: 'alice' });
+ });
+
+ it('derives required from the default and lets the template override it', () => {
+ const params = roomTemplatesController.params({
+ yamlText: [
+ 'params:',
+ ' a:',
+ ' type: string',
+ ' b:',
+ ' type: string',
+ ' default: x',
+ ' c:',
+ ' type: string',
+ ' default: x',
+ ' required: true',
+ ' d:',
+ ' type: bridge',
+ ' default: [$first]',
+ ' e:',
+ ' type: bridge',
+ ' default: [$first]',
+ ' required: false',
+ ].join('\n'),
+ });
+ const byName = Object.fromEntries(params.map((p) => [p.name, p.required]));
+ expect(byName).toEqual({ a: true, b: false, c: true, d: true, e: false });
+ });
+
+ it('reads input, label, pattern and bounds where they apply', () => {
+ const params = roomTemplatesController.params({
+ yamlText: [
+ 'params:',
+ ' name:',
+ ' type: string',
+ ' label: Agent name',
+ ' input: advanced',
+ ' pattern: "[a-z]+"',
+ ' min: 3',
+ ' size:',
+ ' type: number',
+ ' min: 1',
+ ' max: 5',
+ ' input: nonsense',
+ ].join('\n'),
+ });
+ expect(params[0]).toMatchObject({
+ label: 'Agent name',
+ input: 'advanced',
+ pattern: '[a-z]+',
+ min: null,
+ });
+ expect(params[1]).toMatchObject({ input: 'ask', min: 1, max: 5, pattern: null });
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/room-templates/controller.ts b/console/apps/switch-console-desktop/src/main/core/room-templates/controller.ts
index 51c68d6bf..700ade308 100644
--- a/console/apps/switch-console-desktop/src/main/core/room-templates/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/room-templates/controller.ts
@@ -1,22 +1,60 @@
import Ajv from 'ajv';
import { dump, load } from 'js-yaml';
-import { PARAM_TYPES, type ParamType } from '@shared/core/switch-servers/room-template-params';
+import type { KV } from '@main/db/kv';
+import exampleTemplateYaml from '@root/../../../examples/room-templates/red-blue-workroom.template.yaml?raw';
+import {
+ CHAIN_PARAM_TYPES,
+ PARAM_INPUTS,
+ PARAM_TYPES,
+ type ParamInput,
+ type ParamType,
+} from '@shared/core/switch-servers/room-template-params';
import { createRPCController } from '@shared/lib/ipc/rpc';
+/** One entry of a template's `params:`, as core's `ParamSpec` reads it. */
export type ParamSpec = {
name: string;
type: ParamType;
description: string | null;
- default: string | number | boolean | null;
+ /** The human name of the input, when the key is not one. */
+ label: string | null;
+ /** A value, or for a chain type (`CHAIN_PARAM_TYPES`) the candidates tried in order. */
+ default: string | number | boolean | string[] | null;
+ /** Whether the value may be empty when the template is used. Without a
+ * default, or with a chain, a param is required unless the template says
+ * `required: false`. */
+ required: boolean;
+ input: ParamInput;
enum: string[] | null;
/** String params carrying long text render as a textarea (a one-line input
* would strip pasted newlines). Declared in the template: `multiline: true`. */
multiline: boolean;
+ /** A regular expression the whole value of a string param must match. */
+ pattern: string | null;
+ /** Bounds of a number param, inclusive. */
+ min: number | null;
+ max: number | null;
+};
+
+/** One room of a template, with the fields the Use page shows and edits. */
+export type TemplateRoom = {
+ name: string | null;
+ description: string | null;
+ agents: string[];
+ users: string[];
+ bridge: string | null;
+ kickoff: string | null;
};
export type ParsedTemplate = {
params: ParamSpec[];
+ /** The rooms the document creates: one for `room:`, one per entry of `rooms:`. */
+ rooms: TemplateRoom[];
+ /** The group's name when the document is a group, else null. */
+ groupName: string | null;
roomName: string | null;
+ /** The room's description as written in the template, for a listing card. */
+ roomDescription: string | null;
/** All agents from the template (both interpolated and hardcoded). */
agents: string[];
/** Hardcoded agents (no `{param}` interpolation), editable in the form. */
@@ -34,7 +72,7 @@ export type ParsedTemplate = {
warnings: string[];
};
-function extractParams(raw: unknown): ParamSpec[] {
+export function extractParams(raw: unknown): ParamSpec[] {
if (raw === null || raw === undefined || typeof raw !== 'object') return [];
const params = raw as Record<string, unknown>;
return Object.entries(params).map(([name, spec]) => {
@@ -43,9 +81,15 @@ function extractParams(raw: unknown): ParamSpec[] {
name,
type: 'string' as const,
description: null,
+ label: null,
default: null,
+ required: true,
+ input: 'ask' as const,
enum: null,
multiline: false,
+ pattern: null,
+ min: null,
+ max: null,
};
}
const s = spec as Record<string, unknown>;
@@ -53,13 +97,29 @@ function extractParams(raw: unknown): ParamSpec[] {
// An unknown type is read as a string so the form still renders; the
// server's schema is what rejects it, with a message naming the type.
const validType = PARAM_TYPES.includes(type as ParamType) ? (type as ParamType) : 'string';
+ const chain =
+ Array.isArray(s.default) && CHAIN_PARAM_TYPES.includes(validType)
+ ? s.default.filter((c): c is string => typeof c === 'string')
+ : null;
+ const def: ParamSpec['default'] =
+ chain !== null
+ ? chain
+ : s.default !== undefined && !Array.isArray(s.default)
+ ? (s.default as string | number | boolean | null)
+ : null;
return {
name,
type: validType,
description: typeof s.description === 'string' ? s.description : null,
- default: s.default !== undefined ? (s.default as ParamSpec['default']) : null,
+ label: typeof s.label === 'string' && s.label.trim() ? s.label.trim() : null,
+ default: def,
+ required: typeof s.required === 'boolean' ? s.required : def === null || chain !== null,
+ input: PARAM_INPUTS.includes(s.input as ParamInput) ? (s.input as ParamInput) : 'ask',
enum: Array.isArray(s.enum) ? (s.enum as string[]) : null,
multiline: validType === 'string' && s.multiline === true,
+ pattern: validType === 'string' && typeof s.pattern === 'string' ? s.pattern : null,
+ min: validType === 'number' && typeof s.min === 'number' ? s.min : null,
+ max: validType === 'number' && typeof s.max === 'number' ? s.max : null,
};
});
}
@@ -89,14 +149,95 @@ function extractStringList(raw: unknown): string[] {
const ajv = new Ajv({ allErrors: true, strict: false });
+/**
+ * Pick the part of the server's JSON schema that applies to this document.
+ *
+ * The schema can be a plain object schema or a `oneOf` with one branch per
+ * document shape (room, group). Validating a room document against the
+ * whole `oneOf` reports the group branch's errors too, which reads as
+ * noise. Validating against the matching branch reports only the mistake.
+ *
+ * The group branch is found by `Group` in its `$ref`, the server's model
+ * name for it; the other branch is the room one.
+ */
+function documentSchema(
+ schema: Record<string, unknown>,
+ doc: Record<string, unknown>
+): Record<string, unknown> {
+ const branches = (schema.oneOf ?? schema.anyOf) as Array<{ $ref?: string }> | undefined;
+ if (!Array.isArray(branches)) return schema;
+ const isGroup = doc.group !== undefined || Array.isArray(doc.rooms);
+ const branch = branches.find((b) =>
+ isGroup ? /Group/.test(b.$ref ?? '') : !/Group/.test(b.$ref ?? '')
+ );
+ if (!branch?.$ref) return schema;
+ const { oneOf: _one, anyOf: _any, ...rest } = schema;
+ return { ...rest, $ref: branch.$ref };
+}
+
+// ── Recents ────────────────────────────────────────────────────────────────
+
+/** A template document used from this Console, kept locally so it can be used again or saved to a workspace. */
+export type RecentTemplate = {
+ name: string;
+ yamlText: string;
+ usedAt: number;
+};
+
+type RecentsKV = Record<string, RecentTemplate[]>;
+
+const MAX_RECENTS = 10;
+
+// Imported inside the function rather than at the top of the module. The KV
+// module imports Electron's `app`, which does not exist in the unit tests
+// that call `parse`.
+let _recentsKV: KV<RecentsKV> | null = null;
+async function recentsKV(): Promise<KV<RecentsKV>> {
+ if (!_recentsKV) {
+ const { KV: Store } = await import('@main/db/kv');
+ _recentsKV = new Store<RecentsKV>('template-recents');
+ }
+ return _recentsKV;
+}
+
export const roomTemplatesController = createRPCController({
+ /** Templates used from this Console on `serverId`, newest first. */
+ getRecents: async (serverId: string): Promise<RecentTemplate[]> => {
+ const kv = await recentsKV();
+ return (await kv.get(serverId)) ?? [];
+ },
+
+ saveRecent: async (params: {
+ serverId: string;
+ name: string;
+ yamlText: string;
+ }): Promise<void> => {
+ const kv = await recentsKV();
+ const existing = (await kv.get(params.serverId)) ?? [];
+ // Using the same document again moves its entry to the top instead of adding a duplicate.
+ const rest = existing.filter((r) => r.yamlText !== params.yamlText);
+ const entry: RecentTemplate = {
+ name: params.name,
+ yamlText: params.yamlText,
+ usedAt: Date.now(),
+ };
+ await kv.set(params.serverId, [entry, ...rest].slice(0, MAX_RECENTS));
+ },
+
+ /** The example room template from `examples/`, shown when there is nothing else to start from. */
+ getExampleTemplate: (): string => exampleTemplateYaml,
+
+ /** Only the `params:` of a document. For agent-only documents, which have no room to parse. */
+ params: (params: { yamlText: string }): ParamSpec[] =>
+ extractParams(parseYaml(params.yamlText).params),
+
parse: (params: { yamlText: string; schema?: Record<string, unknown> }): ParsedTemplate => {
const warnings: string[] = [];
const doc = parseYaml(params.yamlText);
// Validate against server schema if provided
if (params.schema) {
- const validate = ajv.compile(params.schema);
+ const validate = ajv.compile(documentSchema(params.schema, doc));
if (!validate(doc)) {
const errors = (validate.errors ?? [])
.map((err) => {
@@ -106,38 +247,58 @@ export const roomTemplatesController = createRPCController({
.slice(0, 5);
throw new Error(errors.join('\n'));
}
- } else if (!doc.room) {
- throw new Error('Template must have a "room:" block.');
+ } else if (!doc.room && !Array.isArray(doc.rooms)) {
+ throw new Error('Template must have a "room:" block, or "group:" with "rooms:".');
}
- const room = doc.room as Record<string, unknown> | undefined;
- const roomName = room && typeof room.name === 'string' ? room.name : null;
- const allAgents = extractStringList(room?.agents);
- const allUsers = extractStringList(room?.users);
+ const isGroup = doc.group !== undefined || Array.isArray(doc.rooms);
+ const rawRooms: Record<string, unknown>[] = isGroup
+ ? (Array.isArray(doc.rooms) ? doc.rooms : []).filter(
+ (r): r is Record<string, unknown> => r !== null && typeof r === 'object'
+ )
+ : doc.room && typeof doc.room === 'object'
+ ? [doc.room as Record<string, unknown>]
+ : [];
+ const rooms: TemplateRoom[] = rawRooms.map((room) => ({
+ name: typeof room.name === 'string' ? room.name : null,
+ description: typeof room.description === 'string' ? room.description.trim() : null,
+ agents: extractStringList(room.agents),
+ users: extractStringList(room.users),
+ bridge:
+ typeof room.bridge === 'string' && !hasInterpolation(room.bridge) ? room.bridge : null,
+ kickoff: typeof room.kickoff === 'string' ? room.kickoff : null,
+ }));
+ const first = rooms[0] ?? null;
+ const allAgents = [...new Set(rooms.flatMap((r) => r.agents))];
+ const allUsers = [...new Set(rooms.flatMap((r) => r.users))];
const paramSpecs = extractParams(doc.params);
const kickoff = typeof doc.kickoff === 'string' ? doc.kickoff : null;
- if (room && typeof room.kickoff === 'string') {
+ if (!isGroup && first?.kickoff) {
warnings.push(
- '`kickoff:` belongs at the top level, beside `room:`. Inside `room:` the server ignores it.'
+ '`kickoff:` belongs at the top level, beside `room:`. Inside `room:` the server refuses it.'
);
}
- const bridge =
- room && typeof room.bridge === 'string' && !hasInterpolation(room.bridge)
- ? room.bridge
- : null;
-
- if (!room) {
+ if (isGroup && kickoff) {
+ warnings.push(
+ "A group's `kickoff:` goes inside the room it is for; at the top level the server refuses it."
+ );
+ }
+ if (rooms.length === 0) {
warnings.push('Template has no "room:" block, so the server may reject it.');
}
+ const group = doc.group as Record<string, unknown> | undefined;
return {
params: paramSpecs,
- roomName,
+ rooms,
+ groupName: group && typeof group.name === 'string' ? group.name : null,
+ roomName: first?.name ?? null,
+ roomDescription: first?.description ?? null,
agents: allAgents,
hardcodedAgents: allAgents.filter((a) => !hasInterpolation(a)),
hardcodedUsers: allUsers.filter((u) => !hasInterpolation(u)),
users: allUsers,
- bridge,
+ bridge: first?.bridge ?? null,
kickoff,
usesCreator: usesCreator(params.yamlText),
warnings,
@@ -148,7 +309,9 @@ export const roomTemplatesController = createRPCController({
rewriteYaml: (params: { yamlText: string; agents: string[]; users: string[] }): string => {
const doc = parseYaml(params.yamlText);
const room = doc.room as Record<string, unknown> | undefined;
- if (!room) return params.yamlText;
+ // The form does not edit the member lists of a group's rooms, so a group
+ // document is returned unchanged.
+ if (!room || Array.isArray(doc.rooms)) return params.yamlText;
room.agents = params.agents;
if (params.users.length > 0) {
room.users = params.users;
diff --git a/console/apps/switch-console-desktop/src/main/core/settings/settings-registry.ts b/console/apps/switch-console-desktop/src/main/core/settings/settings-registry.ts
index bdd2e57a6..77c195c48 100644
--- a/console/apps/switch-console-desktop/src/main/core/settings/settings-registry.ts
+++ b/console/apps/switch-console-desktop/src/main/core/settings/settings-registry.ts
@@ -12,7 +12,7 @@ type SettingsDefaultsMap = {
export const SETTINGS_DEFAULTS = {
localLocation: () => ({
- defaultLocationsDirectory: join(homedir(), 'switchdash', 'repositories'),
+ defaultLocationsDirectory: join(homedir(), '.switch', 'agents'),
defaultWorktreeDirectory: getDefaultLocalWorktreeDirectory(),
writeAgentConfigToGitIgnore: true,
}),
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.ts
index d9e6232b7..b68cdf5ee 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
@@ -103,13 +103,19 @@ import {
fetchRoomGroups,
fetchRoomRoles,
fetchRooms,
+ createTemplate,
+ deleteTemplate,
+ fetchTemplateDetail,
+ fetchTemplates,
GatewayError,
ownsOwnerAddressedAgent,
releaseBridgeIdentity,
createRoomFromTemplate,
fetchTemplateSchema,
removeRoomAgent,
- type TemplateProvisionResult,
+ type StoredTemplateDetail,
+ type StoredTemplateSummary,
+ type ProvisionFromTemplateResult,
updateAddressingPolicy,
updateAgentIcon,
updateRoom,
@@ -555,9 +561,35 @@ export const switchServersController = createRPCController({
serverId: string,
yamlText: string,
inputs: Record<string, string | number | boolean>
- ): Promise<TemplateProvisionResult> =>
+ ): Promise<ProvisionFromTemplateResult> =>
createRoomFromTemplate(await requireServer(serverId), yamlText, inputs),
+ listTemplates: async (params: {
+ serverId: string;
+ kind?: string;
+ }): Promise<StoredTemplateSummary[]> =>
+ fetchTemplates(await requireServer(params.serverId), params.kind),
+
+ getTemplateDetail: async (params: {
+ serverId: string;
+ templateId: string;
+ }): Promise<StoredTemplateDetail> =>
+ fetchTemplateDetail(await requireServer(params.serverId), params.templateId),
+
+ deleteTemplate: async (params: { serverId: string; templateId: string }): Promise<void> =>
+ deleteTemplate(await requireServer(params.serverId), params.templateId),
+
+ saveTemplate: async (params: {
+ serverId: string;
+ name: string;
+ description: string;
+ kind: string;
+ content: string;
+ }): Promise<StoredTemplateDetail> => {
+ const { serverId, ...template } = params;
+ return createTemplate(await requireServer(serverId), template);
+ },
+
fetchTemplateSchema: async (serverId: string): Promise<Record<string, unknown> | null> =>
fetchTemplateSchema(await requireServer(serverId)),
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.ts
index 4b17b43dc..d7918c249 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
@@ -1051,11 +1051,39 @@ export type TemplateProvisionResult = {
failedAttachments: Array<{ kind: string; id: string; error: string }>;
};
+/** The result of provisioning a room group from a YAML template. */
+export type GroupProvisionResult = {
+ groupId: string;
+ groupName: string;
+ rooms: TemplateProvisionResult[];
+ /** Rooms or links that could not be created. The others were. */
+ errors: Array<Record<string, unknown> & { error: string }>;
+};
+
+export type ProvisionFromTemplateResult =
+ | ({ kind: 'room' } & TemplateProvisionResult)
+ | ({ kind: 'group' } & GroupProvisionResult);
+
+type RoomJson = {
+ room_id: string;
+ room_name: string;
+ failed_attachments?: Array<{ kind: string; id: string; error: string }>;
+};
+
+function toRoomResult(json: RoomJson): TemplateProvisionResult {
+ return {
+ roomId: json.room_id,
+ roomName: json.room_name,
+ failedAttachments: json.failed_attachments ?? [],
+ };
+}
+
/**
- * Create a room from a YAML template (`POST /rooms/from-yaml`). Sends the
- * template as a JSON body with the YAML text and any user-supplied inputs.
- * The server parses the template, interpolates inputs, and provisions
- * everything in one call.
+ * Create a room, or a group of rooms, from a YAML template
+ * (`POST /rooms/from-yaml`). Sends the template as a JSON body with the YAML
+ * text and any user-supplied inputs. The server parses the template,
+ * interpolates inputs, and provisions everything in one call; the document's
+ * shape decides which result comes back.
*
* A 400 carries a `detail` naming the bad input; the caller maps it back to
* the form field.
@@ -1064,24 +1092,113 @@ export async function createRoomFromTemplate(
server: SwitchServer,
yamlText: string,
inputs: Record<string, string | number | boolean>
-): Promise<TemplateProvisionResult> {
+): Promise<ProvisionFromTemplateResult> {
const res = await gatewayFetch(server, '/rooms/from-yaml', {
authenticated: true,
method: 'POST',
body: { yaml: yamlText, inputs },
});
- const json = (await res.json()) as {
- room_id: string;
- room_name: string;
- failed_attachments?: Array<{ kind: string; id: string; error: string }>;
- };
+ const json = (await res.json()) as
+ | RoomJson
+ | {
+ group_id: string;
+ group_name: string;
+ rooms?: RoomJson[];
+ errors?: Array<Record<string, unknown> & { error: string }>;
+ };
+ if ('group_id' in json) {
+ return {
+ kind: 'group',
+ groupId: json.group_id,
+ groupName: json.group_name,
+ rooms: (json.rooms ?? []).map(toRoomResult),
+ errors: json.errors ?? [],
+ };
+ }
+ return { kind: 'room', ...toRoomResult(json) };
+}
+
+// ── Stored templates (template registry) ────────────────────────────────────
+
+export type StoredTemplateSummary = {
+ id: string;
+ name: string;
+ description: string;
+ kind: string;
+ creator: string;
+ /** The owner's user id, so the Console can mark the signed-in user's own templates. */
+ ownerId: string | null;
+};
+
+export type StoredTemplateDetail = StoredTemplateSummary & {
+ definition: string;
+};
+
+type RegistryTemplateSummary = {
+ id: string;
+ owner_id: string;
+ owner_name: string | null;
+ name: string;
+ description: string;
+ kind: string;
+};
+
+function toSummary(t: RegistryTemplateSummary): StoredTemplateSummary {
return {
- roomId: json.room_id,
- roomName: json.room_name,
- failedAttachments: json.failed_attachments ?? [],
+ id: t.id,
+ name: t.name,
+ description: t.description,
+ kind: t.kind,
+ creator: t.owner_name ?? t.owner_id,
+ ownerId: t.owner_id,
};
}
+export async function fetchTemplates(
+ server: SwitchServer,
+ kind?: string
+): Promise<StoredTemplateSummary[]> {
+ const qs = kind ? `?kind=${encodeURIComponent(kind)}` : '';
+ const res = await gatewayFetch(server, `/templates${qs}`, {
+ authenticated: true,
+ });
+ const json = (await res.json()) as RegistryTemplateSummary[];
+ return json.map(toSummary);
+}
+
+/** Store a template document on the server's registry (`POST /templates`). */
+export async function createTemplate(
+ server: SwitchServer,
+ params: { name: string; description: string; kind: string; content: string }
+): Promise<StoredTemplateDetail> {
+ const res = await gatewayFetch(server, '/templates', {
+ authenticated: true,
+ method: 'POST',
+ body: params,
+ });
+ const t = (await res.json()) as RegistryTemplateSummary & { content: string };
+ return { ...toSummary(t), definition: t.content };
+}
+
+/** Remove a template from the server's registry (`DELETE /templates/{id}`). */
+export async function deleteTemplate(server: SwitchServer, templateId: string): Promise<void> {
+ await gatewayFetch(server, `/templates/${encodeURIComponent(templateId)}`, {
+ authenticated: true,
+ method: 'DELETE',
+ });
+}
+
+export async function fetchTemplateDetail(
+ server: SwitchServer,
+ templateId: string
+): Promise<StoredTemplateDetail> {
+ const res = await gatewayFetch(server, `/templates/${encodeURIComponent(templateId)}`, {
+ authenticated: true,
+ });
+ const t = (await res.json()) as RegistryTemplateSummary & { content: string };
+ return { ...toSummary(t), definition: t.content };
+}
+
/**
* Fetch the JSON Schema describing a valid room template. Returns null when
* the server does not support the endpoint (404): older servers without
diff --git a/console/apps/switch-console-desktop/src/main/rpc.ts b/console/apps/switch-console-desktop/src/main/rpc.ts
index e325b6590..de16b72d5 100644
--- a/console/apps/switch-console-desktop/src/main/rpc.ts
+++ b/console/apps/switch-console-desktop/src/main/rpc.ts
@@ -1,4 +1,5 @@
import { createRPCNamespace, createRPCRouter } from '../shared/lib/ipc/rpc';
+import { agentTemplatesController } from './core/agent-templates/controller';
import { agentsController } from './core/agents/controller';
import { appController } from './core/app/controller';
import { filesController } from './core/fs/controller';
@@ -27,6 +28,7 @@ export const rpcRouter = createRPCRouter({
sdkHost: sdkHostController,
providers: providersController,
agents: agentsController,
+ agentTemplates: agentTemplatesController,
app: appController,
appSettings: appSettingsController,
providerSettings: providerSettingsController,
diff --git a/console/apps/switch-console-desktop/src/main/vite-env.d.ts b/console/apps/switch-console-desktop/src/main/vite-env.d.ts
new file mode 100644
index 000000000..22dd406e2
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/vite-env.d.ts
@@ -0,0 +1,4 @@
+declare module '*.yaml?raw' {
+ const value: string;
+ export default value;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts
index 22808fac9..b94ed44bb 100644
--- a/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts
+++ b/console/apps/switch-console-desktop/src/renderer/app/modal-registry.ts
@@ -19,6 +19,7 @@ import { CreateRoomModal } from '@renderer/features/switch-servers/CreateRoomMod
import { DeleteServerModal } from '@renderer/features/switch-servers/DeleteServerModal';
import { DisconnectMessagingAppModal } from '@renderer/features/switch-servers/DisconnectMessagingAppModal';
import { RenameServerModal } from '@renderer/features/switch-servers/RenameServerModal';
+import { SaveTemplateModal } from '@renderer/features/templates/save-template-modal';
import { ConfirmActionDialog } from '@renderer/lib/components/confirm-action-dialog';
import { ExternalLinkChoiceDialog } from '@renderer/lib/components/external-link-choice-dialog';
import { UnsavedChangesDialog } from '@renderer/lib/components/unsaved-changes-dialog';
@@ -51,6 +52,7 @@ export const modalRegistry = {
commandPaletteModal: createModal(CommandPaletteModal, { size: 'md' }),
sessionModal: createModal(CreateSessionModal, { dismissOnOutsideClick: false }),
addAgentModal: createModal(AddAgentModal, { size: 'lg', dismissOnOutsideClick: false }),
+ saveTemplateModal: createModal(SaveTemplateModal, { size: 'sm', dismissOnOutsideClick: false }),
confirmActionModal: createModal(ConfirmActionDialog, { size: 'xs' }),
deleteAgentModal: createModal(DeleteAgentModal, { size: 'sm' }),
removeAgentConfigModal: createModal(RemoveAgentConfigModal, { size: 'sm' }),
diff --git a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts
index c2b25fe60..205db09aa 100644
--- a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts
+++ b/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts
@@ -3,13 +3,16 @@ import { homeView } from '@renderer/app/home-view';
import { locationView } from '@renderer/features/locations/view';
import { remoteHostView } from '@renderer/features/remote-hosts/views/remote-host-view';
import { remoteHostsView } from '@renderer/features/remote-hosts/views/remote-hosts-view';
-import { roomTemplateImportView } from '@renderer/features/room-templates/room-template-import-view';
+import { templateImportView } from '@renderer/features/room-templates/room-template-import-view';
import { sessionView } from '@renderer/features/sessions/view';
import { settingsView } from '@renderer/features/settings/settings-view';
import { roomView } from '@renderer/features/switch-rooms/view';
import { serverAgentsView } from '@renderer/features/switch-servers/server-agents-view';
import { serverRoomsView } from '@renderer/features/switch-servers/server-rooms-view';
import { serverView } from '@renderer/features/switch-servers/view';
+import { templateDetailView } from '@renderer/features/templates/template-detail-view';
+import { templateUseView } from '@renderer/features/templates/template-use-view';
+import { templatesView } from '@renderer/features/templates/templates-view';
import type { CommandProvider } from '@renderer/lib/commands/types';
import { appState } from '@renderer/lib/stores/app-state';
import type { ViewIdName } from '@shared/core/views/view-ids';
@@ -28,7 +31,10 @@ export const views = {
serverRooms: serverRoomsView,
remoteHosts: remoteHostsView,
remoteHost: remoteHostView,
- roomTemplateImport: roomTemplateImportView,
+ templateImport: templateImportView,
+ templates: templatesView,
+ templateDetail: templateDetailView,
+ templateUse: templateUseView,
// oxlint-disable-next-line typescript/no-explicit-any
} satisfies Record<string, ViewDefinition<any>>;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
index c4f243079..9f1d334d1 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
@@ -23,6 +23,7 @@ import {
useShowModal,
type BaseModalProps,
} from '@renderer/lib/modal/modal-provider';
+import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
import { Button } from '@renderer/lib/ui/button';
import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
import {
@@ -96,6 +97,7 @@ export const AddAgentModal = observer(function AddAgentModal({
// Typed directly, with no commit step: it used to need one because committing
// fired the directory scans, and there are none left to fire.
const [remoteRepoDir, setRemoteRepoDir] = useState('');
+
const { data: remoteHosts } = useQuery({
queryKey: ['remote-hosts'],
queryFn: () => rpc.remoteHosts.listHosts(),
@@ -131,6 +133,15 @@ export const AddAgentModal = observer(function AddAgentModal({
}
}, [targetServerId, pickedServerId, setServerId]);
+ // Names already taken on the server, so a clash is refused before anything
+ // is created rather than reported by the server afterwards.
+ const remoteAgents = useRemoteAgents(pickState.serverId);
+ const takenNames = useMemo(
+ () => new Set((remoteAgents.data ?? []).map((a) => a.name)),
+ [remoteAgents.data]
+ );
+ const nameTaken = form.nameIsValid && takenNames.has(form.agentName);
+
// A managed server is only reachable from certain run locations, so constrain
// the picker to them: a remote-managed server from this computer or its own
// host (the desktop reaches it through the SSH forward; the host reaches it on
@@ -224,6 +235,7 @@ export const AddAgentModal = observer(function AddAgentModal({
const canSubmit =
form.isValid &&
+ !nameTaken &&
!policyHasDeadRule(form.addressingPolicy) &&
!!pickState.serverId &&
!!pickState.providerId &&
@@ -242,23 +254,25 @@ export const AddAgentModal = observer(function AddAgentModal({
? 'Enter a name for the agent.'
: !form.nameIsValid
? 'Fix the agent name: lowercase letters, digits, . - _, starting with a letter or digit.'
- : form.description.trim().length === 0
- ? 'Add a description so people and agents know what this agent is for.'
- : !runHostReachable
- ? `${runLocationLabel} can’t be reached right now — pick a run location that can.`
- : hostReadiness.checking
- ? `Checking what ${runLocationLabel} has installed…`
- : hostReadiness.blocked
- ? `${runLocationLabel} is missing setup this agent needs — the notice below has the details.`
- : !pickState.providerId
- ? 'Choose an agent type.'
- : dir.trim().length === 0
- ? isRemoteRun
- ? 'Enter the agent’s working directory on the host.'
- : 'Choose the agent’s working directory.'
- : policyHasDeadRule(form.addressingPolicy)
- ? 'One addressing rule can never match — fix it under Settings.'
- : null;
+ : nameTaken
+ ? `An agent called ${form.agentName} already exists on this server. Pick another name.`
+ : form.description.trim().length === 0
+ ? 'Add a description so people and agents know what this agent is for.'
+ : !runHostReachable
+ ? `${runLocationLabel} can’t be reached right now — pick a run location that can.`
+ : hostReadiness.checking
+ ? `Checking what ${runLocationLabel} has installed…`
+ : hostReadiness.blocked
+ ? `${runLocationLabel} is missing setup this agent needs — the notice below has the details.`
+ : !pickState.providerId
+ ? 'Choose an agent type.'
+ : dir.trim().length === 0
+ ? isRemoteRun
+ ? 'Enter the agent’s working directory on the host.'
+ : 'Choose the agent’s working directory.'
+ : policyHasDeadRule(form.addressingPolicy)
+ ? 'One addressing rule can never match — fix it under Settings.'
+ : null;
/** `agentName` is what picks the agent out of the location — a location can
* hold several, so navigating on `locationId` alone opens the directory
@@ -328,9 +342,9 @@ export const AddAgentModal = observer(function AddAgentModal({
* per-agent credentials, and create the row — all via `addAgent`. */
const createNewAgent = async () => {
if (!pickState.serverId || !pickState.providerId) return;
- setSubmitState('creating');
setCloseGuard(true);
try {
+ setSubmitState('creating');
const result = await getLocationManagerStore().addAgentAndOpen({
sshHost: isRemoteRun ? runHost : null,
dir: isRemoteRun ? trimmedRemoteDir : pickState.path,
@@ -381,6 +395,19 @@ export const AddAgentModal = observer(function AddAgentModal({
header={
<DialogHeader showCloseButton={submitState === 'idle'}>
<DialogTitle>New agent</DialogTitle>
+ {targetServerId && (
+ <button
+ type="button"
+ disabled={submitState !== 'idle'}
+ onClick={() => {
+ onClose();
+ navigate('templates', { serverId: targetServerId, kind: 'agent' });
+ }}
+ className="w-fit cursor-pointer text-xs text-foreground-muted underline underline-offset-2 hover:text-foreground disabled:cursor-default disabled:opacity-50"
+ >
+ Or start from a template
+ </button>
+ )}
</DialogHeader>
}
footer={
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/local-directory-selector.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/local-directory-selector.tsx
index 0b570f831..e65fb90df 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/local-directory-selector.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/local-directory-selector.tsx
@@ -1,4 +1,4 @@
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
import { rpc } from '@renderer/lib/ipc';
import { Button } from '@renderer/lib/ui/button';
import { cn } from '@renderer/utils/utils';
@@ -15,15 +15,22 @@ export function LocalDirectorySelector({
title,
message,
onPathChange,
- path: initialPath,
+ path: pathProp,
placeholder = 'Select a directory',
}: LocalDirectorySelectorProps) {
- const [path, setPath] = useState<string>(initialPath || '');
+ const [path, setPath] = useState<string>(pathProp || '');
+ // The parent can change the path (a template can provide one), so a new prop
+ // value replaces the local state. The local state exists only to hold the
+ // result of the directory dialog until the parent receives it.
+ useEffect(() => {
+ setPath(pathProp || '');
+ }, [pathProp]);
const handleOpenFileDialog = async () => {
const result = await rpc.app.openSelectDirectoryDialog({
title,
message,
+ defaultPath: path || undefined,
});
if (result) {
setPath(result);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-instructions-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-instructions-section.tsx
index b14fbcd65..b285b317c 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-instructions-section.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-instructions-section.tsx
@@ -1,8 +1,13 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
+import {
+ loadAgentTemplateByOrigin,
+ templateOriginExists,
+} from '@renderer/features/templates/agent-template-data';
import { describeFailure } 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 { Field, FieldLabel } from '@renderer/lib/ui/field';
import { Textarea } from '@renderer/lib/ui/textarea';
import { log } from '@renderer/utils/logger';
@@ -36,6 +41,43 @@ export function AgentInstructionsSection({
enabled: !!agentId,
});
+ // The template this agent was created from, if any. A template's
+ // instructions change over time (the Switch expert's are maintained in the
+ // repository) while the agent keeps the copy it was created with, so the
+ // page offers to load the current version into the editor. Nothing is
+ // saved until the user saves the edit.
+ const { data: origin } = useQuery({
+ queryKey: ['agent-template-origin', agentId],
+ queryFn: () => (agentId ? rpc.agents.readTemplateOrigin({ agentId }) : Promise.resolve(null)),
+ enabled: !!agentId,
+ });
+ const [refreshing, setRefreshing] = useState(false);
+ const refreshFromTemplate = async () => {
+ if (!origin) return;
+ setRefreshing(true);
+ try {
+ const template = await loadAgentTemplateByOrigin(origin);
+ if (template.instructions === value) {
+ toast({ title: `Already up to date with "${origin.name}"` });
+ return;
+ }
+ setValue(template.instructions);
+ setExpanded(true);
+ toast({
+ title: `Instructions replaced with the current "${origin.name}"`,
+ description: 'Nothing is saved yet. Read them over, then save or revert.',
+ });
+ } catch (error) {
+ const { headline, detail } = describeFailure(
+ error,
+ `Could not load the template "${origin.name}".`
+ );
+ toast({ title: headline, description: detail ?? undefined, variant: 'destructive' });
+ } finally {
+ setRefreshing(false);
+ }
+ };
+
const savedValue = saved ?? '';
const [value, setValue] = useState('');
const [expanded, setExpanded] = useState(false);
@@ -105,19 +147,33 @@ export function AgentInstructionsSection({
<FieldLabel htmlFor={fieldId}>
Agent instructions <span className="text-foreground-muted">(optional)</span>
</FieldLabel>
- {/* Offered only once there is something being withheld, so a two-line
+ <span className="flex items-center gap-3">
+ {origin && templateOriginExists(origin) && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ disabled={refreshing}
+ onClick={() => void refreshFromTemplate()}
+ title={`This agent was created from the "${origin.name}" template`}
+ >
+ {refreshing ? 'Loading…' : `Update from "${origin.name}"`}
+ </Button>
+ )}
+ {/* Offered only once there is something being withheld, so a two-line
instruction does not carry a control that would do nothing. */}
- {(clipped || expanded) && (
- <button
- type="button"
- aria-expanded={expanded}
- aria-controls={fieldId}
- onClick={() => setExpanded((open) => !open)}
- className="cursor-pointer text-sm text-foreground-muted hover:text-foreground"
- >
- {expanded ? 'Collapse' : 'Expand'}
- </button>
- )}
+ {(clipped || expanded) && (
+ <button
+ type="button"
+ aria-expanded={expanded}
+ aria-controls={fieldId}
+ onClick={() => setExpanded((open) => !open)}
+ className="cursor-pointer text-sm text-foreground-muted hover:text-foreground"
+ >
+ {expanded ? 'Collapse' : 'Expand'}
+ </button>
+ )}
+ </span>
</div>
<Textarea
ref={boxRef}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx b/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx
index 17f52e235..88b0d245d 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx
@@ -42,7 +42,7 @@ export type EntityLists = {
const NOT_ON_SERVER = 'Not on this server';
/** The grid every chosen tile sits in, so single picks and lists line up. */
-function TileGrid({ children }: { children: React.ReactNode }) {
+export function TileGrid({ children }: { children: React.ReactNode }) {
return <div className="grid grid-cols-3 gap-2.5">{children}</div>;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx
index 9d53485fc..165cb1c6d 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx
@@ -1,48 +1,20 @@
import Editor from '@monaco-editor/react';
-import { useQuery, useQueryClient } from '@tanstack/react-query';
-import { ArrowRight, Check, FileText, Loader2, Upload } from 'lucide-react';
+import { ArrowRight, Save, Upload, FileText } from 'lucide-react';
import { observer } from 'mobx-react-lite';
-import { useCallback, useMemo, useRef, useState } from 'react';
-import { toast } from 'sonner';
-import type { ParamSpec, ParsedTemplate } from '@main/core/room-templates/controller';
+import { useCallback, useEffect, useRef, useState } from 'react';
import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';
-import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';
import { ServerPage } from '@renderer/features/switch-servers/server-page';
import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';
-import { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';
+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { prefillForSave } from '@renderer/features/templates/agent-template-data';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { useParams } from '@renderer/lib/layout/navigation-provider';
import { useModalContext } from '@renderer/lib/modal/modal-provider';
import { appState } from '@renderer/lib/stores/app-state';
-import { remoteAgentsQueryKey, useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
import { Alert, AlertDescription } from '@renderer/lib/ui/alert';
import { Button } from '@renderer/lib/ui/button';
import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';
-import { Input } from '@renderer/lib/ui/input';
-import { Textarea } from '@renderer/lib/ui/textarea';
-import { isEntityParamType } from '@shared/core/switch-servers/room-template-params';
-import { RpcError } from '@shared/lib/ipc/rpc-error';
-import { type BlockedHandoff, blockedHandoffs } from './agent-handoff';
-import {
- AgentField,
- AgentListField,
- BridgeField,
- type EntityLists,
- RoomField,
- UserField,
- UserListField,
-} from './entity-fields';
-
-type Step = 'source' | 'inputs' | 'creating';
-
-/** Interpolate `{param}` and `{$builtin}` patterns with current form values. */
-function interpolate(template: string, values: Record<string, string | number | boolean>): string {
- return template.replace(/\{(\$?\w+)\}/g, (match, key: string) => {
- const val = values[key];
- return val !== undefined && val !== '' ? String(val) : match;
- });
-}
// ── Source step ─────────────────────────────────────────────────────────────
@@ -60,12 +32,16 @@ function SourceStep({
parseError,
onNext,
onFileSelect,
+ onSaveToServer,
+ saving,
}: {
yamlText: string;
onYamlChange: (text: string) => void;
parseError: string | null;
onNext: () => void;
onFileSelect: (name: string) => void;
+ onSaveToServer: () => void;
+ saving: boolean;
}) {
const fileInputRef = useRef<HTMLInputElement>(null);
const [dragging, setDragging] = useState(false);
@@ -101,7 +77,7 @@ function SourceStep({
<div className="flex flex-col gap-4">
<FieldGroup>
<Field>
- <FieldLabel>Paste a room template</FieldLabel>
+ <FieldLabel>Paste a template</FieldLabel>
<div
onDragOver={(e) => {
e.preventDefault();
@@ -149,7 +125,19 @@ function SourceStep({
Choose file
</Button>
<span className="text-xs text-foreground-passive">
- or paste YAML above, or drag and drop
+ or paste YAML above, or drag and drop, or start from the{' '}
+ <button
+ type="button"
+ onClick={() => {
+ void rpc.roomTemplates.getExampleTemplate().then((yaml) => {
+ onFileSelect('red-blue-workroom.template.yaml');
+ onYamlChange(yaml);
+ });
+ }}
+ className="cursor-pointer underline underline-offset-2 hover:text-foreground"
+ >
+ example room template
+ </button>
</span>
</div>
@@ -159,8 +147,12 @@ function SourceStep({
</Alert>
)}
- <div className="flex justify-end pt-2">
- <Button disabled={!yamlText.trim()} onClick={onNext}>
+ <div className="flex items-center justify-end gap-2 pt-2">
+ <Button variant="outline" disabled={!yamlText.trim() || saving} onClick={onSaveToServer}>
+ <Save className="mr-1.5 size-3.5" />
+ {saving ? 'Saving…' : 'Save to workspace'}
+ </Button>
+ <Button disabled={!yamlText.trim() || saving} onClick={onNext}>
Next
<ArrowRight className="ml-1.5 size-3.5" />
</Button>
@@ -169,834 +161,132 @@ function SourceStep({
);
}
-// ── Param field ────────────────────────────────────────────────────────────
-
-/** The label, description and error every param field shares, around
- * whatever control the param's type calls for. */
-function ParamFieldShell({
- param,
- value,
- error,
- children,
-}: {
- param: ParamSpec;
- value: string | number | boolean;
- error: string | null;
- children: React.ReactNode;
-}) {
- const isRequired = param.default === null;
- const defaultKept = param.default !== null && value === param.default;
- // Label: param name (humanized) + default annotation
- const nameLabel = param.name.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
- return (
- <Field>
- <FieldLabel>
- {nameLabel}
- {defaultKept && (
- <span className="ml-1 font-normal text-foreground-muted">(default kept)</span>
- )}
- {isRequired && <span className="ml-1 text-destructive">*</span>}
- </FieldLabel>
- {children}
- {param.description && (
- <p className="mt-1 text-xs text-foreground-muted">{param.description}</p>
- )}
- {error && <p className="text-xs text-destructive">{error}</p>}
- </Field>
- );
-}
-
-function ParamField({
- param,
- value,
- onChange,
- error,
- lists,
-}: {
- param: ParamSpec;
- value: string | number | boolean;
- onChange: (v: string | number | boolean) => void;
- error: string | null;
- lists: EntityLists;
-}) {
- if (param.type === 'boolean') {
- const isRequired = param.default === null;
- const nameLabel = param.name.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
- return (
- <Field>
- <label className="flex items-center gap-2">
- <input
- type="checkbox"
- checked={Boolean(value)}
- onChange={(e) => onChange(e.target.checked)}
- className="size-4 rounded border-border"
- />
- <span className="text-sm font-medium">
- {nameLabel}
- {isRequired && <span className="ml-1 text-destructive">*</span>}
- </span>
- </label>
- {param.description && (
- <p className="mt-1 text-xs text-foreground-muted">{param.description}</p>
- )}
- </Field>
- );
- }
-
- // Entity-typed params pick from what the server has, the same way the
- // new-room dialog does; the value is the entity's name as the template
- // would spell it, and the server checks it again on create.
- if (isEntityParamType(param.type)) {
- const strVal = typeof value === 'string' ? value : String(value ?? '');
- const control =
- param.type === 'agent' ? (
- <AgentField value={strVal} onChange={onChange} lists={lists} />
- ) : param.type === 'room' ? (
- <RoomField value={strVal} onChange={onChange} lists={lists} />
- ) : param.type === 'bridge' ? (
- <BridgeField value={strVal} onChange={onChange} lists={lists} />
- ) : (
- <UserField value={strVal} onChange={onChange} lists={lists} />
- );
- return (
- <ParamFieldShell param={param} value={value} error={error}>
- {control}
- </ParamFieldShell>
- );
- }
-
- if (param.type === 'enum' && param.enum) {
- return (
- <ParamFieldShell param={param} value={value} error={error}>
- <select
- value={String(value)}
- onChange={(e) => onChange(e.target.value)}
- className="flex h-9 w-full rounded-md border border-border bg-transparent px-2.5 text-sm"
- aria-invalid={error ? true : undefined}
- >
- <option value="">Select…</option>
- {param.enum.map((opt) => (
- <option key={opt} value={opt}>
- {opt}
- </option>
- ))}
- </select>
- </ParamFieldShell>
- );
- }
-
- if (param.type === 'number') {
- return (
- <ParamFieldShell param={param} value={value} error={error}>
- <Input
- type="number"
- value={value === '' ? '' : Number(value)}
- onChange={(e) => onChange(e.target.value === '' ? '' : Number(e.target.value))}
- aria-invalid={error ? true : undefined}
- />
- </ParamFieldShell>
- );
- }
-
- // Long-text string param: a textarea, because a one-line input strips the
- // newlines out of a pasted brief.
- if (param.multiline) {
- return (
- <ParamFieldShell param={param} value={value} error={error}>
- <Textarea
- value={String(value)}
- onChange={(e) => onChange(e.target.value)}
- className="min-h-40 resize-y font-mono text-xs"
- aria-invalid={error ? true : undefined}
- />
- </ParamFieldShell>
- );
- }
-
- return (
- <ParamFieldShell param={param} value={value} error={error}>
- <Input
- value={String(value)}
- onChange={(e) => onChange(e.target.value)}
- aria-invalid={error ? true : undefined}
- />
- </ParamFieldShell>
- );
-}
-
-// ── Summary panel ──────────────────────────────────────────────────────────
-
-function SummaryPanel({
- parsed,
- values,
- sourceName,
- creatorIdentity,
- bridgeName,
- onLinkAccount,
-}: {
- parsed: ParsedTemplate;
- values: Record<string, string | number | boolean>;
- sourceName: string | null;
- /** How the signed-in user resolves on the template's bridge, or null. */
- creatorIdentity: string | null;
- /** The bridge the room will land on, when known. */
- bridgeName: string | null;
- /** Opens the link-account flow for the template's bridge; null when the
- * bridge is not known, so there is nothing to link to yet. */
- onLinkAccount: (() => void) | null;
-}) {
- const preview = (s: string) => interpolate(s, { ...values, $creator: creatorIdentity ?? 'you' });
- const roomNamePreview = parsed.roomName ? preview(parsed.roomName) : null;
-
- // Agent names with interpolation applied
- const agentPreviews = parsed.agents.map(preview).filter((a) => !a.includes('{'));
- const userPreviews = parsed.users.map(preview).filter((u) => !u.includes('{'));
- const kickoffPreview = parsed.kickoff ? preview(parsed.kickoff) : null;
-
- const steps: React.ReactNode[] = [];
- if (roomNamePreview) {
- steps.push(
- <span>
- Room <strong>{roomNamePreview}</strong>
- {bridgeName ? (
- <>
- {' '}
- with its channel on <strong>{bridgeName}</strong>
- </>
- ) : null}
- </span>
- );
- }
- steps.push(<span>Instructions filled with your inputs</span>);
- for (const agent of agentPreviews) {
- steps.push(
- <span>
- Agent <strong>{agent}</strong> added as member
- </span>
- );
- }
- for (const user of userPreviews) {
- steps.push(
- <span>
- {creatorIdentity !== null && user === creatorIdentity ? (
- <>
- <strong>You</strong> invited as <strong>{user}</strong>
- </>
- ) : (
- <>
- <strong>{user}</strong> invited to the channel
- </>
- )}
- </span>
- );
- }
- if (kickoffPreview) {
- steps.push(<span>Switch posts the kickoff on your behalf to start the agents</span>);
- }
-
- return (
- <div className="flex flex-col gap-6">
- <div className="rounded-lg border border-border p-5">
- <h3 className="mb-3 text-sm font-semibold">What this creates</h3>
- <ol className="space-y-2 text-sm">
- {steps.map((step, i) => (
- <li key={i} className="flex items-start gap-2">
- <span className="flex size-5 shrink-0 items-center justify-center rounded border border-border text-xs">
- {i + 1}
- </span>
- {step}
- </li>
- ))}
- </ol>
- <p className="mt-3 text-xs text-foreground-muted">Nothing else. One room, from one file.</p>
- </div>
-
- {parsed.usesCreator && (
- <div className="rounded-lg border border-border p-4">
- <h4 className="mb-1 text-xs font-semibold text-foreground-muted">You in this room</h4>
- {creatorIdentity ? (
- <p className="text-sm">
- The server knows you{bridgeName ? ` on ${bridgeName}` : ''} as{' '}
- <strong>{creatorIdentity}</strong> <Check className="inline size-3" />
- </p>
- ) : (
- <div className="flex flex-col gap-2">
- <p className="text-sm text-amber-600 dark:text-amber-500">
- This template puts you in the room, and the server does not know which account is
- yours{bridgeName ? ` on ${bridgeName}` : ''}. Link it first; the room cannot be
- created until then, or you would end up with a channel you cannot enter.
- </p>
- {onLinkAccount ? (
- <Button variant="outline" size="sm" className="self-start" onClick={onLinkAccount}>
- Link your account
- </Button>
- ) : (
- <p className="text-xs text-foreground-muted">
- Pick the messaging app first, then link your account there.
- </p>
- )}
- </div>
- )}
- </div>
- )}
-
- {kickoffPreview && (
- <div className="rounded-lg border border-border p-4">
- <h4 className="mb-1 text-xs font-semibold text-foreground-muted">Kickoff message</h4>
- <p className="mb-2 text-xs text-foreground-muted">
- Posted by Switch on your behalf: a one-line headline in the channel, with this text in
- its thread. Each agent it mentions checks whether you may address it, the same as if you
- had typed it, and answers in that thread.
- </p>
- <pre className="max-h-40 overflow-y-auto text-xs whitespace-pre-wrap text-foreground-muted">
- {kickoffPreview}
- </pre>
- </div>
- )}
-
- <div className="rounded-lg border border-border p-4">
- <h4 className="mb-1 text-xs font-semibold text-foreground-muted">Template source</h4>
- <p className="text-sm font-medium">{sourceName ?? 'pasted template'}</p>
- <p className="text-xs text-foreground-muted">
- {sourceName ? 'file' : 'pasted'} · {parsed.params.length} param
- {parsed.params.length !== 1 ? 's' : ''} · valid{' '}
- <Check className="inline size-3 text-foreground-muted" />
- </p>
- </div>
- </div>
- );
-}
-
-// ── Inputs step ────────────────────────────────────────────────────────────
-
-function InputsStep({
- parsed,
- values,
- onValuesChange,
- fieldErrors,
- lists,
- onBack,
- onSubmit,
- sourceName,
- createError,
- editedAgents,
- onEditedAgentsChange,
- editedUsers,
- onEditedUsersChange,
- creatorIdentity,
- bridgeName,
- creatorBlocked,
- onLinkAccount,
- handoffBlocked,
- onAllowHandoffs,
- allowingHandoffs,
-}: {
- parsed: ParsedTemplate;
- values: Record<string, string | number | boolean>;
- onValuesChange: (values: Record<string, string | number | boolean>) => void;
- fieldErrors: Record<string, string>;
- lists: EntityLists;
- onBack: () => void;
- onSubmit: () => void;
- sourceName: string | null;
- createError: string | null;
- editedAgents: string[];
- onEditedAgentsChange: (agents: string[]) => void;
- editedUsers: string[];
- onEditedUsersChange: (users: string[]) => void;
- creatorIdentity: string | null;
- bridgeName: string | null;
- /** The template needs the creator's account on the bridge and none is linked. */
- creatorBlocked: boolean;
- onLinkAccount: (() => void) | null;
- /** Agents in this room that will not hear each other. */
- handoffBlocked: BlockedHandoff[];
- /** Widen the blocked agents' policies so the hand-offs go through. */
- onAllowHandoffs: () => void;
- allowingHandoffs: boolean;
-}) {
- // The template's fixed members are editable only when it has any: a
- // template that names no agents gets no empty "Agents" section to puzzle
- // over, the same way the params list only shows what is declared.
- const showAgents = parsed.hardcodedAgents.length > 0 || editedAgents.length > 0;
- const showUsers = parsed.hardcodedUsers.length > 0 || editedUsers.length > 0;
-
- const handleChange = useCallback(
- (name: string, value: string | number | boolean) => {
- onValuesChange({ ...values, [name]: value });
- },
- [values, onValuesChange]
- );
-
- return (
- <div className="flex gap-8">
- {/* Left: form */}
- <div className="flex min-w-0 flex-1 flex-col gap-4">
- {createError && (
- <Alert variant="destructive">
- <AlertDescription>{createError}</AlertDescription>
- </Alert>
- )}
- {handoffBlocked.length > 0 && (
- <Alert>
- <AlertDescription>
- <div className="flex flex-col gap-2">
- <span>
- These agents will not hear each other:{' '}
- {handoffBlocked.map((b) => `${b.to} ignores ${b.from}`).join(', ')}. An agent
- created from the Console answers only its owner, so the hand-offs in this template
- would bounce.
- </span>
- <Button
- variant="outline"
- size="sm"
- className="self-start"
- disabled={allowingHandoffs}
- onClick={onAllowHandoffs}
- >
- {allowingHandoffs ? 'Updating…' : 'Let them hear each other'}
- </Button>
- </div>
- </AlertDescription>
- </Alert>
- )}
- <FieldGroup>
- {parsed.params.map((param) => (
- <ParamField
- key={param.name}
- param={param}
- value={values[param.name] ?? ''}
- onChange={(v) => handleChange(param.name, v)}
- error={fieldErrors[param.name] ?? null}
- lists={lists}
- />
- ))}
- {showAgents && (
- <Field>
- <div className="flex items-center justify-between gap-3">
- <FieldLabel>Agents</FieldLabel>
- {editedAgents.length > 0 && (
- <span className="text-sm text-foreground-muted">{editedAgents.length} added</span>
- )}
- </div>
- <AgentListField items={editedAgents} onChange={onEditedAgentsChange} lists={lists} />
- <p className="mt-1 text-xs text-foreground-muted">
- Agents the template puts in the room. Drop any the server does not have, or add
- more.
- </p>
- </Field>
- )}
- {showUsers && (
- <Field>
- <div className="flex items-center justify-between gap-3">
- <FieldLabel>Users</FieldLabel>
- {editedUsers.length > 0 && (
- <span className="text-sm text-foreground-muted">{editedUsers.length} added</span>
- )}
- </div>
- <UserListField items={editedUsers} onChange={onEditedUsersChange} lists={lists} />
- <p className="mt-1 text-xs text-foreground-muted">
- People the template invites. A name the server has not seen is looked up in the
- messaging app&apos;s directory when the room is created.
- </p>
- </Field>
- )}
- </FieldGroup>
- <div className="flex flex-col gap-2 pt-2">
- <Button variant="outline" className="w-full" onClick={onBack}>
- Back to template
- </Button>
- <Button className="w-full" onClick={onSubmit} disabled={creatorBlocked}>
- Create room
- </Button>
- {creatorBlocked && (
- <p className="text-center text-xs text-foreground-muted">
- Link your messaging account first, on the right.
- </p>
- )}
- </div>
- </div>
-
- {/* Right: summary */}
- <div className="hidden w-80 shrink-0 lg:block">
- <SummaryPanel
- parsed={parsed}
- values={values}
- sourceName={sourceName}
- creatorIdentity={creatorIdentity}
- bridgeName={bridgeName}
- onLinkAccount={onLinkAccount}
- />
- </div>
- </div>
- );
-}
-
// ── Main view ──────────────────────────────────────────────────────────────
function useServerId(): string {
- return useParams('roomTemplateImport').params.serverId;
+ return useParams('templateImport').params.serverId;
}
const TemplateImportTitlebar = observer(function TemplateImportTitlebar() {
+ const serverId = useServerId();
return (
- <ServerSectionTitlebar serverId={useServerId()} icon={FileText} label="Create from Template" />
+ <ServerSectionTitlebar
+ serverId={serverId}
+ icon={FileText}
+ label="Templates"
+ item={{ label: 'Import' }}
+ onSectionClick={() => appState.navigation.navigate('templates', { serverId })}
+ />
);
});
const TemplateImportPanel = observer(function TemplateImportPanel() {
const serverId = useServerId();
- const agents = useRemoteAgents(serverId);
- const roomsQuery = useQuery({
- queryKey: ['remote-rooms', serverId],
- queryFn: () => rpc.switchServers.listRemoteRooms(serverId),
- });
- const bridgesQuery = useQuery({
- queryKey: ['remote-bridges', serverId],
- queryFn: () => rpc.switchServers.listRemoteBridges(serverId),
- });
- const knownUsersQuery = useQuery({
- queryKey: ['remote-external-users', serverId],
- queryFn: () => rpc.switchServers.listRemoteExternalUsers(serverId),
- });
- // Null from a server without the endpoint: the parser then falls back to
- // its own shape check and the server validates on create.
- const schemaQuery = useQuery({
- queryKey: ['template-schema', serverId],
- queryFn: () => rpc.switchServers.fetchTemplateSchema(serverId),
- });
- const { identities, refresh: refreshIdentities } = useMyIdentities(serverId);
const { showModal } = useModalContext();
- const bridges = useMemo(() => bridgesQuery.data ?? [], [bridgesQuery.data]);
- const templateSchema = schemaQuery.data ?? null;
-
- const [step, setStep] = useState<Step>('source');
- const [yamlText, setYamlText] = useState('');
- const [parsed, setParsed] = useState<ParsedTemplate | null>(null);
+ const {
+ yamlText: initialYaml,
+ sourceName: initialName,
+ templateId: initialTemplateId,
+ edit: editing,
+ } = useParams('templateImport').params;
+ const [yamlText, setYamlText] = useState(initialYaml ?? '');
+ const [saving, setSaving] = useState(false);
const [parseError, setParseError] = useState<string | null>(null);
- const [values, setValues] = useState<Record<string, string | number | boolean>>({});
- const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
- const [createError, setCreateError] = useState<string | null>(null);
- const [sourceName, setSourceName] = useState<string | null>(null);
- const [editedAgents, setEditedAgents] = useState<string[]>([]);
- const [editedUsers, setEditedUsers] = useState<string[]>([]);
-
- // The bridge the room will land on: what a bridge-typed param has been set
- // to, else the one the template names, else the server's default, which is
- // what the server itself falls back to. Following the param means the
- // summary and the creator identity move with the pick.
- const templateBridge = useMemo(() => {
- const bridgeParam = parsed?.params.find((p) => p.type === 'bridge');
- const picked = bridgeParam ? String(values[bridgeParam.name] ?? '') : '';
- const named = picked !== '' ? picked : (parsed?.bridge ?? null);
- if (named) {
- return bridges.find((b) => b.displayName === named) ?? null;
- }
- return bridges.find((b) => b.isDefault) ?? (bridges.length === 1 ? bridges[0] : null);
- }, [bridges, parsed, values]);
-
- // How the signed-in user resolves on that bridge: what `{$creator}`
- // becomes.
- const creatorIdentity = useMemo(() => {
- if (identities === null) return null;
- if (templateBridge) {
- return identities.find((i) => i.bridgeId === templateBridge.id)?.externalUsername ?? null;
- }
- return identities[0]?.externalUsername ?? null;
- }, [identities, templateBridge]);
-
- // The server refuses a template that needs the creator on the bridge when
- // no account is linked; saying so here, with the fix one click away, beats
- // a rejected create. Unknown identities (still loading) do not block.
- const creatorBlocked =
- parsed?.usesCreator === true && identities !== null && creatorIdentity === null;
- const onLinkAccount = useMemo(() => {
- if (!templateBridge) return null;
- return () =>
- showModal('claimIdentityModal', {
- serverId,
- bridgeId: templateBridge.id,
- onSuccess: () => refreshIdentities(),
- });
- }, [templateBridge, serverId, showModal, refreshIdentities]);
-
- // Every agent the room will hold: the template's fixed ones as edited, and
- // whatever the agent-typed params have been set to.
- const handoffBlocked = useMemo(() => {
- if (!parsed) return [];
- const names = new Set<string>(editedAgents);
- for (const param of parsed.params) {
- if (param.type === 'agent') {
- const v = values[param.name];
- if (typeof v === 'string' && v !== '') names.add(v);
- }
- }
- const inRoom = (agents.data ?? []).filter((a) => names.has(a.name));
- return blockedHandoffs(inRoom);
- }, [parsed, editedAgents, values, agents.data]);
+ const [sourceName, setSourceName] = useState<string | null>(initialName ?? null);
- // The template implies these agents talk to each other, so the fix is
- // offered here rather than found later in each agent's settings. Same
- // owner gets "my agents" on every rule; a stranger is named outright.
- const queryClient = useQueryClient();
- const [allowingHandoffs, setAllowingHandoffs] = useState(false);
- const allowHandoffs = useCallback(async () => {
- const byName = new Map((agents.data ?? []).map((a) => [a.name, a]));
- setAllowingHandoffs(true);
+ // Parse before navigating so a syntax error is shown next to the editor,
+ // where it can be fixed, rather than on the Use page.
+ const handleParseAndAdvance = useCallback(async () => {
+ setParseError(null);
try {
- const targets = new Set(handoffBlocked.map((b) => b.to));
- for (const targetName of targets) {
- const target = byName.get(targetName);
- if (!target) continue;
- const sources = handoffBlocked
- .filter((b) => b.to === targetName)
- .map((b) => byName.get(b.from))
- .filter((a): a is NonNullable<typeof a> => a !== undefined);
- const rules = (target.addressingPolicy?.rules ?? []).map((rule) => {
- const next = { ...rule };
- for (const source of sources) {
- if (target.ownerId !== null && source.ownerId === target.ownerId) {
- next.owner_agents = true;
- } else if (next.agents !== '*' && !next.agents.includes(source.id)) {
- next.agents = [...next.agents, source.id];
- }
- }
- return next;
- });
- await rpc.switchServers.updateAddressingPolicy({
- serverId,
- agentId: target.id,
- policy: { rules },
- });
+ await rpc.agentTemplates.parseAgents({ yamlText });
+ const coreYaml = await rpc.agentTemplates.serverDocument({ yamlText });
+ if (coreYaml) await rpc.roomTemplates.parse({ yamlText: coreYaml });
+ else if ((await rpc.agentTemplates.parseAgents({ yamlText })).agents.length === 0) {
+ throw new Error('Template must have a "room:", "group:" or "agent:" block.');
}
- await queryClient.invalidateQueries({ queryKey: remoteAgentsQueryKey(serverId) });
+ appState.navigation.navigate('templateUse', {
+ serverId,
+ yamlText,
+ sourceName: sourceName ?? undefined,
+ });
} catch (e) {
- toast.error(failureText(e, 'Could not update the agents.'));
- } finally {
- setAllowingHandoffs(false);
- }
- }, [agents.data, handoffBlocked, serverId, queryClient]);
-
- const lists = useMemo(
- (): EntityLists => ({
- serverId,
- agents: agents.data ?? [],
- agentsLoading: agents.isLoading,
- rooms: roomsQuery.data ?? [],
- roomsLoading: roomsQuery.isLoading,
- bridges,
- identities,
- knownUsers: knownUsersQuery.data ?? [],
- bridgeId: templateBridge?.id ?? null,
- }),
- [
- serverId,
- agents.data,
- agents.isLoading,
- roomsQuery.data,
- roomsQuery.isLoading,
- bridges,
- identities,
- knownUsersQuery.data,
- templateBridge,
- ]
- );
-
- const validateInputs = useCallback((): boolean => {
- if (!parsed) return false;
- const errors: Record<string, string> = {};
- for (const param of parsed.params) {
- const val = values[param.name];
- if (param.default === null) {
- if (val === '' || val === undefined) {
- errors[param.name] = 'This field is required';
- }
- }
- if (param.type === 'number' && val !== '' && val !== undefined) {
- if (typeof val === 'string' && isNaN(Number(val))) {
- errors[param.name] = 'Must be a number';
- }
- }
+ setParseError(failureText(e, 'Could not parse this template.'));
}
- setFieldErrors(errors);
- return Object.keys(errors).length === 0;
- }, [parsed, values]);
-
- const handleCreate = useCallback(
- async (template?: ParsedTemplate) => {
- const t = template ?? parsed;
- if (!t) return;
-
- if (t.params.length > 0 && !validateInputs()) return;
+ }, [yamlText, serverId, sourceName]);
- setStep('creating');
- setCreateError(null);
-
- try {
- const inputs: Record<string, string | number | boolean> = {};
- for (const param of t.params) {
- const val = values[param.name];
- if (val !== '' && val !== undefined) {
- if (param.type === 'number') {
- inputs[param.name] = Number(val);
- } else {
- inputs[param.name] = val;
- }
- }
- }
-
- // Rewrite YAML with the user's edited agents/users lists. Entries
- // still carrying `{...}` (params and `{$creator}`) are not editable
- // in the form and must survive the rewrite for the server to resolve.
- const interpolatedAgents = t.agents.filter((a) => /\{[^}]+\}/.test(a));
- const finalAgents = [...interpolatedAgents, ...editedAgents];
- const interpolatedUsers = t.users.filter((u) => /\{[^}]+\}/.test(u));
- const finalUsers = [...interpolatedUsers, ...editedUsers];
- const finalYaml = await rpc.roomTemplates.rewriteYaml({
- yamlText,
- agents: finalAgents,
- users: finalUsers,
- });
-
- const result = await rpc.switchServers.createRoomFromTemplate(serverId, finalYaml, inputs);
- await refreshSidebarRoomState(true);
- if (result.failedAttachments.length > 0) {
- const names = result.failedAttachments.map((f) => `${f.id} (${f.error})`).join(', ');
- toast.warning('Room created, but some items could not be added', {
- description: names,
- duration: 8000,
- });
- }
- appState.navigation.navigate('room', { roomId: result.roomId });
- } catch (e) {
- const serverDetail =
- e instanceof RpcError && e.code === 'GatewayError' ? e.stringField('detail') : undefined;
- const message =
- serverDetail ?? failureText(e, 'Could not create the room from this template.');
- const paramMatch = message.match(/param(?:\(s\))?:?\s*['"]?(\w+)/i);
- if (paramMatch && t.params.some((p) => p.name === paramMatch[1])) {
- setFieldErrors({ [paramMatch[1]]: message });
- setStep('inputs');
- } else {
- setCreateError(message);
- setStep(t.params.length > 0 ? 'inputs' : 'source');
- }
- }
- },
- [parsed, values, serverId, yamlText, validateInputs, editedAgents, editedUsers]
- );
-
- const handleParseAndAdvance = useCallback(async () => {
+ // Save the document to the workspace without using it. The dialog asks for
+ // the name and description, prefilled from the document.
+ const handleSaveToServer = useCallback(async () => {
+ setSaving(true);
setParseError(null);
try {
- const result = await rpc.roomTemplates.parse({
- yamlText,
- schema: templateSchema ?? undefined,
+ const prefill = await prefillForSave(yamlText, sourceName);
+ showModal('saveTemplateModal', {
+ serverId,
+ serverName: switchServersStore.servers.find((sv) => sv.id === serverId)?.name ?? null,
+ content: yamlText,
+ ...prefill,
+ onSuccess: () => appState.navigation.navigate('templates', { serverId }),
});
- setParsed(result);
-
- const defaults: Record<string, string | number | boolean> = {};
- for (const param of result.params) {
- if (param.default !== null) {
- defaults[param.name] = param.default;
- } else if (param.type === 'boolean') {
- defaults[param.name] = false;
- } else {
- defaults[param.name] = '';
- }
- }
- setValues((prev) => ({ ...defaults, ...prev }));
- setEditedAgents(result.hardcodedAgents);
- setEditedUsers(result.hardcodedUsers);
- setFieldErrors({});
- setCreateError(null);
-
- const hasForm =
- result.params.length > 0 ||
- result.hardcodedAgents.length > 0 ||
- result.hardcodedUsers.length > 0;
- if (!hasForm) {
- await handleCreate(result);
- } else {
- setStep('inputs');
- }
} catch (e) {
- setParseError(failureText(e, 'Could not parse this template.'));
+ setParseError(failureText(e, 'Could not read this template.'));
+ } finally {
+ setSaving(false);
}
- }, [yamlText, handleCreate, templateSchema]);
-
- const stepNumber = step === 'source' ? 1 : 2;
- const totalSteps = 2;
-
- const subtitle =
- step === 'source'
- ? 'Paste a room template or pick a YAML file.'
- : `${sourceName ?? 'template'}: ${parsed?.params.length ?? 0} input${(parsed?.params.length ?? 0) !== 1 ? 's' : ''}. The room is created only when you hit Create.`;
+ }, [yamlText, sourceName, serverId, showModal]);
+
+ // When this page is opened with a document already chosen (a dropped file,
+ // a recent, a template id), there is nothing to edit here: go on to the
+ // Use page.
+ const advancedOnce = useRef(false);
+ useEffect(() => {
+ if (advancedOnce.current) return;
+ if (initialTemplateId) {
+ advancedOnce.current = true;
+ appState.navigation.navigate('templateUse', { serverId, templateId: initialTemplateId });
+ return;
+ }
+ // `edit` is set when the deployer came back from the Use page to change
+ // the document, so it must not be sent on again.
+ if (initialYaml && initialYaml.trim().length > 0 && !editing) {
+ advancedOnce.current = true;
+ void handleParseAndAdvance();
+ }
+ }, [initialTemplateId, initialYaml, editing, serverId, handleParseAndAdvance]);
return (
<ServerPage
- title="Create from template"
- description={subtitle}
- action={
- <span className="text-xs text-foreground-muted">
- Step {stepNumber} of {totalSteps}
- </span>
- }
+ title="Import a template"
+ description="Paste an agent, room or group template, or pick a YAML file. The document says which it is."
>
- {step === 'source' && (
- <SourceStep
- yamlText={yamlText}
- onYamlChange={setYamlText}
- parseError={parseError}
- onNext={handleParseAndAdvance}
- onFileSelect={setSourceName}
- />
- )}
-
- {step === 'inputs' && parsed && (
- <>
- {parsed.warnings.map((w, i) => (
- <Alert key={i} className="mb-4">
- <AlertDescription>{w}</AlertDescription>
- </Alert>
- ))}
- <InputsStep
- parsed={parsed}
- values={values}
- onValuesChange={setValues}
- fieldErrors={fieldErrors}
- lists={lists}
- onBack={() => setStep('source')}
- onSubmit={() => handleCreate()}
- sourceName={sourceName}
- createError={createError}
- editedAgents={editedAgents}
- onEditedAgentsChange={setEditedAgents}
- editedUsers={editedUsers}
- onEditedUsersChange={setEditedUsers}
- creatorIdentity={creatorIdentity}
- bridgeName={templateBridge?.displayName ?? parsed.bridge}
- creatorBlocked={creatorBlocked}
- onLinkAccount={onLinkAccount}
- handoffBlocked={handoffBlocked}
- onAllowHandoffs={() => void allowHandoffs()}
- allowingHandoffs={allowingHandoffs}
- />
- </>
- )}
-
- {step === 'creating' && (
- <div className="flex items-center justify-center py-12">
- <Loader2 className="size-6 animate-spin text-foreground-passive" />
- <span className="ml-2 text-sm text-foreground-passive">Creating room…</span>
- </div>
- )}
+ <SourceStep
+ yamlText={yamlText}
+ onYamlChange={setYamlText}
+ parseError={parseError}
+ onNext={handleParseAndAdvance}
+ onFileSelect={setSourceName}
+ onSaveToServer={handleSaveToServer}
+ saving={saving}
+ />
</ServerPage>
);
});
-export const roomTemplateImportView = {
- WrapView: ({ children }: { children: React.ReactNode; serverId: string }) => <>{children}</>,
+export const templateImportView = {
+ WrapView: ({
+ children,
+ }: {
+ children: React.ReactNode;
+ serverId: string;
+ /** A document to open the editor with. */
+ yamlText?: string;
+ sourceName?: string;
+ /** A workspace template to load and pass on to the Use page. */
+ templateId?: string;
+ /** Show `yamlText` in the editor instead of passing it on to the Use page. */
+ edit?: boolean;
+ }) => <>{children}</>,
TitlebarSlot: TemplateImportTitlebar,
MainPanel: TemplateImportPanel,
canActivate: (params: unknown): GuardResult => {
@@ -1007,4 +297,10 @@ export const roomTemplateImportView = {
if (typeof serverId !== 'string') return { ok: false, redirect: 'home' };
return { ok: true };
},
-} satisfies ViewDefinition<{ serverId: string }>;
+} satisfies ViewDefinition<{
+ serverId: string;
+ yamlText?: string;
+ sourceName?: string;
+ templateId?: string;
+ edit?: boolean;
+}>;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx
index 40a5ea955..7af7903e2 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx
@@ -18,7 +18,7 @@ export const WorkspaceNav = observer(function WorkspaceNav() {
const { params: homeParams } = useParams('server');
const { params: agentsParams } = useParams('serverAgents');
const { params: roomsParams } = useParams('serverRooms');
- const { params: templatesParams } = useParams('roomTemplateImport');
+ const { params: templatesParams } = useParams('templates');
const active = switchServersStore.activeServer;
if (!active) return null;
@@ -26,7 +26,7 @@ export const WorkspaceNav = observer(function WorkspaceNav() {
{ view: 'server', icon: House, label: 'Home', params: homeParams },
{ view: 'serverAgents', icon: Bot, label: 'Your Agents', params: agentsParams },
{ view: 'serverRooms', icon: DoorOpen, label: 'Your Rooms', params: roomsParams },
- { view: 'roomTemplateImport', icon: FileText, label: 'Templates', params: templatesParams },
+ { view: 'templates', icon: FileText, label: 'Templates', params: templatesParams },
] as const;
return (
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
index 6e73e9157..0bc81fee9 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
@@ -1,12 +1,18 @@
+import { FileText } from 'lucide-react';
import { observer } from 'mobx-react-lite';
-import { useCallback, useState } from 'react';
+import { useCallback, useEffect, useState } from 'react';
+import type { StoredTemplateSummary } from '@main/core/switch-servers/gateway-client';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { bundledTemplates } from '@renderer/features/templates/bundled-templates';
import { agentProviderLabel } from '@renderer/lib/components/agent-mark';
import { AgentPickerRow, ChosenAgentTile } from '@renderer/lib/components/agent-picker';
import { PickerCombobox } from '@renderer/lib/components/picker-combobox';
import { failureText } from '@renderer/lib/errors/describe-failure';
+import { toast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
+import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
import { Button } from '@renderer/lib/ui/button';
@@ -35,9 +41,65 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
onClose,
}: Props) {
const { setCloseGuard } = useModalContext();
+ const { navigate } = useNavigate();
const serverId = switchRoomsStore.roomServerId(roomId);
const roomName = switchRoomsStore.roomNameById(roomId);
+ // Templates can create an agent straight into this room. The bundled
+ // templates are listed at once; the workspace's are added when the request
+ // returns.
+ const [serverTemplates, setServerTemplates] = useState<StoredTemplateSummary[]>([]);
+ useEffect(() => {
+ if (!serverId) return;
+ let cancelled = false;
+ rpc.switchServers
+ .listTemplates({ serverId, kind: 'agent' })
+ .then((list) => {
+ if (!cancelled) setServerTemplates(list);
+ })
+ .catch((e: unknown) => {
+ if (cancelled) return;
+ setServerTemplates([]);
+ toast({
+ title: failureText(e, "Could not load the workspace's templates."),
+ description: 'The built-in ones are still offered.',
+ variant: 'destructive',
+ });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [serverId]);
+ // A built-in template the signed-in user saved to the workspace is listed
+ // once, as their copy. Names are unique only per owner, so someone else's
+ // template of the same name is not a copy.
+ const meId = serverId ? (switchServersStore.statusFor(serverId)?.user?.id ?? null) : null;
+ const onWorkspace = serverTemplates.filter((t) => t.kind === 'agent');
+ const templates: StoredTemplateSummary[] = [
+ ...bundledTemplates
+ .filter(
+ (b) =>
+ b.kind === 'agent' &&
+ !onWorkspace.some((t) => t.name === b.name && meId !== null && t.ownerId === meId)
+ )
+ .map(({ id, name, description, kind, creator }) => ({
+ id,
+ name,
+ description,
+ kind,
+ creator,
+ ownerId: null,
+ })),
+ ...onWorkspace,
+ ];
+ // The Use page creates the agent. With `intoRoomId` it adds the agent to
+ // this room instead of creating the template's own room.
+ const createFromTemplate = (template: StoredTemplateSummary) => {
+ if (!serverId) return;
+ onClose();
+ navigate('templateUse', { serverId, templateId: template.id, intoRoomId: roomId });
+ };
+
const [selected, setSelected] = useState<Candidate[]>([]);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -102,6 +164,30 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
</p>
)}
+ {serverId && templates.length > 0 && (
+ <Field>
+ <FieldLabel>New agent from a template</FieldLabel>
+ <div className="flex flex-wrap gap-2">
+ {templates.map((t) => (
+ <Button
+ key={t.id}
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={isSubmitting}
+ onClick={() => void createFromTemplate(t)}
+ >
+ <FileText className="size-3.5" />
+ {t.name}
+ </Button>
+ ))}
+ </div>
+ <span className="text-xs text-foreground-muted">
+ Creates the agent and puts it in this room. Mention it here afterwards to start it.
+ </span>
+ </Field>
+ )}
+
<Field>
<div className="flex items-center justify-between gap-3">
<FieldLabel>Agents</FieldLabel>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
index fde4dbc93..af436450b 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
@@ -1,5 +1,5 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
-import { ExternalLink, Loader2, Plus, RefreshCw, Search, X } from 'lucide-react';
+import { ExternalLink, FileText, Loader2, Plus, RefreshCw, Search, X } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useState } from 'react';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
@@ -319,6 +319,7 @@ const ParticipantsSection = observer(function ParticipantsSection({
}) {
const queryClient = useQueryClient();
const [adding, setAdding] = useState(false);
+ const showAddAgentsToRoomModal = useShowModal('addAgentsToRoomModal');
// Names for agents belonging to other installs, which this computer has no
// local record of. Shares its key with the rest of the app, so it is usually
@@ -340,15 +341,25 @@ const ParticipantsSection = observer(function ParticipantsSection({
{membershipSummary(room.agentIds.length, room.connectedUserNames.length)}
</span>
</div>
- <Button
- variant="outline"
- size="sm"
- aria-expanded={adding}
- onClick={() => setAdding((v) => !v)}
- >
- <Plus className="size-3.5" />
- Add agent
- </Button>
+ <div className="flex items-center gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => showAddAgentsToRoomModal({ roomId: room.id })}
+ >
+ <FileText className="size-3.5" />
+ From a template
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ aria-expanded={adding}
+ onClick={() => setAdding((v) => !v)}
+ >
+ <Plus className="size-3.5" />
+ Add agent
+ </Button>
+ </div>
</div>
{room.agentIds.length === 0 && room.connectedUserNames.length === 0 ? (
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-section-titlebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-section-titlebar.tsx
index c79343daa..64fa91558 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-section-titlebar.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-section-titlebar.tsx
@@ -17,10 +17,16 @@ export const ServerSectionTitlebar = observer(function ServerSectionTitlebar({
serverId,
icon: SectionIcon,
label,
+ item,
+ onSectionClick,
}: {
serverId: string;
icon: LucideIcon;
label: string;
+ /** A third breadcrumb for a page inside the section, such as one template's page. */
+ item?: { label: string; icon?: React.ReactNode };
+ /** Navigates back to the section's list. Used when `item` is shown, so the section crumb is clickable. */
+ onSectionClick?: () => void;
}) {
const server = switchServersStore.servers.find((s) => s.id === serverId);
return (
@@ -38,7 +44,11 @@ export const ServerSectionTitlebar = observer(function ServerSectionTitlebar({
key: 'section',
icon: <SectionIcon className="size-3.5 shrink-0" />,
label,
+ ...(item && onSectionClick ? { onClick: onSectionClick } : {}),
},
+ ...(item
+ ? [{ key: 'item', icon: item.icon, label: item.label, maxWidthClassName: 'max-w-64' }]
+ : []),
]}
/>
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/agent-template-data.ts b/console/apps/switch-console-desktop/src/renderer/features/templates/agent-template-data.ts
new file mode 100644
index 000000000..133d4e935
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/agent-template-data.ts
@@ -0,0 +1,238 @@
+import type { ParsedAgentTemplate } from '@main/core/agent-templates/agent-template-format';
+import type { ParsedAgentEntry, TemplateKind } from '@main/core/agent-templates/template-document';
+import type { TemplateSummary } from '@main/core/agent-templates/template-summary';
+import type { AgentTemplateOrigin } from '@main/core/agents/agent-config-file';
+import type { ParsedTemplate } from '@main/core/room-templates/controller';
+import type { StoredTemplateSummary } from '@main/core/switch-servers/gateway-client';
+import { rpc } from '@renderer/lib/ipc';
+import { type BundledTemplate, bundledTemplates, findBundledTemplate } from './bundled-templates';
+
+/**
+ * One agent as a template describes it, plus its room part already converted
+ * to a room template. A caller can create the room as soon as the agent
+ * exists, without parsing YAML itself.
+ */
+export type AgentTemplate = {
+ /** The template's own name, for a heading. */
+ name: string;
+ /** Where the template came from. Recorded on the agent so its settings
+ * page can load the template again and offer its current instructions.
+ * Null for a pasted document, which cannot be loaded again. */
+ origin: AgentTemplateOrigin | null;
+ /** The agent name from the template's `name` field. The deployer can change it before creating. */
+ agentName: string | null;
+ description: string;
+ instructions: string;
+ repoUrl: string | null;
+ sources: ParsedAgentTemplate['sources'];
+ addressing: ParsedAgentTemplate['addressing'];
+ /** The template's room as a room template document, or null when it declares no room. */
+ roomYaml: string | null;
+ roomName: string | null;
+ warnings: string[];
+};
+
+/** Parse a document into the agent it describes. */
+export async function agentTemplateFromContent(
+ templateName: string,
+ content: string,
+ instructions: string | null,
+ origin: AgentTemplateOrigin | null
+): Promise<AgentTemplate> {
+ const parsed = await rpc.agentTemplates.parse({ yamlText: content, instructions });
+ const roomYaml = parsed.room
+ ? await rpc.agentTemplates.serverDocument({ yamlText: content })
+ : null;
+ return {
+ name: templateName,
+ origin,
+ agentName: parsed.name,
+ description: parsed.description,
+ instructions: parsed.instructions,
+ repoUrl: parsed.repoUrl,
+ sources: parsed.sources,
+ addressing: parsed.addressing,
+ roomYaml,
+ roomName: parsed.room?.name ?? null,
+ warnings: parsed.warnings,
+ };
+}
+
+/** Whether the template recorded on an agent's config can still be loaded.
+ * A bundled template can be dropped from a later Console. */
+export function templateOriginExists(origin: AgentTemplateOrigin): boolean {
+ return origin.source !== 'bundled' || findBundledTemplate(origin.id) !== undefined;
+}
+
+/** Load the template recorded on an agent's config. */
+export async function loadAgentTemplateByOrigin(
+ origin: AgentTemplateOrigin
+): Promise<AgentTemplate> {
+ if (origin.source === 'bundled') {
+ const bundled = findBundledTemplate(origin.id);
+ if (!bundled) throw new Error(`This Console no longer bundles "${origin.name}".`);
+ return agentTemplateFromContent(origin.name, bundled.yamlText, bundled.instructions, origin);
+ }
+ if (!origin.serverId)
+ throw new Error(`"${origin.name}" came from a server this Console does not know.`);
+ const detail = await rpc.switchServers.getTemplateDetail({
+ serverId: origin.serverId,
+ templateId: origin.id,
+ });
+ return agentTemplateFromContent(origin.name, detail.definition, null, origin);
+}
+
+/** Resolve a listing entry (bundled or from the server's registry) into the agent it describes. */
+export async function loadAgentTemplate(
+ serverId: string,
+ template: StoredTemplateSummary
+): Promise<AgentTemplate> {
+ const bundled = findBundledTemplate(template.id);
+ if (bundled) {
+ return agentTemplateFromContent(bundled.name, bundled.yamlText, bundled.instructions, {
+ id: bundled.id,
+ name: bundled.name,
+ source: 'bundled',
+ });
+ }
+ const detail = await rpc.switchServers.getTemplateDetail({ serverId, templateId: template.id });
+ return agentTemplateFromContent(detail.name, detail.definition, null, {
+ id: detail.id,
+ name: detail.name,
+ source: 'server',
+ serverId,
+ });
+}
+
+/** A template loaded for its page: its source, what it creates, and its document. */
+export type LoadedTemplate = {
+ name: string;
+ description: string;
+ kind: TemplateKind;
+ /** The bundled template, when this is one. Null for a workspace template. */
+ bundled: BundledTemplate | null;
+ /** For a bundled template: its copy saved on the workspace, or null when there is none. */
+ savedCopy: StoredTemplateSummary | null;
+ /** For a workspace template: the bundled template with the same name, or null when there is none. */
+ copyOf: BundledTemplate | null;
+ /** The workspace record, when the template is stored on the server. Null for a bundled template. */
+ server: StoredTemplateSummary | null;
+ /** The agents the template creates, in document order. Empty for a room template. */
+ agents: ParsedAgentEntry[];
+ /** The room part, parsed: the rooms and the params. Null when the document has no rooms. */
+ room: ParsedTemplate | null;
+ /** The rooms and agents it creates, with counts for the listing card. */
+ summary: TemplateSummary;
+ /** The full document with agent instructions inlined, as stored or as it would be stored. */
+ document: string;
+};
+
+/**
+ * Load one template by the id the listing gave it: a bundled id, or a registry
+ * row id. A bundled template also records whether the signed-in user saved a
+ * copy of it on the workspace, and a workspace row of theirs records which
+ * built-in it copies, so the page can say either. Names are unique only per
+ * owner, so someone else's template of the same name is not a copy.
+ */
+export async function loadTemplateById(
+ serverId: string,
+ templateId: string,
+ meId: string | null
+): Promise<LoadedTemplate> {
+ const bundled = findBundledTemplate(templateId);
+ let name: string;
+ let description: string;
+ let document: string;
+ let server: StoredTemplateSummary | null = null;
+ let copyOf: BundledTemplate | null = null;
+ let savedCopy: StoredTemplateSummary | null = null;
+ if (bundled) {
+ savedCopy =
+ (await rpc.switchServers.listTemplates({ serverId }).catch(() => [])).find(
+ (t) => t.name === bundled.name && meId !== null && t.ownerId === meId
+ ) ?? null;
+ name = bundled.name;
+ description = bundled.description;
+ document = bundled.instructions
+ ? await rpc.agentTemplates.compose({
+ yamlText: bundled.yamlText,
+ instructions: bundled.instructions,
+ })
+ : bundled.yamlText;
+ } else {
+ const detail = await rpc.switchServers.getTemplateDetail({ serverId, templateId });
+ const { definition, ...summary } = detail;
+ name = detail.name;
+ description = detail.description;
+ document = definition;
+ server = summary;
+ copyOf =
+ meId !== null && detail.ownerId === meId
+ ? (bundledTemplates.find((b) => b.name === detail.name) ?? null)
+ : null;
+ }
+ const kind = await rpc.agentTemplates.kind({ yamlText: document });
+ const { agents } = await rpc.agentTemplates.parseAgents({ yamlText: document });
+ // Every param, the Console's own types included, so the Inputs table lists
+ // what the Use page asks for and what the card counts.
+ const coreYaml = await rpc.agentTemplates.serverDocument({
+ yamlText: document,
+ keepConsoleParams: true,
+ });
+ const room = coreYaml ? await rpc.roomTemplates.parse({ yamlText: coreYaml }) : null;
+ const summary = await rpc.agentTemplates.summarize({ yamlText: document });
+ return {
+ name,
+ description,
+ kind,
+ bundled: bundled ?? null,
+ savedCopy,
+ copyOf,
+ server,
+ agents,
+ room,
+ summary,
+ document,
+ };
+}
+
+/** A readable listing name from a file name: no extension, no `.template`, words not dashes. */
+export function templateNameFromFile(fileName: string): string {
+ const stem = fileName
+ .replace(/(\.template)?\.ya?ml$/i, '')
+ .replace(/[-_]+/g, ' ')
+ .trim();
+ return stem.length === 0 ? stem : stem[0].toUpperCase() + stem.slice(1);
+}
+
+/** What the save dialog should offer for a document: its kind, a name and a description. */
+export async function prefillForSave(
+ content: string,
+ sourceName: string | null
+): Promise<{ kind: TemplateKind; name: string; description: string }> {
+ const fromFile = sourceName ? templateNameFromFile(sourceName) : '';
+ const kind = await rpc.agentTemplates.kind({ yamlText: content });
+ if (kind === 'agent') {
+ const t = await agentTemplateFromContent(fromFile || 'Agent template', content, null, null);
+ return {
+ kind,
+ name: fromFile || t.agentName || 'Agent template',
+ description: t.description,
+ };
+ }
+ const coreYaml = await rpc.agentTemplates.serverDocument({ yamlText: content });
+ const t = coreYaml ? await rpc.roomTemplates.parse({ yamlText: coreYaml }) : null;
+ const literal = (s: string | null) => (s && !/\{[^}]+\}/.test(s) ? s : null);
+ return {
+ kind,
+ name:
+ fromFile ||
+ literal(t?.groupName ?? null) ||
+ literal(t?.roomName ?? null) ||
+ (kind === 'group' ? 'Group template' : 'Room template'),
+ // A room's description often contains a placeholder ("Workroom for
+ // {task}"), which reads badly on a listing card. Leave the description
+ // empty and let the user write one in the dialog.
+ description: literal(t?.roomDescription ?? null) ?? '',
+ };
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/bundled-templates.ts b/console/apps/switch-console-desktop/src/renderer/features/templates/bundled-templates.ts
new file mode 100644
index 000000000..95f49e2b7
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/bundled-templates.ts
@@ -0,0 +1,36 @@
+import switchExpertInstructions from '@root/../../../switch-expert/AGENT.md?raw';
+import switchExpertTemplate from '@root/../../../switch-expert/template.yaml?raw';
+
+/**
+ * Templates that ship inside the Console, read from the repository at build
+ * time: the Switch expert from `switch-expert/`, the template from
+ * `template.yaml` and the instructions from `AGENT.md`. Listing them needs
+ * no request to the server, so they are there before the server has a
+ * template registry.
+ */
+export type BundledTemplate = {
+ id: string;
+ name: string;
+ description: string;
+ kind: string;
+ creator: string;
+ yamlText: string;
+ /** Instructions kept in a separate file, used when the document has no `instructions:`. */
+ instructions: string | null;
+};
+
+export const bundledTemplates: BundledTemplate[] = [
+ {
+ id: 'bundled:switch-expert',
+ name: 'Switch expert',
+ description: 'Knows Switch inside out. Ask it how to set things up or why something is off.',
+ kind: 'agent',
+ creator: 'Switch',
+ yamlText: switchExpertTemplate,
+ instructions: switchExpertInstructions,
+ },
+];
+
+export function findBundledTemplate(id: string): BundledTemplate | undefined {
+ return bundledTemplates.find((t) => t.id === id);
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx
new file mode 100644
index 000000000..aac7d16b5
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/save-template-modal.tsx
@@ -0,0 +1,132 @@
+import { useId, useState } from 'react';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { toast } from '@renderer/lib/hooks/use-toast';
+import { rpc } from '@renderer/lib/ipc';
+import type { BaseModalProps } from '@renderer/lib/modal/modal-provider';
+import { Alert, AlertDescription } from '@renderer/lib/ui/alert';
+import { Badge } from '@renderer/lib/ui/badge';
+import { Button } from '@renderer/lib/ui/button';
+import {
+ DialogContentArea,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@renderer/lib/ui/dialog';
+import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';
+import { Input } from '@renderer/lib/ui/input';
+import { ModalLayout } from '@renderer/lib/ui/modal-layout';
+
+export type SaveTemplateArgs = {
+ serverId: string;
+ serverName?: string | null;
+ kind: 'agent' | 'room' | 'group';
+ content: string;
+ /** Name and description, prefilled from the document. The user can change both. */
+ name: string;
+ description: string;
+};
+
+type Props = BaseModalProps<{ id: string }> & SaveTemplateArgs;
+
+/**
+ * Asks for the name and description before a document is saved to the
+ * workspace. They are asked rather than derived because a file name makes a
+ * poor listing name and a room's description often carries a placeholder.
+ */
+export function SaveTemplateModal({
+ serverId,
+ serverName,
+ kind,
+ content,
+ name: initialName,
+ description: initialDescription,
+ onSuccess,
+ onClose,
+}: Props) {
+ const nameId = useId();
+ const descriptionId = useId();
+ const [name, setName] = useState(initialName);
+ const [description, setDescription] = useState(initialDescription);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const save = async () => {
+ setSaving(true);
+ setError(null);
+ try {
+ const saved = await rpc.switchServers.saveTemplate({
+ serverId,
+ name: name.trim(),
+ description: description.trim(),
+ kind,
+ content,
+ });
+ toast({
+ title: `"${name.trim()}" is now on ${serverName ?? 'the server'}`,
+ });
+ onSuccess({ id: saved.id });
+ } catch (e) {
+ setError(failureText(e, 'Could not save the template to the server.'));
+ setSaving(false);
+ }
+ };
+
+ return (
+ <ModalLayout
+ header={
+ <DialogHeader showCloseButton={!saving}>
+ <DialogTitle>Save to {serverName ?? 'the server'}</DialogTitle>
+ </DialogHeader>
+ }
+ footer={
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={onClose} disabled={saving}>
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ onClick={() => void save()}
+ disabled={saving || name.trim().length === 0}
+ >
+ {saving ? 'Saving…' : 'Save'}
+ </Button>
+ </DialogFooter>
+ }
+ >
+ <DialogContentArea className="gap-4">
+ <p className="text-sm text-foreground-muted">
+ Everyone on this workspace will find it under Templates.{' '}
+ <Badge variant="outline">{kind} template</Badge>
+ </p>
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor={nameId}>Name</FieldLabel>
+ <Input
+ id={nameId}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder={kind === 'agent' ? 'Switch expert' : 'Coder and reviewer workroom'}
+ autoFocus
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor={descriptionId}>
+ Description <span className="text-foreground-muted">(optional)</span>
+ </FieldLabel>
+ <Input
+ id={descriptionId}
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ placeholder="What it is for, in a line"
+ />
+ </Field>
+ </FieldGroup>
+ {error && (
+ <Alert variant="destructive">
+ <AlertDescription>{error}</AlertDescription>
+ </Alert>
+ )}
+ </DialogContentArea>
+ </ModalLayout>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx
new file mode 100644
index 000000000..6a955a1be
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-detail-view.tsx
@@ -0,0 +1,559 @@
+import {
+ ArrowLeft,
+ Bot,
+ Check,
+ Copy,
+ DoorOpen,
+ Download,
+ FileText,
+ Loader2,
+ Trash2,
+} from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useEffect, useState } from 'react';
+import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';
+import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';
+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { PageHeader } from '@renderer/lib/components/page-header';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { toast } from '@renderer/lib/hooks/use-toast';
+import { rpc } from '@renderer/lib/ipc';
+import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
+import { openExternalUrl } from '@renderer/lib/open-external';
+import { Badge } from '@renderer/lib/ui/badge';
+import { Button } from '@renderer/lib/ui/button';
+import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';
+import { cn } from '@renderer/utils/utils';
+import { type LoadedTemplate, loadTemplateById } from './agent-template-data';
+import { isRequired, paramLabel, typeLabel } from './use/use-template-model';
+
+function useViewParams() {
+ return useParams('templateDetail').params;
+}
+
+const ADDRESSING_LABEL = {
+ owner: 'Only its owner',
+ 'owner-agents': 'Its owner and their agents',
+ anyone: 'Anyone in its rooms',
+} as const;
+
+const TemplateDetailTitlebar = observer(function TemplateDetailTitlebar() {
+ const { serverId } = useViewParams();
+ const { navigate } = useNavigate();
+ return (
+ <ServerSectionTitlebar
+ serverId={serverId}
+ icon={FileText}
+ label="Templates"
+ onSectionClick={() => navigate('templates', { serverId })}
+ item={{ label: useTemplateName() ?? 'Template' }}
+ />
+ );
+});
+
+// The panel loads the template; the titlebar shows its name. They share the
+// name through this module-level value so the titlebar does not load the
+// template a second time.
+let currentName: string | null = null;
+const nameListeners = new Set<(name: string | null) => void>();
+function setCurrentName(name: string | null) {
+ currentName = name;
+ for (const l of nameListeners) l(name);
+}
+function useTemplateName(): string | null {
+ const [name, setName] = useState(currentName);
+ useEffect(() => {
+ nameListeners.add(setName);
+ return () => {
+ nameListeners.delete(setName);
+ };
+ }, []);
+ return name;
+}
+
+function FactRow({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+ <div className="flex items-start gap-3 text-sm">
+ <span className="w-28 shrink-0 text-foreground-muted">{label}</span>
+ <div className="min-w-0 flex-1">{children}</div>
+ </div>
+ );
+}
+
+function Link({ url, label }: { url: string; label?: string | null }) {
+ return (
+ <button
+ type="button"
+ className="cursor-pointer underline underline-offset-2"
+ onClick={() => void openExternalUrl(url, 'Could not open the page')}
+ >
+ {label ?? url.replace(/^https?:\/\//, '')}
+ </button>
+ );
+}
+
+function ExpandableTextBlock({
+ text,
+ collapsedHeight = 'max-h-56',
+}: {
+ text: string;
+ collapsedHeight?: string;
+}) {
+ const [expanded, setExpanded] = useState(false);
+ const lines = text.split('\n').length;
+ return (
+ <div className="flex flex-col gap-2">
+ <pre
+ className={`overflow-auto rounded-md border border-border bg-background-2 p-3 font-mono text-xs leading-5 whitespace-pre-wrap text-foreground ${expanded ? '' : collapsedHeight}`}
+ >
+ {text}
+ </pre>
+ {lines > 12 && (
+ <button
+ type="button"
+ onClick={() => setExpanded((v) => !v)}
+ className="cursor-pointer self-start text-sm text-foreground-muted hover:text-foreground"
+ >
+ {expanded ? 'Collapse' : `Expand (${lines} lines)`}
+ </button>
+ )}
+ </div>
+ );
+}
+
+function CopyButton({ text }: { text: string }) {
+ const [copied, setCopied] = useState(false);
+ return (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ void navigator.clipboard.writeText(text).then(() => {
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ });
+ }}
+ >
+ {copied ? (
+ <Check className="size-3.5 text-foreground-success" />
+ ) : (
+ <Copy className="size-3.5" />
+ )}
+ {copied ? 'Copied' : 'Copy'}
+ </Button>
+ );
+}
+
+const KIND_LABEL: Record<LoadedTemplate['kind'], string> = {
+ agent: 'Agent',
+ room: 'Room',
+ group: 'Group',
+};
+
+const TemplateDetailPanel = observer(function TemplateDetailPanel() {
+ const { serverId, templateId } = useViewParams();
+ const { navigate } = useNavigate();
+ const server = switchServersStore.servers.find((s) => s.id === serverId);
+ const me = switchServersStore.statusFor(serverId)?.user ?? null;
+
+ const [loaded, setLoaded] = useState<LoadedTemplate | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState<'save' | 'delete' | 'export' | null>(null);
+ const [confirmRemove, setConfirmRemove] = useState(false);
+ const [showDocument, setShowDocument] = useState(false);
+ const [showInstructions, setShowInstructions] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ setLoaded(null);
+ setError(null);
+ loadTemplateById(serverId, templateId, me?.id ?? null)
+ .then((t) => {
+ if (cancelled) return;
+ setLoaded(t);
+ setCurrentName(t.name);
+ })
+ .catch((e: unknown) => {
+ if (!cancelled) setError(failureText(e, 'Could not load this template.'));
+ });
+ return () => {
+ cancelled = true;
+ setCurrentName(null);
+ };
+ }, [serverId, templateId, me?.id]);
+
+ const back = (
+ <Button
+ size="sm"
+ variant="ghost"
+ className="-ml-2"
+ onClick={() => navigate('templates', { serverId })}
+ >
+ <ArrowLeft className="size-4" /> All templates
+ </Button>
+ );
+
+ if (error) {
+ return (
+ <div className="relative z-10 flex min-h-0 flex-1 flex-col overflow-auto bg-background">
+ <div className="space-y-6 px-8 pb-10">
+ <PageHeader sticky title="Template" back={back} />
+ <p className="text-sm text-destructive">{error}</p>
+ </div>
+ </div>
+ );
+ }
+ if (!loaded) {
+ return (
+ <div className="flex flex-1 items-center justify-center">
+ <Loader2 className="size-5 animate-spin text-foreground-muted" />
+ </div>
+ );
+ }
+
+ const mine = loaded.server !== null && me !== null && loaded.server.ownerId === me.id;
+ const canDelete = loaded.server !== null && (mine || me?.role === 'admin');
+ const singleAgent = loaded.kind === 'agent' ? (loaded.agents[0] ?? null) : null;
+ // In a single-agent document the room refers to the agent as `{agent}`. The
+ // Console fills that in with the agent's name, so it is not an input to list.
+ const params = (loaded.room?.params ?? []).filter((p) => !(singleAgent && p.name === 'agent'));
+ const slug = (singleAgent?.name ?? loaded.name).toLowerCase().replace(/[^a-z0-9]+/g, '-');
+
+ const use = () => navigate('templateUse', { serverId, templateId });
+
+ const saveToServer = async () => {
+ if (!loaded.bundled) return;
+ setBusy('save');
+ try {
+ const saved = await rpc.switchServers.saveTemplate({
+ serverId,
+ name: loaded.bundled.name,
+ description: loaded.bundled.description,
+ kind: loaded.bundled.kind,
+ content: loaded.document,
+ });
+ toast({ title: `"${loaded.name}" is now on ${server?.name ?? 'the workspace'}` });
+ navigate('templateDetail', { serverId, templateId: saved.id });
+ } catch (e) {
+ toast({
+ title: 'Could not save the template to the workspace',
+ description: failureText(e, 'Check the server connection and try again.'),
+ variant: 'destructive',
+ });
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const remove = async () => {
+ if (!loaded.server) return;
+ setBusy('delete');
+ try {
+ await rpc.switchServers.deleteTemplate({ serverId, templateId: loaded.server.id });
+ toast({ title: `"${loaded.name}" removed from ${server?.name ?? 'the workspace'}` });
+ navigate('templates', { serverId });
+ } catch (e) {
+ toast({
+ title: 'Could not remove the template',
+ description: failureText(e, 'Check the server connection and try again.'),
+ variant: 'destructive',
+ });
+ setBusy(null);
+ }
+ };
+
+ const exportYaml = async () => {
+ setBusy('export');
+ try {
+ const path = await rpc.app.saveTextFile({
+ title: 'Export template',
+ defaultPath: `${slug}.template.yaml`,
+ content: loaded.document,
+ });
+ if (path) toast({ title: 'Exported', description: path });
+ } catch (e) {
+ toast({
+ title: 'Could not export the template',
+ description: failureText(e, ''),
+ variant: 'destructive',
+ });
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const ownerLine = loaded.bundled
+ ? 'Shipped with Switch'
+ : mine
+ ? 'Yours'
+ : `Uploaded by ${loaded.server?.creator ?? 'someone'}`;
+ const visibilityLine = loaded.server ? 'Shared with the workspace' : 'Shared with everyone';
+
+ return (
+ <div className="relative z-10 flex min-h-0 flex-1 flex-col overflow-auto bg-background">
+ <div className="mx-auto w-full max-w-4xl space-y-7 px-8 pb-10">
+ <PageHeader
+ sticky
+ title={loaded.name}
+ description={
+ <span className="flex flex-col gap-1.5">
+ <span>{loaded.description || 'No description.'}</span>
+ <span className="flex items-center gap-2 text-xs text-foreground-passive">
+ <span>{ownerLine}</span>
+ <span>·</span>
+ <span>{visibilityLine}</span>
+ {loaded.copyOf && (
+ <>
+ <span>·</span>
+ <span>A copy of the built-in one</span>
+ </>
+ )}
+ {loaded.savedCopy && (
+ <>
+ <span>·</span>
+ <button
+ type="button"
+ className="cursor-pointer underline underline-offset-2 hover:text-foreground"
+ onClick={() =>
+ navigate('templateDetail', { serverId, templateId: loaded.savedCopy!.id })
+ }
+ >
+ A copy is saved on this workspace
+ </button>
+ </>
+ )}
+ </span>
+ </span>
+ }
+ back={back}
+ >
+ <div className="flex flex-wrap items-center gap-2">
+ <Badge variant="secondary">{KIND_LABEL[loaded.kind]}</Badge>
+ {loaded.bundled && (
+ <Badge variant="outline" title="Shipped with Switch">
+ Official
+ </Badge>
+ )}
+ <span className="flex-1" />
+ {loaded.bundled && !loaded.savedCopy && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={busy !== null}
+ onClick={() => void saveToServer()}
+ >
+ {busy === 'save' ? 'Saving…' : 'Save to workspace'}
+ </Button>
+ )}
+ {canDelete && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={busy !== null}
+ onClick={() => {
+ // The first click asks for confirmation, the second removes.
+ // Removal is visible to everyone on the workspace and cannot
+ // be undone, and this page has no confirmation dialog.
+ if (confirmRemove) void remove();
+ else setConfirmRemove(true);
+ }}
+ onBlur={() => setConfirmRemove(false)}
+ >
+ <Trash2 className="size-3.5" />
+ {busy === 'delete'
+ ? 'Removing…'
+ : confirmRemove
+ ? 'Click again to remove'
+ : 'Remove from workspace'}
+ </Button>
+ )}
+ <Button type="button" size="sm" onClick={use} disabled={busy !== null}>
+ Use template
+ </Button>
+ </div>
+ </PageHeader>
+
+ <section className="flex flex-col gap-2.5">
+ <h2 className="text-sm font-semibold text-foreground">What it creates</h2>
+ {loaded.summary.creates.length > 0 ? (
+ <div className="flex flex-col divide-y divide-border overflow-hidden rounded-[11px] border border-border bg-background-1">
+ {loaded.summary.creates.map((c, i) => {
+ const Icon = c.kind === 'room' ? DoorOpen : Bot;
+ return (
+ <div key={i} className="flex items-center gap-3 px-3.5 py-3">
+ <span className="flex size-6 shrink-0 items-center justify-center rounded-lg bg-background-2 text-foreground-muted">
+ <Icon className="size-3.5" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="truncate font-mono text-[13px] font-medium">{c.name}</div>
+ <div className="mt-0.5 text-xs leading-snug text-foreground-muted">
+ {c.description}
+ </div>
+ </div>
+ <span className="shrink-0 text-[11px] text-foreground-passive">
+ {c.kind === 'room' ? 'Room' : 'Agent'}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ ) : (
+ <p className="text-sm text-foreground-muted">Nothing yet: the document is empty.</p>
+ )}
+ {singleAgent && (
+ <div className="flex flex-col gap-2 pt-1">
+ {singleAgent.repoUrl && (
+ <FactRow label="Repository">
+ <Link url={singleAgent.repoUrl} />
+ <span className="text-foreground-muted">, cloned into its directory</span>
+ </FactRow>
+ )}
+ {singleAgent.sources.length > 0 && (
+ <FactRow label="Sources">
+ <span className="flex flex-wrap gap-x-1.5">
+ {singleAgent.sources.map((src, i) => (
+ <span key={src.url}>
+ {i > 0 && <span className="text-foreground-muted">· </span>}
+ <Link url={src.url} label={src.label} />
+ </span>
+ ))}
+ </span>
+ </FactRow>
+ )}
+ <FactRow label="Answers">
+ {ADDRESSING_LABEL[singleAgent.addressing ?? 'owner']}
+ </FactRow>
+ {loaded.room?.kickoff && (
+ <FactRow label="Kickoff">
+ <span className="text-foreground-muted">Posted as you once the room exists</span>
+ </FactRow>
+ )}
+ </div>
+ )}
+ {!singleAgent && loaded.room?.kickoff && (
+ <FactRow label="Kickoff">
+ <span className="whitespace-pre-wrap">{loaded.room.kickoff.trim()}</span>
+ </FactRow>
+ )}
+ </section>
+
+ {params.length > 0 && (
+ <section className="flex flex-col gap-2.5">
+ <div className="flex items-baseline gap-2">
+ <h2 className="text-sm font-semibold text-foreground">Inputs</h2>
+ <span className="text-xs text-foreground-passive">
+ You fill these in when you use it.
+ </span>
+ </div>
+ <div className="flex flex-col divide-y divide-border overflow-hidden rounded-[11px] border border-border bg-background-1">
+ {params.map((p) => (
+ <div key={p.name} className="flex items-start gap-3 px-3.5 py-2.5 text-[12.5px]">
+ <span
+ className={cn(
+ 'w-36 shrink-0 truncate',
+ paramLabel(p) === p.name && 'font-mono'
+ )}
+ >
+ {paramLabel(p)}
+ </span>
+ <span className="w-16 shrink-0 text-[11.5px] text-foreground-passive">
+ {typeLabel(p.type)}
+ </span>
+ <span className="min-w-0 flex-1 leading-snug text-foreground-muted">
+ {p.description ??
+ (Array.isArray(p.default)
+ ? `Tries ${p.default.join(', then ')}`
+ : p.default !== null
+ ? `Defaults to ${String(p.default)}`
+ : '')}
+ </span>
+ <span
+ className={cn(
+ 'shrink-0 text-[11.5px]',
+ isRequired(p)
+ ? 'text-amber-600 dark:text-amber-400'
+ : 'text-foreground-passive'
+ )}
+ >
+ {p.input === 'fixed'
+ ? 'Set by the template'
+ : p.input === 'advanced'
+ ? 'Advanced'
+ : isRequired(p)
+ ? 'Required'
+ : 'Optional'}
+ </span>
+ </div>
+ ))}
+ </div>
+ </section>
+ )}
+
+ {singleAgent && (
+ <section className="flex flex-col gap-2.5">
+ <DisclosureRow
+ open={showInstructions}
+ title={showInstructions ? 'Hide the instructions' : 'Show the instructions'}
+ meta={`${singleAgent.instructions.split('\n').length} lines`}
+ onToggle={() => setShowInstructions((o) => !o)}
+ />
+ {showInstructions && (
+ <ExpandableTextBlock text={singleAgent.instructions} collapsedHeight="max-h-none" />
+ )}
+ </section>
+ )}
+
+ <section className="flex flex-col gap-2.5">
+ <DisclosureRow
+ open={showDocument}
+ title={showDocument ? 'Hide the document' : 'Show the document'}
+ onToggle={() => setShowDocument((o) => !o)}
+ />
+ {showDocument && (
+ <div className="overflow-hidden rounded-[11px] border border-border bg-background-1">
+ <div className="flex items-center gap-2 border-b border-border px-3 py-2 text-[11.5px] text-foreground-passive">
+ <span className="min-w-0 flex-1 truncate font-mono">{slug}.template.yaml</span>
+ <span className="shrink-0">
+ {loaded.server ? 'Stored exactly as uploaded' : 'Bundled with the Console'}
+ </span>
+ <CopyButton text={loaded.document} />
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ disabled={busy !== null}
+ onClick={() => void exportYaml()}
+ >
+ <Download className="size-3.5" />
+ Export YAML
+ </Button>
+ </div>
+ <pre className="overflow-x-auto p-3 font-mono text-xs leading-relaxed whitespace-pre-wrap text-foreground-muted">
+ {loaded.document}
+ </pre>
+ </div>
+ )}
+ </section>
+ </div>
+ </div>
+ );
+});
+
+export const templateDetailView = {
+ WrapView: ({ children }: { children: React.ReactNode; serverId: string; templateId: string }) => (
+ <>{children}</>
+ ),
+ TitlebarSlot: TemplateDetailTitlebar,
+ MainPanel: TemplateDetailPanel,
+ canActivate: (params: unknown): GuardResult => {
+ const p =
+ typeof params === 'object' && params !== null ? (params as Record<string, unknown>) : {};
+ if (typeof p.serverId !== 'string' || typeof p.templateId !== 'string') {
+ return { ok: false, redirect: 'home' };
+ }
+ return { ok: true };
+ },
+} satisfies ViewDefinition<{ serverId: string; templateId: string }>;
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.tsx
new file mode 100644
index 000000000..632687d32
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx
@@ -0,0 +1,1744 @@
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { FileText, Loader2 } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import type {
+ FormOptions,
+ ParsedAgentEntry,
+ TemplateKind,
+} from '@main/core/agent-templates/template-document';
+import type { AgentTemplateOrigin } from '@main/core/agents/agent-config-file';
+import type { ParamSpec, ParsedTemplate } from '@main/core/room-templates/controller';
+import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';
+import { AgentTypePicker } from '@renderer/features/locations/components/add-agent-modal/agent-type-picker';
+import { agentsStore } from '@renderer/features/locations/stores/agents-store';
+import { HostReachabilityNotice } from '@renderer/features/remote-hosts/host-reachability-notice';
+import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
+import {
+ HostReadinessNotice,
+ useRemoteHostReadiness,
+} from '@renderer/features/remote-hosts/host-readiness-notice';
+import { blockedHandoffs } from '@renderer/features/room-templates/agent-handoff';
+import {
+ AgentListField,
+ type EntityLists,
+ UserListField,
+} from '@renderer/features/room-templates/entity-fields';
+import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';
+import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';
+import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
+import { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { toast } from '@renderer/lib/hooks/use-toast';
+import { rpc } from '@renderer/lib/ipc';
+import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
+import { useModalContext } from '@renderer/lib/modal/modal-provider';
+import { remoteAgentsQueryKey, useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
+import { useAgentTypeAvailability } from '@renderer/lib/stores/use-switch-setup';
+import { Alert, AlertDescription } from '@renderer/lib/ui/alert';
+import { Button } from '@renderer/lib/ui/button';
+import { Switch } from '@renderer/lib/ui/switch';
+import { cn } from '@renderer/utils/utils';
+import { AGENT_NAME_PATTERN, slugifyAgentNamePart } from '@shared/core/agents/agent-slug';
+import {
+ AGENT_PROVIDER_IDS,
+ type AgentProviderId,
+ providerDisplayName,
+} from '@shared/core/providers/agent-provider-registry';
+import { ownerAndMyAgentsPolicy, ownerOnlyPolicy } from '@shared/core/switch-servers/owner-policy';
+import { NEW } from '@shared/core/switch-servers/room-template-params';
+import { RpcError } from '@shared/lib/ipc/rpc-error';
+import { findBundledTemplate } from './bundled-templates';
+import { CollapsibleInput } from './use/collapsible-input';
+import {
+ type AgentSlot,
+ AgentSlotCard,
+ newSlot,
+ ResolvedDocument,
+ RoomCard,
+ SlotDirectoryField,
+ type SlotStatus,
+} from './use/creates-rail';
+import { CreatingScreen } from './use/creating-screen';
+import { ParamField } from './use/param-field';
+import { RoomChoiceField } from './use/room-pick-field';
+import { LOCAL_RUN_LOCATION, runLocationLabel, useAllowedHosts } from './use/run-location-select';
+import {
+ agentCreateSteps,
+ bridgeCandidates,
+ type CreateStep,
+ createStepStatus,
+ defaultsFor,
+ hasPlaceholder,
+ interpolate,
+ isChain,
+ isEmpty,
+ missingParams,
+ paramLabel,
+ placeholdersIn,
+ resolveChain,
+ sectionOf,
+ serverInputs,
+ type Values,
+ valueProblem,
+} from './use/use-template-model';
+
+type Params = {
+ serverId: string;
+ /** A workspace template id or bundled template id to load. */
+ templateId?: string;
+ /** A document to use instead of a stored template: pasted, dropped, or a recent. */
+ yamlText?: string;
+ sourceName?: string;
+ /** Add the created agent to this room instead of creating the template's room. */
+ intoRoomId?: string;
+};
+
+function useViewParams(): Params {
+ return useParams('templateUse').params as Params;
+}
+
+/** A template loaded for the Use page: its document, its origin, and everything parsed from it. */
+type UsePageTemplate = {
+ name: string;
+ yamlText: string;
+ instructions: string | null;
+ origin: AgentTemplateOrigin | null;
+ kind: TemplateKind;
+ agents: ParsedAgentEntry[];
+ /** True for the singular `agent:` form, whose room refers to the agent as `{agent}`. */
+ singular: boolean;
+ /** Every declared param, the Console types included. */
+ params: ParamSpec[];
+ /** The names of the params the server document keeps. */
+ serverParamNames: Set<string>;
+ form: FormOptions;
+ parsed: ParsedTemplate | null;
+ coreYaml: string | null;
+ warnings: string[];
+};
+
+async function loadUsePageTemplate(serverId: string, params: Params): Promise<UsePageTemplate> {
+ let name: string;
+ let yamlText: string;
+ let instructions: string | null = null;
+ let origin: AgentTemplateOrigin | null = null;
+ if (params.templateId) {
+ const bundled = findBundledTemplate(params.templateId);
+ if (bundled) {
+ name = bundled.name;
+ yamlText = bundled.yamlText;
+ instructions = bundled.instructions;
+ origin = { id: bundled.id, name: bundled.name, source: 'bundled' };
+ } else {
+ const detail = await rpc.switchServers.getTemplateDetail({
+ serverId,
+ templateId: params.templateId,
+ });
+ name = detail.name;
+ yamlText = detail.definition;
+ origin = { id: detail.id, name: detail.name, source: 'server', serverId };
+ }
+ } else if (params.yamlText) {
+ name = params.sourceName?.replace(/(\.template)?\.ya?ml$/i, '') ?? 'Pasted template';
+ yamlText = params.yamlText;
+ } else {
+ throw new Error('Nothing to use: no template was given.');
+ }
+ const kind = await rpc.agentTemplates.kind({ yamlText });
+ const { agents, singular, warnings } = await rpc.agentTemplates.parseAgents({
+ yamlText,
+ instructions,
+ });
+ // Two versions of the room document: one that keeps every param, for
+ // building the form, and one with only what the server understands.
+ const forForm = await rpc.agentTemplates.serverDocument({ yamlText, keepConsoleParams: true });
+ const coreYaml = await rpc.agentTemplates.serverDocument({ yamlText });
+ // Without the schema the form is built from the Console's own parse and
+ // the server validates on create, so an older server without the schema
+ // endpoint still gets a working page.
+ const schema = await rpc.switchServers.fetchTemplateSchema(serverId).catch(() => null);
+ const parsed = forForm
+ ? await rpc.roomTemplates.parse({ yamlText: forForm, schema: schema ?? undefined })
+ : null;
+ // A document without rooms can still declare params, used in agent names.
+ const declaredParams = parsed?.params ?? (await rpc.roomTemplates.params({ yamlText }));
+ const serverParams = coreYaml ? await rpc.roomTemplates.params({ yamlText: coreYaml }) : [];
+ const form = await rpc.agentTemplates.form({ yamlText });
+ return {
+ name,
+ yamlText,
+ instructions,
+ origin,
+ kind,
+ agents,
+ singular,
+ params: declaredParams,
+ serverParamNames: new Set(serverParams.map((p) => p.name)),
+ form,
+ parsed,
+ coreYaml,
+ warnings: [...warnings, ...(parsed?.warnings ?? [])],
+ };
+}
+
+const TemplateUseTitlebar = observer(function TemplateUseTitlebar() {
+ const { serverId } = useViewParams();
+ const { navigate } = useNavigate();
+ return (
+ <ServerSectionTitlebar
+ serverId={serverId}
+ icon={FileText}
+ label="Templates"
+ item={{ label: 'Use template' }}
+ onSectionClick={() => navigate('templates', { serverId })}
+ />
+ );
+});
+
+function SectionTitle({ title, hint }: { title: string; hint?: string }) {
+ return (
+ <div className="flex flex-col gap-1">
+ <h3 className="text-sm font-semibold text-foreground">{title}</h3>
+ {hint && <p className="text-[12.5px] leading-relaxed text-foreground-muted">{hint}</p>}
+ </div>
+ );
+}
+
+/** A value the template fixed: shown so nothing is hidden, not editable. */
+function FixedRow({ label, value }: { label: string; value: string }) {
+ return (
+ <div className="flex items-center gap-3 rounded-[10px] border border-dashed border-border px-3 py-2.5">
+ <span className="w-[104px] shrink-0 truncate text-[12.5px] font-medium">{label}</span>
+ <span className="min-w-0 flex-1 truncate font-mono text-[12.5px] text-foreground-muted">
+ {value}
+ </span>
+ <span className="shrink-0 text-[11px] text-foreground-passive">Set by the template</span>
+ </div>
+ );
+}
+
+/** Everything the page has worked out about one agent entry from the inputs. */
+type SlotSetup = {
+ /** The identifier the agent is created under. */
+ name: string;
+ displayName: string | null;
+ provider: AgentProviderId | null;
+ /** `local`, or an SSH host. */
+ location: string;
+ directory: string;
+ /** Rooms the agent joins once it exists, by name. */
+ joins: string[];
+ /** Whether the run creates the template's room for it. */
+ makesRoom: boolean;
+};
+
+const TemplateUsePanel = observer(function TemplateUsePanel() {
+ const params = useViewParams();
+ const { serverId, intoRoomId = null } = params;
+ const { navigate } = useNavigate();
+ const { showModal } = useModalContext();
+ const queryClient = useQueryClient();
+ const [loaded, setLoaded] = useState<UsePageTemplate | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [values, setValues] = useState<Values>({});
+ const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
+ const [slots, setSlots] = useState<AgentSlot[]>([]);
+ const [editedAgents, setEditedAgents] = useState<string[]>([]);
+ const [editedUsers, setEditedUsers] = useState<string[]>([]);
+ // The provider for agents whose template names none and declares no
+ // `provider` param: asked on the page, never chosen for the deployer.
+ const [pickedProvider, setPickedProvider] = useState<AgentProviderId | null>(null);
+ const [phase, setPhase] = useState<'form' | 'creating' | 'done' | 'failed'>('form');
+ const [doneDetail, setDoneDetail] = useState<string | null>(null);
+ // What the server returned for the room, kept so that a step failing after
+ // it does not make Retry create the room a second time.
+ const createdRoom = useRef<Awaited<
+ ReturnType<typeof rpc.switchServers.createRoomFromTemplate>
+ > | null>(null);
+ const [roomStatus, setRoomStatus] = useState<SlotStatus>('idle');
+ const [createError, setCreateError] = useState<string | null>(null);
+ // Advanced inputs the deployer opened, by param name or row key.
+ const [opened, setOpened] = useState<ReadonlySet<string>>(new Set());
+ // For a template whose agent joins a `room` param: whether the deployer
+ // wants a room at all, and whether they are choosing one right now.
+ const [roomOn, setRoomOn] = useState(false);
+ const [pickingRoom, setPickingRoom] = useState(false);
+ const open = (key: string) => setOpened((prev) => new Set(prev).add(key));
+ // Chains decided once their candidates are known, so a value the deployer
+ // clears is not filled in again.
+ const chainDecided = useRef(new Set<string>());
+ // The directory agents are kept under, per location, for `{$agents_dir}`.
+ const [agentsDirs, setAgentsDirs] = useState<Record<string, string>>({});
+
+ // Reload only when a different document is requested. Reloading on every
+ // render would reset the form.
+ const { templateId, yamlText: givenYaml, sourceName } = params;
+ useEffect(() => {
+ let cancelled = false;
+ setLoaded(null);
+ setLoadError(null);
+ loadUsePageTemplate(serverId, { serverId, templateId, yamlText: givenYaml, sourceName })
+ .then((result) => {
+ if (cancelled) return;
+ setLoaded(result);
+ const formParams = result.params.filter((p) => !(result.singular && p.name === 'agent'));
+ setValues(defaultsFor(formParams));
+ chainDecided.current = new Set();
+ createdRoom.current = null;
+ setOpened(new Set());
+ setRoomOn(false);
+ setPickingRoom(false);
+ nameStepped.current = false;
+ setPickedProvider(null);
+ setSlots(result.agents.map(newSlot));
+ // The editable member list holds the room's fixed agents that the template
+ // does not create. Agents it creates have their own cards.
+ const slotNames = new Set(result.agents.map((a) => a.name ?? ''));
+ setEditedAgents((result.parsed?.hardcodedAgents ?? []).filter((a) => !slotNames.has(a)));
+ setEditedUsers(result.parsed?.hardcodedUsers ?? []);
+ })
+ .catch((e: unknown) => {
+ if (!cancelled) setLoadError(failureText(e, 'Could not load this template.'));
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [serverId, templateId, givenYaml, sourceName]);
+
+ const parsed = loaded?.parsed ?? null;
+ // In the singular `agent:` form the room refers to the agent as `{agent}`.
+ // The page fills that in with the agent's name, so it is not an input.
+ const templateParams = useMemo(
+ () => (loaded?.params ?? []).filter((p) => !(loaded?.singular && p.name === 'agent')),
+ [loaded]
+ );
+ const createsAgents = (loaded?.agents.length ?? 0) > 0;
+ const hasRoomPart = loaded?.coreYaml !== null && parsed !== null && !intoRoomId;
+ const isGroupDoc = (parsed?.rooms.length ?? 0) > 1 || (parsed?.groupName ?? null) !== null;
+ const templateRoom = parsed?.rooms[0] ?? null;
+
+ // ── Which section each param belongs to ─────────────────────────────────
+ const agentTexts = useMemo(
+ () =>
+ (loaded?.agents ?? []).map((a) => [
+ a.name ?? '',
+ a.displayName ?? '',
+ a.provider ?? '',
+ a.location ?? '',
+ a.directory ?? '',
+ ...a.join,
+ ]),
+ [loaded]
+ );
+ const roomText = loaded?.coreYaml ?? '';
+ const sections = useMemo(
+ () => new Map(templateParams.map((p) => [p.name, sectionOf(p, agentTexts, roomText)])),
+ [templateParams, agentTexts, roomText]
+ );
+ const paramsOfAgent = (i: number) =>
+ templateParams.filter((p) => {
+ const s = sections.get(p.name);
+ return s?.section === 'agent' && s.index === i;
+ });
+ const roomParams = templateParams.filter((p) => sections.get(p.name)?.section === 'room');
+ // The `room` param an agent joins, when the template leaves the room to the deployer.
+ const joinParam =
+ templateParams.find(
+ (p) => p.type === 'room' && (loaded?.agents ?? []).some((a) => a.join.includes(`{${p.name}}`))
+ ) ?? null;
+ const joinValue = joinParam ? String(values[joinParam.name] ?? '') : '';
+ // A chain that resolved to a room switches the room on.
+ useEffect(() => {
+ if (joinValue !== '' && !roomOn) setRoomOn(true);
+ }, [joinValue, roomOn]);
+ // A Console-type param no agent entry binds applies to every agent.
+ const unboundOfType = (type: ParamSpec['type']) =>
+ templateParams.find(
+ (p) =>
+ p.type === type && !agentTexts.some((texts) => texts.some((t) => t.includes(`{${p.name}}`)))
+ ) ?? null;
+ const providerParam = unboundOfType('provider');
+ const locationParam = unboundOfType('location');
+ const directoryParam = unboundOfType('directory');
+
+ // ── Server lists (pickers, identities, bridges) ─────────────────────────
+ const agents = useRemoteAgents(serverId);
+ const roomsQuery = useQuery({
+ queryKey: ['remote-rooms', serverId],
+ queryFn: () => rpc.switchServers.listRemoteRooms(serverId),
+ });
+ const bridgesQuery = useQuery({
+ queryKey: ['remote-bridges', serverId],
+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId),
+ });
+ const knownUsersQuery = useQuery({
+ queryKey: ['remote-external-users', serverId],
+ queryFn: () => rpc.switchServers.listRemoteExternalUsers(serverId),
+ });
+ const { identities, refresh: refreshIdentities } = useMyIdentities(serverId);
+ const bridges = useMemo(() => bridgesQuery.data ?? [], [bridgesQuery.data]);
+ const allowedHosts = useAllowedHosts(serverId);
+
+ // The messaging app the room is created on: the bridge param's value if
+ // there is one, else the bridge named in the template, else the server's default.
+ const templateBridge = useMemo(() => {
+ const bridgeParam = templateParams.find((p) => p.type === 'bridge');
+ const picked = bridgeParam ? String(values[bridgeParam.name] ?? '') : '';
+ const named = picked !== '' ? picked : (parsed?.bridge ?? null);
+ if (named) return bridges.find((b) => b.displayName === named) ?? null;
+ return bridges.find((b) => b.isDefault) ?? null;
+ }, [bridges, parsed, templateParams, values]);
+ const creatorIdentity = useMemo(() => {
+ if (identities === null) return null;
+ if (templateBridge) {
+ return identities.find((i) => i.bridgeId === templateBridge.id)?.externalUsername ?? null;
+ }
+ return identities[0]?.externalUsername ?? null;
+ }, [identities, templateBridge]);
+ // A linked account is needed only when the room is on a messaging app. On
+ // a server without one, the server uses the deployer's gateway name.
+ const creatorBlocked =
+ parsed?.usesCreator === true &&
+ templateBridge !== null &&
+ identities !== null &&
+ creatorIdentity === null;
+ const linkAccount = templateBridge
+ ? () =>
+ showModal('claimIdentityModal', {
+ serverId,
+ bridgeId: templateBridge.id,
+ onSuccess: () => refreshIdentities(),
+ })
+ : null;
+ const noMessagingApp = parsed !== null && bridgesQuery.data !== undefined && bridges.length === 0;
+
+ const lists = useMemo(
+ (): EntityLists => ({
+ serverId,
+ agents: agents.data ?? [],
+ agentsLoading: agents.isLoading,
+ rooms: roomsQuery.data ?? [],
+ roomsLoading: roomsQuery.isLoading,
+ bridges,
+ identities,
+ knownUsers: knownUsersQuery.data ?? [],
+ bridgeId: templateBridge?.id ?? null,
+ }),
+ [
+ serverId,
+ agents.data,
+ agents.isLoading,
+ roomsQuery.data,
+ roomsQuery.isLoading,
+ bridges,
+ identities,
+ knownUsersQuery.data,
+ templateBridge,
+ ]
+ );
+
+ // ── The agents: what each is made of, from the inputs ───────────────────
+ const setups: SlotSetup[] = useMemo(() => {
+ const roomJoinParam = (entry: ParsedAgentEntry) =>
+ templateParams.find((p) => p.type === 'room' && entry.join.includes(`{${p.name}}`)) ?? null;
+ return slots.map((slot) => {
+ const entry = slot.entry;
+ const name = entry.name
+ ? interpolate(entry.name, values)
+ : slugifyAgentNamePart(interpolate(entry.displayName ?? '', values));
+ const displayName = entry.displayName ? interpolate(entry.displayName, values) : null;
+ const providerText = entry.provider
+ ? interpolate(entry.provider, values)
+ : providerParam
+ ? String(values[providerParam.name] ?? '')
+ : (pickedProvider ?? '');
+ const provider = (AGENT_PROVIDER_IDS as readonly string[]).includes(providerText)
+ ? (providerText as AgentProviderId)
+ : null;
+ const locationText = entry.location
+ ? interpolate(entry.location, values)
+ : locationParam
+ ? String(values[locationParam.name] ?? '')
+ : LOCAL_RUN_LOCATION;
+ const location = locationText === '' ? LOCAL_RUN_LOCATION : locationText;
+ const agentsDir = agentsDirs[location] ?? '';
+ const dirValues: Values = { ...values, agent: name, $agents_dir: agentsDir };
+ // A directory read from a param is interpolated twice: once to reach
+ // the param's value, once for the `{$agents_dir}` and `{agent}` inside it.
+ const directory = slot.dirPicked
+ ? slot.dir
+ : entry.directory
+ ? interpolate(interpolate(entry.directory, dirValues), dirValues)
+ : directoryParam
+ ? interpolate(String(values[directoryParam.name] ?? ''), dirValues)
+ : agentsDir && name && !hasPlaceholder(name)
+ ? `${agentsDir}/${name}`
+ : '';
+ const joinParam = roomJoinParam(entry);
+ const joins = entry.join
+ .map((j) => interpolate(j, values))
+ .filter((j) => j !== '' && j !== NEW && !hasPlaceholder(j));
+ const makesRoom =
+ hasRoomPart && (joinParam === null ? true : String(values[joinParam.name] ?? '') === NEW);
+ return { name, displayName, provider, location, directory, joins, makesRoom };
+ });
+ }, [
+ slots,
+ values,
+ templateParams,
+ providerParam,
+ locationParam,
+ directoryParam,
+ pickedProvider,
+ agentsDirs,
+ hasRoomPart,
+ ]);
+ // A room template with no agents still makes its room.
+ const makesRoom = hasRoomPart && (setups.length === 0 || setups.some((s) => s.makesRoom));
+ const locations = useMemo(() => [...new Set(setups.map((s) => s.location))], [setups]);
+ const firstRemote = locations.find((l) => l !== LOCAL_RUN_LOCATION) ?? null;
+ const hostReachable = locations.every(
+ (l) => l === LOCAL_RUN_LOCATION || !hostReachabilityStore.isBlocked(l)
+ );
+ const hostReadiness = useRemoteHostReadiness(
+ firstRemote,
+ setups.find((s) => s.location === firstRemote)?.provider ?? null
+ );
+ const hostReady = firstRemote === null || (!hostReadiness.blocked && !hostReadiness.checking);
+ // A location the server does not allow falls back to this computer.
+ useEffect(() => {
+ if (!locationParam) return;
+ const v = String(values[locationParam.name] ?? '');
+ if (v !== '' && v !== LOCAL_RUN_LOCATION && !allowedHosts.some((h) => h.sshHost === v)) {
+ setValues((prev) => ({ ...prev, [locationParam.name]: LOCAL_RUN_LOCATION }));
+ }
+ }, [allowedHosts, locationParam, values]);
+
+ // `{$agents_dir}` for every location in play, fetched once each.
+ useEffect(() => {
+ for (const location of locations) {
+ if (agentsDirs[location] !== undefined) continue;
+ const sshHost = location === LOCAL_RUN_LOCATION ? null : location;
+ if (sshHost && hostReachabilityStore.isBlocked(sshHost)) continue;
+ void rpc.agentTemplates
+ .agentsDirectory({ sshHost })
+ .then((dir) => setAgentsDirs((prev) => ({ ...prev, [location]: dir })))
+ .catch(() => {});
+ }
+ }, [locations, agentsDirs]);
+
+ // ── Chains: each decided once its candidates are known ──────────────────
+ const availability = useAgentTypeAvailability(firstRemote ?? undefined);
+ const localAvailability = useAgentTypeAvailability(undefined);
+ useEffect(() => {
+ if (!loaded) return;
+ for (const param of templateParams) {
+ if (!isChain(param) || chainDecided.current.has(param.name)) continue;
+ let candidates: string[] | undefined;
+ if (param.type === 'bridge') {
+ candidates = bridgesQuery.data && bridgeCandidates(bridgesQuery.data);
+ } else if (param.type === 'agent') {
+ candidates = agents.data?.map((a) => a.name).sort();
+ } else if (param.type === 'room') {
+ candidates = roomsQuery.data?.map((r) => r.name).sort();
+ } else if (param.type === 'location') {
+ candidates = [LOCAL_RUN_LOCATION, ...allowedHosts.map((h) => h.sshHost)];
+ } else if (param.type === 'provider') {
+ // The providers installed where the agent reading this param runs.
+ const section = sections.get(param.name);
+ const at = section?.section === 'agent' ? setups[section.index] : undefined;
+ const list =
+ at && at.location !== LOCAL_RUN_LOCATION ? availability.data : localAvailability.data;
+ candidates = list
+ ?.filter(
+ (a) => a.available && (AGENT_PROVIDER_IDS as readonly string[]).includes(a.agentId)
+ )
+ .map((a) => a.agentId);
+ }
+ if (candidates === undefined) continue; // the list is still loading
+ chainDecided.current.add(param.name);
+ const choice = resolveChain(param, candidates, hasRoomPart);
+ if (choice === null) continue;
+ setValues((prev) => (isEmpty(prev[param.name]) ? { ...prev, [param.name]: choice } : prev));
+ }
+ }, [
+ loaded,
+ templateParams,
+ sections,
+ setups,
+ hasRoomPart,
+ bridgesQuery.data,
+ agents.data,
+ roomsQuery.data,
+ allowedHosts,
+ availability.data,
+ localAvailability.data,
+ ]);
+
+ // ── Names: taken, invalid, or still unresolved ──────────────────────────
+ const takenNames = useMemo(() => new Set((agents.data ?? []).map((a) => a.name)), [agents.data]);
+ // The param an agent entry takes its name from, when it takes it from one.
+ const nameParamOf = useCallback(
+ (entry: ParsedAgentEntry): ParamSpec | null => {
+ const source = entry.name ?? entry.displayName ?? '';
+ const key = placeholdersIn(source)[0];
+ return key ? (templateParams.find((p) => p.name === key) ?? null) : null;
+ },
+ [templateParams]
+ );
+ // The template's default name steps to the first free one, "Switch expert
+ // 2", before the deployer sees it, so a second agent from the same
+ // template does not start out clashing. Decided once per load, and only
+ // while the field still holds the template's default.
+ const nameStepped = useRef(false);
+ useEffect(() => {
+ if (!loaded || !agents.data || nameStepped.current) return;
+ nameStepped.current = true;
+ const used = new Set(takenNames);
+ const next: Values = {};
+ for (const entry of loaded.agents) {
+ const param = nameParamOf(entry);
+ if (!param || typeof param.default !== 'string') continue;
+ const current = String(values[param.name] ?? '');
+ if (current !== param.default) continue;
+ const identifierFor = (text: string) =>
+ entry.name
+ ? interpolate(entry.name, { ...values, [param.name]: text })
+ : slugifyAgentNamePart(text);
+ let candidate = param.default;
+ for (let n = 2; used.has(identifierFor(candidate)); n++) candidate = `${param.default} ${n}`;
+ used.add(identifierFor(candidate));
+ if (candidate !== current) next[param.name] = candidate;
+ }
+ if (Object.keys(next).length > 0) setValues((prev) => ({ ...prev, ...next }));
+ }, [loaded, agents.data, takenNames, nameParamOf, values]);
+
+ // ── Why Create is disabled ──────────────────────────────────────────────
+ // A room's own params matter only when the room is made.
+ const liveParams = templateParams.filter(
+ (p) =>
+ makesRoom || joinParam === null || p === joinParam || sections.get(p.name)?.section !== 'room'
+ );
+ const missing = missingParams(liveParams, values);
+ const invalid = liveParams
+ .map((p) => ({ p, problem: valueProblem(p, values[p.name] ?? '') }))
+ .filter((x) => x.problem !== null);
+ const slotProblems: string[] = [];
+ // A clash on a name the deployer can edit is shown in red under its field.
+ const clashErrors: Record<string, string> = {};
+ const seenNames = new Set<string>();
+ slots.forEach((slot, i) => {
+ const setup = setups[i];
+ if (slot.mode === 'existing') {
+ if (slot.existingName === '')
+ slotProblems.push(`Pick the existing agent for ${setup.name || `agent ${i + 1}`}.`);
+ return;
+ }
+ const name = slot.createdName ?? setup.name;
+ if (name === '') {
+ slotProblems.push('Give the agent a name.');
+ return;
+ }
+ if (hasPlaceholder(name)) {
+ slotProblems.push(`Fill in ${placeholdersIn(name).join(', ')} to name the agent.`);
+ return;
+ }
+ if (!AGENT_NAME_PATTERN.test(name)) {
+ slotProblems.push(
+ `${name} is not a valid agent name: lowercase letters, digits, . - _, starting with a letter or digit.`
+ );
+ } else if (slot.createdName === null && (takenNames.has(name) || seenNames.has(name))) {
+ const message = `An agent called ${name} already exists on this server. Change the name.`;
+ slotProblems.push(message);
+ const param = nameParamOf(slot.entry);
+ if (param) clashErrors[param.name] = message;
+ }
+ seenNames.add(name);
+ if (!setup.provider) slotProblems.push(`Choose which coding agent runs ${name}.`);
+ if (setup.directory.trim() === '') slotProblems.push(`Choose a directory for ${name}.`);
+ for (const room of setup.joins) {
+ if (roomsQuery.data && !roomsQuery.data.some((r) => r.name === room))
+ slotProblems.push(`There is no room called ${room} on this server.`);
+ }
+ });
+ if (joinParam && roomOn && joinValue === '')
+ slotProblems.push('Pick the room, or switch it off.');
+ const newSlots = slots.filter((s) => s.mode === 'new');
+ const remoteLabel = firstRemote ? runLocationLabel(firstRemote, allowedHosts) : '';
+ const blockedReason: string | null =
+ phase !== 'form'
+ ? null
+ : loaded === null
+ ? 'Loading…'
+ : missing.length > 0
+ ? `Fill in ${missing.map(paramLabel).join(', ')}`
+ : invalid.length > 0
+ ? `${paramLabel(invalid[0].p)}: ${invalid[0].problem}`
+ : slotProblems.length > 0
+ ? slotProblems[0]
+ : newSlots.length > 0 && !hostReachable
+ ? `${remoteLabel} cannot be reached right now.`
+ : newSlots.length > 0 && !hostReady
+ ? hostReadiness.checking
+ ? `Checking what ${remoteLabel} has installed…`
+ : `${remoteLabel} is missing setup the agents need.`
+ : !makesRoom
+ ? null // no room is made, so nothing below applies
+ : creatorBlocked
+ ? 'Link your messaging account first.'
+ : parsed !== null && noMessagingApp && parsed.usesCreator
+ ? 'This server has no messaging app, so the room would have no chat.'
+ : null;
+ const stillNeeded =
+ missing.length > 0
+ ? `${missing.length} input${missing.length === 1 ? '' : 's'} still needed`
+ : slotProblems.length > 0 || invalid.length > 0
+ ? `${slotProblems.length + invalid.length} thing${slotProblems.length + invalid.length === 1 ? '' : 's'} to settle`
+ : 'Every input filled in';
+
+ // Existing agents in the room whose addressing policy blocks messages from
+ // another member. New agents get the template's addressing at creation.
+ const handoffBlocked = useMemo(() => {
+ if (!parsed) return [];
+ const names = new Set<string>(editedAgents);
+ for (const param of templateParams) {
+ if (param.type === 'agent') {
+ const v = values[param.name];
+ if (typeof v === 'string' && v !== '') names.add(v);
+ }
+ }
+ for (const slot of slots)
+ if (slot.mode === 'existing' && slot.existingName) names.add(slot.existingName);
+ return blockedHandoffs((agents.data ?? []).filter((a) => names.has(a.name)));
+ }, [parsed, editedAgents, templateParams, values, slots, agents.data]);
+ const [allowingHandoffs, setAllowingHandoffs] = useState(false);
+ const allowHandoffs = useCallback(async () => {
+ const byName = new Map((agents.data ?? []).map((a) => [a.name, a]));
+ setAllowingHandoffs(true);
+ try {
+ for (const targetName of new Set(handoffBlocked.map((b) => b.to))) {
+ const target = byName.get(targetName);
+ if (!target) continue;
+ const sources = handoffBlocked
+ .filter((b) => b.to === targetName)
+ .map((b) => byName.get(b.from))
+ .filter((a): a is NonNullable<typeof a> => a !== undefined);
+ const rules = (target.addressingPolicy?.rules ?? []).map((rule) => {
+ const next = { ...rule };
+ for (const source of sources) {
+ if (target.ownerId !== null && source.ownerId === target.ownerId) {
+ next.owner_agents = true;
+ } else if (next.agents !== '*' && !next.agents.includes(source.id)) {
+ next.agents = [...next.agents, source.id];
+ }
+ }
+ return next;
+ });
+ await rpc.switchServers.updateAddressingPolicy({
+ serverId,
+ agentId: target.id,
+ policy: { rules },
+ });
+ }
+ await queryClient.invalidateQueries({ queryKey: remoteAgentsQueryKey(serverId) });
+ } catch (e) {
+ toast({ title: failureText(e, 'Could not update the agents.'), variant: 'destructive' });
+ } finally {
+ setAllowingHandoffs(false);
+ }
+ }, [agents.data, handoffBlocked, serverId, queryClient]);
+
+ // ── Create ──────────────────────────────────────────────────────────────
+ const setSlot = (i: number, patch: Partial<AgentSlot>) =>
+ setSlots((prev) => prev.map((s, j) => (j === i ? { ...s, ...patch } : s)));
+
+ const createAll = async () => {
+ if (!loaded || blockedReason !== null) return;
+ setPhase('creating');
+ setCreateError(null);
+ setFieldErrors({});
+ const created: { slotIndex: number; name: string; switchAgentId: string | null }[] = [];
+
+ for (let i = 0; i < slots.length; i++) {
+ const slot = slots[i];
+ const setup = setups[i];
+ if (slot.mode !== 'new' || slot.status === 'created') continue;
+ const name = slot.createdName ?? setup.name;
+ const providerId = setup.provider;
+ if (!providerId) continue;
+ const sshHost = setup.location === LOCAL_RUN_LOCATION ? null : setup.location;
+ setSlot(i, { status: 'creating', error: null, step: 'prepare' });
+ try {
+ // An agent created on an earlier attempt is not created again; only its policy is set.
+ let switchAgentId = slot.createdSwitchAgentId;
+ if (!switchAgentId) {
+ const prepared = await rpc.agentTemplates.prepareWorkspace({
+ dir: setup.directory.trim(),
+ repoUrl: slot.cloneRepo ? slot.entry.repoUrl : null,
+ sshHost,
+ });
+ if (prepared.repo?.outcome === 'failed') {
+ setSlot(i, {
+ cloneWarning: `The repository could not be cloned (${prepared.repo.error ?? 'git clone failed'}). The agent clones it on its first run.`,
+ });
+ toast({
+ title: `Could not fetch the repository for ${name}`,
+ description: `${prepared.repo.error ?? 'git clone failed'}. The agent will try to clone it itself on its first run.`,
+ variant: 'destructive',
+ });
+ }
+ setSlot(i, { step: 'create' });
+ const result = await rpc.agents.addAgent({
+ sshHost,
+ dir: setup.directory.trim(),
+ name,
+ providerId,
+ serverId,
+ description: slot.entry.description,
+ displayName:
+ setup.displayName && setup.displayName.trim() !== name
+ ? setup.displayName.trim()
+ : null,
+ iconUrl: null,
+ autoSession: true,
+ // Nobody sits at a host's terminal to approve tool calls.
+ autoApprove: sshHost !== null,
+ instructions: slot.entry.instructions,
+ definitionAttributes: {},
+ providerConfig: null,
+ entryPoint: 'server_page',
+ // Only a single-agent template can be loaded again for this
+ // agent's instructions; a team template has no one entry to offer.
+ templateOrigin: loaded.singular ? loaded.origin : null,
+ });
+ if (result.kind !== 'created') {
+ setSlot(i, { status: 'failed', error: provisionErrorText(result) });
+ setPhase('failed');
+ return;
+ }
+ switchAgentId = result.agent.switchAgentId ?? null;
+ // Record the created agent before setting its policy, so a retry after a
+ // policy failure does not create a second agent.
+ setSlot(i, { createdName: result.agent.name, createdSwitchAgentId: switchAgentId });
+ }
+ // A new agent answers only its owner by default. The template's `anyone`
+ // must be written as the open policy; leaving the default would keep it closed.
+ if (switchAgentId && slot.entry.addressing) {
+ setSlot(i, { step: 'policy' });
+ await rpc.switchServers.updateAddressingPolicy({
+ serverId,
+ agentId: switchAgentId,
+ policy:
+ slot.entry.addressing === 'owner-agents'
+ ? ownerAndMyAgentsPolicy()
+ : slot.entry.addressing === 'owner'
+ ? ownerOnlyPolicy()
+ : null,
+ });
+ }
+ created.push({ slotIndex: i, name, switchAgentId });
+ setSlot(i, { status: 'created' });
+ } catch (e) {
+ setSlot(i, { status: 'failed', error: failureText(e, 'Could not create the agent.') });
+ setPhase('failed');
+ return;
+ }
+ }
+ if (created.length > 0) {
+ // The agents exist whether or not the lists refresh, so a refresh that
+ // fails must not fail the run.
+ await agentsStore.load().catch(() => {});
+ await queryClient
+ .invalidateQueries({ queryKey: remoteAgentsQueryKey(serverId) })
+ .catch(() => {});
+ }
+ // A recent is used again from its own text, so a bundled template whose
+ // instructions live in a separate file is stored with them inlined.
+ void (async () => {
+ const yamlText = loaded.instructions
+ ? await rpc.agentTemplates.compose({
+ yamlText: loaded.yamlText,
+ instructions: loaded.instructions,
+ })
+ : loaded.yamlText;
+ await rpc.roomTemplates.saveRecent({ serverId, name: loaded.name, yamlText });
+ })().catch(() => {});
+
+ // Rooms the agents join: the one this page was opened from, and the ones
+ // the template names for each agent.
+ const byRoomName = new Map((roomsQuery.data ?? []).map((r) => [r.name, r.id]));
+ const byAgentName = new Map((agents.data ?? []).map((a) => [a.name, a.id]));
+ const joinsByRoom = new Map<string, string[]>();
+ // Agents the server did not register cannot be put in a room; the run
+ // stops and says so rather than opening the room without them.
+ const missingJoin: string[] = [];
+ slots.forEach((slot, i) => {
+ const agentId =
+ slot.mode === 'existing'
+ ? (byAgentName.get(slot.existingName) ?? null)
+ : (slot.createdSwitchAgentId ??
+ created.find((c) => c.slotIndex === i)?.switchAgentId ??
+ null);
+ if (!agentId) {
+ if (intoRoomId || setups[i].joins.length > 0)
+ missingJoin.push(slot.createdName ?? setups[i].name);
+ return;
+ }
+ const roomIds = [
+ ...(intoRoomId ? [intoRoomId] : []),
+ ...setups[i].joins.map((r) => byRoomName.get(r)).filter((id): id is string => !!id),
+ ];
+ for (const roomId of roomIds) {
+ joinsByRoom.set(roomId, [...(joinsByRoom.get(roomId) ?? []), agentId]);
+ }
+ });
+ if (missingJoin.length > 0) {
+ setRoomStatus('failed');
+ setCreateError(
+ `${missingJoin.join(', ')} ${missingJoin.length === 1 ? 'was' : 'were'} created but the server has not registered ${missingJoin.length === 1 ? 'it' : 'them'} yet, so ${missingJoin.length === 1 ? 'it' : 'they'} could not be added to the room. Open the agent and add it to the room from there.`
+ );
+ setPhase('failed');
+ return;
+ }
+ let joinedRoomId: string | null = null;
+ if (joinsByRoom.size > 0) {
+ setRoomStatus('creating');
+ try {
+ for (const [roomId, ids] of joinsByRoom) {
+ await rpc.switchServers.addRoomAgents({
+ serverId,
+ roomId,
+ agentIds: [...new Set(ids)],
+ direction: 'agents_to_room',
+ });
+ joinedRoomId = roomId;
+ }
+ if (!makesRoom) setRoomStatus('created');
+ await refreshSidebarRoomState(true).catch(() => {});
+ } catch (e) {
+ setRoomStatus('failed');
+ setCreateError(
+ failureText(e, 'The agents were created, but could not be added to the room.')
+ );
+ setPhase('failed');
+ return;
+ }
+ }
+
+ if (!makesRoom || !loaded.coreYaml || !parsed) {
+ // No room to make. Every path out of here navigates, so a run that
+ // created nothing new does not stay on the creating screen.
+ if (joinedRoomId) {
+ toast({
+ title: 'In the room',
+ description: 'Mention an agent there to start it. A message from you is what wakes it.',
+ });
+ const roomId = joinedRoomId;
+ finish(`Opening ${switchRoomsStore.roomNameById(roomId) ?? 'the room'}…`, () =>
+ navigate('room', { roomId })
+ );
+ return;
+ }
+ const firstName = created[0]?.name ?? slots.find((s) => s.createdName)?.createdName;
+ const local = firstName
+ ? agentsStore.agentsOnServer(serverId).find((a) => a.name === firstName)
+ : undefined;
+ finish(local ? `Opening ${local.name}…` : 'Opening Your Agents…', () =>
+ local
+ ? navigate('location', { locationId: local.locationId, agentName: local.name })
+ : navigate('serverAgents', { serverId })
+ );
+ return;
+ }
+
+ // Then the rooms. Agent names in the document are replaced with the names
+ // the agents got, so the server finds them.
+ setRoomStatus('creating');
+ try {
+ const replacements: Record<string, string> = {};
+ slots.forEach((slot, i) => {
+ const expression = slot.entry.name ?? '';
+ const actual =
+ slot.mode === 'existing' ? slot.existingName : (slot.createdName ?? setups[i].name);
+ if (expression && actual && expression !== actual) replacements[expression] = actual;
+ });
+ let coreYaml = await rpc.agentTemplates.substituteSlots({
+ coreYaml: loaded.coreYaml,
+ replacements,
+ });
+ if (!isGroupDoc) {
+ // The member lists are rebuilt from the parsed template, so the renamed
+ // agents must be renamed here too, or the original names would come back.
+ const slotNamesSet = new Set(slots.map((s) => s.entry.name ?? ''));
+ const keep = (list: string[]) =>
+ list
+ .filter((a) => hasPlaceholder(a) || slotNamesSet.has(a))
+ .map((a) => replacements[a] ?? a);
+ coreYaml = await rpc.roomTemplates.rewriteYaml({
+ yamlText: coreYaml,
+ agents: [...new Set([...keep(parsed.agents), ...editedAgents])],
+ users: [...keep(parsed.users), ...editedUsers],
+ });
+ }
+ const inputs = serverInputs(templateParams, values, loaded.serverParamNames);
+ if (loaded.singular && slots.length === 1) {
+ // The singular `agent:` form: the server fills `{agent}` from this input.
+ const slot = slots[0];
+ inputs.agent =
+ slot.mode === 'existing' ? slot.existingName : (slot.createdName ?? setups[0].name);
+ }
+ const result =
+ createdRoom.current ??
+ (await rpc.switchServers.createRoomFromTemplate(serverId, coreYaml, inputs));
+ createdRoom.current = result;
+ setRoomStatus('created');
+ // The room exists whether or not the sidebar refreshes.
+ await refreshSidebarRoomState(true).catch(() => {});
+ if (result.kind === 'room') {
+ if (result.failedAttachments.length > 0) {
+ const kickoff = result.failedAttachments.find((f) => f.kind === 'kickoff');
+ const others = result.failedAttachments.filter((f) => f.kind !== 'kickoff');
+ toast({
+ title: kickoff
+ ? `"${result.roomName}" exists, but nobody has spoken in it yet`
+ : `"${result.roomName}" was created with gaps`,
+ description: [
+ kickoff ? `The first message could not be posted: ${kickoff.error}` : null,
+ others.length > 0
+ ? `Could not add: ${others.map((f) => `${f.id} (${f.error})`).join(', ')}`
+ : null,
+ ]
+ .filter(Boolean)
+ .join(' '),
+ variant: 'destructive',
+ });
+ }
+ // Open the room. The kickoff and the agents' answers appear there, and the
+ // agents' sessions appear in the sidebar.
+ finish(`Opening ${result.roomName}…`, () => navigate('room', { roomId: result.roomId }));
+ } else {
+ const gaps = [
+ ...result.errors.map((e) => e.error),
+ ...result.rooms.flatMap((r) =>
+ r.failedAttachments.map((f) => `${r.roomName}: ${f.id} (${f.error})`)
+ ),
+ ];
+ if (gaps.length > 0) {
+ toast({
+ title: `"${result.groupName}" was created with gaps`,
+ description: gaps.join('; '),
+ variant: 'destructive',
+ });
+ } else {
+ toast({
+ title: `"${result.groupName}" is ready`,
+ description: `${result.rooms.length} room${result.rooms.length === 1 ? '' : 's'} created.`,
+ });
+ }
+ const first = result.rooms[0];
+ finish(first ? `Opening ${first.roomName}…` : 'Opening Your Rooms…', () =>
+ first ? navigate('room', { roomId: first.roomId }) : navigate('serverRooms', { serverId })
+ );
+ }
+ } catch (e) {
+ setRoomStatus('failed');
+ const serverDetail =
+ e instanceof RpcError && e.code === 'GatewayError' ? e.stringField('detail') : undefined;
+ const message =
+ serverDetail ?? failureText(e, 'Could not create the room from this template.');
+ const paramMatch = message.match(/param(?:\(s\))?:?\s*['"]?(\w+)/i);
+ if (paramMatch && templateParams.some((p) => p.name === paramMatch[1])) {
+ setFieldErrors({ [paramMatch[1]]: message });
+ open(paramMatch[1]);
+ }
+ setCreateError(
+ created.length > 0
+ ? `The agents were created, but the room could not be: ${message}`
+ : message
+ );
+ setPhase('failed');
+ }
+ };
+
+ // A short finished state before the page moves on, skipped for a deployer
+ // who asked the system for less motion.
+ const finish = (detail: string, go: () => void) => {
+ setDoneDetail(detail);
+ setPhase('done');
+ const still = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ window.setTimeout(go, still ? 0 : 900);
+ };
+
+ // Values for the preview cards: the inputs, `{agent}` for a single-agent
+ // template, and every agent's final name.
+ const railValues: Values =
+ loaded?.singular && setups[0] ? { ...values, agent: setups[0].name || '{agent}' } : values;
+ const railRenames = useMemo(() => {
+ const out: Record<string, string> = {};
+ slots.forEach((slot, i) => {
+ const expression = slot.entry.name ?? '';
+ const actual =
+ slot.mode === 'existing' ? slot.existingName : (slot.createdName ?? setups[i]?.name);
+ if (expression && actual && expression !== actual) out[expression] = actual;
+ });
+ return out;
+ }, [slots, setups]);
+
+ // ── Render ──────────────────────────────────────────────────────────────
+ const partlyDone =
+ slots.some((s) => s.status === 'created' || s.status === 'failed') || roomStatus === 'failed';
+ const roomCount = makesRoom ? (parsed?.rooms.length ?? 0) : 0;
+ const primaryLabel = partlyDone
+ ? 'Retry remaining steps'
+ : intoRoomId
+ ? 'Create and add to room'
+ : createsAgents && roomCount > 0
+ ? slots.length === 1
+ ? 'Create agent and room'
+ : 'Create all'
+ : createsAgents
+ ? slots.length === 1
+ ? 'Create agent'
+ : 'Create agents'
+ : roomCount > 1
+ ? 'Create rooms'
+ : 'Create room';
+ const intoRoomName = intoRoomId ? switchRoomsStore.roomNameById(intoRoomId) : null;
+
+ const cancel = () =>
+ intoRoomId
+ ? navigate('room', { roomId: intoRoomId })
+ : params.templateId
+ ? navigate('templateDetail', { serverId, templateId: params.templateId })
+ : params.yamlText
+ ? navigate('templateImport', {
+ serverId,
+ yamlText: params.yamlText,
+ sourceName: params.sourceName,
+ edit: true,
+ })
+ : navigate('templates', { serverId });
+ const showAgentLists =
+ parsed !== null &&
+ !isGroupDoc &&
+ (parsed.hardcodedAgents.length > 0 || editedAgents.length > 0);
+ const showUserLists =
+ parsed !== null && !isGroupDoc && (parsed.hardcodedUsers.length > 0 || editedUsers.length > 0);
+
+ // The rows of the creating screen: one per call the run makes.
+ const createSteps: CreateStep[] = slots.flatMap((slot, i) =>
+ slot.mode === 'new'
+ ? agentCreateSteps(i, {
+ name: slot.createdName ?? setups[i]?.name ?? 'the agent',
+ status: slot.status,
+ step: slot.step,
+ clones: slot.cloneRepo && !!slot.entry.repoUrl,
+ setsPolicy: !!slot.entry.addressing,
+ cloneWarning: slot.cloneWarning,
+ })
+ : []
+ );
+ const joinNames = [
+ ...(intoRoomName ? [intoRoomName] : []),
+ ...new Set(setups.flatMap((s) => s.joins)),
+ ];
+ if (joinNames.length > 0) {
+ createSteps.push({
+ key: 'join',
+ label: `Add to ${joinNames.join(', ')}`,
+ status: makesRoom && roomStatus === 'created' ? 'done' : createStepStatus(roomStatus),
+ });
+ }
+ if (makesRoom && parsed) {
+ const count = parsed.rooms.length;
+ const hasKickoff = parsed.kickoff !== null || parsed.rooms.some((r) => r.kickoff);
+ createSteps.push({
+ key: 'room',
+ label:
+ (count > 1 ? `Create ${count} rooms` : 'Create the room') +
+ (hasKickoff ? (count > 1 ? ' and post their kickoffs' : ' and post the kickoff') : ''),
+ status: createStepStatus(roomStatus),
+ });
+ }
+ const runError =
+ createError ?? slots.find((s) => s.status === 'failed')?.error ?? Object.values(fieldErrors)[0];
+
+ const busy = phase === 'creating';
+ const newRoomForPick =
+ hasRoomPart && templateRoom
+ ? {
+ name: interpolate(templateRoom.name ?? 'New room', railValues),
+ bridgeType: templateBridge?.type ?? null,
+ }
+ : null;
+
+ /** One param as the template says to show it: asked, folded, or fixed.
+ * Inside the Advanced fold an `advanced` param is a plain field: the fold does the folding. */
+ const paramRow = (
+ param: ParamSpec,
+ sshHost: string | null,
+ inFold = false,
+ /** The agent whose section the row sits in, for a directory param's resolved path. */
+ slotIndex: number | null = null
+ ) => {
+ const value = values[param.name] ?? '';
+ const error = fieldErrors[param.name] ?? clashErrors[param.name] ?? valueProblem(param, value);
+ const resolvedDirectory =
+ param.type === 'directory' && slotIndex !== null && setups[slotIndex]?.directory
+ ? setups[slotIndex].directory
+ : null;
+ const summary =
+ param.type === 'provider'
+ ? (providerDisplayName(String(value)) ?? String(value))
+ : param.type === 'location'
+ ? runLocationLabel(String(value) || LOCAL_RUN_LOCATION, allowedHosts)
+ : param.type === 'room' && value === NEW
+ ? (newRoomForPick?.name ?? 'New room')
+ : param.type === 'directory'
+ ? (resolvedDirectory ?? String(value)).replace(/^\/(?:Users|home)\/[^/]+/, '~')
+ : String(value);
+ if (param.input === 'fixed') {
+ return <FixedRow key={param.name} label={paramLabel(param)} value={summary} />;
+ }
+ // A directory param's value can read `{$agents_dir}` and `{agent}`; the
+ // control shows the path they resolve to, and an edit writes a literal.
+ const shown = resolvedDirectory ?? value;
+ const field = (
+ <ParamField
+ key={param.name}
+ param={param}
+ value={shown}
+ onChange={(v) => setValues((prev) => ({ ...prev, [param.name]: v }))}
+ error={error}
+ lists={lists}
+ sshHost={sshHost}
+ hosts={allowedHosts}
+ newRoom={newRoomForPick}
+ disabled={busy}
+ onNavigateAway={() =>
+ param.type === 'location'
+ ? navigate('remoteHosts')
+ : navigate('settings', { tab: 'clis-models' })
+ }
+ />
+ );
+ if (param.input === 'advanced' && !inFold) {
+ const settled = !isEmpty(value) && error === null;
+ return (
+ <CollapsibleInput
+ key={param.name}
+ label={paramLabel(param)}
+ summary={summary}
+ collapsed={settled && !opened.has(param.name) && phase === 'form'}
+ onOpen={() => open(param.name)}
+ disabled={busy}
+ >
+ {field}
+ </CollapsibleInput>
+ );
+ }
+ return field;
+ };
+
+ /** A summary line for the fold: each folded value, in order. */
+ const foldSummary = (rows: ParamSpec[], directory: string, asksDirectory: boolean) =>
+ [
+ ...rows.map((p) => {
+ const v = values[p.name] ?? '';
+ return p.type === 'provider'
+ ? (providerDisplayName(String(v)) ?? String(v))
+ : p.type === 'location'
+ ? runLocationLabel(String(v) || LOCAL_RUN_LOCATION, allowedHosts)
+ : p.type === 'directory'
+ ? (directory || String(v)).replace(/^\/(?:Users|home)\/[^/]+/, '~')
+ : String(v);
+ }),
+ ...(asksDirectory ? [directory.replace(/^\/(?:Users|home)\/[^/]+/, '~')] : []),
+ ]
+ .filter((v) => v !== '')
+ .join(' · ');
+
+ /** The section for one agent entry: what it asks, then one fold with what the template settled. */
+ const agentSection = (slot: AgentSlot, i: number) => {
+ const setup = setups[i];
+ const sshHost = setup.location === LOCAL_RUN_LOCATION ? null : setup.location;
+ const own = paramsOfAgent(i);
+ const shared = i === 0 ? [providerParam, locationParam, directoryParam] : [];
+ const rows = [...own, ...shared.filter((p): p is ParamSpec => p !== null && !own.includes(p))];
+ const asked = rows.filter((p) => p.input === 'ask');
+ const folded = rows.filter((p) => p.input !== 'ask');
+ const asksProvider = !slot.entry.provider && !providerParam && slot.mode === 'new';
+ const asksDirectory = !slot.entry.directory && !directoryParam && slot.mode === 'new';
+ const isRemote = sshHost !== null;
+ const foldKey = `fold:${i}`;
+ const foldSettled =
+ folded.every(
+ (p) =>
+ p.input === 'fixed' ||
+ (!isEmpty(values[p.name]) &&
+ (fieldErrors[p.name] ?? valueProblem(p, values[p.name] ?? '')) === null)
+ ) &&
+ (!asksDirectory || (setup.directory !== '' && !slot.dirPicked)) &&
+ hostReachable &&
+ hostReady;
+ const hasFold = folded.length > 0 || asksDirectory;
+ const foldLabel = loaded?.form.advanced.label ?? 'Advanced';
+ return (
+ <div key={i} className="flex flex-col gap-4">
+ {slots.length > 1 && (
+ <SectionTitle
+ title={setup.name && !hasPlaceholder(setup.name) ? setup.name : `Agent ${i + 1}`}
+ hint={slot.entry.description || undefined}
+ />
+ )}
+ {asked.map((p) => paramRow(p, sshHost, false, i))}
+ {asksProvider && (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-baseline gap-2">
+ <span className="text-[12.5px] font-medium">Provider</span>
+ <span className="flex-1" />
+ <span className="text-[11px] text-amber-600 dark:text-amber-400">Required</span>
+ </div>
+ <p className="text-xs text-foreground-muted">
+ The template names no coding agent. Only what{' '}
+ {runLocationLabel(setup.location, allowedHosts)} has installed is offered.
+ </p>
+ {hostReachable ? (
+ <AgentTypePicker
+ value={pickedProvider}
+ onChange={setPickedProvider}
+ sshHost={sshHost ?? undefined}
+ onNavigateAway={() => navigate('settings', { tab: 'clis-models' })}
+ />
+ ) : (
+ <p className="text-xs text-foreground-passive">Waiting for the host…</p>
+ )}
+ </div>
+ )}
+ {hasFold && (
+ <CollapsibleInput
+ label={foldLabel}
+ summary={foldSummary(folded, setup.directory, asksDirectory)}
+ collapsed={
+ phase === 'form' &&
+ !(loaded?.form.advanced.open ?? false) &&
+ !opened.has(foldKey) &&
+ foldSettled
+ }
+ onOpen={() => open(foldKey)}
+ disabled={busy}
+ wrap
+ >
+ <div className="flex flex-col gap-5 rounded-[10px] border border-border px-4 py-4">
+ <span className="text-[12.5px] font-medium">{foldLabel}</span>
+ {folded.map((p) => paramRow(p, sshHost, true, i))}
+ {asksDirectory && (
+ <div className="flex flex-col gap-2">
+ <span className="text-[12.5px] font-medium">Directory</span>
+ <p className="text-xs text-foreground-muted">
+ The template names no directory, so the agent gets a folder of its own under the
+ one this Console keeps agents in.
+ </p>
+ <SlotDirectoryField
+ slot={{ ...slot, dir: setup.directory }}
+ onChange={(next) =>
+ setSlots((prev) => prev.map((x, j) => (j === i ? next : x)))
+ }
+ sshHost={sshHost}
+ busy={busy}
+ />
+ </div>
+ )}
+ {isRemote && <HostReachabilityNotice sshHost={setup.location} />}
+ {isRemote &&
+ hostReachable &&
+ firstRemote === setup.location &&
+ !hostReadiness.checking && (
+ <HostReadinessNotice
+ sshHost={setup.location}
+ readiness={hostReadiness}
+ onNavigateAway={() => navigate('remoteHosts')}
+ />
+ )}
+ </div>
+ </CollapsibleInput>
+ )}
+ </div>
+ );
+ };
+
+ const memberLists = (
+ <>
+ {showAgentLists && (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-baseline gap-2">
+ <span className="font-mono text-[12.5px] font-medium">agents</span>
+ <span className="text-[11px] text-foreground-passive">already on the server</span>
+ </div>
+ <AgentListField items={editedAgents} onChange={setEditedAgents} lists={lists} />
+ <p className="text-xs text-foreground-muted">
+ Agents the template puts in the room. Drop any the server does not have, or add more.
+ </p>
+ </div>
+ )}
+ {showUserLists && (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-baseline gap-2">
+ <span className="font-mono text-[12.5px] font-medium">users</span>
+ <span className="text-[11px] text-foreground-passive">people</span>
+ </div>
+ <UserListField items={editedUsers} onChange={setEditedUsers} lists={lists} />
+ <p className="text-xs text-foreground-muted">
+ People the template invites. A name the server has not seen is looked up in the
+ messaging app's directory when the room is created.
+ </p>
+ </div>
+ )}
+ </>
+ );
+
+ const otherRoomParams = roomParams.filter((p) => p !== joinParam);
+ const roomDetails = (
+ <>
+ {otherRoomParams.filter((p) => p.input !== 'advanced').map((p) => paramRow(p, null))}
+ {makesRoom && memberLists}
+ {otherRoomParams.filter((p) => p.input === 'advanced').map((p) => paramRow(p, null))}
+ </>
+ );
+ const roomSummary =
+ joinValue === NEW
+ ? `New room: ${newRoomForPick?.name ?? 'from the template'}`
+ : joinValue || 'Pick a room';
+ const roomSection = joinParam ? (
+ // The template leaves the room to the deployer: one switch, and the
+ // details only once it is on. Off, the agent is created on its own.
+ <div className="flex flex-col gap-4">
+ <label className="flex cursor-pointer items-start gap-3">
+ <Switch
+ checked={roomOn}
+ disabled={busy}
+ onCheckedChange={(on) => {
+ setRoomOn(on);
+ const next = on && hasRoomPart ? NEW : '';
+ setValues((prev) => ({ ...prev, [joinParam.name]: next }));
+ setPickingRoom(on && next === '');
+ }}
+ className="mt-0.5"
+ />
+ <span className="flex flex-col gap-0.5">
+ <span className="text-sm font-semibold text-foreground">{paramLabel(joinParam)}</span>
+ {joinParam.description && (
+ <span className="text-[12.5px] leading-relaxed text-foreground-muted">
+ {joinParam.description}
+ </span>
+ )}
+ </span>
+ </label>
+ {roomOn && (
+ <div className="flex flex-col gap-4 border-l-2 border-border pl-4">
+ {pickingRoom ? (
+ <div className="flex flex-col gap-2">
+ <span className="text-[12.5px] font-medium">Room</span>
+ <RoomChoiceField
+ rooms={lists.rooms}
+ loading={lists.roomsLoading}
+ newRoom={newRoomForPick}
+ value=""
+ onChange={(v) => {
+ setValues((prev) => ({ ...prev, [joinParam.name]: v }));
+ setPickingRoom(false);
+ }}
+ />
+ </div>
+ ) : (
+ <CollapsibleInput
+ label="Room"
+ summary={roomSummary}
+ collapsed
+ onOpen={() => setPickingRoom(true)}
+ disabled={busy}
+ >
+ {null}
+ </CollapsibleInput>
+ )}
+ {roomDetails}
+ </div>
+ )}
+ </div>
+ ) : hasRoomPart || roomParams.length > 0 || intoRoomId ? (
+ <div className="flex flex-col gap-4">
+ <SectionTitle
+ title={roomCount > 1 ? 'Rooms' : 'Room'}
+ hint={
+ intoRoomId
+ ? `The agent joins ${intoRoomName ?? 'the room'} you came from.`
+ : roomParams.length === 0 && makesRoom
+ ? 'Created as the template describes, with the agent in it.'
+ : undefined
+ }
+ />
+ {roomDetails}
+ </div>
+ ) : null;
+
+ return (
+ <div className="relative z-10 flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
+ <div className="flex shrink-0 items-start gap-4 border-b border-border px-8 pt-8 pb-5 [-webkit-app-region:drag]">
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <span className="text-xs text-foreground-passive">
+ {intoRoomId ? `Add an agent to ${intoRoomName ?? 'the room'}` : 'Use template'}
+ </span>
+ <h2 className="truncate text-xl font-semibold tracking-tight">
+ {loaded?.name ?? params.sourceName ?? 'Template'}
+ </h2>
+ {partlyDone && phase === 'form' && (
+ <span className="text-xs text-foreground-muted">
+ What was created stays created; the button carries on from the first step that did not
+ finish.
+ </span>
+ )}
+ </div>
+ <div
+ className={cn(
+ 'flex shrink-0 flex-col items-end gap-1 [-webkit-app-region:no-drag]',
+ phase !== 'form' && 'invisible'
+ )}
+ >
+ <div className="flex items-center gap-2">
+ <Button variant="outline" size="sm" onClick={cancel} disabled={phase !== 'form'}>
+ {params.yamlText && !intoRoomId ? 'Back to the document' : 'Cancel'}
+ </Button>
+ <Button
+ size="sm"
+ onClick={() => void createAll()}
+ disabled={blockedReason !== null || phase !== 'form'}
+ title={blockedReason ?? undefined}
+ >
+ {primaryLabel}
+ </Button>
+ </div>
+ {blockedReason && loaded && phase === 'form' && (
+ <span className="max-w-md text-right text-[11.5px] text-foreground-muted">
+ {blockedReason}
+ </span>
+ )}
+ </div>
+ </div>
+
+ {loadError ? (
+ <div className="px-8 py-6">
+ <Alert variant="destructive">
+ <AlertDescription>{loadError}</AlertDescription>
+ </Alert>
+ </div>
+ ) : !loaded || (!parsed && loaded.coreYaml) ? (
+ <div className="flex items-center justify-center py-16">
+ <Loader2 className="size-5 animate-spin text-foreground-muted" />
+ </div>
+ ) : (
+ <>
+ {phase !== 'form' && (
+ <CreatingScreen
+ templateName={loaded.name}
+ phase={phase}
+ steps={createSteps}
+ error={runError ?? null}
+ doneDetail={doneDetail}
+ onRetry={() => void createAll()}
+ onBack={() => setPhase('form')}
+ />
+ )}
+ {/* The form stays mounted under the creating screen, so Back to the
+ form finds every choice as it was left. */}
+ <div className={cn('flex min-h-0 flex-1', phase !== 'form' && 'hidden')}>
+ {/* Left: inputs */}
+ <div className="flex w-[46%] min-w-[340px] shrink-0 flex-col gap-6 overflow-auto px-8 py-6">
+ {createError && (
+ <Alert variant="destructive">
+ <AlertDescription>{createError}</AlertDescription>
+ </Alert>
+ )}
+ {loaded.warnings.map((w, i) => (
+ <Alert key={i}>
+ <AlertDescription>{w}</AlertDescription>
+ </Alert>
+ ))}
+ {creatorBlocked && makesRoom && (
+ <Alert>
+ <AlertDescription>
+ <div className="flex flex-col gap-2">
+ <span>
+ This template puts you in the room, and this server does not know which
+ account is yours{templateBridge ? ` on ${templateBridge.displayName}` : ''}.
+ </span>
+ {linkAccount && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="self-start"
+ onClick={linkAccount}
+ >
+ Link account
+ </Button>
+ )}
+ </div>
+ </AlertDescription>
+ </Alert>
+ )}
+ {handoffBlocked.length > 0 && (
+ <Alert>
+ <AlertDescription>
+ <div className="flex flex-col gap-2">
+ <span>
+ These agents will not hear each other:{' '}
+ {handoffBlocked.map((b) => `${b.to} ignores ${b.from}`).join(', ')}.
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ className="self-start"
+ disabled={allowingHandoffs}
+ onClick={() => void allowHandoffs()}
+ >
+ {allowingHandoffs ? 'Updating…' : 'Let them hear each other'}
+ </Button>
+ </div>
+ </AlertDescription>
+ </Alert>
+ )}
+
+ {createsAgents && (
+ <>
+ <SectionTitle
+ title={slots.length === 1 ? 'Agent' : 'Agents'}
+ hint={
+ templateParams.length === 0
+ ? 'This template asks for nothing. Create it as it is, or open Advanced.'
+ : undefined
+ }
+ />
+ {slots.map(agentSection)}
+ </>
+ )}
+ {createsAgents && roomSection && <div className="border-t border-border" />}
+ {!createsAgents && templateParams.length === 0 && (
+ <p className="text-sm text-foreground-muted">This template asks for nothing.</p>
+ )}
+ {roomSection}
+ </div>
+
+ {/* Right: what this will create */}
+ <div className="flex min-w-0 flex-1 flex-col border-l border-border bg-background-1">
+ <div className="flex shrink-0 items-center gap-3 border-b border-border px-5 py-3">
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="text-[10.5px] font-medium tracking-wide text-foreground-passive uppercase">
+ Preview
+ </span>
+ <span className="text-[13px] font-semibold">What this will create</span>
+ </span>
+ <span
+ className={cn(
+ 'shrink-0 text-[11.5px]',
+ missing.length > 0 || slotProblems.length > 0 || invalid.length > 0
+ ? 'text-amber-600 dark:text-amber-400'
+ : 'text-emerald-700 dark:text-emerald-400'
+ )}
+ >
+ {stillNeeded}
+ </span>
+ </div>
+ <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-auto px-5 py-4">
+ <div className="flex flex-col gap-2">
+ {slots.map((slot, i) => (
+ <AgentSlotCard
+ key={i}
+ slot={slot}
+ wantedName={setups[i]?.name ?? ''}
+ onChange={(next) =>
+ setSlots((prev) => prev.map((s, j) => (j === i ? next : s)))
+ }
+ lists={lists}
+ locationLabel={runLocationLabel(
+ setups[i]?.location ?? LOCAL_RUN_LOCATION,
+ allowedHosts
+ )}
+ choice={loaded.kind === 'group'}
+ />
+ ))}
+ {intoRoomId ? (
+ <p className="px-1 text-xs text-foreground-muted">
+ Joins{' '}
+ <span className="font-medium text-foreground">
+ {intoRoomName ?? 'the room'}
+ </span>
+ . Mention it there to start it.
+ </p>
+ ) : null}
+ {joinNames
+ .filter((n) => n !== intoRoomName)
+ .map((n) => (
+ <p key={n} className="px-1 text-xs text-foreground-muted">
+ Joins <span className="font-medium text-foreground">{n}</span>. Mention it
+ there to start it.
+ </p>
+ ))}
+ {makesRoom &&
+ parsed?.rooms.map((room, i) => (
+ <RoomCard
+ key={i}
+ room={room}
+ values={railValues}
+ renames={railRenames}
+ bridgeName={templateBridge?.displayName ?? parsed.bridge}
+ creatorIdentity={creatorIdentity}
+ status={roomStatus}
+ toggle={null}
+ />
+ ))}
+ </div>
+ <ResolvedDocument
+ yamlText={loaded.yamlText}
+ values={railValues}
+ renames={railRenames}
+ />
+ </div>
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ );
+});
+
+function provisionErrorText(
+ result: Exclude<Awaited<ReturnType<typeof rpc.agents.addAgent>>, { kind: 'created' }>
+): string {
+ switch (result.kind) {
+ case 'unauthenticated':
+ return 'Sign in to this server first.';
+ case 'name-conflict':
+ return 'An agent with this name already exists in this directory or on the server.';
+ case 'credentials-conflict':
+ return `This directory already holds credentials for an agent of that name on ${result.endpoint}. Pick another directory.`;
+ case 'already-configured':
+ return 'This directory already holds credentials for an agent of that name. Load it instead.';
+ case 'invalid-name':
+ return result.message;
+ default:
+ return result.message;
+ }
+}
+
+export const templateUseView = {
+ WrapView: ({ children }: { children: React.ReactNode } & Params) => <>{children}</>,
+ TitlebarSlot: TemplateUseTitlebar,
+ MainPanel: TemplateUsePanel,
+ canActivate: (params: unknown): GuardResult => {
+ const p = params as Partial<Params> | null;
+ if (typeof p?.serverId !== 'string') return { ok: false, redirect: 'home' };
+ if (!p.templateId && !p.yamlText)
+ return { ok: false, redirect: 'templates', params: { serverId: p.serverId } };
+ return { ok: true };
+ },
+} satisfies ViewDefinition<Params>;
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.tsx
new file mode 100644
index 000000000..9dd589359
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/templates-view.tsx
@@ -0,0 +1,700 @@
+import {
+ Bot,
+ Boxes,
+ CircleAlert,
+ Clock,
+ DoorOpen,
+ FileText,
+ Loader2,
+ Save,
+ Upload,
+ UserRound,
+ Users,
+} from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import type { TemplateKind } from '@main/core/agent-templates/template-document';
+import type { TemplateSummary } from '@main/core/agent-templates/template-summary';
+import type { RecentTemplate } from '@main/core/room-templates/controller';
+import type { StoredTemplateSummary } from '@main/core/switch-servers/gateway-client';
+import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';
+import { ServerPage } from '@renderer/features/switch-servers/server-page';
+import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';
+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { toast } from '@renderer/lib/hooks/use-toast';
+import { rpc } from '@renderer/lib/ipc';
+import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
+import { useShowModal } from '@renderer/lib/modal/modal-provider';
+import { useAgentTypeAvailability } from '@renderer/lib/stores/use-switch-setup';
+import { Alert, AlertAction, AlertDescription } from '@renderer/lib/ui/alert';
+import { Badge } from '@renderer/lib/ui/badge';
+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 { prefillForSave } from './agent-template-data';
+import { bundledTemplates } from './bundled-templates';
+
+function useServerId(): string {
+ return useParams('templates').params.serverId;
+}
+
+const TemplatesTitlebar = observer(function TemplatesTitlebar() {
+ return <ServerSectionTitlebar serverId={useServerId()} icon={FileText} label="Templates" />;
+});
+
+type Kind = 'agent' | 'room' | 'group';
+type KindFilter = 'all' | Kind;
+
+const KIND_OPTIONS = [
+ { value: 'all', label: 'All' },
+ { value: 'room', label: 'Rooms', icon: DoorOpen },
+ { value: 'agent', label: 'Agents', icon: Bot },
+ { value: 'group', label: 'Groups', icon: Boxes },
+] as const satisfies readonly {
+ value: KindFilter;
+ label: string;
+ icon?: typeof Bot;
+}[];
+
+const KIND_ICON: Record<Kind, typeof Bot> = {
+ agent: Bot,
+ room: DoorOpen,
+ group: Boxes,
+};
+
+/** One card in the listing: a bundled template, or a template saved on the workspace. */
+type TemplateListEntry = {
+ /** The id the card opens: a bundled id, or a workspace template id. */
+ id: string;
+ kind: Kind;
+ name: string;
+ description: string;
+ bundled: boolean;
+ server: StoredTemplateSummary | null;
+ /** The document text, when it is available without a request (a bundled template). */
+ content: string | null;
+};
+
+function kindOf(kind: string): Kind {
+ return kind === 'agent' || kind === 'group' ? kind : 'room';
+}
+
+function readFileAsText(file: File): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(String(reader.result ?? ''));
+ reader.onerror = () => reject(reader.error ?? new Error('Could not read the file'));
+ reader.readAsText(file);
+ });
+}
+
+function hasFiles(e: React.DragEvent): boolean {
+ return Array.from(e.dataTransfer.types).includes('Files');
+}
+
+function plural(n: number, noun: string): string {
+ return `${n} ${noun}${n === 1 ? '' : 's'}`;
+}
+
+/** The card's summary line, for example "Creates 1 room and 2 agents · 4 inputs".
+ * An agent template's room is optional, so its card names the agent alone. */
+function summaryLine(s: TemplateSummary): string {
+ const parts: string[] = [];
+ if (s.rooms > 0 && s.kind !== 'agent') parts.push(plural(s.rooms, 'room'));
+ if (s.agents > 0) parts.push(s.kind === 'agent' ? 'an agent' : plural(s.agents, 'agent'));
+ const creates = parts.length > 0 ? `Creates ${parts.join(' and ')}` : 'Creates nothing yet';
+ const inputs = s.inputs === 0 ? 'nothing to fill in' : plural(s.inputs, 'input');
+ return `${creates} · ${inputs}`;
+}
+
+// The listing endpoint returns no document text, and the summary line
+// needs the document. Each card fetches its own once and keeps it for the
+// session.
+const summaryCache = new Map<string, Promise<TemplateSummary>>();
+
+function fetchSummary(serverId: string, item: TemplateListEntry): Promise<TemplateSummary> {
+ const key = `${serverId}:${item.id}`;
+ let pending = summaryCache.get(key);
+ if (!pending) {
+ pending = (async () => {
+ const yamlText =
+ item.content ??
+ (
+ await rpc.switchServers.getTemplateDetail({
+ serverId,
+ templateId: item.id,
+ })
+ ).definition;
+ return rpc.agentTemplates.summarize({ yamlText });
+ })();
+ pending.catch(() => summaryCache.delete(key));
+ summaryCache.set(key, pending);
+ }
+ return pending;
+}
+
+function useTemplateSummary(serverId: string, item: TemplateListEntry): TemplateSummary | null {
+ const [summary, setSummary] = useState<TemplateSummary | null>(null);
+ useEffect(() => {
+ let cancelled = false;
+ fetchSummary(serverId, item)
+ .then((s) => {
+ if (!cancelled) setSummary(s);
+ })
+ .catch(() => {
+ // The card renders without the summary line when the document cannot be fetched.
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [serverId, item]);
+ return summary;
+}
+
+function OwnerRow({ name, mine }: { name: string; mine: boolean }) {
+ const initial = (name.trim()[0] ?? '?').toUpperCase();
+ return (
+ <span className="flex items-center gap-1.5 text-xs text-foreground-muted">
+ <span
+ aria-hidden
+ className="flex size-4.5 items-center justify-center rounded-full bg-background-2 text-[10px] font-medium text-foreground"
+ >
+ {initial}
+ </span>
+ {mine ? 'You' : name}
+ </span>
+ );
+}
+
+function TemplateCard({
+ serverId,
+ item,
+ meId,
+ busy,
+ onOpen,
+ onUse,
+}: {
+ serverId: string;
+ item: TemplateListEntry;
+ meId: string | null;
+ busy: boolean;
+ onOpen: () => void;
+ onUse: () => void;
+}) {
+ const Icon = KIND_ICON[item.kind];
+ const summary = useTemplateSummary(serverId, item);
+ const mine = item.server !== null && meId !== null && item.server.ownerId === meId;
+ return (
+ <div className="group relative flex min-h-[168px] flex-col rounded-[11px] border border-border bg-background transition-colors hover:border-border-1">
+ <button
+ type="button"
+ aria-label={`Open ${item.name}`}
+ className="focus-visible:ring-ring absolute inset-0 cursor-pointer rounded-[11px] focus-visible:ring-2 focus-visible:outline-none"
+ onClick={onOpen}
+ />
+ <div className="pointer-events-none flex flex-1 flex-col gap-2 p-4">
+ <div className="flex items-center gap-2">
+ <Icon className="size-4.5 shrink-0 text-foreground-muted" />
+ <h3 className="min-w-0 truncate font-medium text-foreground">{item.name}</h3>
+ {item.bundled && (
+ <Badge variant="outline" title="Shipped with Switch">
+ Official
+ </Badge>
+ )}
+ {item.server && mine && !item.bundled && <Badge variant="secondary">Yours</Badge>}
+ {item.bundled && item.server && (
+ <Badge variant="secondary" title="A copy is saved on this workspace; it lists below">
+ <Users />
+ Saved
+ </Badge>
+ )}
+ </div>
+ <p className="line-clamp-3 text-sm text-foreground-muted">
+ {item.description || <span className="italic">No description.</span>}
+ </p>
+ <div className="mt-auto flex flex-col gap-1.5 pt-1 pr-16">
+ <span className="text-xs text-foreground-passive">
+ {summary ? summaryLine(summary) : ' '}
+ </span>
+ {item.server && !item.bundled && <OwnerRow name={item.server.creator} mine={mine} />}
+ </div>
+ </div>
+ {/* On top of the overlay: the one action that does not need the page. */}
+ <div className="absolute right-3 bottom-3">
+ <Button size="sm" variant="outline" onClick={onUse} disabled={busy}>
+ {busy ? 'Opening…' : 'Use'}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function Section({
+ title,
+ subtitle,
+ children,
+}: {
+ title: string;
+ subtitle: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <section>
+ <h3 className="text-sm font-semibold text-foreground">{title}</h3>
+ <p className="mt-0.5 mb-3 text-xs text-foreground-muted">{subtitle}</p>
+ {children}
+ </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.
+ */
+function RecentsSection({
+ serverId,
+ serverName,
+ onWorkspace,
+ kind,
+ query,
+ onSaved,
+}: {
+ serverId: string;
+ serverName: string | null;
+ /** Names of templates saved on the workspace. A recent with one of these names gets no Save button. */
+ onWorkspace: ReadonlySet<string>;
+ /** The listing's kind filter and search text. They apply to the recents too. Only mine does not: every recent is the user's own. */
+ kind: KindFilter;
+ query: string;
+ onSaved: () => void;
+}) {
+ const { navigate } = useNavigate();
+ const showSaveModal = useShowModal('saveTemplateModal');
+ // 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);
+
+ useEffect(() => {
+ let cancelled = false;
+ void (async () => {
+ try {
+ const list = await rpc.roomTemplates.getRecents(serverId);
+ // One row per name. The same template used before and after an edit is two
+ // documents with one name, and only the newest use is offered.
+ const newest = list.filter((r, i) => list.findIndex((o) => o.name === r.name) === i);
+ const classified = await Promise.all(
+ newest.map(async (r) => ({
+ ...r,
+ kind: await rpc.agentTemplates
+ .kind({ yamlText: r.yamlText })
+ .catch(() => 'room' as const),
+ }))
+ );
+ if (!cancelled) setRecents(classified);
+ } catch {
+ if (!cancelled) setRecents([]);
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [serverId]);
+
+ const saveToWorkspace = async (recent: RecentTemplate) => {
+ setSaving(recent.yamlText);
+ try {
+ const prefill = await prefillForSave(recent.yamlText, recent.name);
+ showSaveModal({
+ serverId,
+ serverName,
+ content: recent.yamlText,
+ ...prefill,
+ onSuccess: onSaved,
+ });
+ } catch (error) {
+ toast({
+ title: `Could not read "${recent.name}"`,
+ description: failureText(error, 'The document did not parse.'),
+ variant: 'destructive',
+ });
+ } finally {
+ setSaving(null);
+ }
+ };
+
+ const needle = query.trim().toLowerCase();
+ const shown = (recents ?? []).filter(
+ (r) =>
+ (kind === 'all' || r.kind === kind) &&
+ (needle.length === 0 || r.name.toLowerCase().includes(needle))
+ );
+ if (shown.length === 0) return null;
+
+ return (
+ <section>
+ <h3 className="flex items-center gap-1.5 text-sm font-semibold text-foreground">
+ <Clock className="size-3.5 text-foreground-muted" />
+ 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.
+ </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
+ type="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)}
+ >
+ <Save className="size-3.5" />
+ Save to workspace
+ </Button>
+ )}
+ </div>
+ ))}
+ </div>
+ </section>
+ );
+}
+
+const TemplatesPanel = observer(function TemplatesPanel() {
+ const serverId = useServerId();
+ const server = switchServersStore.servers.find((s) => s.id === serverId);
+ const meId = switchServersStore.statusFor(serverId)?.user?.id ?? null;
+ const { navigate } = useNavigate();
+
+ const [templates, setTemplates] = useState<StoredTemplateSummary[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [listError, setListError] = useState<string | null>(null);
+ const [query, setQuery] = useState('');
+ // A caller can open the listing with a kind preselected; the deployer can clear it.
+ const initialKind = useParams('templates').params.kind;
+ const [kind, setKind] = useState<KindFilter>(initialKind ?? 'all');
+ // Navigating here without the param, as the sidebar does, shows every kind.
+ useEffect(() => setKind(initialKind ?? 'all'), [initialKind]);
+ const [onlyMine, setOnlyMine] = useState(false);
+ const [dragging, setDragging] = useState(0);
+ const [reloadKey, setReloadKey] = useState(0);
+ const reload = useCallback(() => setReloadKey((k) => k + 1), []);
+
+ // An agent template needs a coding agent where its agents will run, and
+ // this computer is the default run location. Say at the top of the listing
+ // when it has none, rather than at the end of the Use page; a host gets
+ // its own check there.
+ const { data: availability } = useAgentTypeAvailability();
+ const noProvider = availability !== undefined && !availability.some((a) => a.available);
+
+ useEffect(() => {
+ let cancelled = false;
+ setLoading(true);
+ setListError(null);
+ rpc.switchServers
+ .listTemplates({ serverId })
+ .then((result) => {
+ if (!cancelled) setTemplates(result);
+ })
+ .catch((e: unknown) => {
+ // The bundled templates render either way. A failed request is shown as a
+ // failure, not as an empty workspace.
+ if (!cancelled) {
+ setTemplates([]);
+ setListError(failureText(e, 'Could not read this workspace’s templates.'));
+ }
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [serverId, reloadKey]);
+
+ const { builtIn, onWorkspace } = useMemo(() => {
+ // A bundled card is always the bundled document. Saving it creates a
+ // workspace template, listed below as the user's own; the bundled card
+ // only marks that a copy exists. Names are unique per owner, so only the
+ // user's own template of that name counts as the copy.
+ const byName = new Map(
+ templates.filter((t) => meId !== null && t.ownerId === meId).map((t) => [t.name, t])
+ );
+ const builtIn: TemplateListEntry[] = bundledTemplates.map((b) => ({
+ id: b.id,
+ kind: kindOf(b.kind),
+ name: b.name,
+ description: b.description,
+ bundled: true,
+ server: byName.get(b.name) ?? null,
+ content: b.yamlText,
+ }));
+ const onWorkspace: TemplateListEntry[] = templates.map((t) => ({
+ id: t.id,
+ kind: kindOf(t.kind),
+ name: t.name,
+ description: t.description,
+ bundled: false,
+ server: t,
+ content: null,
+ }));
+ const needle = query.trim().toLowerCase();
+ const matches = (t: TemplateListEntry) =>
+ (kind === 'all' || t.kind === kind) &&
+ (needle.length === 0 ||
+ t.name.toLowerCase().includes(needle) ||
+ t.description.toLowerCase().includes(needle) ||
+ (t.server?.creator ?? '').toLowerCase().includes(needle));
+ const mine = (t: TemplateListEntry) => meId !== null && t.server?.ownerId === meId;
+ return {
+ builtIn: onlyMine ? [] : builtIn.filter(matches),
+ onWorkspace: onWorkspace.filter((t) => matches(t) && (!onlyMine || mine(t))),
+ };
+ }, [templates, query, kind, onlyMine, meId]);
+
+ const handleUse = (item: TemplateListEntry) =>
+ navigate('templateUse', { serverId, templateId: item.id });
+
+ const importFile = async (file: File) => {
+ try {
+ const yamlText = await readFileAsText(file);
+ navigate('templateImport', { serverId, yamlText, sourceName: file.name });
+ } catch (error) {
+ toast({
+ title: `Could not read ${file.name}`,
+ description: failureText(error, ''),
+ variant: 'destructive',
+ });
+ }
+ };
+
+ const grid = 'grid grid-cols-[repeat(auto-fill,minmax(280px,1fr))] gap-[14px]';
+ const filtering = query.trim().length > 0 || kind !== 'all' || onlyMine;
+ const open = (item: TemplateListEntry) =>
+ navigate('templateDetail', { serverId, templateId: item.id });
+ const card = (item: TemplateListEntry) => (
+ <TemplateCard
+ key={item.id}
+ serverId={serverId}
+ item={item}
+ meId={meId}
+ busy={false}
+ onOpen={() => open(item)}
+ onUse={() => handleUse(item)}
+ />
+ );
+
+ return (
+ <ServerPage
+ title="Templates"
+ description="A template is one YAML document that creates a room, an agent, or a group of them. Use one, fill in its inputs, and everything it describes appears on this workspace."
+ action={
+ <Button size="sm" onClick={() => navigate('templateImport', { serverId })}>
+ <Upload className="size-4" />
+ Import template
+ </Button>
+ }
+ >
+ {/* The whole page takes a dropped file: the import view is one step
+ away, and a file in hand should not have to find a target first. */}
+ <div
+ className="relative"
+ onDragEnter={(e) => {
+ if (hasFiles(e)) setDragging((n) => n + 1);
+ }}
+ onDragLeave={(e) => {
+ if (hasFiles(e)) setDragging((n) => Math.max(0, n - 1));
+ }}
+ onDragOver={(e) => {
+ if (hasFiles(e)) e.preventDefault();
+ }}
+ onDrop={(e) => {
+ if (!hasFiles(e)) return;
+ e.preventDefault();
+ setDragging(0);
+ const file = e.dataTransfer.files[0];
+ if (file) void importFile(file);
+ }}
+ >
+ {dragging > 0 && (
+ <div className="border-primary pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-[11px] border-2 border-dashed bg-[var(--sel-soft)]/90">
+ <span className="flex items-center gap-2 text-sm font-medium text-foreground">
+ <Upload className="size-4" />
+ Drop the template file to import it
+ </span>
+ </div>
+ )}
+ {loading ? (
+ <div className="flex items-center justify-center py-12">
+ <Loader2 className="size-5 animate-spin text-foreground-muted" />
+ </div>
+ ) : (
+ <div className="space-y-8">
+ {noProvider && (
+ <Alert>
+ <CircleAlert />
+ <AlertDescription>
+ No agent provider is set up on this computer yet. A template creates an agent that
+ runs here, so it needs Claude Code, Codex or OpenCode installed with its Switch
+ connector first.
+ </AlertDescription>
+ <AlertAction>
+ <Button
+ variant="outline"
+ size="xs"
+ onClick={() => navigate('settings', { tab: 'clis-models' })}
+ >
+ Set up agent providers
+ </Button>
+ </AlertAction>
+ </Alert>
+ )}
+
+ <div className="flex flex-wrap items-center gap-2">
+ <SearchInput
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search name and description…"
+ aria-label="Search templates by name and description"
+ containerClassName="min-w-[220px] flex-1"
+ className="h-8"
+ />
+ <SegmentedControl
+ value={kind}
+ onChange={setKind}
+ options={KIND_OPTIONS}
+ ariaLabel="Show templates of one kind"
+ />
+ <Toggle
+ variant="outline"
+ size="sm"
+ pressed={onlyMine}
+ onPressedChange={setOnlyMine}
+ aria-label="Only templates you own"
+ title={meId ? 'Only templates you saved' : 'Sign in to see which are yours'}
+ disabled={meId === null}
+ >
+ <UserRound />
+ Only mine
+ </Toggle>
+ </div>
+
+ {!onlyMine && (
+ <Section
+ title="Built in"
+ subtitle="Shipped with Switch. Use one to see how a template is put together."
+ >
+ {builtIn.length > 0 ? (
+ <div className={grid}>{builtIn.map(card)}</div>
+ ) : (
+ <p className="text-sm text-foreground-muted">No built-in template matches.</p>
+ )}
+ </Section>
+ )}
+
+ <Section
+ title="On this workspace"
+ subtitle="Saved here. Everyone on this workspace can see and use them; only the owner can change one."
+ >
+ {onWorkspace.length > 0 ? (
+ <div className={grid}>{onWorkspace.map(card)}</div>
+ ) : listError ? (
+ <div className="flex flex-col items-start gap-2 rounded-[11px] border border-border px-4 py-4">
+ <p className="text-sm text-foreground-muted">{listError}</p>
+ <Button size="sm" variant="outline" onClick={reload}>
+ Try again
+ </Button>
+ </div>
+ ) : filtering ? (
+ <p className="text-sm text-foreground-muted">
+ {onlyMine
+ ? 'None of yours match. Save a template you used, or import one, and it shows up here as yours.'
+ : 'No template on this workspace matches.'}
+ </p>
+ ) : (
+ <div className="flex flex-col items-start gap-3 rounded-[11px] border border-dashed border-border px-4 py-5">
+ <p className="text-sm text-foreground-muted">
+ Nothing saved here yet. Import a template, or save one you have used, and
+ everyone on this workspace finds it here.
+ </p>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => navigate('templateImport', { serverId })}
+ >
+ <Upload className="size-3.5" />
+ Import a template
+ </Button>
+ </div>
+ )}
+ </Section>
+
+ <RecentsSection
+ serverId={serverId}
+ serverName={server?.name ?? null}
+ onWorkspace={new Set(templates.map((t) => t.name))}
+ kind={kind}
+ query={query}
+ onSaved={reload}
+ />
+ </div>
+ )}
+ </div>
+ </ServerPage>
+ );
+});
+
+export const templatesView = {
+ WrapView: ({ children }: { children: React.ReactNode; serverId: string; kind?: Kind }) => (
+ <>{children}</>
+ ),
+ TitlebarSlot: TemplatesTitlebar,
+ MainPanel: TemplatesPanel,
+ canActivate: (params: unknown): GuardResult => {
+ const serverId =
+ typeof params === 'object' && params !== null
+ ? (params as { serverId?: unknown }).serverId
+ : undefined;
+ if (typeof serverId !== 'string') return { ok: false, redirect: 'home' };
+ return { ok: true };
+ },
+} satisfies ViewDefinition<{ serverId: string; kind?: Kind }>;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/use/collapsible-input.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/use/collapsible-input.tsx
new file mode 100644
index 000000000..643f47c91
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/use/collapsible-input.tsx
@@ -0,0 +1,51 @@
+import type { ReactNode } from 'react';
+import { cn } from '@renderer/utils/utils';
+
+/**
+ * An input the page already filled in shows as one line, its label and its
+ * value, with a Change button. The deployer who accepts the value never
+ * sees the control; the one who wants another opens it.
+ */
+export function CollapsibleInput({
+ label,
+ summary,
+ collapsed,
+ onOpen,
+ disabled,
+ wrap = false,
+ children,
+}: {
+ label: string;
+ summary: string;
+ collapsed: boolean;
+ onOpen: () => void;
+ disabled?: boolean;
+ /** Let a long summary wrap instead of being cut. */
+ wrap?: boolean;
+ children: ReactNode;
+}) {
+ if (!collapsed) return <>{children}</>;
+ return (
+ <div className="flex items-center gap-3 rounded-[10px] border border-border px-3 py-2.5">
+ <span className="w-[104px] shrink-0 truncate text-[12.5px] font-medium">{label}</span>
+ <span
+ className={cn(
+ 'min-w-0 flex-1 font-mono text-[12.5px] text-foreground-muted',
+ wrap ? 'break-words' : 'truncate'
+ )}
+ title={summary}
+ >
+ {summary}
+ </span>
+ <button
+ type="button"
+ onClick={onOpen}
+ disabled={disabled}
+ aria-label={`Change ${label}`}
+ className="shrink-0 cursor-pointer text-xs text-foreground-muted underline underline-offset-2 hover:text-foreground disabled:cursor-default disabled:opacity-50"
+ >
+ Change
+ </button>
+ </div>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/use/creates-rail.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/use/creates-rail.tsx
new file mode 100644
index 000000000..4376a102c
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/use/creates-rail.tsx
@@ -0,0 +1,354 @@
+import { Check, ChevronRight, DoorOpen, Loader2, TriangleAlert } from 'lucide-react';
+import { useState } from 'react';
+import type { ParsedAgentEntry } from '@main/core/agent-templates/template-document';
+import type { TemplateRoom } from '@main/core/room-templates/controller';
+import { LocalDirectorySelector } from '@renderer/features/locations/components/add-agent-modal/local-directory-selector';
+import { AgentField, type EntityLists } from '@renderer/features/room-templates/entity-fields';
+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
+import { Input } from '@renderer/lib/ui/input';
+import { SegmentedControl } from '@renderer/lib/ui/segmented-control';
+import { Switch } from '@renderer/lib/ui/switch';
+import { cn } from '@renderer/utils/utils';
+import { hasPlaceholder, interpolate, type Values } from './use-template-model';
+
+export type SlotStatus = 'idle' | 'creating' | 'created' | 'failed';
+
+/**
+ * One agent entry of the template and the choices made for it on the Use
+ * page: create it or use an existing agent, its working directory, whether
+ * to clone its repository, and its creation status.
+ */
+export type AgentSlot = {
+ entry: ParsedAgentEntry;
+
+ mode: 'new' | 'existing';
+ /** The existing agent's name, when `mode` is `existing`. */
+ existingName: string;
+ /** The working directory for a new agent: a local path, or a path on the host. */
+ dir: string;
+ /** Whether the deployer chose the directory; a chosen path stays put when the name changes. */
+ dirPicked: boolean;
+ cloneRepo: boolean;
+ status: SlotStatus;
+ error: string | null;
+ /** Null until the agent is created, then the name it was created under. */
+ createdName: string | null;
+ createdSwitchAgentId: string | null;
+ /** The call in progress, or the one that failed, while the agent is being created. */
+ step: SlotStep | null;
+ /** Why the repository could not be cloned. The run carries on without the clone. */
+ cloneWarning: string | null;
+};
+
+/** The calls that make one agent: its directory (and clone), the agent, who may address it. */
+export type SlotStep = 'prepare' | 'create' | 'policy';
+
+export function newSlot(entry: ParsedAgentEntry): AgentSlot {
+ return {
+ entry,
+ mode: 'new',
+ existingName: '',
+ dir: '',
+ dirPicked: false,
+ cloneRepo: true,
+ status: 'idle',
+ error: null,
+ createdName: null,
+ createdSwitchAgentId: null,
+ step: null,
+ cloneWarning: null,
+ };
+}
+
+function StatusLine({ slot }: { slot: AgentSlot }) {
+ if (slot.status === 'creating')
+ return (
+ <span className="flex items-center gap-1 text-[11px] text-foreground-muted">
+ <Loader2 className="size-3 animate-spin" /> Creating…
+ </span>
+ );
+ if (slot.status === 'created')
+ return (
+ <span className="flex items-center gap-1 text-[11px] text-emerald-700 dark:text-emerald-400">
+ <Check className="size-3" /> Created
+ </span>
+ );
+ if (slot.status === 'failed')
+ return (
+ <span className="flex items-center gap-1 text-[11px] text-destructive">
+ <TriangleAlert className="size-3" /> Failed
+ </span>
+ );
+ return null;
+}
+
+function Card({ children, className }: { children: React.ReactNode; className?: string }) {
+ return (
+ <div className={cn('rounded-[10px] border border-border bg-background p-3', className)}>
+ {children}
+ </div>
+ );
+}
+
+export function RoomCard({
+ room,
+ values,
+ renames,
+ bridgeName,
+ creatorIdentity,
+ status,
+ toggle,
+}: {
+ room: TemplateRoom;
+ values: Values;
+ /** Agent name as written in the template → the name the agent will have. */
+ renames: Record<string, string>;
+ bridgeName: string | null;
+ creatorIdentity: string | null;
+ status: SlotStatus;
+ /** For an agent template, whether to create the room. Null hides the toggle: the room is not optional, or creation has started. */
+ toggle: { checked: boolean; onChange: (checked: boolean) => void } | null;
+}) {
+ const fill = (s: string) =>
+ interpolate(renames[s] ?? s, { ...values, $creator: creatorIdentity ?? 'you' });
+ const name = room.name ? fill(room.name) : 'Unnamed room';
+ const members = [...room.agents, ...room.users].map(fill);
+ const note =
+ room.description?.trim() ||
+ (members.length > 0 ? `With ${members.join(', ')}` : 'A room with nobody in it yet');
+ return (
+ <Card>
+ <div className="flex items-center gap-3">
+ <span className="flex size-7 shrink-0 items-center justify-center rounded-lg bg-background-2 text-foreground-muted">
+ <DoorOpen className="size-3.5" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <div
+ className={cn(
+ 'truncate font-mono text-[13px] font-medium',
+ hasPlaceholder(name) ? 'text-foreground-passive' : 'text-foreground'
+ )}
+ >
+ {name}
+ </div>
+ <div className="mt-0.5 text-xs leading-snug text-foreground-muted">
+ {fill(note)}
+ {bridgeName ? ` · on ${bridgeName}` : ''}
+ </div>
+ </div>
+ <span className="shrink-0 text-[11px] text-foreground-passive">Room</span>
+ </div>
+ {toggle && (
+ <label className="mt-3 flex w-max cursor-pointer items-center gap-2 border-t border-border pt-3 text-xs text-foreground-muted">
+ <Switch size="sm" checked={toggle.checked} onCheckedChange={toggle.onChange} />
+ {toggle.checked
+ ? 'Create this room and start the agent in it'
+ : 'Agent only; add it to a room later'}
+ </label>
+ )}
+ {status !== 'idle' && (
+ <div className="mt-2">
+ <StatusLine slot={{ status } as AgentSlot} />
+ </div>
+ )}
+ </Card>
+ );
+}
+
+/** Where a new agent works: its directory, and whether the template's repository is cloned into it. */
+export function SlotDirectoryField({
+ slot,
+ onChange,
+ sshHost,
+ busy,
+}: {
+ slot: AgentSlot;
+ onChange: (next: AgentSlot) => void;
+ sshHost: string | null;
+ busy: boolean;
+}) {
+ return (
+ <>
+ <div className="flex flex-col gap-1">
+ <span className="text-[11px] text-foreground-passive">Directory</span>
+ {sshHost ? (
+ <Input
+ value={slot.dir}
+ disabled={busy}
+ placeholder="/home/agent/repo"
+ className="font-mono text-xs"
+ onChange={(e) => onChange({ ...slot, dir: e.target.value, dirPicked: true })}
+ />
+ ) : (
+ <LocalDirectorySelector
+ title="Choose the agent's working directory"
+ message="The agent runs from here. A suggested folder is created when the agent is."
+ path={slot.dir}
+ onPathChange={(dir) => onChange({ ...slot, dir, dirPicked: true })}
+ />
+ )}
+ </div>
+ {slot.entry.repoUrl && (
+ <label className="flex w-max cursor-pointer items-center gap-2 text-xs text-foreground-muted">
+ <Switch
+ size="sm"
+ checked={slot.cloneRepo}
+ onCheckedChange={(cloneRepo) => onChange({ ...slot, cloneRepo })}
+ />
+ Clone {slot.entry.repoUrl.replace(/^https?:\/\//, '')} into it
+ </label>
+ )}
+ </>
+ );
+}
+
+export function AgentSlotCard({
+ slot,
+ wantedName,
+ onChange,
+ lists,
+ locationLabel,
+ choice = true,
+}: {
+ slot: AgentSlot;
+ /** The name the agent is created under, as far as the inputs resolve it. */
+ wantedName: string;
+ onChange: (next: AgentSlot) => void;
+ lists: EntityLists;
+ /** The run location's display name, shown under the existing-agent picker. */
+ locationLabel: string;
+ /** Whether the deployer may point the slot at an existing agent. An agent
+ * template always makes a new one, so its card offers no choice. */
+ choice?: boolean;
+}) {
+ const unresolved = hasPlaceholder(wantedName) || wantedName === '';
+ const shownName =
+ slot.mode === 'existing'
+ ? slot.existingName || 'Pick an agent'
+ : (slot.createdName ?? wantedName);
+ return (
+ <Card className={cn(slot.status === 'failed' && 'border-destructive/50')}>
+ <div className="flex items-center gap-3">
+ <AgentAvatar name={shownName || 'agent'} iconUrl={null} size={28} />
+ <div className="min-w-0 flex-1">
+ <div
+ className={cn(
+ 'truncate font-mono text-[13px] font-medium',
+ unresolved && slot.mode === 'new' ? 'text-foreground-passive' : 'text-foreground'
+ )}
+ >
+ {shownName || 'Named by an input'}
+ </div>
+ <div className="mt-0.5 truncate text-xs leading-snug text-foreground-muted">
+ {slot.entry.description || 'An agent with its own instructions'}
+ </div>
+ </div>
+ <span className="shrink-0 text-[11px] text-foreground-passive">Agent</span>
+ </div>
+
+ {/* An agent that exists can no longer change how it is made, even when a
+ later step for it failed. */}
+ {(slot.status === 'idle' || slot.status === 'failed') &&
+ slot.createdName === null &&
+ choice && (
+ <div className="mt-3 flex flex-col gap-2.5 border-t border-border pt-3">
+ <SegmentedControl
+ value={slot.mode}
+ onChange={(mode) => onChange({ ...slot, mode })}
+ options={[
+ { value: 'new', label: 'New agent' },
+ { value: 'existing', label: 'Existing agent' },
+ ]}
+ ariaLabel={`How to fill ${wantedName || 'this agent'}`}
+ className="w-max"
+ />
+ {slot.mode === 'existing' ? (
+ <div className="flex flex-col gap-1.5">
+ <AgentField
+ value={slot.existingName}
+ onChange={(name) => onChange({ ...slot, existingName: name })}
+ lists={lists}
+ />
+ <p className="text-[11px] text-foreground-passive">
+ {lists.agents.length === 0
+ ? `No agent of yours runs on ${locationLabel} yet.`
+ : `Agents of yours that run on ${locationLabel}.`}
+ </p>
+ </div>
+ ) : null}
+ </div>
+ )}
+ {slot.status !== 'idle' && (
+ <div className="mt-2 flex flex-col gap-1">
+ <StatusLine slot={slot} />
+ {slot.error && <p className="text-xs text-destructive">{slot.error}</p>}
+ </div>
+ )}
+ </Card>
+ );
+}
+
+/** The template document with the inputs filled in, one line per row, with the changed lines highlighted. */
+export function ResolvedDocument({
+ yamlText,
+ values,
+ renames,
+}: {
+ yamlText: string;
+ values: Values;
+ renames: Record<string, string>;
+}) {
+ const [open, setOpen] = useState(false);
+ const renamed = Object.entries(renames).reduce(
+ (text, [from, to]) => text.split(from).join(to),
+ yamlText
+ );
+ const lines = renamed.replace(/\n$/, '').split('\n');
+ return (
+ <div className="flex flex-col gap-2.5">
+ <button
+ type="button"
+ onClick={() => setOpen((o) => !o)}
+ aria-expanded={open}
+ className="flex w-max cursor-pointer items-center gap-2 text-[12.5px] font-medium text-foreground-muted hover:text-foreground"
+ >
+ <ChevronRight
+ className={cn(
+ 'size-3.5 text-foreground-passive transition-transform',
+ open && 'rotate-90'
+ )}
+ />
+ {open ? 'Hide the resolved document' : 'Show the resolved document'}
+ </button>
+ {open && (
+ <div className="overflow-x-auto rounded-[10px] border border-border bg-background p-3 font-mono text-xs leading-relaxed">
+ {lines.map((line, i) => {
+ const filled = interpolate(line, values);
+ const changed = filled !== line;
+ return (
+ <div
+ key={i}
+ className={cn(
+ 'flex gap-3 rounded-sm whitespace-pre-wrap',
+ changed && 'bg-[var(--sel-soft)]'
+ )}
+ >
+ <span className="w-5 shrink-0 text-right text-foreground-passive opacity-60">
+ {i + 1}
+ </span>
+ <span
+ className={cn(
+ 'min-w-0 flex-1',
+ hasPlaceholder(filled) ? 'text-foreground-passive' : 'text-foreground'
+ )}
+ >
+ {filled}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/use/creating-screen.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/use/creating-screen.tsx
new file mode 100644
index 000000000..9a7ad558e
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/use/creating-screen.tsx
@@ -0,0 +1,139 @@
+import { Check, Circle, Loader2, TriangleAlert } from 'lucide-react';
+import { Button } from '@renderer/lib/ui/button';
+import { cn } from '@renderer/utils/utils';
+import type { CreateStep, CreateStepStatus } from './use-template-model';
+
+function StepIcon({ status }: { status: CreateStepStatus }) {
+ if (status === 'running') return <Loader2 className="size-4 animate-spin text-foreground" />;
+ if (status === 'done')
+ return (
+ <span className="flex size-4 items-center justify-center rounded-full bg-emerald-600 text-white dark:bg-emerald-500">
+ <Check className="size-2.5" strokeWidth={3.5} />
+ </span>
+ );
+ if (status === 'failed') return <TriangleAlert className="size-4 text-destructive" />;
+ return <Circle className="size-4 text-foreground-passive opacity-50" />;
+}
+
+const STATUS_WORD: Record<CreateStepStatus, string> = {
+ waiting: 'waiting',
+ running: 'working',
+ done: 'done',
+ failed: 'failed',
+};
+
+/**
+ * Shown in place of the form from the moment Create is pressed: the steps
+ * of the run, how far it is, and, when a step fails, the way on. The form
+ * is out of reach while it shows, so a half-made template cannot be edited
+ * underneath a run.
+ */
+export function CreatingScreen({
+ templateName,
+ phase,
+ steps,
+ error,
+ doneDetail,
+ onRetry,
+ onBack,
+}: {
+ templateName: string;
+ phase: 'creating' | 'done' | 'failed';
+ steps: CreateStep[];
+ error: string | null;
+ /** Where the page goes next, shown under the finished heading. */
+ doneDetail: string | null;
+ onRetry: () => void;
+ onBack: () => void;
+}) {
+ const done = steps.filter((s) => s.status === 'done').length;
+ const progress = phase === 'done' ? 1 : steps.length === 0 ? 0 : done / steps.length;
+ return (
+ <div
+ className="flex min-h-0 flex-1 flex-col items-center overflow-auto px-8 py-14"
+ role="status"
+ aria-live="polite"
+ >
+ <div className="flex w-full max-w-[440px] flex-col gap-6">
+ <div className="flex flex-col items-center gap-2 text-center">
+ {phase === 'done' && (
+ <span className="flex size-11 animate-in items-center justify-center rounded-full bg-emerald-600 text-white duration-300 zoom-in-50 motion-reduce:animate-none dark:bg-emerald-500">
+ <Check className="size-6" strokeWidth={3} />
+ </span>
+ )}
+ <h3 className="text-lg font-semibold tracking-tight">
+ {phase === 'done'
+ ? `${templateName} is ready`
+ : phase === 'failed'
+ ? 'Stopped at one step'
+ : `Creating ${templateName}`}
+ </h3>
+ <p className="text-[13px] text-foreground-muted">
+ {phase === 'done'
+ ? (doneDetail ?? 'Opening it…')
+ : phase === 'failed'
+ ? done > 0
+ ? 'What was created stays created.'
+ : 'Nothing was created.'
+ : 'This takes a few seconds.'}
+ </p>
+ </div>
+
+ <div className="h-1 overflow-hidden rounded-full bg-background-2">
+ <div
+ className={cn(
+ 'h-full rounded-full transition-[width] duration-500 ease-out motion-reduce:transition-none',
+ phase === 'failed' ? 'bg-destructive' : 'bg-emerald-600 dark:bg-emerald-500'
+ )}
+ style={{ width: `${Math.max(progress, 0.04) * 100}%` }}
+ />
+ </div>
+
+ <ul className="flex flex-col divide-y divide-border rounded-[10px] border border-border bg-background">
+ {steps.map((step) => (
+ <li key={step.key} className="flex flex-col gap-1 px-3.5 py-2.5">
+ <div className="flex items-center gap-3">
+ <StepIcon status={step.status} />
+ <span
+ className={cn(
+ 'min-w-0 flex-1 truncate text-[13px]',
+ step.status === 'waiting' ? 'text-foreground-muted' : 'text-foreground'
+ )}
+ >
+ {step.label}
+ </span>
+ <span
+ className={cn(
+ 'shrink-0 text-[11px]',
+ step.status === 'failed' ? 'text-destructive' : 'text-foreground-passive'
+ )}
+ >
+ {STATUS_WORD[step.status]}
+ </span>
+ </div>
+ {step.warning && (
+ <p className="pl-7 text-[11.5px] text-amber-700 dark:text-amber-400">
+ {step.warning}
+ </p>
+ )}
+ </li>
+ ))}
+ </ul>
+
+ {phase === 'failed' && (
+ <div className="flex flex-col gap-3">
+ {error && <p className="text-[13px] text-destructive">{error}</p>}
+ <div className="flex items-center justify-center gap-2">
+ <Button size="sm" onClick={onRetry}>
+ Retry remaining steps
+ </Button>
+ <Button size="sm" variant="outline" onClick={onBack}>
+ Back to the form
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/use/param-field.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/use/param-field.tsx
new file mode 100644
index 000000000..54ce2b36f
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/use/param-field.tsx
@@ -0,0 +1,226 @@
+import type { ParamSpec } from '@main/core/room-templates/controller';
+import { AgentTypePicker } from '@renderer/features/locations/components/add-agent-modal/agent-type-picker';
+import { LocalDirectorySelector } from '@renderer/features/locations/components/add-agent-modal/local-directory-selector';
+import {
+ AgentField,
+ BridgeField,
+ type EntityLists,
+ UserField,
+} from '@renderer/features/room-templates/entity-fields';
+import { Input } from '@renderer/lib/ui/input';
+import { Switch } from '@renderer/lib/ui/switch';
+import { Textarea } from '@renderer/lib/ui/textarea';
+import { cn } from '@renderer/utils/utils';
+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
+import { RoomChoiceField } from './room-pick-field';
+import { RunLocationSelect } from './run-location-select';
+import { isChain, isRequired, paramLabel, typeLabel } from './use-template-model';
+
+/** One input of a template on the Use page, with the control its type calls for. */
+export function ParamField({
+ param,
+ value,
+ onChange,
+ error,
+ lists,
+ sshHost,
+ hosts,
+ newRoom,
+ disabled,
+ onNavigateAway,
+}: {
+ param: ParamSpec;
+ value: string | number | boolean;
+ onChange: (v: string | number | boolean) => void;
+ error: string | null;
+ lists: EntityLists;
+ /** The machine a `provider` must be installed on and a `directory` lives on: an SSH host, or null for this computer. */
+ sshHost: string | null;
+ /** The SSH hosts a `location` param may name. */
+ hosts: readonly { sshHost: string; name: string }[];
+ /** For a `room` param: the room the template creates, offered as `$new`. */
+ newRoom: { name: string; bridgeType: string | null } | null;
+ disabled?: boolean;
+ onNavigateAway: () => void;
+}) {
+ const required = isRequired(param);
+ const strVal = typeof value === 'string' ? value : String(value ?? '');
+ const showDefault = param.default !== null && !isChain(param) && param.type !== 'boolean';
+
+ let control: React.ReactNode;
+ if (param.type === 'boolean') {
+ control = (
+ <label className="flex w-max cursor-pointer items-center gap-2.5 text-sm text-foreground-muted">
+ <Switch
+ checked={Boolean(value)}
+ onCheckedChange={(checked) => onChange(checked)}
+ disabled={disabled}
+ />
+ {value ? 'Yes' : 'No'}
+ </label>
+ );
+ } else if (param.type === 'provider') {
+ control = (
+ <AgentTypePicker
+ value={(strVal || null) as AgentProviderId | null}
+ onChange={(id) => onChange(id)}
+ sshHost={sshHost ?? undefined}
+ onNavigateAway={onNavigateAway}
+ />
+ );
+ } else if (param.type === 'location') {
+ control = (
+ <RunLocationSelect
+ value={strVal || 'local'}
+ onChange={onChange}
+ hosts={hosts}
+ disabled={disabled}
+ />
+ );
+ } else if (param.type === 'directory') {
+ control = sshHost ? (
+ <Input
+ value={strVal}
+ disabled={disabled}
+ placeholder="/home/agent/repo"
+ className="font-mono text-xs"
+ onChange={(e) => onChange(e.target.value)}
+ />
+ ) : (
+ <LocalDirectorySelector
+ title="Choose the agent's working directory"
+ message="The agent runs from here. The folder is created when the agent is."
+ path={strVal}
+ onPathChange={onChange}
+ />
+ );
+ } else if (param.type === 'room') {
+ control = (
+ <RoomChoiceField
+ rooms={lists.rooms}
+ loading={lists.roomsLoading}
+ newRoom={newRoom}
+ value={strVal}
+ onChange={onChange}
+ />
+ );
+ } else if (param.type === 'agent') {
+ control = <AgentField value={strVal} onChange={onChange} lists={lists} />;
+ } else if (param.type === 'bridge') {
+ control = <BridgeField value={strVal} onChange={onChange} lists={lists} />;
+ } else if (param.type === 'user') {
+ control = <UserField value={strVal} onChange={onChange} lists={lists} />;
+ } else if (param.type === 'enum' && param.enum) {
+ control = (
+ <div className="flex flex-wrap gap-1.5">
+ {param.enum.map((opt) => {
+ const on = strVal === opt;
+ return (
+ <button
+ key={opt}
+ type="button"
+ aria-pressed={on}
+ disabled={disabled}
+ onClick={() => onChange(on ? '' : opt)}
+ className={cn(
+ 'h-[30px] cursor-pointer rounded-lg border px-2.5 font-mono text-xs transition-colors',
+ on
+ ? 'border-foreground bg-[var(--sel)] text-foreground'
+ : 'border-border text-foreground-muted hover:bg-[var(--sel-soft)]'
+ )}
+ >
+ {opt}
+ </button>
+ );
+ })}
+ </div>
+ );
+ } else if (param.type === 'number') {
+ control = (
+ <Input
+ type="number"
+ className="w-32 font-mono"
+ value={value === '' ? '' : Number(value)}
+ min={param.min ?? undefined}
+ max={param.max ?? undefined}
+ disabled={disabled}
+ onChange={(e) => onChange(e.target.value === '' ? '' : Number(e.target.value))}
+ placeholder={showDefault ? String(param.default) : param.name}
+ aria-invalid={error ? true : undefined}
+ />
+ );
+ } else if (param.multiline) {
+ control = (
+ <Textarea
+ value={strVal}
+ disabled={disabled}
+ onChange={(e) => onChange(e.target.value)}
+ className="min-h-40 resize-y font-mono text-xs"
+ aria-invalid={error ? true : undefined}
+ />
+ );
+ } else {
+ control = (
+ <Input
+ value={strVal}
+ className={param.label ? undefined : 'font-mono'}
+ disabled={disabled}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={showDefault ? String(param.default) : param.name}
+ aria-invalid={error ? true : undefined}
+ />
+ );
+ }
+
+ const label = paramLabel(param);
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-baseline gap-2">
+ <span
+ className={cn(
+ 'text-[12.5px] font-medium text-foreground',
+ label === param.name && 'font-mono'
+ )}
+ >
+ {label}
+ </span>
+ <span className="text-[11px] text-foreground-passive">{typeLabel(param.type)}</span>
+ <span className="flex-1" />
+ <span
+ className={cn(
+ 'text-[11px]',
+ required ? 'text-amber-600 dark:text-amber-400' : 'text-foreground-passive'
+ )}
+ >
+ {required ? 'Required' : 'Optional'}
+ </span>
+ </div>
+ {param.description && (
+ <p className="text-xs leading-relaxed text-foreground-muted">{param.description}</p>
+ )}
+ {control}
+ {showDefault && (
+ <p className="text-[11.5px] text-foreground-passive">Defaults to {String(param.default)}</p>
+ )}
+ {isChain(param) && (
+ <p className="text-[11.5px] text-foreground-passive">
+ The template tries{' '}
+ {param.default
+ .map((c) => (c === '$first' ? 'the first one' : c === '$new' ? 'its own room' : c))
+ .join(', then ')}
+ .
+ </p>
+ )}
+ {param.type === 'bridge' && !required && isEmpty(value) && (
+ <p className="text-[11.5px] text-foreground-passive">
+ Left empty, the room is created on the server's default messaging app.
+ </p>
+ )}
+ {error && <p className="text-xs text-destructive">{error}</p>}
+ </div>
+ );
+}
+
+function isEmpty(value: string | number | boolean): boolean {
+ return value === '';
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/use/room-pick-field.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/use/room-pick-field.tsx
new file mode 100644
index 000000000..4f70768d2
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/use/room-pick-field.tsx
@@ -0,0 +1,70 @@
+import { TileGrid } from '@renderer/features/room-templates/entity-fields';
+import { PickerCombobox } from '@renderer/lib/components/picker-combobox';
+import { ChosenRoomTile, type RoomPick, RoomPickerRow } from '@renderer/lib/components/room-picker';
+import { NEW } from '@shared/core/switch-servers/room-template-params';
+
+/**
+ * The room an agent works in, for a `room` param: one of the workspace's
+ * rooms by name, or `$new` for the room the template creates, offered when
+ * the template describes one.
+ */
+export function RoomChoiceField({
+ rooms,
+ loading,
+ newRoom,
+ value,
+ onChange,
+}: {
+ rooms: RoomPick[];
+ loading: boolean;
+ /** The template's own room, resolved as far as the inputs allow, or null when it has none. */
+ newRoom: { name: string; bridgeType: string | null } | null;
+ /** A room name, `$new`, or empty. */
+ value: string;
+ onChange: (value: string) => void;
+}) {
+ const newPick: RoomPick | null = newRoom
+ ? { id: NEW, name: newRoom.name, bridgeType: newRoom.bridgeType }
+ : null;
+ if (value === NEW && newPick) {
+ return (
+ <TileGrid>
+ <ChosenRoomTile room={newPick} subtitle="New room" onRemove={() => onChange('')} />
+ </TileGrid>
+ );
+ }
+ if (value !== '') {
+ const found = rooms.find((r) => r.name === value);
+ return (
+ <TileGrid>
+ <ChosenRoomTile
+ room={found ?? { id: value, name: value, bridgeType: null }}
+ subtitle={found ? undefined : 'Not on this server'}
+ subtitleTone={found ? undefined : 'warning'}
+ onRemove={() => onChange('')}
+ />
+ </TileGrid>
+ );
+ }
+ const items = newPick ? [newPick, ...rooms] : rooms;
+ return (
+ <PickerCombobox
+ items={items}
+ onPick={(room) => onChange(room.id === NEW ? NEW : room.name)}
+ searchText={(room) => room.name}
+ renderItem={(room) =>
+ room.id === NEW ? (
+ <>
+ <span className="min-w-0 flex-1 truncate">{room.name}</span>
+ <span className="shrink-0 text-xs text-foreground-muted">New room</span>
+ </>
+ ) : (
+ <RoomPickerRow room={room} />
+ )
+ }
+ disabled={loading}
+ placeholder={loading ? 'Loading rooms…' : 'Search rooms…'}
+ emptyText="No rooms found"
+ />
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/use/run-location-select.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/use/run-location-select.tsx
new file mode 100644
index 000000000..0a6c0d0fe
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/use/run-location-select.tsx
@@ -0,0 +1,90 @@
+import { useQuery } from '@tanstack/react-query';
+import { Monitor, Server } from 'lucide-react';
+import { useMemo } from 'react';
+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { rpc } from '@renderer/lib/ipc';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@renderer/lib/ui/select';
+
+export const LOCAL_RUN_LOCATION = 'local';
+
+/**
+ * The SSH hosts an agent for `serverId` may run on. A server the Console
+ * manages is reachable only from certain machines: one managed on a host is
+ * reachable from this computer and from that host, one managed locally from
+ * this computer only. A server the Console does not manage has no restriction.
+ */
+export function useAllowedHosts(serverId: string | null) {
+ const { data: remoteHosts } = useQuery({
+ queryKey: ['remote-hosts'],
+ queryFn: () => rpc.remoteHosts.listHosts(),
+ });
+ const server = switchServersStore.servers.find((s) => s.id === serverId) ?? null;
+ const kind = server?.managementKind ?? null;
+ const host = server?.sshHost ?? null;
+ return useMemo(
+ () =>
+ (remoteHosts ?? []).filter((h) =>
+ kind === 'remote' ? h.sshHost === host : kind !== 'local'
+ ),
+ [remoteHosts, kind, host]
+ );
+}
+
+export function runLocationLabel(
+ value: string,
+ hosts: readonly { sshHost: string; name: string }[]
+): string {
+ if (value === LOCAL_RUN_LOCATION) return 'This computer';
+ return hosts.find((h) => h.sshHost === value)?.name ?? value;
+}
+
+export function RunLocationSelect({
+ value,
+ onChange,
+ hosts,
+ disabled,
+}: {
+ value: string;
+ onChange: (value: string) => void;
+ hosts: readonly { sshHost: string; name: string }[];
+ disabled?: boolean;
+}) {
+ return (
+ <Select
+ value={value}
+ onValueChange={(v) => onChange(v ?? LOCAL_RUN_LOCATION)}
+ disabled={disabled}
+ >
+ <SelectTrigger className="w-full" aria-label="Run location">
+ <SelectValue>
+ {value === LOCAL_RUN_LOCATION ? (
+ <Monitor className="size-4 text-foreground-muted" />
+ ) : (
+ <Server className="size-4 text-foreground-muted" />
+ )}
+ <span className="truncate">{runLocationLabel(value, hosts)}</span>
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={LOCAL_RUN_LOCATION}>
+ <Monitor className="size-4 text-foreground-muted" />
+ <span className="flex-1">This computer</span>
+ <span className="text-xs text-foreground-muted">local</span>
+ </SelectItem>
+ {hosts.map((h) => (
+ <SelectItem key={h.sshHost} value={h.sshHost}>
+ <Server className="size-4 text-foreground-muted" />
+ <span className="flex-1 truncate">{h.name}</span>
+ <span className="text-xs text-foreground-muted">ssh</span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/use/use-template-model.test.ts b/console/apps/switch-console-desktop/src/renderer/features/templates/use/use-template-model.test.ts
new file mode 100644
index 000000000..fe969851b
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/use/use-template-model.test.ts
@@ -0,0 +1,151 @@
+import { describe, expect, it } from 'vitest';
+import type { ParamSpec } from '@main/core/room-templates/controller';
+import {
+ agentCreateSteps,
+ bridgeCandidates,
+ paramLabel,
+ resolveChain,
+ sectionOf,
+ serverInputs,
+ valueProblem,
+} from './use-template-model';
+
+function param(overrides: Partial<ParamSpec>): ParamSpec {
+ return {
+ name: 'p',
+ type: 'string',
+ description: null,
+ label: null,
+ default: null,
+ required: true,
+ input: 'ask',
+ enum: null,
+ multiline: false,
+ pattern: null,
+ min: null,
+ max: null,
+ ...overrides,
+ };
+}
+
+describe('bridgeCandidates', () => {
+ it('puts the default app first, then the rest by name, and leaves out stopped ones', () => {
+ expect(
+ bridgeCandidates([
+ { displayName: 'Teams', status: 'active', isDefault: false },
+ { displayName: 'Slack', status: 'active', isDefault: true },
+ { displayName: 'Discord', status: 'stopped', isDefault: false },
+ { displayName: 'Mattermost', status: 'active', isDefault: false },
+ ])
+ ).toEqual(['Slack', 'Mattermost', 'Teams']);
+ });
+});
+
+describe('resolveChain', () => {
+ it('takes the first candidate the server has, in the order the template wrote', () => {
+ const p = param({ type: 'bridge', default: ['Teams', 'Mattermost', '$first'] });
+ expect(resolveChain(p, ['Slack', 'Mattermost'])).toBe('Mattermost');
+ expect(resolveChain(p, ['Slack'])).toBe('Slack');
+ expect(resolveChain(p, [])).toBeNull();
+ });
+
+ it('resolves $new only for a room param when the template describes a room', () => {
+ const p = param({ type: 'room', default: ['$new'] });
+ expect(resolveChain(p, ['lobby'], true)).toBe('$new');
+ expect(resolveChain(p, ['lobby'], false)).toBeNull();
+ expect(resolveChain(param({ type: 'bridge', default: ['$new'] }), ['Slack'])).toBeNull();
+ });
+
+ it('is null for a plain default', () => {
+ expect(resolveChain(param({ type: 'bridge', default: 'Slack' }), ['Slack'])).toBeNull();
+ });
+});
+
+describe('valueProblem', () => {
+ it('checks a string against its pattern as a whole', () => {
+ const p = param({ pattern: '[a-z]+' });
+ expect(valueProblem(p, 'alpha')).toBeNull();
+ expect(valueProblem(p, 'Alpha1')).toMatch(/Must match/);
+ expect(valueProblem(p, '')).toBeNull();
+ });
+
+ it('checks a number against its bounds', () => {
+ const p = param({ type: 'number', min: 1, max: 5 });
+ expect(valueProblem(p, 3)).toBeNull();
+ expect(valueProblem(p, 0)).toBe('Must be at least 1');
+ expect(valueProblem(p, 9)).toBe('Must be at most 5');
+ });
+});
+
+describe('serverInputs', () => {
+ it('sends only the params the server document declares, never a Console type', () => {
+ const params = [
+ param({ name: 'bridge', type: 'bridge' }),
+ param({ name: 'provider', type: 'provider' }),
+ param({ name: 'name' }),
+ param({ name: 'size', type: 'number' }),
+ ];
+ const values = { bridge: 'Slack', provider: 'claude', name: 'Expert', size: '3' };
+ expect(serverInputs(params, values, new Set(['bridge', 'size', 'provider']))).toEqual({
+ bridge: 'Slack',
+ size: 3,
+ });
+ });
+});
+
+describe('sectionOf', () => {
+ const agents = [['{name}', '{provider}'], ['{other}']];
+ const room = 'name: "Ask {agent}"\nbridge: "{bridge}"\n';
+ it('puts a param with the agent that reads it, and the rest with the room', () => {
+ expect(sectionOf(param({ name: 'provider' }), agents, room)).toEqual({
+ section: 'agent',
+ index: 0,
+ });
+ expect(sectionOf(param({ name: 'other' }), agents, room)).toEqual({
+ section: 'agent',
+ index: 1,
+ });
+ expect(sectionOf(param({ name: 'bridge' }), agents, room)).toEqual({ section: 'room' });
+ });
+
+ it('keeps a room param with the room even when an agent joins it', () => {
+ expect(sectionOf(param({ name: 'where', type: 'room' }), [['{where}']], room)).toEqual({
+ section: 'room',
+ });
+ });
+});
+
+describe('paramLabel', () => {
+ it('prefers the template label, then a readable name for the common types', () => {
+ expect(paramLabel(param({ name: 'bridge', type: 'bridge', label: 'Chat app' }))).toBe(
+ 'Chat app'
+ );
+ expect(paramLabel(param({ name: 'bridge', type: 'bridge' }))).toBe('Messaging app');
+ expect(paramLabel(param({ name: 'team' }))).toBe('team');
+ });
+});
+
+describe('agentCreateSteps', () => {
+ const base = { name: 'a', clones: false, setsPolicy: true, cloneWarning: null } as const;
+
+ it('marks the rows before the call in progress done, the one at it running', () => {
+ const steps = agentCreateSteps(0, { ...base, status: 'creating', step: 'create' });
+ expect(steps.map((s) => s.status)).toEqual(['done', 'running', 'waiting']);
+ });
+
+ it('marks every row done for a created agent, whatever step it stopped on', () => {
+ const steps = agentCreateSteps(0, { ...base, status: 'created', step: 'policy' });
+ expect(steps.map((s) => s.status)).toEqual(['done', 'done', 'done']);
+ });
+
+ it('marks the failed call failed and leaves the rest waiting', () => {
+ const steps = agentCreateSteps(0, { ...base, status: 'failed', step: 'policy' });
+ expect(steps.map((s) => s.status)).toEqual(['done', 'done', 'failed']);
+ });
+
+ it('has no policy row when the template sets no addressing', () => {
+ expect(
+ agentCreateSteps(0, { ...base, setsPolicy: false, status: 'idle', step: null })
+ ).toHaveLength(2);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/use/use-template-model.ts b/console/apps/switch-console-desktop/src/renderer/features/templates/use/use-template-model.ts
new file mode 100644
index 000000000..1e683a86c
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/use/use-template-model.ts
@@ -0,0 +1,249 @@
+import type { ParamSpec } from '@main/core/room-templates/controller';
+import {
+ FIRST,
+ NEW,
+ type ParamType,
+ isConsoleParamType,
+} from '@shared/core/switch-servers/room-template-params';
+import type { SlotStatus, SlotStep } from './creates-rail';
+
+export type Values = Record<string, string | number | boolean>;
+
+/** Fill `{param}` and `{$builtin}` placeholders from `values`. A placeholder with no value yet is left as written. */
+export function interpolate(template: string, values: Values): string {
+ return template.replace(/\{(\$?\w+)\}/g, (match, key: string) => {
+ const val = values[key];
+ return val !== undefined && val !== '' ? String(val) : match;
+ });
+}
+
+export function hasPlaceholder(text: string): boolean {
+ return /\{\$?\w+\}/.test(text);
+}
+
+/** Every `{name}` placeholder written in `text`, without the braces. */
+export function placeholdersIn(text: string): string[] {
+ return [...text.matchAll(/\{(\$?\w+)\}/g)].map((m) => m[1]);
+}
+
+export function typeLabel(type: ParamType): string {
+ switch (type) {
+ case 'string':
+ return 'text';
+ case 'boolean':
+ return 'yes / no';
+ case 'enum':
+ return 'one of';
+ default:
+ return type;
+ }
+}
+
+/** The name of the input on the form: the template's `label`, else a
+ * readable name for the common types, else the param key. */
+export function paramLabel(param: ParamSpec): string {
+ if (param.label) return param.label;
+ switch (param.type) {
+ case 'bridge':
+ return 'Messaging app';
+ case 'provider':
+ return 'Provider';
+ case 'location':
+ return 'Runs on';
+ case 'directory':
+ return 'Directory';
+ case 'room':
+ return 'Room';
+ default:
+ return param.name;
+ }
+}
+
+/** Whether the value may not be empty at Create. Read from the template. */
+export function isRequired(param: ParamSpec): boolean {
+ return param.required;
+}
+
+/** Whether the default is a chain of candidates rather than a value. */
+export function isChain(param: ParamSpec): param is ParamSpec & { default: string[] } {
+ return Array.isArray(param.default);
+}
+
+/** Each param's starting value: its default, `false` for a boolean without
+ * one, empty for the rest. A chain starts empty and `resolveChain` fills it
+ * once the candidates are known. */
+export function defaultsFor(params: ParamSpec[]): Values {
+ const defaults: Values = {};
+ for (const param of params) {
+ if (param.default !== null && !Array.isArray(param.default))
+ defaults[param.name] = param.default;
+ else if (param.type === 'boolean') defaults[param.name] = false;
+ else defaults[param.name] = '';
+ }
+ return defaults;
+}
+
+export function isEmpty(value: string | number | boolean | undefined): boolean {
+ return value === undefined || value === '';
+}
+
+export function missingParams(params: ParamSpec[], values: Values): ParamSpec[] {
+ return params.filter((p) => isRequired(p) && isEmpty(values[p.name]));
+}
+
+/** What is wrong with a value, by the template's own rules, or null. */
+export function valueProblem(param: ParamSpec, value: string | number | boolean): string | null {
+ if (isEmpty(value)) return null;
+ if (param.type === 'string' && param.pattern !== null) {
+ let re: RegExp;
+ try {
+ re = new RegExp(`^(?:${param.pattern})$`);
+ } catch {
+ return null;
+ }
+ if (!re.test(String(value))) return `Must match ${param.pattern}`;
+ }
+ if (param.type === 'number' && typeof value === 'number') {
+ if (param.min !== null && value < param.min) return `Must be at least ${param.min}`;
+ if (param.max !== null && value > param.max) return `Must be at most ${param.max}`;
+ }
+ return null;
+}
+
+/**
+ * The inputs sent to the server: every filled param the server document
+ * declares, with numbers converted. Params of a Console type are never sent,
+ * nor those only an agent entry reads (`serverNames` says which are left).
+ */
+export function serverInputs(
+ params: ParamSpec[],
+ values: Values,
+ serverNames: Set<string>
+): Values {
+ const inputs: Values = {};
+ for (const param of params) {
+ if (isConsoleParamType(param.type) || !serverNames.has(param.name)) continue;
+ const val = values[param.name];
+ if (isEmpty(val)) continue;
+ inputs[param.name] = param.type === 'number' ? Number(val) : (val as string | boolean);
+ }
+ return inputs;
+}
+
+/** The messaging apps a room can be created on, the server's default first, then by name. */
+export function bridgeCandidates(
+ bridges: { displayName: string; status: string; isDefault: boolean }[]
+): string[] {
+ return bridges
+ .filter((b) => b.status === 'active')
+ .sort(
+ (a, b) =>
+ Number(b.isDefault) - Number(a.isDefault) || a.displayName.localeCompare(b.displayName)
+ )
+ .map((b) => b.displayName);
+}
+
+/**
+ * The value a chain resolves to: the first candidate the server or the
+ * Console has, `$first` standing for the first of `candidates`, `$new` for
+ * the template's own room when `hasNewRoom`. Null when nothing matches.
+ */
+export function resolveChain(
+ param: ParamSpec,
+ candidates: string[],
+ hasNewRoom = false
+): string | null {
+ if (!isChain(param)) return null;
+ for (const candidate of param.default) {
+ if (candidate === FIRST) {
+ if (candidates.length > 0) return candidates[0];
+ } else if (candidate === NEW) {
+ if (param.type === 'room' && hasNewRoom) return NEW;
+ } else if (candidates.includes(candidate)) {
+ return candidate;
+ }
+ }
+ return null;
+}
+
+/** Which section of the page a param belongs to: the agent it is written
+ * into, or the room part. A `room` param always sits with the room, since
+ * it says where the agent works; a param used by both sits with the agent. */
+export function sectionOf(
+ param: ParamSpec,
+ agentTexts: string[][],
+ roomText: string
+): { section: 'agent'; index: number } | { section: 'room' } {
+ if (param.type !== 'room') {
+ const index = agentTexts.findIndex((texts) =>
+ texts.some((t) => placeholdersIn(t).includes(param.name))
+ );
+ if (index >= 0) return { section: 'agent', index };
+ }
+ if (param.type === 'room' || placeholdersIn(roomText).includes(param.name))
+ return { section: 'room' };
+ return { section: 'agent', index: 0 };
+}
+
+export type CreateStepStatus = 'waiting' | 'running' | 'done' | 'failed';
+
+/** One call the page makes while creating, as a row of the creating screen. */
+export type CreateStep = {
+ key: string;
+ label: string;
+ status: CreateStepStatus;
+ /** A problem that did not stop the run, such as a repository that could not be cloned. */
+ warning?: string | null;
+};
+
+export function createStepStatus(status: SlotStatus): CreateStepStatus {
+ return status === 'created'
+ ? 'done'
+ : status === 'creating'
+ ? 'running'
+ : status === 'failed'
+ ? 'failed'
+ : 'waiting';
+}
+
+/**
+ * The rows for one new agent: its directory, the agent, and who may address
+ * it when the template sets that. Rows before the call in progress are done,
+ * the one at it is running or failed, the ones after it wait.
+ */
+export function agentCreateSteps(
+ index: number,
+ agent: {
+ name: string;
+ status: SlotStatus;
+ step: SlotStep | null;
+ clones: boolean;
+ setsPolicy: boolean;
+ cloneWarning: string | null;
+ }
+): CreateStep[] {
+ const order: SlotStep[] = agent.setsPolicy
+ ? ['prepare', 'create', 'policy']
+ : ['prepare', 'create'];
+ const at = agent.step ? order.indexOf(agent.step) : -1;
+ return order.map((step, k) => ({
+ key: `${index}:${step}`,
+ label:
+ step === 'prepare'
+ ? agent.clones
+ ? `Prepare the directory of ${agent.name} and clone the repository`
+ : `Prepare the directory of ${agent.name}`
+ : step === 'create'
+ ? `Create ${agent.name}`
+ : `Set who can talk to ${agent.name}`,
+ status:
+ agent.status === 'created'
+ ? 'done'
+ : agent.status === 'idle' || k > at
+ ? 'waiting'
+ : k < at
+ ? 'done'
+ : createStepStatus(agent.status),
+ warning: step === 'prepare' ? agent.cloneWarning : null,
+ }));
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/images.d.ts b/console/apps/switch-console-desktop/src/renderer/images.d.ts
index c1b58fbeb..efa52db2c 100644
--- a/console/apps/switch-console-desktop/src/renderer/images.d.ts
+++ b/console/apps/switch-console-desktop/src/renderer/images.d.ts
@@ -32,3 +32,13 @@ declare module '*.webp' {
const value: string;
export default value;
}
+
+declare module '*.md?raw' {
+ const value: string;
+ export default value;
+}
+
+declare module '*.yaml?raw' {
+ const value: string;
+ export default value;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/ui/segmented-control.tsx b/console/apps/switch-console-desktop/src/renderer/lib/ui/segmented-control.tsx
index d49a6fb73..5c2946f79 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/ui/segmented-control.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/ui/segmented-control.tsx
@@ -1,3 +1,4 @@
+import type { LucideIcon } from 'lucide-react';
import { ToggleGroup, ToggleGroupItem } from '@renderer/lib/ui/toggle-group';
import { cn } from '@renderer/utils/utils';
@@ -21,7 +22,7 @@ export function SegmentedControl<T extends string>({
}: {
value: T;
onChange: (value: T) => void;
- options: readonly { value: T; label: string }[];
+ options: readonly { value: T; label: string; icon?: LucideIcon }[];
ariaLabel: string;
className?: string;
}) {
@@ -51,6 +52,7 @@ export function SegmentedControl<T extends string>({
// surface itself in dark mode, so it draws nothing.
className="h-auto cursor-pointer rounded-[7px] px-[9px] py-[2px] text-[11.5px] font-medium text-foreground-muted transition-colors hover:bg-transparent hover:text-foreground aria-pressed:bg-[var(--btn-1)] aria-pressed:text-foreground aria-pressed:shadow-[0_1px_2px_rgb(0_0_0_/_0.12)] aria-[pressed=false]:hover:bg-[var(--sel-soft)] data-pressed:bg-[var(--btn-1)] data-[state=on]:bg-[var(--btn-1)] data-[state=on]:text-foreground data-[state=on]:shadow-[0_1px_2px_rgb(0_0_0_/_0.12)]"
>
+ {option.icon && <option.icon className="size-3.5" />}
{option.label}
</ToggleGroupItem>
))}
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/room-template-params.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/room-template-params.ts
index 8db483441..c72658e21 100644
--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/room-template-params.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/room-template-params.ts
@@ -9,7 +9,20 @@
export const ENTITY_PARAM_TYPES = ['agent', 'bridge', 'room', 'user'] as const;
export type EntityParamType = (typeof ENTITY_PARAM_TYPES)[number];
-export type ParamType = 'string' | 'number' | 'boolean' | 'enum' | EntityParamType;
+/** Param types the Console answers itself and leaves out of the request to
+ * the server. `provider` is the coding agent that runs an agent the template
+ * creates, `location` the machine it runs on, `directory` its working
+ * directory. Mirrors `CONSOLE_PARAM_TYPES` in core. */
+export const CONSOLE_PARAM_TYPES = ['provider', 'location', 'directory'] as const;
+export type ConsoleParamType = (typeof CONSOLE_PARAM_TYPES)[number];
+
+export type ParamType =
+ | 'string'
+ | 'number'
+ | 'boolean'
+ | 'enum'
+ | EntityParamType
+ | ConsoleParamType;
export const PARAM_TYPES: readonly ParamType[] = [
'string',
@@ -17,8 +30,35 @@ export const PARAM_TYPES: readonly ParamType[] = [
'boolean',
'enum',
...ENTITY_PARAM_TYPES,
+ ...CONSOLE_PARAM_TYPES,
];
+export function isConsoleParamType(type: ParamType): type is ConsoleParamType {
+ return (CONSOLE_PARAM_TYPES as readonly string[]).includes(type);
+}
+
export function isEntityParamType(type: ParamType): type is EntityParamType {
return (ENTITY_PARAM_TYPES as readonly string[]).includes(type);
}
+
+/** Param types whose `default` may be a list of candidates tried in order.
+ * Mirrors `CHAIN_PARAM_TYPES` in core. A `user` param has no first:
+ * `{$creator}` already names the deployer. */
+export const CHAIN_PARAM_TYPES: readonly ParamType[] = [
+ 'agent',
+ 'bridge',
+ 'room',
+ 'provider',
+ 'location',
+];
+
+/** In a chain: the first thing of the param's type the server or the Console has. */
+export const FIRST = '$first';
+/** In a `room` param's chain: the room the template's own `room:` block describes. */
+export const NEW = '$new';
+
+/** How a form presents a param. `ask` is a visible input; `advanced` is
+ * prefilled and folded away; `fixed` is shown but not editable. Mirrors
+ * `ParamInput` in core. */
+export type ParamInput = 'ask' | 'advanced' | 'fixed';
+export const PARAM_INPUTS: readonly ParamInput[] = ['ask', 'advanced', 'fixed'];
diff --git a/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts b/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts
index af1089b54..557cee552 100644
--- a/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts
@@ -18,7 +18,10 @@ export const VIEW_IDS = [
'serverRooms',
'remoteHosts',
'remoteHost',
- 'roomTemplateImport',
+ 'templateImport',
+ 'templates',
+ 'templateDetail',
+ 'templateUse',
] as const;
export type ViewIdName = (typeof VIEW_IDS)[number];
diff --git a/console/packages/plugins/src/agents/impl/opencode/skill-file.ts b/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
index e79458e04..e7b827815 100644
--- a/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
+++ b/console/packages/plugins/src/agents/impl/opencode/skill-file.ts
@@ -830,6 +830,7 @@ failure-mode tools are covered in the sections just above.
- \`list_room_groups\` — the group tree rooms are organised into.
- \`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.
- \`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/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.py
index b461768d9..a7b11f2ee 100644
--- a/core/switch_core/bridges/agent/operations/definitions.py
+++ b/core/switch_core/bridges/agent/operations/definitions.py
@@ -30,7 +30,8 @@ from switch_core.bridges.agent.protocol.connections import (
from switch_core.bridges.agent.protocol.instructions import build_room_instructions
from switch_core.bridges.agent.protocol.service import ProtocolService
from switch_core.bridges.agent.protocol.types import IntegrationProfile
-from switch_core.db.models import CollaborationBridge
+from switch_core.db.models import CollaborationBridge, User
+from switch_core.rooms_yaml import GroupSpec
logger = logging.getLogger(__name__)
@@ -1552,6 +1553,81 @@ async def get_room_group_detail(group_id: str) -> dict[str, Any]:
return await protocol.get_room_group_detail(agent_id, group_id)
+@operation
+async def create_room_from_yaml(
+ yaml: str,
+ inputs: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Provision a room, or a group of rooms, from a YAML template.
+
+ The agent-side mirror of the gateway's ``POST /rooms/from-yaml``: the
+ document is parsed, its ``params:`` resolved from ``inputs``, and the
+ result provisioned as the calling agent's owner (an ownerless agent
+ cannot provision rooms). Server-provided ``{$creator}`` names the owner.
+
+ Args:
+ yaml: The template text. A top-level ``room:`` makes one room; a
+ ``group:`` with a ``rooms:`` list (and optional ``links:``) makes
+ a room group. Either may declare ``params:`` with defaults and
+ descriptions; placeholders are filled in before provisioning.
+ inputs: Values for declared params. A required param with no default
+ must be supplied here, or provisioning fails naming it.
+
+ Returns:
+ For a room: ``{room_id, room_name, attached_reference_ids,
+ created_reference_ids, created_document_ids, role_names,
+ failed_attachments}``. For a group: ``{group_id, group_name,
+ rooms: [...], errors: [...]}``.
+ """
+ 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)
+ if 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)
+
+ 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
+ )
+ 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(
+ parsed.spec,
+ user_id=owner_id,
+ is_admin=owner_is_admin,
+ creator_name=builtins["$creator"],
+ )
+ 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()
+
+
@operation
async 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.py
index 28e3c8730..ea79dcc42 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -127,6 +127,7 @@ if TYPE_CHECKING:
from switch_core.db.stores.task_store import TaskStore
from switch_core.gateway.schemas import AgentDetail
from switch_core.room_service import RoomCreateResult, RoomService
+ from switch_core.rooms_yaml import RoomYamlService
logger = logging.getLogger(__name__)
@@ -2568,6 +2569,28 @@ class ProtocolService:
except ValueError as e:
raise ValueError(f"Failed to add users: {str(e)}") from e
+ def room_yaml_service(self) -> RoomYamlService:
+ """The template engine over this service's collaborators.
+
+ Built here so the gateway's dependency and the agent operation wire
+ it the same way; a collaborator added to ``RoomYamlService`` is then
+ added once.
+ """
+ from switch_core.rooms_yaml import RoomYamlService
+
+ return RoomYamlService(
+ room_service=self.room_service,
+ resource_service=self.resource_service,
+ room_store=self.room_store,
+ agent_store=self.agent_store,
+ bridge_store=self.bridge_store,
+ external_user_store=self.external_user_store,
+ room_role_store=self.room_role_store,
+ session_factory=self.session_factory,
+ room_group_store=self.room_group_store,
+ client_lifecycle=self.client_lifecycle,
+ )
+
async def _resolve_acting_identity(
self, session: AsyncSession, agent_id: str
) -> tuple[Agent, str | None, bool]:
diff --git a/core/switch_core/gateway/dependencies.py b/core/switch_core/gateway/dependencies.py
index d9265fa2d..c891bcd88 100644
--- a/core/switch_core/gateway/dependencies.py
+++ b/core/switch_core/gateway/dependencies.py
@@ -141,17 +141,7 @@ def get_session_factory() -> Any:
def get_room_yaml_service() -> RoomYamlService:
protocol: ProtocolService = _state["protocol"]
- return RoomYamlService(
- room_service=_state["room_service"],
- resource_service=_state["resource_service"],
- room_store=_state["room_store"],
- agent_store=_state["agent_store"],
- bridge_store=_state["bridge_store"],
- external_user_store=_state["external_user_store"],
- room_role_store=protocol.room_role_store,
- session_factory=_state["session_factory"],
- client_lifecycle=_state["client_lifecycle"],
- )
+ return protocol.room_yaml_service()
def get_agent_store() -> AgentStore:
diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.py
index cca27956f..446d06cd8 100644
--- a/core/switch_core/gateway/rooms.py
+++ b/core/switch_core/gateway/rooms.py
@@ -53,7 +53,13 @@ from switch_core.gateway.schemas import (
RoomUsersRequest,
)
from switch_core.room_service import RoleSpec, RoomCreateConfig, RoomService
-from switch_core.rooms_yaml import ProvisionResult, RoomYamlService, TemplateDocument
+from switch_core.rooms_yaml import (
+ GroupProvisionResult,
+ GroupSpec,
+ ProvisionResult,
+ RoomYamlService,
+ template_json_schema,
+)
from switch_core.telemetry import emit_safely
logger = logging.getLogger(__name__)
@@ -383,8 +389,12 @@ async def create_room_from_yaml(
rooms_yaml: Annotated[RoomYamlService, Depends(get_room_yaml_service)],
user: Annotated[User, Depends(get_current_user)],
is_admin: Annotated[bool, Depends(get_tenant_is_admin)],
-) -> ProvisionResult:
- """Provision a single room and its attachments from a YAML spec.
+) -> ProvisionResult | GroupProvisionResult:
+ """Provision a room, or a group of rooms, from a YAML spec.
+
+ The document shape picks the result: a ``room:`` document makes one room
+ (``ProvisionResult``); a ``group:`` + ``rooms:`` document makes a room
+ group with its rooms and links (``GroupProvisionResult``).
Two content types are accepted:
@@ -408,11 +418,19 @@ async def create_room_from_yaml(
else:
text = (await request.body()).decode("utf-8")
inputs = None
+ inputs = 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
+ user_id=user.id, name=user.name, email=user.email, text=text, inputs=inputs
)
parsed = rooms_yaml.parse_template(text, inputs=inputs, builtins=builtins)
await rooms_yaml.check_entity_params(parsed)
+ if isinstance(parsed.spec, GroupSpec):
+ return await rooms_yaml.provision_group(
+ parsed.spec,
+ user_id=user.id,
+ is_admin=is_admin,
+ creator_name=builtins["$creator"],
+ )
return await rooms_yaml.provision(
parsed.spec,
kickoff=parsed.kickoff,
@@ -432,8 +450,9 @@ async def create_room_from_yaml(
async def get_template_schema(
_user: Annotated[User, Depends(get_current_user)],
) -> dict:
- """Return the JSON Schema describing a valid room template document."""
- return TemplateDocument.model_json_schema()
+ """Return the JSON Schema describing a valid template document, either
+ the single-room or the group shape."""
+ return template_json_schema()
@router.get("/{room_id}/yaml")
diff --git a/core/switch_core/rooms_yaml.py b/core/switch_core/rooms_yaml.py
index 88f14611a..616d27f9e 100644
--- a/core/switch_core/rooms_yaml.py
+++ b/core/switch_core/rooms_yaml.py
@@ -1,11 +1,19 @@
-"""Declarative provisioning of a single room from YAML, and export back.
+"""Declarative provisioning of rooms from YAML, and export back.
-v0 supports a ``params:`` block beside ``room:`` that declares typed,
-defaultable placeholders. ``parse(text, inputs)`` resolves them and
-interpolates ``{name}`` throughout the ``room:`` tree before validation, so
-one file can stamp out many rooms with different inputs. A literal
-``{word}`` that collides with a declared param name *is* substituted — this
-is accepted for v0; ``sensitive: true`` is deferred to a later version.
+Two document shapes are supported, told apart by their top-level key:
+
+* **Single room** (``room:``): one room with its attachments, and an optional
+ top-level ``kickoff:`` posted once it exists.
+* **Group** (``group:`` + ``rooms:``): a room group, several rooms filed under
+ it, and optional directed ``links:`` between them. A kickoff belongs to the
+ room it is for, so in a group it sits inside each room entry.
+
+v0 supports a ``params:`` block that declares typed, defaultable
+placeholders. ``parse_template(text, inputs)`` resolves them and interpolates
+``{name}`` throughout the document before validation, so one file can stamp
+out many rooms with different inputs. A literal ``{word}`` that collides
+with a declared param name *is* substituted — this is accepted for v0;
+``sensitive: true`` is deferred to a later version.
An optional top-level ``version:`` key (default ``0``) is accepted and
validated as an integer, but not acted on yet.
@@ -13,7 +21,8 @@ validated as an integer, but not acted on yet.
Provisioning is room-first and best-effort: the room is created first (which
fails loud on bad agents / refs / config), then inline references and docs are
attached, with any post-creation failures collected into ``failed_attachments``
-rather than silently dropped.
+rather than silently dropped. A group is provisioned room by room in order; a
+room that fails is reported in ``errors`` and does not roll back the others.
Export emits resolved rooms and never emits ``params:``.
"""
@@ -28,7 +37,7 @@ from datetime import date
from typing import TYPE_CHECKING, Any, Literal, cast
import yaml
-from pydantic import BaseModel, ValidationError, model_validator
+from pydantic import BaseModel, Field, TypeAdapter, ValidationError, model_validator
from switch_core.bridges.collaboration.models import ChannelType
from switch_core.bridges.resource.registry import validate_reference_value
@@ -47,6 +56,7 @@ if TYPE_CHECKING:
CollaborationBridgeStore,
)
from switch_core.db.stores.external_user_store import ExternalUserStore
+ from switch_core.db.stores.room_group_store import RoomGroupStore
from switch_core.db.stores.room_role_store import RoomRoleStore
from switch_core.db.stores.room_store import RoomStore
from switch_core.room_service import RoomService
@@ -67,38 +77,156 @@ PLACEHOLDER_RE = re.compile(r"\{(\$?[A-Za-z_][A-Za-z0-9_]*)\}")
# bridge's display name, a room's name, a platform username.
ENTITY_PARAM_TYPES = ("agent", "bridge", "room", "user")
+# Param types the Console answers and removes before provisioning: the coding
+# agent that runs an agent the template creates, the machine it runs on, and
+# its working directory. The server sees them only in stored documents. They
+# are known types so such a document passes the lint and can be stored; if
+# one does reach provisioning it is treated as a string.
+CONSOLE_PARAM_TYPES = ("provider", "location", "directory")
+
+# Param types whose ``default`` may be a list of candidates, tried in order
+# until one names something the server (or, for the Console's types, the
+# Console) has. ``$first`` in such a list stands for the first thing of the
+# param's type: the default messaging app, the first agent or room by name,
+# the first coding agent available where the agent runs. A `user` param has no "first":
+# which account is meant depends on who asks, and ``{$creator}`` already
+# covers the deployer.
+CHAIN_PARAM_TYPES = ("agent", "bridge", "room", "provider", "location")
+FIRST = "$first"
+# In a `room` param's chain: the room the template's own ``room:`` block
+# describes. Resolved by the Console, which decides between creating that
+# room and joining a chosen one; it never reaches the server.
+NEW = "$new"
+# The types whose param may be left without a value when the template marks
+# it ``required: false`` and gives no default: a string is empty, a room
+# with no bridge lands on the server's default messaging app, and an unset
+# room drops out of the list it was written in (an agent's ``join``, where
+# it means "no room").
+OPTIONAL_WITHOUT_DEFAULT_TYPES = ("string", "bridge", "room")
+
ParamType = Literal[
- "string", "number", "boolean", "enum", "agent", "bridge", "room", "user"
+ "string",
+ "number",
+ "boolean",
+ "enum",
+ "agent",
+ "bridge",
+ "room",
+ "user",
+ "provider",
+ "location",
+ "directory",
]
+# How a form presents a param. ``ask`` is a visible input. ``advanced`` is
+# prefilled from the default and folded away for the deployer who wants it.
+# ``fixed`` is the default, shown but not editable: the template author has
+# decided, and wrote it as a param to name and describe the value.
+ParamInput = Literal["ask", "advanced", "fixed"]
+
class ParamSpec(BaseModel):
model_config = {"extra": "forbid"}
type: ParamType = "string"
description: str | None = None
- default: str | int | float | bool | None = None
+ # The human name of the input on a form, when the key is not one.
+ label: str | None = None
+ # A value, or for a type in CHAIN_PARAM_TYPES a list of candidates tried
+ # in order (see ``resolve_defaults``).
+ default: str | int | float | bool | list[str] | None = None
+ # Whether the value may be empty when the template is used. Unset means
+ # "required unless there is a default"; a chain is not one, since every
+ # candidate can be absent, so a param with a chain stays required unless
+ # the template says otherwise.
+ required: bool | None = None
+ input: ParamInput = "ask"
enum: list[str] | None = None
# Rendering hint for string params that carry long text (a task brief,
# instructions): the form shows a textarea instead of a one-line input,
# which would strip the pasted text's newlines.
multiline: bool = False
+ # A regular expression the whole value of a string param must match.
+ pattern: str | None = None
+ # Bounds of a number param, inclusive.
+ min: float | None = None
+ max: float | None = None
+
+ @property
+ def is_required(self) -> bool:
+ if self.required is not None:
+ return self.required
+ return self.default is None or isinstance(self.default, list)
+
+ @model_validator(mode="after")
+ def _fields_fit_the_type(self) -> ParamSpec:
+ if isinstance(self.default, list):
+ if self.type not in CHAIN_PARAM_TYPES:
+ raise ValueError(
+ "a list default applies to params of type "
+ + ", ".join(CHAIN_PARAM_TYPES)
+ )
+ if not self.default:
+ raise ValueError("a list default must name at least one candidate")
+ if NEW in self.default and self.type != "room":
+ raise ValueError(f"{NEW!r} applies to params of type room")
+ if self.input == "fixed" and self.default is None:
+ raise ValueError("a fixed param needs a default: that is its value")
+ if (
+ self.required is False
+ and self.default is None
+ and self.type not in OPTIONAL_WITHOUT_DEFAULT_TYPES
+ ):
+ raise ValueError(
+ f"a {self.type} param without a default cannot be optional; "
+ "give it a default or leave it required"
+ )
+ if self.pattern is not None:
+ if self.type != "string":
+ raise ValueError("'pattern' applies to params of type string")
+ try:
+ re.compile(self.pattern)
+ except re.error as e:
+ raise ValueError(
+ f"'pattern' is not a valid regular expression: {e}"
+ ) from e
+ if (self.min is not None or self.max is not None) and self.type != "number":
+ raise ValueError("'min' and 'max' apply to params of type number")
+ if self.min is not None and self.max is not None and self.min > self.max:
+ raise ValueError("'min' must not exceed 'max'")
+ return self
def _coerce(value: Any, spec: ParamSpec, name: str) -> str | int | float | bool:
"""Coerce a raw input value to the declared type."""
t = spec.type
- if t == "string" or t in ENTITY_PARAM_TYPES:
+ if t == "string":
+ s = str(value)
+ if spec.pattern is not None and re.fullmatch(spec.pattern, s) is None:
+ raise ValueError(
+ f"param {name!r}: {s!r} does not match the pattern {spec.pattern!r}"
+ )
+ return s
+ if t in ENTITY_PARAM_TYPES or t in CONSOLE_PARAM_TYPES:
return str(value)
if t == "number":
if isinstance(value, bool):
raise ValueError(f"param {name!r}: expected a number, got {value!r}")
+ n: int | float
if isinstance(value, int):
- return value # keep int as int; no float roundtrip, no precision loss
- try:
- f = float(value)
- return int(f) if f == int(f) else f
- except (ValueError, TypeError, OverflowError) as e:
- raise ValueError(f"param {name!r}: expected a number, got {value!r}") from e
+ n = value # keep int as int; no float roundtrip, no precision loss
+ else:
+ try:
+ f = float(value)
+ n = int(f) if f == int(f) else f
+ except (ValueError, TypeError, OverflowError) as e:
+ raise ValueError(
+ f"param {name!r}: expected a number, got {value!r}"
+ ) from e
+ if spec.min is not None and n < spec.min:
+ raise ValueError(f"param {name!r}: {n} is below the minimum {spec.min:g}")
+ if spec.max is not None and n > spec.max:
+ raise ValueError(f"param {name!r}: {n} is above the maximum {spec.max:g}")
+ return n
if t == "boolean":
if isinstance(value, bool):
return value
@@ -120,7 +248,14 @@ def resolve_params(
declared: dict[str, ParamSpec],
inputs: dict[str, Any] | None,
) -> dict[str, str | int | float | bool]:
- """Merge inputs over defaults, enforce required, coerce types."""
+ """Merge inputs over defaults, enforce required, coerce types.
+
+ A list default is a chain that ``resolve_defaults`` turns into an input
+ before this runs; one still here has no candidate the server has, and
+ counts as no value. An optional param left without a value is a string
+ left empty, or an entity name left out of the result altogether so that
+ ``drop_unset`` can clear the field it was written into.
+ """
if inputs is not None and not isinstance(inputs, dict):
raise ValueError("'inputs' must be a mapping of param name to value")
inputs = inputs or {}
@@ -130,17 +265,60 @@ def resolve_params(
resolved: dict[str, str | int | float | bool] = {}
missing: list[str] = []
for name, spec in declared.items():
- if name in inputs:
+ if name in inputs and inputs[name] is not None:
resolved[name] = _coerce(inputs[name], spec, name)
- elif spec.default is not None:
+ elif spec.default is not None and not isinstance(spec.default, list):
resolved[name] = _coerce(spec.default, spec, name)
- else:
+ elif spec.is_required:
missing.append(name)
+ elif spec.type == "string":
+ resolved[name] = ""
if missing:
+ chains = [n for n in missing if isinstance(declared[n].default, list)]
+ if chains:
+ raise ValueError(
+ "Missing required param(s): "
+ + ", ".join(missing)
+ + " (none of the candidates listed for "
+ + ", ".join(chains)
+ + " is set up on this server)"
+ )
raise ValueError(f"Missing required param(s): {', '.join(missing)}")
return resolved
+def unset_params(declared: dict[str, ParamSpec], values: dict[str, Any]) -> set[str]:
+ """The declared params ``resolve_params`` gave no value: optional entity
+ params the caller left empty."""
+ return {name for name in declared if name not in values}
+
+
+def drop_unset(node: Any, names: set[str]) -> Any:
+ """Clear the fields written as exactly ``{name}`` for an unset param.
+
+ A mapping value becomes null (a room's ``bridge: null`` lands on the
+ default messaging app); a list entry is removed. A placeholder inside a
+ longer string is left as written, since there is nothing sensible to put
+ there.
+ """
+ if not names:
+ return node
+
+ def _is_unset(value: Any) -> bool:
+ if not isinstance(value, str):
+ return False
+ m = PLACEHOLDER_RE.fullmatch(value)
+ return m is not None and m.group(1) in names
+
+ if isinstance(node, dict):
+ return {
+ k: (None if _is_unset(v) else drop_unset(v, names)) for k, v in node.items()
+ }
+ if isinstance(node, list):
+ return [drop_unset(v, names) for v in node if not _is_unset(v)]
+ return node
+
+
def interpolate(
node: Any,
values: dict[str, str | int | float | bool],
@@ -168,7 +346,9 @@ def interpolate(
return PLACEHOLDER_RE.sub(_replace, node)
if isinstance(node, dict):
- return {k: interpolate(v, values) for k, v in node.items()}
+ # Keys are interpolated as well as values. An alias map is written
+ # `"{bot}": helper`, where the key is the agent name a param provides.
+ return {interpolate(k, values): interpolate(v, values) for k, v in node.items()}
if isinstance(node, list):
return [interpolate(item, values) for item in node]
return node
@@ -246,21 +426,69 @@ class RoomSpec(BaseModel):
roles: list[RoleSpec] = []
references: list[ExternalReferenceEntry] = []
docs: list[DocSpec] = []
+ # Agent name to the alias it can be addressed by in this room.
+ aliases: dict[str, str] | None = None
+ # Used only for a room inside a group's ``rooms:`` list, where each room
+ # has its own kickoff. A single-room document puts ``kickoff:`` at the
+ # top level, next to ``room:``.
+ kickoff: str | None = None
+
+# ── Group document models ────────────────────────────────────────────────
-class TemplateDocument(BaseModel):
- """Top-level shape of a room template file (for JSON Schema generation)."""
+
+class GroupLinkSpec(BaseModel):
+ model_config = {"extra": "forbid", "populate_by_name": True}
+ from_: str = Field(alias="from")
+ to: str
+ label: str
+
+
+class GroupMeta(BaseModel):
+ model_config = {"extra": "forbid"}
+ name: str
+ description: str | None = None
+ color: str | None = None
+
+
+class GroupSpec(BaseModel):
+ group: GroupMeta
+ rooms: list[RoomSpec]
+ links: list[GroupLinkSpec] = []
+
+
+class RoomTemplateDocument(BaseModel):
+ """Top-level shape of a single-room template file."""
room: RoomSpec
params: dict[str, ParamSpec] | None = None
kickoff: str | None = None
+class GroupTemplateDocument(BaseModel):
+ """Top-level shape of a group template file."""
+
+ group: GroupMeta
+ rooms: list[RoomSpec]
+ links: list[GroupLinkSpec] = []
+ params: dict[str, ParamSpec] | None = None
+
+
+# Both document shapes, for the JSON Schema served by ``GET /rooms/template-schema``.
+TemplateDocument = RoomTemplateDocument | GroupTemplateDocument
+
+
+def template_json_schema() -> dict[str, Any]:
+ """The schema a client validates a template against, either shape."""
+ return TypeAdapter(TemplateDocument).json_schema()
+
+
@dataclass(frozen=True)
class ParsedTemplate:
"""What ``parse_template`` makes of one template plus one set of inputs."""
- spec: RoomSpec
+ spec: RoomSpec | GroupSpec
+ #: The kickoff of a single-room document. A group's kickoffs are on its rooms.
kickoff: str | None
#: The template's declared params, by name.
params: dict[str, ParamSpec]
@@ -278,6 +506,13 @@ class ProvisionResult(BaseModel):
failed_attachments: list[dict[str, Any]] = []
+class GroupProvisionResult(BaseModel):
+ group_id: str
+ group_name: str
+ rooms: list[ProvisionResult] = []
+ errors: list[dict[str, Any]] = []
+
+
# ── YAML literal-block dumper (keeps multiline doc content readable) ────────
@@ -294,8 +529,8 @@ _SpecDumper.add_representer(str, _str_representer)
class RoomYamlService:
- """Parse / provision / export a single room as YAML. Free of HTTP concerns
- so it is unit-testable and reusable for future MCP / CLI surfaces."""
+ """Parse / provision / export rooms as YAML. Free of HTTP concerns so it
+ is unit-testable and reusable for future MCP / CLI surfaces."""
def __init__(
self,
@@ -308,6 +543,7 @@ class RoomYamlService:
external_user_store: ExternalUserStore,
room_role_store: RoomRoleStore,
session_factory: async_sessionmaker[AsyncSession],
+ room_group_store: RoomGroupStore,
client_lifecycle: ClientLifecycleService | None = None,
) -> None:
self._rooms = room_service
@@ -317,6 +553,7 @@ class RoomYamlService:
self._bridge_store = bridge_store
self._external_users = external_user_store
self._room_roles = room_role_store
+ self._room_groups = room_group_store
self._session_factory = session_factory
self._client_lifecycle = client_lifecycle
@@ -335,6 +572,10 @@ class RoomYamlService:
entity-typed params before provisioning.
"""
parsed = self.parse_template(text, inputs=inputs, builtins=builtins)
+ if isinstance(parsed.spec, GroupSpec):
+ raise ValueError(
+ "this is a group template; parse_template handles both shapes"
+ )
return parsed.spec, parsed.kickoff
def parse_template(
@@ -343,7 +584,10 @@ class RoomYamlService:
inputs: dict[str, Any] | None = None,
builtins: dict[str, str] | None = None,
) -> ParsedTemplate:
- """Parse a YAML template into its room spec, kickoff, and resolved params.
+ """Parse a YAML template into its spec, kickoff, and resolved params.
+
+ The top-level key tells the shapes apart: ``room:`` gives a
+ ``RoomSpec``, ``group:`` + ``rooms:`` a ``GroupSpec``.
``builtins`` are server-injected variables (e.g. ``{creator}``) that
are always available for interpolation alongside user-supplied
@@ -355,12 +599,24 @@ class RoomYamlService:
data = yaml.safe_load(text)
except yaml.YAMLError as e:
raise ValueError(f"Invalid YAML: {e}") from e
- if not isinstance(data, dict) or "room" not in data:
+ if not isinstance(data, dict):
raise ValueError("YAML must have a single top-level 'room:' mapping")
-
- allowed_keys = {"room", "params", "version", "kickoff"}
+ is_group = "group" in data
+ if not is_group and "room" not in data:
+ raise ValueError("YAML must have a top-level 'room:' or 'group:' mapping")
+
+ allowed_keys = (
+ {"group", "rooms", "links", "params", "version"}
+ if is_group
+ else {"room", "params", "version", "kickoff"}
+ )
extra = set(data) - allowed_keys
if extra:
+ if is_group and extra == {"kickoff"}:
+ raise ValueError(
+ "a group template's kickoff goes on the room it is for: "
+ "put 'kickoff:' inside each entry of 'rooms:'"
+ )
raise ValueError(f"Unknown top-level key(s): {', '.join(sorted(extra))}")
# version: accepted, not acted on yet.
@@ -393,28 +649,80 @@ class RoomYamlService:
resolved = resolve_params(declared, inputs)
values.update(resolved)
+ body = {k: v for k, v in data.items() if k not in ("params", "version")}
if values:
- room_data = interpolate(data["room"], values)
- kickoff_raw = data.get("kickoff")
- kickoff = (
- interpolate(kickoff_raw, values)
- if isinstance(kickoff_raw, str)
- else None
- )
- else:
- room_data = data["room"]
- kickoff = (
- data.get("kickoff") if isinstance(data.get("kickoff"), str) else None
- )
+ body = interpolate(body, values)
+ if declared:
+ body = drop_unset(body, unset_params(declared, resolved))
- try:
- spec = RoomSpec.model_validate(room_data)
- except ValidationError as e:
- raise ValueError(f"Invalid room spec: {e}") from e
+ if is_group:
+ spec: RoomSpec | GroupSpec = self._group_spec(body)
+ kickoff = None
+ else:
+ try:
+ spec = RoomSpec.model_validate(body["room"])
+ except ValidationError as e:
+ raise ValueError(f"Invalid room spec: {e}") from e
+ if spec.kickoff is not None:
+ raise ValueError(
+ "a single-room template's kickoff goes at the top level, "
+ "beside 'room:'"
+ )
+ kickoff_raw = body.get("kickoff")
+ if kickoff_raw is not None and not isinstance(kickoff_raw, str):
+ raise ValueError(
+ f"'kickoff' must be a string, got {type(kickoff_raw).__name__}"
+ )
+ kickoff = kickoff_raw
return ParsedTemplate(
spec=spec, kickoff=kickoff, params=declared, values=resolved
)
+ @staticmethod
+ def _group_spec(body: dict[str, Any]) -> GroupSpec:
+ """Validate an interpolated group document: the meta, every room, and
+ links that name rooms the document has."""
+ if "rooms" not in body:
+ raise ValueError("Group document requires a 'rooms:' list")
+ try:
+ group_meta = GroupMeta.model_validate(body["group"])
+ except ValidationError as e:
+ raise ValueError(f"Invalid group spec: {e}") from e
+ raw_rooms = body["rooms"]
+ if not isinstance(raw_rooms, list) or not raw_rooms:
+ raise ValueError("'rooms:' must be a non-empty list")
+ rooms: list[RoomSpec] = []
+ for i, entry in enumerate(raw_rooms):
+ try:
+ rooms.append(RoomSpec.model_validate(entry))
+ except ValidationError as e:
+ raise ValueError(f"Invalid room spec at index {i}: {e}") from e
+ raw_links = body.get("links") or []
+ if not isinstance(raw_links, list):
+ raise ValueError("'links:' must be a list")
+ links: list[GroupLinkSpec] = []
+ for i, entry in enumerate(raw_links):
+ try:
+ links.append(GroupLinkSpec.model_validate(entry))
+ except ValidationError as e:
+ raise ValueError(f"Invalid link spec at index {i}: {e}") from e
+ # Links refer to rooms by name, so room names must be unique in the document.
+ seen: set[str] = set()
+ dupes: list[str] = []
+ for r in rooms:
+ if r.name in seen and r.name not in dupes:
+ dupes.append(r.name)
+ seen.add(r.name)
+ if dupes:
+ raise ValueError(f"Duplicate room name(s): {', '.join(dupes)}")
+ for link in links:
+ for end, name in (("from", link.from_), ("to", link.to)):
+ if name not in seen:
+ raise ValueError(
+ f"Link {end} {name!r} does not match any room name"
+ )
+ return GroupSpec(group=group_meta, rooms=rooms, links=links)
+
# ── Entity params ─────────────────────────────────────────────────────
async def check_entity_params(self, parsed: ParsedTemplate) -> None:
@@ -428,7 +736,8 @@ class RoomYamlService:
"""
wanted: dict[str, list[tuple[str, str]]] = {}
for name, spec in parsed.params.items():
- if spec.type in ENTITY_PARAM_TYPES:
+ # An optional entity param left empty names nothing to check.
+ if spec.type in ENTITY_PARAM_TYPES and name in parsed.values:
wanted.setdefault(spec.type, []).append(
(name, str(parsed.values[name]))
)
@@ -469,7 +778,16 @@ class RoomYamlService:
)
if "user" in wanted:
- bridge_id = await self._resolve_bridge_id(parsed.spec.bridge)
+ # TODO: look users up on each room's messaging app. Only the first
+ # room's app is checked, so a group whose rooms are on different
+ # apps passes here and gets a failed attachment when the other
+ # rooms are provisioned.
+ first = (
+ parsed.spec.rooms[0]
+ if isinstance(parsed.spec, GroupSpec)
+ else parsed.spec
+ )
+ bridge_id = await self._resolve_bridge_id(first.bridge)
if bridge_id is None:
param = wanted["user"][0][0]
raise ValueError(
@@ -485,8 +803,82 @@ class RoomYamlService:
"room's messaging app"
)
+ async def resolve_defaults(
+ self, text: str, inputs: dict[str, Any] | None
+ ) -> dict[str, Any] | None:
+ """Turn each list default into an input, for params sent no value.
+
+ The candidates are tried in order and the first one the server has
+ wins: a bridge by display name, an agent or room by name, ``$first``
+ for the default messaging app or the first agent or room by name. A
+ chain with no hit leaves the param as it was, for ``resolve_params``
+ to report. Runs before ``builtins_for``, because the bridge decides
+ which messaging app ``{$creator}`` is looked up on. A document that
+ does not parse is returned untouched; ``parse_template`` reports the
+ error. Chains of the Console's types are the Console's to resolve.
+ """
+ try:
+ data = yaml.safe_load(text)
+ declared = {
+ name: ParamSpec.model_validate(spec)
+ for name, spec in ((data or {}).get("params") or {}).items()
+ }
+ except (yaml.YAMLError, ValidationError, AttributeError, TypeError):
+ return inputs
+ given = inputs if isinstance(inputs, dict) else {}
+ chains = {
+ name: spec
+ for name, spec in declared.items()
+ if isinstance(spec.default, list)
+ and spec.type in ENTITY_PARAM_TYPES
+ and given.get(name) is None
+ }
+ if not chains:
+ return inputs
+
+ filled = dict(given)
+ async with self._session_factory() as session:
+ names: dict[str, list[str]] = {}
+ for name, spec in chains.items():
+ if spec.type not in names:
+ names[spec.type] = await self._names_of(session, spec.type)
+ have = names[spec.type]
+ for candidate in spec.default: # type: ignore[union-attr]
+ if candidate == FIRST and have:
+ filled[name] = have[0]
+ break
+ if candidate in have:
+ filled[name] = candidate
+ break
+ return filled if filled != given else inputs
+
+ async def _names_of(self, session: AsyncSession, param_type: str) -> list[str]:
+ """What the server has of one entity type, the ``$first`` one first."""
+ if param_type == "bridge":
+ active = [
+ b
+ for b in await self._bridge_store.get_all(session)
+ if b.status == "active"
+ ]
+ return sorted(
+ (b.display_name for b in active),
+ key=lambda n: (
+ not any(b.display_name == n and b.is_default for b in active),
+ n,
+ ),
+ )
+ if param_type == "agent":
+ return sorted(a.name for a in await self._agent_store.get_all(session))
+ return sorted(r.name for r in await self._room_store.get_all(session))
+
async def builtins_for(
- self, *, user_id: str, name: str, email: str, text: str
+ self,
+ *,
+ user_id: str,
+ name: str,
+ email: str,
+ text: str,
+ inputs: dict[str, Any] | None = None,
) -> dict[str, str]:
"""The server-injected ``{$...}`` variables for one create call.
@@ -499,7 +891,7 @@ class RoomYamlService:
in.
"""
creator = name
- bridge_id = await self._peek_bridge_id(text)
+ bridge_id = await self._peek_bridge_id(text, inputs)
if bridge_id is not None:
async with self._session_factory() as session:
claimed = await self._external_users.get_by_user(session, user_id)
@@ -523,13 +915,19 @@ class RoomYamlService:
"$timestamp": str(int(time.time())),
}
- async def _peek_bridge_id(self, text: str) -> str | None:
+ async def _peek_bridge_id(
+ self, text: str, inputs: dict[str, Any] | None = None
+ ) -> str | None:
"""The bridge the template will land on, read before interpolation.
- Best-effort: an unparseable template, an interpolated bridge name, or
- an unknown bridge all answer None; parse/provision fails loudly later
- when it matters. A template naming no bridge lands on the default one,
- same as provisioning."""
+ A `bridge:` written as `{param}` is filled from `inputs` (or the
+ param's default) the way provisioning will fill it, so a template
+ that asks which app to use still finds the creator's account there.
+
+ Best-effort: an unparseable template, a bridge name that cannot be
+ resolved yet, or an unknown bridge all answer None; parse/provision
+ fails loudly later when it matters. A template naming no bridge lands
+ on the default one, same as provisioning."""
try:
data = yaml.safe_load(text)
except yaml.YAMLError:
@@ -537,12 +935,27 @@ class RoomYamlService:
if not isinstance(data, dict):
return None
room = data.get("room")
+ if room is None:
+ rooms = data.get("rooms")
+ room = rooms[0] if isinstance(rooms, list) and rooms else None
if not isinstance(room, dict):
return None
bridge = room.get("bridge")
- if bridge is not None and (
- not isinstance(bridge, str) or PLACEHOLDER_RE.search(bridge)
- ):
+ if isinstance(bridge, str) and PLACEHOLDER_RE.search(bridge):
+ raw_params = data.get("params")
+ try:
+ declared = {
+ k: ParamSpec.model_validate(v)
+ for k, v in (raw_params or {}).items()
+ }
+ values = resolve_params(declared, inputs)
+ except (ValueError, ValidationError, AttributeError):
+ return None
+ filled = interpolate(bridge, values)
+ if not isinstance(filled, str) or PLACEHOLDER_RE.search(filled):
+ return None
+ bridge = filled
+ if bridge is not None and not isinstance(bridge, str):
return None
try:
return await self._resolve_bridge_id(bridge)
@@ -559,12 +972,14 @@ class RoomYamlService:
is_admin: bool,
kickoff: str | None = None,
creator_name: str | None = None,
+ group_id: str | None = None,
) -> ProvisionResult:
"""Create the room and everything the spec attaches to it.
``kickoff`` is posted once the room exists, by the platform on the
creator's behalf (see ``_send_kickoff``); ``creator_name`` is how the
- message names them.
+ message names them. ``group_id`` files the room under a group that
+ already exists (see ``provision_group``).
"""
bridge_id = await self._resolve_bridge_id(spec.bridge)
if spec.users and bridge_id is None:
@@ -585,6 +1000,7 @@ class RoomYamlService:
agent_names=spec.agents or None,
user_names=spec.users or None,
bridge_id=bridge_id,
+ group_id=group_id,
created_by=user_id,
from_template=True,
owner_id=user_id,
@@ -594,6 +1010,7 @@ class RoomYamlService:
write_visibility=spec.write_visibility,
roles=spec.roles or None,
reference_ids=attached_ref_ids or None,
+ aliases=spec.aliases,
)
result = await self._rooms.create_room(config)
room_id = result.room.id
@@ -607,14 +1024,19 @@ class RoomYamlService:
)
if kickoff:
- await self._send_kickoff(
- result.room,
- kickoff,
- agent_names=spec.agents,
- user_id=user_id,
- user_name=creator_name,
- failures=failures,
- )
+ # The room exists at this point. A kickoff failure is recorded on
+ # the result; raising here would report the room as not created.
+ try:
+ await self._send_kickoff(
+ result.room,
+ kickoff,
+ agent_names=spec.agents,
+ user_id=user_id,
+ user_name=creator_name,
+ failures=failures,
+ )
+ except Exception as e: # noqa: BLE001 - reported on the result
+ failures.append({"kind": "kickoff", "id": "kickoff", "error": str(e)})
return ProvisionResult(
room_id=room_id,
@@ -626,6 +1048,88 @@ class RoomYamlService:
failed_attachments=failures,
)
+ async def provision_group(
+ self,
+ spec: GroupSpec,
+ *,
+ user_id: str,
+ is_admin: bool,
+ creator_name: str | None = None,
+ ) -> GroupProvisionResult:
+ """Provision a room group, its rooms, and the links between them.
+
+ Order: group row → each room with ``group_id`` (its own kickoff, if
+ any, posted as it is created) → links by name. A room that fails is
+ reported in ``errors`` and the rest still go ahead; nothing is rolled
+ back, so the caller sees exactly what exists.
+ """
+ async with self._session_factory() as session:
+ group = await self._room_groups.create(
+ session,
+ name=spec.group.name,
+ description=spec.group.description,
+ color=spec.group.color,
+ parent_group_id=None,
+ )
+ await session.commit()
+ group_id = group.id
+
+ room_results: list[ProvisionResult] = []
+ errors: list[dict[str, Any]] = []
+ name_to_room_id: dict[str, str] = {}
+
+ for i, room_spec in enumerate(spec.rooms):
+ try:
+ result = await self.provision(
+ room_spec,
+ user_id=user_id,
+ is_admin=is_admin,
+ kickoff=room_spec.kickoff,
+ creator_name=creator_name,
+ group_id=group_id,
+ )
+ except Exception as e: # noqa: BLE001 - reported, not swallowed
+ errors.append(
+ {"room_index": i, "room_name": room_spec.name, "error": str(e)}
+ )
+ continue
+ room_results.append(result)
+ name_to_room_id[room_spec.name] = result.room_id
+
+ for link in spec.links:
+ from_id = name_to_room_id.get(link.from_)
+ to_id = name_to_room_id.get(link.to)
+ if from_id is None or to_id is None:
+ errors.append(
+ {
+ "kind": "link",
+ "from": link.from_,
+ "to": link.to,
+ "error": "one or both rooms were not created",
+ }
+ )
+ continue
+ try:
+ async with self._session_factory() as session:
+ await self._resources.attach_linked_room(
+ session,
+ source_room_id=from_id,
+ target_room_id=to_id,
+ label=link.label,
+ )
+ await session.commit()
+ except Exception as e: # noqa: BLE001 - reported, not swallowed
+ errors.append(
+ {"kind": "link", "from": link.from_, "to": link.to, "error": str(e)}
+ )
+
+ return GroupProvisionResult(
+ group_id=group_id,
+ group_name=spec.group.name,
+ rooms=room_results,
+ errors=errors,
+ )
+
async def _resolve_bridge_id(self, bridge_name: str | None) -> str | None:
if bridge_name is None:
async with self._session_factory() as session:
@@ -896,13 +1400,20 @@ class RoomYamlService:
if agents:
agent_ids = await self._room_store.get_agent_ids(session, room.id)
- names: list[str] = []
+ id_to_name: dict[str, str] = {}
for aid in agent_ids:
agent = await self._agent_store.get(session, aid)
if agent is not None:
- names.append(agent.name)
- if names:
- data["agents"] = sorted(names)
+ id_to_name[aid] = agent.name
+ if id_to_name:
+ data["agents"] = sorted(id_to_name.values())
+ alias_map = await self._room_store.list_aliases(session, room.id)
+ if alias_map:
+ data["aliases"] = {
+ id_to_name[aid]: alias
+ for aid, alias in alias_map.items()
+ if aid in id_to_name
+ }
if users and room.bridge_id:
client_ids = await self._room_store.get_client_ids(session, room.id)
diff --git a/core/switch_core/template_lint.py b/core/switch_core/template_lint.py
index 680604e44..4960d5172 100644
--- a/core/switch_core/template_lint.py
+++ b/core/switch_core/template_lint.py
@@ -32,11 +32,28 @@ from switch_core.rooms_yaml import PLACEHOLDER_RE, ParamSpec
# be in flight — room, group, and the kickoff message that rides beside them.
# Additive on purpose, and only ever a warning: an unrecognised key is as
# likely to be a format this server predates as it is to be a typo.
-_KNOWN_TOP_LEVEL = frozenset({"room", "group", "rooms", "params", "version", "kickoff"})
+_KNOWN_TOP_LEVEL = frozenset(
+ {
+ "room",
+ "group",
+ "rooms",
+ "links",
+ "params",
+ "version",
+ "kickoff",
+ "agent",
+ "agents",
+ "form",
+ }
+)
-# `{$...}` placeholders the server fills in itself. A template does not declare
-# them and must not be told to.
-_BUILTINS = frozenset({"$creator", "$creator_email", "$date", "$timestamp"})
+# `{$...}` placeholders the server fills in itself, plus `$agents_dir`, which
+# the Console fills in (the directory it keeps agents under, on the machine
+# the agent runs on) before the document reaches the server. A template does
+# not declare them and must not be told to.
+_BUILTINS = frozenset(
+ {"$creator", "$creator_email", "$date", "$timestamp", "$agents_dir"}
+)
# Matched here rather than left to `PLACEHOLDER_RE`, which only learned about
# the `$` prefix alongside the builtins themselves. Scanning for them directly
@@ -260,6 +277,29 @@ def lint_template(text: str) -> LintResult:
if "params" in document
else set()
)
+ # An agent template's room refers to the agent as `{agent}`. The Console
+ # fills that in with the agent's name, so the template uses it without
+ # declaring it.
+ if "agent" in document:
+ declared = declared | {"agent"}
+ # `$new` in a room param's chain means the room this document describes,
+ # so a document without one has nothing for it to mean.
+ if (
+ "room" not in document
+ and "rooms" not in document
+ and isinstance(document.get("params"), dict)
+ ):
+ for name, spec in document["params"].items():
+ default = spec.get("default") if isinstance(spec, dict) else None
+ if isinstance(default, list) and "$new" in default:
+ errors.append(
+ Finding(
+ "new_without_room",
+ f"Parameter '{name}' lists '$new' among its defaults, but "
+ "the document describes no room to create.",
+ name,
+ )
+ )
# Placeholders are looked for everywhere except the params block, which
# declares them rather than using them.
@@ -298,7 +338,9 @@ def lint_template(text: str) -> LintResult:
name,
)
)
- for name in sorted(declared - used):
+ # `agent` is the Console's to fill, not a declared param, so a room that
+ # never names the agent is not an unused parameter.
+ for name in sorted(declared - used - {"agent"}):
warnings.append(
Finding(
"unused_param",
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.py
new file mode 100644
index 000000000..76176f549
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/operations/test_create_room_from_yaml.py
@@ -0,0 +1,344 @@
+"""Behavioural tests for the create_room_from_yaml operation.
+
+The full operation path: YAML in, room or group provisioned as the calling
+agent's owner, with the error cases for missing inputs and an ownerless agent.
+Same FakeRoomService pattern as test_rooms_yaml.py: real PostgreSQL, no Matrix.
+"""
+
+from __future__ import annotations
+
+import uuid
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+import pytest_asyncio
+from sqlalchemy import insert, select
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.agent.operations import context as op_context
+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
+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,
+ 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
+room:
+ name: "Test Room"
+ description: "A test room"
+ agents: ["claude-code.alice"]
+"""
+
+PARAMETERIZED_YAML = """\
+version: 0
+params:
+ project:
+ type: string
+room:
+ name: "{project} room"
+ description: "Room for {project}, made by {$creator}"
+ agents: ["claude-code.alice"]
+"""
+
+GROUP_YAML = """\
+version: 0
+params:
+ team:
+ type: string
+group:
+ name: "{team} group"
+rooms:
+ - name: "{team} main"
+ description: "Main room"
+ agents: ["claude-code.alice"]
+ - name: "{team} support"
+ description: "Support room"
+ agents: ["claude-code.bob"]
+links:
+ - from: "{team} main"
+ to: "{team} support"
+ label: support
+"""
+
+
+async def _call(agent_id: str, **kwargs: Any) -> dict[str, Any]:
+ token = set_call_context(CallContext(agent_id=agent_id, session_key=None))
+ try:
+ return await create_room_from_yaml(**kwargs)
+ finally:
+ reset_call_context(token)
+
+
+async def test_single_room_provisioned(env):
+ result = await _call(env["agent_id"], yaml=SINGLE_ROOM_YAML)
+ assert result["room_name"] == "Test Room"
+ async with env["session_factory"]() as session:
+ room = await session.get(Room, result["room_id"])
+ assert room is not None
+ assert room.owner_id == env["user_id"]
+
+
+async def test_single_room_with_params_and_creator_builtin(env):
+ result = await _call(
+ env["agent_id"], yaml=PARAMETERIZED_YAML, inputs={"project": "Atlas"}
+ )
+ assert result["room_name"] == "Atlas room"
+ async with env["session_factory"]() as session:
+ room = await session.get(Room, result["room_id"])
+ assert room is not None
+ assert room.description == "Room for Atlas, made by alice"
+
+
+async def test_group_provisioned_with_links(env):
+ result = await _call(env["agent_id"], yaml=GROUP_YAML, inputs={"team": "alpha"})
+ assert result["group_name"] == "alpha group"
+ assert {r["room_name"] for r in result["rooms"]} == {"alpha main", "alpha support"}
+ assert result["errors"] == []
+ async with env["session_factory"]() as session:
+ group = await session.get(RoomGroup, result["group_id"])
+ assert group is not None
+ links = (await session.execute(select(RoomLink))).scalars().all()
+ assert [link.label for link in links] == ["support"]
+
+
+KICKOFF_YAML = """\
+version: 0
+room:
+ name: "Kickoff Room"
+ description: "A room with a kickoff"
+ agents: ["claude-code.alice"]
+kickoff: "Start on the brief."
+"""
+
+
+async def test_kickoff_is_posted_on_behalf_of_the_owner(env):
+ result = await _call(env["agent_id"], yaml=KICKOFF_YAML)
+
+ assert result["failed_attachments"] == []
+ sent = env["admin"].sent
+ assert [m["body"] for m in sent][-1] == "Start on the brief."
+ assert all(m["on_behalf_of"].name == "alice" for m in sent)
+
+
+async def test_missing_required_input_creates_nothing(env):
+ with pytest.raises(ValueError, match="project"):
+ await _call(env["agent_id"], yaml=PARAMETERIZED_YAML)
+ async with env["session_factory"]() as session:
+ assert (await session.execute(select(Room))).scalars().all() == []
+
+
+async def test_ownerless_agent_cannot_provision(env):
+ with pytest.raises(ValueError, match="no owner"):
+ await _call(env["orphan_id"], yaml=SINGLE_ROOM_YAML)
diff --git a/core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py b/core/tests/switch_core/bridges/agent/test_mcp_tool_surface.py
index 274b8a9ba..9bef7dd33 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
@@ -78,6 +78,7 @@ async def test_documented_tools_exist(tool_names: set[str]) -> None:
"list_room_groups",
"create_room_group",
"get_room_group_detail",
+ "create_room_from_yaml",
"list_agents",
"get_agent_detail",
"update_agent_detail",
diff --git a/core/tests/switch_core/test_rooms_yaml.py b/core/tests/switch_core/test_rooms_yaml.py
index 20752d80c..62d71a67b 100644
--- a/core/tests/switch_core/test_rooms_yaml.py
+++ b/core/tests/switch_core/test_rooms_yaml.py
@@ -15,6 +15,7 @@ from typing import Any
import pytest
import pytest_asyncio
+import yaml
from sqlalchemy import insert, select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
@@ -32,6 +33,8 @@ from switch_core.db.models import (
Reference,
ReferenceType,
Room,
+ RoomGroup,
+ RoomLink,
RoomRole,
User,
room_agents,
@@ -44,12 +47,14 @@ 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.room_service import RoomCreateConfig, RoomCreateResult
from switch_core.rooms_yaml import (
ExistingReferenceById,
+ GroupSpec,
ParamSpec,
RoomYamlService,
interpolate,
@@ -115,6 +120,7 @@ class FakeRoomService:
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()
@@ -190,6 +196,7 @@ async def env(session_factory: async_sessionmaker[AsyncSession]):
external_user_store=ExternalUserStore(),
room_role_store=RoomRoleStore(),
session_factory=session_factory,
+ room_group_store=RoomGroupStore(),
)
async with session_factory() as session:
@@ -1514,6 +1521,190 @@ async def test_builtins_creator_resolves_named_bridge(env):
assert builtins["$creator"] == "abel.slack"
+async def test_builtins_creator_resolves_a_bridge_param_from_inputs(env):
+ """A `bridge:` written as `{bridge}` is filled from the inputs before the
+ claim is looked up, so the creator is found on the app they picked."""
+ await _seed_bridge_with_claim(
+ env["session_factory"],
+ display_name="Mattermost",
+ is_default=True,
+ claimed_by=env["user_id"],
+ external_username="abel.mm",
+ )
+ await _seed_bridge_with_claim(
+ env["session_factory"],
+ display_name="Slack",
+ is_default=False,
+ claimed_by=env["user_id"],
+ external_username="abel.slack",
+ )
+ text = (
+ "params:\n bridge:\n type: bridge\n"
+ 'room:\n name: n\n description: d\n bridge: "{bridge}"\n'
+ ' users: ["{$creator}"]\n'
+ )
+ svc = _svc(env)
+ picked = await svc.builtins_for(
+ user_id=env["user_id"],
+ name="alice",
+ text=text,
+ inputs={"bridge": "Slack"},
+ )
+ assert picked["$creator"] == "abel.slack"
+ # No input for it and no default: the app is unknown, so the gateway
+ # name stands in rather than a guess at one bridge's claim.
+ unset = await svc.builtins_for(
+ user_id=env["user_id"], name="alice", email="[email protected]", text=text
+ )
+ assert unset["$creator"] == "alice"
+
+
+CHAIN_TEXT = (
+ "params:\n bridge:\n type: bridge\n default: [Teams, $first]\n"
+ " helper:\n type: agent\n default: [nobody, $first]\n"
+ 'room:\n name: n\n description: d\n bridge: "{bridge}"\n'
+ ' agents: ["{helper}"]\n'
+)
+
+
+async def test_resolve_defaults_walks_each_chain_in_order(env):
+ """The first candidate the server has wins: Teams is not set up, so the
+ bridge falls through to the default app; no agent is called nobody, so the
+ first agent by name stands in. An input the caller did send is kept."""
+ for name, is_default in (("Mattermost", False), ("Slack", True)):
+ await _seed_bridge_with_claim(
+ env["session_factory"],
+ display_name=name,
+ is_default=is_default,
+ claimed_by=env["user_id"],
+ external_username=f"abel.{name.lower()}",
+ )
+ svc = _svc(env)
+
+ filled = await svc.resolve_defaults(CHAIN_TEXT, None)
+ assert filled == {"bridge": "Slack", "helper": "claude-code.alice"}
+
+ kept = await svc.resolve_defaults(CHAIN_TEXT, {"bridge": "Mattermost"})
+ assert kept == {"bridge": "Mattermost", "helper": "claude-code.alice"}
+
+ named = CHAIN_TEXT.replace("[Teams, $first]", "[Mattermost, $first]")
+ assert (await svc.resolve_defaults(named, None))["bridge"] == "Mattermost"
+
+
+async def test_a_chain_with_no_hit_is_reported_as_missing(env):
+ text = (
+ "params:\n bridge:\n type: bridge\n default: [Teams, $first]\n"
+ 'room:\n name: n\n description: d\n bridge: "{bridge}"\n'
+ )
+ svc = _svc(env)
+ assert await svc.resolve_defaults(text, None) is None
+ with pytest.raises(ValueError, match="none of the candidates listed for bridge"):
+ svc.parse_template(text)
+
+
+def test_a_list_default_is_refused_on_a_param_with_no_list(env):
+ text = (
+ "params:\n topic:\n type: string\n default: [a, b]\n"
+ "room:\n name: n\n description: d\n"
+ )
+ with pytest.raises(ValueError, match="a list default applies to params of type"):
+ _svc(env).parse_template(text, inputs={"topic": "x"})
+
+
+def test_new_is_only_for_room_params(env):
+ with pytest.raises(ValueError, match="'\\$new' applies to params of type room"):
+ ParamSpec(type="bridge", default=["$new"])
+ assert ParamSpec(type="room", default=["$new"]).default == ["$new"]
+
+
+def test_required_and_input_default_from_the_default(env):
+ assert ParamSpec(type="string").is_required
+ assert not ParamSpec(type="string", default="x").is_required
+ assert ParamSpec(type="string", default="x", required=True).is_required
+ assert ParamSpec(type="string").input == "ask"
+ with pytest.raises(ValueError, match="a fixed param needs a default"):
+ ParamSpec(type="string", input="fixed")
+ with pytest.raises(ValueError, match="cannot be optional"):
+ ParamSpec(type="agent", required=False)
+ assert not ParamSpec(type="room", required=False).is_required
+
+
+def test_an_optional_string_left_empty_is_empty(env):
+ spec, _ = _svc(env).parse(
+ "params:\n suffix:\n type: string\n required: false\n"
+ 'room:\n name: "n{suffix}"\n description: d\n'
+ )
+ assert spec.name == "n"
+
+
+async def test_an_unset_optional_entity_param_passes_the_entity_check(env):
+ """``check_entity_params`` skips a param ``resolve_params`` gave no value,
+ instead of asking for it."""
+ svc = _svc(env)
+ parsed = svc.parse_template(
+ "params:\n bridge:\n type: bridge\n required: false\n"
+ 'room:\n name: n\n description: d\n bridge: "{bridge}"\n'
+ )
+ assert "bridge" not in parsed.values
+ await svc.check_entity_params(parsed)
+
+
+async def test_a_chain_resolves_over_an_input_sent_as_null(env):
+ await _seed_bridge_with_claim(
+ env["session_factory"],
+ display_name="Slack",
+ is_default=True,
+ claimed_by=env["user_id"],
+ external_username="abel.slack",
+ )
+ text = (
+ "params:\n app:\n type: bridge\n default: [Slack, $first]\n"
+ 'room:\n name: n\n description: d\n bridge: "{app}"\n'
+ )
+ assert await _svc(env).resolve_defaults(text, {"app": None}) == {"app": "Slack"}
+
+
+def test_an_optional_bridge_left_empty_lands_on_the_default_app(env):
+ """The room's bridge field written as `{bridge}` is cleared rather than
+ left as a placeholder, so provisioning picks the default messaging app."""
+ spec, _ = _svc(env).parse(
+ "params:\n bridge:\n type: bridge\n required: false\n"
+ 'room:\n name: n\n description: d\n bridge: "{bridge}"\n'
+ )
+ assert spec.bridge is None
+
+
+def test_pattern_and_bounds_are_enforced(env):
+ svc = _svc(env)
+ text = (
+ "params:\n team:\n type: string\n pattern: '[a-z]+'\n"
+ " size:\n type: number\n min: 1\n max: 5\n"
+ 'room:\n name: "{team}"\n description: "size {size}"\n'
+ )
+ spec, _ = svc.parse(text, inputs={"team": "alpha", "size": 3})
+ assert spec.name == "alpha"
+ assert spec.description == "size 3"
+ with pytest.raises(ValueError, match="does not match the pattern"):
+ svc.parse(text, inputs={"team": "Alpha1", "size": 3})
+ with pytest.raises(ValueError, match="above the maximum 5"):
+ svc.parse(text, inputs={"team": "alpha", "size": 9})
+ with pytest.raises(ValueError, match="'pattern' applies to params of type string"):
+ ParamSpec(type="number", pattern="x")
+ with pytest.raises(ValueError, match="not a valid regular expression"):
+ ParamSpec(type="string", pattern="(")
+
+
+def test_label_and_the_new_fields_ride_into_the_schema(env):
+ from switch_core.rooms_yaml import template_json_schema
+
+ props = template_json_schema()["$defs"]["ParamSpec"]["properties"]
+ for key in ("label", "required", "input", "pattern", "min", "max"):
+ assert key in props
+ assert "prefill" not in props
+
+
def test_parse_multiline_param_option(env):
"""`multiline: true` is a valid param option and rides into the schema."""
spec, _ = _svc(env).parse(
@@ -1530,9 +1721,9 @@ def test_parse_multiline_param_option(env):
)
assert spec.instructions == "line one\nline two\n## Acceptance\n- item\n"
- from switch_core.rooms_yaml import TemplateDocument
+ from switch_core.rooms_yaml import template_json_schema
- schema = TemplateDocument.model_json_schema()
+ schema = template_json_schema()
assert "multiline" in schema["$defs"]["ParamSpec"]["properties"]
@@ -1567,9 +1758,9 @@ def test_resolve_params_entity_types_coerce_to_string():
def test_template_schema_advertises_entity_types():
"""The Console reads the allowed types off the schema, so the new ones
must be in it or every typed template is rejected client-side."""
- from switch_core.rooms_yaml import TemplateDocument
+ from switch_core.rooms_yaml import template_json_schema
- schema = TemplateDocument.model_json_schema()
+ schema = template_json_schema()
allowed = schema["$defs"]["ParamSpec"]["properties"]["type"]["enum"]
assert {"agent", "bridge", "room", "user"} <= set(allowed)
@@ -1684,3 +1875,364 @@ async def test_check_entity_params_ignores_plain_params(env):
inputs={"label": "anything"},
)
await svc.check_entity_params(parsed)
+
+
+# ── group parse ─────────────────────────────────────────────────────────────
+
+
+GROUP_TEMPLATE = """\
+version: 0
+params:
+ newcomer:
+ type: string
+group:
+ name: "Onboarding"
+ description: "Lobby + per-person workroom"
+ color: "#3b82f6"
+rooms:
+ - name: "{newcomer} lobby"
+ description: "Welcome room for {newcomer}"
+ agents: ["claude-code.alice"]
+ aliases:
+ claude-code.alice: greeter
+ - name: "{newcomer} workroom"
+ description: "Work room for {newcomer}"
+ agents: ["claude-code.bob"]
+links:
+ - from: "{newcomer} lobby"
+ to: "{newcomer} workroom"
+ label: workroom
+"""
+
+
+def _group(env, text: str, inputs: dict | None = None) -> GroupSpec:
+ spec = _svc(env).parse_template(text, inputs=inputs).spec
+ assert isinstance(spec, GroupSpec)
+ return spec
+
+
+def test_parse_group_returns_group_spec(env):
+ spec = _group(env, GROUP_TEMPLATE, {"newcomer": "dana"})
+ assert spec.group.name == "Onboarding"
+ assert spec.group.color == "#3b82f6"
+ assert [r.name for r in spec.rooms] == ["dana lobby", "dana workroom"]
+ assert spec.rooms[0].aliases == {"claude-code.alice": "greeter"}
+ assert len(spec.links) == 1
+ assert (spec.links[0].from_, spec.links[0].to) == ("dana lobby", "dana workroom")
+
+
+def test_parse_group_params_interpolate_alias_keys(env):
+ spec = _group(
+ env,
+ """\
+params:
+ bot:
+ type: string
+group:
+ name: "G"
+rooms:
+ - name: "R"
+ description: "d"
+ agents: ["{bot}"]
+ aliases:
+ "{bot}": helper
+""",
+ {"bot": "claude-code.alice"},
+ )
+ assert spec.rooms[0].agents == ["claude-code.alice"]
+ assert spec.rooms[0].aliases == {"claude-code.alice": "helper"}
+
+
+def test_parse_group_builtins_resolve_in_rooms(env):
+ parsed = _svc(env).parse_template(
+ """\
+group:
+ name: "G"
+rooms:
+ - name: "{$creator}'s room"
+ description: "d"
+""",
+ builtins={"$creator": "dana"},
+ )
+ assert isinstance(parsed.spec, GroupSpec)
+ assert parsed.spec.rooms[0].name == "dana's room"
+
+
+def test_parse_group_room_kickoffs_stay_on_their_rooms(env):
+ spec = _group(
+ env,
+ """\
+group:
+ name: "G"
+rooms:
+ - name: "A"
+ description: "d"
+ kickoff: "hello A"
+ - name: "B"
+ description: "d"
+""",
+ )
+ assert [r.kickoff for r in spec.rooms] == ["hello A", None]
+
+
+def test_parse_group_rejects_top_level_kickoff(env):
+ with pytest.raises(ValueError, match="inside each entry of 'rooms:'"):
+ _svc(env).parse_template(
+ """\
+group:
+ name: "G"
+rooms:
+ - name: "A"
+ description: "d"
+kickoff: "hello"
+"""
+ )
+
+
+def test_parse_room_rejects_nested_kickoff(env):
+ with pytest.raises(ValueError, match="top level"):
+ _svc(env).parse_template(
+ """\
+room:
+ name: "A"
+ description: "d"
+ kickoff: "hello"
+"""
+ )
+
+
+ ("text", "message"),
+ [
+ ('group:\n name: "G"\n', "'rooms:'"),
+ ('group:\n name: "G"\nrooms: []\n', "non-empty"),
+ (
+ 'group:\n name: "G"\nrooms:\n - name: lobby\n description: d\n'
+ " - name: lobby\n description: d2\n",
+ "Duplicate room name",
+ ),
+ (
+ 'group:\n name: "G"\nrooms:\n - name: A\n description: d\n'
+ "links:\n - from: A\n to: B\n label: x\n",
+ "does not match",
+ ),
+ (
+ 'group:\n name: "G"\nrooms:\n - name: A\n description: d\nextra: bad\n',
+ "Unknown top-level",
+ ),
+ ("name: oops\ndescription: d\n", "'room:' or 'group:'"),
+ ],
+)
+def test_parse_group_shape_errors(env, text, message):
+ with pytest.raises(ValueError, match=message):
+ _svc(env).parse_template(text)
+
+
+def test_parse_short_form_refuses_a_group(env):
+ with pytest.raises(ValueError, match="group template"):
+ _svc(env).parse(
+ 'group:\n name: "G"\nrooms:\n - name: A\n description: d\n'
+ )
+
+
+def test_template_schema_covers_both_shapes():
+ from switch_core.rooms_yaml import template_json_schema
+
+ schema = template_json_schema()
+ branches = schema["oneOf"] if "oneOf" in schema else schema["anyOf"]
+ titles = {b["$ref"].rsplit("/", 1)[-1] for b in branches}
+ assert titles == {"RoomTemplateDocument", "GroupTemplateDocument"}
+ assert "aliases" in schema["$defs"]["RoomSpec"]["properties"]
+
+
+# ── group provision ──────────────────────────────────────────────────────────
+
+
+async def test_provision_group_two_rooms_linked(env):
+ """The onboarder-shaped template imports in one call: both rooms exist,
+ grouped together, linked to each other."""
+ svc = _svc(env)
+ spec = _group(env, GROUP_TEMPLATE, {"newcomer": "dana"})
+
+ result = await svc.provision_group(spec, user_id=env["user_id"], is_admin=False)
+
+ assert result.group_name == "Onboarding"
+ assert [r.room_name for r in result.rooms] == ["dana lobby", "dana workroom"]
+ assert result.errors == []
+
+ async with env["session_factory"]() as session:
+ group = await session.get(RoomGroup, result.group_id)
+ assert group is not None
+ assert (group.name, group.color) == ("Onboarding", "#3b82f6")
+ for rr in result.rooms:
+ room = await session.get(Room, rr.room_id)
+ assert room is not None
+ assert room.group_id == result.group_id
+ link = await session.get(
+ RoomLink, (result.rooms[0].room_id, result.rooms[1].room_id)
+ )
+ assert link is not None
+ assert link.label == "workroom"
+
+
+async def test_provision_group_reports_a_failed_room_and_keeps_the_rest(env):
+ svc = _svc(env)
+ spec = _group(
+ env,
+ """\
+group:
+ name: "Collider"
+rooms:
+ - name: "safe room"
+ description: "d"
+ agents: ["claude-code.alice"]
+ - name: "boom room"
+ description: "d"
+ agents: ["does-not-exist"]
+links:
+ - from: "safe room"
+ to: "boom room"
+ label: next
+""",
+ )
+ result = await svc.provision_group(spec, user_id=env["user_id"], is_admin=False)
+
+ assert [r.room_name for r in result.rooms] == ["safe room"]
+ assert result.errors[0]["room_name"] == "boom room"
+ assert "does-not-exist" in result.errors[0]["error"]
+ # The link could not be made either, and says so rather than vanishing.
+ assert result.errors[1]["kind"] == "link"
+ async with env["session_factory"]() as session:
+ assert await session.get(RoomGroup, result.group_id) is not None
+
+
+async def test_provision_group_posts_each_rooms_kickoff(env, monkeypatch):
+ svc = _svc(env)
+ posted: list[tuple[str, str]] = []
+
+ async def fake_send(room, kickoff, **kwargs):
+ posted.append((room.name, kickoff))
+
+ monkeypatch.setattr(svc, "_send_kickoff", fake_send)
+ spec = _group(
+ env,
+ """\
+group:
+ name: "G"
+rooms:
+ - name: "A"
+ description: "d"
+ kickoff: "start A"
+ - name: "B"
+ description: "d"
+""",
+ )
+ await svc.provision_group(
+ spec, user_id=env["user_id"], is_admin=False, creator_name="alice"
+ )
+ assert posted == [("A", "start A")]
+
+
+async def test_check_entity_params_covers_every_room_of_a_group(env):
+ svc = _svc(env)
+ parsed = svc.parse_template(
+ """\
+params:
+ pick:
+ type: agent
+group:
+ name: "G"
+rooms:
+ - name: "A"
+ description: "d"
+ - name: "B"
+ description: "uses {pick}"
+""",
+ inputs={"pick": "nobody"},
+ )
+ with pytest.raises(ValueError, match="param 'pick': no agent named 'nobody'"):
+ await svc.check_entity_params(parsed)
+
+
+async def test_endpoint_json_body_group(env):
+ """The /from-yaml endpoint provisions a group document."""
+ import json
+ from unittest.mock import AsyncMock
+
+ from switch_core.gateway.rooms import create_room_from_yaml
+
+ svc = _svc(env)
+ user = User(name="alice", email="[email protected]", role="member")
+ object.__setattr__(user, "id", env["user_id"])
+ request = AsyncMock()
+ request.headers = {"content-type": "application/json"}
+ request.body.return_value = json.dumps(
+ {"yaml": GROUP_TEMPLATE, "inputs": {"newcomer": "frank"}}
+ ).encode()
+
+ async with env["session_factory"]() as session:
+ result = await create_room_from_yaml(request, session, svc, user, False)
+ assert result.group_name == "Onboarding"
+ assert [r.room_name for r in result.rooms] == ["frank lobby", "frank workroom"]
+
+
+async def test_export_emits_aliases(env):
+ svc = _svc(env)
+ spec = _group(
+ env,
+ """\
+group:
+ name: "G"
+rooms:
+ - name: "A"
+ description: "d"
+ agents: ["claude-code.alice"]
+ aliases:
+ claude-code.alice: greeter
+""",
+ )
+ result = await svc.provision_group(spec, user_id=env["user_id"], is_admin=False)
+ room_id = result.rooms[0].room_id
+ # FakeRoomService does not seed aliases; write the row the real one would.
+ async with env["session_factory"]() as session:
+ agent = (await AgentStore().get_by_names(session, ["claude-code.alice"]))[0]
+ await session.execute(
+ room_agents.update()
+ .where(room_agents.c.room_id == room_id)
+ .where(room_agents.c.agent_id == agent.id)
+ .values(alias="greeter")
+ )
+ await session.commit()
+ exported = yaml.safe_load(await svc.export(room_id))
+ assert exported["room"]["aliases"] == {"claude-code.alice": "greeter"}
+
+
+def test_parse_rejects_non_string_kickoff(env):
+ with pytest.raises(ValueError, match="'kickoff' must be a string"):
+ _svc(env).parse_template(
+ "room:\n name: r\n description: d\nkickoff: [hello]\n"
+ )
+
+
+async def test_provision_reports_a_kickoff_that_raises(env, monkeypatch):
+ svc = _svc(env)
+
+ async def boom(*args, **kwargs):
+ raise RuntimeError("admin client is gone")
+
+ monkeypatch.setattr(svc, "_send_kickoff", boom)
+ parsed = svc.parse_template("room:\n name: r\n description: d\nkickoff: hi\n")
+ result = await svc.provision(
+ parsed.spec, kickoff=parsed.kickoff, user_id=env["user_id"], is_admin=False
+ )
+ assert result.room_name == "r"
+ assert result.failed_attachments == [
+ {"kind": "kickoff", "id": "kickoff", "error": "admin client is gone"}
+ ]
diff --git a/core/tests/switch_core/test_template_lint.py b/core/tests/switch_core/test_template_lint.py
index 82bf928ae..757dfd249 100644
--- a/core/tests/switch_core/test_template_lint.py
+++ b/core/tests/switch_core/test_template_lint.py
@@ -172,7 +172,7 @@ class TestBuiltins:
assert "$creator" in warning.message
@pytest.mark.parametrize(
- "builtin", ["$creator", "$creator_email", "$date", "$timestamp"]
+ "builtin", ["$creator", "$creator_email", "$date", "$timestamp", "$agents_dir"]
)
def test_each_known_builtin_passes(self, builtin: str) -> None:
result = lint_template(f'room:\n name: "{{{builtin}}}"\n')
@@ -224,7 +224,7 @@ class TestShapeAgnosticism:
assert result.warnings == []
def test_a_group_template_is_clean_too(self) -> None:
- """No `room:` key at all — the shape CHOO-2657 introduces.
+ """No `room:` key at all: the group shape.
The linter must not have learned that a template is a room, or it
starts rejecting valid documents the moment a second shape exists.
@@ -243,10 +243,35 @@ class TestShapeAgnosticism:
assert result.warnings == []
def test_a_shape_nobody_has_invented_yet_is_a_warning_not_an_error(self) -> None:
- result = lint_template("agent:\n name: helper\n model: sonnet\n")
+ result = lint_template("workflow:\n name: helper\n steps: []\n")
assert result.ok, "an unknown shape must still be storable"
assert _codes(result.warnings) == {"unknown_top_level_key"}
+ def test_an_agent_template_is_a_known_shape(self) -> None:
+ """Agent templates ride beside room templates: `agent:` plus an
+ optional `room:` and `kickoff:` for the room it is dispatched into."""
+ result = lint_template(
+ "agent:\n"
+ " name: switch-expert\n"
+ " description: Answers questions about Switch.\n"
+ " instructions: You are the Switch expert.\n"
+ " repo: https://github.com/sandbox-quantum/switch\n"
+ "room:\n"
+ " name: Ask switch-expert\n"
+ " agents: ['{agent}']\n"
+ " users: ['{$creator}']\n"
+ "kickoff: '@{agent} say hello'\n"
+ )
+ assert result.ok, [f.message for f in result.errors]
+ assert "unknown_top_level_key" not in _codes(result.warnings)
+ assert "undeclared_placeholder" not in _codes(result.warnings), (
+ "{agent} is the Console's to fill in an agent template"
+ )
+
+ def test_a_room_template_still_has_to_declare_agent(self) -> None:
+ result = lint_template("room:\n name: r\n agents: ['{agent}']\n")
+ assert "undeclared_placeholder" in _codes(result.warnings)
+
def test_a_document_with_no_recognised_key_is_still_only_warned_about(self) -> None:
result = lint_template("whatever:\n - 1\n - 2\n")
assert result.ok
@@ -425,3 +450,61 @@ class TestItNeverBlocksAnUpload:
result = lint_template("a: [unclosed\n")
assert not result.ok
assert isinstance(result.errors, list)
+
+
+def test_group_and_agents_keys_are_known():
+ result = lint_template(
+ "params:\n team:\n type: string\n"
+ "agents:\n - name: '{team}-triager'\n"
+ "group:\n name: '{team}'\nrooms:\n - name: '{team} lobby'\n"
+ " description: d\nlinks: []\n"
+ )
+ assert result.errors == []
+ assert [f.code for f in result.warnings] == []
+
+
+def test_provider_param_type_is_accepted():
+ """The Console answers `type: provider` itself; a stored document that
+ declares one must still lint, or it could never be saved to a server."""
+ result = lint_template(
+ "params:\n provider:\n type: provider\n"
+ "agents:\n - name: helper\n provider: '{provider}'\n"
+ "room:\n name: r\n description: d\n"
+ )
+ assert result.errors == []
+
+
+def test_new_in_a_room_chain_needs_a_room_to_create():
+ text = (
+ "params:\n where:\n type: room\n default: [$new]\n"
+ 'agent:\n name: a\n join: ["{where}"]\n'
+ )
+ result = lint_template(text)
+ assert "new_without_room" in {e.code for e in result.errors}
+ with_room = text + 'room:\n name: r\n agents: ["{agent}"]\n'
+ assert "new_without_room" not in {e.code for e in lint_template(with_room).errors}
+
+
+def test_form_is_a_known_top_level_key():
+ result = lint_template("form:\n advanced:\n open: true\nroom:\n name: r\n")
+ assert "unknown_top_level_key" not in {w.code for w in result.warnings}
+
+
+def test_the_policy_fields_are_known_param_fields():
+ text = (
+ "params:\n name:\n type: string\n label: Agent name\n"
+ " default: x\n required: true\n input: advanced\n"
+ " pattern: '[a-z]+'\n"
+ " bridge:\n type: bridge\n default: [Slack, $first]\n"
+ " location:\n type: location\n default: local\n input: fixed\n"
+ 'room:\n name: "{name}"\n bridge: "{bridge}"\n'
+ 'agent:\n location: "{location}"\n'
+ )
+ result = lint_template(text)
+ assert result.errors == []
+ assert "unknown_param_field" not in {w.code for w in result.warnings}
+
+
+def test_an_agent_template_without_a_room_is_not_told_agent_is_unused():
+ result = lint_template("agent:\n name: a\n instructions: x\n")
+ assert "unused_param" not in {w.code for w in result.warnings}
diff --git a/docs/README.md b/docs/README.md
index 4a48c6a46..6a94e5fda 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -25,3 +25,10 @@ locally for development. None of it is published,
and none of it is covered by the pages under `official/` — where the two
describe the same thing, this is the deeper account and the published page is
the one users act on.
+
+## Reference pages at this level
+
+- [`TEMPLATES.md`](TEMPLATES.md): the template language, the one YAML
+ document that describes agents and rooms to create and the params a
+ deployer fills in. The bundled Switch expert (`switch-expert/template.yaml`)
+ is the worked example.
diff --git a/docs/TEMPLATES.md b/docs/TEMPLATES.md
new file mode 100644
index 000000000..529f4edbf
--- /dev/null
+++ b/docs/TEMPLATES.md
@@ -0,0 +1,447 @@
+# Switch templates: the language
+
+A template is one YAML document that says what to create: an agent, a room,
+or several of each, with the values the deployer may change declared up
+front. Switch Console reads it on the Templates page, builds one form from
+its `params:` block, and creates everything in one pass. Nothing the form
+fills in comes from anywhere but the document: every default, every choice
+of what to ask and what to fold away, and every fallback order is written in
+the template.
+
+This page is the reference. `switch-expert/template.yaml` at the repository
+root is the worked example, and `examples/` holds more.
+
+## Contents
+
+1. [A first template](#a-first-template)
+2. [Document structure](#document-structure)
+3. [Params](#params)
+4. [Placeholders and builtins](#placeholders-and-builtins)
+5. [The agent block](#the-agent-block)
+6. [The room block](#the-room-block)
+7. [Groups](#groups)
+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)
+
+## A first template
+
+```yaml
+version: 1
+params:
+ name:
+ type: string
+ label: Agent name
+ default: jq expert
+ bridge:
+ type: bridge
+ default: [$first]
+ provider:
+ type: provider
+ default: [claude, codex, opencode]
+ input: advanced
+agent:
+ display_name: "{name}"
+ provider: "{provider}"
+ repo: https://github.com/jqlang/jq
+ addressing: anyone
+ instructions: |
+ You help people write and debug jq filters. Read the jq source in
+ `jq/` inside your directory rather than answering from memory.
+room:
+ name: "Ask {agent}"
+ bridge: "{bridge}"
+ agents: ["{agent}"]
+ users: ["{$creator}"]
+kickoff: "@{agent} hi, introduce yourself in two lines."
+```
+
+The form for this template shows two inputs, the agent's name and the
+messaging app, both filled in, and an Advanced fold with the provider. One
+click creates the agent, then the room with the agent and the deployer in
+it, then posts the kickoff.
+
+## Document structure
+
+A document has these top-level keys. All are optional except that it must
+describe at least one thing to create.
+
+| Key | What it is | Created by |
+|---|---|---|
+| `version` | The format version, an integer. `1` today. | |
+| `params` | The inputs of the form, each with a type and a policy. | |
+| `agent` | One agent to create. | Switch Console |
+| `agents` | A list of agents to create. | Switch Console |
+| `room` | One room to create. | The server |
+| `group`, `rooms`, `links` | A room group, its rooms, and links between them. | The server |
+| `kickoff` | A message posted into the room once it exists. | The server |
+| `form` | How the form folds things away. | Switch Console |
+
+There is only one kind of template. A listing shows a document as an agent,
+room or group template by looking at which keys it has, so a saved document
+with `agents:` and `room:` is listed as a group. Nothing about the language
+changes with the kind.
+
+Two engines read the document. Switch Console creates the agents, because an
+agent runs on a machine the Console can reach and the server cannot, and
+resolves the params only it can answer (where an agent runs, which coding
+agent runs it, in which directory). The server creates the rooms from the
+rest, through `POST /rooms/from-yaml`, and resolves the params that name
+things it has (messaging apps, agents, rooms, users). Both read the same
+document under the same rules.
+
+## Params
+
+### Configuration model
+
+```yaml
+params:
+ <name>:
+ type: string | number | boolean | enum | agent | bridge | room | user
+ | provider | location | directory
+ description: text
+ label: text
+ default: value, or a list of candidates
+ required: true | false
+ input: ask | advanced | fixed
+ enum: [choices] # enum only
+ multiline: true | false # string only
+ pattern: regular expression # string only
+ min: number # number only
+ max: number # number only
+```
+
+A param is referred to as `{name}` anywhere else in the document. The key
+is the name; keep it a plain identifier.
+
+### Specification
+
+**`type`**. Data type: one of the names below. Default: `string`.
+
+| Type | Value | Who resolves it |
+|---|---|---|
+| `string` | Text. | |
+| `number` | An integer or decimal. | |
+| `boolean` | `true` or `false`. | |
+| `enum` | One of the strings in `enum:`. | |
+| `agent` | The name of an agent the server has. | The server checks it exists. |
+| `bridge` | The display name of a messaging app set up on the server. | The server checks it exists. |
+| `room` | The name of a room on the server. | The server checks it exists. |
+| `user` | A username on the room's messaging app. | The server looks it up on the app. |
+| `provider` | A coding agent id: `claude`, `codex` or `opencode`. | Switch Console; never sent to the server. |
+| `location` | Where an agent runs: `local`, or an SSH host name the Console knows. | Switch Console; never sent to the server. |
+| `directory` | An agent's working directory, on the machine it runs on. | Switch Console; never sent to the server. |
+
+**`description`**. Data type: text. Shown under the input.
+
+**`label`**. Data type: text. The name of the input on the form, when the
+key is not a good one ("Agent name" for `name`). Without it the form shows
+the key, or a stock label for `bridge`, `provider`, `location`, `directory`
+and `room`.
+
+**`default`**. Data type: a value of the param's type, or for `agent`,
+`bridge`, `room`, `provider` and `location` a list of candidates. Default:
+none. A single value fills the input before the deployer touches it. A list
+is a fallback chain, tried in order: the first candidate the server (or,
+for `provider` and `location`, the Console) has wins. Two words are
+special inside a chain:
+
+- `$first`: the first thing of that type. For a bridge, the server's default
+ messaging app; for an agent or a room, the first by name; for a provider,
+ the first coding agent installed where the agent runs; for a location,
+ this computer.
+- `$new`: for a `room` param only, the room this document's own `room:`
+ block describes. See [Where an agent works](#where-an-agent-works).
+
+```yaml
+bridge:
+ type: bridge
+ default: [Slack, Mattermost, $first] # Slack if set up, else Mattermost, else the default app
+```
+
+A chain with no hit leaves the input empty. With `required: true` that
+blocks creation, and the message names the candidates that were tried.
+
+**`required`**. Data type: boolean. Default: `true` when there is no default
+or the default is a chain, `false` when there is a single default value.
+Whether the value may be empty when the template is used. Only a `string`,
+a `bridge` or a `room` param may be optional without a default: an empty
+string is substituted, a room whose `bridge:` reads an empty bridge param
+is created on the server's default messaging app, and an empty room param
+drops out of the list it was written in, which for an agent's `join` means
+no room. Every other type needs a default to be optional.
+
+**`input`**. Data type: `ask`, `advanced` or `fixed`. Default: `ask`. How the
+form shows the param.
+
+- `ask`: a visible input, filled from the default when there is one.
+- `advanced`: filled from the default and folded away, one line with a
+ Change button. The deployer who accepts the value never sees the control.
+ Without a default, or when the value is empty or wrong, it opens by itself.
+- `fixed`: shown, not editable. The value is the default. This exists so
+ an author can name and describe a value instead of burying a literal in
+ the document, and loosen it later by changing one word. Needs a default.
+
+**`enum`**. Data type: list of strings. The choices of an `enum` param. The
+default, when given, must be one of them.
+
+**`multiline`**. Data type: boolean. Default: `false`. A `string` param
+carrying long text (a brief, instructions) renders as a text area, which
+keeps pasted newlines.
+
+**`pattern`**. Data type: a regular expression. A `string` param's whole
+value must match it. Checked on the form as the deployer types and again
+by the server.
+
+**`min`**, **`max`**. Data type: number. Inclusive bounds of a `number`
+param. Checked on the form and by the server.
+
+### What the form does with a param
+
+The form has an agent section per agent the template creates, then a room
+section. A param is shown in the section of the block that reads it: one
+written into an agent's fields sits with that agent, one written into the
+room sits with the room, and a `room` param always sits with the room since
+it says where the agent works. A `provider`, `location` or `directory`
+param that no agent binds applies to every agent.
+
+The Create button stays disabled while a required param is empty or a
+value breaks its `pattern` or bounds, and says which.
+
+## Placeholders and builtins
+
+Any string in the document may contain `{name}` for a declared param. When
+a whole field is one placeholder the typed value is substituted (so a
+boolean param can fill a boolean field); inside longer text the value is
+written as text. A `{word}` that names no param is left as written.
+
+Some placeholders are filled in without being declared:
+
+| Placeholder | Value | Filled by |
+|---|---|---|
+| `{$creator}` | The deployer, as the room's messaging app knows them: the account they linked there. On a room with no messaging app, their gateway name. | The server |
+| `{$creator_email}` | The deployer's email. | The server |
+| `{$date}` | Today's date, `YYYY-MM-DD`. | The server |
+| `{$timestamp}` | The current Unix time. | The server |
+| `{$agents_dir}` | The directory the Console keeps agents under, on the machine the agent runs on. | Switch Console |
+| `{agent}` | In a document with a single `agent:`, that agent's identifier. | Switch Console |
+
+A template that puts `{$creator}` in a bridged room needs the deployer to
+have linked their account on that messaging app; the form says so and
+offers to link it.
+
+## The agent block
+
+```yaml
+agent:
+ name: identifier
+ display_name: text
+ description: text
+ instructions: text
+ provider: claude | codex | opencode | "{param}"
+ location: local | ssh host | "{param}"
+ directory: path | "{param}"
+ repo: URL
+ sources: [ {label, url} or url ]
+ addressing: owner | owner-agents | anyone
+ join: [ room name or "{param}" ]
+```
+
+`agents:` is a list of the same block, for a template that creates a team.
+In that form a room refers to each agent by the text written as its `name`
+(`"{team}-triager"`), and the form lets the deployer point each entry at an
+agent the server already has instead of creating it.
+
+**`name`**. The identifier the agent is created under and addressed by:
+lowercase letters, digits, `.`, `-` and `_`, starting with a letter or
+digit. When omitted, the Console derives it from `display_name` the same
+way it derives an identifier from a name typed in its own dialog. A name
+that an agent on the server already has blocks creation with a message;
+nothing is renamed behind the deployer's back.
+
+**`display_name`**. How the agent is shown to people. Write it as `{param}`
+to let the deployer change it.
+
+**`description`**. What the agent is for, shown to others.
+
+**`instructions`**. The agent's brief. Required, except that the Console
+reads the bundled Switch expert's from `AGENT.md` next to its template. A
+template stored on a server or pasted into the Console carries it inline.
+
+**`provider`**. The coding agent that runs it. A literal fixes it; `{param}`
+of type `provider` lets the template say how much choice the deployer has.
+When the field is absent and no `provider` param is declared, the form asks,
+with nothing selected: the Console never picks one on its own.
+
+**`location`**. Where it runs. `local` is this computer; otherwise an SSH
+host the Console knows. When absent and no `location` param is declared,
+the agent runs on this computer.
+
+**`directory`**. Its working directory on that machine. `{$agents_dir}` and
+`{agent}` are useful here. When absent and no `directory` param is declared,
+the agent gets `{$agents_dir}/{agent}`, shown on the form under Advanced.
+
+**`repo`**. A repository the agent works from. The Console clones it
+(shallow) into the directory before the agent first runs; if that fails
+the agent is still created and clones it itself.
+
+**`sources`**. Pages the agent should read. Shown to the deployer; the agent
+fetches them itself.
+
+**`addressing`**. Who may talk to the agent: `owner` (the default), the
+deployer only; `owner-agents`, the deployer and their other agents;
+`anyone`, every member of its rooms. Set right after the agent is created.
+
+**`join`**. Rooms the agent is added to once it exists, by name or through
+a `room` param. See the next section but one.
+
+## The room block
+
+```yaml
+room:
+ name: text
+ description: text
+ instructions: text
+ bridge: messaging app display name, or "{param}"
+ channel_type: channel_public | channel_private
+ read_visibility: public | ...
+ write_visibility: public | ...
+ agents: [ agent names ]
+ users: [ usernames ]
+ roles: [ ... ]
+ references: [ ... ]
+ docs: [ ... ]
+ aliases: { agent name: alias }
+```
+
+The same shape `POST /rooms/from-yaml` accepts and `GET /rooms/{id}/yaml`
+exports, so an exported room is a valid template once you add `params:`.
+`examples/room-templates/red-blue-workroom.template.yaml` documents every
+field in place.
+
+`agents:` names agents that exist on the server, plus the ones this
+document creates by the text written as their `name`. `users:` names people
+by their username on the room's messaging app; `{$creator}` puts the
+deployer in. Without `bridge:` the room is created on the server's default
+messaging app; on a server with none, it is a Switch-only room.
+
+## Groups
+
+```yaml
+group:
+ name: text
+ description: text
+ color: text
+rooms:
+ - <room block>
+ kickoff: text
+links:
+ - { from: room name, to: room name, label: text }
+```
+
+`group:` with `rooms:` replaces `room:` for several rooms. Each room may
+carry its own `kickoff:`; a top-level `kickoff:` on a group document is an
+error, since it would not say which room it belongs to. `links:` are
+optional and connect rooms of the group by name.
+
+## Kickoff
+
+```yaml
+kickoff: |
+ @{agent} hi. Introduce yourself in two lines.
+```
+
+Posted into the room on behalf of the deployer once the room exists and
+its members have joined. An agent starts working when a message addresses
+it, 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.
+
+## Where an agent works
+
+Three shapes cover the cases, each one line of template.
+
+**The described room, no choice.** A `room:` block with no `room` param.
+The room is always created with the agent in it.
+
+```yaml
+room: { name: "Ask {agent}", agents: ["{agent}"] }
+```
+
+**A room the deployer picks.** A `room` param the agent `join`s.
+
+```yaml
+params:
+ where: { type: room, label: Room }
+agent:
+ join: ["{where}"]
+```
+
+**A choice, with the described room as the default.** Both, with `$new`
+in the param's chain. The form offers the template's room as "New room"
+alongside the rooms that exist.
+
+```yaml
+params:
+ where: { type: room, default: [$new] }
+agent:
+ join: ["{where}"]
+room: { name: "Ask {agent}", agents: ["{agent}"] }
+```
+
+When a `join` param exists, the template's room is created only when the
+param resolves to `$new`. A document with neither `room:` nor `join:`
+creates the agent and stops.
+
+On the form, a `room` param an agent joins is a switch with the param's
+label, on when its chain resolved to a room and off otherwise. The room
+choice and the room's own params (its messaging app, its members) sit
+under the switch and only while it is on. With `required: false` and no
+default the switch starts off, and turning it on offers the template's
+room first; the Switch expert ships that way. With `default: [$new]` it
+starts on.
+
+```yaml
+params:
+ where:
+ type: room
+ label: Start it in a room
+ required: false
+```
+
+## The form block
+
+```yaml
+form:
+ advanced:
+ label: Advanced
+ open: false
+```
+
+Every `input: advanced` and `input: fixed` param of an agent, and the
+agent's directory when the template names none, sit together in one fold
+under the agent's asked inputs. `label` names the fold; `open` says whether
+it starts open. Folded, it shows its values on one line with a Change
+button, and it opens by itself when something inside it is empty or wrong.
+The block is the Console's; the server ignores it.
+
+## Validation
+
+The server checks a document on upload and before provisioning, and the
+Console runs the same check as the deployer types. Three findings refuse a
+document outright: not YAML, empty, or not a mapping. Everything else is a
+warning or an error the deployer sees against the field: an unknown param
+type, a default that is not one of the enum's choices, a `$new` in a
+document with no room, a placeholder no param declares, a param nothing
+uses.
+
+A param field this server does not know is a warning, not an error, since a
+registry holds documents written for newer versions of Switch than the one
+reading them.
+
+## Versioning
+
+`version: 1` names the format described here. The key is accepted and
+checked as an integer; the server does not yet change how it reads a
+document by its version, and a document without one is read the same way.
diff --git a/examples/agent-templates/jq-expert.template.yaml b/examples/agent-templates/jq-expert.template.yaml
new file mode 100644
index 000000000..f4dbc3104
--- /dev/null
+++ b/examples/agent-templates/jq-expert.template.yaml
@@ -0,0 +1,57 @@
+# jq expert: an agent template for a jq specialist.
+#
+# Same format as switch-expert/template.yaml, which describes every field.
+# The instructions are inline, as they must be in any template stored on a
+# server or pasted into the Console. Save it to a workspace with kind
+# `agent`, or paste it into the Console's import page.
+version: 1
+agent:
+ name: jq-expert
+ description: >-
+ Answers questions about jq, the command-line JSON processor, and writes
+ and debugs jq filters. Reads the jq source and manual rather than
+ answering from memory.
+ repo: https://github.com/jqlang/jq
+ addressing: anyone
+ sources:
+ - label: jq manual
+ url: https://jqlang.org/manual/
+ instructions: |
+ You are jq-expert. You help people write, read and debug jq filters, and
+ you explain how jq behaves.
+
+ ## Where your answers come from
+
+ A clone of the jq repository sits in `jq/` inside your working directory.
+ If it is missing, say "One moment, fetching the jq source." and run
+ `git clone --depth 1 https://github.com/jqlang/jq jq`. At the start of
+ every conversation run `git -C jq pull --ff-only` so you read today's
+ version.
+
+ - Filter syntax, builtins and their exact behaviour: `jq/docs/content/manual/`
+ in the clone, and https://jqlang.org/manual/ when the person is on a
+ released version.
+ - How something actually behaves when the manual is silent: the source
+ under `jq/src/`. Say when you are reading code rather than docs.
+ - Never quote a version number from memory. Look it up in the clone or
+ at https://github.com/jqlang/jq/releases.
+
+ ## How to answer
+
+ - Lead with the filter. Show it, then one or two lines on why it works.
+ - Test it. Run `jq` on a small input before you post a filter, and paste
+ the input and output you used.
+ - Be short. A couple of sentences answers most questions.
+ - When you do not know, say so, and say where the answer would live.
+room:
+ name: "Ask {agent}"
+ description: "Where {$creator} asks {agent} for help with jq."
+ channel_type: channel_private
+ agents: ["{agent}"]
+ users: ["{$creator}"]
+ instructions: |
+ This room is for asking {agent} about jq. Answer here, briefly, with a
+ tested filter whenever the question is about one.
+kickoff: |
+ @{agent} hi. In one line, what can I ask you? Then show me the filter that
+ turns {"a": [1, 2, 3]} into the sum of the array.
diff --git a/examples/agent-templates/support-desk.template.yaml b/examples/agent-templates/support-desk.template.yaml
new file mode 100644
index 000000000..c45ff4e9c
--- /dev/null
+++ b/examples/agent-templates/support-desk.template.yaml
@@ -0,0 +1,77 @@
+# Support desk: two agents across two linked rooms.
+#
+# Switch Console creates the `agents:`. The server creates the room group
+# from `group:`, `rooms:` and `links:`: each room has its own `kickoff:`, and
+# a link connects two rooms by name. The greeter is in both rooms and carries
+# a case from intake to escalations. The engineer is only in escalations.
+version: 1
+
+params:
+ team:
+ type: string
+ description: Prefix for every name this creates
+ pattern: "[a-z][a-z0-9-]*"
+ provider:
+ type: provider
+ description: Which coding agent backs both. The first one installed is chosen.
+ default: [claude, codex, opencode]
+ input: advanced
+ bridge:
+ type: bridge
+ description: Where the rooms are mirrored. The server's default app is chosen.
+ default: [$first]
+
+agents:
+ - name: "{team}-greeter"
+ description: Meets every request first and answers what it can
+ addressing: anyone
+ provider: "{provider}"
+ instructions: |
+ You are the greeter of a support desk. You sit in two rooms: the intake
+ room, where people bring requests, and the escalations room, where the
+ engineer works.
+
+ In the intake room, for each request: answer it yourself when it is a
+ how-to or a known answer. When it needs code changed or investigated,
+ post a one-line summary in the escalations room addressed to the
+ engineer by name, with the person's exact words, and tell the person
+ in the intake room that it has been escalated and to whom.
+
+ Keep a running numbered list of open requests in the intake room.
+ - name: "{team}-engineer"
+ description: Works the cases the greeter escalates
+ addressing: owner-agents
+ provider: "{provider}"
+ instructions: |
+ You are the engineer of a support desk. You only see what the greeter
+ escalates into your room. For each case: say what you are about to
+ check before a slow step, work in your directory, and report back in
+ the same thread with what you found and what you changed, if anything.
+ Never guess a result you did not run.
+
+group:
+ name: "{team} support desk"
+ description: Intake and escalations for {team}
+
+rooms:
+ - name: "{team}-intake"
+ description: Where requests arrive; the greeter answers or escalates
+ bridge: "{bridge}"
+ agents: ["{team}-greeter"]
+ users: ["{$creator}"]
+ kickoff: |
+ @{team}-greeter this is the intake room. Say hello in one line and
+ explain what you will answer here and what you will escalate.
+ - name: "{team}-escalations"
+ description: Where the engineer works escalated cases with the greeter
+ bridge: "{bridge}"
+ agents: ["{team}-greeter", "{team}-engineer"]
+ users: ["{$creator}"]
+ kickoff: |
+ @{team}-engineer this is the escalations room. Say hello in one line;
+ the greeter will bring you cases from the intake room.
+
+links:
+ - from: "{team}-intake"
+ to: "{team}-escalations"
+ label: escalations
diff --git a/examples/agent-templates/triage-pair.template.yaml b/examples/agent-templates/triage-pair.template.yaml
new file mode 100644
index 000000000..9cdf3e597
--- /dev/null
+++ b/examples/agent-templates/triage-pair.template.yaml
@@ -0,0 +1,73 @@
+# Triage pair: two agents and the room they share.
+#
+# Switch Console creates each entry of `agents:`, in its own working
+# directory and backed by the coding agent the `provider` param names. The
+# server creates the `room:` with both agents in it. Every value the form
+# starts with is written under `params:`; the language is documented in
+# docs/TEMPLATES.md.
+version: 1
+
+params:
+ team:
+ type: string
+ description: Prefix for every name this creates
+ pattern: "[a-z][a-z0-9-]*"
+ provider:
+ type: provider
+ description: Which coding agent backs both. The first one installed is chosen.
+ default: [claude, codex, opencode]
+ input: advanced
+ location:
+ type: location
+ description: The machine both run on.
+ default: local
+ input: advanced
+ bridge:
+ type: bridge
+ description: Where the room is mirrored. The server's default app is chosen.
+ default: [$first]
+
+agents:
+ - name: "{team}-triager"
+ description: Reads reports, files and routes them
+ addressing: anyone
+ provider: "{provider}"
+ location: "{location}"
+ instructions: |
+ You are the triager of a small team. Reports arrive in your room from
+ people and from other agents. For each one:
+
+ 1. Restate it in one line.
+ 2. Decide whether it is a bug, a question, or a request, and say why.
+ 3. Bugs go to the reproducer: address it by name with the report and
+ what you expect it to check. Questions you answer yourself.
+ Requests you file back to the person with what is missing.
+
+ Keep a running list of open reports in your replies, so anyone joining
+ the room can see the state without scrolling.
+ - name: "{team}-repro"
+ description: Reproduces what the triager routes to it
+ addressing: owner-agents
+ provider: "{provider}"
+ location: "{location}"
+ instructions: |
+ You reproduce bugs the triager hands you. For each one, work in your
+ directory: write the smallest script or command that shows the
+ problem, run it, and report back in the same thread with the exact
+ output, whether it reproduced, and your best guess at the cause.
+
+ Say what you are about to try before a slow step, so the room is not
+ left wondering. Never guess a result you did not run.
+
+# The room is created on the messaging app the `bridge` input names.
+# `{$creator}` puts the deployer in it, so the agents' answers reach them.
+room:
+ name: "{team}-triage"
+ description: Both agents and you, the triager routing to the reproducer
+ bridge: "{bridge}"
+ agents: ["{team}-triager", "{team}-repro"]
+ users: ["{$creator}"]
+
+kickoff: |
+ @{team}-triager and @{team}-repro: this is your triage room. Triager, say
+ hello in one line and describe how you will hand bugs to the reproducer.
diff --git a/examples/room-templates/red-blue-workroom.template.yaml b/examples/room-templates/red-blue-workroom.template.yaml
index ead6ccc0f..5730259d6 100644
--- a/examples/room-templates/red-blue-workroom.template.yaml
+++ b/examples/room-templates/red-blue-workroom.template.yaml
@@ -40,7 +40,7 @@ params:
description: The task brief (paste the full text)
room:
name: "Switch work: {task_name}"
- description: "Workroom for {task_name}: coder/reviewer loop, human-gated."
+ description: "A coder implements the task and a reviewer drives the acceptance loop; you gate the merge."
channel_type: channel_private
agents: ["{coder_agent}", "{reviewer_agent}"]
users: ["{$creator}"]
diff --git a/switch-expert/AGENT.md b/switch-expert/AGENT.md
index 414c5091b..27b48ed6a 100644
--- a/switch-expert/AGENT.md
+++ b/switch-expert/AGENT.md
@@ -51,11 +51,15 @@ are coming from a checkout of unknown age. Do not quietly answer anyway.
Match the question to the source. Getting this wrong is how you end up confidently stale.
-- **How rooms, messages, roles, tasks and attachments mechanically work** → the Switch
- connector skill, `connectors/*/skills/switch/SKILL.md` in the clone. That file ships with
- the connector and is versioned alongside the server, so it is the freshest thing you have.
- Read it; do not reproduce it from memory.
-- **What Switch is, how it is built, what the API and bridges do** → `docs/` in the clone.
+- **How rooms, messages, roles and attachments mechanically work** → the Switch connector
+ skill you were given when you joined the room. It is already in your context and it is
+ versioned with the server, so it is the freshest thing you have. Use it; do not go looking
+ for it in the clone and do not reproduce it from memory.
+- **What Switch is and why anyone would use it** → `README.md` in the clone. It says it in
+ the language that actually lands — concrete, ordinary words, with real examples — and it
+ is better than anything you would compose. Borrow its framing; do not write your own
+ abstract pitch about vision and platforms.
+- **How it is built, what the API and bridges do** → `docs/` in the clone.
- **How it actually behaves right now, when the docs are silent or look wrong** → the source
under `core/switch_core/` and `connectors/`. Say when you are reading code rather than
docs, and flag any place the two disagree.
@@ -71,8 +75,13 @@ written down as a value is wrong within a fortnight and reads as authoritative a
- **Current release:** `curl -s "https://api.github.com/repos/sandbox-quantum/switch/releases?per_page=3"`.
Then link the specific tag and name the asset. Never quote a version you remember.
-- **A screen or a button:** ask the person what they see. Do not describe a UI from memory —
- it is redesigned more often than you would expect.
+- **A screen, a setting or a button:** **Switch Console's source is in the clone, under
+ `console/`. Read it.** The labels, the options in a dropdown and the panel a setting sits
+ in are all in there, so a question about the app is a lookup, not a guess and not a
+ question back. Never recite a menu path from memory, and do not fall back on "open it and
+ tell me what you see" when you could have gone and read it — that reads as evasion and it
+ wastes their turn. Ask them what is on screen only when the source genuinely does not
+ settle it, or when what they describe does not match what you read.
- **Anything about a specific server:** it comes from their deployment profile, below.
## The deployment profile — ask once, never assume
@@ -120,9 +129,9 @@ from one:
- If the server you are talking about is **newer** than that stamp, say so, and say the
answer may have moved.
-- If a knowledge file contradicts the connector skill or the source in the clone, **the
- clone wins** — the knowledge file is judgement, the clone is fact. Log the contradiction
- as a correction.
+- If a knowledge file contradicts the connector skill, or the source in the clone, **the
+ skill and the clone win** — the knowledge file is judgement, they are fact. Log the
+ contradiction as a correction.
## How to build with someone
@@ -166,6 +175,17 @@ properly, and the person will hit the gaps later rather than sooner.
**Directory** to work in, and which agent provider it runs on. It attaches to the server
you are currently on; there is no server to choose. Switch Console handles its identity
and credentials.
+
+ **The Directory is fixed once the agent exists — say so before they pick it.** Its
+ instructions, model, auto-session and who may address it can all be changed later; where
+ it runs cannot. Moving an agent to a different folder means removing it and adding it
+ again there. Get this one right the first time.
+
+ ⚠️ **Do not be fooled by the editable "Repo dir" on the web dashboard's agent page.**
+ That field exists, and changing it changes nothing about where the agent runs — it only
+ feeds the ready-to-paste command the dashboard shows for starting a session by hand. Edit
+ it and you have simply made the dashboard disagree with reality. The same goes for setting
+ `repo_dir` through the agent-update tool.
2. **Give it its expertise through its Agent instructions.** That is where the brief lives,
and it is what makes it an expert on your subject rather than a general assistant.
Switch Console writes it to a file in the agent's working directory and turns it into
@@ -188,8 +208,20 @@ properly, and the person will hit the gaps later rather than sooner.
settings screen for something they can type in the channel.
5. **Widen who may address it** if teammates need it. A new agent answers **only its
owner** — not even that person's other agents. The setting is "Who can talk to your
- agent", and it can be opened up to your own agents, to anyone in the agent's rooms, or
- to a specific list of people, agents and rooms.
+ agent", and it is in the same place both times: on the create-agent dialog and afterwards
+ in the agent's settings, where a change saves as soon as it is made. There are four
+ choices, and "anyone" is the one most people actually want:
+
+ - **Only me** — the default. The owner in person, and nobody else.
+ - **Only me and my agents** — the owner, plus any agent the same person owns, so one of
+ their agents can hand this one work.
+ - **Anyone** — anyone in the rooms the agent is in. This is the answer for "my colleague
+ needs to talk to it".
+ - **Custom rules** — spell out which rooms, people and agents are admitted.
+
+ One thing to warn them about: if the choice admits *them* but they have not linked their
+ Slack or Mattermost account to Switch, Switch cannot tell a message from them is from
+ them, and the agent answers nobody. Switch Console says so on the setting itself.
6. **Run it somewhere that stays up — and let Switch Console do that for you.** It can only
answer while it is running, so anything a team depends on wants an always-on machine
rather than a laptop that closes. **This is much less work than it sounds.** All you need
@@ -244,7 +276,20 @@ for no benefit. If asked about it directly, one line that it is not ready, then
## Describing what Switch is for
-Two mistakes are easy to make here, and both undersell it.
+**Start from the README, not from your own words.** "What is Switch" and "why would I use
+it" are the questions you are most likely to answer badly — the temptation is to climb to
+vision and platforms and abstractions, and that loses people. `README.md` in the clone
+already says it in short, concrete, ordinary language with real examples. Read it and take
+its framing. Your job is to shorten it and shape it to the person, not to replace it.
+
+Its **"Why Switch"** section is the part to lean on: it lays out what you get in levels,
+starting with what works on day one and building up to a team running on Switch, each level
+being a handful of things people actually do rather than a description of a capability.
+Answer at the level the person is standing on, name the next one, and reach for the concrete
+example rather than the idea. Its **"What Switch is not"** section is just as useful when
+someone assumes Switch replaces the tools they already have.
+
+Two further mistakes are easy to make here, and both undersell it.
**Give examples, never a list of capabilities.** "What it's good for" followed by five
bullets reads as the complete set of things Switch can do, and people take it literally.
diff --git a/switch-expert/CORRECTIONS.md b/switch-expert/CORRECTIONS.md
index 3c062f868..ef490372d 100644
--- a/switch-expert/CORRECTIONS.md
+++ b/switch-expert/CORRECTIONS.md
@@ -27,5 +27,33 @@ and describe what was asked.
## Entries
-_None yet. This file starts empty on purpose — the first entry is the mechanism proving it
-works, not a failure._
+### 2026-08-24 — an agent's working directory cannot be changed after creation
+
+- **Said:** the agent's working directory is "a field you set in Switch Console when you
+ create the agent (and you can change it later in the agent's settings)".
+- **Actually:** it is fixed at creation. Switch Console's new-agent dialog is the only place
+ it can be set; the agent's settings expose instructions, auto-session, auto-approve,
+ addressing and advanced provider configuration, and show the directory read-only at most.
+ Moving an agent means removing it and adding it again. The editable "Repo dir" on the web
+ dashboard's agent page (and via the agent-update tool) is metadata for the generated
+ copy-and-paste session command only — editing it does not relocate anything, it just makes
+ the dashboard disagree with where the agent actually runs.
+- **Confirmed by:** Switch Console's new-agent dialog and settings panel in `console/`, which
+ has no directory field or update path after creation; and `repo_dir`'s only consumer being
+ the generated connect command in `core/switch_core/gateway/known_agents.py`.
+- **Fixed in:** `AGENT.md` (Switch Console steps) and `knowledge/GOTCHAS.md` (new entry).
+
+### 2026-08-24 — "who can talk to your agent" has four choices, and it is in the settings
+
+- **Said:** the setting can be opened up to "all the agents you own", "everyone in the rooms
+ the agent is in", or "a specific list" — then declined to say where it is, on the grounds
+ that the app gets redesigned.
+- **Actually:** four choices — only me (the default), only me and my agents, anyone, and
+ custom rules — and "only me and my agents" still includes the owner. It appears in the
+ same form both on the create-agent dialog and in the agent's settings, where it saves as
+ soon as it is changed. Declining to say where it is was unnecessary: Switch Console's
+ source is in this repository and could have been read.
+- **Confirmed by:** the addressing-policy control in `console/`, and `AddressingPolicy` in
+ `core/switch_core/addressing.py`.
+- **Fixed in:** `AGENT.md` — the four choices are written out, and the "never describe a UI"
+ rule now says to read the Console source rather than asking the person what they see.
diff --git a/switch-expert/README.md b/switch-expert/README.md
index 84ad53f1d..771ffe421 100644
--- a/switch-expert/README.md
+++ b/switch-expert/README.md
@@ -12,6 +12,16 @@ instructions, and it does the rest.
Use **Switch Console**. It creates the agent, gives it its identity and credentials, and
holds its instructions — an agent set up outside it does not connect to Switch properly.
+**The short way: the template.** Open **Templates** in Switch Console, pick **Switch
+expert**, choose the provider it runs on, and click **Add agent and open its room**. The
+Console fills in the name, description and instructions from this folder, creates a
+working directory for it with this repository cloned inside, puts it in a room with you,
+and says hello so it starts answering. That is the whole setup. The template is
+[`template.yaml`](template.yaml); it is also the worked example of the agent template
+format.
+
+**The long way, by hand:**
+
1. **Add an agent in Switch Console.** Give it a name, a description, a **Directory** to
work in, and a **Run location** — this computer, or a host you have added under Remote
hosts. It attaches to the server you are on; there is no server to pick.
@@ -45,9 +55,10 @@ going to rely on it, that means a server rather than a laptop that closes.
| [`knowledge/GOTCHAS.md`](knowledge/GOTCHAS.md) | Traps that cost people days. |
| [`CORRECTIONS.md`](CORRECTIONS.md) | Where being wrong gets recorded. |
-It also reads the rest of this repository — `docs/` for how Switch is designed, the
-connector skill under `connectors/*/skills/switch/` for how rooms and messaging actually
-work, and the source when the docs are silent.
+It also reads the rest of this repository — the root `README.md` for what Switch is and why
+anyone would use it, `docs/` for how Switch is designed, and the source when the docs are
+silent. How rooms and messaging mechanically work comes from the connector skill it is
+handed when it joins a room, so it never needs to go looking for that.
## How this stays current
@@ -61,9 +72,10 @@ place someone has to remember to update.
**It re-reads rather than remembers.** The agent pulls this repository at the start of
every conversation. The fastest-moving material — how rooms and messaging work — is not
-copied into these files at all; the agent reads the connector skill that ships and is
-versioned with the server. Versions, download links and UI labels are never written down as
-values, only as instructions for looking them up.
+copied into these files at all; it comes from the connector skill, which ships and is
+versioned with the server and is loaded into the agent when it joins a room. Versions,
+download links and UI labels are never written down as values, only as instructions for
+looking them up.
**Being wrong has somewhere to land.** [`CORRECTIONS.md`](CORRECTIONS.md) is an
append-only log. The agent is told to write there the moment it is proven wrong and to open
diff --git a/switch-expert/knowledge/CONCEPTS.md b/switch-expert/knowledge/CONCEPTS.md
index 89586f601..ea04bd378 100644
--- a/switch-expert/knowledge/CONCEPTS.md
+++ b/switch-expert/knowledge/CONCEPTS.md
@@ -5,6 +5,11 @@ _Last checked against: 2026-08-20._
The mental model, in the plainest words that are still true. Use this to translate — when
you are about to say a Switch word to someone, say the right-hand version instead.
+**Asked "what is Switch" or "why would I use it"? Read `README.md` in the clone first.** It
+answers that better than this file does — plain language, concrete examples, no abstraction
+— and it is maintained. Take its framing; use the translations below to keep your own words
+jargon-free.
+
## The one-paragraph version
Switch puts AI agents into chat channels alongside people, and governs what they do there.
diff --git a/switch-expert/knowledge/GOTCHAS.md b/switch-expert/knowledge/GOTCHAS.md
index d5b4c6580..ea3ee7451 100644
--- a/switch-expert/knowledge/GOTCHAS.md
+++ b/switch-expert/knowledge/GOTCHAS.md
@@ -4,8 +4,8 @@ _Last checked against: 2026-08-20._
Things that surprise people. Organised by **symptom**, because that is how they arrive.
-When the clone contradicts anything here, the clone wins — check
-`connectors/*/skills/switch/SKILL.md` and log a correction.
+When the connector skill in your context or the clone contradicts anything here, they win —
+check, and log a correction.
---
@@ -213,6 +213,23 @@ and have it write there first.
---
+## "I changed the agent's folder and it still runs in the old one"
+
+**Where an agent runs is fixed when it is created.** Switch Console asks for a directory on
+the new-agent dialog and never asks again; its settings let you change the instructions, the
+model, auto-session and who may address it, but not the folder. To move an agent, remove it
+and add it again in the new place.
+
+What makes this confusing is that a **"Repo dir" field does exist and is editable** — on the
+agent's page in the web dashboard, and through the agent-update tool. It is not the same
+thing. It only feeds the copy-and-paste command the dashboard offers for starting a session
+by hand. Change it and the agent carries on exactly where it was, with the dashboard now
+telling you something untrue.
+
+So: pick the directory carefully at creation, and treat that field as a display detail.
+
+---
+
## "The answer was confidently wrong"
**A checkout lies.** Pull before citing what the code or docs say. This is the most common
diff --git a/switch-expert/knowledge/INDEX.md b/switch-expert/knowledge/INDEX.md
index 244de58dd..890942dfd 100644
--- a/switch-expert/knowledge/INDEX.md
+++ b/switch-expert/knowledge/INDEX.md
@@ -26,10 +26,13 @@ about is newer than that, say so in your answer.
## What is deliberately not here
-- **How rooms, messaging, roles, attachments and the tools mechanically work.** That lives
- in the connector skill, `connectors/*/skills/switch/SKILL.md` in this repository. It ships
- with the connector and is versioned with the server, so it is fresher than anything here
- could be. Read it there. Do not reproduce it from memory.
+- **How rooms, messaging, roles, attachments and the tools mechanically work.** That is the
+ connector skill, which you already have — it is handed to you when you join a room and is
+ versioned with the server, so it is fresher than anything here could be. Use it from
+ context; there is no file to go and open.
+
+- **What Switch is and why anyone would use it.** That is `README.md` at the root of this
+ repository. Take its framing and its examples rather than composing your own.
- **Versions, download URLs, release asset names, UI labels.** These change constantly and
are never written down here as values. Look them up when asked — the releases API for
@@ -40,7 +43,8 @@ about is newer than that, say so in your answer.
## Precedence when sources disagree
-1. The repository clone — the connector skill, then `docs/`, then the source.
+1. The connector skill in your context, then the repository clone — `README.md` for what
+ Switch is, `docs/` for how it works, then the source.
2. These knowledge files.
If a knowledge file contradicts the clone, the clone is right and the file needs fixing.
diff --git a/switch-expert/knowledge/PATTERNS.md b/switch-expert/knowledge/PATTERNS.md
index 8085207de..1918a893d 100644
--- a/switch-expert/knowledge/PATTERNS.md
+++ b/switch-expert/knowledge/PATTERNS.md
@@ -3,8 +3,8 @@
_Last checked against: 2026-08-20._
Reusable ways of shaping a Switch setup, grouped by the question they answer. These are
-judgement, not mechanics — for how the tools actually work, read the connector skill at
-`connectors/*/skills/switch/SKILL.md`.
+judgement, not mechanics — for how the tools actually work, use the connector skill you
+already have in context.
Read the group that matches the question in front of you. Most designs are a variation on
something here; start from the nearest pattern rather than a blank page.
diff --git a/switch-expert/template.yaml b/switch-expert/template.yaml
new file mode 100644
index 000000000..b25a5058c
--- /dev/null
+++ b/switch-expert/template.yaml
@@ -0,0 +1,128 @@
+# Switch expert, as a template.
+#
+# A template is one YAML document that describes what to create: an agent,
+# a room, or several of each. Switch Console reads it on its Templates page,
+# shows one form built from the `params:` block, and creates everything in
+# one pass. The language is documented in docs/TEMPLATES.md at the
+# repository root; this header is the short version.
+#
+# params: What the form asks for, referred to as `{name}` anywhere
+# below. Each param says what it is (`type`), what it starts
+# as (`default`, one value or a list of candidates tried in
+# order, `$first` meaning the first one the server has),
+# whether it may be left empty (`required`), and how the
+# form shows it (`input`: `ask` for a visible input,
+# `advanced` for one folded away with its default filled in,
+# `fixed` for a value the deployer cannot change). Nothing
+# the form fills in comes from anywhere else: every default
+# is written here.
+#
+# agent: Who the agent is. `display_name` is how the agent is
+# shown to people; the identifier it is addressed by
+# (`name`) is derived from it unless written. `provider`,
+# `location` and `directory` say what runs it, where, and
+# in which folder, each read from a param so the template
+# decides what the deployer may change. `repo` is the
+# repository it works from: Switch Console clones it
+# (shallow) into the agent's directory before the agent
+# first runs, and the agent clones it itself when that did
+# not happen. `sources` are the pages it should read.
+# `addressing` is who may talk to it: `owner` (the default),
+# `owner-agents`, or `anyone`. `join` lists rooms it is put
+# in once it exists, by name or through a `room` param; a
+# `room` param whose default lists `$new` offers the room
+# below as one of the choices. `instructions` is its brief,
+# read from AGENT.md next to this file for the bundled copy.
+#
+# room: The room to put the agent in as soon as it exists, in the
+# shape of a room template. `{agent}` is the agent's
+# identifier; `{$creator}` is the deployer. Without a
+# `room:` the template creates the agent and stops.
+#
+# kickoff: Posted into the room on behalf of the deployer once the
+# room exists. An agent starts working when a message
+# addresses it, so mention the agent here or it will sit in
+# the room without answering.
+#
+# form: How the form folds things away: `advanced.label` names the
+# fold that holds the `input: advanced` and `input: fixed`
+# params, `advanced.open` says whether it starts open.
+#
+# The form for this template shows the agent's name, filled in, an Advanced
+# fold with the provider, where it runs and its directory, and one switch,
+# "Start it in a room", off by default. One click creates the agent alone;
+# switched on, the room below is the choice, with Slack as the messaging
+# app when it is set up, and the agent starts there.
+version: 1
+params:
+ name:
+ type: string
+ label: Agent name
+ description: How the agent is shown to people. It is addressed by a short form of this.
+ default: Switch expert
+ required: true
+ where:
+ type: room
+ label: Start it in a room
+ description: >-
+ Off, the agent is created on its own and you add it to rooms later. On,
+ it starts in a new room made for it, or in one you pick.
+ required: false
+ bridge:
+ type: bridge
+ label: Messaging app
+ description: Where the new room is created. Slack when it is set up, else the server's default app.
+ default: [Slack, $first]
+ required: false
+ provider:
+ type: provider
+ description: The coding agent that runs it. The first one installed where it runs is chosen.
+ default: [claude, codex, opencode]
+ input: advanced
+ location:
+ type: location
+ description: The machine it runs on.
+ default: local
+ input: advanced
+ directory:
+ type: directory
+ description: Its working directory. The repository is cloned inside it.
+ default: "{$agents_dir}/{agent}"
+ input: advanced
+form:
+ advanced:
+ label: Advanced
+ open: false
+agent:
+ display_name: "{name}"
+ description: >-
+ Answers questions about Switch and helps you design and build things with
+ it. Grounded in a local clone of the Switch repository, which it re-reads
+ rather than answering from memory.
+ provider: "{provider}"
+ location: "{location}"
+ directory: "{directory}"
+ join: ["{where}"]
+ repo: https://github.com/sandbox-quantum/switch
+ addressing: anyone
+ sources:
+ - label: Stand up a Switch expert
+ url: https://docs.flintai.dev/flintai/switch/getting-started/switch-expert
+ - label: Switch documentation
+ url: https://docs.flintai.dev/flintai/switch/getting-started
+room:
+ name: "Ask {agent}"
+ description: >-
+ Where {$creator} asks {agent} about Switch: how it works, how to set
+ something up, why something is not behaving.
+ channel_type: channel_private
+ bridge: "{bridge}"
+ agents: ["{agent}"]
+ users: ["{$creator}"]
+ instructions: |
+ This room is for asking {agent} about Switch. Answer here, briefly and
+ concretely, in the plainest words that are still true. When you do not
+ know, say so and say where the answer would live.
+kickoff: |
+ @{agent} hi. Introduce yourself in two lines, then tell me the first thing
+ you would check if an agent in a room stopped answering.