{"record":{"id":"2ea3ad43e592efae","repo":"mastra-ai/mastra","slug":"countcoresystemmessagetokens-can-only-be-used-with","errorCode":null,"errorMessage":"countCoreSystemMessageTokens can only be used with system messages, received role: ${message.role}","messagePattern":"countCoreSystemMessageTokens can only be used with system messages, received role: (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/core/src/processors/processors/token-limiter.ts","lineNumber":229,"sourceCode":"        },\n      );\n    }\n\n    // Remove messages that don't fit within the token budget\n    const keepIds = new Set(messagesToKeep.map(m => m.id));\n    const idsToRemove = messages.filter(m => !keepIds.has(m.id)).map(m => m.id);\n    if (idsToRemove.length > 0) {\n      messageList.removeByIds(idsToRemove);\n    }\n  }\n\n  /**\n   * Count tokens for a system message. Accepts both untagged and tagged system messages\n   * read from `messageList.getAllSystemMessages()`. Only string content is supported.\n   */\n  private async countCoreSystemMessageTokens(message: CoreMessageV4): Promise<number> {\n    if (message.role !== 'system') {\n      throw new Error(\n        `countCoreSystemMessageTokens can only be used with system messages, received role: ${message.role}`,\n      );\n    }\n\n    if (typeof message.content !== 'string') {\n      throw new Error('countCoreSystemMessageTokens: System message content must be a string');\n    }\n\n    const tokenString = message.role + message.content;\n\n    return this.countTokens(tokenString) + TokenLimiterProcessor.TOKENS_PER_MESSAGE;\n  }\n\n  /**\n   * Count tokens for an input message, including overhead for message structure\n   */\n  private async countInputMessageTokens(message: MastraDBMessage): Promise<number> {\n    let tokenString = message.role;","sourceCodeStart":211,"sourceCodeEnd":247,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/processors/processors/token-limiter.ts#L211-L247","documentation":"countCoreSystemMessageTokens is a private helper that tokenizes a message retrieved from messageList.getAllSystemMessages(). It guards that the passed message actually has role 'system'; anything else indicates an internal invariant violation (wrong list source or malformed MessageList contents) and throws a plain Error.","triggerScenarios":"processInputStep passes a CoreMessageV4 whose role is not 'system' to countCoreSystemMessageTokens — e.g. a MessageList regression where getAllSystemMessages() returns non-system messages, or custom code inserting developer/user-role messages into the system bucket.","commonSituations":"Custom processors or memory code injecting messages with unexpected roles tagged as system; upgrading @mastra/core and hitting an internal invariant change; subclassing/patching the processor and calling the helper directly with arbitrary messages.","solutions":["Check what you are putting into the MessageList as system messages — only role:'system' entries belong there.","If using a custom processor, only call countCoreSystemMessageTokens with messages from getAllSystemMessages().","Update @mastra/core to the latest patch — this may be a fixed MessageList regression.","Log the offending message.role and message content to find the code path inserting the wrong role."],"exampleFix":"// before\ncountCoreSystemMessageTokens(someUserMessage);\n// after\nif (msg.role === 'system') countCoreSystemMessageTokens(msg);","handlingStrategy":"type-guard","validationCode":null,"typeGuard":"function isSystemMessage(m) {\n  return !!m && m.role === 'system';\n}\n// use: if (isSystemMessage(msg)) countCoreSystemMessageTokens(msg);","tryCatchPattern":null,"preventionTips":["Only add role:'system' messages where system messages are expected.","Don't call private helpers with arbitrary messages.","Keep @mastra/core updated to avoid MessageList regressions."],"tags":["internal-invariant","processors","message-list","typescript"],"backgroundTag":"invalid-argument-type","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}