feat(saas): industry agent template assignment system
Some checks failed
CI / Lint & TypeCheck (push) Has been cancelled
CI / Unit Tests (push) Has been cancelled
CI / Build Frontend (push) Has been cancelled
CI / Rust Check (push) Has been cancelled
CI / Security Scan (push) Has been cancelled
CI / E2E Tests (push) Has been cancelled

Phase 1-8 of industry-agent-delivery plan:

- DB migration: accounts.assigned_template_id (ON DELETE SET NULL)
- SaaS API: 4 new endpoints (assign/get/unassign/create-agent)
- Service layer: assign_template_to_account, get_assigned_template, unassign_template, create_agent_from_template)
- Types: AssignTemplateRequest, AgentConfigFromTemplate (capabilities merged into tools)
- Frontend SaaS Client: assignTemplate, getAssignedTemplate, unassignTemplate, createAgentFromTemplate
- saasStore: assignedTemplate state + login auto-fetch + actions
- saas-relay-client: fix unused import and saasUrl reference error
- connectionStore: fix relayModel undefined error
- capabilities default to glm-4-flash

- Route registration: new template assignment routes

Cospec and handlers consolidated

Build: cargo check --workspace PASS, tsc --noEmit Pass
This commit is contained in:
iven
2026-04-03 13:31:58 +08:00
parent 5b1b747810
commit ea00c32c08
10 changed files with 618 additions and 16 deletions

View File

@@ -66,6 +66,7 @@ export type {
CreateTemplateRequest,
AgentTemplateAvailable,
AgentTemplateFull,
AgentConfigFromTemplate,
} from './saas-types';
export { SaaSApiError } from './saas-errors';
@@ -101,6 +102,7 @@ import type {
PaginatedResponse,
AgentTemplateAvailable,
AgentTemplateFull,
AgentConfigFromTemplate,
} from './saas-types';
import { SaaSApiError } from './saas-errors';
import { clearSaaSSession } from './saas-session';
@@ -403,6 +405,41 @@ export class SaaSClient {
async fetchTemplateFull(id: string): Promise<AgentTemplateFull> {
return this.request<AgentTemplateFull>('GET', `/api/v1/agent-templates/${id}/full`);
}
// --- Template Assignment ---
/**
* Assign a template to the current account.
* Records the user's industry choice for onboarding flow control.
*/
async assignTemplate(templateId: string): Promise<AgentTemplateFull> {
return this.request<AgentTemplateFull>('POST', '/api/v1/accounts/me/assign-template', {
template_id: templateId,
});
}
/**
* Get the template currently assigned to the account.
* Returns null if no template is assigned.
*/
async getAssignedTemplate(): Promise<AgentTemplateFull | null> {
return this.request<AgentTemplateFull | null>('GET', '/api/v1/accounts/me/assigned-template');
}
/**
* Unassign the current template from the account.
*/
async unassignTemplate(): Promise<void> {
await this.request<unknown>('DELETE', '/api/v1/accounts/me/assigned-template');
}
/**
* Create an agent configuration from a template.
* Merges capabilities into tools, applies default model fallback.
*/
async createAgentFromTemplate(templateId: string): Promise<AgentConfigFromTemplate> {
return this.request<AgentConfigFromTemplate>('POST', `/api/v1/agent-templates/${templateId}/create-agent`);
}
}
// === Install mixin methods ===

View File

