@geminixiang/mama 0.2.0-beta.5 → 0.2.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +73 -18
  2. package/dist/adapters/discord/bot.d.ts +1 -1
  3. package/dist/adapters/discord/bot.d.ts.map +1 -1
  4. package/dist/adapters/discord/bot.js +67 -17
  5. package/dist/adapters/discord/bot.js.map +1 -1
  6. package/dist/adapters/slack/bot.d.ts +4 -0
  7. package/dist/adapters/slack/bot.d.ts.map +1 -1
  8. package/dist/adapters/slack/bot.js +60 -8
  9. package/dist/adapters/slack/bot.js.map +1 -1
  10. package/dist/adapters/telegram/bot.d.ts.map +1 -1
  11. package/dist/adapters/telegram/bot.js +1 -35
  12. package/dist/adapters/telegram/bot.js.map +1 -1
  13. package/dist/agent.d.ts.map +1 -1
  14. package/dist/agent.js +3 -3
  15. package/dist/agent.js.map +1 -1
  16. package/dist/commands/index.d.ts.map +1 -1
  17. package/dist/commands/index.js +8 -1
  18. package/dist/commands/index.js.map +1 -1
  19. package/dist/commands/model.d.ts +14 -0
  20. package/dist/commands/model.d.ts.map +1 -0
  21. package/dist/commands/model.js +94 -0
  22. package/dist/commands/model.js.map +1 -0
  23. package/dist/commands/new.d.ts +9 -0
  24. package/dist/commands/new.d.ts.map +1 -0
  25. package/dist/commands/new.js +28 -0
  26. package/dist/commands/new.js.map +1 -0
  27. package/dist/commands/types.d.ts +2 -0
  28. package/dist/commands/types.d.ts.map +1 -1
  29. package/dist/commands/types.js.map +1 -1
  30. package/dist/config.d.ts +11 -4
  31. package/dist/config.d.ts.map +1 -1
  32. package/dist/config.js +148 -31
  33. package/dist/config.js.map +1 -1
  34. package/dist/main.d.ts.map +1 -1
  35. package/dist/main.js +46 -3
  36. package/dist/main.js.map +1 -1
  37. package/dist/runtime/session-runtime.d.ts +1 -0
  38. package/dist/runtime/session-runtime.d.ts.map +1 -1
  39. package/dist/runtime/session-runtime.js +18 -0
  40. package/dist/runtime/session-runtime.js.map +1 -1
  41. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"bot.js","sourceRoot":"","sources":["../../../src/adapters/telegram/bot.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACxE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACtC,OAAO,EAAE,GAAG,IAAI,SAAS,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC;AAErD,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,EACL,oBAAoB,EACpB,gBAAgB,EAChB,YAAY,EACZ,2BAA2B,EAC3B,iBAAiB,EACjB,SAAS,GACV,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAE/C,+EAA+E;AAC/E,wEAAwE;AACxE,wEAAwE;AACxE,SAAS,qBAAqB,CAAC,GAAU;IACvC,OAAQ,GAA+B,CAAC,UAAU,KAAK,GAAG,CAAC;AAC7D,CAAC;AAED,MAAM,aAAa,GAAG,CAAI,EAAoB,EAAc,EAAE,CAC5D,SAAS,CAAC,EAAE,EAAE,EAAE,aAAa,EAAE,qBAAqB,EAAE,CAAC,CAAC;AAwB1D,+EAA+E;AAC/E,cAAc;AACd,+EAA+E;AAE/E,SAAS,wBAAwB,CAAC,OAAe;IAC/C,OAAO,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAC,CAAC;AAClD,CAAC;AAED,MAAM,OAAO,WAAW;IAUtB,YAAY,OAAmB,EAAE,MAA6C;QALtE,cAAS,GAA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\nimport { Bot as GrammyBot, InputFile } from \"grammy\";\nimport type { Bot, BotEvent, BotHandler, PlatformInfo } from \"../../adapter.js\";\nimport * as log from \"../../log.js\";\nimport { resolveChatSessionKey } from \"../../session-policy.js\";\nimport { formatAlreadyWorking, formatNothingRunning } from \"../../ui-copy.js\";\nimport {\n appendBotResponseLog,\n appendChannelLog,\n ChannelQueue,\n resolveOnlyScopedStopTarget,\n resolveStopTarget,\n withRetry,\n} from \"../shared.js\";\nimport { createTelegramAdapters } from \"./context.js\";\nimport { escapeTelegramHtml } from \"./html.js\";\n\n// grammY surfaces Telegram errors as `GrammyError` with `error_code` mirroring\n// the Bot API. 429 is the rate-limit status; the response also includes\n// `parameters.retry_after` but exponential backoff is good enough here.\nfunction telegramIsRateLimited(err: Error): boolean {\n return (err as { error_code?: number }).error_code === 429;\n}\n\nconst telegramRetry = <T>(fn: () => Promise<T>): Promise<T> =>\n withRetry(fn, { isRateLimited: telegramIsRateLimited });\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface TelegramEvent extends BotEvent {\n type: \"message\" | \"command\";\n userName?: string;\n}\n\ninterface MessageContext {\n msg: any;\n text: string;\n chatId: string;\n chatType: string;\n conversationKind: \"direct\" | \"shared\";\n userId: string;\n userName: string;\n msgId: string;\n threadTs: string | undefined;\n sessionKey: string;\n}\n\n// ============================================================================\n// TelegramBot\n// ============================================================================\n\nfunction isTelegramHtmlParseError(message: string): boolean {\n return message.includes(\"can't parse entities\");\n}\n\nexport class TelegramBot implements Bot {\n private client: GrammyBot;\n private handler: BotHandler;\n private botToken: string;\n private workingDir: string;\n private botUserId: string | null = null;\n private botUsername: string | null = null;\n private queues = new Map<string, ChannelQueue>();\n private startupTime: number = 0;\n\n constructor(handler: BotHandler, config: { token: string; workingDir: string }) {\n this.handler = handler;\n this.botToken = config.token;\n this.workingDir = config.workingDir;\n this.client = new GrammyBot(config.token);\n this.client.catch((err) => {\n log.logWarning(\"Telegram error\", err instanceof Error ? err.message : String(err));\n });\n }\n\n // ==========================================================================\n // Public API (implements Bot)\n // ==========================================================================\n\n async start(): Promise<void> {\n const me = await this.client.api.getMe();\n this.botUserId = String(me.id);\n this.botUsername = me.username ?? null;\n this.startupTime = Date.now();\n\n await this.client.api.setMyCommands([\n { command: \"start\", description: \"Welcome message\" },\n { command: \"help\", description: \"Show available commands\" },\n { command: \"login\", description: \"Store credentials in your private vault\" },\n { command: \"session\", description: \"Open the current session in the web viewer\" },\n { command: \"stop\", description: \"Stop ongoing conversation\" },\n { command: \"new\", description: \"Reset conversation history and start fresh\" },\n ]);\n\n this.setupEventHandlers();\n\n // Start polling in background (bot.start() runs indefinitely)\n this.client.start().catch((err) => {\n log.logWarning(\"Telegram polling error\", err instanceof Error ? err.message : String(err));\n });\n\n log.logConnected();\n log.logInfo(`Telegram bot started as @${this.botUsername ?? this.botUserId}`);\n }\n\n async postMessage(channel: string, text: string): Promise<string> {\n const result = await this.postMessageRaw(parseInt(channel), text);\n return String(result);\n }\n\n async updateMessage(channel: string, ts: string, text: string): Promise<void> {\n return telegramRetry(async () => {\n try {\n await this.client.api.editMessageText(parseInt(channel), parseInt(ts), text, {\n parse_mode: \"HTML\",\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (msg.includes(\"message is not modified\")) {\n return;\n }\n if (!isTelegramHtmlParseError(msg)) {\n throw err;\n }\n await this.client.api.editMessageText(\n parseInt(channel),\n parseInt(ts),\n escapeTelegramHtml(text),\n {\n parse_mode: \"HTML\",\n },\n );\n }\n });\n }\n\n enqueueEvent(event: BotEvent): boolean {\n const conversationId = event.conversationId;\n const queue = this.getQueue(conversationId);\n if (queue.size() >= 5) {\n log.logWarning(\n `Event queue full for ${conversationId}, discarding: ${event.text.substring(0, 50)}`,\n );\n return false;\n }\n log.logInfo(`Enqueueing event for ${conversationId}: ${event.text.substring(0, 50)}`);\n queue.enqueue(() => {\n const adapters = createTelegramAdapters(event as TelegramEvent, this, true);\n return this.handler.handleEvent(event, this, adapters, true);\n });\n return true;\n }\n\n getPlatformInfo(): PlatformInfo {\n return {\n name: \"telegram\",\n formattingGuide:\n '## Telegram Formatting (HTML mode)\\nBold: <b>text</b>, Italic: <i>text</i>, Code: <code>code</code>, Pre: <pre>code</pre>\\nLinks: <a href=\"url\">text</a>',\n channels: [],\n users: [],\n };\n }\n\n // ==========================================================================\n // Internal helpers (used by context.ts)\n // ==========================================================================\n\n async postMessageRaw(chatId: number, text: string): Promise<number> {\n return telegramRetry(async () => {\n try {\n const result = await this.client.api.sendMessage(chatId, text, { parse_mode: \"HTML\" });\n return result.message_id;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (!isTelegramHtmlParseError(msg)) {\n throw err;\n }\n const result = await this.client.api.sendMessage(chatId, escapeTelegramHtml(text), {\n parse_mode: \"HTML\",\n });\n return result.message_id;\n }\n });\n }\n\n async postPlainMessage(chatId: number, text: string): Promise<void> {\n return telegramRetry(async () => {\n await this.client.api.sendMessage(chatId, text);\n });\n }\n\n async postReply(chatId: number, replyToMessageId: number, text: string): Promise<number> {\n return telegramRetry(async () => {\n try {\n const result = await this.client.api.sendMessage(chatId, text, {\n parse_mode: \"HTML\",\n reply_parameters: { message_id: replyToMessageId },\n });\n return result.message_id;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (!isTelegramHtmlParseError(msg)) {\n throw err;\n }\n const result = await this.client.api.sendMessage(chatId, escapeTelegramHtml(text), {\n parse_mode: \"HTML\",\n reply_parameters: { message_id: replyToMessageId },\n });\n return result.message_id;\n }\n });\n }\n\n async deleteMessageRaw(chatId: number, messageId: number): Promise<void> {\n await this.client.api.deleteMessage(chatId, messageId);\n }\n\n async sendTyping(chatId: number): Promise<void> {\n await this.client.api.sendChatAction(chatId, \"typing\");\n }\n\n async uploadFile(channel: string, filePath: string, title?: string): Promise<void> {\n return telegramRetry(async () => {\n const fileName = title ?? basename(filePath);\n const fileContent = readFileSync(filePath);\n await this.client.api.sendDocument(parseInt(channel), new InputFile(fileContent, fileName));\n });\n }\n\n logToFile(channel: string, entry: object): void {\n appendChannelLog(this.workingDir, channel, entry);\n }\n\n logBotResponse(channel: string, text: string, ts: string): void {\n appendBotResponseLog(this.workingDir, channel, text, ts);\n }\n\n /**\n * Process attachments from a Telegram message\n * Downloads files before returning metadata so the agent can read them immediately\n * Returns format compatible with ChatMessage: { name: string, localPath: string }[]\n */\n async processAttachments(\n chatId: string,\n message: any,\n ): Promise<{ name: string; localPath: string }[]> {\n const downloads: Array<Promise<{ name: string; localPath: string } | null>> = [];\n\n // Handle photos (take the largest size for best quality)\n if (message.photo && message.photo.length > 0) {\n const photos = message.photo;\n const photo = photos[photos.length - 1]; // Largest photo\n const fileId = photo.file_id;\n\n downloads.push(this.processTelegramFile(chatId, fileId, `photo_${message.message_id}.jpg`));\n }\n\n // Handle documents\n if (message.document) {\n const doc = message.document;\n const fileId = doc.file_id;\n const fileName = doc.file_name ?? `document_${message.message_id}`;\n\n downloads.push(this.processTelegramFile(chatId, fileId, fileName));\n }\n\n const attachments = await Promise.all(downloads);\n return attachments.filter(\n (attachment): attachment is { name: string; localPath: string } => attachment !== null,\n );\n }\n\n /**\n * Download a file from Telegram and return attachment metadata\n */\n private async processTelegramFile(\n chatId: string,\n fileId: string,\n originalName: string,\n ): Promise<{ name: string; localPath: string } | null> {\n try {\n // Get file info from Telegram\n const file = await this.client.api.getFile(fileId);\n if (!file.file_path) {\n log.logWarning(\"Telegram file has no path\", fileId);\n return null;\n }\n\n // Generate local filename\n const ts = Date.now();\n const sanitizedName = originalName.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n const filename = `${ts}_${sanitizedName}`;\n const localPath = `${chatId}/attachments/${filename}`;\n const fullDir = join(this.workingDir, chatId, \"attachments\");\n\n if (!existsSync(fullDir)) mkdirSync(fullDir, { recursive: true });\n\n // Construct download URL\n const downloadUrl = `https://api.telegram.org/file/bot${this.botToken}/${file.file_path}`;\n\n // Download the file\n const response = await fetch(downloadUrl);\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n const buffer = await response.arrayBuffer();\n writeFileSync(join(fullDir, filename), Buffer.from(buffer));\n\n return {\n name: originalName,\n localPath: localPath,\n };\n } catch (err) {\n log.logWarning(`Failed to process Telegram file`, `${originalName}: ${err}`);\n return null;\n }\n }\n\n // ==========================================================================\n // Private - Event Handlers\n // ==========================================================================\n\n private getQueue(channelId: string): ChannelQueue {\n let queue = this.queues.get(channelId);\n if (!queue) {\n queue = new ChannelQueue(\"Telegram\");\n this.queues.set(channelId, queue);\n }\n return queue;\n }\n\n private extractMessageContext(msg: any): MessageContext | null {\n if (!msg) return null;\n if (msg.date * 1000 < this.startupTime) return null;\n if (msg.from?.is_bot) return null;\n\n const text = msg.text ?? msg.caption ?? \"\";\n if (!text && !msg.document && !msg.photo) return null;\n\n const chatId = String(msg.chat.id);\n const chatType = msg.chat.type;\n const userId = String(msg.from?.id ?? \"unknown\");\n const userName = msg.from?.username ?? msg.from?.first_name ?? userId;\n const msgId = String(msg.message_id);\n const replyToId = msg.reply_to_message?.message_id;\n const threadTs = replyToId ? String(replyToId) : undefined;\n const conversationKind = chatType === \"private\" ? \"direct\" : \"shared\";\n\n const sessionKey = resolveChatSessionKey({\n conversationId: chatId,\n conversationKind,\n messageId: msgId,\n threadTs,\n });\n\n return {\n msg,\n text,\n chatId,\n chatType,\n conversationKind,\n userId,\n userName,\n msgId,\n threadTs,\n sessionKey,\n };\n }\n\n private isAddressedToBot(text: string, chatType: string): boolean {\n if (chatType === \"private\") return true;\n if (!this.botUsername) return false;\n return text.toLowerCase().includes(`@${this.botUsername.toLowerCase()}`);\n }\n\n private cleanText(text: string): string {\n if (!this.botUsername) return text.trim();\n return text.replace(new RegExp(`@${this.botUsername}`, \"gi\"), \"\").trim();\n }\n\n private isStopText(text: string): boolean {\n return /^\\/?stop(?:@\\w+)?$/i.test(text.trim());\n }\n\n private resolveStopTarget(mc: MessageContext): string | null {\n const directTarget = resolveStopTarget({\n handler: this.handler,\n conversationId: mc.chatId,\n sessionKey: mc.sessionKey,\n });\n if (directTarget) return directTarget;\n return resolveOnlyScopedStopTarget(this.handler, mc.chatId);\n }\n\n private setupEventHandlers(): void {\n // --- Slash commands (registered before catch-all so grammY intercepts them) ---\n\n this.client.command(\"start\", async (ctx) => {\n const mc = this.extractMessageContext(ctx.message);\n if (!mc) return;\n await this.postMessageRaw(\n parseInt(mc.chatId),\n [\n \"<b>Welcome!</b>\",\n \"\",\n \"I'm an AI coding agent. Send me a message or use these commands:\",\n \"\",\n \"/new — Reset conversation history and start fresh\",\n \"/stop — Stop the current conversation\",\n \"/session — Open the current session in the web viewer\",\n \"/help — Show available commands\",\n \"/login — Store credentials in your private vault\",\n ].join(\"\\n\"),\n );\n });\n\n this.client.command(\"help\", async (ctx) => {\n const mc = this.extractMessageContext(ctx.message);\n if (!mc) return;\n await this.postMessageRaw(\n parseInt(mc.chatId),\n [\n \"<b>Available commands:</b>\",\n \"\",\n \"/start — Welcome message\",\n \"/help — Show this help\",\n \"/login — Store credentials in your private vault\",\n \"/session — Open the current session in the web viewer\",\n \"/stop — Stop ongoing conversation\",\n \"/new — Reset conversation history and start fresh\",\n \"\",\n \"You can also send a regular message to chat with the agent.\",\n ].join(\"\\n\"),\n );\n });\n\n this.client.command(\"stop\", async (ctx) => {\n const mc = this.extractMessageContext(ctx.message);\n if (!mc) return;\n const stopTarget = this.resolveStopTarget(mc);\n if (stopTarget) {\n await this.handler.handleStop(stopTarget, mc.chatId, this);\n } else {\n await this.postMessage(mc.chatId, formatNothingRunning(\"telegram\"));\n }\n });\n\n this.client.command(\"new\", async (ctx) => {\n const mc = this.extractMessageContext(ctx.message);\n if (!mc) return;\n await this.handler.handleNew(mc.sessionKey, mc.chatId, this);\n });\n\n // --- Catch-all for regular (non-command) messages ---\n\n this.client.on(\"message\", async (ctx) => {\n const mc = this.extractMessageContext(ctx.message);\n if (!mc) return;\n\n const cleanedText = this.cleanText(mc.text);\n const addressedToBot = this.isAddressedToBot(mc.text, mc.chatType);\n\n if (this.isStopText(cleanedText)) {\n this.logToFile(mc.chatId, {\n date: new Date(mc.msg.date * 1000).toISOString(),\n ts: mc.msgId,\n user: mc.userId,\n userName: mc.userName,\n text: cleanedText,\n attachments: [],\n isBot: false,\n });\n\n const stopTarget = this.resolveStopTarget(mc);\n if (stopTarget) {\n await this.handler.handleStop(stopTarget, mc.chatId, this);\n } else if (addressedToBot || mc.chatType === \"private\") {\n await this.postMessage(mc.chatId, formatNothingRunning(\"telegram\"));\n }\n return;\n }\n\n // In groups, only respond when addressed to bot\n if (!addressedToBot) return;\n\n // Process attachments\n const processedAttachments = await this.processAttachments(mc.chatId, mc.msg);\n\n const event: TelegramEvent = {\n type: \"message\",\n conversationId: mc.chatId,\n conversationKind: mc.conversationKind,\n ts: mc.msgId,\n thread_ts: mc.threadTs,\n sessionKey: mc.sessionKey,\n user: mc.userId,\n userName: mc.userName,\n text: cleanedText,\n attachments: processedAttachments,\n };\n\n // Log the message\n this.logToFile(mc.chatId, {\n date: new Date(mc.msg.date * 1000).toISOString(),\n ts: mc.msgId,\n ...(mc.conversationKind === \"shared\" && mc.threadTs ? { threadTs: mc.threadTs } : {}),\n user: mc.userId,\n userName: mc.userName,\n text: cleanedText,\n attachments: processedAttachments,\n isBot: false,\n });\n\n if (this.handler.isRunning(mc.sessionKey)) {\n await this.postMessage(mc.chatId, formatAlreadyWorking(\"telegram\", \"/stop\"));\n } else {\n this.getQueue(mc.sessionKey).enqueue(() => {\n const adapters = createTelegramAdapters(event, this, false);\n return this.handler.handleEvent(event, this, adapters, false);\n });\n }\n });\n }\n}\n"]}
