🤯 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
♻️ refactor(context-engine): let the engine assemble the system message (#19485)
Arvin Xuabdd7ff74fcd
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.test.tsindex 8144829526c..2f4e9dc9de0 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.test.ts@@ -99,6 +99,46 @@ beforeEach(() => {});});+/**+ * Covers the executor-context to engine-input link. Every failure this feature+ * has had was a name dropped from an explicit field list rather than broken+ * logic, and each one was silent: the injectors kept working, they just never+ * received anything. So each link gets an assertion of its own.+ */+describe('buildServerCallLlmContext - system-message context reaches the engine', () => {+ it('forwards the project instructions off the operation context', async () => {+ const projectInstructions = [{ content: 'Use bun.', source: 'AGENTS.md' }];++ await buildServerCallLlmContext({+ ctx: createCtx({ projectInstructions }),+ llmPayload,+ model: 'gpt-4',+ provider: 'openai',+ state,+ tooling,+ });++ expect(serverMessagesEngineMock).toHaveBeenCalledWith(+ expect.objectContaining({ projectInstructions }),+ );+ });++ it('forwards the connector ownership note off the operation context', async () => {+ await buildServerCallLlmContext({+ ctx: createCtx({ connectorOwnershipNote: 'Gmail runs on Alice’s account.' }),+ llmPayload,+ model: 'gpt-4',+ provider: 'openai',+ state,+ tooling,+ });++ expect(serverMessagesEngineMock).toHaveBeenCalledWith(+ expect.objectContaining({ connectorOwnershipNote: 'Gmail runs on Alice’s account.' }),+ );+ });+});+describe('buildServerCallLlmContext - {{username}}/{{language}} placeholder source', () => {it('resolves user info from the creator when the run is not a share-visitor run', async () => {await buildServerCallLlmContext({diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex ae900e8071b..fc4aeb3c668 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -727,6 +727,8 @@ export const buildServerCallLlmContext = async ({modelKnowledgeCutoff,provider,...(planTodo && { planTodo }),+ connectorOwnershipNote: ctx.connectorOwnershipNote,+ projectInstructions: ctx.projectInstructions,systemRole: agentConfig.systemRole ?? undefined,toolDiscoveryConfig,toolsConfig: {diff --git a/apps/server/src/modules/AgentRuntime/context.ts b/apps/server/src/modules/AgentRuntime/context.tsindex 8213ac41d81..7e8eff6ae87 100644--- a/apps/server/src/modules/AgentRuntime/context.ts+++ b/apps/server/src/modules/AgentRuntime/context.ts@@ -1,5 +1,5 @@import { type AgentState } from '@lobechat/agent-runtime';-import { type BotPlatformContext } from '@lobechat/context-engine';+import type { BotPlatformContext, ProjectInstructionFile } from '@lobechat/context-engine';import {type AgentShareVisitorContext,type ExecSubAgentParams,@@ -46,6 +46,8 @@ export interface RuntimeExecutorContext {allowEarlyFinalAnswerVisibleOutputEnd?: boolean;botContext?: unknown;botPlatformContext?: BotPlatformContext;+ /** Borrowed-connector attribution, injected into the system message. */+ connectorOwnershipNote?: string;discordContext?: any;evalContext?: EvalContext;/**@@ -71,6 +73,8 @@ export interface RuntimeExecutorContext {messageModel: MessageModel;modelRuntimeConfig?: AgentState['modelRuntimeConfig'];operationId: string;+ /** A project's root instruction files, injected into the system message. */+ projectInstructions?: ProjectInstructionFile[];searchDecision?: SearchDecision;serverDB: LobeChatDatabase;stepIndex: number;diff --git a/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts b/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.tsindex 90daf65f530..18a739e9a9a 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts@@ -32,6 +32,73 @@ describe('serverMessagesEngine', () => {} as UIChatMessage,];+ /**+ * These cover the wrapper→engine seam rather than the injectors themselves.+ * The injectors had unit tests and still shipped dead: `serverMessagesEngine`+ * destructures a fixed parameter list, so a field it does not name is+ * dropped, and the call site passes an intermediate object, which disables+ * excess-property checking. Nothing but a test at this boundary catches it.+ */+ describe('system-message context forwarded to the engine', () => {+ it('forwards project instructions', async () => {+ const result = await serverMessagesEngine({+ messages: createBasicMessages(),+ model: 'gpt-4',+ projectInstructions: [{ content: 'Use bun, not npm.', source: 'AGENTS.md' }],+ provider: 'openai',+ systemRole: 'You are helpful.',+ });++ const system = result.find((message) => message.role === 'system')?.content;+ expect(system).toContain('<project_instructions source="AGENTS.md">');+ expect(system).toContain('Use bun, not npm.');+ });++ it('forwards the connector ownership note', async () => {+ const result = await serverMessagesEngine({+ connectorOwnershipNote: 'Gmail runs on Alice’s account.',+ messages: createBasicMessages(),+ model: 'gpt-4',+ provider: 'openai',+ systemRole: 'You are helpful.',+ });++ expect(result.find((message) => message.role === 'system')?.content).toContain(+ 'Gmail runs on Alice’s account.',+ );+ });++ it('keeps the connector note ahead of the project instructions', async () => {+ const result = await serverMessagesEngine({+ connectorOwnershipNote: 'CONNECTOR-NOTE',+ messages: createBasicMessages(),+ model: 'gpt-4',+ projectInstructions: [{ content: 'PROJECT-RULE', source: 'AGENTS.md' }],+ provider: 'openai',+ systemRole: 'You are helpful.',+ });++ // `discoverTools` runs before `prepareOperation`, so this is the order the+ // old string appends produced; reversing it changes which block the model+ // reads last.+ const system = String(result.find((message) => message.role === 'system')?.content ?? '');+ expect(system.indexOf('CONNECTOR-NOTE')).toBeGreaterThan(-1);+ expect(system.indexOf('CONNECTOR-NOTE')).toBeLessThan(system.indexOf('PROJECT-RULE'));+ });++ it('leaves the system message alone when a run has neither', async () => {+ const result = await serverMessagesEngine({+ messages: createBasicMessages(),+ model: 'gpt-4',+ provider: 'openai',+ systemRole: 'You are helpful.',+ });++ const system = String(result.find((message) => message.role === 'system')?.content ?? '');+ expect(system).not.toContain('<project_instructions');+ });+ });+describe('TODO context', () => {const items = [{ status: 'processing' as const, text: 'Keep server context in sync' }];diff --git a/apps/server/src/modules/Mecha/ContextEngineering/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/index.tsindex 46a423d9f7d..d33e923fa0f 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/index.ts@@ -153,10 +153,14 @@ export const serverMessagesEngine = async ({planTodo,topicReferences,additionalVariables,+ connectorOwnershipNote,+ projectInstructions,userTimezone,}: ServerMessagesEngineParams): Promise<OpenAIChatMessage[]> => {const engine = new MessagesEngine({additionalContexts,+ connectorOwnershipNote,+ projectInstructions,// Capability injectioncapabilities: {isCanUseAudio: capabilities?.isCanUseAudio,diff --git a/apps/server/src/modules/Mecha/ContextEngineering/types.ts b/apps/server/src/modules/Mecha/ContextEngineering/types.tsindex f23f98f4716..a8764e6412e 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/types.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/types.ts@@ -17,6 +17,7 @@ import type {ToolDiscoveryConfig,TopicReferenceItem,UserMemoryData,+ ProjectInstructionFile,WorkspaceContext,} from '@lobechat/context-engine';import type { AgentIdentityContext, PageContentContext } from '@lobechat/prompts';@@ -112,7 +113,11 @@ export interface ServerMessagesEngineParams {discordContext?: DiscordContext;// ========== Eval context ==========/** Eval context for injecting environment prompts into system message */+ /** Borrowed-connector attribution, injected into the system message. */+ connectorOwnershipNote?: string;evalContext?: EvalContext;+ /** A project's root instruction files, injected into the system message. */+ projectInstructions?: ProjectInstructionFile[];// ========== Onboarding context ==========/** Onboarding context for injecting phase guidance and documents */onboardingContext?: OnboardingContext;diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex 00a7bf30a2a..38e67ceecde 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -525,6 +525,29 @@ describe('AgentRuntimeService', () => {);});+ it('should persist the system-message context in metadata', async () => {+ mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');++ const projectInstructions = [{ content: 'Use bun.', source: 'AGENTS.md' }];+ const connectorOwnershipNote = 'Gmail runs on Alice’s account.';+ await service.createOperation({+ ...mockParams,+ connectorOwnershipNote,+ projectInstructions,+ });++ // `metadata` is assembled from an explicit field list, so a value not+ // named there is dropped without a word — and steps can be claimed by+ // another worker, so anything the context engine needs has to survive on+ // the operation rather than in memory.+ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({+ metadata: expect.objectContaining({ connectorOwnershipNote, projectInstructions }),+ }),+ );+ });+it('should persist the operation expertise snapshot in runtime state', async () => {mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');const expertise = {diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 16b7e8b5775..432536ba5b2 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -873,11 +873,13 @@ export class AgentRuntimeService {botContext,botPlatformContext,deviceAccessPolicy,+ connectorOwnershipNote,discordContext,evalContext,evalRuntime,enableExpertise,expertise,+ projectInstructions,executionPlan,maxSteps,userMemory,@@ -1000,12 +1002,14 @@ export class AgentRuntimeService {agentShareVisitor,botContext,botPlatformContext,+ connectorOwnershipNote,deviceAccessPolicy,deviceSystemInfo,discordContext,evalContext,evalRuntime,executionPlan,+ projectInstructions,...(interventionResolution? { agentInterventionContinuation: interventionResolution }: {}),@@ -3762,9 +3766,11 @@ export class AgentRuntimeService {agent instanceof GeneralChatAgent && !stateHasEntityFileEdits(agentState),botContext: metadata?.botContext,botPlatformContext: metadata?.botPlatformContext,+ connectorOwnershipNote: metadata?.connectorOwnershipNote,discordContext: metadata?.discordContext,userTimezone: metadata?.userTimezone,evalContext: metadata?.evalContext,+ projectInstructions: metadata?.projectInstructions,execSubAgent: this.delegate.execSubAgent,execVirtualSubAgent: this.delegate.execVirtualSubAgent,execGroupMember: this.delegate.execGroupMember,diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex 6986e467825..63542b14325 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -4,6 +4,7 @@ import type {BotPlatformContext,LobeToolManifest,OperationSkillSet,+ ProjectInstructionFile,ToolExecutor,ToolSource,} from '@lobechat/context-engine';@@ -429,6 +430,11 @@ export interface OperationCreationParams {botContext?: ChatTopicBotContext;/** Bot platform context for injecting platform capabilities (e.g. markdown support) */botPlatformContext?: BotPlatformContext;+ /**+ * Borrowed-connector attribution, resolved once during tool discovery. Run+ * context for the context engine to inject — see `expertise`.+ */+ connectorOwnershipNote?: string;/*** Device-access policy decision computed once per turn by* `resolveDeviceAccessPolicy`. Forwarded into `state.metadata.deviceAccessPolicy`@@ -489,6 +495,11 @@ export interface OperationCreationParams {* sub-tree back to its root.*/parentOperationId?: string;+ /**+ * A project's root instruction files, collected once during operation prep.+ * Run context for the context engine to inject — see `expertise`.+ */+ projectInstructions?: ProjectInstructionFile[];queueRetries?: number;queueRetryDelay?: string;/** Search route resolved once before the operation starts. */diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.tsindex 874dc3abc5e..6ca1f5ee7b4 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts@@ -17,6 +17,7 @@ const {mockPluginQuery,mockQueryDeviceList,mockQueryDeviceSystemInfo,+ mockFindWorkspaceDeviceById,mockQueryWorkspaceDevices,} = vi.hoisted(() => ({mockCreateOperation: vi.fn(),@@ -29,6 +30,7 @@ const {mockPluginQuery: vi.fn(),mockQueryDeviceList: vi.fn(),mockQueryDeviceSystemInfo: vi.fn(),+ mockFindWorkspaceDeviceById: vi.fn().mockResolvedValue(undefined),mockQueryWorkspaceDevices: vi.fn(),}));@@ -66,7 +68,7 @@ vi.mock('@/database/models/device', () => ({DeviceModel: vi.fn().mockImplementation(function () {return {findByDeviceId: vi.fn().mockResolvedValue(undefined),- findWorkspaceDeviceById: vi.fn().mockResolvedValue(undefined),+ findWorkspaceDeviceById: mockFindWorkspaceDeviceById,queryPersonal: vi.fn().mockResolvedValue([]),queryWorkspaceDevices: mockQueryWorkspaceDevices,queryWorkspaceHiddenDeviceIds: vi.fn().mockResolvedValue([]),@@ -771,4 +773,67 @@ describe('AiAgentService.execAgent - device tool pipeline ()', () => {expect(createOpArgs.deviceSystemInfo).toBeUndefined();});});++ /**+ * Pins the stage order the assembled system message depends on. Carrying a+ * real payload end to end through here needs the whole device workspace-scan+ * chain stood up — an active device, a device row, a fresh cached scan, and+ * the skill lookup that shares its `try` — which is why the payload itself is+ * covered link by link instead (`AgentRuntimeService`,+ * `serverCallLlmContextBuilder`, `serverMessagesEngine`).+ */+ describe('system-message run context', () => {+ const withScannedProject = () => {+ mockQueryWorkspaceDevices.mockResolvedValue([+ {+ deviceId: 'ws-dev-1',+ friendlyName: null,+ hostname: 'workspace-mac',+ lastSeenAt: new Date('2026-09-09T00:00:00.000Z'),+ platform: 'darwin',+ },+ ]);+ mockQueryDeviceList.mockResolvedValue([+ { deviceId: 'ws-dev-1', hostname: 'workspace-mac', online: true, platform: 'darwin' },+ ]);+ mockQueryDeviceSystemInfo.mockResolvedValue({+ arch: 'arm64',+ homePath: '/Users/me',+ platform: 'darwin',+ });+ // A device whose bound project root already carries a FRESH scan, so the+ // run reads the cache instead of going out to the gateway.+ mockFindWorkspaceDeviceById.mockResolvedValue({+ defaultCwd: '/repo',+ deviceId: 'ws-dev-1',+ workingDirs: [+ {+ path: '/repo',+ workspace: {+ instructions: [{ content: 'Use bun, not npm.', source: 'AGENTS.md' }],+ skills: [],+ },+ workspaceScannedAt: Date.now(),+ },+ ],+ });+ mockGetAgentConfig.mockResolvedValue(+ createBaseAgentConfig({ agencyConfig: { executionTarget: 'auto' } }),+ );+ };++ it('discovers tools before preparing the operation', async () => {+ withScannedProject();++ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });++ // Tool discovery resolves the device the workspace scan then reads, which+ // is also why connector attribution precedes the project instructions in+ // the assembled system message. Pinning it here keeps that ordering+ // argument from resting on a comment.+ const discoveryCall = mockQueryDeviceList.mock.invocationCallOrder[0];+ const prepCall = mockFindWorkspaceDeviceById.mock.invocationCallOrder[0];+ expect(discoveryCall).toBeLessThan(prepCall);+ });+ });});diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.tsindex 50e4b0cda9d..d4b7fbbbd4f 100644--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts@@ -3,7 +3,7 @@ import { extractActivatedToolIdsFromMessages } from '@lobechat/agent-runtime';import { builtinSkills } from '@lobechat/builtin-skills';import { getShellSyntaxGuidance } from '@lobechat/builtin-tool-local-system';import { builtinTools } from '@lobechat/builtin-tools';-import type { AgentManagementContext } from '@lobechat/context-engine';+import type { AgentManagementContext, ProjectInstructionFile } from '@lobechat/context-engine';import { buildExpertiseContextSnapshot, SkillEngine } from '@lobechat/context-engine';import type { LobeChatDatabase } from '@lobechat/database';import { buildTaskManagerDefaultsPrompt, resourcesTreePrompt } from '@lobechat/prompts';@@ -199,6 +199,12 @@ export interface OperationPrepResult {expertise?: Awaited<ReturnType<typeof buildExpertiseContextSnapshot>>;initialContext: AgentRuntimeContext;operationSkillSet?: ReturnType<SkillEngine['generate']>;+ /**+ * A project's root instruction files. Run context, not agent config — it+ * travels on the operation like `expertise` does, and the context engine+ * injects it.+ */+ projectInstructions?: ProjectInstructionFile[];userMemory?: ServerUserMemoryConfig;}@@ -324,16 +330,18 @@ const resolveWorkspaceInit = async (* (bound cwd + project instructions), the OperationSkillSet, and the learned* expertise snapshot.*- * Side effects, all order-preserving with the pre-extraction code: appends- * project instructions to `ctx.agentConfig.systemRole`, writes the bound cwd- * onto the returned `deviceSystemInfo`, pins the topic working directory, and- * merges attachment warnings into `botPlatformContext`.+ * Side effects, all order-preserving with the pre-extraction code: writes the+ * bound cwd onto the returned `deviceSystemInfo`, pins the topic working+ * directory, and merges attachment warnings into `botPlatformContext`. The+ * project instructions come back on the result instead.*/export const prepareOperation = async (deps: OperationPrepDeps,ctx: ExecRunContext,input: OperationPrepInput,): Promise<OperationPrepResult> => {+ /** Filled by the workspace branch below; returned as run context. */+ let projectInstructions: ProjectInstructionFile[] | undefined;const {agentConfig,appContext,@@ -921,20 +929,15 @@ export const prepareOperation = async ();}- // Inject the project-root agent instructions (AGENTS.md / CLAUDE.md) as- // trailing blocks on the system role — after the agent's persona and any- // page/task/additional instructions. `agentConfig` is read by- // `createOperation` below, so appending here still reaches the LLM.+ // Collected for the context engine, which assembles the system message and+ // injects these directly after the persona — where this code used to+ // concatenate them. Returning them rather than stamping `agentConfig` keeps+ // run context off the agent's configuration.if (workspaceInit.workspace.instructions.length) {- const block = workspaceInit.workspace.instructions- .map(- ({ content, source }) =>- `<project_instructions source="${source}">\n${content}\n</project_instructions>`,- )- .join('\n\n');- agentConfig.systemRole = agentConfig.systemRole- ? `${agentConfig.systemRole}\n\n${block}`- : block;+ projectInstructions = workspaceInit.workspace.instructions.map(({ content, source }) => ({+ content,+ source,+ }));log('execAgent: injected %d project instruction file(s): %s',workspaceInit.workspace.instructions.length,@@ -1020,6 +1023,7 @@ export const prepareOperation = async (expertise,initialContext,operationSkillSet,+ projectInstructions,userMemory,};};diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.tsindex 75af4887b98..4b843036454 100644--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts@@ -234,10 +234,14 @@ export const startOperation = async (botPlatformContext,deviceAccessPolicy: { canUseDevice, reason: deviceAccessReason },discordContext,+ // Run context the context engine injects into the system message —+ // carried on the operation like `expertise`, not on the agent config.+ connectorOwnershipNote: discovery.connectorOwnershipNote,evalContext,evalRuntime,enableExpertise,expertise: prep.expertise,+ projectInstructions: prep.projectInstructions,initialContext,initialMessages: prep.allMessages,initialStepCount,diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.tsindex 8571fffc647..c667bdf9785 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts@@ -135,6 +135,11 @@ export interface ToolDiscoveryResult {builtinModels: Awaited<ReturnType<typeof loadModels>>;composioManifests: LobeToolManifest[];connectorManifests: ReturnType<typeof buildConnectorManifests>;+ /**+ * Tells the model whose connected account each borrowed tool runs on. Run+ * context: it travels on the operation and the context engine injects it.+ */+ connectorOwnershipNote?: string;executionPlan?: ExecutionPlan;hasAgentDocuments: boolean;hasEnabledKnowledgeBases: boolean;@@ -164,14 +169,16 @@ export interface ToolDiscoveryResult {* Short-circuits when `disableTools` is set (only the client function tools* are honored), matching the pre-extraction behavior.*- * Side effect: appends to `ctx.agentConfig.systemRole` (connector credential- * ownership note) — `createOperation` downstream must see that write.+ * Returns the connector credential ownership note as run context when the run+ * borrows connectors other members authorized; the context engine injects it.*/export const discoverTools = async (deps: ToolDiscoveryDeps,ctx: ExecRunContext,input: ToolDiscoveryInput,): Promise<ToolDiscoveryResult> => {+ /** Filled below when the run borrows connectors; returned as run context. */+ let connectorOwnershipNote: string | undefined;const {agentConfig,appContext,@@ -359,9 +366,9 @@ export const discoverTools = async ();const note = buildConnectorOwnershipPrompt(borrowed, displayMap);if (note) {- agentConfig.systemRole = agentConfig.systemRole- ? `${agentConfig.systemRole}\n\n${note}`- : note;+ // Returned as run context for the context engine to inject, rather+ // than concatenated onto the agent's systemRole here.+ connectorOwnershipNote = note;log('execAgent: injected tool credential ownership note for %d connector(s)',borrowed.length,@@ -1176,6 +1183,7 @@ export const discoverTools = async (builtinModels,composioManifests,connectorManifests,+ connectorOwnershipNote,executionPlan,hasAgentDocuments,hasEnabledKnowledgeBases,diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.tsindex 07f9387060c..d97c48d636f 100644--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts@@ -37,6 +37,7 @@ import {AgentIdentityInjector,AgentManagementContextInjector,BotPlatformContextInjector,+ ConnectorOwnershipInjector,ContextSelectionsInjector,DiscordContextProvider,EvalContextSystemInjector,@@ -55,6 +56,7 @@ import {PageEditorContextInjector,PageSelectionsInjector,PlanInjector,+ ProjectInstructionsInjector,RuntimeAdditionalContextProvider,selectActivatedSkills,SelectedSkillInjector,@@ -176,7 +178,9 @@ export class MessagesEngine {botPlatformContext,workspaceContext,discordContext,+ connectorOwnershipNote,evalContext,+ projectInstructions,onboardingContext,agentManagementContext,groupAgentBuilderContext,@@ -289,6 +293,17 @@ export class MessagesEngine {new AgentDocumentBeforeSystemInjector(agentDocConfig),// Agent's system role (creates the initial system message)new SystemRoleInjector({ systemRole }),+ // Both sit directly after the persona because that is exactly where they+ // used to be: the server concatenated them onto `agentConfig.systemRole`+ // several pipeline stages before the engine ran. Moving them later would+ // push them behind every other Phase 2 provider.+ //+ // Connector attribution precedes the project instructions because+ // `discoverTools` runs before `prepareOperation` in the agent pipeline,+ // so that is the order the appends produced. Reversing these two changes+ // which block the model reads last.+ new ConnectorOwnershipInjector({ note: connectorOwnershipNote }),+ new ProjectInstructionsInjector({ instructions: projectInstructions }),// Agent identity (name/title) — lets the model answer "who are you?"// with the user-given name. Group chat establishes identity through// GroupContextInjector instead, so it is suppressed there.diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.tsindex 496fd00db25..e5c8b165fd3 100644--- a/packages/context-engine/src/engine/messages/types.ts+++ b/packages/context-engine/src/engine/messages/types.ts@@ -27,6 +27,7 @@ import type { GroupAgentBuilderContext } from '../../providers/GroupAgentBuilderimport type { GroupMemberInfo } from '../../providers/GroupContextInjector';import type { OnboardingContext } from '../../providers/OnboardingContextInjector';import type { Plan } from '../../providers/PlanInjector';+import type { ProjectInstructionFile } from '../../providers/ProjectInstructionsInjector';import type { SkillMeta } from '../../providers/SkillContextProvider';import type { TodoList } from '../../providers/TodoInjector';import type { ToolDiscoveryMeta } from '../../providers/ToolDiscoveryProvider';@@ -316,7 +317,11 @@ export interface MessagesEngineParams {/** Discord context for injecting channel/guild info into system injection message */discordContext?: DiscordContext;/** Eval context for injecting environment prompts into system message */+ /** Borrowed-connector attribution note, already rendered by the caller. */+ connectorOwnershipNote?: string;evalContext?: EvalContext;+ /** A project's root instruction files (`AGENTS.md` / `CLAUDE.md`). */+ projectInstructions?: ProjectInstructionFile[];/** Onboarding context for injecting phase guidance and documents */onboardingContext?: OnboardingContext;/** Agent Management context */diff --git a/packages/context-engine/src/providers/ConnectorOwnershipInjector.ts b/packages/context-engine/src/providers/ConnectorOwnershipInjector.tsnew file mode 100644index 00000000000..5ce5d114052--- /dev/null+++ b/packages/context-engine/src/providers/ConnectorOwnershipInjector.ts@@ -0,0 +1,56 @@+import debug from 'debug';++import { BaseSystemRoleProvider } from '../base/BaseSystemRoleProvider';+import type { PipelineContext, ProcessorOptions } from '../types';++declare module '../types' {+ interface PipelineContextMetadataOverrides {+ connectorOwnershipInjected?: boolean;+ }+}++const log = debug('context-engine:provider:ConnectorOwnershipInjector');++export interface ConnectorOwnershipInjectorConfig {+ enabled?: boolean;+ /**+ * The rendered note. Unlike project instructions this arrives pre-rendered,+ * because naming the authorizers needs a user lookup the engine has no way+ * to perform — the same split as `EvalContextSystemInjector` and its+ * `envPrompt`.+ */+ note?: string;+}++/**+ * Tells the model whose connected account each borrowed tool runs on, when the+ * run uses connectors other workspace members authorized.+ *+ * Was concatenated onto `agentConfig.systemRole` during tool discovery, several+ * stages before the engine ran, which is why that object had to stay mutable+ * all the way through the pipeline.+ */+export class ConnectorOwnershipInjector extends BaseSystemRoleProvider {+ readonly name = 'ConnectorOwnershipInjector';++ constructor(+ private config: ConnectorOwnershipInjectorConfig,+ options: ProcessorOptions = {},+ ) {+ super(options);+ }++ protected buildSystemRoleContent(_context: PipelineContext): string | null {+ const { enabled, note } = this.config;+ if (enabled === false || !note) {+ log('No borrowed connectors to attribute, skipping');+ return null;+ }++ return note;+ }++ protected onInjected(context: PipelineContext): void {+ context.metadata.connectorOwnershipInjected = true;+ }+}diff --git a/packages/context-engine/src/providers/ProjectInstructionsInjector.ts b/packages/context-engine/src/providers/ProjectInstructionsInjector.tsnew file mode 100644index 00000000000..aba70659c6c--- /dev/null+++ b/packages/context-engine/src/providers/ProjectInstructionsInjector.ts@@ -0,0 +1,67 @@+import debug from 'debug';++import { BaseSystemRoleProvider } from '../base/BaseSystemRoleProvider';+import type { PipelineContext, ProcessorOptions } from '../types';++declare module '../types' {+ interface PipelineContextMetadataOverrides {+ projectInstructionCount?: number;+ }+}++const log = debug('context-engine:provider:ProjectInstructionsInjector');++export interface ProjectInstructionFile {+ content: string;+ /** Where the file came from, e.g. `AGENTS.md` — surfaced to the model. */+ source: string;+}++export interface ProjectInstructionsInjectorConfig {+ enabled?: boolean;+ instructions?: ProjectInstructionFile[];+}++/**+ * Injects a project's root instruction files (`AGENTS.md` / `CLAUDE.md`) into+ * the system message.+ *+ * Takes the files rather than a rendered block: wrapping them is presentation,+ * which belongs to the pipeline that owns the system message. The server used+ * to render and concatenate this onto `agentConfig.systemRole` several stages+ * before the engine ran, which made the final prompt's composition readable+ * only by following three files in execution order.+ *+ * Runs immediately after `SystemRoleInjector` so the text lands exactly where+ * it used to — directly after the agent's persona and ahead of every other+ * Phase 2 provider.+ */+export class ProjectInstructionsInjector extends BaseSystemRoleProvider {+ readonly name = 'ProjectInstructionsInjector';++ constructor(+ private config: ProjectInstructionsInjectorConfig,+ options: ProcessorOptions = {},+ ) {+ super(options);+ }++ protected buildSystemRoleContent(_context: PipelineContext): string | null {+ const { enabled, instructions } = this.config;+ if (enabled === false || !instructions?.length) {+ log('No project instructions to inject, skipping');+ return null;+ }++ return instructions+ .map(+ ({ content, source }) =>+ `<project_instructions source="${source}">\n${content}\n</project_instructions>`,+ )+ .join('\n\n');+ }++ protected onInjected(context: PipelineContext): void {+ context.metadata.projectInstructionCount = this.config.instructions?.length ?? 0;+ }+}diff --git a/packages/context-engine/src/providers/__tests__/ConnectorOwnershipInjector.test.ts b/packages/context-engine/src/providers/__tests__/ConnectorOwnershipInjector.test.tsnew file mode 100644index 00000000000..ec38ed529a0--- /dev/null+++ b/packages/context-engine/src/providers/__tests__/ConnectorOwnershipInjector.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest';++import type { PipelineContext } from '../../types';+import { ConnectorOwnershipInjector } from '../ConnectorOwnershipInjector';++const createContext = (messages: any[]) => ({+ initialState: { messages: [], model: 'gpt-4', provider: 'openai', systemRole: '', tools: [] },+ isAborted: false,+ messages,+ metadata: { maxTokens: 4096, model: 'gpt-4' },+});++const systemMessage = {+ content: 'You are a helpful assistant.',+ createdAt: Date.now(),+ id: 'system-1',+ role: 'system',+ updatedAt: Date.now(),+};++/** The single system message the providers append to; asserted, not assumed. */+const systemContentOf = (result: PipelineContext): string => {+ const system = result.messages.find((message) => message.role === 'system');+ if (!system) throw new Error('expected a system message');+ return system.content as string;+};++const run = async (config: ConstructorParameters<typeof ConnectorOwnershipInjector>[0]) =>+ new ConnectorOwnershipInjector(config).process(createContext([systemMessage]) as any);++describe('ConnectorOwnershipInjector', () => {+ it('appends the attribution note after the persona', async () => {+ const result = await run({ note: 'Gmail runs on Alice’s account.' });++ const system = systemContentOf(result);+ expect(system).toBe(+ 'You are a helpful assistant.\n\nGmail runs on Alice’s account.',+ );+ expect(result.metadata.connectorOwnershipInjected).toBe(true);+ });++ it('does nothing when the run borrows no connectors', async () => {+ // The common case — the caller authorized everything — must cost nothing.+ for (const config of [{}, { note: '' }, { enabled: false, note: 'ignored' }]) {+ const result = await run(config);+ expect(systemContentOf(result)).toBe('You are a helpful assistant.');+ expect(result.metadata.connectorOwnershipInjected).toBeUndefined();+ }+ });+});diff --git a/packages/context-engine/src/providers/__tests__/ProjectInstructionsInjector.test.ts b/packages/context-engine/src/providers/__tests__/ProjectInstructionsInjector.test.tsnew file mode 100644index 00000000000..25cb9449a90--- /dev/null+++ b/packages/context-engine/src/providers/__tests__/ProjectInstructionsInjector.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest';++import type { PipelineContext } from '../../types';+import { ProjectInstructionsInjector } from '../ProjectInstructionsInjector';++const createContext = (messages: any[]) => ({+ initialState: { messages: [], model: 'gpt-4', provider: 'openai', systemRole: '', tools: [] },+ isAborted: false,+ messages,+ metadata: { maxTokens: 4096, model: 'gpt-4' },+});++const systemMessage = {+ content: 'You are a helpful assistant.',+ createdAt: Date.now(),+ id: 'system-1',+ role: 'system',+ updatedAt: Date.now(),+};++/** The single system message the providers append to; asserted, not assumed. */+const systemContentOf = (result: PipelineContext): string => {+ const system = result.messages.find((message) => message.role === 'system');+ if (!system) throw new Error('expected a system message');+ return system.content as string;+};++const run = async (config: ConstructorParameters<typeof ProjectInstructionsInjector>[0]) =>+ new ProjectInstructionsInjector(config).process(createContext([systemMessage]) as any);++describe('ProjectInstructionsInjector', () => {+ it('wraps each file so the model can tell where an instruction came from', async () => {+ const result = await run({+ instructions: [+ { content: 'Use bun.', source: 'AGENTS.md' },+ { content: 'Prefer rebase.', source: 'CLAUDE.md' },+ ],+ });++ const system = systemContentOf(result);+ expect(system).toContain('<project_instructions source="AGENTS.md">\nUse bun.\n</project_instructions>');+ expect(system).toContain('<project_instructions source="CLAUDE.md">');+ // Appended after the persona, not replacing it.+ expect(system.startsWith('You are a helpful assistant.')).toBe(true);+ expect(result.metadata.projectInstructionCount).toBe(2);+ });++ it('keeps the files in the order they were collected', async () => {+ const result = await run({+ instructions: [+ { content: 'first', source: 'a.md' },+ { content: 'second', source: 'b.md' },+ ],+ });++ const system = systemContentOf(result);+ expect(system.indexOf('first')).toBeLessThan(system.indexOf('second'));+ });++ it('leaves the system message untouched when there are no files', async () => {+ for (const config of [{}, { instructions: [] }, { enabled: false, instructions: [{ content: 'x', source: 'a.md' }] }]) {+ const result = await run(config);+ expect(systemContentOf(result)).toBe('You are a helpful assistant.');+ }+ });+});diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.tsindex 86e5a59547d..b9edf1f4bcf 100644--- a/packages/context-engine/src/providers/index.ts+++ b/packages/context-engine/src/providers/index.ts@@ -14,7 +14,9 @@ export { AgentManagementContextInjector } from './AgentManagementContextInjectorexport { BotPlatformContextInjector } from './BotPlatformContextInjector';export { ContextSelectionsInjector } from './ContextSelectionsInjector';export { DiscordContextProvider } from './DiscordContextProvider';+export { ConnectorOwnershipInjector } from './ConnectorOwnershipInjector';export { EvalContextSystemInjector } from './EvalContextSystemInjector';+export { ProjectInstructionsInjector } from './ProjectInstructionsInjector';export {buildExpertiseContextSnapshot,ExpertiseContextInjector,@@ -94,7 +96,12 @@ export type {} from './BotPlatformContextInjector';export type { ContextSelectionsInjectorConfig } from './ContextSelectionsInjector';export type { DiscordContext, DiscordContextProviderConfig } from './DiscordContextProvider';+export type { ConnectorOwnershipInjectorConfig } from './ConnectorOwnershipInjector';export type { EvalContext, EvalContextSystemInjectorConfig } from './EvalContextSystemInjector';+export type {+ ProjectInstructionFile,+ ProjectInstructionsInjectorConfig,+} from './ProjectInstructionsInjector';export type {ExpertiseContextInjectorConfig,ExpertiseContextSource,