fix(mom): handle Slack msg_too_long errors gracefully

- Add try/catch to all Slack API calls in promise chain
- Truncate main channel messages at 35K with elaboration note
- Truncate thread messages at 20K
- Prevents process crash on long messages
This commit is contained in:
Mario Zechner 2025-12-04 23:39:17 +01:00
parent c7585e37c9
commit e1d3c2b76e
3 changed files with 152 additions and 68 deletions

View file

@ -127,7 +127,11 @@ function getRecentMessages(channelDir: string, turnCount: number): string {
for (const msg of turn) {
const date = (msg.date || "").substring(0, 19);
const user = msg.userName || msg.user || "";
const text = msg.text || "";
let text = msg.text || "";
// Truncate bot messages (tool results can be huge)
if (msg.isBot) {
text = truncateForContext(text, 50000, 2000, msg.ts);
}
const attachments = (msg.attachments || []).map((a) => a.local).join(",");
formatted.push(`${date}\t${user}\t${text}\t${attachments}`);
}
@ -136,6 +140,43 @@ function getRecentMessages(channelDir: string, turnCount: number): string {
return formatted.join("\n");
}
/**
* Truncate text to maxChars or maxLines, whichever comes first.
* Adds a note with stats and instructions if truncation occurred.
*/
function truncateForContext(text: string, maxChars: number, maxLines: number, ts?: string): string {
const lines = text.split("\n");
const originalLines = lines.length;
const originalChars = text.length;
let truncated = false;
let result = text;
// Check line limit first
if (lines.length > maxLines) {
result = lines.slice(0, maxLines).join("\n");
truncated = true;
}
// Check char limit
if (result.length > maxChars) {
result = result.substring(0, maxChars);
truncated = true;
}
if (truncated) {
const remainingLines = originalLines - result.split("\n").length;
const remainingChars = originalChars - result.length;
result += `\n[... truncated ${remainingLines} more lines, ${remainingChars} more chars. `;
if (ts) {
result += `To get full content: jq -r 'select(.ts=="${ts}") | .text' log.jsonl > /tmp/msg.txt, then read /tmp/msg.txt in segments]`;
} else {
result += `Search log.jsonl for full content]`;
}
}
return result;
}
function getMemory(channelDir: string): string {
const parts: string[] = [];
@ -545,7 +586,7 @@ export function createAgentRunner(sandboxConfig: SandboxConfig): AgentRunner {
date: new Date().toISOString(),
ts: toSlackTs(),
user: "bot",
text: `[Tool Result] ${event.toolName}: ${event.isError ? "ERROR: " : ""}${truncate(resultStr, 1000)}`,
text: `[Tool Result] ${event.toolName}: ${event.isError ? "ERROR: " : ""}${resultStr}`,
attachments: [],
isBot: true,
});