π€― 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(mecha): share the context engineering core between hosts (#19514)
Arvin Xua8bf6854adaa
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/index.tsindex d33e923fa0f..0b13c1e6907 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/index.ts@@ -1,268 +1,132 @@-import { getShellSyntaxGuidance } from '@lobechat/builtin-tool-local-system';-import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';-import { MessagesEngine } from '@lobechat/context-engine';+import { type ContextSnapshot, runContextEngineering } from '@lobechat/mecha';import { type OpenAIChatMessage } from '@lobechat/types';import { type ServerMessagesEngineParams } from './types';/**- * Create server-side variable generators with runtime context- * These are safe to use in Node.js environment+ * Shape the server's per-step gathering into the host-agnostic context+ * snapshot. The assembly itself (engine parameters, placeholder generators,+ * page-agent gating) lives in `@lobechat/mecha` and is shared with the client.*/-const createServerVariableGenerators = (params: {- model?: string;- provider?: string;- timezone?: string;-}) => {- const { model, provider, timezone } = params;- const tz = timezone || 'UTC';- // Wall-clock components in the user's timezone. The client generators read them- // off a local Date (2-digit, 24h) β h23 keeps midnight as "00" instead of "24".- const timeParts = (): Record<string, string> => {- const parts = new Intl.DateTimeFormat('en-US', {- day: '2-digit',- hour: '2-digit',- hourCycle: 'h23',- minute: '2-digit',- month: '2-digit',- second: '2-digit',- timeZone: tz,- year: 'numeric',- }).formatToParts(new Date());- return Object.fromEntries(parts.map((part) => [part.type, part.value]));- };- return {- // Time-related variables (localized to user's timezone), mirroring the client- // VARIABLE_GENERATORS set so no temporal placeholder leaks as a literal in- // server-side runs. Prefer the coarse ones ({{date}}, {{hour}}) in system- // prompts: fine-grained values change every request and break prompt caching.- date: () => new Date().toLocaleDateString('en-US', { dateStyle: 'full', timeZone: tz }),- datetime: () => new Date().toLocaleString('en-US', { timeZone: tz }),- day: () => timeParts().day,- hour: () => timeParts().hour,- iso: () => new Date().toISOString(),- // The client resolves {{locale}} from the browser (Intl resolvedOptions). The- // server has no request locale here β the user's configured response language- // arrives via `additionalVariables` and overrides this through the spread- // order below; without it, fall back to the same default as- // UserModel.getInfoForAIGeneration instead of leaking the literal token.- locale: () => 'en-US',- minute: () => timeParts().minute,- month: () => timeParts().month,- second: () => timeParts().second,- time: () => new Date().toLocaleTimeString('en-US', { timeStyle: 'medium', timeZone: tz }),- timestamp: () => Date.now().toString(),- timezone: () => tz,- weekday: () => new Date().toLocaleDateString('en-US', { timeZone: tz, weekday: 'long' }),- year: () => timeParts().year,- // Model-related variables- model: () => model ?? '',- provider: () => provider ?? '',- // Working directory fallback. Unlike the client generator, the server has no- // store to resolve cwd from β the real value arrives via `additionalVariables`- // (`deviceSystemInfo.workingDirectory`, only set when a device-run's bound cwd- // resolves) and overrides this through the spread order below. Without this- // fallback, a device-run whose cwd can't be resolved (e.g. a web-originated- // session with no bound directory) leaves `{{workingDirectory}}` unmatched and- // leaks the literal into the local-system system prompt.- workingDirectory: () => '(not specified, use user Home directory as default)',- // Same leak-guard as workingDirectory: the real value arrives via- // `additionalVariables` (deviceSystemInfo.defaultShell) and overrides this.- // Without a device-reported value, describe the platform default instead of- // leaking the literal `{{defaultShell}}` token into the prompt.- defaultShell: () =>- 'the platform default shell (PowerShell on Windows, /bin/sh on macOS/Linux)',- // Same leak-guard for the paired syntax-guidance placeholder; passing- // undefined yields the shell-agnostic wording.- shellSyntaxGuidance: () => getShellSyntaxGuidance(undefined),- // Leak-guards for the device identity/path placeholders in the local-system- // system role. Real values arrive via `additionalVariables` (device system- // info) and override these; without a device report, tell the model the- // value is unknown instead of leaking the literal `{{...}}` token.- arch: () => 'unknown',- hostname: () => 'unknown',- platform: () => 'unknown',- desktopPath: () => '(not reported)',- documentsPath: () => '(not reported)',- downloadsPath: () => '(not reported)',- homePath: () => '(not reported)',- musicPath: () => '(not reported)',- picturesPath: () => '(not reported)',- userDataPath: () => '(not reported)',- videosPath: () => '(not reported)',- };-};--/**- * Server-side messages engine function- *- * This function wraps MessagesEngine for server-side usage.- * Unlike the frontend version, it receives all data as parameters- * instead of fetching from stores.- *- * @example- * ```typescript- * const messages = await serverMessagesEngine({- * messages: chatMessages,- * model: 'gpt-4',- * provider: 'openai',- * systemRole: 'You are a helpful assistant',- * knowledge: {- * fileContents: [...],- * knowledgeBases: [...],- * },- * });- * ```- */-export const serverMessagesEngine = async ({+export const toContextSnapshot = ({additionalContexts,- messages = [],- model,- modelDisplayName,- modelKnowledgeCutoff,- provider,- systemRole,+ additionalVariables,+ agentBuilderContext,+ agentDocuments,+ agentGroup,agentIdentity,- inputTemplate,+ agentManagementContext,+ botPlatformContext,+ capabilities,+ connectorOwnershipNote,+ discordContext,enableAgentMode,enableExpertise,enableHistoryCount,+ evalContext,+ expertise,forceFinish,+ formatHistorySummary,+ groupAgentBuilderContext,historyCount,historySummary,- formatHistorySummary,initialContext,+ inputTemplate,knowledge,- agentDocuments,- skillsConfig,- toolDiscoveryConfig,- toolsConfig,- capabilities,- userMemory,- agentBuilderContext,- agentGroup,- botPlatformContext,- workspaceContext,- discordContext,- evalContext,- expertise,- agentManagementContext,- groupAgentBuilderContext,+ messages = [],+ model,+ modelDisplayName,+ modelKnowledgeCutoff,onboardingContext,pageContentContext,planTodo,- topicReferences,- additionalVariables,- connectorOwnershipNote,projectInstructions,+ provider,+ skillsConfig,+ systemRole,+ toolDiscoveryConfig,+ toolsConfig,+ topicReferences,+ userMemory,userTimezone,-}: ServerMessagesEngineParams): Promise<OpenAIChatMessage[]> => {- const engine = new MessagesEngine({- additionalContexts,- connectorOwnershipNote,- projectInstructions,- // Capability injection+ workspaceContext,+}: ServerMessagesEngineParams): ContextSnapshot => ({+ agent: {+ documents: agentDocuments,+ enableHistoryCount,+ historyCount,+ identity: agentIdentity,+ inputTemplate,+ knowledge: { fileContents: knowledge?.fileContents, knowledgeBases: knowledge?.knowledgeBases },+ systemRole,+ },+ // Server-side file access URLs resolve to stable file-proxy URLs in production.+ fileContext: { enabled: true, includeFileUrl: true },+ model: {capabilities: {isCanUseAudio: capabilities?.isCanUseAudio,isCanUseFC: capabilities?.isCanUseFC,isCanUseVideo: capabilities?.isCanUseVideo,isCanUseVision: capabilities?.isCanUseVision,},-- // Agent configuration+ displayName: modelDisplayName,+ knowledgeCutoff: modelKnowledgeCutoff,+ model,+ provider,+ },+ run: {+ additionalContexts,enableAgentMode,enableExpertise,- enableHistoryCount,expertise,-- // Server-side file access URLs resolve to stable file-proxy URLs in production.- fileContext: { enabled: true, includeFileUrl: true },-- // Force finish mode (inject summary prompt when maxSteps exceeded)forceFinish,-formatHistorySummary,-- historyCount,-historySummary,-- inputTemplate,-initialContext,-- // Knowledge injection- knowledge: {- fileContents: knowledge?.fileContents,- knowledgeBases: knowledge?.knowledgeBases,- },- agentDocuments,-- // Messagesmessages,-- // Model info- model,- modelDisplayName,- modelKnowledgeCutoff,-- provider,+ },+ step: {+ agentBuilderContext,+ agentManagementContext,+ groupAgentBuilderContext,+ onboardingContext,+ pageContentContext,planTodo,- systemRole,- agentIdentity,-- // Timezone for system date provider- timezone: userTimezone,-- // Tools configuration+ topicReferences,+ workspaceContext,+ },+ tools: {+ disabledToolIdentifiers: toolsConfig?.disabledToolIdentifiers,+ enabledSkills: skillsConfig?.enabledSkills,+ enabledToolIds: toolsConfig?.tools,+ manifests: toolsConfig?.manifests,toolDiscoveryConfig,- toolsConfig: {- disabledToolIdentifiers:- toolsConfig?.disabledToolIdentifiers ??- (toolsConfig?.tools?.includes(PageAgentIdentifier) ? undefined : [PageAgentIdentifier]),- manifests: toolsConfig?.manifests,- tools: toolsConfig?.tools,- },-- // User memory configuration+ },+ variables: additionalVariables,+ world: {+ botPlatformContext,+ connectorOwnershipNote,+ discordContext,+ evalContext,+ group: agentGroup,+ projectInstructions,userMemory: userMemory?.memories- ? {- enabled: true,- fetchedAt: userMemory.fetchedAt,- memories: userMemory.memories,- }+ ? { enabled: true, fetchedAt: userMemory.fetchedAt, memories: userMemory.memories }: undefined,+ userTimezone,+ },+});- // Server-side variable generators (with model/provider context + device paths)- variableGenerators: {- ...createServerVariableGenerators({ model, provider, timezone: userTimezone }),- ...Object.fromEntries(- Object.entries(additionalVariables ?? {}).map(([k, v]) => [k, () => v]),- ),- },-- // Skills configuration- ...(skillsConfig?.enabledSkills && skillsConfig.enabledSkills.length > 0 && { skillsConfig }),-- // Topic references- ...(topicReferences && topicReferences.length > 0 && { topicReferences }),-- // Extended contexts- ...(agentBuilderContext && { agentBuilderContext }),- ...(agentGroup && { agentGroup }),- ...(botPlatformContext && { botPlatformContext }),- ...(workspaceContext && { workspaceContext }),- ...(discordContext && { discordContext }),- ...(evalContext && { evalContext }),- ...(onboardingContext && { onboardingContext }),- ...(agentManagementContext && { agentManagementContext }),- ...(groupAgentBuilderContext && { groupAgentBuilderContext }),- ...(pageContentContext && { pageContentContext }),- });-- const result = await engine.process();- return result.messages;-};+/**+ * Server-side messages engine function.+ *+ * Unlike the frontend version, it receives all data as parameters instead of+ * fetching from stores, shapes them into a {@link ContextSnapshot} and runs the+ * shared context engineering core.+ */+export const serverMessagesEngine = async (+ params: ServerMessagesEngineParams,+): Promise<OpenAIChatMessage[]> => runContextEngineering(toContextSnapshot(params));// Re-export typesexport type {diff --git a/packages/mecha/package.json b/packages/mecha/package.jsonindex fc2cd3405f1..65ebcd8c15f 100644--- a/packages/mecha/package.json+++ b/packages/mecha/package.json@@ -9,9 +9,11 @@},"dependencies": {"@lobechat/builtin-agents": "workspace:*",+ "@lobechat/builtin-tool-local-system": "workspace:*","@lobechat/builtin-tool-page-agent": "workspace:*","@lobechat/builtin-tool-task": "workspace:*","@lobechat/context-engine": "workspace:*",+ "@lobechat/prompts": "workspace:*","@lobechat/types": "workspace:*","debug": "^4.4.3","immer": "^10.1.3"diff --git a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.tsnew file mode 100644index 00000000000..f632bd5ad51--- /dev/null+++ b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.test.ts@@ -0,0 +1,99 @@+import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';+import { describe, expect, it } from 'vitest';++import { buildMessagesEngineParams } from './buildMessagesEngineParams';+import type { ContextSnapshot } from './types';++const baseSnapshot = (): ContextSnapshot => ({+ agent: { systemRole: 'You are helpful.' },+ model: { model: 'gpt-4', provider: 'openai' },+ run: { messages: [] },+});++describe('buildMessagesEngineParams', () => {+ it('hides the page agent system role unless the run enabled the tool', () => {+ expect(buildMessagesEngineParams(baseSnapshot()).toolsConfig?.disabledToolIdentifiers).toEqual([+ PageAgentIdentifier,+ ]);++ const withPageAgent = buildMessagesEngineParams({+ ...baseSnapshot(),+ tools: { enabledToolIds: [PageAgentIdentifier] },+ });+ expect(withPageAgent.toolsConfig?.disabledToolIdentifiers).toBeUndefined();++ const explicit = buildMessagesEngineParams({+ ...baseSnapshot(),+ tools: { disabledToolIdentifiers: ['x'], enabledToolIds: [] },+ });+ expect(explicit.toolsConfig?.disabledToolIdentifiers).toEqual(['x']);+ });++ it('only sets skills and topic references when there is something to inject', () => {+ const empty = buildMessagesEngineParams({+ ...baseSnapshot(),+ step: { topicReferences: [] },+ tools: { enabledSkills: [] },+ });+ expect(empty).not.toHaveProperty('skillsConfig');+ expect(empty).not.toHaveProperty('topicReferences');++ const filled = buildMessagesEngineParams({+ ...baseSnapshot(),+ step: { topicReferences: [{ id: 't1' } as any] },+ tools: { enabledSkills: [{ identifier: 's1' } as any] },+ });+ expect(filled.skillsConfig).toEqual({ enabledSkills: [{ identifier: 's1' }] });+ expect(filled.topicReferences).toEqual([{ id: 't1' }]);+ });++ it('places world and step facts without leaking undefined keys', () => {+ const params = buildMessagesEngineParams({+ ...baseSnapshot(),+ step: { planTodo: { enabled: true } },+ world: { connectorOwnershipNote: 'note', userTimezone: 'Asia/Shanghai' },+ });++ expect(params.connectorOwnershipNote).toBe('note');+ expect(params.timezone).toBe('Asia/Shanghai');+ expect(params.planTodo).toEqual({ enabled: true });+ expect(params).not.toHaveProperty('agentGroup');+ expect(params).not.toHaveProperty('workspaceContext');+ });++ it('defaults file URLs to the server-safe form and lets the host override', () => {+ expect(buildMessagesEngineParams(baseSnapshot()).fileContext).toEqual({+ enabled: true,+ includeFileUrl: true,+ });+ expect(+ buildMessagesEngineParams({+ ...baseSnapshot(),+ fileContext: { enabled: true, includeFileUrl: false },+ }).fileContext,+ ).toEqual({ enabled: true, includeFileUrl: false });+ });++ it('renders placeholders from the run timezone and lets host variables win', () => {+ const generators = buildMessagesEngineParams({+ ...baseSnapshot(),+ variables: {+ locale: 'zh-CN',+ topic_title: () => 'lazy',+ username: 'arvin',+ workingDirectory: '/repo',+ },+ world: { userTimezone: 'Asia/Tokyo' },+ }).variableGenerators!;++ expect(generators.timezone()).toBe('Asia/Tokyo');+ expect(generators.model()).toBe('gpt-4');+ expect(generators.locale()).toBe('zh-CN');+ expect(generators.username()).toBe('arvin');+ expect(generators.workingDirectory()).toBe('/repo');+ expect(generators.topic_title()).toBe('lazy');+ // Unresolved device placeholders never leak their literal token.+ expect(generators.hostname()).toBe('unknown');+ expect(generators.defaultShell()).not.toContain('{{');+ });+});diff --git a/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.tsnew file mode 100644index 00000000000..9bbcff6491f--- /dev/null+++ b/packages/mecha/src/contextEngineering/buildMessagesEngineParams.ts@@ -0,0 +1,100 @@+import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';+import type { MessagesEngineParams } from '@lobechat/context-engine';++import type { ContextSnapshot } from './types';+import { createVariableGenerators } from './variableGenerators';++const definedOnly = <T extends Record<string, unknown>>(record: T): Partial<T> =>+ Object.fromEntries(+ Object.entries(record).filter(([, value]) => value !== undefined),+ ) as Partial<T>;++/**+ * Turn a {@link ContextSnapshot} into the parameters the messages engine runs+ * on. Pure: the same snapshot always yields the same parameters, so hosts+ * differ only in how they assemble the snapshot.+ */+export const buildMessagesEngineParams = (snapshot: ContextSnapshot): MessagesEngineParams => {+ const { agent, fileContext, model, run, step, tools, variables, world } = snapshot;++ const enabledToolIds = tools?.enabledToolIds;+ // The page agent's system role is only meaningful while a page is being+ // edited; hide it unless the run enabled the tool explicitly.+ const disabledToolIdentifiers =+ tools?.disabledToolIdentifiers ??+ (enabledToolIds?.includes(PageAgentIdentifier) ? undefined : [PageAgentIdentifier]);++ return {+ // --- conversation + runtime flags ---+ additionalContexts: run.additionalContexts,+ enableAgentMode: run.enableAgentMode,+ enableExpertise: run.enableExpertise,+ expertise: run.expertise,+ forceFinish: run.forceFinish,+ formatHistorySummary: run.formatHistorySummary,+ historySummary: run.historySummary,+ initialContext: run.initialContext,+ messages: run.messages,+ stepContext: run.stepContext,++ // --- agent definition ---+ agentDocuments: agent.documents,+ agentIdentity: agent.identity,+ enableHistoryCount: agent.enableHistoryCount,+ historyCount: agent.historyCount,+ inputTemplate: agent.inputTemplate,+ knowledge: agent.knowledge,+ systemRole: agent.systemRole,++ // --- model ---+ capabilities: model.capabilities,+ model: model.model,+ modelDisplayName: model.displayName,+ modelKnowledgeCutoff: model.knowledgeCutoff,+ provider: model.provider,++ // --- tools + skills ---+ selectedSkills: tools?.selectedSkills,+ selectedTools: tools?.selectedTools,+ toolDiscoveryConfig: tools?.toolDiscoveryConfig,+ toolsConfig: {+ disabledToolIdentifiers,+ manifests: tools?.manifests,+ tools: enabledToolIds,+ },+ ...(tools?.enabledSkills?.length && { skillsConfig: { enabledSkills: tools.enabledSkills } }),++ // --- files + placeholders ---+ fileContext: fileContext ?? { enabled: true, includeFileUrl: true },+ variableGenerators: createVariableGenerators({+ model: model.model,+ provider: model.provider,+ timezone: world?.userTimezone,+ variables,+ }),+ timezone: world?.userTimezone,++ // --- world (frozen at creation) ---+ ...definedOnly({+ agentGroup: world?.group,+ botPlatformContext: world?.botPlatformContext,+ connectorOwnershipNote: world?.connectorOwnershipNote,+ discordContext: world?.discordContext,+ evalContext: world?.evalContext,+ projectInstructions: world?.projectInstructions,+ userMemory: world?.userMemory,+ }),++ // --- step facts (gathered per step) ---+ ...definedOnly({+ agentBuilderContext: step?.agentBuilderContext,+ agentManagementContext: step?.agentManagementContext,+ groupAgentBuilderContext: step?.groupAgentBuilderContext,+ onboardingContext: step?.onboardingContext,+ pageContentContext: step?.pageContentContext,+ planTodo: step?.planTodo,+ workspaceContext: step?.workspaceContext,+ }),+ ...(step?.topicReferences?.length && { topicReferences: step.topicReferences }),+ };+};diff --git a/packages/mecha/src/contextEngineering/index.ts b/packages/mecha/src/contextEngineering/index.tsnew file mode 100644index 00000000000..f2bae540f5b--- /dev/null+++ b/packages/mecha/src/contextEngineering/index.ts@@ -0,0 +1,24 @@+import { MessagesEngine } from '@lobechat/context-engine';+import type { OpenAIChatMessage } from '@lobechat/types';++import { buildMessagesEngineParams } from './buildMessagesEngineParams';+import type { ContextSnapshot } from './types';++/**+ * Run the context engine over a snapshot and return the messages to send.+ * The host owns gathering the snapshot and anything it does with the result.+ */+export const runContextEngineering = async (+ snapshot: ContextSnapshot,+): Promise<OpenAIChatMessage[]> => {+ const engine = new MessagesEngine(buildMessagesEngineParams(snapshot));+ const result = await engine.process();+ return result.messages;+};++export { buildMessagesEngineParams } from './buildMessagesEngineParams';+export type * from './types';+export {+ createVariableGenerators,+ type CreateVariableGeneratorsParams,+} from './variableGenerators';diff --git a/packages/mecha/src/contextEngineering/types.ts b/packages/mecha/src/contextEngineering/types.tsnew file mode 100644index 00000000000..c7bd95f05ef--- /dev/null+++ b/packages/mecha/src/contextEngineering/types.ts@@ -0,0 +1,163 @@+import type {+ AgentBuilderContext,+ AgentContextDocument,+ AgentGroupConfig,+ AgentManagementContext,+ BotPlatformContext,+ DiscordContext,+ EvalContext,+ FileContextConfig,+ GroupAgentBuilderContext,+ KnowledgeConfig,+ LobeToolManifest,+ ModelCapabilityChecker,+ OnboardingContext,+ PlanTodoConfig,+ ProjectInstructionFile,+ SkillMeta,+ ToolDiscoveryConfig,+ TopicReferenceItem,+ UserMemoryConfig,+ WorkspaceContext,+} from '@lobechat/context-engine';+import type { AgentIdentityContext, PageContentContext } from '@lobechat/prompts';+import type {+ ExpertiseContextSnapshot,+ RuntimeAdditionalContextFragment,+ RuntimeInitialContext,+ RuntimeSelectedSkill,+ RuntimeSelectedTool,+ RuntimeStepContext,+ UIChatMessage,+} from '@lobechat/types';++/** Placeholder values, eager or lazy. */+export type ContextVariables = Record<string, string | (() => string)>;++/**+ * The agent definition as it shapes the prompt: who the agent is and how it+ * wants its history and knowledge presented. Resolved once per run by the+ * host (`resolveAgentConfig`) and frozen.+ */+export interface ContextAgentSnapshot {+ /** Agent documents the agent may consult. */+ documents?: AgentContextDocument[];+ enableHistoryCount?: boolean;+ historyCount?: number;+ /** Identity shown to the model so it introduces itself by the user-given name. */+ identity?: AgentIdentityContext;+ inputTemplate?: string;+ /** Files and knowledge bases attached to the agent. */+ knowledge?: KnowledgeConfig;+ systemRole?: string;+}++/**+ * The model the turn is sent to, and what it can consume.+ */+export interface ContextModelSnapshot {+ capabilities?: ModelCapabilityChecker;+ displayName?: string;+ knowledgeCutoff?: string;+ model: string;+ provider: string;+}++/**+ * What the run itself carries into the turn: the conversation and the+ * runtime's own flags. Changes every step.+ */+export interface ContextRunSnapshot {+ additionalContexts?: readonly RuntimeAdditionalContextFragment[];+ /**+ * Runtime-resolved agent mode. `false` forces chat mode (skills and agent+ * documents are not injected) regardless of the stored chat config.+ */+ enableAgentMode?: boolean;+ enableExpertise?: boolean;+ expertise?: ExpertiseContextSnapshot;+ /** maxSteps exceeded: tools are stripped and a summary prompt is injected. */+ forceFinish?: boolean;+ formatHistorySummary?: (summary: string) => string;+ historySummary?: string;+ initialContext?: RuntimeInitialContext;+ messages: UIChatMessage[];+ stepContext?: RuntimeStepContext;+}++/**+ * Tools and skills the turn may use, already resolved for this step.+ */+export interface ContextToolsSnapshot {+ /**+ * Tool identifiers whose system roles must not be injected even though the+ * tool is enabled. Defaults to hiding the page agent unless it is enabled.+ */+ disabledToolIdentifiers?: string[];+ enabledSkills?: SkillMeta[];+ enabledToolIds?: string[];+ manifests?: LobeToolManifest[];+ /** Skills the user pinned for this request. */+ selectedSkills?: RuntimeSelectedSkill[];+ /** Tools the user pinned for this request. */+ selectedTools?: RuntimeSelectedTool[];+ toolDiscoveryConfig?: ToolDiscoveryConfig;+}++/**+ * Facts about the run's world that are fixed when the operation is created:+ * the roster, the project's instructions, the user's memory and timezone, the+ * channel the run came in on. Mirrors `AgentState.world`.+ */+export interface ContextWorldSnapshot {+ botPlatformContext?: BotPlatformContext;+ connectorOwnershipNote?: string;+ discordContext?: DiscordContext;+ evalContext?: EvalContext;+ group?: AgentGroupConfig;+ projectInstructions?: ProjectInstructionFile[];+ userMemory?: UserMemoryConfig;+ userTimezone?: string;+}++/**+ * Facts gathered fresh for this step because they move while the run executes:+ * the plan, referenced topics, the page being edited, builder / onboarding+ * state. The host decides how to fetch them; the core only places them.+ */+export interface ContextStepSnapshot {+ agentBuilderContext?: AgentBuilderContext;+ agentManagementContext?: AgentManagementContext;+ groupAgentBuilderContext?: GroupAgentBuilderContext;+ onboardingContext?: OnboardingContext;+ pageContentContext?: PageContentContext;+ planTodo?: PlanTodoConfig;+ topicReferences?: TopicReferenceItem[];+ workspaceContext?: WorkspaceContext;+}++/**+ * Everything the context engine needs to turn a run's state into the messages+ * sent to the model. Hosts assemble it from their own sources (runtime state+ * slots, database rows, client stores); the core is a pure function of it.+ */+export interface ContextSnapshot {+ agent: ContextAgentSnapshot;+ /**+ * How attached files are referenced. Server-side URLs resolve to stable+ * proxy URLs; desktop-local URLs are not fetchable by remote providers.+ */+ fileContext?: FileContextConfig;+ model: ContextModelSnapshot;+ run: ContextRunSnapshot;+ step?: ContextStepSnapshot;+ tools?: ContextToolsSnapshot;+ /**+ * Host-resolved placeholder values (`{{username}}`, `{{CREDS_LIST}}`,+ * device paths β¦). They override the core's defaults and leak guards. A+ * value may be a thunk so hosts only pay for expensive lookups when the+ * placeholder actually renders.+ */+ variables?: ContextVariables;+ world?: ContextWorldSnapshot;+}diff --git a/packages/mecha/src/contextEngineering/variableGenerators.ts b/packages/mecha/src/contextEngineering/variableGenerators.tsnew file mode 100644index 00000000000..eb8a74a1c37--- /dev/null+++ b/packages/mecha/src/contextEngineering/variableGenerators.ts@@ -0,0 +1,97 @@+import { getShellSyntaxGuidance } from '@lobechat/builtin-tool-local-system';+import type { VariableGenerators } from '@lobechat/context-engine';++import type { ContextVariables } from './types';++export interface CreateVariableGeneratorsParams {+ model?: string;+ provider?: string;+ /** IANA timezone the temporal placeholders render in. Defaults to UTC. */+ timezone?: string;+ /** Host-resolved values; each wins over the core default for the same key. */+ variables?: ContextVariables;+}++/**+ * Placeholder generators for the system role and tool prompts.+ *+ * Temporal values are localized to the run's timezone (prefer the coarse+ * `{{date}}` / `{{hour}}` in prompts: fine-grained values change every request+ * and break prompt caching). Everything a host may know better β the user's+ * locale and identity, the bound device's paths and shell, credential lists β+ * arrives through `variables` and overrides the defaults below; the defaults+ * exist so an unresolved placeholder never leaks its literal `{{β¦}}` token+ * into the prompt.+ */+export const createVariableGenerators = ({+ model,+ provider,+ timezone,+ variables,+}: CreateVariableGeneratorsParams): VariableGenerators => {+ const tz = timezone || 'UTC';+ // h23 keeps midnight as "00" instead of "24".+ const timeParts = (): Record<string, string> => {+ const parts = new Intl.DateTimeFormat('en-US', {+ day: '2-digit',+ hour: '2-digit',+ hourCycle: 'h23',+ minute: '2-digit',+ month: '2-digit',+ second: '2-digit',+ timeZone: tz,+ year: 'numeric',+ }).formatToParts(new Date());+ return Object.fromEntries(parts.map((part) => [part.type, part.value]));+ };++ const defaults: VariableGenerators = {+ // --- time ---+ date: () => new Date().toLocaleDateString('en-US', { dateStyle: 'full', timeZone: tz }),+ datetime: () => new Date().toLocaleString('en-US', { timeZone: tz }),+ day: () => timeParts().day,+ hour: () => timeParts().hour,+ iso: () => new Date().toISOString(),+ locale: () => 'en-US',+ minute: () => timeParts().minute,+ month: () => timeParts().month,+ second: () => timeParts().second,+ time: () => new Date().toLocaleTimeString('en-US', { timeStyle: 'medium', timeZone: tz }),+ timestamp: () => Date.now().toString(),+ timezone: () => tz,+ weekday: () => new Date().toLocaleDateString('en-US', { timeZone: tz, weekday: 'long' }),+ year: () => timeParts().year,++ // --- model ---+ model: () => model ?? '',+ provider: () => provider ?? '',++ // --- device leak guards: a run without a bound device still renders the+ // local-system prompt, so describe the unknown instead of leaking the token.+ arch: () => 'unknown',+ defaultShell: () =>+ 'the platform default shell (PowerShell on Windows, /bin/sh on macOS/Linux)',+ desktopPath: () => '(not reported)',+ documentsPath: () => '(not reported)',+ downloadsPath: () => '(not reported)',+ homePath: () => '(not reported)',+ hostname: () => 'unknown',+ musicPath: () => '(not reported)',+ picturesPath: () => '(not reported)',+ platform: () => 'unknown',+ shellSyntaxGuidance: () => getShellSyntaxGuidance(undefined),+ userDataPath: () => '(not reported)',+ videosPath: () => '(not reported)',+ workingDirectory: () => '(not specified, use user Home directory as default)',+ };++ return {+ ...defaults,+ ...Object.fromEntries(+ Object.entries(variables ?? {}).map(([key, value]) => [+ key,+ typeof value === 'function' ? value : () => value,+ ]),+ ),+ };+};diff --git a/packages/mecha/src/index.ts b/packages/mecha/src/index.tsindex f10af132e21..33789466c35 100644--- a/packages/mecha/src/index.ts+++ b/packages/mecha/src/index.ts@@ -1,3 +1,4 @@+export * from './contextEngineering';export type {AgentConfigResolverContext,AgentConfigSnapshot,