Skip to content

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

Console knows the buddy by the template that made it

Simon Flack2367302b4297
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.ts b/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.ts
index b99d5dcaf..18a4ccaa0 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-agents/controller.ts
@@ -111,6 +111,7 @@ export const managedAgentsController = createRPCController({
: null,
desiredState: agent.desiredState,
revision: agent.revision,
+ ...(agent.template !== undefined ? { template: agent.template } : {}),
definition: {
provider: agent.provider,
model: agent.model,
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 1fb327b41..4658dbdd2 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
@@ -13,6 +13,7 @@ import { type CloudMachine, cloudMachineSchema } from '@shared/core/cloud-agents
import type { RemoteFeatureFlag } from '@shared/core/feature-flags/feature-flags';
import type {
AdvancedConfigField,
+ ManagedAgentTemplate,
ManagedMachine,
} from '@shared/core/managed-agents/managed-agents';
import { ManagedServerStoppedError } from '@shared/core/managed-switch-server/managed-switch-server';
@@ -2487,6 +2488,12 @@ export async function runTemplateDocument(
/** Existing agents standing in for slots that allow it, by resource key. */
filled: Record<string, string>;
templateName: string;
+ /**
+ * The template the document is, when it is one: the server records the run
+ * as that template's, to update its agents from, only when the document is
+ * exactly the template's.
+ */
+ templateId: string | null;
}
): Promise<TemplateRunResult> {
return postTemplateRun(server, '/rooms/from-template-document', {
@@ -2494,6 +2501,7 @@ export async function runTemplateDocument(
inputs: body.inputs,
filled: body.filled,
template_name: body.templateName,
+ ...(body.templateId !== null ? { template_id: body.templateId } : {}),
});
}
@@ -3735,6 +3743,12 @@ export type ManagedAgent = {
machine?: ManagedMachine | null;
desiredState: 'running' | 'stopped';
revision: number;
+ /**
+ * The template that created it, as the server's record of that run has it:
+ * null for an agent no template run the server vouches for created, and
+ * undefined from a server too old to say.
+ */
+ template?: ManagedAgentTemplate | null;
provider: string;
model: string | null;
/** The provider's advanced configuration, keyed by its field keys; unset fields are absent. */
@@ -3786,6 +3800,8 @@ type ManagedAgentJson = {
desired_state: 'running' | 'stopped';
description?: string;
revision?: number;
+ /** Absent from servers older than template installs. */
+ template?: { id: string; key: string; revision: number } | null;
definition: {
provider?: unknown;
model?: unknown;
@@ -3999,6 +4015,7 @@ function toManagedAgent(json: ManagedAgentJson): ManagedAgent {
machine: machineOf(json),
desiredState: json.desired_state,
revision: json.revision ?? 0,
+ ...(json.template !== undefined ? { template: json.template } : {}),
provider: typeof json.definition?.provider === 'string' ? json.definition.provider : 'unknown',
model: typeof json.definition?.model === 'string' ? json.definition.model : null,
advancedConfig: advancedConfigOf(json.agent_id, json.definition?.advanced_config),
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts
index e07f0d349..552af2657 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.test.ts
@@ -446,6 +446,7 @@ describe('reporting what a template made', () => {
inputs: {},
filled: {},
templateName: 'Buddy',
+ templateId: null,
entryPoint: 'onboarding',
});
@@ -518,6 +519,7 @@ describe('reporting what a template made', () => {
inputs: {},
filled: {},
templateName: 'T',
+ templateId: null,
entryPoint: 'template',
});
@@ -561,6 +563,7 @@ describe('reporting what a template made', () => {
inputs: {},
filled: {},
templateName: 'T',
+ templateId: null,
entryPoint: 'template',
});
diff --git a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts
index 496ba3327..e1b944e04 100644
--- a/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/workspaces/controller.ts
@@ -763,6 +763,8 @@ export const workspacesController = createRPCController({
inputs: Record<string, string | number | boolean>;
filled: Record<string, string>;
templateName: string;
+ /** The template the document is, when it is one; see `runTemplateDocument`. */
+ templateId: string | null;
/** Where the run was started, for the agents it makes. */
entryPoint: UiEntryPoint;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-identity.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-identity.test.ts
index dba86e4d1..e7d616e04 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-identity.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-identity.test.ts
@@ -28,6 +28,17 @@ describe('isBuddy', () => {
expect(isBuddy({ name: 'helper' })).toBe(false);
expect(isBuddy({ name: 'switch-buddyish' })).toBe(false);
});
+
+ it("goes by the server's record of the template that made it, when there is one", () => {
+ const buddy = { id: 'official:switch-buddy', key: 'buddy', revision: 9 };
+ expect(isBuddy({ name: 'renamed-by-max', template: buddy })).toBe(true);
+ expect(
+ isBuddy({ name: 'switch-buddy-max', template: { id: 'tpl-1', key: 'helper', revision: 1 } })
+ ).toBe(false);
+ // No record (null), or a server too old to keep one (absent): the name decides.
+ expect(isBuddy({ name: 'switch-buddy-max', template: null })).toBe(true);
+ expect(isBuddy({ name: 'helper', template: null })).toBe(false);
+ });
});
describe('buddyIsPending', () => {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-identity.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-identity.ts
index 54843297e..865efe9b6 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-identity.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-identity.ts
@@ -4,6 +4,9 @@ import type { ManagedAgentView } from '@shared/core/managed-agents/managed-agent
/** The template every person's buddy is created from, served by the server. */
export const BUDDY_TEMPLATE_ID = 'official:switch-buddy';
+/** The template's key for the buddy among what it creates. */
+export const BUDDY_KEY = 'buddy';
+
/** What the buddy is, whoever's it is: each one is shown by its own name, switch-buddy-<person>. */
export const BUDDY_KIND = 'switch-buddy';
@@ -37,13 +40,21 @@ export function buddyAgentName(
}
/**
- * Whether one of the person's own managed agents is their buddy: named as
- * buddies are created (`switch-buddy` or `switch-buddy-<person>`). Read off
- * the name rather than the picture, which the person, or the buddy itself,
- * may change; the list holds only their own agents, so another person's
- * buddy is never taken for theirs.
+ * Whether one of the person's own managed agents is their buddy.
+ *
+ * The server records which template run created an agent: when it says, that
+ * decides (the buddy is what switch-buddy's template created as `buddy`, so an
+ * agent another template made is never taken for it, whatever its name). An
+ * agent with no record, or from a server too old to keep one, is read off its
+ * name instead: named as buddies are created (`switch-buddy` or
+ * `switch-buddy-<person>`). The list holds only the person's own agents, so
+ * another person's buddy is never taken for theirs.
*/
-export function isBuddy(agent: Pick<ManagedAgentView, 'name'>): boolean {
+export function isBuddy(
+ agent: Pick<ManagedAgentView, 'name'> & Partial<Pick<ManagedAgentView, 'template'>>
+): boolean {
+ if (agent.template)
+ return agent.template.id === BUDDY_TEMPLATE_ID && agent.template.key === BUDDY_KEY;
return agent.name === NAME_PREFIX || agent.name.startsWith(`${NAME_PREFIX}-`);
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/create-buddy.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/create-buddy.ts
index c865abe27..04c83497f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/create-buddy.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/create-buddy.ts
@@ -59,6 +59,7 @@ async function createBuddyAgent(input: {
inputs: { agent_name: name, provider: input.provider, machine: input.machineId },
filled: {},
templateName: template.name,
+ templateId: BUDDY_TEMPLATE_ID,
entryPoint: input.entryPoint,
});
if (result.kind === 'created') {
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
index 307a36a0a..2ab8c73db 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx
@@ -1260,6 +1260,7 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
inputs,
filled,
templateName: loaded.name,
+ templateId: templateId ?? null,
entryPoint: 'template',
});
} catch (e) {
diff --git a/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts b/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts
index 54fcdea07..ee6ee41b3 100644
--- a/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/managed-agents/managed-agents.ts
@@ -20,6 +20,12 @@ export type ManagedAgentView = {
machine: ManagedMachine | null;
desiredState: 'running' | 'stopped';
revision: number;
+ /**
+ * The template that created it, as the server's record of that run has it:
+ * null for an agent no template run the server vouches for created, and
+ * undefined from a server too old to say.
+ */
+ template?: ManagedAgentTemplate | null;
definition: {
provider: string;
model: string | null;
@@ -48,6 +54,9 @@ export type ManagedAgentView = {
} | null;
};
+/** The template run that created an agent: the template's id, its key for the agent, and the revision it follows. */
+export type ManagedAgentTemplate = { id: string; key: string; revision: number };
+
/** A machine a managed agent can be placed on. */
export type ManagedMachine = {
id: string;
diff --git a/core/switch_core/db/stores/template_install_store.py b/core/switch_core/db/stores/template_install_store.py
index 167acca20..42c900834 100644
--- a/core/switch_core/db/stores/template_install_store.py
+++ b/core/switch_core/db/stores/template_install_store.py
@@ -190,3 +190,33 @@ class TemplateInstallStore:
for agent_id, notice in rows.tuples()
if agent_id is not None and notice is not None
}
+
+ async def templates_of_agents(
+ self, session: AsyncSession, agent_ids: list[str]
+ ) -> dict[str, dict[str, Any]]:
+ """The template that created each of these agents, {id, key,
+ revision}, for those an install records."""
+ if not agent_ids:
+ return {}
+ rows = await session.execute(
+ select(
+ TemplateInstallResource.agent_id,
+ TemplateInstallResource.key,
+ TemplateInstall.template_id,
+ TemplateInstall.revision,
+ )
+ .join(
+ TemplateInstall,
+ (TemplateInstallResource.install_id == TemplateInstall.id)
+ & (TemplateInstallResource.tenant_id == TemplateInstall.tenant_id),
+ )
+ .where(
+ TemplateInstallResource.tenant_id == require_tenant_id(),
+ TemplateInstallResource.agent_id.in_(agent_ids),
+ )
+ )
+ return {
+ agent_id: {"id": template_id, "key": key, "revision": revision}
+ for agent_id, key, template_id, revision in rows.tuples()
+ if agent_id is not None
+ }
diff --git a/core/switch_core/management/schemas.py b/core/switch_core/management/schemas.py
index 1dc4f1ac7..0897c54a9 100644
--- a/core/switch_core/management/schemas.py
+++ b/core/switch_core/management/schemas.py
@@ -647,7 +647,11 @@ def managed_agent_view(
agent: Agent,
controller: AgentController | None,
controller_state: str | None,
+ template: dict[str, Any] | None,
) -> dict[str, Any]:
+ """`template` is the template that created the agent, as its install
+ records it ({id, key, revision}), or None for one no template run the
+ server vouches for created."""
return {
"agent_id": agent.id,
"name": agent.name,
@@ -662,6 +666,7 @@ def managed_agent_view(
"revision": row.revision,
"definition": stored_definition(row.definition),
"status": agent_status_from(controller, agent.id),
+ "template": template,
"created_at": wire_time(row.created_at),
"updated_at": wire_time(row.updated_at),
}
diff --git a/core/switch_core/management/service.py b/core/switch_core/management/service.py
index 34bde61f8..4ab24dc9a 100644
--- a/core/switch_core/management/service.py
+++ b/core/switch_core/management/service.py
@@ -68,6 +68,7 @@ from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.api_key_store import ApiKeyStore
from switch_core.db.stores.hosted_machine_store import CloudMachineStore
from switch_core.db.stores.switch_core_process_store import SwitchCoreProcessStore
+from switch_core.db.stores.template_install_store import TemplateInstallStore
from switch_core.gateway.cloud_controllers import (
enroll_revoked_again,
record_controller_status,
@@ -103,6 +104,7 @@ from switch_core.process_lease import ProcessLeases, read_leases
from switch_core.providers.registry import provider_ids
from switch_core.user_changes import MACHINE, MANAGED_AGENT, UserChangePublisher
+_INSTALLS = TemplateInstallStore()
logger = logging.getLogger(__name__)
OPERATION_LEASE = timedelta(minutes=5)
@@ -1132,7 +1134,11 @@ class ManagementService:
agent: Agent,
controllers: dict[str, AgentController],
leases: ProcessLeases,
+ templates: dict[str, dict[str, Any]] | None = None,
) -> dict[str, Any]:
+ """The managed agent as the API shows it. `templates` is what
+ `templates_of_agents` read for a list of agents at once; without it,
+ this agent's is read."""
controller = None
if row.controller_id is not None:
controller = controllers.get(row.controller_id)
@@ -1142,11 +1148,14 @@ class ManagementService:
)
if controller is not None:
controllers[controller.id] = controller
+ if templates is None:
+ templates = await _INSTALLS.templates_of_agents(session, [agent.id])
return managed_agent_view(
row,
agent,
controller,
self.state_of(controller, leases) if controller is not None else None,
+ templates.get(agent.id),
)
async def list_managed_agents(
@@ -1159,11 +1168,15 @@ class ManagementService:
)
}
leases = await self.leases(session)
+ owned = await self.definitions.list_for_owner(session, tenant_id, owner_id)
+ templates = await _INSTALLS.templates_of_agents(
+ session, [agent.id for _, agent in owned]
+ )
return [
- await self._view(session, tenant_id, row, agent, controllers, leases)
- for row, agent in await self.definitions.list_for_owner(
- session, tenant_id, owner_id
+ await self._view(
+ session, tenant_id, row, agent, controllers, leases, templates
)
+ for row, agent in owned
]
async def _owned_agent(
diff --git a/core/tests/switch_core/fixtures/agent_controllers/stream_frames.json b/core/tests/switch_core/fixtures/agent_controllers/stream_frames.json
index 910ffa49c..c04cefa06 100644
--- a/core/tests/switch_core/fixtures/agent_controllers/stream_frames.json
+++ b/core/tests/switch_core/fixtures/agent_controllers/stream_frames.json
@@ -55,7 +55,8 @@
"thread_id": null,
"attachments": [],
"opening_message": null,
- "sender_role": null
+ "sender_role": null,
+ "switch_notice": null
},
"sequence": 1,
"missed": {
diff --git a/core/tests/switch_core/management/test_template_updates.py b/core/tests/switch_core/management/test_template_updates.py
index 12fcbf924..f11cb3882 100644
--- a/core/tests/switch_core/management/test_template_updates.py
+++ b/core/tests/switch_core/management/test_template_updates.py
@@ -397,3 +397,40 @@ async def _as(agent_id: str, fn: Any, **kwargs: Any) -> Any:
return await fn(**kwargs)
finally:
reset_call_context(token)
+
+
+async def test_a_managed_agent_says_which_template_made_it(
+ harness: Harness, client: httpx.AsyncClient
+) -> None:
+ owner = await add_member(harness.session_factory, "ada")
+ agent_id = await _create_buddy(harness, client, owner, "switch-buddy-ada")
+ await _create_buddy(harness, client, owner, "my-helper")
+ await _forget_install(
+ harness,
+ next(
+ a["agent_id"]
+ for a in await _managed(harness, owner)
+ if a["name"] == "my-helper"
+ ),
+ )
+
+ listed = {a["name"]: a for a in await _managed(harness, owner)}
+
+ assert listed["switch-buddy-ada"]["template"] == {
+ "id": BUDDY_ID,
+ "key": "buddy",
+ "revision": _buddy().version,
+ }
+ assert listed["my-helper"]["template"] is None
+ async with harness.session_factory() as session:
+ one = await harness.management.service.get_managed_agent(
+ session, TENANT_ZERO_ID, owner.id, agent_id
+ )
+ assert one["template"] == listed["switch-buddy-ada"]["template"]
+
+
+async def _managed(harness: Harness, owner: User) -> list[dict[str, Any]]:
+ async with harness.session_factory() as session:
+ return await harness.management.service.list_managed_agents(
+ session, TENANT_ZERO_ID, owner.id
+ )