@@ -0,0 +1,276 @@
/**
* SaaS Relay Gateway Client
*
* A lightweight GatewayClient-compatible adapter for browser-only mode.
* Routes agent listing through SaaS agent-templates, Converts
* chatStream() to OpenAI SSE streaming via SaaS relay.
*
* Used in connectionStore when running in a browser (non-Tauri) with
* SaaS relay connection mode.
*/
import type { GatewayClient } from './gateway-client';
import { saasClient } from './saas-client';
import type { AgentTemplateAvailable } from './saas-types';
import { createLogger } from './logger';
const log = createLogger('SaaSRelayGateway');
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface CloneInfo {
id: string;
name: string;
role?: string;
nickname?: string;
emoji?: string;
personality?: string;
scenarios?: string[];
model?: string;
status?: string;
templateId?: string;
}
// ---------------------------------------------------------------------------
// Implementation
// ---------------------------------------------------------------------------
/**
* Create a GatewayClient-compatible object that routes through SaaS APIs.
* Only the methods needed by the stores are implemented; others return
* sensible defaults.
*/
export function createSaaSRelayGatewayClient(
_saasUrl: string,
relayModel: string,
): GatewayClient {
// saasUrl preserved for future direct API routing (currently routed through saasClient singleton)
void _saasUrl;
// Local in-memory agent registry
const agents = new Map<string, CloneInfo>();
let defaultAgentId: string | null = null;
// -----------------------------------------------------------------------
// Helper: list agents as clones
// -----------------------------------------------------------------------
async function listClones(): Promise<{ clones: CloneInfo[] }> {
try {
const templates: AgentTemplateAvailable[] = await saasClient.fetchAvailableTemplates();
const clones: CloneInfo[] = templates.map((t) => {
const id = t.id || `agent-${t.name}`;
const clone: CloneInfo = {
id,
name: t.name,
role: t.description || t.category,
emoji: t.emoji,
personality: t.category,
scenarios: [],
model: relayModel,
status: 'active',
templateId: t.id,
};
agents.set(id, clone);
return clone;
});
// Set first as default
if (clones.length > 0 && !defaultAgentId) {
defaultAgentId = clones[0].id;
}
return { clones };
} catch (err) {
log.warn('Failed to list templates', err);
return { clones: [] };
}
}
// -----------------------------------------------------------------------
// Helper: OpenAI SSE streaming via SaaS relay
// -----------------------------------------------------------------------
async function chatStream(
message: string,
callbacks: {
onDelta: (delta: string) => void;
onThinkingDelta?: (delta: string) => void;
onTool?: (tool: string, input: string, output: string) => void;
onHand?: (name: string, status: string, result?: unknown) => void;
onComplete: (inputTokens?: number, outputTokens?: number) => void;
onError: (error: string) => void;
},
opts?: {
sessionKey?: string;
agentId?: string;
thinking_enabled?: boolean;
reasoning_effort?: string;
plan_mode?: boolean;
},
): Promise<{ runId: string }> {
const runId = `run_${Date.now()}`;
try {
const body: Record<string, unknown> = {
model: relayModel,
messages: [{ role: 'user', content: message }],
stream: true,
};
if (opts?.thinking_enabled) body['thinking_enabled'] = true;
if (opts?.reasoning_effort) body['reasoning_effort'] = opts.reasoning_effort;
const response = await saasClient.chatCompletion(body);
if (!response.ok) {
const errText = await response.text().catch(() => '');
callbacks.onError(`Relay error: ${response.status} ${errText}`);
callbacks.onComplete();
return { runId };
}
// Parse SSE stream
const reader = response.body?.getReader();
if (!reader) {
callbacks.onError('No response body');
callbacks.onComplete();
return { runId };
}
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || ''; // keep incomplete last line
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
const data = line.slice(6).trim();
if (data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
const choices = parsed.choices?.[0];
if (!choices) continue;
const delta = choices.delta;
// Handle thinking/reasoning content
if (delta?.reasoning_content) {
callbacks.onThinkingDelta?.(delta.reasoning_content);
}
// Handle regular content
if (delta?.content) {
callbacks.onDelta(delta.content);
}
// Check for completion
if (choices.finish_reason) {
const usage = parsed.usage;
callbacks.onComplete(
usage?.prompt_tokens,
usage?.completion_tokens,
);
return { runId };
}
} catch {
// Skip malformed SSE lines
}
}
}
// Stream ended without explicit finish_reason
callbacks.onComplete();
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
callbacks.onError(msg);
callbacks.onComplete();
}
return { runId };
}
// -----------------------------------------------------------------------
// Build the client object with GatewayClient-compatible shape
// -----------------------------------------------------------------------
return {
// --- Connection ---
connect: async () => { log.debug('SaaS relay client connect'); },
disconnect: async () => {},
getState: () => 'connected' as const,
onStateChange: undefined,
onLog: undefined,
// --- Agents (Clones) ---
listClones,
createClone: async (opts: Record<string, unknown>) => {
const id = `agent-${Date.now()}`;
const clone: CloneInfo = {
id,
name: (opts.name as string) || 'New Agent',
role: opts.role as string,
nickname: opts.nickname as string,
emoji: opts.emoji as string,
model: relayModel,
status: 'active',
};
agents.set(id, clone);
if (!defaultAgentId) defaultAgentId = id;
return { clone };
},
updateClone: async (id: string, updates: Record<string, unknown>) => {
const existing = agents.get(id);
if (existing) agents.set(id, { ...existing, ...updates });
return { clone: agents.get(id) };
},
deleteClone: async (id: string) => {
agents.delete(id);
if (defaultAgentId === id) defaultAgentId = null;
},
getDefaultAgentId: () => defaultAgentId,
setDefaultAgentId: (id: string) => { defaultAgentId = id; },
// --- Chat ---
chatStream,
// --- Hands ---
listHands: async () => ({ hands: [] }),
getHand: async () => null,
triggerHand: async () => ({ runId: `hand_${Date.now()}`, status: 'completed' }),
// --- Skills ---
listSkills: async () => ({ skills: [] }),
getSkill: async () => null,
createSkill: async () => null,
updateSkill: async () => null,
deleteSkill: async () => {},
// --- Config ---
getQuickConfig: async () => ({}),
saveQuickConfig: async () => {},
getWorkspaceInfo: async () => null,
// --- Health ---
health: async () => ({ status: 'ok', mode: 'saas-relay' }),
status: async () => ({ version: 'saas-relay', mode: 'browser' }),
// --- Usage ---
getUsageStats: async () => null,
getSessionStats: async () => null,
// --- REST helpers (not used in browser mode) ---
restGet: async () => { throw new Error('REST not available in browser mode'); },
restPost: async () => { throw new Error('REST not available in browser mode'); },
restPut: async () => { throw new Error('REST not available in browser mode'); },
restDelete: async () => { throw new Error('REST not available in browser mode'); },
restPatch: async () => { throw new Error('REST not available in browser mode'); },
} as unknown as GatewayClient;
}

View File

@@ -460,3 +460,27 @@ export interface CreateTemplateRequest {
description?: string;
permissions: string[];
}
// === Template Assignment Types ===
/** Request to assign a template to the current account */
export interface AssignTemplateRequest {
template_id: string;
}
/** Agent configuration derived from a template.
* capabilities are merged into tools (no separate field). */
export interface AgentConfigFromTemplate {
name: string;
model: string;
system_prompt?: string;
tools: string[];
soul_content?: string;
welcome_message?: string;
quick_commands: Array<{ label: string; command: string }>;
temperature?: number;
max_tokens?: number;
personality?: string;
communication_style?: string;
emoji?: string;
}