1
+ {"version":3,"file":"bot.js","sourceRoot":"","sources":["../../../src/adapters/telegram/bot.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AACxE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACtC,OAAO,EAAE,G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,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,WAAW,EAAE;gBAChD,EAAE,EAAE,EAAE,CAAC,KAAK;gBACZ,GAAG,CAAC,EAAE,CAAC,gBAAgB,KAAK,QAAQ,IAAI,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;gBACrF,IAAI,EAAE,EAAE,CAAC,MAAM;gBACf,QAAQ,EAAE,EAAE,CAAC,QAAQ;gBACrB,IAAI,EAAE,WAAW;gBACjB,WAAW,EAAE,oBAAoB;gBACjC,KAAK,EAAE,KAAK;aACb,CAAC,CAAC;YAEH,IAAI,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC,UAAU,CAAC,EAAE,CAAC;gBAC1C,MAAM,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,MAAM,EAAE,oBAAoB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC;YAC/E,CAAC;iBAAM,CAAC;gBACN,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE;oBACxC,MAAM,QAAQ,GAAG,sBAAsB,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;oBAC5D,OAAO,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;gBAChE,CAAC,CAAC,CAAC;YACL,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from \"fs\";\nimport { basename, join } from \"path\";\nimport { Bot as GrammyBot, InputFile } from \"grammy\";\nimport type { Bot, BotEvent, BotHandler, PlatformInfo } from \"../../adapter.js\";\nimport * as log from \"../../log.js\";\nimport { resolveChatSessionKey } from \"../../session-policy.js\";\nimport { formatAlreadyWorking, formatNothingRunning } from \"../../ui-copy.js\";\nimport {\n appendBotResponseLog,\n appendChannelLog,\n ChannelQueue,\n resolveOnlyScopedStopTarget,\n resolveStopTarget,\n withRetry,\n} from \"../shared.js\";\nimport { createTelegramAdapters } from \"./context.js\";\nimport { escapeTelegramHtml } from \"./html.js\";\n\n// grammY surfaces Telegram errors as `GrammyError` with `error_code` mirroring\n// the Bot API. 429 is the rate-limit status; the response also includes\n// `parameters.retry_after` but exponential backoff is good enough here.\nfunction telegramIsRateLimited(err: Error): boolean {\n return (err as { error_code?: number }).error_code === 429;\n}\n\nconst telegramRetry = <T>(fn: () => Promise<T>): Promise<T> =>\n withRetry(fn, { isRateLimited: telegramIsRateLimited });\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface TelegramEvent extends BotEvent {\n type: \"message\" | \"command\";\n userName?: string;\n}\n\ninterface MessageContext {\n msg: any;\n text: string;\n chatId: string;\n chatType: string;\n conversationKind: \"direct\" | \"shared\";\n userId: string;\n userName: string;\n msgId: string;\n threadTs: string | undefined;\n sessionKey: string;\n}\n\n// ============================================================================\n// TelegramBot\n// ============================================================================\n\nfunction isTelegramHtmlParseError(message: string): boolean {\n return message.includes(\"can't parse entities\");\n}\n\nexport class TelegramBot implements Bot {\n private client: GrammyBot;\n private handler: BotHandler;\n private botToken: string;\n private workingDir: string;\n private botUserId: string | null = null;\n private botUsername: string | null = null;\n private queues = new Map<string, ChannelQueue>();\n private startupTime: number = 0;\n\n constructor(handler: BotHandler, config: { token: string; workingDir: string }) {\n this.handler = handler;\n this.botToken = config.token;\n this.workingDir = config.workingDir;\n this.client = new GrammyBot(config.token);\n this.client.catch((err) => {\n log.logWarning(\"Telegram error\", err instanceof Error ? err.message : String(err));\n });\n }\n\n // ==========================================================================\n // Public API (implements Bot)\n // ==========================================================================\n\n async start(): Promise<void> {\n const me = await this.client.api.getMe();\n this.botUserId = String(me.id);\n this.botUsername = me.username ?? null;\n this.startupTime = Date.now();\n\n await this.client.api.setMyCommands([\n { command: \"login\", description: \"Store credentials in your private vault\" },\n { command: \"session\", description: \"Open the current session in the web viewer\" },\n { command: \"model\", description: \"Switch this conversation's LLM model\" },\n { command: \"stop\", description: \"Stop ongoing conversation\" },\n { command: \"new\", description: \"Reset conversation history and start fresh\" },\n ]);\n\n this.setupEventHandlers();\n\n // Start polling in background (bot.start() runs indefinitely)\n this.client.start().catch((err) => {\n log.logWarning(\"Telegram polling error\", err instanceof Error ? err.message : String(err));\n });\n\n log.logConnected();\n log.logInfo(`Telegram bot started as @${this.botUsername ?? this.botUserId}`);\n }\n\n async postMessage(channel: string, text: string): Promise<string> {\n const result = await this.postMessageRaw(parseInt(channel), text);\n return String(result);\n }\n\n async updateMessage(channel: string, ts: string, text: string): Promise<void> {\n return telegramRetry(async () => {\n try {\n await this.client.api.editMessageText(parseInt(channel), parseInt(ts), text, {\n parse_mode: \"HTML\",\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (msg.includes(\"message is not modified\")) {\n return;\n }\n if (!isTelegramHtmlParseError(msg)) {\n throw err;\n }\n await this.client.api.editMessageText(\n parseInt(channel),\n parseInt(ts),\n escapeTelegramHtml(text),\n {\n parse_mode: \"HTML\",\n },\n );\n }\n });\n }\n\n enqueueEvent(event: BotEvent): boolean {\n const conversationId = event.conversationId;\n const queue = this.getQueue(conversationId);\n if (queue.size() >= 5) {\n log.logWarning(\n `Event queue full for ${conversationId}, discarding: ${event.text.substring(0, 50)}`,\n );\n return false;\n }\n log.logInfo(`Enqueueing event for ${conversationId}: ${event.text.substring(0, 50)}`);\n queue.enqueue(() => {\n const adapters = createTelegramAdapters(event as TelegramEvent, this, true);\n return this.handler.handleEvent(event, this, adapters, true);\n });\n return true;\n }\n\n getPlatformInfo(): PlatformInfo {\n return {\n name: \"telegram\",\n formattingGuide:\n '## Telegram Formatting (HTML mode)\\nBold: <b>text</b>, Italic: <i>text</i>, Code: <code>code</code>, Pre: <pre>code</pre>\\nLinks: <a href=\"url\">text</a>',\n channels: [],\n users: [],\n };\n }\n\n // ==========================================================================\n // Internal helpers (used by context.ts)\n // ==========================================================================\n\n async postMessageRaw(chatId: number, text: string): Promise<number> {\n return telegramRetry(async () => {\n try {\n const result = await this.client.api.sendMessage(chatId, text, { parse_mode: \"HTML\" });\n return result.message_id;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (!isTelegramHtmlParseError(msg)) {\n throw err;\n }\n const result = await this.client.api.sendMessage(chatId, escapeTelegramHtml(text), {\n parse_mode: \"HTML\",\n });\n return result.message_id;\n }\n });\n }\n\n async postPlainMessage(chatId: number, text: string): Promise<void> {\n return telegramRetry(async () => {\n await this.client.api.sendMessage(chatId, text);\n });\n }\n\n async postReply(chatId: number, replyToMessageId: number, text: string): Promise<number> {\n return telegramRetry(async () => {\n try {\n const result = await this.client.api.sendMessage(chatId, text, {\n parse_mode: \"HTML\",\n reply_parameters: { message_id: replyToMessageId },\n });\n return result.message_id;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (!isTelegramHtmlParseError(msg)) {\n throw err;\n }\n const result = await this.client.api.sendMessage(chatId, escapeTelegramHtml(text), {\n parse_mode: \"HTML\",\n reply_parameters: { message_id: replyToMessageId },\n });\n return result.message_id;\n }\n });\n }\n\n async deleteMessageRaw(chatId: number, messageId: number): Promise<void> {\n await this.client.api.deleteMessage(chatId, messageId);\n }\n\n async sendTyping(chatId: number): Promise<void> {\n await this.client.api.sendChatAction(chatId, \"typing\");\n }\n\n async uploadFile(channel: string, filePath: string, title?: string): Promise<void> {\n return telegramRetry(async () => {\n const fileName = title ?? basename(filePath);\n const fileContent = readFileSync(filePath);\n await this.client.api.sendDocument(parseInt(channel), new InputFile(fileContent, fileName));\n });\n }\n\n logToFile(channel: string, entry: object): void {\n appendChannelLog(this.workingDir, channel, entry);\n }\n\n logBotResponse(channel: string, text: string, ts: string): void {\n appendBotResponseLog(this.workingDir, channel, text, ts);\n }\n\n /**\n * Process attachments from a Telegram message\n * Downloads files before returning metadata so the agent can read them immediately\n * Returns format compatible with ChatMessage: { name: string, localPath: string }[]\n */\n async processAttachments(\n chatId: string,\n message: any,\n ): Promise<{ name: string; localPath: string }[]> {\n const downloads: Array<Promise<{ name: string; localPath: string } | null>> = [];\n\n // Handle photos (take the largest size for best quality)\n if (message.photo && message.photo.length > 0) {\n const photos = message.photo;\n const photo = photos[photos.length - 1]; // Largest photo\n const fileId = photo.file_id;\n\n downloads.push(this.processTelegramFile(chatId, fileId, `photo_${message.message_id}.jpg`));\n }\n\n // Handle documents\n if (message.document) {\n const doc = message.document;\n const fileId = doc.file_id;\n const fileName = doc.file_name ?? `document_${message.message_id}`;\n\n downloads.push(this.processTelegramFile(chatId, fileId, fileName));\n }\n\n const attachments = await Promise.all(downloads);\n return attachments.filter(\n (attachment): attachment is { name: string; localPath: string } => attachment !== null,\n );\n }\n\n /**\n * Download a file from Telegram and return attachment metadata\n */\n private async processTelegramFile(\n chatId: string,\n fileId: string,\n originalName: string,\n ): Promise<{ name: string; localPath: string } | null> {\n try {\n // Get file info from Telegram\n const file = await this.client.api.getFile(fileId);\n if (!file.file_path) {\n log.logWarning(\"Telegram file has no path\", fileId);\n return null;\n }\n\n // Generate local filename\n const ts = Date.now();\n const sanitizedName = originalName.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n const filename = `${ts}_${sanitizedName}`;\n const localPath = `${chatId}/attachments/${filename}`;\n const fullDir = join(this.workingDir, chatId, \"attachments\");\n\n if (!existsSync(fullDir)) mkdirSync(fullDir, { recursive: true });\n\n // Construct download URL\n const downloadUrl = `https://api.telegram.org/file/bot${this.botToken}/${file.file_path}`;\n\n // Download the file\n const response = await fetch(downloadUrl);\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n const buffer = await response.arrayBuffer();\n writeFileSync(join(fullDir, filename), Buffer.from(buffer));\n\n return {\n name: originalName,\n localPath: localPath,\n };\n } catch (err) {\n log.logWarning(`Failed to process Telegram file`, `${originalName}: ${err}`);\n return null;\n }\n }\n\n // ==========================================================================\n // Private - Event Handlers\n // ==========================================================================\n\n private getQueue(channelId: string): ChannelQueue {\n let queue = this.queues.get(channelId);\n if (!queue) {\n queue = new ChannelQueue(\"Telegram\");\n this.queues.set(channelId, queue);\n }\n return queue;\n }\n\n private extractMessageContext(msg: any): MessageContext | null {\n if (!msg) return null;\n if (msg.date * 1000 < this.startupTime) return null;\n if (msg.from?.is_bot) return null;\n\n const text = msg.text ?? msg.caption ?? \"\";\n if (!text && !msg.document && !msg.photo) return null;\n\n const chatId = String(msg.chat.id);\n const chatType = msg.chat.type;\n const userId = String(msg.from?.id ?? \"unknown\");\n const userName = msg.from?.username ?? msg.from?.first_name ?? userId;\n const msgId = String(msg.message_id);\n const replyToId = msg.reply_to_message?.message_id;\n const threadTs = replyToId ? String(replyToId) : undefined;\n const conversationKind = chatType === \"private\" ? \"direct\" : \"shared\";\n\n const sessionKey = resolveChatSessionKey({\n conversationId: chatId,\n conversationKind,\n messageId: msgId,\n threadTs,\n });\n\n return {\n msg,\n text,\n chatId,\n chatType,\n conversationKind,\n userId,\n userName,\n msgId,\n threadTs,\n sessionKey,\n };\n }\n\n private isAddressedToBot(text: string, chatType: string): boolean {\n if (chatType === \"private\") return true;\n if (!this.botUsername) return false;\n return text.toLowerCase().includes(`@${this.botUsername.toLowerCase()}`);\n }\n\n private cleanText(text: string): string {\n if (!this.botUsername) return text.trim();\n return text.replace(new RegExp(`@${this.botUsername}`, \"gi\"), \"\").trim();\n }\n\n private isStopText(text: string): boolean {\n return /^\\/?stop(?:@\\w+)?$/i.test(text.trim());\n }\n\n private resolveStopTarget(mc: MessageContext): string | null {\n const directTarget = resolveStopTarget({\n handler: this.handler,\n conversationId: mc.chatId,\n sessionKey: mc.sessionKey,\n });\n if (directTarget) return directTarget;\n return resolveOnlyScopedStopTarget(this.handler, mc.chatId);\n }\n\n private setupEventHandlers(): void {\n // --- Slash commands (registered before catch-all so grammY intercepts them) ---\n\n this.client.command(\"stop\", async (ctx) => {\n const mc = this.extractMessageContext(ctx.message);\n if (!mc) return;\n const stopTarget = this.resolveStopTarget(mc);\n if (stopTarget) {\n await this.handler.handleStop(stopTarget, mc.chatId, this);\n } else {\n await this.postMessage(mc.chatId, formatNothingRunning(\"telegram\"));\n }\n });\n\n this.client.command(\"new\", async (ctx) => {\n const mc = this.extractMessageContext(ctx.message);\n if (!mc) return;\n await this.handler.handleNew(mc.sessionKey, mc.chatId, this);\n });\n\n // --- Catch-all for regular (non-command) messages ---\n\n this.client.on(\"message\", async (ctx) => {\n const mc = this.extractMessageContext(ctx.message);\n if (!mc) return;\n\n const cleanedText = this.cleanText(mc.text);\n const addressedToBot = this.isAddressedToBot(mc.text, mc.chatType);\n\n if (this.isStopText(cleanedText)) {\n this.logToFile(mc.chatId, {\n date: new Date(mc.msg.date * 1000).toISOString(),\n ts: mc.msgId,\n user: mc.userId,\n userName: mc.userName,\n text: cleanedText,\n attachments: [],\n isBot: false,\n });\n\n const stopTarget = this.resolveStopTarget(mc);\n if (stopTarget) {\n await this.handler.handleStop(stopTarget, mc.chatId, this);\n } else if (addressedToBot || mc.chatType === \"private\") {\n await this.postMessage(mc.chatId, formatNothingRunning(\"telegram\"));\n }\n return;\n }\n\n // In groups, only respond when addressed to bot\n if (!addressedToBot) return;\n\n // Process attachments\n const processedAttachments = await this.processAttachments(mc.chatId, mc.msg);\n\n const event: TelegramEvent = {\n type: \"message\",\n conversationId: mc.chatId,\n conversationKind: mc.conversationKind,\n ts: mc.msgId,\n thread_ts: mc.threadTs,\n sessionKey: mc.sessionKey,\n user: mc.userId,\n userName: mc.userName,\n text: cleanedText,\n attachments: processedAttachments,\n };\n\n // Log the message\n this.logToFile(mc.chatId, {\n date: new Date(mc.msg.date * 1000).toISOString(),\n ts: mc.msgId,\n ...(mc.conversationKind === \"shared\" && mc.threadTs ? { threadTs: mc.threadTs } : {}),\n user: mc.userId,\n userName: mc.userName,\n text: cleanedText,\n attachments: processedAttachments,\n isBot: false,\n });\n\n if (this.handler.isRunning(mc.sessionKey)) {\n await this.postMessage(mc.chatId, formatAlreadyWorking(\"telegram\", \"/stop\"));\n } else {\n this.getQueue(mc.sessionKey).enqueue(() => {\n const adapters = createTelegramAdapters(event, this, false);\n return this.handler.handleEvent(event, this, adapters, false);\n });\n }\n });\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EACV,WAAW,EACX,mBAAmB,EAGnB,YAAY,EACb,MAAM,cAAc,CAAC;AAKtB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAiC,KAAK,aAAa,EAAE,MAAM,cAAc,CAAC;AAEjF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAIL,KAAK,oBAAoB,EAE1B,MAAM,oBAAoB,CAAC;AAI5B,MAAM,WAAW,WAAW;IAC1B,GAAG,CACD,OAAO,EAAE,WAAW,EACpB,WAAW,EAAE,mBAAmB,EAChC,QAAQ,EAAE,YAAY,GACrB,OAAO,CAAC;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC1D,KAAK,IAAI,IAAI,CAAC;IACd,6DAA6D;IAC7D,cAAc,IAAI;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;CACrE;AAgXD;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,aAAa,EAAE,aAAa,EAC5B,UAAU,EAAE,MAAM,EAClB,cAAc,EAAE,MAAM,EACtB,eAAe,EAAE,MAAM,EACvB,YAAY,EAAE,MAAM,EACpB,YAAY,EAAE,oBAAoB,EAClC,YAAY,CAAC,EAAE,YAAY,EAC3B,YAAY,CAAC,EAAE,gBAAgB,EAC/B,WAAW,CAAC,EAAE,sBAAsB,GACnC,OAAO,CAAC,WAAW,CAAC,CA0sBtB","sourcesContent":["import { Agent, type AgentEvent } from \"@mariozechner/pi-agent-core\";\nimport { getModel, type ImageContent } from \"@mariozechner/pi-ai\";\nimport {\n AgentSession,\n AuthStorage,\n convertToLlm,\n DefaultResourceLoader,\n formatSkillsForPrompt,\n getAgentDir,\n loadSkillsFromDir,\n ModelRegistry,\n type Skill,\n} from \"@mariozechner/pi-coding-agent\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { mkdir, readFile, writeFile } from \"fs/promises\";\nimport { homedir } from \"os\";\nimport { join } from \"path\";\nimport type {\n ChatMessage,\n ChatResponseContext,\n ChatToolResult,\n ConversationKind,\n PlatformInfo,\n} from \"./adapter.js\";\nimport { loadAgentConfig } from \"./config.js\";\nimport { createMamaSettingsManager, syncLogToSessionManager } from \"./context.js\";\nimport { ActorExecutionResolver } from \"./execution-resolver.js\";\nimport * as log from \"./log.js\";\nimport type { UserBindingStore } from \"./bindings.js\";\nimport type { DockerContainerManager } from \"./provisioner.js\";\nimport { createExecutor, type Executor, type SandboxConfig } from \"./sandbox.js\";\nimport { addLifecycleBreadcrumb, metricAttributes } from \"./sentry.js\";\nimport type { VaultManager } from \"./vault.js\";\nimport {\n extractSessionSuffix,\n extractSessionUuid,\n openManagedSession,\n type ResolvedSessionScope,\n type ThreadRootMessage,\n} from \"./session-store.js\";\nimport { createMamaTools } from \"./tools/index.js\";\nimport * as Sentry from \"@sentry/node\";\n\nexport interface AgentRunner {\n run(\n message: ChatMessage,\n responseCtx: ChatResponseContext,\n platform: PlatformInfo,\n ): Promise<{ stopReason: string; errorMessage?: string }>;\n abort(): void;\n /** Get current step info (tool name, label) for debugging */\n getCurrentStep(): { toolName?: string; label?: string } | undefined;\n}\n\nconst IMAGE_MIME_TYPES: Record<string, string> = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n gif: \"image/gif\",\n webp: \"image/webp\",\n};\n\nfunction getImageMimeType(filename: string): string | undefined {\n return IMAGE_MIME_TYPES[filename.toLowerCase().split(\".\").pop() || \"\"];\n}\n\nfunction buildThreadSessionName(message: ThreadRootMessage | null): string | undefined {\n const text = message?.text?.trim();\n if (!text) return undefined;\n const userLabel = message?.userName || message?.user || \"unknown\";\n return `[${userLabel}]: ${text}`;\n}\n\nasync function getMemory(conversationDir: string): Promise<string> {\n const parts: string[] = [];\n\n // Read workspace-level memory (shared across all conversations)\n const workspaceMemoryPath = join(conversationDir, \"..\", \"MEMORY.md\");\n if (existsSync(workspaceMemoryPath)) {\n try {\n const content = (await readFile(workspaceMemoryPath, \"utf-8\")).trim();\n if (content) {\n parts.push(`### Global Workspace Memory\\n${content}`);\n }\n } catch (error) {\n log.logWarning(\"Failed to read workspace memory\", `${workspaceMemoryPath}: ${error}`);\n }\n }\n\n // Read conversation-specific memory\n const conversationMemoryPath = join(conversationDir, \"MEMORY.md\");\n if (existsSync(conversationMemoryPath)) {\n try {\n const content = (await readFile(conversationMemoryPath, \"utf-8\")).trim();\n if (content) {\n parts.push(`### Conversation-Specific Memory\\n${content}`);\n }\n } catch (error) {\n log.logWarning(\"Failed to read conversation memory\", `${conversationMemoryPath}: ${error}`);\n }\n }\n\n if (parts.length === 0) {\n return \"(no working memory yet)\";\n }\n\n return parts.join(\"\\n\\n\");\n}\n\nfunction loadMamaSkills(conversationDir: string, workspacePath: string): Skill[] {\n const skillMap = new Map<string, Skill>();\n\n // conversationDir is the host path (e.g., /Users/.../data/C0A34FL8PMH)\n // hostWorkspacePath is the parent directory on host\n // workspacePath is the container path (e.g., /workspace)\n const hostWorkspacePath = join(conversationDir, \"..\");\n\n // Helper to translate host paths to container paths\n const translatePath = (hostPath: string): string => {\n if (hostPath.startsWith(hostWorkspacePath)) {\n return workspacePath + hostPath.slice(hostWorkspacePath.length);\n }\n return hostPath;\n };\n\n // Load workspace-level skills (global)\n const workspaceSkillsDir = join(hostWorkspacePath, \"skills\");\n for (const skill of loadSkillsFromDir({ dir: workspaceSkillsDir, source: \"workspace\" }).skills) {\n // Translate paths to container paths for system prompt\n skill.filePath = translatePath(skill.filePath);\n skill.baseDir = translatePath(skill.baseDir);\n skillMap.set(skill.name, skill);\n }\n\n // Load conversation-specific skills (override workspace skills on collision)\n const conversationSkillsDir = join(conversationDir, \"skills\");\n for (const skill of loadSkillsFromDir({ dir: conversationSkillsDir, source: \"channel\" }).skills) {\n skill.filePath = translatePath(skill.filePath);\n skill.baseDir = translatePath(skill.baseDir);\n skillMap.set(skill.name, skill);\n }\n\n return Array.from(skillMap.values());\n}\n\nfunction buildSystemPrompt(\n workspacePath: string,\n conversationId: string,\n conversationKind: ConversationKind,\n currentUserId: string | undefined,\n memory: string,\n sandboxConfig: SandboxConfig,\n platform: PlatformInfo,\n skills: Skill[],\n): string {\n const conversationPath = `${workspacePath}/${conversationId}`;\n const isContainer = sandboxConfig.type === \"container\" || sandboxConfig.type === \"image\";\n const isImageSandbox = sandboxConfig.type === \"image\";\n const isFirecracker = sandboxConfig.type === \"firecracker\";\n const isCloudflareSandbox = sandboxConfig.type === \"cloudflare\";\n\n // Format channel mappings\n const channelMappings =\n platform.channels.length > 0\n ? platform.channels.map((c) => `${c.id}\\t#${c.name}`).join(\"\\n\")\n : \"(no channels loaded)\";\n\n // Format user mappings\n const userMappings =\n platform.users.length > 0\n ? platform.users.map((u) => `${u.id}\\t@${u.userName}\\t${u.displayName}`).join(\"\\n\")\n : \"(no users loaded)\";\n\n const envDescription = isImageSandbox\n ? `You are running inside a managed per-user container.\n- Bash working directory: / (use cd or absolute paths)\n- Install tools with the image's package manager\n- Your changes persist for this user's container until it is recreated`\n : isContainer\n ? `You are running inside a shared container.\n- Bash working directory: / (use cd or absolute paths)\n- Install tools with the container's package manager\n- Your changes persist across sessions`\n : isFirecracker\n ? `You are running inside a Firecracker microVM.\n- Bash working directory: / (use cd or absolute paths)\n- Install tools with: apt-get install <package> (Debian-based)\n- Your changes persist across sessions`\n : isCloudflareSandbox\n ? `You are running through a Cloudflare Sandbox bridge.\n- Bash working directory: /workspace\n- Your commands run in a remote container managed by Cloudflare\n- Important: the remote filesystem is not automatically synced back to the host workspace`\n : `You are running directly on the host machine.\n- Bash working directory: ${process.cwd()}\n- Be careful with system modifications`;\n\n return `You are mama, a ${platform.name} bot assistant. Be concise. No emojis.\n\n## Context\n- For current date/time, use: date\n- You have access to previous conversation context including tool results from prior turns.\n- For older human-readable history beyond your context, search \\`log.jsonl\\` (contains user messages and your final responses, but not tool results).\n- Structured session history with tool results lives in \\`${conversationPath}/sessions/\\`.\n- The active top-level session is selected by \\`${conversationPath}/sessions/current\\`, which points to a timestamped \\`.jsonl\\` file in the same directory.\n- Scoped/thread sessions use fixed files at \\`${conversationPath}/sessions/<scope_id>.jsonl\\` (for example \\`${conversationPath}/sessions/1777386320.800769.jsonl\\`).\n- User messages include a \\`[in-thread:TS]\\` marker when sent from within a platform thread/reply (TS is the thread or parent message identifier). Without this marker, the message is a top-level conversation message.\n\n${platform.formattingGuide}\n\n## Platform IDs\nChannels: ${channelMappings}\n\nUsers: ${userMappings}\n\nWhen mentioning users, use <@username> format (e.g., <@mario>).\n\n## Environment\n${envDescription}\n\n## Workspace Layout\n${workspacePath}/\n├── MEMORY.md # Global memory (all conversations)\n├── skills/ # Global CLI tools you create\n└── ${conversationId}/ # This conversation\n ├── MEMORY.md # Conversation-specific memory\n ├── log.jsonl # Human-readable message history (no tool results)\n ├── sessions/ # Structured session history used for context reconstruction\n │ ├── current # Active top-level session pointer\n │ ├── <timestamp>_<id>.jsonl # Top-level session files\n │ └── <scope_id>.jsonl # Scoped thread/reply session files\n ├── attachments/ # User-shared files\n ├── scratch/ # Your working directory\n └── skills/ # Conversation-specific tools\n\n## Skills (Custom CLI Tools)\nYou can create reusable CLI tools for recurring tasks (email, APIs, data processing, etc.).\n\n### Creating Skills\nStore in \\`${workspacePath}/skills/<name>/\\` (global) or \\`${conversationPath}/skills/<name>/\\` (conversation-specific).\nEach skill directory needs a \\`SKILL.md\\` with YAML frontmatter:\n\n\\`\\`\\`markdown\n---\nname: skill-name\ndescription: Short description of what this skill does\n---\n\n# Skill Name\n\nUsage instructions, examples, etc.\nScripts are in: {baseDir}/\n\\`\\`\\`\n\n\\`name\\` and \\`description\\` are required. Use \\`{baseDir}\\` as placeholder for the skill's directory path.\n\n### Available Skills\n${skills.length > 0 ? formatSkillsForPrompt(skills) : \"(no skills installed yet)\"}\n\n## Events\nYou can schedule events that wake you up at specific times or when external things happen. Events are JSON files in \\`${workspacePath}/events/\\`.\n\n### Event Types\n\n**Immediate** - Triggers as soon as harness sees the file. Use in scripts/webhooks to signal external events.\n\\`\\`\\`json\n{\"type\": \"immediate\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"New GitHub issue opened\"}\n\\`\\`\\`\n\n**One-shot** - Triggers once at a specific time. Use for reminders.\n\\`\\`\\`json\n{\"type\": \"one-shot\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"Remind Mario about dentist\", \"at\": \"2025-12-15T09:00:00+01:00\"}\n\\`\\`\\`\n\n**Periodic** - Triggers on a cron schedule. Use for recurring tasks.\n\\`\\`\\`json\n{\"type\": \"periodic\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"Check inbox and summarize\", \"schedule\": \"0 9 * * 1-5\", \"timezone\": \"${Intl.DateTimeFormat().resolvedOptions().timeZone}\"}\n\\`\\`\\`\n\n### Cron Format\n\\`minute hour day-of-month month day-of-week\\`\n- \\`0 9 * * *\\` = daily at 9:00\n- \\`0 9 * * 1-5\\` = weekdays at 9:00\n- \\`30 14 * * 1\\` = Mondays at 14:30\n- \\`0 0 1 * *\\` = first of each month at midnight\n\n### Timezones\nAll \\`at\\` timestamps must include offset (e.g., \\`+01:00\\`). Periodic events use IANA timezone names. The harness runs in ${Intl.DateTimeFormat().resolvedOptions().timeZone}. When users mention times without timezone, assume ${Intl.DateTimeFormat().resolvedOptions().timeZone}.\n\n### Platform and Credential Routing\nSet \\`platform\\` to the target bot platform (\\`${platform.name}\\` for this conversation). Include it explicitly to avoid ambiguity.\n\nSet \\`userId\\` to the platform userId of whoever asked for the event. When the event fires, tool execution routes using that user's vault selection in per-user modes. In \\`container:<name>\\`, events use the container's single shared vault.\n\nPrefer the \\`event\\` tool over manually writing JSON files; it fills \\`platform\\`, \\`conversationId\\`, \\`conversationKind\\`, and \\`userId\\` for the current conversation automatically.\n\n### Creating Events\nUse unique filenames to avoid overwriting existing events. Include a timestamp or random suffix:\n\\`\\`\\`bash\ncat > ${workspacePath}/events/dentist-reminder-$(date +%s).json << 'EOF'\n{\"type\": \"one-shot\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"Dentist tomorrow\", \"at\": \"2025-12-14T09:00:00+01:00\"}\nEOF\n\\`\\`\\`\nOr check if file exists first before creating.\n\n### Managing Events\n- List: \\`ls ${workspacePath}/events/\\`\n- View: \\`cat ${workspacePath}/events/foo.json\\`\n- Delete/cancel: \\`rm ${workspacePath}/events/foo.json\\`\n\n### When Events Trigger\nYou receive a message like:\n\\`\\`\\`\n[EVENT:dentist-reminder.json:one-shot:2025-12-14T09:00:00+01:00] Dentist tomorrow\n\\`\\`\\`\nImmediate and one-shot events auto-delete after triggering. Periodic events persist until you delete them.\n\n### Silent Completion\nFor periodic events where there's nothing to report, respond with just \\`[SILENT]\\` (no other text). This deletes the status message and posts nothing to the platform. Use this to avoid spamming the channel when periodic checks find nothing actionable.\n\n### Debouncing\nWhen writing programs that create immediate events (email watchers, webhook handlers, etc.), always debounce. If 50 emails arrive in a minute, don't create 50 immediate events. Instead collect events over a window and create ONE immediate event summarizing what happened, or just signal \"new activity, check inbox\" rather than per-item events. Or simpler: use a periodic event to check for new items every N minutes instead of immediate events.\n\n### Limits\nMaximum 5 events can be queued. Don't create excessive immediate or periodic events.\n\n## Memory\nWrite to MEMORY.md files to persist context across conversations.\n- Global (${workspacePath}/MEMORY.md): skills, preferences, project info\n- Conversation (${conversationPath}/MEMORY.md): conversation-specific decisions, ongoing work\nUpdate when you learn something important or when asked to remember something.\n\n### Current Memory\n${memory}\n\n## System Configuration Log\nMaintain ${workspacePath}/SYSTEM.md to log all environment modifications:\n- Installed packages (apt install, npm install, uv pip install)\n- Environment variables set\n- Config files modified (~/.gitconfig, cron jobs, etc.)\n- Skill dependencies installed\n\nUpdate this file whenever you modify the environment. On fresh container, read it first to restore your setup.\n\n## Log Queries (for older history)\nFormat: \\`{\"date\":\"...\",\"ts\":\"...\",\"user\":\"...\",\"userName\":\"...\",\"text\":\"...\",\"isBot\":false}\\`\nThe log contains user messages and your final responses (not tool calls/results).\nUse \\`log.jsonl\\` for quick grep-style history. Use \\`${conversationPath}/sessions/\\` when you need structured turns, tool outputs, or branch lineage.\n${isContainer ? \"Install jq: apt-get install jq\" : \"\"}\n${isFirecracker ? \"Install jq: apt-get install jq\" : \"\"}\n\n\\`\\`\\`bash\n# Recent messages\ntail -30 log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'\n\n# Search for specific topic\ngrep -i \"topic\" log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'\n\n# Messages from specific user\ngrep '\"userName\":\"mario\"' log.jsonl | tail -20 | jq -c '{date: .date[0:19], text}'\n\n# Inspect top-level session pointer and available session files\ncat sessions/current\nls -1 sessions/\n\\`\\`\\`\n\n## Tools\n- bash: Run shell commands (primary tool). Install packages as needed.\n- read: Read files\n- write: Create/overwrite files\n- edit: Surgical file edits\n- attach: Share files to the platform\n\nEach tool requires a \"label\" parameter (shown to user).\n`;\n}\n\nfunction truncate(text: string, maxLen: number): string {\n if (text.length <= maxLen) return text;\n return `${text.substring(0, maxLen - 3)}...`;\n}\n\n// Tools whose output is interesting in the structured session log but too noisy\n// to surface as a per-tool diagnostic to the user.\nconst QUIET_TOOLS = new Set([\"read\", \"write\", \"edit\"]);\n\n// Cap raw tool output before handing it to adapters. Bash output can be MB; without\n// this each adapter's splitter would fan it out into many sequential platform posts.\nconst TOOL_RESULT_DIAGNOSTIC_CAP = 8000;\n\nfunction extractToolResultText(result: unknown): string {\n if (typeof result === \"string\") {\n return result;\n }\n\n if (\n result &&\n typeof result === \"object\" &&\n \"content\" in result &&\n Array.isArray((result as { content: unknown }).content)\n ) {\n const content = (result as { content: Array<{ type: string; text?: string }> }).content;\n const textParts: string[] = [];\n for (const part of content) {\n if (part.type === \"text\" && part.text) {\n textParts.push(part.text);\n }\n }\n if (textParts.length > 0) {\n return textParts.join(\"\\n\");\n }\n }\n\n return JSON.stringify(result);\n}\n\n// ============================================================================\n// Agent runner\n// ============================================================================\n\n/**\n * Create a new AgentRunner for a channel.\n * Sets up the session and subscribes to events once.\n *\n * Runner caching is handled by the caller (channelStates in main.ts).\n * This is a stateless factory function.\n */\nexport async function createRunner(\n sandboxConfig: SandboxConfig,\n sessionKey: string,\n conversationId: string,\n conversationDir: string,\n workspaceDir: string,\n sessionScope: ResolvedSessionScope,\n vaultManager?: VaultManager,\n bindingStore?: UserBindingStore,\n provisioner?: DockerContainerManager,\n): Promise<AgentRunner> {\n const agentConfig = loadAgentConfig();\n\n // Initialize logger with settings from config\n log.initLogger({\n logFormat: agentConfig.logFormat,\n logLevel: agentConfig.logLevel,\n });\n\n const executionResolver =\n vaultManager &&\n sandboxConfig.type !== \"host\" &&\n (vaultManager.isEnabled() ||\n sandboxConfig.type === \"container\" ||\n sandboxConfig.type === \"image\" ||\n sandboxConfig.type === \"cloudflare\" ||\n sandboxConfig.type === \"firecracker\")\n ? new ActorExecutionResolver(sandboxConfig, vaultManager, provisioner, workspaceDir)\n : undefined;\n // activeExecutor is replaced at the start of each run() call when executionResolver\n // is present, so the stable `executor` wrapper always delegates to the latest resolved value.\n let activeExecutor: Executor =\n executionResolver !== undefined\n ? createExecutor({ type: \"host\" })\n : createExecutor(sandboxConfig);\n const executor: Executor = {\n exec(command, options) {\n return activeExecutor.exec(command, options);\n },\n getWorkspacePath(hostPath) {\n return activeExecutor.getWorkspacePath(hostPath);\n },\n getSandboxConfig() {\n return activeExecutor.getSandboxConfig();\n },\n };\n const workspaceBase = conversationDir.replace(`/${conversationId}`, \"\");\n const getWorkspacePath = () => executor.getWorkspacePath(workspaceBase);\n let workspacePath = getWorkspacePath();\n\n // Create tools (per-runner, with per-runner upload function setter)\n const { tools, setUploadFunction, setEventContext } = createMamaTools(executor, workspaceDir);\n\n // Resolve model from config\n // Use 'as any' cast because agentConfig.provider/model are plain strings,\n // while getModel() has constrained generic types for known providers.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const model = (getModel as any)(agentConfig.provider, agentConfig.model);\n\n // Initial system prompt (will be updated each run with fresh memory/channels/users/skills)\n const memory = await getMemory(conversationDir);\n const skills = loadMamaSkills(conversationDir, workspacePath);\n const emptyPlatform: PlatformInfo = {\n name: \"chat\",\n formattingGuide: \"\",\n channels: [],\n users: [],\n };\n const systemPrompt = buildSystemPrompt(\n workspacePath,\n conversationId,\n \"shared\",\n undefined,\n memory,\n sandboxConfig,\n emptyPlatform,\n skills,\n );\n\n // Create session manager and settings manager. Top-level/private sessions\n // use the conversation's current pointer; scoped sessions use fixed files.\n // Platform-specific branch/fork behavior is resolved before runner creation.\n const isThread = sessionKey.includes(\":\");\n const rootTs = extractSessionSuffix(sessionKey);\n const { sessionDir, contextFile, threadRootMessage } = sessionScope;\n const sessionManager = openManagedSession(contextFile, sessionDir, conversationDir);\n const threadSessionName = buildThreadSessionName(threadRootMessage);\n if (isThread && threadSessionName && sessionManager.getSessionName() !== threadSessionName) {\n sessionManager.appendSessionInfo(threadSessionName);\n }\n\n const sessionUuid = extractSessionUuid(contextFile);\n const settingsManager = createMamaSettingsManager(join(conversationDir, \"..\"));\n\n // Create AuthStorage and ModelRegistry\n // Auth stored outside workspace so agent can't access it\n const authStorage = AuthStorage.create(join(homedir(), \".pi\", \"mama\", \"auth.json\"));\n const modelRegistry = ModelRegistry.create(authStorage);\n\n // Create agent\n const agent = new Agent({\n initialState: {\n systemPrompt,\n model,\n thinkingLevel:\n (agentConfig.thinkingLevel as \"off\" | \"low\" | \"medium\" | \"high\" | undefined) ?? \"off\",\n tools,\n },\n convertToLlm,\n getApiKey: async () => {\n const key = await modelRegistry.getApiKeyForProvider(model.provider);\n if (!key)\n throw new Error(\n `No API key for provider \"${model.provider}\". Set the appropriate environment variable or configure via auth.json`,\n );\n return key;\n },\n });\n\n // Load existing messages\n const loadedSession = sessionManager.buildSessionContext();\n if (loadedSession.messages.length > 0) {\n agent.state.messages = loadedSession.messages;\n log.logInfo(\n `[${conversationId}] Loaded ${loadedSession.messages.length} messages from context.jsonl`,\n );\n }\n\n // Load extensions, skills, prompts, themes via DefaultResourceLoader\n // This reads ~/.pi/agent/settings.json (packages, extensions enable/disable)\n // and discovers resources from standard locations + npm/git packages.\n const resourceLoader = new DefaultResourceLoader({\n cwd: workspaceDir,\n agentDir: getAgentDir(),\n systemPrompt,\n });\n try {\n await resourceLoader.reload();\n const extResult = resourceLoader.getExtensions();\n if (extResult.errors.length > 0) {\n for (const err of extResult.errors) {\n log.logWarning(`[${conversationId}] Extension load error: ${err.path}`, err.error);\n }\n }\n log.logInfo(\n `[${conversationId}] Loaded ${extResult.extensions.length} extension(s): ${extResult.extensions.map((e) => e.path).join(\", \")}`,\n );\n } catch (error) {\n log.logWarning(`[${conversationId}] Failed to load resources`, String(error));\n }\n\n const baseToolsOverride = Object.fromEntries(tools.map((tool) => [tool.name, tool]));\n\n // Create AgentSession wrapper\n const session = new AgentSession({\n agent,\n sessionManager,\n settingsManager,\n cwd: workspaceDir,\n modelRegistry,\n resourceLoader,\n baseToolsOverride,\n });\n\n // Mutable per-run state - event handler references this\n const runState = {\n responseCtx: null as ChatResponseContext | null,\n logCtx: null as {\n conversationId: string;\n userName?: string;\n conversationName?: string;\n sessionId?: string;\n } | null,\n queue: null as {\n enqueue(fn: () => Promise<void>, errorContext: string): void;\n } | null,\n pendingTools: new Map<string, { toolName: string; args: unknown; startTime: number }>(),\n totalUsage: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n },\n llmCallCount: 0,\n stopReason: \"stop\",\n errorMessage: undefined as string | undefined,\n };\n\n // Subscribe to events ONCE\n session.subscribe(async (event) => {\n // Skip if no active run\n if (!runState.responseCtx || !runState.logCtx || !runState.queue) return;\n\n const { responseCtx, logCtx, queue, pendingTools } = runState;\n const baseAttrs = { channel_id: logCtx.conversationId, session_id: logCtx.sessionId };\n\n if (event.type === \"tool_execution_start\") {\n const agentEvent = event as AgentEvent & { type: \"tool_execution_start\" };\n const args = agentEvent.args as { label?: string };\n const label = args.label || agentEvent.toolName;\n\n pendingTools.set(agentEvent.toolCallId, {\n toolName: agentEvent.toolName,\n args: agentEvent.args,\n startTime: Date.now(),\n });\n addLifecycleBreadcrumb(\"agent.tool.started\", {\n tool: agentEvent.toolName,\n ...baseAttrs,\n });\n\n log.logToolStart(\n logCtx,\n agentEvent.toolName,\n label,\n agentEvent.args as Record<string, unknown>,\n );\n } else if (event.type === \"tool_execution_end\") {\n const agentEvent = event as AgentEvent & { type: \"tool_execution_end\" };\n const resultStr = extractToolResultText(agentEvent.result);\n const pending = pendingTools.get(agentEvent.toolCallId);\n pendingTools.delete(agentEvent.toolCallId);\n\n const durationMs = pending ? Date.now() - pending.startTime : 0;\n\n Sentry.metrics.count(\"agent.tool.calls\", 1, {\n attributes: metricAttributes({\n tool: agentEvent.toolName,\n error: String(agentEvent.isError),\n ...baseAttrs,\n }),\n });\n Sentry.metrics.distribution(\"agent.tool.duration\", durationMs, {\n unit: \"millisecond\",\n attributes: metricAttributes({\n tool: agentEvent.toolName,\n ...baseAttrs,\n }),\n });\n addLifecycleBreadcrumb(\"agent.tool.completed\", {\n tool: agentEvent.toolName,\n error: agentEvent.isError,\n duration_ms: durationMs,\n ...baseAttrs,\n });\n\n if (agentEvent.isError) {\n log.logToolError(logCtx, agentEvent.toolName, durationMs, resultStr);\n } else {\n log.logToolSuccess(logCtx, agentEvent.toolName, durationMs, resultStr);\n }\n\n if (!QUIET_TOOLS.has(agentEvent.toolName)) {\n const toolResult: ChatToolResult = {\n toolName: agentEvent.toolName,\n label: pending?.args ? (pending.args as { label?: string }).label : undefined,\n args: pending?.args as Record<string, unknown> | undefined,\n result: truncate(resultStr, TOOL_RESULT_DIAGNOSTIC_CAP),\n isError: agentEvent.isError,\n durationMs,\n };\n queue.enqueue(() => responseCtx.respondToolResult(toolResult), \"tool result diagnostic\");\n }\n\n if (agentEvent.isError) {\n queue.enqueue(\n () => responseCtx.respond(`_Error: ${truncate(resultStr, 200)}_`),\n \"tool error\",\n );\n }\n } else if (event.type === \"message_start\") {\n const agentEvent = event as AgentEvent & { type: \"message_start\" };\n if (agentEvent.message.role === \"assistant\") {\n runState.llmCallCount += 1;\n addLifecycleBreadcrumb(\"agent.llm.call.started\", {\n call_index: runState.llmCallCount,\n provider: model.provider,\n model: agentConfig.model,\n ...baseAttrs,\n });\n log.logResponseStart(logCtx);\n }\n } else if (event.type === \"message_end\") {\n const agentEvent = event as AgentEvent & { type: \"message_end\" };\n if (agentEvent.message.role === \"assistant\") {\n const assistantMsg = agentEvent.message as any;\n\n if (assistantMsg.stopReason) {\n runState.stopReason = assistantMsg.stopReason;\n }\n if (assistantMsg.errorMessage) {\n runState.errorMessage = assistantMsg.errorMessage;\n }\n\n if (assistantMsg.usage) {\n runState.totalUsage.input += assistantMsg.usage.input;\n runState.totalUsage.output += assistantMsg.usage.output;\n runState.totalUsage.cacheRead += assistantMsg.usage.cacheRead;\n runState.totalUsage.cacheWrite += assistantMsg.usage.cacheWrite;\n runState.totalUsage.cost.input += assistantMsg.usage.cost.input;\n runState.totalUsage.cost.output += assistantMsg.usage.cost.output;\n runState.totalUsage.cost.cacheRead += assistantMsg.usage.cost.cacheRead;\n runState.totalUsage.cost.cacheWrite += assistantMsg.usage.cost.cacheWrite;\n runState.totalUsage.cost.total += assistantMsg.usage.cost.total;\n\n // Per-turn LLM metrics\n const llmAttributes = metricAttributes({\n provider: model.provider,\n model: agentConfig.model,\n ...baseAttrs,\n stop_reason: assistantMsg.stopReason,\n error: Boolean(assistantMsg.errorMessage),\n });\n Sentry.metrics.count(\"agent.llm.calls\", 1, { attributes: llmAttributes });\n Sentry.metrics.distribution(\"agent.llm.tokens_in\", assistantMsg.usage.input, {\n attributes: llmAttributes,\n });\n Sentry.metrics.distribution(\"agent.llm.tokens_out\", assistantMsg.usage.output, {\n attributes: llmAttributes,\n });\n if (assistantMsg.usage.cacheRead > 0) {\n Sentry.metrics.distribution(\"agent.llm.cache_read\", assistantMsg.usage.cacheRead, {\n attributes: llmAttributes,\n });\n }\n if (assistantMsg.usage.cacheWrite > 0) {\n Sentry.metrics.distribution(\"agent.llm.cache_write\", assistantMsg.usage.cacheWrite, {\n attributes: llmAttributes,\n });\n }\n Sentry.metrics.distribution(\"agent.llm.cost_per_turn\", assistantMsg.usage.cost.total, {\n attributes: llmAttributes,\n });\n addLifecycleBreadcrumb(\"agent.llm.call.completed\", {\n call_index: runState.llmCallCount,\n provider: model.provider,\n model: agentConfig.model,\n stop_reason: assistantMsg.stopReason,\n error: Boolean(assistantMsg.errorMessage),\n input_tokens: assistantMsg.usage.input,\n output_tokens: assistantMsg.usage.output,\n cost_total_usd: assistantMsg.usage.cost.total,\n });\n }\n\n const content = agentEvent.message.content;\n const thinkingParts: string[] = [];\n const textParts: string[] = [];\n for (const part of content) {\n if (part.type === \"thinking\") {\n thinkingParts.push((part as any).thinking);\n } else if (part.type === \"text\") {\n textParts.push((part as any).text);\n }\n }\n\n const text = textParts.join(\"\\n\");\n\n for (const thinking of thinkingParts) {\n log.logThinking(logCtx, thinking);\n queue.enqueue(() => responseCtx.respond(`_${thinking}_`), \"thinking main\");\n queue.enqueue(\n () => responseCtx.respondDiagnostic(`_${thinking}_`),\n \"thinking diagnostic\",\n );\n }\n\n if (text.trim()) {\n log.logResponse(logCtx, text);\n queue.enqueue(() => responseCtx.respond(text), \"response main\");\n }\n }\n } else if (event.type === \"compaction_start\") {\n log.logInfo(`Auto-compaction started (reason: ${(event as any).reason})`);\n queue.enqueue(() => responseCtx.respond(\"_Compacting context..._\"), \"compaction start\");\n } else if (event.type === \"compaction_end\") {\n const compEvent = event as any;\n if (compEvent.result) {\n log.logInfo(`Auto-compaction complete: ${compEvent.result.tokensBefore} tokens compacted`);\n } else if (compEvent.aborted) {\n log.logInfo(\"Auto-compaction aborted\");\n }\n } else if (event.type === \"auto_retry_start\") {\n const retryEvent = event as any;\n log.logWarning(\n `Retrying (${retryEvent.attempt}/${retryEvent.maxAttempts})`,\n retryEvent.errorMessage,\n );\n queue.enqueue(\n () =>\n responseCtx.respond(`_Retrying (${retryEvent.attempt}/${retryEvent.maxAttempts})..._`),\n \"retry\",\n );\n }\n });\n\n return {\n async run(\n message: ChatMessage,\n responseCtx: ChatResponseContext,\n platform: PlatformInfo,\n ): Promise<{ stopReason: string; errorMessage?: string }> {\n // Extract conversationId from sessionKey (format: \"conversationId:rootTs\" or just \"conversationId\")\n const sessionConversation = message.sessionKey.split(\":\")[0];\n\n // Ensure conversation directory exists\n await mkdir(conversationDir, { recursive: true });\n\n if (executionResolver) {\n executionResolver.refresh();\n activeExecutor = await executionResolver.resolve({\n platform: platform.name,\n userId: message.userId,\n conversationId,\n });\n workspacePath = getWorkspacePath();\n }\n\n // Sync messages from log.jsonl that arrived while we were offline or busy\n // Exclude the current message (it will be added via prompt())\n // Default sync range is 10 days (handled by syncLogToSessionManager)\n // Thread filter ensures only messages from this session's thread are synced\n const threadFilter = message.sessionKey.includes(\":\")\n ? { scope: \"thread\" as const, rootTs, threadTs: message.threadTs }\n : { scope: \"top-level\" as const, rootTs };\n const syncedCount = await syncLogToSessionManager(\n sessionManager,\n conversationDir,\n message.id,\n undefined,\n threadFilter,\n );\n if (syncedCount > 0) {\n log.logInfo(`[${conversationId}] Synced ${syncedCount} messages from log.jsonl`);\n }\n\n // Reload messages from context.jsonl\n // This picks up any messages synced above\n const reloadedSession = sessionManager.buildSessionContext();\n if (reloadedSession.messages.length > 0) {\n agent.state.messages = reloadedSession.messages;\n log.logInfo(\n `[${conversationId}] Reloaded ${reloadedSession.messages.length} messages from context`,\n );\n }\n\n // Update system prompt with fresh memory, channel/user info, and skills\n const memory = await getMemory(conversationDir);\n const skills = loadMamaSkills(conversationDir, workspacePath);\n const systemPrompt = buildSystemPrompt(\n workspacePath,\n conversationId,\n message.conversationKind,\n message.userId,\n memory,\n executor.getSandboxConfig(),\n platform,\n skills,\n );\n session.agent.state.systemPrompt = systemPrompt;\n\n setEventContext({\n platform: platform.name,\n conversationId,\n conversationKind: message.conversationKind,\n userId: message.userId,\n sessionKey: message.sessionKey,\n // For Slack scheduled events, preserve thread targeting only when the\n // request was created inside an existing thread. Top-level reminders\n // should come back as top-level messages.\n threadTs: message.threadTs,\n });\n\n // Set up file upload function\n setUploadFunction(async (filePath: string, title?: string) => {\n const hostPath = translateToHostPath(\n filePath,\n conversationDir,\n workspacePath,\n conversationId,\n );\n await responseCtx.uploadFile(hostPath, title);\n });\n\n // Reset per-run state\n runState.responseCtx = responseCtx;\n runState.logCtx = {\n conversationId: sessionConversation,\n userName: message.userName,\n conversationName: undefined,\n sessionId: sessionUuid,\n };\n runState.pendingTools.clear();\n runState.totalUsage = {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n };\n runState.llmCallCount = 0;\n runState.stopReason = \"stop\";\n runState.errorMessage = undefined;\n\n // Create queue for this run\n let queueChain = Promise.resolve();\n runState.queue = {\n enqueue(fn: () => Promise<void>, errorContext: string): void {\n queueChain = queueChain.then(async () => {\n try {\n await fn();\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(`API error (${errorContext})`, errMsg);\n try {\n await responseCtx.respondDiagnostic(`Error: ${errMsg}`, { style: \"error\" });\n } catch {\n // Ignore\n }\n }\n });\n },\n };\n\n // Log context info\n log.logInfo(\n `Context sizes - system: ${systemPrompt.length} chars, memory: ${memory.length} chars`,\n );\n log.logInfo(`Channels: ${platform.channels.length}, Users: ${platform.users.length}`);\n\n // Build user message with timestamp and username prefix\n // Format: \"[YYYY-MM-DD HH:MM:SS+HH:MM] [username]: message\" so LLM knows when and who\n const now = new Date();\n const pad = (n: number) => n.toString().padStart(2, \"0\");\n const offset = -now.getTimezoneOffset();\n const offsetSign = offset >= 0 ? \"+\" : \"-\";\n const offsetHours = pad(Math.floor(Math.abs(offset) / 60));\n const offsetMins = pad(Math.abs(offset) % 60);\n const timestamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}${offsetSign}${offsetHours}:${offsetMins}`;\n const threadContext = message.threadTs ? ` [in-thread:${message.threadTs}]` : \"\";\n let userMessage = `[${timestamp}] [${message.userName || \"unknown\"}]${threadContext}: ${message.text}`;\n\n const imageAttachments: ImageContent[] = [];\n const nonImagePaths: string[] = [];\n\n for (const a of message.attachments || []) {\n // a.localPath is the path relative to the workspace.\n const fullPath = `${workspacePath}/${a.localPath}`;\n const mimeType = getImageMimeType(a.localPath);\n\n if (mimeType && existsSync(fullPath)) {\n try {\n imageAttachments.push({\n type: \"image\",\n mimeType,\n data: readFileSync(fullPath).toString(\"base64\"),\n });\n } catch {\n nonImagePaths.push(fullPath);\n }\n } else {\n nonImagePaths.push(fullPath);\n }\n }\n\n if (nonImagePaths.length > 0) {\n userMessage += `\\n\\n<slack_attachments>\\n${nonImagePaths.join(\"\\n\")}\\n</slack_attachments>`;\n }\n\n // Debug: write context to last_prompt.jsonl\n const debugContext = {\n systemPrompt,\n messages: session.messages,\n newUserMessage: userMessage,\n imageAttachmentCount: imageAttachments.length,\n };\n await writeFile(\n join(conversationDir, \"last_prompt.jsonl\"),\n JSON.stringify(debugContext, null, 2),\n );\n addLifecycleBreadcrumb(\"agent.prompt.sent\", {\n provider: model.provider,\n model: agentConfig.model,\n channel_id: sessionConversation,\n session_id: sessionUuid,\n attachment_count: message.attachments?.length ?? 0,\n image_attachment_count: imageAttachments.length,\n });\n\n await session.prompt(\n userMessage,\n imageAttachments.length > 0 ? { images: imageAttachments } : undefined,\n );\n\n // Wait for queued messages\n await queueChain;\n\n // Handle error case - update main message and post error to thread\n if (runState.stopReason === \"error\" && runState.errorMessage) {\n try {\n await responseCtx.replaceResponse(\"_Sorry, something went wrong_\");\n await responseCtx.respondDiagnostic(`Error: ${runState.errorMessage}`, {\n style: \"error\",\n });\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(\"Failed to post error message\", errMsg);\n }\n } else {\n // Final message update\n const messages = session.messages;\n const lastAssistant = messages.filter((m) => m.role === \"assistant\").pop();\n const finalText =\n lastAssistant?.content\n .filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\\n\") || \"\";\n\n // Check for [SILENT] marker - delete message and thread instead of posting\n if (finalText.trim() === \"[SILENT]\" || finalText.trim().startsWith(\"[SILENT]\")) {\n try {\n await responseCtx.deleteResponse();\n log.logInfo(\"Silent response - deleted message and thread\");\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(\"Failed to delete message for silent response\", errMsg);\n }\n } else if (finalText.trim()) {\n try {\n await responseCtx.replaceResponse(finalText);\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(\"Failed to replace message with final text\", errMsg);\n }\n }\n }\n\n // Log usage summary with context info\n if (runState.totalUsage.cost.total > 0) {\n // Get last non-aborted assistant message for context calculation\n const messages = session.messages;\n const lastAssistantMessage = messages\n .slice()\n .reverse()\n .find((m) => m.role === \"assistant\" && (m as any).stopReason !== \"aborted\") as any;\n\n const contextTokens = lastAssistantMessage\n ? lastAssistantMessage.usage.input +\n lastAssistantMessage.usage.output +\n lastAssistantMessage.usage.cacheRead +\n lastAssistantMessage.usage.cacheWrite\n : 0;\n const contextWindow = model.contextWindow || 200000;\n\n // Run-level Sentry metrics\n const { totalUsage } = runState;\n const runMetricAttributes = metricAttributes({\n provider: model.provider,\n model: agentConfig.model,\n channel_id: sessionConversation,\n session_id: sessionUuid,\n stop_reason: runState.stopReason,\n llm_calls: runState.llmCallCount,\n });\n Sentry.metrics.distribution(\"agent.run.tokens_in\", totalUsage.input, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.tokens_out\", totalUsage.output, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.cache_read\", totalUsage.cacheRead, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.cache_write\", totalUsage.cacheWrite, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.cost\", totalUsage.cost.total, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.gauge(\"agent.context.utilization\", contextTokens / contextWindow, {\n unit: \"ratio\",\n attributes: runMetricAttributes,\n });\n\n const summary = log.logUsageSummary(\n runState.logCtx!,\n runState.totalUsage,\n contextTokens,\n contextWindow,\n );\n if (platform.diagnostics?.showUsageSummary === true) {\n runState.queue!.enqueue(\n () => responseCtx.respondDiagnostic(summary, { style: \"muted\" }),\n \"usage summary\",\n );\n await queueChain;\n }\n }\n\n // Clear run state\n runState.responseCtx = null;\n runState.logCtx = null;\n runState.queue = null;\n\n return { stopReason: runState.stopReason, errorMessage: runState.errorMessage };\n },\n\n abort(): void {\n session.abort();\n },\n\n getCurrentStep(): { toolName?: string; label?: string } | undefined {\n const pending = runState.pendingTools;\n if (pending.size === 0) return undefined;\n // Get the first pending tool\n const first = pending.values().next().value;\n if (!first) return undefined;\n return {\n toolName: first.toolName,\n label: (first.args as { label?: string })?.label,\n };\n },\n };\n}\n\n/**\n * Translate container path back to host path for file operations\n */\nfunction translateToHostPath(\n containerPath: string,\n conversationDir: string,\n workspacePath: string,\n conversationId: string,\n): string {\n if (workspacePath === \"/workspace\") {\n const prefix = `/workspace/${conversationId}/`;\n if (containerPath.startsWith(prefix)) {\n return join(conversationDir, containerPath.slice(prefix.length));\n }\n if (containerPath.startsWith(\"/workspace/\")) {\n return join(conversationDir, \"..\", containerPath.slice(\"/workspace/\".length));\n }\n }\n return containerPath;\n}\n"]}
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EACV,WAAW,EACX,mBAAmB,EAGnB,YAAY,EACb,MAAM,cAAc,CAAC;AAKtB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAiC,KAAK,aAAa,EAAE,MAAM,cAAc,CAAC;AAEjF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAIL,KAAK,oBAAoB,EAE1B,MAAM,oBAAoB,CAAC;AAI5B,MAAM,WAAW,WAAW;IAC1B,GAAG,CACD,OAAO,EAAE,WAAW,EACpB,WAAW,EAAE,mBAAmB,EAChC,QAAQ,EAAE,YAAY,GACrB,OAAO,CAAC;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC1D,KAAK,IAAI,IAAI,CAAC;IACd,6DAA6D;IAC7D,cAAc,IAAI;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;CACrE;AAgXD;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,aAAa,EAAE,aAAa,EAC5B,UAAU,EAAE,MAAM,EAClB,cAAc,EAAE,MAAM,EACtB,eAAe,EAAE,MAAM,EACvB,YAAY,EAAE,MAAM,EACpB,YAAY,EAAE,oBAAoB,EAClC,YAAY,CAAC,EAAE,YAAY,EAC3B,YAAY,CAAC,EAAE,gBAAgB,EAC/B,WAAW,CAAC,EAAE,sBAAsB,GACnC,OAAO,CAAC,WAAW,CAAC,CAysBtB","sourcesContent":["import { Agent, type AgentEvent } from \"@mariozechner/pi-agent-core\";\nimport { getModel, type ImageContent } from \"@mariozechner/pi-ai\";\nimport {\n AgentSession,\n AuthStorage,\n convertToLlm,\n DefaultResourceLoader,\n formatSkillsForPrompt,\n getAgentDir,\n loadSkillsFromDir,\n ModelRegistry,\n type Skill,\n} from \"@mariozechner/pi-coding-agent\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { mkdir, readFile, writeFile } from \"fs/promises\";\nimport { homedir } from \"os\";\nimport { join } from \"path\";\nimport type {\n ChatMessage,\n ChatResponseContext,\n ChatToolResult,\n ConversationKind,\n PlatformInfo,\n} from \"./adapter.js\";\nimport { loadAgentConfigForConversation } from \"./config.js\";\nimport { createMamaSettingsManager, syncLogToSessionManager } from \"./context.js\";\nimport { ActorExecutionResolver } from \"./execution-resolver.js\";\nimport * as log from \"./log.js\";\nimport type { UserBindingStore } from \"./bindings.js\";\nimport type { DockerContainerManager } from \"./provisioner.js\";\nimport { createExecutor, type Executor, type SandboxConfig } from \"./sandbox.js\";\nimport { addLifecycleBreadcrumb, metricAttributes } from \"./sentry.js\";\nimport type { VaultManager } from \"./vault.js\";\nimport {\n extractSessionSuffix,\n extractSessionUuid,\n openManagedSession,\n type ResolvedSessionScope,\n type ThreadRootMessage,\n} from \"./session-store.js\";\nimport { createMamaTools } from \"./tools/index.js\";\nimport * as Sentry from \"@sentry/node\";\n\nexport interface AgentRunner {\n run(\n message: ChatMessage,\n responseCtx: ChatResponseContext,\n platform: PlatformInfo,\n ): Promise<{ stopReason: string; errorMessage?: string }>;\n abort(): void;\n /** Get current step info (tool name, label) for debugging */\n getCurrentStep(): { toolName?: string; label?: string } | undefined;\n}\n\nconst IMAGE_MIME_TYPES: Record<string, string> = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n gif: \"image/gif\",\n webp: \"image/webp\",\n};\n\nfunction getImageMimeType(filename: string): string | undefined {\n return IMAGE_MIME_TYPES[filename.toLowerCase().split(\".\").pop() || \"\"];\n}\n\nfunction buildThreadSessionName(message: ThreadRootMessage | null): string | undefined {\n const text = message?.text?.trim();\n if (!text) return undefined;\n const userLabel = message?.userName || message?.user || \"unknown\";\n return `[${userLabel}]: ${text}`;\n}\n\nasync function getMemory(conversationDir: string): Promise<string> {\n const parts: string[] = [];\n\n // Read workspace-level memory (shared across all conversations)\n const workspaceMemoryPath = join(conversationDir, \"..\", \"MEMORY.md\");\n if (existsSync(workspaceMemoryPath)) {\n try {\n const content = (await readFile(workspaceMemoryPath, \"utf-8\")).trim();\n if (content) {\n parts.push(`### Global Workspace Memory\\n${content}`);\n }\n } catch (error) {\n log.logWarning(\"Failed to read workspace memory\", `${workspaceMemoryPath}: ${error}`);\n }\n }\n\n // Read conversation-specific memory\n const conversationMemoryPath = join(conversationDir, \"MEMORY.md\");\n if (existsSync(conversationMemoryPath)) {\n try {\n const content = (await readFile(conversationMemoryPath, \"utf-8\")).trim();\n if (content) {\n parts.push(`### Conversation-Specific Memory\\n${content}`);\n }\n } catch (error) {\n log.logWarning(\"Failed to read conversation memory\", `${conversationMemoryPath}: ${error}`);\n }\n }\n\n if (parts.length === 0) {\n return \"(no working memory yet)\";\n }\n\n return parts.join(\"\\n\\n\");\n}\n\nfunction loadMamaSkills(conversationDir: string, workspacePath: string): Skill[] {\n const skillMap = new Map<string, Skill>();\n\n // conversationDir is the host path (e.g., /Users/.../data/C0A34FL8PMH)\n // hostWorkspacePath is the parent directory on host\n // workspacePath is the container path (e.g., /workspace)\n const hostWorkspacePath = join(conversationDir, \"..\");\n\n // Helper to translate host paths to container paths\n const translatePath = (hostPath: string): string => {\n if (hostPath.startsWith(hostWorkspacePath)) {\n return workspacePath + hostPath.slice(hostWorkspacePath.length);\n }\n return hostPath;\n };\n\n // Load workspace-level skills (global)\n const workspaceSkillsDir = join(hostWorkspacePath, \"skills\");\n for (const skill of loadSkillsFromDir({ dir: workspaceSkillsDir, source: \"workspace\" }).skills) {\n // Translate paths to container paths for system prompt\n skill.filePath = translatePath(skill.filePath);\n skill.baseDir = translatePath(skill.baseDir);\n skillMap.set(skill.name, skill);\n }\n\n // Load conversation-specific skills (override workspace skills on collision)\n const conversationSkillsDir = join(conversationDir, \"skills\");\n for (const skill of loadSkillsFromDir({ dir: conversationSkillsDir, source: \"channel\" }).skills) {\n skill.filePath = translatePath(skill.filePath);\n skill.baseDir = translatePath(skill.baseDir);\n skillMap.set(skill.name, skill);\n }\n\n return Array.from(skillMap.values());\n}\n\nfunction buildSystemPrompt(\n workspacePath: string,\n conversationId: string,\n conversationKind: ConversationKind,\n currentUserId: string | undefined,\n memory: string,\n sandboxConfig: SandboxConfig,\n platform: PlatformInfo,\n skills: Skill[],\n): string {\n const conversationPath = `${workspacePath}/${conversationId}`;\n const isContainer = sandboxConfig.type === \"container\" || sandboxConfig.type === \"image\";\n const isImageSandbox = sandboxConfig.type === \"image\";\n const isFirecracker = sandboxConfig.type === \"firecracker\";\n const isCloudflareSandbox = sandboxConfig.type === \"cloudflare\";\n\n // Format channel mappings\n const channelMappings =\n platform.channels.length > 0\n ? platform.channels.map((c) => `${c.id}\\t#${c.name}`).join(\"\\n\")\n : \"(no channels loaded)\";\n\n // Format user mappings\n const userMappings =\n platform.users.length > 0\n ? platform.users.map((u) => `${u.id}\\t@${u.userName}\\t${u.displayName}`).join(\"\\n\")\n : \"(no users loaded)\";\n\n const envDescription = isImageSandbox\n ? `You are running inside a managed per-user container.\n- Bash working directory: / (use cd or absolute paths)\n- Install tools with the image's package manager\n- Your changes persist for this user's container until it is recreated`\n : isContainer\n ? `You are running inside a shared container.\n- Bash working directory: / (use cd or absolute paths)\n- Install tools with the container's package manager\n- Your changes persist across sessions`\n : isFirecracker\n ? `You are running inside a Firecracker microVM.\n- Bash working directory: / (use cd or absolute paths)\n- Install tools with: apt-get install <package> (Debian-based)\n- Your changes persist across sessions`\n : isCloudflareSandbox\n ? `You are running through a Cloudflare Sandbox bridge.\n- Bash working directory: /workspace\n- Your commands run in a remote container managed by Cloudflare\n- Important: the remote filesystem is not automatically synced back to the host workspace`\n : `You are running directly on the host machine.\n- Bash working directory: ${process.cwd()}\n- Be careful with system modifications`;\n\n return `You are mama, a ${platform.name} bot assistant. Be concise. No emojis.\n\n## Context\n- For current date/time, use: date\n- You have access to previous conversation context including tool results from prior turns.\n- For older human-readable history beyond your context, search \\`log.jsonl\\` (contains user messages and your final responses, but not tool results).\n- Structured session history with tool results lives in \\`${conversationPath}/sessions/\\`.\n- The active top-level session is selected by \\`${conversationPath}/sessions/current\\`, which points to a timestamped \\`.jsonl\\` file in the same directory.\n- Scoped/thread sessions use fixed files at \\`${conversationPath}/sessions/<scope_id>.jsonl\\` (for example \\`${conversationPath}/sessions/1777386320.800769.jsonl\\`).\n- User messages include a \\`[in-thread:TS]\\` marker when sent from within a platform thread/reply (TS is the thread or parent message identifier). Without this marker, the message is a top-level conversation message.\n\n${platform.formattingGuide}\n\n## Platform IDs\nChannels: ${channelMappings}\n\nUsers: ${userMappings}\n\nWhen mentioning users, use <@username> format (e.g., <@mario>).\n\n## Environment\n${envDescription}\n\n## Workspace Layout\n${workspacePath}/\n├── MEMORY.md # Global memory (all conversations)\n├── skills/ # Global CLI tools you create\n└── ${conversationId}/ # This conversation\n ├── MEMORY.md # Conversation-specific memory\n ├── log.jsonl # Human-readable message history (no tool results)\n ├── sessions/ # Structured session history used for context reconstruction\n │ ├── current # Active top-level session pointer\n │ ├── <timestamp>_<id>.jsonl # Top-level session files\n │ └── <scope_id>.jsonl # Scoped thread/reply session files\n ├── attachments/ # User-shared files\n ├── scratch/ # Your working directory\n └── skills/ # Conversation-specific tools\n\n## Skills (Custom CLI Tools)\nYou can create reusable CLI tools for recurring tasks (email, APIs, data processing, etc.).\n\n### Creating Skills\nStore in \\`${workspacePath}/skills/<name>/\\` (global) or \\`${conversationPath}/skills/<name>/\\` (conversation-specific).\nEach skill directory needs a \\`SKILL.md\\` with YAML frontmatter:\n\n\\`\\`\\`markdown\n---\nname: skill-name\ndescription: Short description of what this skill does\n---\n\n# Skill Name\n\nUsage instructions, examples, etc.\nScripts are in: {baseDir}/\n\\`\\`\\`\n\n\\`name\\` and \\`description\\` are required. Use \\`{baseDir}\\` as placeholder for the skill's directory path.\n\n### Available Skills\n${skills.length > 0 ? formatSkillsForPrompt(skills) : \"(no skills installed yet)\"}\n\n## Events\nYou can schedule events that wake you up at specific times or when external things happen. Events are JSON files in \\`${workspacePath}/events/\\`.\n\n### Event Types\n\n**Immediate** - Triggers as soon as harness sees the file. Use in scripts/webhooks to signal external events.\n\\`\\`\\`json\n{\"type\": \"immediate\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"New GitHub issue opened\"}\n\\`\\`\\`\n\n**One-shot** - Triggers once at a specific time. Use for reminders.\n\\`\\`\\`json\n{\"type\": \"one-shot\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"Remind Mario about dentist\", \"at\": \"2025-12-15T09:00:00+01:00\"}\n\\`\\`\\`\n\n**Periodic** - Triggers on a cron schedule. Use for recurring tasks.\n\\`\\`\\`json\n{\"type\": \"periodic\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"Check inbox and summarize\", \"schedule\": \"0 9 * * 1-5\", \"timezone\": \"${Intl.DateTimeFormat().resolvedOptions().timeZone}\"}\n\\`\\`\\`\n\n### Cron Format\n\\`minute hour day-of-month month day-of-week\\`\n- \\`0 9 * * *\\` = daily at 9:00\n- \\`0 9 * * 1-5\\` = weekdays at 9:00\n- \\`30 14 * * 1\\` = Mondays at 14:30\n- \\`0 0 1 * *\\` = first of each month at midnight\n\n### Timezones\nAll \\`at\\` timestamps must include offset (e.g., \\`+01:00\\`). Periodic events use IANA timezone names. The harness runs in ${Intl.DateTimeFormat().resolvedOptions().timeZone}. When users mention times without timezone, assume ${Intl.DateTimeFormat().resolvedOptions().timeZone}.\n\n### Platform and Credential Routing\nSet \\`platform\\` to the target bot platform (\\`${platform.name}\\` for this conversation). Include it explicitly to avoid ambiguity.\n\nSet \\`userId\\` to the platform userId of whoever asked for the event. When the event fires, tool execution routes using that user's vault selection in per-user modes. In \\`container:<name>\\`, events use the container's single shared vault.\n\nPrefer the \\`event\\` tool over manually writing JSON files; it fills \\`platform\\`, \\`conversationId\\`, \\`conversationKind\\`, and \\`userId\\` for the current conversation automatically.\n\n### Creating Events\nUse unique filenames to avoid overwriting existing events. Include a timestamp or random suffix:\n\\`\\`\\`bash\ncat > ${workspacePath}/events/dentist-reminder-$(date +%s).json << 'EOF'\n{\"type\": \"one-shot\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"Dentist tomorrow\", \"at\": \"2025-12-14T09:00:00+01:00\"}\nEOF\n\\`\\`\\`\nOr check if file exists first before creating.\n\n### Managing Events\n- List: \\`ls ${workspacePath}/events/\\`\n- View: \\`cat ${workspacePath}/events/foo.json\\`\n- Delete/cancel: \\`rm ${workspacePath}/events/foo.json\\`\n\n### When Events Trigger\nYou receive a message like:\n\\`\\`\\`\n[EVENT:dentist-reminder.json:one-shot:2025-12-14T09:00:00+01:00] Dentist tomorrow\n\\`\\`\\`\nImmediate and one-shot events auto-delete after triggering. Periodic events persist until you delete them.\n\n### Silent Completion\nFor periodic events where there's nothing to report, respond with just \\`[SILENT]\\` (no other text). This deletes the status message and posts nothing to the platform. Use this to avoid spamming the channel when periodic checks find nothing actionable.\n\n### Debouncing\nWhen writing programs that create immediate events (email watchers, webhook handlers, etc.), always debounce. If 50 emails arrive in a minute, don't create 50 immediate events. Instead collect events over a window and create ONE immediate event summarizing what happened, or just signal \"new activity, check inbox\" rather than per-item events. Or simpler: use a periodic event to check for new items every N minutes instead of immediate events.\n\n### Limits\nMaximum 5 events can be queued. Don't create excessive immediate or periodic events.\n\n## Memory\nWrite to MEMORY.md files to persist context across conversations.\n- Global (${workspacePath}/MEMORY.md): skills, preferences, project info\n- Conversation (${conversationPath}/MEMORY.md): conversation-specific decisions, ongoing work\nUpdate when you learn something important or when asked to remember something.\n\n### Current Memory\n${memory}\n\n## System Configuration Log\nMaintain ${workspacePath}/SYSTEM.md to log all environment modifications:\n- Installed packages (apt install, npm install, uv pip install)\n- Environment variables set\n- Config files modified (~/.gitconfig, cron jobs, etc.)\n- Skill dependencies installed\n\nUpdate this file whenever you modify the environment. On fresh container, read it first to restore your setup.\n\n## Log Queries (for older history)\nFormat: \\`{\"date\":\"...\",\"ts\":\"...\",\"user\":\"...\",\"userName\":\"...\",\"text\":\"...\",\"isBot\":false}\\`\nThe log contains user messages and your final responses (not tool calls/results).\nUse \\`log.jsonl\\` for quick grep-style history. Use \\`${conversationPath}/sessions/\\` when you need structured turns, tool outputs, or branch lineage.\n${isContainer ? \"Install jq: apt-get install jq\" : \"\"}\n${isFirecracker ? \"Install jq: apt-get install jq\" : \"\"}\n\n\\`\\`\\`bash\n# Recent messages\ntail -30 log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'\n\n# Search for specific topic\ngrep -i \"topic\" log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'\n\n# Messages from specific user\ngrep '\"userName\":\"mario\"' log.jsonl | tail -20 | jq -c '{date: .date[0:19], text}'\n\n# Inspect top-level session pointer and available session files\ncat sessions/current\nls -1 sessions/\n\\`\\`\\`\n\n## Tools\n- bash: Run shell commands (primary tool). Install packages as needed.\n- read: Read files\n- write: Create/overwrite files\n- edit: Surgical file edits\n- attach: Share files to the platform\n\nEach tool requires a \"label\" parameter (shown to user).\n`;\n}\n\nfunction truncate(text: string, maxLen: number): string {\n if (text.length <= maxLen) return text;\n return `${text.substring(0, maxLen - 3)}...`;\n}\n\n// Tools whose output is interesting in the structured session log but too noisy\n// to surface as a per-tool diagnostic to the user.\nconst QUIET_TOOLS = new Set([\"read\", \"write\", \"edit\"]);\n\n// Cap raw tool output before handing it to adapters. Bash output can be MB; without\n// this each adapter's splitter would fan it out into many sequential platform posts.\nconst TOOL_RESULT_DIAGNOSTIC_CAP = 8000;\n\nfunction extractToolResultText(result: unknown): string {\n if (typeof result === \"string\") {\n return result;\n }\n\n if (\n result &&\n typeof result === \"object\" &&\n \"content\" in result &&\n Array.isArray((result as { content: unknown }).content)\n ) {\n const content = (result as { content: Array<{ type: string; text?: string }> }).content;\n const textParts: string[] = [];\n for (const part of content) {\n if (part.type === \"text\" && part.text) {\n textParts.push(part.text);\n }\n }\n if (textParts.length > 0) {\n return textParts.join(\"\\n\");\n }\n }\n\n return JSON.stringify(result);\n}\n\n// ============================================================================\n// Agent runner\n// ============================================================================\n\n/**\n * Create a new AgentRunner for a channel.\n * Sets up the session and subscribes to events once.\n *\n * Runner caching is handled by the caller (channelStates in main.ts).\n * This is a stateless factory function.\n */\nexport async function createRunner(\n sandboxConfig: SandboxConfig,\n sessionKey: string,\n conversationId: string,\n conversationDir: string,\n workspaceDir: string,\n sessionScope: ResolvedSessionScope,\n vaultManager?: VaultManager,\n bindingStore?: UserBindingStore,\n provisioner?: DockerContainerManager,\n): Promise<AgentRunner> {\n const agentConfig = loadAgentConfigForConversation(conversationDir);\n\n // Initialize logger with settings from config\n log.initLogger({\n logFormat: agentConfig.logFormat,\n logLevel: agentConfig.logLevel,\n });\n\n const executionResolver =\n vaultManager &&\n sandboxConfig.type !== \"host\" &&\n (vaultManager.isEnabled() ||\n sandboxConfig.type === \"container\" ||\n sandboxConfig.type === \"image\" ||\n sandboxConfig.type === \"cloudflare\" ||\n sandboxConfig.type === \"firecracker\")\n ? new ActorExecutionResolver(sandboxConfig, vaultManager, provisioner, workspaceDir)\n : undefined;\n // activeExecutor is replaced at the start of each run() call when executionResolver\n // is present, so the stable `executor` wrapper always delegates to the latest resolved value.\n let activeExecutor: Executor =\n executionResolver !== undefined\n ? createExecutor({ type: \"host\" })\n : createExecutor(sandboxConfig);\n const executor: Executor = {\n exec(command, options) {\n return activeExecutor.exec(command, options);\n },\n getWorkspacePath(hostPath) {\n return activeExecutor.getWorkspacePath(hostPath);\n },\n getSandboxConfig() {\n return activeExecutor.getSandboxConfig();\n },\n };\n const workspaceBase = conversationDir.replace(`/${conversationId}`, \"\");\n const getWorkspacePath = () => executor.getWorkspacePath(workspaceBase);\n let workspacePath = getWorkspacePath();\n\n // Create tools (per-runner, with per-runner upload function setter)\n const { tools, setUploadFunction, setEventContext } = createMamaTools(executor, workspaceDir);\n\n // Resolve model from config\n // Use 'as any' cast because agentConfig.provider/model are plain strings,\n // while getModel() has constrained generic types for known providers.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const model = (getModel as any)(agentConfig.provider, agentConfig.model);\n\n // Initial system prompt (will be updated each run with fresh memory/channels/users/skills)\n const memory = await getMemory(conversationDir);\n const skills = loadMamaSkills(conversationDir, workspacePath);\n const emptyPlatform: PlatformInfo = {\n name: \"chat\",\n formattingGuide: \"\",\n channels: [],\n users: [],\n };\n const systemPrompt = buildSystemPrompt(\n workspacePath,\n conversationId,\n \"shared\",\n undefined,\n memory,\n sandboxConfig,\n emptyPlatform,\n skills,\n );\n\n // Create session manager and settings manager. Top-level/private sessions\n // use the conversation's current pointer; scoped sessions use fixed files.\n // Platform-specific branch/fork behavior is resolved before runner creation.\n const isThread = sessionKey.includes(\":\");\n const rootTs = extractSessionSuffix(sessionKey);\n const { sessionDir, contextFile, threadRootMessage } = sessionScope;\n const sessionManager = openManagedSession(contextFile, sessionDir, conversationDir);\n const threadSessionName = buildThreadSessionName(threadRootMessage);\n if (isThread && threadSessionName && sessionManager.getSessionName() !== threadSessionName) {\n sessionManager.appendSessionInfo(threadSessionName);\n }\n\n const sessionUuid = extractSessionUuid(contextFile);\n const settingsManager = createMamaSettingsManager(join(conversationDir, \"..\"));\n\n // Create AuthStorage and ModelRegistry\n // Auth stored outside workspace so agent can't access it\n const authStorage = AuthStorage.create(join(homedir(), \".pi\", \"mama\", \"auth.json\"));\n const modelRegistry = ModelRegistry.create(authStorage);\n\n // Create agent\n const agent = new Agent({\n initialState: {\n systemPrompt,\n model,\n thinkingLevel: agentConfig.thinkingLevel,\n tools,\n },\n convertToLlm,\n getApiKey: async () => {\n const key = await modelRegistry.getApiKeyForProvider(model.provider);\n if (!key)\n throw new Error(\n `No API key for provider \"${model.provider}\". Set the appropriate environment variable or configure via auth.json`,\n );\n return key;\n },\n });\n\n // Load existing messages\n const loadedSession = sessionManager.buildSessionContext();\n if (loadedSession.messages.length > 0) {\n agent.state.messages = loadedSession.messages;\n log.logInfo(\n `[${conversationId}] Loaded ${loadedSession.messages.length} messages from context.jsonl`,\n );\n }\n\n // Load extensions, skills, prompts, themes via DefaultResourceLoader\n // This reads ~/.pi/agent/settings.json (packages, extensions enable/disable)\n // and discovers resources from standard locations + npm/git packages.\n const resourceLoader = new DefaultResourceLoader({\n cwd: workspaceDir,\n agentDir: getAgentDir(),\n systemPrompt,\n });\n try {\n await resourceLoader.reload();\n const extResult = resourceLoader.getExtensions();\n if (extResult.errors.length > 0) {\n for (const err of extResult.errors) {\n log.logWarning(`[${conversationId}] Extension load error: ${err.path}`, err.error);\n }\n }\n log.logInfo(\n `[${conversationId}] Loaded ${extResult.extensions.length} extension(s): ${extResult.extensions.map((e) => e.path).join(\", \")}`,\n );\n } catch (error) {\n log.logWarning(`[${conversationId}] Failed to load resources`, String(error));\n }\n\n const baseToolsOverride = Object.fromEntries(tools.map((tool) => [tool.name, tool]));\n\n // Create AgentSession wrapper\n const session = new AgentSession({\n agent,\n sessionManager,\n settingsManager,\n cwd: workspaceDir,\n modelRegistry,\n resourceLoader,\n baseToolsOverride,\n });\n\n // Mutable per-run state - event handler references this\n const runState = {\n responseCtx: null as ChatResponseContext | null,\n logCtx: null as {\n conversationId: string;\n userName?: string;\n conversationName?: string;\n sessionId?: string;\n } | null,\n queue: null as {\n enqueue(fn: () => Promise<void>, errorContext: string): void;\n } | null,\n pendingTools: new Map<string, { toolName: string; args: unknown; startTime: number }>(),\n totalUsage: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n },\n llmCallCount: 0,\n stopReason: \"stop\",\n errorMessage: undefined as string | undefined,\n };\n\n // Subscribe to events ONCE\n session.subscribe(async (event) => {\n // Skip if no active run\n if (!runState.responseCtx || !runState.logCtx || !runState.queue) return;\n\n const { responseCtx, logCtx, queue, pendingTools } = runState;\n const baseAttrs = { channel_id: logCtx.conversationId, session_id: logCtx.sessionId };\n\n if (event.type === \"tool_execution_start\") {\n const agentEvent = event as AgentEvent & { type: \"tool_execution_start\" };\n const args = agentEvent.args as { label?: string };\n const label = args.label || agentEvent.toolName;\n\n pendingTools.set(agentEvent.toolCallId, {\n toolName: agentEvent.toolName,\n args: agentEvent.args,\n startTime: Date.now(),\n });\n addLifecycleBreadcrumb(\"agent.tool.started\", {\n tool: agentEvent.toolName,\n ...baseAttrs,\n });\n\n log.logToolStart(\n logCtx,\n agentEvent.toolName,\n label,\n agentEvent.args as Record<string, unknown>,\n );\n } else if (event.type === \"tool_execution_end\") {\n const agentEvent = event as AgentEvent & { type: \"tool_execution_end\" };\n const resultStr = extractToolResultText(agentEvent.result);\n const pending = pendingTools.get(agentEvent.toolCallId);\n pendingTools.delete(agentEvent.toolCallId);\n\n const durationMs = pending ? Date.now() - pending.startTime : 0;\n\n Sentry.metrics.count(\"agent.tool.calls\", 1, {\n attributes: metricAttributes({\n tool: agentEvent.toolName,\n error: String(agentEvent.isError),\n ...baseAttrs,\n }),\n });\n Sentry.metrics.distribution(\"agent.tool.duration\", durationMs, {\n unit: \"millisecond\",\n attributes: metricAttributes({\n tool: agentEvent.toolName,\n ...baseAttrs,\n }),\n });\n addLifecycleBreadcrumb(\"agent.tool.completed\", {\n tool: agentEvent.toolName,\n error: agentEvent.isError,\n duration_ms: durationMs,\n ...baseAttrs,\n });\n\n if (agentEvent.isError) {\n log.logToolError(logCtx, agentEvent.toolName, durationMs, resultStr);\n } else {\n log.logToolSuccess(logCtx, agentEvent.toolName, durationMs, resultStr);\n }\n\n if (!QUIET_TOOLS.has(agentEvent.toolName)) {\n const toolResult: ChatToolResult = {\n toolName: agentEvent.toolName,\n label: pending?.args ? (pending.args as { label?: string }).label : undefined,\n args: pending?.args as Record<string, unknown> | undefined,\n result: truncate(resultStr, TOOL_RESULT_DIAGNOSTIC_CAP),\n isError: agentEvent.isError,\n durationMs,\n };\n queue.enqueue(() => responseCtx.respondToolResult(toolResult), \"tool result diagnostic\");\n }\n\n if (agentEvent.isError) {\n queue.enqueue(\n () => responseCtx.respond(`_Error: ${truncate(resultStr, 200)}_`),\n \"tool error\",\n );\n }\n } else if (event.type === \"message_start\") {\n const agentEvent = event as AgentEvent & { type: \"message_start\" };\n if (agentEvent.message.role === \"assistant\") {\n runState.llmCallCount += 1;\n addLifecycleBreadcrumb(\"agent.llm.call.started\", {\n call_index: runState.llmCallCount,\n provider: model.provider,\n model: agentConfig.model,\n ...baseAttrs,\n });\n log.logResponseStart(logCtx);\n }\n } else if (event.type === \"message_end\") {\n const agentEvent = event as AgentEvent & { type: \"message_end\" };\n if (agentEvent.message.role === \"assistant\") {\n const assistantMsg = agentEvent.message as any;\n\n if (assistantMsg.stopReason) {\n runState.stopReason = assistantMsg.stopReason;\n }\n if (assistantMsg.errorMessage) {\n runState.errorMessage = assistantMsg.errorMessage;\n }\n\n if (assistantMsg.usage) {\n runState.totalUsage.input += assistantMsg.usage.input;\n runState.totalUsage.output += assistantMsg.usage.output;\n runState.totalUsage.cacheRead += assistantMsg.usage.cacheRead;\n runState.totalUsage.cacheWrite += assistantMsg.usage.cacheWrite;\n runState.totalUsage.cost.input += assistantMsg.usage.cost.input;\n runState.totalUsage.cost.output += assistantMsg.usage.cost.output;\n runState.totalUsage.cost.cacheRead += assistantMsg.usage.cost.cacheRead;\n runState.totalUsage.cost.cacheWrite += assistantMsg.usage.cost.cacheWrite;\n runState.totalUsage.cost.total += assistantMsg.usage.cost.total;\n\n // Per-turn LLM metrics\n const llmAttributes = metricAttributes({\n provider: model.provider,\n model: agentConfig.model,\n ...baseAttrs,\n stop_reason: assistantMsg.stopReason,\n error: Boolean(assistantMsg.errorMessage),\n });\n Sentry.metrics.count(\"agent.llm.calls\", 1, { attributes: llmAttributes });\n Sentry.metrics.distribution(\"agent.llm.tokens_in\", assistantMsg.usage.input, {\n attributes: llmAttributes,\n });\n Sentry.metrics.distribution(\"agent.llm.tokens_out\", assistantMsg.usage.output, {\n attributes: llmAttributes,\n });\n if (assistantMsg.usage.cacheRead > 0) {\n Sentry.metrics.distribution(\"agent.llm.cache_read\", assistantMsg.usage.cacheRead, {\n attributes: llmAttributes,\n });\n }\n if (assistantMsg.usage.cacheWrite > 0) {\n Sentry.metrics.distribution(\"agent.llm.cache_write\", assistantMsg.usage.cacheWrite, {\n attributes: llmAttributes,\n });\n }\n Sentry.metrics.distribution(\"agent.llm.cost_per_turn\", assistantMsg.usage.cost.total, {\n attributes: llmAttributes,\n });\n addLifecycleBreadcrumb(\"agent.llm.call.completed\", {\n call_index: runState.llmCallCount,\n provider: model.provider,\n model: agentConfig.model,\n stop_reason: assistantMsg.stopReason,\n error: Boolean(assistantMsg.errorMessage),\n input_tokens: assistantMsg.usage.input,\n output_tokens: assistantMsg.usage.output,\n cost_total_usd: assistantMsg.usage.cost.total,\n });\n }\n\n const content = agentEvent.message.content;\n const thinkingParts: string[] = [];\n const textParts: string[] = [];\n for (const part of content) {\n if (part.type === \"thinking\") {\n thinkingParts.push((part as any).thinking);\n } else if (part.type === \"text\") {\n textParts.push((part as any).text);\n }\n }\n\n const text = textParts.join(\"\\n\");\n\n for (const thinking of thinkingParts) {\n log.logThinking(logCtx, thinking);\n queue.enqueue(() => responseCtx.respond(`_${thinking}_`), \"thinking main\");\n queue.enqueue(\n () => responseCtx.respondDiagnostic(`_${thinking}_`),\n \"thinking diagnostic\",\n );\n }\n\n if (text.trim()) {\n log.logResponse(logCtx, text);\n queue.enqueue(() => responseCtx.respond(text), \"response main\");\n }\n }\n } else if (event.type === \"compaction_start\") {\n log.logInfo(`Auto-compaction started (reason: ${(event as any).reason})`);\n queue.enqueue(() => responseCtx.respond(\"_Compacting context..._\"), \"compaction start\");\n } else if (event.type === \"compaction_end\") {\n const compEvent = event as any;\n if (compEvent.result) {\n log.logInfo(`Auto-compaction complete: ${compEvent.result.tokensBefore} tokens compacted`);\n } else if (compEvent.aborted) {\n log.logInfo(\"Auto-compaction aborted\");\n }\n } else if (event.type === \"auto_retry_start\") {\n const retryEvent = event as any;\n log.logWarning(\n `Retrying (${retryEvent.attempt}/${retryEvent.maxAttempts})`,\n retryEvent.errorMessage,\n );\n queue.enqueue(\n () =>\n responseCtx.respond(`_Retrying (${retryEvent.attempt}/${retryEvent.maxAttempts})..._`),\n \"retry\",\n );\n }\n });\n\n return {\n async run(\n message: ChatMessage,\n responseCtx: ChatResponseContext,\n platform: PlatformInfo,\n ): Promise<{ stopReason: string; errorMessage?: string }> {\n // Extract conversationId from sessionKey (format: \"conversationId:rootTs\" or just \"conversationId\")\n const sessionConversation = message.sessionKey.split(\":\")[0];\n\n // Ensure conversation directory exists\n await mkdir(conversationDir, { recursive: true });\n\n if (executionResolver) {\n executionResolver.refresh();\n activeExecutor = await executionResolver.resolve({\n platform: platform.name,\n userId: message.userId,\n conversationId,\n });\n workspacePath = getWorkspacePath();\n }\n\n // Sync messages from log.jsonl that arrived while we were offline or busy\n // Exclude the current message (it will be added via prompt())\n // Default sync range is 10 days (handled by syncLogToSessionManager)\n // Thread filter ensures only messages from this session's thread are synced\n const threadFilter = message.sessionKey.includes(\":\")\n ? { scope: \"thread\" as const, rootTs, threadTs: message.threadTs }\n : { scope: \"top-level\" as const, rootTs };\n const syncedCount = await syncLogToSessionManager(\n sessionManager,\n conversationDir,\n message.id,\n undefined,\n threadFilter,\n );\n if (syncedCount > 0) {\n log.logInfo(`[${conversationId}] Synced ${syncedCount} messages from log.jsonl`);\n }\n\n // Reload messages from context.jsonl\n // This picks up any messages synced above\n const reloadedSession = sessionManager.buildSessionContext();\n if (reloadedSession.messages.length > 0) {\n agent.state.messages = reloadedSession.messages;\n log.logInfo(\n `[${conversationId}] Reloaded ${reloadedSession.messages.length} messages from context`,\n );\n }\n\n // Update system prompt with fresh memory, channel/user info, and skills\n const memory = await getMemory(conversationDir);\n const skills = loadMamaSkills(conversationDir, workspacePath);\n const systemPrompt = buildSystemPrompt(\n workspacePath,\n conversationId,\n message.conversationKind,\n message.userId,\n memory,\n executor.getSandboxConfig(),\n platform,\n skills,\n );\n session.agent.state.systemPrompt = systemPrompt;\n\n setEventContext({\n platform: platform.name,\n conversationId,\n conversationKind: message.conversationKind,\n userId: message.userId,\n sessionKey: message.sessionKey,\n // For Slack scheduled events, preserve thread targeting only when the\n // request was created inside an existing thread. Top-level reminders\n // should come back as top-level messages.\n threadTs: message.threadTs,\n });\n\n // Set up file upload function\n setUploadFunction(async (filePath: string, title?: string) => {\n const hostPath = translateToHostPath(\n filePath,\n conversationDir,\n workspacePath,\n conversationId,\n );\n await responseCtx.uploadFile(hostPath, title);\n });\n\n // Reset per-run state\n runState.responseCtx = responseCtx;\n runState.logCtx = {\n conversationId: sessionConversation,\n userName: message.userName,\n conversationName: undefined,\n sessionId: sessionUuid,\n };\n runState.pendingTools.clear();\n runState.totalUsage = {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n };\n runState.llmCallCount = 0;\n runState.stopReason = \"stop\";\n runState.errorMessage = undefined;\n\n // Create queue for this run\n let queueChain = Promise.resolve();\n runState.queue = {\n enqueue(fn: () => Promise<void>, errorContext: string): void {\n queueChain = queueChain.then(async () => {\n try {\n await fn();\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(`API error (${errorContext})`, errMsg);\n try {\n await responseCtx.respondDiagnostic(`Error: ${errMsg}`, { style: \"error\" });\n } catch {\n // Ignore\n }\n }\n });\n },\n };\n\n // Log context info\n log.logInfo(\n `Context sizes - system: ${systemPrompt.length} chars, memory: ${memory.length} chars`,\n );\n log.logInfo(`Channels: ${platform.channels.length}, Users: ${platform.users.length}`);\n\n // Build user message with timestamp and username prefix\n // Format: \"[YYYY-MM-DD HH:MM:SS+HH:MM] [username]: message\" so LLM knows when and who\n const now = new Date();\n const pad = (n: number) => n.toString().padStart(2, \"0\");\n const offset = -now.getTimezoneOffset();\n const offsetSign = offset >= 0 ? \"+\" : \"-\";\n const offsetHours = pad(Math.floor(Math.abs(offset) / 60));\n const offsetMins = pad(Math.abs(offset) % 60);\n const timestamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}${offsetSign}${offsetHours}:${offsetMins}`;\n const threadContext = message.threadTs ? ` [in-thread:${message.threadTs}]` : \"\";\n let userMessage = `[${timestamp}] [${message.userName || \"unknown\"}]${threadContext}: ${message.text}`;\n\n const imageAttachments: ImageContent[] = [];\n const nonImagePaths: string[] = [];\n\n for (const a of message.attachments || []) {\n // a.localPath is the path relative to the workspace.\n const fullPath = `${workspacePath}/${a.localPath}`;\n const mimeType = getImageMimeType(a.localPath);\n\n if (mimeType && existsSync(fullPath)) {\n try {\n imageAttachments.push({\n type: \"image\",\n mimeType,\n data: readFileSync(fullPath).toString(\"base64\"),\n });\n } catch {\n nonImagePaths.push(fullPath);\n }\n } else {\n nonImagePaths.push(fullPath);\n }\n }\n\n if (nonImagePaths.length > 0) {\n userMessage += `\\n\\n<slack_attachments>\\n${nonImagePaths.join(\"\\n\")}\\n</slack_attachments>`;\n }\n\n // Debug: write context to last_prompt.jsonl\n const debugContext = {\n systemPrompt,\n messages: session.messages,\n newUserMessage: userMessage,\n imageAttachmentCount: imageAttachments.length,\n };\n await writeFile(\n join(conversationDir, \"last_prompt.jsonl\"),\n JSON.stringify(debugContext, null, 2),\n );\n addLifecycleBreadcrumb(\"agent.prompt.sent\", {\n provider: model.provider,\n model: agentConfig.model,\n channel_id: sessionConversation,\n session_id: sessionUuid,\n attachment_count: message.attachments?.length ?? 0,\n image_attachment_count: imageAttachments.length,\n });\n\n await session.prompt(\n userMessage,\n imageAttachments.length > 0 ? { images: imageAttachments } : undefined,\n );\n\n // Wait for queued messages\n await queueChain;\n\n // Handle error case - update main message and post error to thread\n if (runState.stopReason === \"error\" && runState.errorMessage) {\n try {\n await responseCtx.replaceResponse(\"_Sorry, something went wrong_\");\n await responseCtx.respondDiagnostic(`Error: ${runState.errorMessage}`, {\n style: \"error\",\n });\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(\"Failed to post error message\", errMsg);\n }\n } else {\n // Final message update\n const messages = session.messages;\n const lastAssistant = messages.filter((m) => m.role === \"assistant\").pop();\n const finalText =\n lastAssistant?.content\n .filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\\n\") || \"\";\n\n // Check for [SILENT] marker - delete message and thread instead of posting\n if (finalText.trim() === \"[SILENT]\" || finalText.trim().startsWith(\"[SILENT]\")) {\n try {\n await responseCtx.deleteResponse();\n log.logInfo(\"Silent response - deleted message and thread\");\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(\"Failed to delete message for silent response\", errMsg);\n }\n } else if (finalText.trim()) {\n try {\n await responseCtx.replaceResponse(finalText);\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(\"Failed to replace message with final text\", errMsg);\n }\n }\n }\n\n // Log usage summary with context info\n if (runState.totalUsage.cost.total > 0) {\n // Get last non-aborted assistant message for context calculation\n const messages = session.messages;\n const lastAssistantMessage = messages\n .slice()\n .reverse()\n .find((m) => m.role === \"assistant\" && (m as any).stopReason !== \"aborted\") as any;\n\n const contextTokens = lastAssistantMessage\n ? lastAssistantMessage.usage.input +\n lastAssistantMessage.usage.output +\n lastAssistantMessage.usage.cacheRead +\n lastAssistantMessage.usage.cacheWrite\n : 0;\n const contextWindow = model.contextWindow || 200000;\n\n // Run-level Sentry metrics\n const { totalUsage } = runState;\n const runMetricAttributes = metricAttributes({\n provider: model.provider,\n model: agentConfig.model,\n channel_id: sessionConversation,\n session_id: sessionUuid,\n stop_reason: runState.stopReason,\n llm_calls: runState.llmCallCount,\n });\n Sentry.metrics.distribution(\"agent.run.tokens_in\", totalUsage.input, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.tokens_out\", totalUsage.output, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.cache_read\", totalUsage.cacheRead, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.cache_write\", totalUsage.cacheWrite, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.cost\", totalUsage.cost.total, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.gauge(\"agent.context.utilization\", contextTokens / contextWindow, {\n unit: \"ratio\",\n attributes: runMetricAttributes,\n });\n\n const summary = log.logUsageSummary(\n runState.logCtx!,\n runState.totalUsage,\n contextTokens,\n contextWindow,\n );\n if (platform.diagnostics?.showUsageSummary === true) {\n runState.queue!.enqueue(\n () => responseCtx.respondDiagnostic(summary, { style: \"muted\" }),\n \"usage summary\",\n );\n await queueChain;\n }\n }\n\n // Clear run state\n runState.responseCtx = null;\n runState.logCtx = null;\n runState.queue = null;\n\n return { stopReason: runState.stopReason, errorMessage: runState.errorMessage };\n },\n\n abort(): void {\n session.abort();\n },\n\n getCurrentStep(): { toolName?: string; label?: string } | undefined {\n const pending = runState.pendingTools;\n if (pending.size === 0) return undefined;\n // Get the first pending tool\n const first = pending.values().next().value;\n if (!first) return undefined;\n return {\n toolName: first.toolName,\n label: (first.args as { label?: string })?.label,\n };\n },\n };\n}\n\n/**\n * Translate container path back to host path for file operations\n */\nfunction translateToHostPath(\n containerPath: string,\n conversationDir: string,\n workspacePath: string,\n conversationId: string,\n): string {\n if (workspacePath === \"/workspace\") {\n const prefix = `/workspace/${conversationId}/`;\n if (containerPath.startsWith(prefix)) {\n return join(conversationDir, containerPath.slice(prefix.length));\n }\n if (containerPath.startsWith(\"/workspace/\")) {\n return join(conversationDir, \"..\", containerPath.slice(\"/workspace/\".length));\n }\n }\n return containerPath;\n}\n"]}
package/dist/agent.js CHANGED
@@ -5,7 +5,7 @@ import { existsSync, readFileSync } from "fs";
5
5
  import { mkdir, readFile, writeFile } from "fs/promises";
