{"record":{"id":"a5fb60dac5765767","repo":"mastra-ai/mastra","slug":"tokenlimiterprocessor-no-messages-fit-within-the","errorCode":null,"errorMessage":"TokenLimiterProcessor: No messages fit within the remaining token budget. Cannot send LLM a request with no messages.","messagePattern":"TokenLimiterProcessor: No messages fit within the remaining token budget\\. Cannot send LLM a request with no messages\\.","errorType":"exception","errorClass":"TripWire","httpStatus":null,"severity":"error","filePath":"packages/core/src/processors/processors/token-limiter.ts","lineNumber":206,"sourceCode":"    for (let i = messages.length - 1; i >= 0; i--) {\n      const message = messages[i];\n      if (!message) continue;\n\n      const messageTokens = await this.countInputMessageTokens(message);\n\n      if (currentTokens + messageTokens <= remainingBudget) {\n        messagesToKeep.unshift(message);\n        currentTokens += messageTokens;\n      } else {\n        if (this.trimMode === 'contiguous') {\n          break;\n        }\n        // best-fit → continue (existing behavior)\n      }\n    }\n\n    if (messagesToKeep.length === 0) {\n      throw new TripWire(\n        'TokenLimiterProcessor: No messages fit within the remaining token budget. Cannot send LLM a request with no messages.',\n        {\n          retry: false,\n          metadata: { systemTokens, limit, remainingBudget, messageCount: messages.length },\n        },\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","sourceCodeStart":188,"sourceCodeEnd":224,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/processors/processors/token-limiter.ts#L188-L224","documentation":"After keeping all system messages, TokenLimiterProcessor runs best-fit selection over non-system messages against the remaining budget (remainingBudget = limit - systemTokens - conversation overhead). If not even one non-system message fits, the resulting request would contain no conversational messages, so the processor throws a TripWire with retry:false.","triggerScenarios":"processInputStep: messagesToKeep.length === 0 after best-fit selection because remainingBudget is smaller than the token count of every candidate message (metadata includes systemTokens, limit, remainingBudget, messageCount).","commonSituations":"A maxTokens barely above the system prompt size; one enormous user message (e.g. a pasted document) that alone exceeds the budget; a long conversation where the newest message alone doesn't fit.","solutions":["Raise maxTokens so the remaining budget after system messages fits at least the latest user message.","Split or truncate very large user messages before they reach the processor.","Reduce system prompt size to increase remainingBudget.","Catch the TripWire and implement application-level truncation/chunking of the input before retrying."],"exampleFix":"// before\nnew TokenLimiterProcessor({ maxTokens: 2000 }); // remainingBudget < any single message\n// after\nnew TokenLimiterProcessor({ maxTokens: 16000 });","handlingStrategy":"validation","validationCode":"const largestMsgTokens = Math.max(...nonSystemMessages.map(m => processor.countTokens(String(m.content))));\nconst remainingBudget = maxTokens - systemTokens - 1000;\nif (remainingBudget < largestMsgTokens) {\n  throw new Error('Remaining token budget cannot fit any single message; raise maxTokens or truncate input');\n}","typeGuard":null,"tryCatchPattern":"try {\n  await agent.generate(input);\n} catch (e) {\n  if (e?.name === 'TripWire' && e?.message?.includes('No messages fit')) {\n    // truncate/chunk the newest user message, then retry once\n  } else throw e;\n}","preventionTips":["Cap individual user message sizes at ingestion time.","Reserve headroom: maxTokens >= systemTokens + largestExpectedMessage + overhead.","Chunk large documents before sending them to the agent."],"tags":["token-limit","processors","tripwire","message-list"],"backgroundTag":"token-limit-exceeded","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T08:17:16.595Z"}