@geminixiang/mama 0.1.8 → 0.1.10

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 (48) hide show
  1. package/README.md +149 -9
  2. package/dist/adapter.d.ts +14 -1
  3. package/dist/adapter.d.ts.map +1 -1
  4. package/dist/adapter.js.map +1 -1
  5. package/dist/adapters/discord/context.d.ts.map +1 -1
  6. package/dist/adapters/discord/context.js +1 -0
  7. package/dist/adapters/discord/context.js.map +1 -1
  8. package/dist/adapters/slack/bot.d.ts +5 -1
  9. package/dist/adapters/slack/bot.d.ts.map +1 -1
  10. package/dist/adapters/slack/bot.js +137 -13
  11. package/dist/adapters/slack/bot.js.map +1 -1
  12. package/dist/adapters/slack/context.d.ts.map +1 -1
  13. package/dist/adapters/slack/context.js +50 -25
  14. package/dist/adapters/slack/context.js.map +1 -1
  15. package/dist/adapters/slack/tools/attach.d.ts.map +1 -1
  16. package/dist/adapters/slack/tools/attach.js +4 -2
  17. package/dist/adapters/slack/tools/attach.js.map +1 -1
  18. package/dist/adapters/telegram/bot.d.ts +4 -3
  19. package/dist/adapters/telegram/bot.d.ts.map +1 -1
  20. package/dist/adapters/telegram/bot.js +11 -23
  21. package/dist/adapters/telegram/bot.js.map +1 -1
  22. package/dist/adapters/telegram/context.d.ts +1 -1
  23. package/dist/adapters/telegram/context.d.ts.map +1 -1
  24. package/dist/adapters/telegram/context.js +23 -40
  25. package/dist/adapters/telegram/context.js.map +1 -1
  26. package/dist/agent.d.ts +5 -0
  27. package/dist/agent.d.ts.map +1 -1
  28. package/dist/agent.js +63 -17
  29. package/dist/agent.js.map +1 -1
  30. package/dist/context.d.ts +13 -1
  31. package/dist/context.d.ts.map +1 -1
  32. package/dist/context.js +20 -2
  33. package/dist/context.js.map +1 -1
  34. package/dist/events.d.ts +10 -5
  35. package/dist/events.d.ts.map +1 -1
  36. package/dist/events.js +44 -10
  37. package/dist/events.js.map +1 -1
  38. package/dist/log.d.ts.map +1 -1
  39. package/dist/log.js +1 -1
  40. package/dist/log.js.map +1 -1
  41. package/dist/main.d.ts.map +1 -1
  42. package/dist/main.js +113 -37
  43. package/dist/main.js.map +1 -1
  44. package/dist/sandbox.d.ts +7 -1
  45. package/dist/sandbox.d.ts.map +1 -1
  46. package/dist/sandbox.js +127 -27
  47. package/dist/sandbox.js.map +1 -1
  48. package/package.json +12 -12
@@ -1 +1 @@
1
- {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../../src/adapters/telegram/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAEvF,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAE3D,eAAO,MAAM,yBAAyB,kNAGY,CAAC;AAEnD,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,aAAa,EACpB,GAAG,EAAE,WAAW,EAChB,OAAO,CAAC,EAAE,OAAO,GAChB;IACD,OAAO,EAAE,WAAW,CAAC;IACrB,WAAW,EAAE,mBAAmB,CAAC;IACjC,QAAQ,EAAE,YAAY,CAAC;CACxB,CA+JA","sourcesContent":["import type { ChatMessage, ChatResponseContext, PlatformInfo } from \"../../adapter.js\";\nimport * as log from \"../../log.js\";\nimport type { TelegramBot, TelegramEvent } from \"./bot.js\";\n\nexport const TELEGRAM_FORMATTING_GUIDE = `## 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>\nDo NOT use Markdown asterisks or backtick syntax.`;\n\nexport function createTelegramAdapters(\n event: TelegramEvent,\n bot: TelegramBot,\n isEvent?: boolean,\n): {\n message: ChatMessage;\n responseCtx: ChatResponseContext;\n platform: PlatformInfo;\n} {\n let messageId: number | null = null;\n let accumulatedText = \"\";\n let isWorking = true;\n const workingIndicator = \" ...\";\n let updatePromise = Promise.resolve();\n\n const eventFilename = isEvent ? event.text.match(/^\\[EVENT:([^:]+):/)?.[1] : undefined;\n const replyToId = event.thread_ts ? parseInt(event.thread_ts) : null;\n\n const message: ChatMessage = {\n id: event.ts,\n sessionKey: `${event.channel}:${event.thread_ts ?? event.ts}`,\n userId: event.user,\n userName: event.userName,\n text: event.text,\n attachments: event.attachments,\n };\n\n const platform: PlatformInfo = {\n name: \"telegram\",\n formattingGuide: TELEGRAM_FORMATTING_GUIDE,\n channels: [],\n users: [],\n };\n\n // Telegram message length limit is 4096 chars; use 3800 for safety\n const MAX_LENGTH = 3800;\n const truncationNote = \"\\n\\n<i>(message truncated, ask me to elaborate on specific parts)</i>\";\n\n function truncate(text: string, limit: number, note: string): string {\n if (text.length > limit) {\n return text.substring(0, limit - note.length) + note;\n }\n return text;\n }\n\n const responseCtx: ChatResponseContext = {\n respond: async (text: string) => {\n updatePromise = updatePromise.then(async () => {\n try {\n accumulatedText = accumulatedText ? `${accumulatedText}\\n${text}` : text;\n const displayText = truncate(\n isWorking ? accumulatedText + workingIndicator : accumulatedText,\n MAX_LENGTH,\n truncationNote,\n );\n\n if (messageId !== null) {\n await bot.updateMessage(event.channel, String(messageId), displayText);\n } else if (replyToId !== null) {\n messageId = await bot.postReply(parseInt(event.channel), replyToId, displayText);\n } else {\n messageId = await bot.postMessageRaw(parseInt(event.channel), displayText);\n }\n\n if (messageId !== null) {\n bot.logBotResponse(event.channel, text, String(messageId));\n }\n } catch (err) {\n log.logWarning(\n \"Telegram respond error\",\n err instanceof Error ? err.message : String(err),\n );\n }\n });\n await updatePromise;\n },\n\n replaceResponse: async (text: string) => {\n updatePromise = updatePromise.then(async () => {\n try {\n accumulatedText = truncate(text, MAX_LENGTH, truncationNote);\n const displayText = isWorking ? accumulatedText + workingIndicator : accumulatedText;\n\n if (messageId !== null) {\n await bot.updateMessage(event.channel, String(messageId), displayText);\n } else if (replyToId !== null) {\n messageId = await bot.postReply(parseInt(event.channel), replyToId, displayText);\n } else {\n messageId = await bot.postMessageRaw(parseInt(event.channel), displayText);\n }\n } catch (err) {\n log.logWarning(\n \"Telegram replaceResponse error\",\n err instanceof Error ? err.message : String(err),\n );\n }\n });\n await updatePromise;\n },\n\n // Telegram has no threads — discard thread-only messages (e.g. usage summary)\n respondInThread: async (_text: string) => {},\n\n setTyping: async (isTyping: boolean) => {\n if (isTyping && messageId === null) {\n updatePromise = updatePromise.then(async () => {\n try {\n if (messageId === null) {\n await bot.sendTyping(parseInt(event.channel));\n const initialText = eventFilename ? `Starting event: ${eventFilename}` : \"Thinking\";\n accumulatedText = initialText;\n const displayText = accumulatedText + workingIndicator;\n if (replyToId !== null) {\n messageId = await bot.postReply(parseInt(event.channel), replyToId, displayText);\n } else {\n messageId = await bot.postMessageRaw(parseInt(event.channel), displayText);\n }\n }\n } catch (err) {\n log.logWarning(\n \"Telegram setTyping error\",\n err instanceof Error ? err.message : String(err),\n );\n }\n });\n await updatePromise;\n }\n },\n\n setWorking: async (working: boolean) => {\n updatePromise = updatePromise.then(async () => {\n try {\n isWorking = working;\n if (messageId !== null) {\n const displayText = isWorking ? accumulatedText + workingIndicator : accumulatedText;\n await bot.updateMessage(event.channel, String(messageId), displayText);\n }\n } catch (err) {\n log.logWarning(\n \"Telegram setWorking error\",\n err instanceof Error ? err.message : String(err),\n );\n }\n });\n await updatePromise;\n },\n\n uploadFile: async (filePath: string, title?: string) => {\n await bot.uploadFile(event.channel, filePath, title);\n },\n\n deleteResponse: async () => {\n updatePromise = updatePromise.then(async () => {\n if (messageId !== null) {\n try {\n await bot.deleteMessageRaw(parseInt(event.channel), messageId);\n } catch {\n // Ignore errors\n }\n messageId = null;\n }\n });\n await updatePromise;\n },\n };\n\n return { message, responseCtx, platform };\n}\n"]}
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../../src/adapters/telegram/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAEvF,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAE3D,eAAO,MAAM,yBAAyB,kNAGY,CAAC;AAEnD,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,aAAa,EACpB,GAAG,EAAE,WAAW,EAChB,QAAQ,CAAC,EAAE,OAAO,GACjB;IACD,OAAO,EAAE,WAAW,CAAC;IACrB,WAAW,EAAE,mBAAmB,CAAC;IACjC,QAAQ,EAAE,YAAY,CAAC;CACxB,CAsIA","sourcesContent":["import type { ChatMessage, ChatResponseContext, PlatformInfo } from \"../../adapter.js\";\nimport * as log from \"../../log.js\";\nimport type { TelegramBot, TelegramEvent } from \"./bot.js\";\n\nexport const TELEGRAM_FORMATTING_GUIDE = `## 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>\nDo NOT use Markdown asterisks or backtick syntax.`;\n\nexport function createTelegramAdapters(\n event: TelegramEvent,\n bot: TelegramBot,\n _isEvent?: boolean,\n): {\n message: ChatMessage;\n responseCtx: ChatResponseContext;\n platform: PlatformInfo;\n} {\n let messageId: number | null = null;\n let accumulatedText = \"\";\n let updatePromise = Promise.resolve();\n let typingInterval: ReturnType<typeof setInterval> | null = null;\n\n function stopTyping() {\n if (typingInterval !== null) {\n clearInterval(typingInterval);\n typingInterval = null;\n }\n }\n\n const replyToId = event.thread_ts ? parseInt(event.thread_ts) : null;\n\n const message: ChatMessage = {\n id: event.ts,\n sessionKey: `${event.channel}:${event.thread_ts ?? event.ts}`,\n userId: event.user,\n userName: event.userName,\n text: event.text,\n attachments: event.attachments,\n threadTs: event.thread_ts,\n };\n\n const platform: PlatformInfo = {\n name: \"telegram\",\n formattingGuide: TELEGRAM_FORMATTING_GUIDE,\n channels: [],\n users: [],\n };\n\n // Telegram message length limit is 4096 chars; use 3800 for safety\n const MAX_LENGTH = 3800;\n const truncationNote = \"\\n\\n<i>(message truncated, ask me to elaborate on specific parts)</i>\";\n\n function truncate(text: string, limit: number, note: string): string {\n if (text.length > limit) {\n return text.substring(0, limit - note.length) + note;\n }\n return text;\n }\n\n const responseCtx: ChatResponseContext = {\n respond: async (text: string) => {\n updatePromise = updatePromise.then(async () => {\n try {\n accumulatedText = accumulatedText ? `${accumulatedText}\\n${text}` : text;\n const displayText = truncate(accumulatedText, MAX_LENGTH, truncationNote);\n\n if (messageId !== null) {\n await bot.updateMessage(event.channel, String(messageId), displayText);\n } else if (replyToId !== null) {\n messageId = await bot.postReply(parseInt(event.channel), replyToId, displayText);\n } else {\n messageId = await bot.postMessageRaw(parseInt(event.channel), displayText);\n }\n\n if (messageId !== null) {\n bot.logBotResponse(event.channel, text, String(messageId));\n }\n } catch (err) {\n log.logWarning(\n \"Telegram respond error\",\n err instanceof Error ? err.message : String(err),\n );\n }\n });\n await updatePromise;\n },\n\n replaceResponse: async (text: string) => {\n updatePromise = updatePromise.then(async () => {\n try {\n accumulatedText = truncate(text, MAX_LENGTH, truncationNote);\n const displayText = accumulatedText;\n\n if (messageId !== null) {\n await bot.updateMessage(event.channel, String(messageId), displayText);\n } else if (replyToId !== null) {\n messageId = await bot.postReply(parseInt(event.channel), replyToId, displayText);\n } else {\n messageId = await bot.postMessageRaw(parseInt(event.channel), displayText);\n }\n } catch (err) {\n log.logWarning(\n \"Telegram replaceResponse error\",\n err instanceof Error ? err.message : String(err),\n );\n }\n });\n await updatePromise;\n },\n\n // Telegram has no threads — discard thread-only messages (e.g. usage summary)\n respondInThread: async (_text: string) => {},\n\n setTyping: async (isTyping: boolean) => {\n if (isTyping && typingInterval === null) {\n const chatId = parseInt(event.channel);\n // Send immediately and repeat every 4s (Telegram clears indicator after ~5s)\n bot.sendTyping(chatId).catch(() => {});\n typingInterval = setInterval(() => {\n bot.sendTyping(chatId).catch(() => {});\n }, 4000);\n } else if (!isTyping) {\n stopTyping();\n }\n },\n\n setWorking: async (working: boolean) => {\n if (!working) stopTyping();\n },\n\n uploadFile: async (filePath: string, title?: string) => {\n await bot.uploadFile(event.channel, filePath, title);\n },\n\n deleteResponse: async () => {\n updatePromise = updatePromise.then(async () => {\n if (messageId !== null) {\n try {\n await bot.deleteMessageRaw(parseInt(event.channel), messageId);\n } catch {\n // Ignore errors\n }\n messageId = null;\n }\n });\n await updatePromise;\n },\n };\n\n return { message, responseCtx, platform };\n}\n"]}
@@ -3,13 +3,17 @@ export const TELEGRAM_FORMATTING_GUIDE = `## Telegram Formatting (HTML mode)
3
3
  Bold: <b>text</b>, Italic: <i>text</i>, Code: <code>code</code>, Pre: <pre>code</pre>
4
4
  Links: <a href="url">text</a>
5
5
  Do NOT use Markdown asterisks or backtick syntax.`;