6
6
  import { homedir } from "os";
7
7
  import { join } from "path";
8
- import { loadAgentConfig } from "./config.js";
8
+ import { loadAgentConfigForConversation } from "./config.js";
9
9
  import { createMamaSettingsManager, syncLogToSessionManager } from "./context.js";
10
10
  import { ActorExecutionResolver } from "./execution-resolver.js";
11
11
  import * as log from "./log.js";
@@ -353,7 +353,7 @@ function extractToolResultText(result) {
353
353
  * This is a stateless factory function.
354
354
  */
355
355
  export async function createRunner(sandboxConfig, sessionKey, conversationId, conversationDir, workspaceDir, sessionScope, vaultManager, bindingStore, provisioner) {
356
- const agentConfig = loadAgentConfig();
356
+ const agentConfig = loadAgentConfigForConversation(conversationDir);
357
357
  // Initialize logger with settings from config
358
358
  log.initLogger({
359
359
  logFormat: agentConfig.logFormat,
@@ -426,7 +426,7 @@ export async function createRunner(sandboxConfig, sessionKey, conversationId, co
426
426
  initialState: {
427
427
  systemPrompt,
428
428
  model,
429
- thinkingLevel: agentConfig.thinkingLevel ?? "off",
429
+ thinkingLevel: agentConfig.thinkingLevel,
430
430
  tools,
431
431
  },
432
432
  convertToLlm,