π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(llm-relay): server system-agent tasks relay device-only models to the requesting tab (#20457)
Arvin Xuccad6d09887d
diff --git a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts b/apps/server/src/routers/lambda/__tests__/aiChat.test.tsindex 0e2a6e9a0fb..4206c288c22 100644--- a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts@@ -1202,7 +1202,7 @@ describe('aiChatRouter', () => {const result = await caller.outputJSON(input);- expect(initModelRuntimeFromDB).toHaveBeenCalledWith({}, 'u1', 'openai');+ expect(initModelRuntimeFromDB).toHaveBeenCalledWith({}, 'u1', 'openai', undefined);expect(mockGenerateObject).toHaveBeenCalledWith({messages: input.messages,diff --git a/apps/server/src/routers/lambda/__tests__/aiProvider.test.ts b/apps/server/src/routers/lambda/__tests__/aiProvider.test.tsindex b1abd9c48ad..767411cf93c 100644--- a/apps/server/src/routers/lambda/__tests__/aiProvider.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiProvider.test.ts@@ -29,6 +29,18 @@ vi.mock('@/database/models/user');vi.mock('@/server/modules/ModelRuntime', () => ({initModelRuntimeFromDB: vi.fn(),}));++const resolveProviderRelay = vi.hoisted(() => vi.fn());+vi.mock('@/server/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite', () => ({+ resolveProviderRelay,+}));+// A deployment that can relay (Agent Gateway + Redis); one that cannot keeps+// calling the provider from the server.+vi.mock('@/server/modules/AgentRuntime/redis', () => ({ getAgentRuntimeRedisClient: () => ({}) }));+vi.mock('@/server/modules/AgentRuntime/factory', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ createStreamEventManager: () => ({ openLlmRelayChannel: vi.fn(), sendLlmExecute: vi.fn() }),+}));vi.mock('@lobechat/business-const', async () => {const actual = await vi.importActual<typeof BusinessConst>('@lobechat/business-const');@@ -88,7 +100,7 @@ describe('aiProviderRouter', () => {describe('checkProviderConnectivity', () => {it('should pass api trigger metadata to the runtime connectivity check', async () => {- const mockChat = vi.fn().mockResolvedValue({ ok: true });+ const mockChat = vi.fn().mockResolvedValue(new Response('{}'));const mockGetDetail = vi.fn().mockResolvedValue({ ...mockProviderDetail, checkModel: 'gpt-4' });@@ -112,6 +124,44 @@ describe('aiProviderRouter', () => {},);});++ // A relayed check streams even with `stream: false`: the device's provider+ // failure is an `error` event in a 200 body, not an error status.+ it('reports a provider error carried in the response stream as a failed check', async () => {+ const body = 'event: error\ndata: {"errorType":"OllamaServiceUnavailable"}\n\n';+ vi.mocked(AiInfraRepos).prototype.getAiProviderDetail = vi+ .fn()+ .mockResolvedValue({ ...mockProviderDetail, checkModel: 'gpt-4' });+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({+ chat: vi.fn().mockResolvedValue(new Response(body)),+ } as any);++ const caller = aiProviderRouter.createCaller(createMockContext());+ const result = await caller.checkProviderConnectivity({ id: mockProviderId });++ expect(result).toEqual({+ error: '{"errorType":"OllamaServiceUnavailable"}',+ model: 'gpt-4',+ ok: false,+ });+ });++ it('reports a device-only provider checked with no browser tab attached (CLI)', async () => {+ resolveProviderRelay.mockResolvedValueOnce({ runtimeProvider: 'ollama' });+ vi.mocked(AiInfraRepos).prototype.getAiProviderDetail = vi+ .fn()+ .mockResolvedValue({ ...mockProviderDetail, checkModel: 'qwen3:1.7b' });++ const caller = aiProviderRouter.createCaller(createMockContext());+ const result = await caller.checkProviderConnectivity({ id: 'ollama' });++ expect(result).toEqual({+ error: 'ClientLlmExecutorUnavailable',+ model: 'qwen3:1.7b',+ ok: false,+ });+ expect(initModelRuntimeFromDB).not.toHaveBeenCalled();+ });});describe('createAiProvider', () => {diff --git a/apps/server/src/routers/lambda/aiProvider.ts b/apps/server/src/routers/lambda/aiProvider.tsindex bbc078b2442..93d549c8f7f 100644--- a/apps/server/src/routers/lambda/aiProvider.ts+++ b/apps/server/src/routers/lambda/aiProvider.ts@@ -21,8 +21,8 @@ import { AiInfraRepos } from '@/database/repositories/aiInfra';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { getServerGlobalConfig } from '@/server/globalConfig';+import { initModelRuntimeForRequest } from '@/server/modules/AgentRuntime/llmRelay/oneShot';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';-import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { getUserScopedAiProviderRuntimeState } from '@/server/services/aiProviderAccess';import { type AiProviderDetailItem, type AiProviderRuntimeState } from '@/types/aiProvider';import {@@ -94,12 +94,11 @@ export const aiProviderRouter = router({}try {- const modelRuntime = await initModelRuntimeFromDB(- ctx.serverDB,- ctx.userId,- input.id,- ctx.workspaceId ?? undefined,- );+ // A device-only provider is checked through the requesting tab+ // (one-shot relay); from the CLI it has no tab and reports so.+ const modelRuntime = await initModelRuntimeForRequest(ctx.serverDB, ctx.userId, input.id, {+ workspaceId: ctx.workspaceId ?? undefined,+ });const response = await modelRuntime.chat({@@ -113,8 +112,14 @@ export const aiProviderRouter = router({},);- // If we get a response without error, connectivity is ok+ // If we get a response without error, connectivity is ok. A relayed+ // call always streams: the device's provider error arrives as an+ // `error` event in the body rather than as the status.if (response.ok) {+ const body = await response.text();+ const relayedError = /^event: error\ndata: (.*)$/m.exec(body);+ if (relayedError) return { error: relayedError[1], model, ok: false };+return { model, ok: true };}diff --git a/apps/server/src/services/aiGeneration/index.test.ts b/apps/server/src/services/aiGeneration/index.test.tsindex 2955a3db334..dd5c5dd354a 100644--- a/apps/server/src/services/aiGeneration/index.test.ts+++ b/apps/server/src/services/aiGeneration/index.test.ts@@ -2,10 +2,23 @@import { RequestTrigger } from '@lobechat/types';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { runWithLlmRelayRequest } from '@/server/modules/AgentRuntime/llmRelay/requestScope';import * as ModelRuntimeModule from '@/server/modules/ModelRuntime';import { AiGenerationService } from './index';+const resolveProviderRelay = vi.hoisted(() => vi.fn());+vi.mock('@/server/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite', () => ({+ resolveProviderRelay,+}));+// A deployment that can relay (Agent Gateway + Redis); one that cannot keeps+// calling the provider from the server.+vi.mock('@/server/modules/AgentRuntime/redis', () => ({ getAgentRuntimeRedisClient: () => ({}) }));+vi.mock('@/server/modules/AgentRuntime/factory', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ createStreamEventManager: () => ({ openLlmRelayChannel: vi.fn(), sendLlmExecute: vi.fn() }),+}));+describe('AiGenerationService.generateObject', () => {const generateObject = vi.fn();const initSpy = vi.spyOn(ModelRuntimeModule, 'initModelRuntimeFromDB');@@ -27,7 +40,7 @@ describe('AiGenerationService.generateObject', () => {},{ metadata: { trigger: RequestTrigger.Chat } },);- expect(initSpy).toHaveBeenCalledWith({}, 'user-1', 'openai');+ expect(initSpy).toHaveBeenCalledWith({}, 'user-1', 'openai', undefined);});it('forwards messages / model / schema / tools / thinking verbatim to the runtime', async () => {@@ -100,3 +113,40 @@ describe('AiGenerationService.generateObject', () => {expect(result.completion).toBe('hello world');});});++describe('AiGenerationService.generateObject with a device-only provider', () => {+ const initSpy = vi.spyOn(ModelRuntimeModule, 'initModelRuntimeFromDB');++ beforeEach(() => {+ initSpy.mockReset();+ resolveProviderRelay.mockReset();+ resolveProviderRelay.mockResolvedValue({ runtimeProvider: 'ollama' });+ });++ const generate = () =>+ new AiGenerationService({} as any, 'user-1').generateObject(+ { messages: [{ content: 'hi', role: 'user' }], model: 'qwen3:1.7b', provider: 'ollama' },+ { metadata: { trigger: RequestTrigger.TopicSummary } },+ );++ // Topic auto summary, task lifecycle, verify: a workflow or a hook with no+ // browser tab. The server cannot reach the user's local model, so it must+ // not try β it fails at once, before any provider call.+ it('fails at once with no_executor in background work (no browser tab)', async () => {+ await expect(generate()).rejects.toMatchObject({+ error: { context: 'no_client_request', reason: 'no_executor' },+ errorType: 'ClientLlmExecutorUnavailable',+ });+ expect(initSpy).not.toHaveBeenCalled();+ });++ it('never relays to a request that named a channel the user does not own', async () => {+ await expect(+ runWithLlmRelayRequest(+ { channel: 'llmcall:someone-else:0b7c1d2e-aaaa', clientId: 'tab-1' },+ 'user-1',+ generate,+ ),+ ).rejects.toMatchObject({ error: { reason: 'no_executor' } });+ });+});diff --git a/apps/server/src/services/aiGeneration/index.ts b/apps/server/src/services/aiGeneration/index.tsindex 8ce48532721..9892f286cd0 100644--- a/apps/server/src/services/aiGeneration/index.ts+++ b/apps/server/src/services/aiGeneration/index.ts@@ -6,7 +6,7 @@ import type {import type { OpenAIChatMessage, RequestTrigger } from '@lobechat/types';import type { LobeChatDatabase } from '@/database/type';-import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import { initModelRuntimeForRequest } from '@/server/modules/AgentRuntime/llmRelay/oneShot';export interface AiGenerationObjectInput {messages: OpenAIChatMessage[] | GenerateObjectPayload['messages'];@@ -38,7 +38,7 @@ export interface AiGenerationObjectOptions {}/**- * Thin wrapper around `initModelRuntimeFromDB` + `ModelRuntime.generateObject`.+ * Thin wrapper around `initModelRuntimeForRequest` + `ModelRuntime.generateObject`.** Almost every server-side caller that produces structured output goes through* the same two-step dance: resolve the user's provider config from the DB,@@ -48,6 +48,11 @@ export interface AiGenerationObjectOptions {* has one place to land.** Construct one per request β `db` and `userId` come from the request context.+ *+ * A provider only the user's device reaches (Ollama, LM Studio, a private base+ * URL; `agent_llm_relay` on) is relayed to the browser tab that sent the+ * request; with no such tab β a bot, a workflow, deferred work β the call+ * fails at once with `ClientLlmExecutorUnavailable` (`no_executor`).*/export class AiGenerationService {private readonly db: LobeChatDatabase;@@ -64,9 +69,9 @@ export class AiGenerationService {input: AiGenerationObjectInput,options: AiGenerationObjectOptions,): Promise<T> {- const runtime = this.workspaceId- ? await initModelRuntimeFromDB(this.db, this.userId, input.provider, this.workspaceId)- : await initModelRuntimeFromDB(this.db, this.userId, input.provider);+ const runtime = await initModelRuntimeForRequest(this.db, this.userId, input.provider, {+ workspaceId: this.workspaceId,+ });return (await runtime.generateObject({messages: input.messages as GenerateObjectPayload['messages'],diff --git a/apps/server/src/services/followUpAction/index.test.ts b/apps/server/src/services/followUpAction/index.test.tsindex fb098a01d4c..c758f329ca9 100644--- a/apps/server/src/services/followUpAction/index.test.ts+++ b/apps/server/src/services/followUpAction/index.test.ts@@ -174,6 +174,7 @@ describe('FollowUpActionService.extract', () => {dbMock,TEST_USER,'custom-provider',+ undefined,);expect(runtimeMock.generateObject).toHaveBeenCalledWith(expect.objectContaining({diff --git a/apps/server/src/services/systemAgent/index.test.ts b/apps/server/src/services/systemAgent/index.test.tsindex fbad8d92106..4edb894ddb8 100644--- a/apps/server/src/services/systemAgent/index.test.ts+++ b/apps/server/src/services/systemAgent/index.test.ts@@ -15,8 +15,21 @@ vi.mock('@/database/models/user', () => ({},}));+const resolveProviderRelay = vi.hoisted(() => vi.fn());+vi.mock('@/server/modules/AgentRuntime/llmRelay/resolveLlmExecutionSite', () => ({+ resolveProviderRelay,+}));+// A deployment that can relay (Agent Gateway + Redis); one that cannot keeps+// calling the provider from the server.+vi.mock('@/server/modules/AgentRuntime/redis', () => ({ getAgentRuntimeRedisClient: () => ({}) }));+vi.mock('@/server/modules/AgentRuntime/factory', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ createStreamEventManager: () => ({ openLlmRelayChannel: vi.fn(), sendLlmExecute: vi.fn() }),+}));+afterEach(() => {vi.restoreAllMocks();+ resolveProviderRelay.mockReset();});describe('SystemAgentService.generateTopicTitle', () => {@@ -50,3 +63,31 @@ describe('SystemAgentService.generateTopicTitle', () => {}});});++describe('SystemAgentService with a device-only system agent model', () => {+ // A bot conversation's topic title runs from a webhook: there is no browser+ // tab to relay a local model to. It must fail fast (no provider call from the+ // server) and leave the caller on its default title.+ it('gives up on the topic title at once when no browser tab is attached', async () => {+ resolveProviderRelay.mockResolvedValue({ runtimeProvider: 'ollama' });+ const init = vi.spyOn(ModelRuntimeModule, 'initModelRuntimeFromDB');+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const service = new SystemAgentService({} as LobeChatDatabase, 'user-1');++ const title = await service.generateTopicTitle({+ lastAssistantContent: 'Here is the answer.',+ topicId: 'topic-a',+ userPrompt: 'A question',+ });++ expect(title).toBeNull();+ expect(init).not.toHaveBeenCalled();+ expect(console.error).toHaveBeenCalledWith(+ 'SystemAgentService.generateTopicTitle failed:',+ expect.objectContaining({+ error: expect.objectContaining({ reason: 'no_executor' }),+ errorType: 'ClientLlmExecutorUnavailable',+ }),+ );+ });+});diff --git a/apps/server/src/services/systemAgent/index.ts b/apps/server/src/services/systemAgent/index.tsindex 79817c85085..2a06ba5b07c 100644--- a/apps/server/src/services/systemAgent/index.ts+++ b/apps/server/src/services/systemAgent/index.ts@@ -17,7 +17,7 @@ import debug from 'debug';import { UserModel } from '@/database/models/user';import type { LobeChatDatabase } from '@/database/type';-import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import { initModelRuntimeForRequest } from '@/server/modules/AgentRuntime/llmRelay/oneShot';import { resolveSystemAgentModelConfig } from './modelConfig';@@ -68,12 +68,11 @@ export class SystemAgentService {const payload = chainSummaryTitle(messages, locale);- const modelRuntime = await initModelRuntimeFromDB(- this.db,- this.userId,- provider,- this.workspaceId,- );+ // Relayed to the requesting tab for a device-only provider; a bot's+ // topic title has no tab and falls back to the default title.+ const modelRuntime = await initModelRuntimeForRequest(this.db, this.userId, provider, {+ workspaceId: this.workspaceId,+ });const result = await modelRuntime.generateObject({messages: payload.messages,@@ -131,12 +130,11 @@ export class SystemAgentService {const payload = chainGenerateSkillMeta({ content, responseLanguage: locale });const tracingId = randomUUID();- const modelRuntime = await initModelRuntimeFromDB(- this.db,- this.userId,- provider,- this.workspaceId,- );+ // Relayed to the requesting tab for a device-only provider; a bot's+ // topic title has no tab and falls back to the default title.+ const modelRuntime = await initModelRuntimeForRequest(this.db, this.userId, provider, {+ workspaceId: this.workspaceId,+ });const result = await modelRuntime.generateObject({messages: payload.messages as any[],diff --git a/apps/server/src/services/topicAutoSummary/index.test.ts b/apps/server/src/services/topicAutoSummary/index.test.tsindex ff54335bf22..b1638b96b0f 100644--- a/apps/server/src/services/topicAutoSummary/index.test.ts+++ b/apps/server/src/services/topicAutoSummary/index.test.ts@@ -142,4 +142,25 @@ describe('TopicAutoSummaryService', () => {expect(result).toEqual({ summarized: true });expect(mocks.generateObject).toHaveBeenCalled();});++ it('skips the summary when a device-only model has no tab to run in', async () => {+ mocks.generateObject.mockRejectedValue({+ error: { reason: 'no_executor', recoverable: true },+ errorType: 'ClientLlmExecutorUnavailable',+ provider: 'ollama',+ });+ const service = new TopicAutoSummaryService(createDb(), 'user-1');++ const result = await service.summarize('topic-1', { force: true });++ expect(result).toEqual({ reason: 'no-executor', summarized: false });+ expect(mocks.updateSummaryIfCurrent).not.toHaveBeenCalled();+ });++ it('still fails the step on any other generation error', async () => {+ mocks.generateObject.mockRejectedValue(new Error('provider down'));+ const service = new TopicAutoSummaryService(createDb(), 'user-1');++ await expect(service.summarize('topic-1', { force: true })).rejects.toThrow('provider down');+ });});diff --git a/apps/server/src/services/topicAutoSummary/index.ts b/apps/server/src/services/topicAutoSummary/index.tsindex 69d36b01ec9..55cd04915ca 100644--- a/apps/server/src/services/topicAutoSummary/index.ts+++ b/apps/server/src/services/topicAutoSummary/index.ts@@ -6,7 +6,7 @@ import {TOPIC_AUTO_SUMMARY_PROMPT_VERSION,} from '@lobechat/prompts';import type { SystemAgentItem, UserSystemAgentConfig } from '@lobechat/types';-import { RequestTrigger } from '@lobechat/types';+import { AgentRuntimeErrorType, RequestTrigger } from '@lobechat/types';import debug from 'debug';import { and, desc, eq } from 'drizzle-orm';@@ -26,7 +26,7 @@ const MAX_PREVIOUS_SUMMARY_CHARS = 20_000;const MAX_TRANSCRIPT_CHARS = 60_000;export interface TopicAutoSummaryResult {- reason?: 'disabled' | 'empty' | 'stale' | 'invalid-output';+ reason?: 'disabled' | 'empty' | 'stale' | 'invalid-output' | 'no-executor';summarized: boolean;}@@ -106,27 +106,43 @@ export class TopicAutoSummaryService {taskKey: 'topicAutoSummary',});const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);- const output = (await ai.generateObject(- {- ...chainTopicAutoSummary({- customPrompt: config?.customPrompt,- previousSummary: topic?.historySummary?.slice(-MAX_PREVIOUS_SUMMARY_CHARS),- transcript,- }),- model,- provider,- schema: TOPIC_AUTO_SUMMARY_JSON_SCHEMA,- },- {- metadata: { trigger: RequestTrigger.TopicSummary },- tracing: {- promptVersion: TOPIC_AUTO_SUMMARY_PROMPT_VERSION,- scenario: TRACING_SCENARIOS.TopicAutoSummary,- schemaName: TOPIC_AUTO_SUMMARY_JSON_SCHEMA.name,- topicId,- } satisfies TracingOptions,- },- )) as { description?: string; summary?: string };+ let output: { description?: string; summary?: string };+ try {+ output = (await ai.generateObject(+ {+ ...chainTopicAutoSummary({+ customPrompt: config?.customPrompt,+ previousSummary: topic?.historySummary?.slice(-MAX_PREVIOUS_SUMMARY_CHARS),+ transcript,+ }),+ model,+ provider,+ schema: TOPIC_AUTO_SUMMARY_JSON_SCHEMA,+ },+ {+ metadata: { trigger: RequestTrigger.TopicSummary },+ tracing: {+ promptVersion: TOPIC_AUTO_SUMMARY_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.TopicAutoSummary,+ schemaName: TOPIC_AUTO_SUMMARY_JSON_SCHEMA.name,+ topicId,+ } satisfies TracingOptions,+ },+ )) as { description?: string; summary?: string };+ } catch (error) {+ // A device-only model (Ollama, LM Studio) runs in the user's open tab,+ // and this summary runs in a workflow with no tab attached. That is a+ // settled outcome, not a transient failure: skip the summary instead of+ // failing the step, which would only make the workflow retry in vain.+ if (+ (error as { errorType?: unknown })?.errorType ===+ AgentRuntimeErrorType.ClientLlmExecutorUnavailable+ ) {+ log('skip topic %s: %s has no executor outside a browser tab', topicId, provider);+ return { reason: 'no-executor', summarized: false };+ }+ throw error;+ }const description = output.description?.trim();const summary = output.summary?.trim();diff --git a/apps/workbench/app/stubs/surface.test.ts b/apps/workbench/app/stubs/surface.test.tsindex 6ef007850fa..7d860b6459e 100644--- a/apps/workbench/app/stubs/surface.test.ts+++ b/apps/workbench/app/stubs/surface.test.ts@@ -23,6 +23,7 @@ describe('workbench stub surface', () => {'lambdaClient','lambdaQuery','toolsClient',+ 'withLlmRelay',]);expect(surface.open.has('lambdaClient')).toBe(true);diff --git a/apps/workbench/app/stubs/trpcClient.client.ts b/apps/workbench/app/stubs/trpcClient.client.tsindex fa2561daa65..5425c7fe454 100644--- a/apps/workbench/app/stubs/trpcClient.client.ts+++ b/apps/workbench/app/stubs/trpcClient.client.ts@@ -18,3 +18,8 @@ export const lambdaClient = createTRPCClient<LambdaRouter>({export const asyncClient = reject('asyncClient');export const toolsClient = reject('toolsClient');export const lambdaQuery = reject('lambdaQuery');++// Workbench never relays an LLM call to a tab, so a call carries no relay headers.+export const withLlmRelay = (_relay?: {+ headers: Record<string, string>;+}): { context: Record<string, unknown> } | undefined => undefined;diff --git a/apps/workbench/app/stubs/trpcClient.ts b/apps/workbench/app/stubs/trpcClient.tsindex 51d23435965..e524ab561ff 100644--- a/apps/workbench/app/stubs/trpcClient.ts+++ b/apps/workbench/app/stubs/trpcClient.ts@@ -4,3 +4,8 @@ export const lambdaClient = reject('lambdaClient');export const asyncClient = reject('asyncClient');export const toolsClient = reject('toolsClient');export const lambdaQuery = reject('lambdaQuery');++// Workbench never relays an LLM call to a tab, so a call carries no relay headers.+export const withLlmRelay = (_relay?: {+ headers: Record<string, string>;+}): { context: Record<string, unknown> } | undefined => undefined;diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.tsindex fcbbdc4e102..c88c0fc9ba1 100644--- a/src/services/agentDocument.ts+++ b/src/services/agentDocument.ts@@ -1,8 +1,11 @@import type { DocumentLoadFormat, DocumentLoadRule } from '@lobechat/agent-templates';import { type AgentContextDocument } from '@lobechat/context-engine';-import { lambdaClient } from '@/libs/trpc/client';+import { lambdaClient, withLlmRelay } from '@/libs/trpc/client';import { invalidateDocumentMutation } from '@/services/document/invalidation';+import { oneShotRelay } from '@/services/llmRelay';+import { useUserStore } from '@/store/user';+import { systemAgentSelectors } from '@/store/user/selectors';import { toAgentContextDocuments } from '@/utils/agentDocumentContextMapping';export { agentDocumentSWRKeys } from '@/services/document/swrKeys';@@ -285,8 +288,15 @@ class AgentDocumentService {return result;};+ /**+ * Runs on the `agentMeta` system agent model; a model only this device+ * reaches is relayed back to this tab (one-shot relay).+ */generateSkillMeta = async (params: { agentId: string; sourceAgentDocumentId: string }) => {- return lambdaClient.agentDocument.generateSkillMeta.mutate(params);+ const { provider } = systemAgentSelectors.agentMeta(useUserStore.getState());+ return oneShotRelay.run(provider, (relay) =>+ lambdaClient.agentDocument.generateSkillMeta.mutate(params, withLlmRelay(relay)),+ );};/**diff --git a/src/services/aiChat.test.ts b/src/services/aiChat.test.tsnew file mode 100644index 00000000000..64ad947ea8b--- /dev/null+++ b/src/services/aiChat.test.ts@@ -0,0 +1,63 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { lambdaClient } from '@/libs/trpc/client';+import { oneShotRelay } from '@/services/llmRelay';++import { aiChatService } from './aiChat';+import { followUpActionService } from './followUpAction';++vi.mock('@/libs/trpc/client', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ lambdaClient: {+ aiChat: { outputJSON: { mutate: vi.fn(async () => ({ data: { title: 'T' } })) } },+ followUpAction: { extract: { mutate: vi.fn(async () => ({ chips: [] })) } },+ },+}));+vi.mock('@/services/llmRelay', () => ({+ oneShotRelay: { run: vi.fn() },+}));++const RELAY = {+ channel: 'llmcall:user-1:abcdefgh',+ headers: { 'x-lobe-client-id': 'tab-1', 'x-lobe-llm-relay-channel': 'llmcall:user-1:abcdefgh' },+};++describe('structured-output services and the one-shot relay', () => {+ beforeEach(() => {+ vi.mocked(oneShotRelay.run).mockImplementation(async (_provider, request) => request(RELAY));+ });++ // Topic / thread titles and input completion run on the server; a local+ // model there is relayed back to this tab, so the call must name the channel+ // this tab subscribed.+ it('sends outputJSON for the model provider with the relay headers', async () => {+ const params = { messages: [], model: 'qwen3:1.7b', provider: 'ollama', schema: {} } as any;++ const controller = new AbortController();+ await aiChatService.generateJSON(params, controller);++ // The abort signal also ends the wait for the relay channel (input completion).+ expect(oneShotRelay.run).toHaveBeenCalledWith('ollama', expect.any(Function), {+ signal: controller.signal,+ });+ expect(lambdaClient.aiChat.outputJSON.mutate).toHaveBeenCalledWith(params, {+ context: { llmRelayHeaders: RELAY.headers, showNotification: false },+ signal: expect.any(AbortSignal),+ });+ });++ it('sends the follow-up extraction for its model provider with the relay headers', async () => {+ const input = { modelConfig: { model: 'qwen3:1.7b', provider: 'lmstudio' }, topicId: 't' };++ const controller = new AbortController();+ await followUpActionService.extract(input as any, controller.signal);++ expect(oneShotRelay.run).toHaveBeenCalledWith('lmstudio', expect.any(Function), {+ signal: controller.signal,+ });+ expect(lambdaClient.followUpAction.extract.mutate).toHaveBeenCalledWith(input, {+ context: { llmRelayHeaders: RELAY.headers },+ signal: controller.signal,+ });+ });+});diff --git a/src/services/aiChat.ts b/src/services/aiChat.tsindex 48c1f231b2a..97d3a4c53e9 100644--- a/src/services/aiChat.ts+++ b/src/services/aiChat.ts@@ -1,7 +1,8 @@import { type SendMessageServerParams, type StructureOutputParams } from '@lobechat/types';import { cleanObject } from '@lobechat/utils';-import { lambdaClient } from '@/libs/trpc/client';+import { lambdaClient, withLlmRelay } from '@/libs/trpc/client';+import { oneShotRelay } from '@/services/llmRelay';export interface RecordTracingFeedbackParams {data?: Record<string, unknown>;@@ -22,12 +23,21 @@ class AiChatService {});};- generateJSON = async (params: StructureOutputParams, abortController: AbortController) => {- return lambdaClient.aiChat.outputJSON.mutate(params, {- context: { showNotification: false },- signal: abortController?.signal,- });- };+ /**+ * Structured output (topic / thread titles, input completion, supervisor+ * decisions, builder suggestions). A provider only this device reaches is+ * relayed back to this tab by the server (one-shot relay).+ */+ generateJSON = async (params: StructureOutputParams, abortController: AbortController) =>+ oneShotRelay.run(+ params.provider,+ (relay) =>+ lambdaClient.aiChat.outputJSON.mutate(params, {+ context: { showNotification: false, ...withLlmRelay(relay)?.context },+ signal: abortController?.signal,+ }),+ { signal: abortController?.signal },+ );recordTracingFeedback = async (params: RecordTracingFeedbackParams) => {return lambdaClient.llmGenerationTracing.recordFeedback.mutate(params, {diff --git a/src/services/expertise.ts b/src/services/expertise.tsindex 3c14ee7826b..0d752aec64a 100644--- a/src/services/expertise.ts+++ b/src/services/expertise.ts@@ -1,4 +1,14 @@-import { lambdaClient } from '@/libs/trpc/client';+import { lambdaClient, withLlmRelay } from '@/libs/trpc/client';+import { oneShotRelay, type OneShotRelayHandle } from '@/services/llmRelay';+import { useUserStore } from '@/store/user';+import { systemAgentSelectors } from '@/store/user/selectors';++/**+ * Drafting runs server-side on the `expertise` system agent; a model only this+ * device reaches is relayed back to this tab (one-shot relay).+ */+const runOnExpertiseModel = <T>(request: (relay?: OneShotRelayHandle) => Promise<T>) =>+ oneShotRelay.run(systemAgentSelectors.expertise(useUserStore.getState()).provider, request);export type ExpertiseOverview = Awaited<ReturnType<typeof lambdaClient.expertise.listByAgent.query>@@ -54,11 +64,20 @@ class ExpertiseService {draftRule = async (input: {brief: string;groups: { gate: string; id: string; title: string }[];- }) => lambdaClient.expertise.draftRule.mutate(input);+ }) =>+ runOnExpertiseModel((relay) =>+ lambdaClient.expertise.draftRule.mutate(input, withLlmRelay(relay)),+ );- draftRuleGroup = async (brief: string) => lambdaClient.expertise.draftRuleGroup.mutate({ brief });+ draftRuleGroup = async (brief: string) =>+ runOnExpertiseModel((relay) =>+ lambdaClient.expertise.draftRuleGroup.mutate({ brief }, withLlmRelay(relay)),+ );- distillRules = async (input: DistillInput) => lambdaClient.expertise.distillRules.mutate(input);+ distillRules = async (input: DistillInput) =>+ runOnExpertiseModel((relay) =>+ lambdaClient.expertise.distillRules.mutate(input, withLlmRelay(relay)),+ );commitDistilledRules = async (input: CommitDistilledInput) =>lambdaClient.expertise.commitDistilledRules.mutate(input);@@ -69,7 +88,9 @@ class ExpertiseService {lambdaClient.expertise.updateRule.mutate({ lessonId, ...patch });judgeRuleDirections = async (lessonIds: string[]) =>- lambdaClient.expertise.judgeRuleDirections.mutate({ lessonIds });+ runOnExpertiseModel((relay) =>+ lambdaClient.expertise.judgeRuleDirections.mutate({ lessonIds }, withLlmRelay(relay)),+ );reorderRule = async (domainId: string, lessonId: string, beforeId: string | null) =>lambdaClient.expertise.reorderRule.mutate({ beforeId, domainId, lessonId });@@ -103,7 +124,10 @@ class ExpertiseService {agentId: string;brief: string;currentDraft?: ExpertiseDomainDraft;- }) => lambdaClient.expertise.draftDomain.mutate(params);+ }) =>+ runOnExpertiseModel((relay) =>+ lambdaClient.expertise.draftDomain.mutate(params, withLlmRelay(relay)),+ );createDomain = async (params: ExpertiseDomainDraft & { agentId: string; brief: string }) =>lambdaClient.expertise.createDomain.mutate(params);diff --git a/src/services/followUpAction.ts b/src/services/followUpAction.tsindex aae8053d710..0e4ea61dfd8 100644--- a/src/services/followUpAction.ts+++ b/src/services/followUpAction.ts@@ -1,6 +1,7 @@import type { FollowUpExtractInput, FollowUpExtractResult } from '@lobechat/types';-import { lambdaClient } from '@/libs/trpc/client';+import { lambdaClient, withLlmRelay } from '@/libs/trpc/client';+import { oneShotRelay } from '@/services/llmRelay';class FollowUpActionService {/**@@ -11,7 +12,13 @@ class FollowUpActionService {signal?: AbortSignal,): Promise<FollowUpExtractResult | null> {try {- const result = await lambdaClient.followUpAction.extract.mutate(input, { signal });+ // A device-only model is relayed back to this tab (one-shot relay).+ const result = await oneShotRelay.run(+ input.modelConfig?.provider,+ (relay) =>+ lambdaClient.followUpAction.extract.mutate(input, { signal, ...withLlmRelay(relay) }),+ { signal },+ );return result;} catch (err) {// TRPC wraps DOMException in TRPCClientError, so check both the raw errordiff --git a/src/services/systemAgentRelay.test.ts b/src/services/systemAgentRelay.test.tsnew file mode 100644index 00000000000..b61a29c7f6c--- /dev/null+++ b/src/services/systemAgentRelay.test.ts@@ -0,0 +1,202 @@+import { DEFAULT_VERIFY_PLAN_MODEL, DEFAULT_VERIFY_PLAN_PROVIDER } from '@lobechat/business-const';+import { act } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { lambdaClient } from '@/libs/trpc/client';+import { oneShotRelay } from '@/services/llmRelay';+import { useUserStore } from '@/store/user';++import { expertiseService } from './expertise';+import { taskService } from './task';+import { verifyService } from './verify';++vi.mock('@/libs/trpc/client', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ lambdaClient: {+ expertise: {+ draftDomain: { mutate: vi.fn(async () => ({})) },+ draftRule: { mutate: vi.fn(async () => ({})) },+ draftRuleGroup: { mutate: vi.fn(async () => ({})) },+ distillRules: { mutate: vi.fn(async () => ({})) },+ judgeRuleDirections: { mutate: vi.fn(async () => ({ judged: 0 })) },+ },+ task: {+ analyzeIntent: { mutate: vi.fn(async () => ({})) },+ synthesizeInstruction: { mutate: vi.fn(async () => ({})) },+ },+ verify: {+ executeVerify: { mutate: vi.fn(async () => []) },+ generateCriteria: { mutate: vi.fn(async () => []) },+ generateDraftPlan: { mutate: vi.fn(async () => []) },+ generateGoalCriteria: { mutate: vi.fn(async () => []) },+ generateGoalPlan: { mutate: vi.fn(async () => undefined) },+ },+ },+}));+vi.mock('@/services/llmRelay', () => ({+ oneShotRelay: { run: vi.fn() },+}));++const RELAY = {+ channel: 'llmcall:user-1:abcdefgh',+ headers: { 'x-lobe-client-id': 'tab-1', 'x-lobe-llm-relay-channel': 'llmcall:user-1:abcdefgh' },+};+const RELAY_OPTIONS = { context: { llmRelayHeaders: RELAY.headers } };++// These browser entries reach server tasks (AiGenerationService) that run on a+// system-agent model. With that model on a device-only provider the server+// relays the call back to the requesting tab β which only works when the+// request names the channel this tab subscribed; without it the server answers+// `no_executor` (no_client_request).+describe('system-agent browser entries and the one-shot relay', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(oneShotRelay.run).mockImplementation(async (_provider, request) => request(RELAY));+ act(() => {+ useUserStore.setState({+ settings: {+ systemAgent: {+ expertise: { enabled: true, model: 'qwen3-1.7b', provider: 'lmstudio' },+ goal: { enabled: true, model: 'qwen3:1.7b', provider: 'ollama' },+ },+ } as any,+ });+ });+ });++ describe('goal model (task intent, goal criteria)', () => {+ it('analyzeIntent', async () => {+ const params = { instruction: 'ship it' };+ await taskService.analyzeIntent(params);++ expect(oneShotRelay.run).toHaveBeenCalledWith('ollama', expect.any(Function));+ expect(lambdaClient.task.analyzeIntent.mutate).toHaveBeenCalledWith(params, RELAY_OPTIONS);+ });++ it('synthesizeInstruction', async () => {+ const params = { answers: [], instruction: 'ship it' };+ await taskService.synthesizeInstruction(params);++ expect(oneShotRelay.run).toHaveBeenCalledWith('ollama', expect.any(Function));+ expect(lambdaClient.task.synthesizeInstruction.mutate).toHaveBeenCalledWith(+ params,+ RELAY_OPTIONS,+ );+ });++ it('generateGoalCriteria', async () => {+ const params = { goal: 'ship it' };+ await verifyService.generateGoalCriteria(params);++ expect(oneShotRelay.run).toHaveBeenCalledWith('ollama', expect.any(Function));+ expect(lambdaClient.verify.generateGoalCriteria.mutate).toHaveBeenCalledWith(+ params,+ RELAY_OPTIONS,+ );+ });++ it('generateGoalPlan', async () => {+ const params = { goal: 'ship it' };+ await verifyService.generateGoalPlan(params);++ expect(oneShotRelay.run).toHaveBeenCalledWith('ollama', expect.any(Function));+ expect(lambdaClient.verify.generateGoalPlan.mutate).toHaveBeenCalledWith(+ params,+ RELAY_OPTIONS,+ );+ });+ });++ describe('expertise model (rules, domains)', () => {+ it('draftRule', async () => {+ const params = { brief: 'be brief', groups: [] };+ await expertiseService.draftRule(params);++ expect(oneShotRelay.run).toHaveBeenCalledWith('lmstudio', expect.any(Function));+ expect(lambdaClient.expertise.draftRule.mutate).toHaveBeenCalledWith(params, RELAY_OPTIONS);+ });++ it('draftRuleGroup', async () => {+ await expertiseService.draftRuleGroup('a group');++ expect(oneShotRelay.run).toHaveBeenCalledWith('lmstudio', expect.any(Function));+ expect(lambdaClient.expertise.draftRuleGroup.mutate).toHaveBeenCalledWith(+ { brief: 'a group' },+ RELAY_OPTIONS,+ );+ });++ it('distillRules', async () => {+ const params = { agentId: 'agt', sources: [] } as any;+ await expertiseService.distillRules(params);++ expect(oneShotRelay.run).toHaveBeenCalledWith('lmstudio', expect.any(Function));+ expect(lambdaClient.expertise.distillRules.mutate).toHaveBeenCalledWith(+ params,+ RELAY_OPTIONS,+ );+ });++ it('judgeRuleDirections', async () => {+ await expertiseService.judgeRuleDirections(['l1']);++ expect(oneShotRelay.run).toHaveBeenCalledWith('lmstudio', expect.any(Function));+ expect(lambdaClient.expertise.judgeRuleDirections.mutate).toHaveBeenCalledWith(+ { lessonIds: ['l1'] },+ RELAY_OPTIONS,+ );+ });++ it('draftDomain', async () => {+ const params = { agentId: 'agt', brief: 'brief' };+ await expertiseService.draftDomain(params);++ expect(oneShotRelay.run).toHaveBeenCalledWith('lmstudio', expect.any(Function));+ expect(lambdaClient.expertise.draftDomain.mutate).toHaveBeenCalledWith(params, RELAY_OPTIONS);+ });+ });++ describe('verify', () => {+ it('generateCriteria runs on the pinned plan model', async () => {+ const params = { goal: 'ship it' };+ await verifyService.generateCriteria(params);++ expect(DEFAULT_VERIFY_PLAN_MODEL).toBeTruthy();+ expect(oneShotRelay.run).toHaveBeenCalledWith(+ DEFAULT_VERIFY_PLAN_PROVIDER,+ expect.any(Function),+ );+ expect(lambdaClient.verify.generateCriteria.mutate).toHaveBeenCalledWith(+ params,+ RELAY_OPTIONS,+ );+ });++ it('generateDraftPlan runs on the pinned plan model', async () => {+ const params = { goal: 'ship it', operationId: 'op' };+ await verifyService.generateDraftPlan(params);++ expect(oneShotRelay.run).toHaveBeenCalledWith(+ DEFAULT_VERIFY_PLAN_PROVIDER,+ expect.any(Function),+ );+ expect(lambdaClient.verify.generateDraftPlan.mutate).toHaveBeenCalledWith(+ params,+ RELAY_OPTIONS,+ );+ });++ it('executeVerify runs on the model it names', async () => {+ const params = {+ deliverable: 'd',+ goal: 'g',+ modelConfig: { model: 'qwen3:1.7b', provider: 'ollama' },+ operationId: 'op',+ };+ await verifyService.executeVerify(params);++ expect(oneShotRelay.run).toHaveBeenCalledWith('ollama', expect.any(Function));+ expect(lambdaClient.verify.executeVerify.mutate).toHaveBeenCalledWith(params, RELAY_OPTIONS);+ });+ });+});diff --git a/src/services/task.ts b/src/services/task.tsindex 0401df935b5..c4f2d975258 100644--- a/src/services/task.ts+++ b/src/services/task.ts@@ -6,7 +6,13 @@ import type {TaskStatus,} from '@lobechat/types';-import { lambdaClient } from '@/libs/trpc/client';+import { lambdaClient, withLlmRelay } from '@/libs/trpc/client';+import { oneShotRelay } from '@/services/llmRelay';+import { useUserStore } from '@/store/user';+import { systemAgentSelectors } from '@/store/user/selectors';++/** The `goal` system agent's provider: task intent runs on it server-side. */+const goalModelProvider = () => systemAgentSelectors.goal(useUserStore.getState()).provider;class TaskService {// ββ Queries ββ@@ -78,23 +84,30 @@ class TaskService {/*** Read a composer draft and report what it means. A mutation on the wire* (it spends a model call), but it creates nothing β the caller decides- * whether to act on the reading.+ * whether to act on the reading. A `goal` model only this device reaches is+ * relayed back to this tab (one-shot relay).*/analyzeIntent = async (params: {context?: string;instruction: string;- }): Promise<TaskIntentAnalysis> => lambdaClient.task.analyzeIntent.mutate(params);+ }): Promise<TaskIntentAnalysis> =>+ oneShotRelay.run(goalModelProvider(), (relay) =>+ lambdaClient.task.analyzeIntent.mutate(params, withLlmRelay(relay)),+ );/*** Rewrite the confirmed draft into the brief that gets executed, with the* user's answers folded in. Also a mutation on the wire, and also creates- * nothing.+ * nothing. Relayed like `analyzeIntent`.*/synthesizeInstruction = async (params: {answers: { answer: string; question: string }[];context?: string;instruction: string;- }): Promise<TaskInstructionSynthesis> => lambdaClient.task.synthesizeInstruction.mutate(params);+ }): Promise<TaskInstructionSynthesis> =>+ oneShotRelay.run(goalModelProvider(), (relay) =>+ lambdaClient.task.synthesizeInstruction.mutate(params, withLlmRelay(relay)),+ );create = async (params: {assigneeAgentId?: string;diff --git a/src/services/verify.ts b/src/services/verify.tsindex 01bc50dcf4e..6d5b85bb2cb 100644--- a/src/services/verify.ts+++ b/src/services/verify.ts@@ -1,3 +1,4 @@+import { DEFAULT_VERIFY_PLAN_PROVIDER } from '@lobechat/business-const';import type {AcceptanceChecklistItem,AcceptanceCheckReviewAction,@@ -23,7 +24,13 @@ import type {VerifyRubricItem,VerifyRunItem,} from '@/database/schemas/verify';-import { lambdaClient } from '@/libs/trpc/client';+import { lambdaClient, withLlmRelay } from '@/libs/trpc/client';+import { oneShotRelay } from '@/services/llmRelay';+import { useUserStore } from '@/store/user';+import { systemAgentSelectors } from '@/store/user/selectors';++/** The `goal` system agent's provider: goal criteria / plans run on it server-side. */+const goalModelProvider = () => systemAgentSelectors.goal(useUserStore.getState()).provider;/** Criterion row plus the judge instruction resolved from its linked document. */export type GoalCriterionWithInstruction = VerifyCriterionItem & { instruction?: string };@@ -399,8 +406,15 @@ export class VerifyService {provider: string | null;} | null> => lambdaClient.verify.getVerifierTracing.query({ tracingId });+ /**+ * The server-side LLM calls below run on a model only this device may reach;+ * such a call is relayed back to this tab (one-shot relay). Plan / criteria+ * generation runs on the pinned plan model.+ */generateDraftPlan = (input: GenerateDraftPlanInput): Promise<VerifyCheckItem[]> =>- lambdaClient.verify.generateDraftPlan.mutate(input) as Promise<VerifyCheckItem[]>;+ oneShotRelay.run(DEFAULT_VERIFY_PLAN_PROVIDER, (relay) =>+ lambdaClient.verify.generateDraftPlan.mutate(input, withLlmRelay(relay)),+ ) as Promise<VerifyCheckItem[]>;updateDraftItems = (operationId: string, items: VerifyCheckItem[]): Promise<unknown> =>lambdaClient.verify.updateDraftItems.mutate({ items, operationId });@@ -446,7 +460,9 @@ export class VerifyService {modelConfig: { model: string; provider: string };operationId: string;}): Promise<VerifyCheckResultItem[]> =>- lambdaClient.verify.executeVerify.mutate(input) as Promise<VerifyCheckResultItem[]>;+ oneShotRelay.run(input.modelConfig.provider, (relay) =>+ lambdaClient.verify.executeVerify.mutate(input, withLlmRelay(relay)),+ ) as Promise<VerifyCheckResultItem[]>;submitDecision = (resultId: string, decision: VerifyUserDecision): Promise<unknown> =>lambdaClient.verify.submitDecision.mutate({ decision, resultId });@@ -458,7 +474,9 @@ export class VerifyService {goal: string;maxCriteria?: number;}): Promise<VerifyCriterionDraft[]> =>- lambdaClient.verify.generateCriteria.mutate(input) as Promise<VerifyCriterionDraft[]>;+ oneShotRelay.run(DEFAULT_VERIFY_PLAN_PROVIDER, (relay) =>+ lambdaClient.verify.generateCriteria.mutate(input, withLlmRelay(relay)),+ ) as Promise<VerifyCriterionDraft[]>;/** Draft the standing acceptance criteria used by the create-goal review step. */generateGoalCriteria = (input: {@@ -466,7 +484,9 @@ export class VerifyService {goal: string;maxCriteria?: number;}): Promise<VerifyCriterionDraft[]> =>- lambdaClient.verify.generateGoalCriteria.mutate(input) as Promise<VerifyCriterionDraft[]>;+ oneShotRelay.run(goalModelProvider(), (relay) =>+ lambdaClient.verify.generateGoalCriteria.mutate(input, withLlmRelay(relay)),+ ) as Promise<VerifyCriterionDraft[]>;/** Draft the title, instruction, and criteria used by the create-goal review step. */generateGoalPlan = (input: {@@ -476,7 +496,9 @@ export class VerifyService {}): Promise<{ criteria: VerifyCriterionDraft[]; instruction: string; title: string } | undefined> =>- lambdaClient.verify.generateGoalPlan.mutate(input) as Promise<+ oneShotRelay.run(goalModelProvider(), (relay) =>+ lambdaClient.verify.generateGoalPlan.mutate(input, withLlmRelay(relay)),+ ) as Promise<{ criteria: VerifyCriterionDraft[]; instruction: string; title: string } | undefined>;diff --git a/src/store/user/slices/settings/selectors/systemAgent.ts b/src/store/user/slices/settings/selectors/systemAgent.tsindex beb094261df..c2e41b7ec6e 100644--- a/src/store/user/slices/settings/selectors/systemAgent.ts+++ b/src/store/user/slices/settings/selectors/systemAgent.ts@@ -23,12 +23,16 @@ const historyCompress = (s: UserStore) => currentSystemAgent(s).historyCompress;const generationTopic = (s: UserStore) => currentSystemAgent(s).generationTopic;const inputCompletion = (s: UserStore) => currentSystemAgent(s).inputCompletion;const followUpAction = (s: UserStore) => currentSystemAgent(s).followUpAction;+const goal = (s: UserStore) => currentSystemAgent(s).goal;+const expertise = (s: UserStore) => currentSystemAgent(s).expertise;export const systemAgentSelectors = {agentMeta,asr,+ expertise,followUpAction,generationTopic,+ goal,historyCompress,inputCompletion,isAsrConfigured,