π€― 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
π fix(context-engine): attach diagnostic context to PlaceholderVariablesProcessor errors (#14741)
Arvin Xu36d0994ec2e9
diff --git a/packages/context-engine/src/base/BaseProcessor.ts b/packages/context-engine/src/base/BaseProcessor.tsindex 3b44eff7e7c..74da9d0cbc6 100644--- a/packages/context-engine/src/base/BaseProcessor.ts+++ b/packages/context-engine/src/base/BaseProcessor.ts@@ -27,11 +27,8 @@ export abstract class BaseProcessor implements ContextProcessor {this.validateOutput(result);return result;} catch (error) {- throw new ProcessorError(- this.name,- `Processing failed: ${error}`,- error instanceof Error ? error : new Error(String(error)),- );+ const cause = error instanceof Error ? error : new Error(String(error));+ throw new ProcessorError(this.name, `Processing failed: ${cause.message}`, cause);}}diff --git a/packages/context-engine/src/pipeline.ts b/packages/context-engine/src/pipeline.tsindex d31fe1dcd70..dcf39e09a1f 100644--- a/packages/context-engine/src/pipeline.ts+++ b/packages/context-engine/src/pipeline.ts@@ -112,10 +112,19 @@ export class ContextEngine {processorDurations[processor.name] = duration;log('Processor', processor.name, 'execution failed:', error);+ const cause = error instanceof Error ? error : new Error(String(error));++ // Build a diagnostic message that includes the immediate cause so+ // dashboard viewers can triage without raw stack access.+ const causeSummary =+ cause.message.length > 300+ ? cause.message.slice(0, 300) + 'β¦'+ : cause.message;+throw new PipelineError(- `Processor [${processor.name}] execution failed`,+ `Processor [${processor.name}] execution failed: ${causeSummary}`,processor.name,- error instanceof Error ? error : new Error(String(error)),+ cause,);}}diff --git a/packages/context-engine/src/processors/PlaceholderVariables.ts b/packages/context-engine/src/processors/PlaceholderVariables.tsindex ea5b27070de..e3d09300af8 100644--- a/packages/context-engine/src/processors/PlaceholderVariables.ts+++ b/packages/context-engine/src/processors/PlaceholderVariables.ts@@ -237,6 +237,39 @@ export const parsePlaceholderVariablesMessages = (return message;});+/**+ * Extract placeholder variable names from a message that are NOT in the+ * generator set (i.e. likely user typos or missing config).+ *+ * Used for diagnostic reporting β not for replacement logic.+ */+const extractUnresolvedPlaceholderNames = (message: any, generatorKeys: string[]): string[] => {+ const generatorSet = new Set(generatorKeys);+ const texts: string[] = [];++ if (typeof message?.content === 'string') {+ texts.push(message.content);+ } else if (Array.isArray(message?.content)) {+ for (const item of message.content) {+ if (item?.type === 'text' && typeof item.text === 'string') {+ texts.push(item.text);+ }+ }+ }++ const unresolved = new Set<string>();+ for (const text of texts) {+ const tokens = extractPlaceholderTokens(text);+ for (const token of tokens) {+ if (!generatorSet.has(token.key)) {+ unresolved.add(token.key);+ }+ }+ }++ return [...unresolved];+};+/*** PlaceholderVariables Processor* Responsible for handling placeholder variable replacement in messages@@ -256,39 +289,95 @@ export class PlaceholderVariablesProcessor extends BaseProcessor {let processedCount = 0;const depth = this.config.depth ?? 2;+ const generators = this.config.variableGenerators;++ // Defensive: guard against a malformed config that reached runtime despite+ // the TypeScript contract. A missing generator map is a harness bug, not a+ // user error β throw early with an actionable message.+ if (!generators || typeof generators !== 'object') {+ throw new Error(+ 'PlaceholderVariablesProcessor: variableGenerators config is missing or invalid. ' ++ `Received: ${JSON.stringify(generators)}`,+ );+ }- log(- `Starting placeholder variables processing with ${Object.keys(this.config.variableGenerators).length} generators`,- );- log('Generator keys: %o', Object.keys(this.config.variableGenerators));+ const generatorKeys = Object.keys(generators);+ log(`Starting placeholder variables processing with ${generatorKeys.length} generators`);+ log('Generator keys: %o', generatorKeys);++ // Collect per-message failures so the caller can see which message(s) failed+ // and with what placeholder(s), even when the processor recovers and continues.+ const failures: Array<{+ error: string;+ messageId?: string;+ messageIndex: number;+ messageRole?: string;+ contentPreview: string;+ unresolvedPlaceholders?: string[];+ }> = [];// Process placeholder variables for each messagefor (let i = 0; i < clonedContext.messages.length; i++) {const message = clonedContext.messages[i];+ const contentPreview =+ typeof message.content === 'string'+ ? message.content.slice(0, 200)+ : JSON.stringify(message.content).slice(0, 200);+log('Processing message %d: role=%s, contentType=%s, contentPreview=%s',i,message.role,typeof message.content,- typeof message.content === 'string'- ? message.content.slice(0, 200)- : JSON.stringify(message.content).slice(0, 200),+ contentPreview,);try {- const originalMessage = JSON.stringify(message);- const processedMessage = this.processMessagePlaceholders(message, depth);+ const { processed, unresolvedPlaceholders } =+ this.processMessagePlaceholdersWithDiagnostics(message, depth);- if (JSON.stringify(processedMessage) !== originalMessage) {- clonedContext.messages[i] = processedMessage;+ if (JSON.stringify(processed) !== JSON.stringify(message)) {+ clonedContext.messages[i] = processed;processedCount++;log(`Processed placeholders in message ${message.id}, role: ${message.role}`);} else {log(`No placeholders found/replaced in message ${message.id}, role: ${message.role}`);}++ // Even when processing "succeeded", track unresolvable placeholders+ // so the dashboard can alert on probable user typos.+ if (unresolvedPlaceholders && unresolvedPlaceholders.length > 0) {+ log(+ 'Unresolved placeholders in message %d (role=%s): %o',+ i,+ message.role,+ unresolvedPlaceholders,+ );+ }} catch (error) {- log.extend('error')(`Error processing placeholders in message ${message.id}: ${error}`);+ const errorMessage = error instanceof Error ? error.message : String(error);++ // Extract unresolved placeholder names from the message content for diagnostics+ const unresolvedPlaceholders = extractUnresolvedPlaceholderNames(message, generatorKeys);++ failures.push({+ contentPreview,+ error: errorMessage,+ messageId: message.id,+ messageIndex: i,+ messageRole: message.role,+ unresolvedPlaceholders,+ });++ log.extend('error')(+ `Error processing placeholders in message %d (id=%s, role=%s, unresolved=%o): %s`,+ i,+ message.id,+ message.role,+ unresolvedPlaceholders,+ errorMessage,+ );// Continue processing other messages}}@@ -296,42 +385,73 @@ export class PlaceholderVariablesProcessor extends BaseProcessor {// Update metadataclonedContext.metadata.placeholderVariablesProcessed = processedCount;+ // Attach failure diagnostics to metadata so the dashboard can surface them+ // without requiring debug-level logging.+ if (failures.length > 0) {+ (clonedContext.metadata as any).placeholderVariablesFailures = failures;+ }+log(`Placeholder variables processing completed, processed ${processedCount} messages`);return this.markAsExecuted(clonedContext);}/**- * Process placeholder variables for a single message+ * Process placeholder variables for a single message, returning both the+ * processed message and the list of placeholder names that could not be resolved.+ *+ * Unresolved placeholders are placeholders whose key exists in the message+ * but has no matching generator. They are likely user typos (e.g.+ * `{{nickname}}` misspelled as `{{nickName}}`) or a missing generator config.*/- private processMessagePlaceholders(message: any, depth: number): any {- if (!message?.content) return message;+ private processMessagePlaceholdersWithDiagnostics(+ message: any,+ depth: number,+ ): { processed: any; unresolvedPlaceholders: string[] } {+ if (!message?.content) return { processed: message, unresolvedPlaceholders: [] };const { content } = message;+ const generatorKeys = Object.keys(this.config.variableGenerators);+ const generatorSet = new Set(generatorKeys);++ // Helper to collect unresolved placeholder names from a text+ const collectUnresolvedFromText = (text: string): string[] => {+ const tokens = extractPlaceholderTokens(text);+ return tokens.filter((t) => !generatorSet.has(t.key)).map((t) => t.key);+ };- // Handle string type directlyif (typeof content === 'string') {+ const unresolved = collectUnresolvedFromText(content);return {- ...message,- content: parsePlaceholderVariables(content, this.config.variableGenerators, depth),+ processed: {+ ...message,+ content: parsePlaceholderVariables(content, this.config.variableGenerators, depth),+ },+ unresolvedPlaceholders: [...new Set(unresolved)],};}- // Handle array type by processing text elementsif (Array.isArray(content)) {+ const allUnresolved: string[] = [];return {- ...message,- content: content.map((item) =>- item?.type === 'text'- ? {+ processed: {+ ...message,+ content: content.map((item) => {+ if (item?.type === 'text' && typeof item.text === 'string') {+ const unresolved = collectUnresolvedFromText(item.text);+ allUnresolved.push(...unresolved);+ return {...item,text: parsePlaceholderVariables(item.text, this.config.variableGenerators, depth),- }- : item,- ),+ };+ }+ return item;+ }),+ },+ unresolvedPlaceholders: [...new Set(allUnresolved)],};}- return message;+ return { processed: message, unresolvedPlaceholders: [] };}}diff --git a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.tsindex 1c353e87276..555a5469746 100644--- a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts+++ b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts@@ -274,6 +274,132 @@ describe('PlaceholderVariablesProcessor', () => {expect(result.messages).toHaveLength(1);});+ it('should isolate generator throws per message and not over-count', async () => {+ const faultyGenerators = {+ error: () => {+ throw new Error('Generator error');+ },+ working: () => 'works',+ };++ const processor = new PlaceholderVariablesProcessor({+ variableGenerators: faultyGenerators,+ });++ const context = {+ initialState: {+ messages: [],+ model: 'gpt-4',+ provider: 'openai',+ systemRole: '',+ tools: [],+ },+ messages: [+ {+ id: 'bad',+ role: 'user',+ content: 'This {{working}} but this {{error}} fails',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ },+ {+ id: 'good',+ role: 'user',+ content: 'Only {{working}} here',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ },+ ],+ metadata: {+ model: 'gpt-4',+ maxTokens: 4096,+ },+ isAborted: false,+ executedProcessors: [],+ };++ const result = await processor.process(context);++ // The faulty message bails out of parsing and stays as-is β the throw must+ // not propagate or corrupt the run, and the count must not double-claim it.+ expect(result.messages[0].content).toBe('This {{working}} but this {{error}} fails');+ // A separate, non-faulty message in the same batch is processed normally β+ // the per-message try/catch in doProcess isolates the failure.+ expect(result.messages[1].content).toBe('Only works here');+ expect(result.metadata.placeholderVariablesProcessed).toBe(1);+ });++ it('should throw an actionable error when variableGenerators is missing', async () => {+ const processor = new PlaceholderVariablesProcessor({+ // Deliberately bypass the TS contract to simulate a misconfigured harness.+ variableGenerators: undefined as unknown as Record<string, () => string>,+ });++ const context = {+ initialState: {+ messages: [],+ model: 'gpt-4',+ provider: 'openai',+ systemRole: '',+ tools: [],+ },+ messages: [+ {+ id: '1',+ role: 'user',+ content: 'Hello {{username}}',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ },+ ],+ metadata: {+ model: 'gpt-4',+ maxTokens: 4096,+ },+ isAborted: false,+ executedProcessors: [],+ };++ await expect(processor.process(context)).rejects.toThrow(+ /variableGenerators config is missing or invalid/,+ );+ });++ it('should throw when variableGenerators is null', async () => {+ const processor = new PlaceholderVariablesProcessor({+ variableGenerators: null as unknown as Record<string, () => string>,+ });++ const context = {+ initialState: {+ messages: [],+ model: 'gpt-4',+ provider: 'openai',+ systemRole: '',+ tools: [],+ },+ messages: [+ {+ id: '1',+ role: 'user',+ content: 'Hello {{username}}',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ },+ ],+ metadata: {+ model: 'gpt-4',+ maxTokens: 4096,+ },+ isAborted: false,+ executedProcessors: [],+ };++ await expect(processor.process(context)).rejects.toThrow(+ /variableGenerators config is missing or invalid/,+ );+ });+it('should use custom depth setting', async () => {const processor = new PlaceholderVariablesProcessor({variableGenerators: mockVariableGenerators,@@ -344,6 +470,140 @@ describe('PlaceholderVariablesProcessor', () => {expect(result.metadata.placeholderVariablesProcessed).toBe(0);});++ it('should not count messages that contain only unresolved placeholders', async () => {+ const processor = new PlaceholderVariablesProcessor({+ variableGenerators: mockVariableGenerators,+ });++ const originalContent = 'Hello {{missing}}, see also {{alsoMissing}}';+ const context = {+ initialState: {+ messages: [],+ model: 'gpt-4',+ provider: 'openai',+ systemRole: '',+ tools: [],+ },+ messages: [+ {+ id: '1',+ role: 'user',+ content: originalContent,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ },+ ],+ metadata: {+ model: 'gpt-4',+ maxTokens: 4096,+ },+ isAborted: false,+ executedProcessors: [],+ };++ const result = await processor.process(context);++ // Count should NOT increment when no placeholder was replaced+ expect(result.metadata.placeholderVariablesProcessed).toBe(0);+ // Content should be left exactly as-is (preserves {{missing}} tokens)+ expect(result.messages[0].content).toBe(originalContent);+ });++ it('should not count array text-part messages with no replaceable placeholders', async () => {+ const processor = new PlaceholderVariablesProcessor({+ variableGenerators: mockVariableGenerators,+ });++ const arrayContent = [+ { type: 'text', text: 'No placeholders in here' },+ { type: 'text', text: 'Only {{missing}} here' },+ { type: 'image', image_url: 'https://example.com/x.png' },+ ];+ const context = {+ initialState: {+ messages: [],+ model: 'gpt-4',+ provider: 'openai',+ systemRole: '',+ tools: [],+ },+ messages: [+ {+ id: '1',+ role: 'user',+ content: arrayContent,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ },+ ],+ metadata: {+ model: 'gpt-4',+ maxTokens: 4096,+ },+ isAborted: false,+ executedProcessors: [],+ };++ const result = await processor.process(context);++ expect(result.metadata.placeholderVariablesProcessed).toBe(0);+ // Content shape preserved verbatim+ expect(result.messages[0].content).toEqual(arrayContent);+ });++ it('should count only messages whose content actually changed in a mixed batch', async () => {+ const processor = new PlaceholderVariablesProcessor({+ variableGenerators: mockVariableGenerators,+ });++ const context = {+ initialState: {+ messages: [],+ model: 'gpt-4',+ provider: 'openai',+ systemRole: '',+ tools: [],+ },+ messages: [+ {+ id: '1',+ role: 'user',+ content: 'No placeholders',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ },+ {+ id: '2',+ role: 'user',+ content: 'Hello {{username}}',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ },+ {+ id: '3',+ role: 'user',+ content: 'Only {{missing}}',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ },+ ],+ metadata: {+ model: 'gpt-4',+ maxTokens: 4096,+ },+ isAborted: false,+ executedProcessors: [],+ };++ const result = await processor.process(context);++ // Only message #2 had a real replacement+ expect(result.metadata.placeholderVariablesProcessed).toBe(1);+ expect(result.messages[0].content).toBe('No placeholders');+ expect(result.messages[1].content).toBe('Hello TestUser');+ expect(result.messages[2].content).toBe('Only {{missing}}');+ });});describe('formatPlaceholderValues & renderPlaceholderTemplate', () => {diff --git a/packages/context-engine/src/types.ts b/packages/context-engine/src/types.tsindex b0bee4dd722..70e5c1e4b7e 100644--- a/packages/context-engine/src/types.ts+++ b/packages/context-engine/src/types.ts@@ -188,30 +188,74 @@ export interface ModelCapabilities {}/**- * Processor error+ * Processor error β carries diagnostic context about which processor failed and why.+ *+ * The `cause` chain follows the ES2022 standard so that error-reporting tooling+ * (Sentry, DataDog, dashboard log viewers) can walk the full causal chain without+ * custom deserialisation. The legacy `originalError` property is kept for+ * backwards compatibility with existing catch sites that destructure it directly.*/export class ProcessorError extends Error {+ /** @deprecated Prefer reading the standard `cause` property. */+ public originalError?: Error;+constructor(public processorName: string,message: string,- public originalError?: Error,+ cause?: Error,) {- super(`[${processorName}] ${message}`);+ super(`[${processorName}] ${message}`, { cause });this.name = 'ProcessorError';+ this.originalError = cause;+ }++ /** Serialise the full causal chain so log aggregators can ingest it. */+ toJSON(): Record<string, unknown> {+ return {+ message: this.message,+ name: this.name,+ processorName: this.processorName,+ cause: this.cause+ ? this.cause instanceof Error && typeof (this.cause as any).toJSON === 'function'+ ? (this.cause as any).toJSON()+ : String(this.cause)+ : undefined,+ };}}/**- * Pipeline error+ * Pipeline error β thrown when a pipeline processor fails.+ *+ * Same design principles as {@link ProcessorError}: standard `cause` chain,+ * legacy `originalError` compatibility, and a `toJSON()` that preserves the+ * full error tree.*/export class PipelineError extends Error {+ /** @deprecated Prefer reading the standard `cause` property. */+ public originalError?: Error;+constructor(message: string,public processorName?: string,- public originalError?: Error,+ cause?: Error,) {- super(message);+ super(message, { cause });this.name = 'PipelineError';+ this.originalError = cause;+ }++ toJSON(): Record<string, unknown> {+ return {+ message: this.message,+ name: this.name,+ processorName: this.processorName,+ cause: this.cause+ ? this.cause instanceof Error && typeof (this.cause as any).toJSON === 'function'+ ? (this.cause as any).toJSON()+ : String(this.cause)+ : undefined,+ };}}