6
- export function createTelegramAdapters(event, bot, isEvent) {
6
+ export function createTelegramAdapters(event, bot, _isEvent) {
7
7
  let messageId = null;
8
8
  let accumulatedText = "";
9
- let isWorking = true;
10
- const workingIndicator = " ...";
11
9
  let updatePromise = Promise.resolve();
12
- const eventFilename = isEvent ? event.text.match(/^\[EVENT:([^:]+):/)?.[1] : undefined;
10
+ let typingInterval = null;
11
+ function stopTyping() {
12
+ if (typingInterval !== null) {
13
+ clearInterval(typingInterval);
14
+ typingInterval = null;
15
+ }
16
+ }
13
17
  const replyToId = event.thread_ts ? parseInt(event.thread_ts) : null;
14
18
  const message = {
15
19
  id: event.ts,
@@ -18,6 +22,7 @@ export function createTelegramAdapters(event, bot, isEvent) {
18
22
  userName: event.userName,
19
23
  text: event.text,
20
24
  attachments: event.attachments,
25
+ threadTs: event.thread_ts,
21
26
  };
22
27
  const platform = {
23
28
  name: "telegram",
@@ -39,7 +44,7 @@ export function createTelegramAdapters(event, bot, isEvent) {
39
44
  updatePromise = updatePromise.then(async () => {
40
45
  try {
41
46
  accumulatedText = accumulatedText ? `${accumulatedText}\n${text}` : text;
42
- const displayText = truncate(isWorking ? accumulatedText + workingIndicator : accumulatedText, MAX_LENGTH, truncationNote);
47
+ const displayText = truncate(accumulatedText, MAX_LENGTH, truncationNote);
43
48
  if (messageId !== null) {
44
49
  await bot.updateMessage(event.channel, String(messageId), displayText);
45
50
  }
@@ -63,7 +68,7 @@ export function createTelegramAdapters(event, bot, isEvent) {
63
68
  updatePromise = updatePromise.then(async () => {
64
69
  try {
65
70
  accumulatedText = truncate(text, MAX_LENGTH, truncationNote);
66
- const displayText = isWorking ? accumulatedText + workingIndicator : accumulatedText;
71
+ const displayText = accumulatedText;
67
72
  if (messageId !== null) {
68
73
  await bot.updateMessage(event.channel, String(messageId), displayText);
69
74
  }
@@ -83,43 +88,21 @@ export function createTelegramAdapters(event, bot, isEvent) {
83
88
  // Telegram has no threads — discard thread-only messages (e.g. usage summary)
84
89
  respondInThread: async (_text) => { },
85
90
  setTyping: async (isTyping) => {
86
- if (isTyping && messageId === null) {
87
- updatePromise = updatePromise.then(async () => {
88
- try {
89
- if (messageId === null) {
90
- await bot.sendTyping(parseInt(event.channel));
91
- const initialText = eventFilename ? `Starting event: ${eventFilename}` : "Thinking";
92
- accumulatedText = initialText;
93
- const displayText = accumulatedText + workingIndicator;
94
- if (replyToId !== null) {
95
- messageId = await bot.postReply(parseInt(event.channel), replyToId, displayText);
96
- }
97
- else {
98
- messageId = await bot.postMessageRaw(parseInt(event.channel), displayText);
99
- }
100
- }
101
- }
102
- catch (err) {
103
- log.logWarning("Telegram setTyping error", err instanceof Error ? err.message : String(err));
104
- }
105
- });
106
- await updatePromise;
91
+ if (isTyping && typingInterval === null) {
92
+ const chatId = parseInt(event.channel);
93
+ // Send immediately and repeat every 4s (Telegram clears indicator after ~5s)
94
+ bot.sendTyping(chatId).catch(() => { });
95
+ typingInterval = setInterval(() => {
96
+ bot.sendTyping(chatId).catch(() => { });
97
+ }, 4000);
98
+ }
99
+ else if (!isTyping) {
100
+ stopTyping();
107
101
  }
108
102
  },
109
103
  setWorking: async (working) => {
110
- updatePromise = updatePromise.then(async () => {
111
- try {
112
- isWorking = working;
113
- if (messageId !== null) {
114
- const displayText = isWorking ? accumulatedText + workingIndicator : accumulatedText;
115
- await bot.updateMessage(event.channel, String(messageId), displayText);
116
- }
117
- }
118
- catch (err) {
119
- log.logWarning("Telegram setWorking error", err instanceof Error ? err.message : String(err));
120
- }
121
- });
122
- await updatePromise;
104
+ if (!working)
105
+ stopTyping();
123
106
  },
124
107
  uploadFile: async (filePath, title) => {
125
108
  await bot.uploadFile(event.channel, filePath, title);
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/adapters/telegram/context.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AAGpC,MAAM,CAAC,MAAM,yBAAyB,GAAG;;;kDAGS,CAAC;AAEnD,MAAM,UAAU,sBAAsB,CACpC,KAAoB,EACpB,GAAgB,EAChB,OAAiB;IAMjB,IAAI,SAAS,GAAkB,IAAI,CAAC;IACpC,IAAI,eAAe,GAAG,EAAE,CAAC;IACzB,IAAI,SAAS,GAAG,IAAI,CAAC;IACrB,MAAM,gBAAgB,GAAG,MAAM,CAAC;IAChC,IAAI,aAAa,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;IAEtC,MAAM,aAAa,GAAG,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,mBAAmB,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACvF,MAAM,SAAS,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IAErE,MAAM,OAAO,GAAgB;QAC3B,EAAE,EAAE,KAAK,CAAC,EAAE;QACZ,UAAU,EAAE,GAAG,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,SAAS,IAAI,KAAK,CAAC,EAAE,EAAE;QAC7D,MAAM,EAAE,KAAK,CAAC,IAAI;QAClB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,IAAI,EAAE,KAAK,CAAC,IAA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AC;QACvD,CAAC;QAED,cAAc,EAAE,KAAK,IAAI,EAAE;YACzB,aAAa,GAAG,aAAa,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE;gBAC5C,IAAI,SAAS,KAAK,IAAI,EAAE,CAAC;oBACvB,IAAI,CAAC;wBACH,MAAM,GAAG,CAAC,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,SAAS,CAAC,CAAC;oBACjE,CAAC;oBAAC,MAAM,CAAC;wBACP,gBAAgB;oBAClB,CAAC;oBACD,SAAS,GAAG,IAAI,CAAC;gBACnB,CAAC;YACH,CAAC,CAAC,CAAC;YACH,MAAM,aAAa,CAAC;QACtB,CAAC;KACF,CAAC;IAEF,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC;AAC5C,CAAC","sourcesContent":["import type { ChatMessage, ChatResponseContext, PlatformInfo } from \"../../adapter.js\";\nimport * as log from \"../../log.js\";\nimport type { TelegramBot, TelegramEvent } from \"./bot.js\";\n\nexport const TELEGRAM_FORMATTING_GUIDE = `## 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>\nDo NOT use Markdown asterisks or backtick syntax.`;\n\nexport function createTelegramAdapters(\n event: TelegramEvent,\n bot: TelegramBot,\n isEvent?: boolean,\n): {\n message: ChatMessage;\n responseCtx: ChatResponseContext;\n platform: PlatformInfo;\n} {\n let messageId: number | null = null;\n let accumulatedText = \"\";\n let isWorking = true;\n const workingIndicator = \" ...\";\n let updatePromise = Promise.resolve();\n\n const eventFilename = isEvent ? event.text.match(/^\\[EVENT:([^:]+):/)?.[1] : undefined;\n const replyToId = event.thread_ts ? parseInt(event.thread_ts) : null;\n\n const message: ChatMessage = {\n id: event.ts,\n sessionKey: `${event.channel}:${event.thread_ts ?? event.ts}`,\n userId: event.user,\n userName: event.userName,\n text: event.text,\n attachments: event.attachments,\n };\n\n const platform: PlatformInfo = {\n name: \"telegram\",\n formattingGuide: TELEGRAM_FORMATTING_GUIDE,\n channels: [],\n users: [],\n };\n\n // Telegram message length limit is 4096 chars; use 3800 for safety\n const MAX_LENGTH = 3800;\n const truncationNote = \"\\n\\n<i>(message truncated, ask me to elaborate on specific parts)</i>\";\n\n function truncate(text: string, limit: number, note: string): string {\n if (text.length > limit) {\n return text.substring(0, limit - note.length) + note;\n }\n return text;\n }\n\n const responseCtx: ChatResponseContext = {\n respond: async (text: string) => {\n updatePromise = updatePromise.then(async () => {\n try {\n accumulatedText = accumulatedText ? `${accumulatedText}\\n${text}` : text;\n const displayText = truncate(\n isWorking ? accumulatedText + workingIndicator : accumulatedText,\n MAX_LENGTH,\n truncationNote,\n );\n\n if (messageId !== null) {\n await bot.updateMessage(event.channel, String(messageId), displayText);\n } else if (replyToId !== null) {\n messageId = await bot.postReply(parseInt(event.channel), replyToId, displayText);\n } else {\n messageId = await bot.postMessageRaw(parseInt(event.channel), displayText);\n }\n\n if (messageId !== null) {\n bot.logBotResponse(event.channel, text, String(messageId));\n }\n } catch (err) {\n log.logWarning(\n \"Telegram respond error\",\n err instanceof Error ? err.message : String(err),\n );\n }\n });\n await updatePromise;\n },\n\n replaceResponse: async (text: string) => {\n updatePromise = updatePromise.then(async () => {\n try {\n accumulatedText = truncate(text, MAX_LENGTH, truncationNote);\n const displayText = isWorking ? accumulatedText + workingIndicator : accumulatedText;\n\n if (messageId !== null) {\n await bot.updateMessage(event.channel, String(messageId), displayText);\n } else if (replyToId !== null) {\n messageId = await bot.postReply(parseInt(event.channel), replyToId, displayText);\n } else {\n messageId = await bot.postMessageRaw(parseInt(event.channel), displayText);\n }\n } catch (err) {\n log.logWarning(\n \"Telegram replaceResponse error\",\n err instanceof Error ? err.message : String(err),\n );\n }\n });\n await updatePromise;\n },\n\n // Telegram has no threads — discard thread-only messages (e.g. usage summary)\n respondInThread: async (_text: string) => {},\n\n setTyping: async (isTyping: boolean) => {\n if (isTyping && messageId === null) {\n updatePromise = updatePromise.then(async () => {\n try {\n if (messageId === null) {\n await bot.sendTyping(parseInt(event.channel));\n const initialText = eventFilename ? `Starting event: ${eventFilename}` : \"Thinking\";\n accumulatedText = initialText;\n const displayText = accumulatedText + workingIndicator;\n if (replyToId !== null) {\n messageId = await bot.postReply(parseInt(event.channel), replyToId, displayText);\n } else {\n messageId = await bot.postMessageRaw(parseInt(event.channel), displayText);\n }\n }\n } catch (err) {\n log.logWarning(\n \"Telegram setTyping error\",\n err instanceof Error ? err.message : String(err),\n );\n }\n });\n await updatePromise;\n }\n },\n\n setWorking: async (working: boolean) => {\n updatePromise = updatePromise.then(async () => {\n try {\n isWorking = working;\n if (messageId !== null) {\n const displayText = isWorking ? accumulatedText + workingIndicator : accumulatedText;\n await bot.updateMessage(event.channel, String(messageId), displayText);\n }\n } catch (err) {\n log.logWarning(\n \"Telegram setWorking error\",\n err instanceof Error ? err.message : String(err),\n );\n }\n });\n await updatePromise;\n },\n\n uploadFile: async (filePath: string, title?: string) => {\n await bot.uploadFile(event.channel, filePath, title);\n },\n\n deleteResponse: async () => {\n updatePromise = updatePromise.then(async () => {\n if (messageId !== null) {\n try {\n await bot.deleteMessageRaw(parseInt(event.channel), messageId);\n } catch {\n // Ignore errors\n }\n messageId = null;\n }\n });\n await updatePromise;\n },\n };\n\n return { message, responseCtx, platform };\n}\n"]}
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/adapters/telegram/context.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AAGpC,MAAM,CAAC,MAAM,yBAAyB,GAAG;;;kDAGS,CAAC;AAEnD,MAAM,UAAU,sBAAsB,CACpC,KAAoB,EACpB,GAAgB,EAChB,QAAkB;IAMlB,IAAI,SAAS,GAAkB,IAAI,CAAC;IACpC,IAAI,eAAe,GAAG,EAAE,CAAC;IACzB,IAAI,aAAa,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;IACtC,IAAI,cAAc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AAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;gBACvC,cAAc,GAAG,WAAW,CAAC,GAAG,EAAE;oBAChC,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;gBACzC,CAAC,EAAE,IAAI,CAAC,CAAC;YACX,CAAC;iBAAM,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACrB,UAAU,EAAE,CAAC;YACf,CAAC;QACH,CAAC;QAED,UAAU,EAAE,KAAK,EAAE,OAAgB,EAAE,EAAE;YACrC,IAAI,CAAC,OAAO;gBAAE,UAAU,EAAE,CAAC;QAC7B,CAAC;QAED,UAAU,EAAE,KAAK,EAAE,QAAgB,EAAE,KAAc,EAAE,EAAE;YACrD,MAAM,GAAG,CAAC,UAAU,CAAC,KAAK,CAAC,OAAO,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;QACvD,CAAC;QAED,cAAc,EAAE,KAAK,IAAI,EAAE;YACzB,aAAa,GAAG,aAAa,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE;gBAC5C,IAAI,SAAS,KAAK,IAAI,EAAE,CAAC;oBACvB,IAAI,CAAC;wBACH,MAAM,GAAG,CAAC,gBAAgB,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,SAAS,CAAC,CAAC;oBACjE,CAAC;oBAAC,MAAM,CAAC;wBACP,gBAAgB;oBAClB,CAAC;oBACD,SAAS,GAAG,IAAI,CAAC;gBACnB,CAAC;YACH,CAAC,CAAC,CAAC;YACH,MAAM,aAAa,CAAC;QACtB,CAAC;KACF,CAAC;IAEF,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC;AAC5C,CAAC","sourcesContent":["import type { ChatMessage, ChatResponseContext, PlatformInfo } from \"../../adapter.js\";\nimport * as log from \"../../log.js\";\nimport type { TelegramBot, TelegramEvent } from \"./bot.js\";\n\nexport const TELEGRAM_FORMATTING_GUIDE = `## 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>\nDo NOT use Markdown asterisks or backtick syntax.`;\n\nexport function createTelegramAdapters(\n event: TelegramEvent,\n bot: TelegramBot,\n _isEvent?: boolean,\n): {\n message: ChatMessage;\n responseCtx: ChatResponseContext;\n platform: PlatformInfo;\n} {\n let messageId: number | null = null;\n let accumulatedText = \"\";\n let updatePromise = Promise.resolve();\n let typingInterval: ReturnType<typeof setInterval> | null = null;\n\n function stopTyping() {\n if (typingInterval !== null) {\n clearInterval(typingInterval);\n typingInterval = null;\n }\n }\n\n const replyToId = event.thread_ts ? parseInt(event.thread_ts) : null;\n\n const message: ChatMessage = {\n id: event.ts,\n sessionKey: `${event.channel}:${event.thread_ts ?? event.ts}`,\n userId: event.user,\n userName: event.userName,\n text: event.text,\n attachments: event.attachments,\n threadTs: event.thread_ts,\n };\n\n const platform: PlatformInfo = {\n name: \"telegram\",\n formattingGuide: TELEGRAM_FORMATTING_GUIDE,\n channels: [],\n users: [],\n };\n\n // Telegram message length limit is 4096 chars; use 3800 for safety\n const MAX_LENGTH = 3800;\n const truncationNote = \"\\n\\n<i>(message truncated, ask me to elaborate on specific parts)</i>\";\n\n function truncate(text: string, limit: number, note: string): string {\n if (text.length > limit) {\n return text.substring(0, limit - note.length) + note;\n }\n return text;\n }\n\n const responseCtx: ChatResponseContext = {\n respond: async (text: string) => {\n updatePromise = updatePromise.then(async () => {\n try {\n accumulatedText = accumulatedText ? `${accumulatedText}\\n${text}` : text;\n const displayText = truncate(accumulatedText, MAX_LENGTH, truncationNote);\n\n if (messageId !== null) {\n await bot.updateMessage(event.channel, String(messageId), displayText);\n } else if (replyToId !== null) {\n messageId = await bot.postReply(parseInt(event.channel), replyToId, displayText);\n } else {\n messageId = await bot.postMessageRaw(parseInt(event.channel), displayText);\n }\n\n if (messageId !== null) {\n bot.logBotResponse(event.channel, text, String(messageId));\n }\n } catch (err) {\n log.logWarning(\n \"Telegram respond error\",\n err instanceof Error ? err.message : String(err),\n );\n }\n });\n await updatePromise;\n },\n\n replaceResponse: async (text: string) => {\n updatePromise = updatePromise.then(async () => {\n try {\n accumulatedText = truncate(text, MAX_LENGTH, truncationNote);\n const displayText = accumulatedText;\n\n if (messageId !== null) {\n await bot.updateMessage(event.channel, String(messageId), displayText);\n } else if (replyToId !== null) {\n messageId = await bot.postReply(parseInt(event.channel), replyToId, displayText);\n } else {\n messageId = await bot.postMessageRaw(parseInt(event.channel), displayText);\n }\n } catch (err) {\n log.logWarning(\n \"Telegram replaceResponse error\",\n err instanceof Error ? err.message : String(err),\n );\n }\n });\n await updatePromise;\n },\n\n // Telegram has no threads — discard thread-only messages (e.g. usage summary)\n respondInThread: async (_text: string) => {},\n\n setTyping: async (isTyping: boolean) => {\n if (isTyping && typingInterval === null) {\n const chatId = parseInt(event.channel);\n // Send immediately and repeat every 4s (Telegram clears indicator after ~5s)\n bot.sendTyping(chatId).catch(() => {});\n typingInterval = setInterval(() => {\n bot.sendTyping(chatId).catch(() => {});\n }, 4000);\n } else if (!isTyping) {\n stopTyping();\n }\n },\n\n setWorking: async (working: boolean) => {\n if (!working) stopTyping();\n },\n\n uploadFile: async (filePath: string, title?: string) => {\n await bot.uploadFile(event.channel, filePath, title);\n },\n\n deleteResponse: async () => {\n updatePromise = updatePromise.then(async () => {\n if (messageId !== null) {\n try {\n await bot.deleteMessageRaw(parseInt(event.channel), messageId);\n } catch {\n // Ignore errors\n }\n messageId = null;\n }\n });\n await updatePromise;\n },\n };\n\n return { message, responseCtx, platform };\n}\n"]}
package/dist/agent.d.ts CHANGED
@@ -14,6 +14,11 @@ export interface AgentRunner {
14
14
  errorMessage?: string;
15
15
  }>;
16
16
  abort(): void;
17
+ /** Get current step info (tool name, label) for debugging */
18
+ getCurrentStep(): {
19
+ toolName?: string;
20
+ label?: string;
21
+ } | undefined;
17
22
  }
18
23
  /**
19
24
  * Create a new AgentRunner for a channel.
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAInF,OAAO,EAAkB,KAAK,aAAa,EAAE,MAAM,cAAc,CAAC;AAGlE,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACjC,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,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;CACf;AAqVD;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,aAAa,EAAE,aAAa,EAC5B,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,WAAW,CAAC,CAmhBtB","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 createExtensionRuntime,\n formatSkillsForPrompt,\n loadSkillsFromDir,\n ModelRegistry,\n type ResourceLoader,\n SessionManager,\n type Skill,\n} from \"@mariozechner/pi-coding-agent\";\nimport { existsSync, mkdirSync, readFileSync } from \"fs\";\nimport { mkdir, readFile, writeFile } from \"fs/promises\";\nimport { homedir } from \"os\";\nimport { join } from \"path\";\nimport type { ChatMessage, ChatResponseContext, PlatformInfo } from \"./adapter.js\";\nimport { loadAgentConfig } from \"./config.js\";\nimport { createMamaSettingsManager, syncLogToSessionManager } from \"./context.js\";\nimport * as log from \"./log.js\";\nimport { createExecutor, type SandboxConfig } from \"./sandbox.js\";\nimport { createMamaTools } from \"./tools/index.js\";\n\nexport interface PendingMessage {\n userName: string;\n text: string;\n attachments: { local: string }[];\n timestamp: number;\n}\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}\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\nasync function getMemory(channelDir: string): Promise<string> {\n const parts: string[] = [];\n\n // Read workspace-level memory (shared across all channels)\n const workspaceMemoryPath = join(channelDir, \"..\", \"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 channel-specific memory\n const channelMemoryPath = join(channelDir, \"MEMORY.md\");\n if (existsSync(channelMemoryPath)) {\n try {\n const content = (await readFile(channelMemoryPath, \"utf-8\")).trim();\n if (content) {\n parts.push(`### Channel-Specific Memory\\n${content}`);\n }\n } catch (error) {\n log.logWarning(\"Failed to read channel memory\", `${channelMemoryPath}: ${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(channelDir: string, workspacePath: string): Skill[] {\n const skillMap = new Map<string, Skill>();\n\n // channelDir 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(channelDir, \"..\");\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 channel-specific skills (override workspace skills on collision)\n const channelSkillsDir = join(channelDir, \"skills\");\n for (const skill of loadSkillsFromDir({ dir: channelSkillsDir, 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 channelId: string,\n memory: string,\n sandboxConfig: SandboxConfig,\n platform: PlatformInfo,\n skills: Skill[],\n): string {\n const channelPath = `${workspacePath}/${channelId}`;\n const isDocker = sandboxConfig.type === \"docker\";\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 = isDocker\n ? `You are running inside a Docker container (Alpine Linux).\n- Bash working directory: / (use cd or absolute paths)\n- Install tools with: apk add <package>\n- Your changes persist across sessions`\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 history beyond your context, search log.jsonl (contains user messages and your final responses, but not tool results).\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 channels)\n├── skills/ # Global CLI tools you create\n└── ${channelId}/ # This channel\n ├── MEMORY.md # Channel-specific memory\n ├── log.jsonl # Message history (no tool results)\n ├── attachments/ # User-shared files\n ├── scratch/ # Your working directory\n └── skills/ # Channel-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 \\`${channelPath}/skills/<name>/\\` (channel-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\", \"channelId\": \"${channelId}\", \"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\", \"channelId\": \"${channelId}\", \"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\", \"channelId\": \"${channelId}\", \"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### 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\", \"channelId\": \"${channelId}\", \"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- Channel (${channelPath}/MEMORY.md): channel-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 (apk add, npm install, 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).\n${isDocker ? \"Install jq: apk add 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\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\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\nfunction formatToolArgsForSlack(_toolName: string, args: Record<string, unknown>): string {\n const lines: string[] = [];\n\n for (const [key, value] of Object.entries(args)) {\n if (key === \"label\") continue;\n\n if (key === \"path\" && typeof value === \"string\") {\n const offset = args.offset as number | undefined;\n const limit = args.limit as number | undefined;\n if (offset !== undefined && limit !== undefined) {\n lines.push(`${value}:${offset}-${offset + limit}`);\n } else {\n lines.push(value);\n }\n continue;\n }\n\n if (key === \"offset\" || key === \"limit\") continue;\n\n if (typeof value === \"string\") {\n lines.push(value);\n } else {\n lines.push(JSON.stringify(value));\n }\n }\n\n return lines.join(\"\\n\");\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 channelId: string,\n channelDir: string,\n workspaceDir: string,\n): Promise<AgentRunner> {\n const agentConfig = loadAgentConfig(workspaceDir);\n\n // Initialize logger with settings from config\n log.initLogger({\n logFormat: agentConfig.logFormat,\n logLevel: agentConfig.logLevel,\n });\n\n const executor = createExecutor(sandboxConfig);\n const workspacePath = executor.getWorkspacePath(channelDir.replace(`/${channelId}`, \"\"));\n\n // Create tools (per-runner, with per-runner upload function setter)\n const { tools, setUploadFunction } = createMamaTools(executor);\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(channelDir);\n const skills = loadMamaSkills(channelDir, workspacePath);\n const emptyPlatform: PlatformInfo = {\n name: \"slack\",\n formattingGuide: \"\",\n channels: [],\n users: [],\n };\n const systemPrompt = buildSystemPrompt(\n workspacePath,\n channelId,\n memory,\n sandboxConfig,\n emptyPlatform,\n skills,\n );\n\n // Create session manager and settings manager\n // Per-session context file: {channelDir}/sessions/{rootTs}/context.jsonl\n const rootTs = sessionKey.includes(\":\") ? sessionKey.split(\":\").pop()! : sessionKey;\n const sessionDir = join(channelDir, \"sessions\", rootTs);\n mkdirSync(sessionDir, { recursive: true });\n const contextFile = join(sessionDir, \"context.jsonl\");\n const sessionManager = SessionManager.open(contextFile, channelDir);\n const settingsManager = createMamaSettingsManager(join(channelDir, \"..\"));\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 = new ModelRegistry(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.getApiKey(model);\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.replaceMessages(loadedSession.messages);\n log.logInfo(\n `[${channelId}] Loaded ${loadedSession.messages.length} messages from context.jsonl`,\n );\n }\n\n const resourceLoader: ResourceLoader = {\n getExtensions: () => ({ extensions: [], errors: [], runtime: createExtensionRuntime() }),\n getSkills: () => ({ skills: [], diagnostics: [] }),\n getPrompts: () => ({ prompts: [], diagnostics: [] }),\n getThemes: () => ({ themes: [], diagnostics: [] }),\n getAgentsFiles: () => ({ agentsFiles: [] }),\n getSystemPrompt: () => systemPrompt,\n getAppendSystemPrompt: () => [],\n getPathMetadata: () => new Map(),\n extendResources: () => {},\n reload: async () => {},\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: process.cwd(),\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 { channelId: string; userName?: string; channelName?: string } | null,\n queue: null as {\n enqueue(fn: () => Promise<void>, errorContext: string): void;\n enqueueMessage(\n text: string,\n target: \"main\" | \"thread\",\n errorContext: string,\n doLog?: boolean,\n ): 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 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\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\n log.logToolStart(\n logCtx,\n agentEvent.toolName,\n label,\n agentEvent.args as Record<string, unknown>,\n );\n queue.enqueue(() => responseCtx.respond(`_→ ${label}_`), \"tool label\");\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 if (agentEvent.isError) {\n log.logToolError(logCtx, agentEvent.toolName, durationMs, resultStr);\n } else {\n log.logToolSuccess(logCtx, agentEvent.toolName, durationMs, resultStr);\n }\n\n // Post args + result to thread\n const label = pending?.args ? (pending.args as { label?: string }).label : undefined;\n const argsFormatted = pending\n ? formatToolArgsForSlack(agentEvent.toolName, pending.args as Record<string, unknown>)\n : \"(args not found)\";\n const duration = (durationMs / 1000).toFixed(1);\n let threadMessage = `*${agentEvent.isError ? \"✗\" : \"✓\"} ${agentEvent.toolName}*`;\n if (label) threadMessage += `: ${label}`;\n threadMessage += ` (${duration}s)\\n`;\n if (argsFormatted) threadMessage += `\\`\\`\\`\\n${argsFormatted}\\n\\`\\`\\`\\n`;\n threadMessage += `*Result:*\\n\\`\\`\\`\\n${resultStr}\\n\\`\\`\\``;\n\n queue.enqueueMessage(threadMessage, \"thread\", \"tool result thread\", false);\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 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\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.enqueueMessage(`_${thinking}_`, \"main\", \"thinking main\");\n queue.enqueueMessage(`_${thinking}_`, \"thread\", \"thinking thread\", false);\n }\n\n if (text.trim()) {\n log.logResponse(logCtx, text);\n queue.enqueueMessage(text, \"main\", \"response main\");\n queue.enqueueMessage(text, \"thread\", \"response thread\", false);\n }\n }\n } else if (event.type === \"auto_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 === \"auto_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 // Message limit constant\n const SLACK_MAX_LENGTH = 40000;\n const splitForSlack = (text: string): string[] => {\n if (text.length <= SLACK_MAX_LENGTH) return [text];\n const parts: string[] = [];\n let remaining = text;\n let partNum = 1;\n while (remaining.length > 0) {\n const chunk = remaining.substring(0, SLACK_MAX_LENGTH - 50);\n remaining = remaining.substring(SLACK_MAX_LENGTH - 50);\n const suffix = remaining.length > 0 ? `\\n_(continued ${partNum}...)_` : \"\";\n parts.push(chunk + suffix);\n partNum++;\n }\n return parts;\n };\n\n return {\n async run(\n message: ChatMessage,\n responseCtx: ChatResponseContext,\n platform: PlatformInfo,\n ): Promise<{ stopReason: string; errorMessage?: string }> {\n // Extract channelId from sessionKey (format: \"channelId:rootTs\" or just \"channelId\")\n const sessionChannel = message.sessionKey.split(\":\")[0];\n\n // Ensure channel directory exists\n await mkdir(channelDir, { recursive: true });\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 const syncedCount = await syncLogToSessionManager(sessionManager, channelDir, message.id);\n if (syncedCount > 0) {\n log.logInfo(`[${channelId}] 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.replaceMessages(reloadedSession.messages);\n log.logInfo(\n `[${channelId}] 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(channelDir);\n const skills = loadMamaSkills(channelDir, workspacePath);\n const systemPrompt = buildSystemPrompt(\n workspacePath,\n channelId,\n memory,\n sandboxConfig,\n platform,\n skills,\n );\n session.agent.setSystemPrompt(systemPrompt);\n\n // Set up file upload function\n setUploadFunction(async (filePath: string, title?: string) => {\n const hostPath = translateToHostPath(filePath, channelDir, workspacePath, channelId);\n await responseCtx.uploadFile(hostPath, title);\n });\n\n // Reset per-run state\n runState.responseCtx = responseCtx;\n runState.logCtx = {\n channelId: sessionChannel,\n userName: message.userName,\n channelName: undefined,\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.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.respondInThread(`_Error: ${errMsg}_`);\n } catch {\n // Ignore\n }\n }\n });\n },\n enqueueMessage(\n text: string,\n target: \"main\" | \"thread\",\n errorContext: string,\n _doLog = true,\n ): void {\n const parts = splitForSlack(text);\n for (const part of parts) {\n this.enqueue(\n () =>\n target === \"main\" ? responseCtx.respond(part) : responseCtx.respondInThread(part),\n errorContext,\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 let userMessage = `[${timestamp}] [${message.userName || \"unknown\"}]: ${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 (same as old a.local)\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(join(channelDir, \"last_prompt.jsonl\"), JSON.stringify(debugContext, null, 2));\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.respondInThread(`_Error: ${runState.errorMessage}_`);\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 const mainText =\n finalText.length > SLACK_MAX_LENGTH\n ? `${finalText.substring(0, SLACK_MAX_LENGTH - 50)}\\n\\n_(see thread for full response)_`\n : finalText;\n await responseCtx.replaceResponse(mainText);\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 const summary = log.logUsageSummary(\n runState.logCtx!,\n runState.totalUsage,\n contextTokens,\n contextWindow,\n );\n runState.queue.enqueue(() => responseCtx.respondInThread(summary), \"usage summary\");\n await queueChain;\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}\n\n/**\n * Translate container path back to host path for file operations\n */\nfunction translateToHostPath(\n containerPath: string,\n channelDir: string,\n workspacePath: string,\n channelId: string,\n): string {\n if (workspacePath === \"/workspace\") {\n const prefix = `/workspace/${channelId}/`;\n if (containerPath.startsWith(prefix)) {\n return join(channelDir, containerPath.slice(prefix.length));\n }\n if (containerPath.startsWith(\"/workspace/\")) {\n return join(channelDir, \"..\", 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":"AAkBA,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAInF,OAAO,EAAkB,KAAK,aAAa,EAAE,MAAM,cAAc,CAAC;AAGlE,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACjC,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,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;AAgWD;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,aAAa,EAAE,aAAa,EAC5B,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,WAAW,CAAC,CA8jBtB","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 createExtensionRuntime,\n formatSkillsForPrompt,\n loadSkillsFromDir,\n ModelRegistry,\n type ResourceLoader,\n SessionManager,\n type Skill,\n} from \"@mariozechner/pi-coding-agent\";\nimport { existsSync, mkdirSync, readFileSync } from \"fs\";\nimport { mkdir, readFile, writeFile } from \"fs/promises\";\nimport { homedir } from \"os\";\nimport { join } from \"path\";\nimport type { ChatMessage, ChatResponseContext, PlatformInfo } from \"./adapter.js\";\nimport { loadAgentConfig } from \"./config.js\";\nimport { createMamaSettingsManager, syncLogToSessionManager } from \"./context.js\";\nimport * as log from \"./log.js\";\nimport { createExecutor, type SandboxConfig } from \"./sandbox.js\";\nimport { createMamaTools } from \"./tools/index.js\";\n\nexport interface PendingMessage {\n userName: string;\n text: string;\n attachments: { local: string }[];\n timestamp: number;\n}\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\nasync function getMemory(channelDir: string): Promise<string> {\n const parts: string[] = [];\n\n // Read workspace-level memory (shared across all channels)\n const workspaceMemoryPath = join(channelDir, \"..\", \"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 channel-specific memory\n const channelMemoryPath = join(channelDir, \"MEMORY.md\");\n if (existsSync(channelMemoryPath)) {\n try {\n const content = (await readFile(channelMemoryPath, \"utf-8\")).trim();\n if (content) {\n parts.push(`### Channel-Specific Memory\\n${content}`);\n }\n } catch (error) {\n log.logWarning(\"Failed to read channel memory\", `${channelMemoryPath}: ${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(channelDir: string, workspacePath: string): Skill[] {\n const skillMap = new Map<string, Skill>();\n\n // channelDir 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(channelDir, \"..\");\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 channel-specific skills (override workspace skills on collision)\n const channelSkillsDir = join(channelDir, \"skills\");\n for (const skill of loadSkillsFromDir({ dir: channelSkillsDir, 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 channelId: string,\n memory: string,\n sandboxConfig: SandboxConfig,\n platform: PlatformInfo,\n skills: Skill[],\n): string {\n const channelPath = `${workspacePath}/${channelId}`;\n const isDocker = sandboxConfig.type === \"docker\";\n const isFirecracker = sandboxConfig.type === \"firecracker\";\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 = isDocker\n ? `You are running inside a Docker container (Alpine Linux).\n- Bash working directory: / (use cd or absolute paths)\n- Install tools with: apk add <package>\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 : `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 history beyond your context, search log.jsonl (contains user messages and your final responses, but not tool results).\n- User messages include a \\`[in-thread:TS]\\` marker when sent from within a Slack thread (TS is the root message timestamp). Without this marker, the message is a top-level channel 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 channels)\n├── skills/ # Global CLI tools you create\n└── ${channelId}/ # This channel\n ├── MEMORY.md # Channel-specific memory\n ├── log.jsonl # Message history (no tool results)\n ├── attachments/ # User-shared files\n ├── scratch/ # Your working directory\n └── skills/ # Channel-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 \\`${channelPath}/skills/<name>/\\` (channel-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}\", \"channelId\": \"${channelId}\", \"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}\", \"channelId\": \"${channelId}\", \"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}\", \"channelId\": \"${channelId}\", \"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 Routing\nSet \\`platform\\` to the target bot platform (\\`${platform.name}\\` for this conversation). When only one platform is running, omitting \\`platform\\` is allowed for backward compatibility, but include it by default to avoid ambiguity.\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}\", \"channelId\": \"${channelId}\", \"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- Channel (${channelPath}/MEMORY.md): channel-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 (apk add, npm install, 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).\n${isDocker ? \"Install jq: apk add 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\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\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\nfunction formatToolArgsForSlack(_toolName: string, args: Record<string, unknown>): string {\n const lines: string[] = [];\n\n for (const [key, value] of Object.entries(args)) {\n if (key === \"label\") continue;\n\n if (key === \"path\" && typeof value === \"string\") {\n const offset = args.offset as number | undefined;\n const limit = args.limit as number | undefined;\n if (offset !== undefined && limit !== undefined) {\n lines.push(`${value}:${offset}-${offset + limit}`);\n } else {\n lines.push(value);\n }\n continue;\n }\n\n if (key === \"offset\" || key === \"limit\") continue;\n\n if (typeof value === \"string\") {\n lines.push(value);\n } else {\n lines.push(JSON.stringify(value));\n }\n }\n\n return lines.join(\"\\n\");\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 channelId: string,\n channelDir: string,\n workspaceDir: string,\n): Promise<AgentRunner> {\n const agentConfig = loadAgentConfig(workspaceDir);\n\n // Initialize logger with settings from config\n log.initLogger({\n logFormat: agentConfig.logFormat,\n logLevel: agentConfig.logLevel,\n });\n\n const executor = createExecutor(sandboxConfig);\n const workspacePath = executor.getWorkspacePath(channelDir.replace(`/${channelId}`, \"\"));\n\n // Create tools (per-runner, with per-runner upload function setter)\n const { tools, setUploadFunction } = createMamaTools(executor);\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(channelDir);\n const skills = loadMamaSkills(channelDir, workspacePath);\n const emptyPlatform: PlatformInfo = {\n name: \"slack\",\n formattingGuide: \"\",\n channels: [],\n users: [],\n };\n const systemPrompt = buildSystemPrompt(\n workspacePath,\n channelId,\n memory,\n sandboxConfig,\n emptyPlatform,\n skills,\n );\n\n // Create session manager and settings manager\n // Per-session context file: {channelDir}/sessions/{rootTs}/context.jsonl\n const rootTs = sessionKey.includes(\":\") ? sessionKey.split(\":\").pop()! : sessionKey;\n const sessionDir = join(channelDir, \"sessions\", rootTs);\n mkdirSync(sessionDir, { recursive: true });\n const contextFile = join(sessionDir, \"context.jsonl\");\n const sessionManager = SessionManager.open(contextFile, channelDir);\n const settingsManager = createMamaSettingsManager(join(channelDir, \"..\"));\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 = new ModelRegistry(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.replaceMessages(loadedSession.messages);\n log.logInfo(\n `[${channelId}] Loaded ${loadedSession.messages.length} messages from context.jsonl`,\n );\n }\n\n const resourceLoader: ResourceLoader = {\n getExtensions: () => ({ extensions: [], errors: [], runtime: createExtensionRuntime() }),\n getSkills: () => ({ skills: [], diagnostics: [] }),\n getPrompts: () => ({ prompts: [], diagnostics: [] }),\n getThemes: () => ({ themes: [], diagnostics: [] }),\n getAgentsFiles: () => ({ agentsFiles: [] }),\n getSystemPrompt: () => systemPrompt,\n getAppendSystemPrompt: () => [],\n extendResources: () => {},\n reload: async () => {},\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: process.cwd(),\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 { channelId: string; userName?: string; channelName?: string } | null,\n queue: null as {\n enqueue(fn: () => Promise<void>, errorContext: string): void;\n enqueueMessage(\n text: string,\n target: \"main\" | \"thread\",\n errorContext: string,\n doLog?: boolean,\n ): 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 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\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\n log.logToolStart(\n logCtx,\n agentEvent.toolName,\n label,\n agentEvent.args as Record<string, unknown>,\n );\n // Tool labels are omitted from the main message to reduce Slack noise.\n // Tool execution details are still posted to the thread (see tool_execution_end).\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 if (agentEvent.isError) {\n log.logToolError(logCtx, agentEvent.toolName, durationMs, resultStr);\n } else {\n log.logToolSuccess(logCtx, agentEvent.toolName, durationMs, resultStr);\n }\n\n // Post args + result to thread\n const label = pending?.args ? (pending.args as { label?: string }).label : undefined;\n const argsFormatted = pending\n ? formatToolArgsForSlack(agentEvent.toolName, pending.args as Record<string, unknown>)\n : \"(args not found)\";\n const duration = (durationMs / 1000).toFixed(1);\n let threadMessage = `*${agentEvent.isError ? \"✗\" : \"✓\"} ${agentEvent.toolName}*`;\n if (label) threadMessage += `: ${label}`;\n threadMessage += ` (${duration}s)\\n`;\n if (argsFormatted) threadMessage += `\\`\\`\\`\\n${argsFormatted}\\n\\`\\`\\`\\n`;\n threadMessage += `*Result:*\\n\\`\\`\\`\\n${resultStr}\\n\\`\\`\\``;\n\n // Only post thread details for tools with meaningful output (bash, attach).\n // Skip read/write/edit to reduce Slack noise — their results are in the log.\n const quietTools = new Set([\"read\", \"write\", \"edit\"]);\n if (!quietTools.has(agentEvent.toolName)) {\n queue.enqueueMessage(threadMessage, \"thread\", \"tool result thread\", false);\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 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\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.enqueueMessage(`_${thinking}_`, \"main\", \"thinking main\");\n queue.enqueueMessage(`_${thinking}_`, \"thread\", \"thinking thread\", false);\n }\n\n if (text.trim()) {\n log.logResponse(logCtx, text);\n queue.enqueueMessage(text, \"main\", \"response main\");\n // Only overflow to thread for texts that will be truncated in main\n if (text.length > SLACK_MAX_LENGTH) {\n queue.enqueueMessage(text, \"thread\", \"response thread\", false);\n }\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 // Message limit constant\n const SLACK_MAX_LENGTH = 40000;\n const splitForSlack = (text: string): string[] => {\n if (text.length <= SLACK_MAX_LENGTH) return [text];\n const parts: string[] = [];\n let remaining = text;\n let partNum = 1;\n while (remaining.length > 0) {\n const chunk = remaining.substring(0, SLACK_MAX_LENGTH - 50);\n remaining = remaining.substring(SLACK_MAX_LENGTH - 50);\n const suffix = remaining.length > 0 ? `\\n_(continued ${partNum}...)_` : \"\";\n parts.push(chunk + suffix);\n partNum++;\n }\n return parts;\n };\n\n return {\n async run(\n message: ChatMessage,\n responseCtx: ChatResponseContext,\n platform: PlatformInfo,\n ): Promise<{ stopReason: string; errorMessage?: string }> {\n // Extract channelId from sessionKey (format: \"channelId:rootTs\" or just \"channelId\")\n const sessionChannel = message.sessionKey.split(\":\")[0];\n\n // Ensure channel directory exists\n await mkdir(channelDir, { recursive: true });\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 syncedCount = await syncLogToSessionManager(\n sessionManager,\n channelDir,\n message.id,\n undefined,\n { rootTs, threadTs: message.threadTs },\n );\n if (syncedCount > 0) {\n log.logInfo(`[${channelId}] 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.replaceMessages(reloadedSession.messages);\n log.logInfo(\n `[${channelId}] 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(channelDir);\n const skills = loadMamaSkills(channelDir, workspacePath);\n const systemPrompt = buildSystemPrompt(\n workspacePath,\n channelId,\n memory,\n sandboxConfig,\n platform,\n skills,\n );\n session.agent.setSystemPrompt(systemPrompt);\n\n // Set up file upload function\n setUploadFunction(async (filePath: string, title?: string) => {\n const hostPath = translateToHostPath(filePath, channelDir, workspacePath, channelId);\n await responseCtx.uploadFile(hostPath, title);\n });\n\n // Reset per-run state\n runState.responseCtx = responseCtx;\n runState.logCtx = {\n channelId: sessionChannel,\n userName: message.userName,\n channelName: undefined,\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.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 // Split long error messages to avoid msg_too_long\n const errParts = splitForSlack(`_Error: ${errMsg}_`);\n for (const part of errParts) {\n await responseCtx.respondInThread(part);\n }\n } catch {\n // Ignore\n }\n }\n });\n },\n enqueueMessage(\n text: string,\n target: \"main\" | \"thread\",\n errorContext: string,\n _doLog = true,\n ): void {\n const parts = splitForSlack(text);\n for (const part of parts) {\n this.enqueue(\n () =>\n target === \"main\" ? responseCtx.respond(part) : responseCtx.respondInThread(part),\n errorContext,\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 (same as old a.local)\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(join(channelDir, \"last_prompt.jsonl\"), JSON.stringify(debugContext, null, 2));\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 // Split long error messages to avoid msg_too_long\n const errorParts = splitForSlack(`_Error: ${runState.errorMessage}_`);\n for (const part of errorParts) {\n await responseCtx.respondInThread(part);\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 const mainText =\n finalText.length > SLACK_MAX_LENGTH\n ? `${finalText.substring(0, SLACK_MAX_LENGTH - 50)}\\n\\n_(see thread for full response)_`\n : finalText;\n await responseCtx.replaceResponse(mainText);\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 const summary = log.logUsageSummary(\n runState.logCtx!,\n runState.totalUsage,\n contextTokens,\n contextWindow,\n );\n // Split long summaries to avoid msg_too_long\n const summaryParts = splitForSlack(summary);\n for (const part of summaryParts) {\n runState.queue!.enqueue(\n () => responseCtx.respondInThread(part, { style: \"muted\" }),\n \"usage summary\",\n );\n }\n await queueChain;\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 channelDir: string,\n workspacePath: string,\n channelId: string,\n): string {\n if (workspacePath === \"/workspace\") {\n const prefix = `/workspace/${channelId}/`;\n if (containerPath.startsWith(prefix)) {\n return join(channelDir, containerPath.slice(prefix.length));\n }\n if (containerPath.startsWith(\"/workspace/\")) {\n return join(channelDir, \"..\", containerPath.slice(\"/workspace/\".length));\n }\n }\n return containerPath;\n}\n"]}
package/dist/agent.js CHANGED
@@ -86,6 +86,7 @@ function loadMamaSkills(channelDir, workspacePath) {
86
86
  function buildSystemPrompt(workspacePath, channelId, memory, sandboxConfig, platform, skills) {
87
87
  const channelPath = `${workspacePath}/${channelId}`;
88
88
  const isDocker = sandboxConfig.type === "docker";
89
+ const isFirecracker = sandboxConfig.type === "firecracker";
89
90
  // Format channel mappings
90
91
  const channelMappings = platform.channels.length > 0
91
92
  ? platform.channels.map((c) => `${c.id}\t#${c.name}`).join("\n")
@@ -99,7 +100,12 @@ function buildSystemPrompt(workspacePath, channelId, memory, sandboxConfig, plat
99
100
  - Bash working directory: / (use cd or absolute paths)
100
101
  - Install tools with: apk add <package>
101
102
  - Your changes persist across sessions`
102
- : `You are running directly on the host machine.
103
+ : isFirecracker
104
+ ? `You are running inside a Firecracker microVM.
105
+ - Bash working directory: / (use cd or absolute paths)
106
+ - Install tools with: apt-get install <package> (Debian-based)
107
+ - Your changes persist across sessions`
108
+ : `You are running directly on the host machine.
103
109
  - Bash working directory: ${process.cwd()}
104
110
  - Be careful with system modifications`;
105
111
  return `You are mama, a ${platform.name} bot assistant. Be concise. No emojis.
@@ -108,6 +114,7 @@ function buildSystemPrompt(workspacePath, channelId, memory, sandboxConfig, plat
108
114
  - For current date/time, use: date
109
115
  - You have access to previous conversation context including tool results from prior turns.
110
116
  - For older history beyond your context, search log.jsonl (contains user messages and your final responses, but not tool results).
117
+ - User messages include a \`[in-thread:TS]\` marker when sent from within a Slack thread (TS is the root message timestamp). Without this marker, the message is a top-level channel message.
111
118
 
112
119
  ${platform.formattingGuide}
113
120
 
@@ -163,17 +170,17 @@ You can schedule events that wake you up at specific times or when external thin
163
170
 
164
171
  **Immediate** - Triggers as soon as harness sees the file. Use in scripts/webhooks to signal external events.
165
172
  \`\`\`json
166
- {"type": "immediate", "channelId": "${channelId}", "text": "New GitHub issue opened"}
173
+ {"type": "immediate", "platform": "${platform.name}", "channelId": "${channelId}", "text": "New GitHub issue opened"}
167
174
  \`\`\`
168
175
 
169
176
  **One-shot** - Triggers once at a specific time. Use for reminders.
170
177
  \`\`\`json
171
- {"type": "one-shot", "channelId": "${channelId}", "text": "Remind Mario about dentist", "at": "2025-12-15T09:00:00+01:00"}
178
+ {"type": "one-shot", "platform": "${platform.name}", "channelId": "${channelId}", "text": "Remind Mario about dentist", "at": "2025-12-15T09:00:00+01:00"}
172
179
  \`\`\`
173
180
 
174
181
  **Periodic** - Triggers on a cron schedule. Use for recurring tasks.
175
182
  \`\`\`json
176
- {"type": "periodic", "channelId": "${channelId}", "text": "Check inbox and summarize", "schedule": "0 9 * * 1-5", "timezone": "${Intl.DateTimeFormat().resolvedOptions().timeZone}"}
183
+ {"type": "periodic", "platform": "${platform.name}", "channelId": "${channelId}", "text": "Check inbox and summarize", "schedule": "0 9 * * 1-5", "timezone": "${Intl.DateTimeFormat().resolvedOptions().timeZone}"}
177
184
  \`\`\`
178
185
 
179
186
  ### Cron Format
@@ -186,11 +193,14 @@ You can schedule events that wake you up at specific times or when external thin
186
193
  ### Timezones
187
194
  All \`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}.
188
195
 
196
+ ### Platform Routing
197
+ Set \`platform\` to the target bot platform (\`${platform.name}\` for this conversation). When only one platform is running, omitting \`platform\` is allowed for backward compatibility, but include it by default to avoid ambiguity.
198
+
189
199
  ### Creating Events
190
200
  Use unique filenames to avoid overwriting existing events. Include a timestamp or random suffix:
191
201
  \`\`\`bash
192
202
  cat > ${workspacePath}/events/dentist-reminder-$(date +%s).json << 'EOF'
193
- {"type": "one-shot", "channelId": "${channelId}", "text": "Dentist tomorrow", "at": "2025-12-14T09:00:00+01:00"}
203
+ {"type": "one-shot", "platform": "${platform.name}", "channelId": "${channelId}", "text": "Dentist tomorrow", "at": "2025-12-14T09:00:00+01:00"}
194
204
  EOF
195
205
  \`\`\`
196
206
  Or check if file exists first before creating.
@@ -238,6 +248,7 @@ Update this file whenever you modify the environment. On fresh container, read i
238
248
  Format: \`{"date":"...","ts":"...","user":"...","userName":"...","text":"...","isBot":false}\`
239
249
  The log contains user messages and your final responses (not tool calls/results).
240
250
  ${isDocker ? "Install jq: apk add jq" : ""}
251
+ ${isFirecracker ? "Install jq: apt-get install jq" : ""}
241
252
 
242
253
  \`\`\`bash
243
254
  # Recent messages
@@ -371,7 +382,7 @@ export async function createRunner(sandboxConfig, sessionKey, channelId, channel
371
382
  },
372
383
  convertToLlm,
373
384
  getApiKey: async () => {
374
- const key = await modelRegistry.getApiKey(model);
385
+ const key = await modelRegistry.getApiKeyForProvider(model.provider);
375
386
  if (!key)
376
387
  throw new Error(`No API key for provider "${model.provider}". Set the appropriate environment variable or configure via auth.json`);
377
388
  return key;
@@ -391,7 +402,6 @@ export async function createRunner(sandboxConfig, sessionKey, channelId, channel
391
402
  getAgentsFiles: () => ({ agentsFiles: [] }),
392
403
  getSystemPrompt: () => systemPrompt,
393
404
  getAppendSystemPrompt: () => [],
394
- getPathMetadata: () => new Map(),
395
405
  extendResources: () => { },
396
406
  reload: async () => { },
397
407
  };
@@ -438,7 +448,8 @@ export async function createRunner(sandboxConfig, sessionKey, channelId, channel
438
448
  startTime: Date.now(),
439
449
  });
440
450
  log.logToolStart(logCtx, agentEvent.toolName, label, agentEvent.args);
441
- queue.enqueue(() => responseCtx.respond(`_→ ${label}_`), "tool label");
451
+ // Tool labels are omitted from the main message to reduce Slack noise.
452
+ // Tool execution details are still posted to the thread (see tool_execution_end).
442
453
  }
443
454
  else if (event.type === "tool_execution_end") {
444
455
  const agentEvent = event;
@@ -465,7 +476,12 @@ export async function createRunner(sandboxConfig, sessionKey, channelId, channel
465
476
  if (argsFormatted)
466
477
  threadMessage += `\`\`\`\n${argsFormatted}\n\`\`\`\n`;
467
478
  threadMessage += `*Result:*\n\`\`\`\n${resultStr}\n\`\`\``;
468
- queue.enqueueMessage(threadMessage, "thread", "tool result thread", false);
479
+ // Only post thread details for tools with meaningful output (bash, attach).
480
+ // Skip read/write/edit to reduce Slack noise — their results are in the log.
481
+ const quietTools = new Set(["read", "write", "edit"]);
482
+ if (!quietTools.has(agentEvent.toolName)) {
483
+ queue.enqueueMessage(threadMessage, "thread", "tool result thread", false);
484
+ }
469
485
  if (agentEvent.isError) {
470
486
  queue.enqueue(() => responseCtx.respond(`_Error: ${truncate(resultStr, 200)}_`), "tool error");
471
487
  }
@@ -517,15 +533,18 @@ export async function createRunner(sandboxConfig, sessionKey, channelId, channel
517
533
  if (text.trim()) {
518
534
  log.logResponse(logCtx, text);
519
535
  queue.enqueueMessage(text, "main", "response main");
520
- queue.enqueueMessage(text, "thread", "response thread", false);
536
+ // Only overflow to thread for texts that will be truncated in main
537
+ if (text.length > SLACK_MAX_LENGTH) {
538
+ queue.enqueueMessage(text, "thread", "response thread", false);
539
+ }
521
540
  }
522
541
  }
523
542
  }
524
- else if (event.type === "auto_compaction_start") {
543
+ else if (event.type === "compaction_start") {
525
544
  log.logInfo(`Auto-compaction started (reason: ${event.reason})`);
526
545
  queue.enqueue(() => responseCtx.respond("_Compacting context..._"), "compaction start");
527
546
  }
528
- else if (event.type === "auto_compaction_end") {
547
+ else if (event.type === "compaction_end") {
529
548
  const compEvent = event;
530
549
  if (compEvent.result) {
531
550
  log.logInfo(`Auto-compaction complete: ${compEvent.result.tokensBefore} tokens compacted`);
@@ -566,7 +585,8 @@ export async function createRunner(sandboxConfig, sessionKey, channelId, channel
566
585
  // Sync messages from log.jsonl that arrived while we were offline or busy
567
586
  // Exclude the current message (it will be added via prompt())
568
587
  // Default sync range is 10 days (handled by syncLogToSessionManager)
569
- const syncedCount = await syncLogToSessionManager(sessionManager, channelDir, message.id);
588
+ // Thread filter ensures only messages from this session's thread are synced
589
+ const syncedCount = await syncLogToSessionManager(sessionManager, channelDir, message.id, undefined, { rootTs, threadTs: message.threadTs });
570
590
  if (syncedCount > 0) {
571
591
  log.logInfo(`[${channelId}] Synced ${syncedCount} messages from log.jsonl`);
572
592
  }
@@ -616,7 +636,11 @@ export async function createRunner(sandboxConfig, sessionKey, channelId, channel
616
636
  const errMsg = err instanceof Error ? err.message : String(err);
617
637
  log.logWarning(`API error (${errorContext})`, errMsg);
618
638
  try {
619
- await responseCtx.respondInThread(`_Error: ${errMsg}_`);
639
+ // Split long error messages to avoid msg_too_long
640
+ const errParts = splitForSlack(`_Error: ${errMsg}_`);
641
+ for (const part of errParts) {
642
+ await responseCtx.respondInThread(part);
643
+ }
620
644
  }
621
645
  catch {
622
646
  // Ignore
@@ -643,7 +667,8 @@ export async function createRunner(sandboxConfig, sessionKey, channelId, channel
643
667
  const offsetHours = pad(Math.floor(Math.abs(offset) / 60));
644
668
  const offsetMins = pad(Math.abs(offset) % 60);
645
669
  const timestamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}${offsetSign}${offsetHours}:${offsetMins}`;
646
- let userMessage = `[${timestamp}] [${message.userName || "unknown"}]: ${message.text}`;
670
+ const threadContext = message.threadTs ? ` [in-thread:${message.threadTs}]` : "";
671
+ let userMessage = `[${timestamp}] [${message.userName || "unknown"}]${threadContext}: ${message.text}`;
647
672
  const imageAttachments = [];
648
673
  const nonImagePaths = [];
649
674
  for (const a of message.attachments || []) {
@@ -684,7 +709,11 @@ export async function createRunner(sandboxConfig, sessionKey, channelId, channel
684
709
  if (runState.stopReason === "error" && runState.errorMessage) {
685
710
  try {
686
711
  await responseCtx.replaceResponse("_Sorry, something went wrong_");
687
- await responseCtx.respondInThread(`_Error: ${runState.errorMessage}_`);
712
+ // Split long error messages to avoid msg_too_long
713
+ const errorParts = splitForSlack(`_Error: ${runState.errorMessage}_`);
714
+ for (const part of errorParts) {
715
+ await responseCtx.respondInThread(part);
716
+ }
688
717
  }
689
718
  catch (err) {
690
719
  const errMsg = err instanceof Error ? err.message : String(err);
@@ -739,7 +768,11 @@ export async function createRunner(sandboxConfig, sessionKey, channelId, channel
739
768
  : 0;
740
769
  const contextWindow = model.contextWindow || 200000;
741
770
  const summary = log.logUsageSummary(runState.logCtx, runState.totalUsage, contextTokens, contextWindow);
742
- runState.queue.enqueue(() => responseCtx.respondInThread(summary), "usage summary");
771
+ // Split long summaries to avoid msg_too_long
772
+ const summaryParts = splitForSlack(summary);
773
+ for (const part of summaryParts) {
774
+ runState.queue.enqueue(() => responseCtx.respondInThread(part, { style: "muted" }), "usage summary");
775
+ }
743
776
  await queueChain;
744
777
  }
745
778
  // Clear run state
@@ -751,6 +784,19 @@ export async function createRunner(sandboxConfig, sessionKey, channelId, channel
751
784
  abort() {
752
785
  session.abort();
753
786
  },
787
+ getCurrentStep() {
788
+ const pending = runState.pendingTools;
789
+ if (pending.size === 0)
790
+ return undefined;
791
+ // Get the first pending tool
792
+ const first = pending.values().next().value;
793
+ if (!first)
794
+ return undefined;
795
+ return {
796
+ toolName: first.toolName,
797
+ label: first.args?.label,
798
+ };
799
+ },
754
800
  };
755
801
  }
756
802
  /**