@geminixiang/mama 0.1.0
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.
- package/LICENSE +22 -0
- package/README.md +158 -0
- package/dist/adapter.d.ts +38 -0
- package/dist/adapter.d.ts.map +1 -0
- package/dist/adapter.js +2 -0
- package/dist/adapter.js.map +1 -0
- package/dist/adapters/slack/bot.d.ts +130 -0
- package/dist/adapters/slack/bot.d.ts.map +1 -0
- package/dist/adapters/slack/bot.js +516 -0
- package/dist/adapters/slack/bot.js.map +1 -0
- package/dist/adapters/slack/context.d.ts +11 -0
- package/dist/adapters/slack/context.d.ts.map +1 -0
- package/dist/adapters/slack/context.js +178 -0
- package/dist/adapters/slack/context.js.map +1 -0
- package/dist/adapters/slack/index.d.ts +3 -0
- package/dist/adapters/slack/index.d.ts.map +1 -0
- package/dist/adapters/slack/index.js +3 -0
- package/dist/adapters/slack/index.js.map +1 -0
- package/dist/adapters/slack/tools/attach.d.ts +12 -0
- package/dist/adapters/slack/tools/attach.d.ts.map +1 -0
- package/dist/adapters/slack/tools/attach.js +38 -0
- package/dist/adapters/slack/tools/attach.js.map +1 -0
- package/dist/agent.d.ts +26 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +763 -0
- package/dist/agent.js.map +1 -0
- package/dist/config.d.ts +10 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +54 -0
- package/dist/config.js.map +1 -0
- package/dist/context.d.ts +34 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +110 -0
- package/dist/context.js.map +1 -0
- package/dist/download.d.ts +2 -0
- package/dist/download.d.ts.map +1 -0
- package/dist/download.js +89 -0
- package/dist/download.js.map +1 -0
- package/dist/events.d.ts +57 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +310 -0
- package/dist/events.js.map +1 -0
- package/dist/log.d.ts +39 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +222 -0
- package/dist/log.js.map +1 -0
- package/dist/main.d.ts +3 -0
- package/dist/main.d.ts.map +1 -0
- package/dist/main.js +247 -0
- package/dist/main.js.map +1 -0
- package/dist/sandbox.d.ts +34 -0
- package/dist/sandbox.d.ts.map +1 -0
- package/dist/sandbox.js +183 -0
- package/dist/sandbox.js.map +1 -0
- package/dist/store.d.ts +60 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +180 -0
- package/dist/store.js.map +1 -0
- package/dist/tools/bash.d.ts +10 -0
- package/dist/tools/bash.d.ts.map +1 -0
- package/dist/tools/bash.js +78 -0
- package/dist/tools/bash.js.map +1 -0
- package/dist/tools/edit.d.ts +11 -0
- package/dist/tools/edit.d.ts.map +1 -0
- package/dist/tools/edit.js +131 -0
- package/dist/tools/edit.js.map +1 -0
- package/dist/tools/index.d.ts +7 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +19 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/read.d.ts +11 -0
- package/dist/tools/read.d.ts.map +1 -0
- package/dist/tools/read.js +134 -0
- package/dist/tools/read.js.map +1 -0
- package/dist/tools/truncate.d.ts +57 -0
- package/dist/tools/truncate.d.ts.map +1 -0
- package/dist/tools/truncate.js +184 -0
- package/dist/tools/truncate.js.map +1 -0
- package/dist/tools/write.d.ts +10 -0
- package/dist/tools/write.d.ts.map +1 -0
- package/dist/tools/write.js +33 -0
- package/dist/tools/write.js.map +1 -0
- package/package.json +57 -0
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import * as log from "../../log.js";
|
|
2
|
+
export const SLACK_FORMATTING_GUIDE = `## Slack Formatting (mrkdwn, NOT Markdown)
|
|
3
|
+
Bold: *text*, Italic: _text_, Code: \`code\`, Block: \`\`\`code\`\`\`, Links: <url|text>
|
|
4
|
+
Do NOT use **double asterisks** or [markdown](links).`;
|
|
5
|
+
export function createSlackAdapters(event, slack, isEvent) {
|
|
6
|
+
let messageTs = null;
|
|
7
|
+
const threadMessageTs = [];
|
|
8
|
+
let accumulatedText = "";
|
|
9
|
+
let isWorking = true;
|
|
10
|
+
const workingIndicator = " ...";
|
|
11
|
+
let updatePromise = Promise.resolve();
|
|
12
|
+
const user = slack.getUser(event.user);
|
|
13
|
+
// Extract event filename for status message
|
|
14
|
+
const eventFilename = isEvent ? event.text.match(/^\[EVENT:([^:]+):/)?.[1] : undefined;
|
|
15
|
+
const rootTs = event.thread_ts ?? event.ts;
|
|
16
|
+
const isThreaded = !!event.thread_ts;
|
|
17
|
+
const message = {
|
|
18
|
+
id: event.ts,
|
|
19
|
+
sessionKey: `${event.channel}:${rootTs}`,
|
|
20
|
+
userId: event.user,
|
|
21
|
+
userName: user?.userName,
|
|
22
|
+
text: event.text,
|
|
23
|
+
attachments: (event.attachments || []).map((a) => ({ name: a.local, localPath: a.local })),
|
|
24
|
+
};
|
|
25
|
+
const platform = {
|
|
26
|
+
name: "slack",
|
|
27
|
+
formattingGuide: SLACK_FORMATTING_GUIDE,
|
|
28
|
+
channels: slack.getAllChannels().map((c) => ({ id: c.id, name: c.name })),
|
|
29
|
+
users: slack.getAllUsers().map((u) => ({ id: u.id, userName: u.userName, displayName: u.displayName })),
|
|
30
|
+
};
|
|
31
|
+
const responseCtx = {
|
|
32
|
+
respond: async (text) => {
|
|
33
|
+
updatePromise = updatePromise.then(async () => {
|
|
34
|
+
try {
|
|
35
|
+
accumulatedText = accumulatedText ? `${accumulatedText}\n${text}` : text;
|
|
36
|
+
// Truncate accumulated text if too long (Slack limit is 40K, we use 35K for safety)
|
|
37
|
+
const MAX_MAIN_LENGTH = 35000;
|
|
38
|
+
const truncationNote = "\n\n_(message truncated, ask me to elaborate on specific parts)_";
|
|
39
|
+
if (accumulatedText.length > MAX_MAIN_LENGTH) {
|
|
40
|
+
accumulatedText =
|
|
41
|
+
accumulatedText.substring(0, MAX_MAIN_LENGTH - truncationNote.length) + truncationNote;
|
|
42
|
+
}
|
|
43
|
+
const displayText = isWorking ? accumulatedText + workingIndicator : accumulatedText;
|
|
44
|
+
if (messageTs) {
|
|
45
|
+
await slack.updateMessage(event.channel, messageTs, displayText);
|
|
46
|
+
}
|
|
47
|
+
else if (isThreaded) {
|
|
48
|
+
// Reply within the user's thread
|
|
49
|
+
messageTs = await slack.postInThread(event.channel, rootTs, displayText);
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
messageTs = await slack.postMessage(event.channel, displayText);
|
|
53
|
+
}
|
|
54
|
+
if (messageTs) {
|
|
55
|
+
slack.logBotResponse(event.channel, text, messageTs);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
catch (err) {
|
|
59
|
+
log.logWarning("Slack respond error", err instanceof Error ? err.message : String(err));
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
await updatePromise;
|
|
63
|
+
},
|
|
64
|
+
replaceResponse: async (text) => {
|
|
65
|
+
updatePromise = updatePromise.then(async () => {
|
|
66
|
+
try {
|
|
67
|
+
// Replace the accumulated text entirely, with truncation
|
|
68
|
+
const MAX_MAIN_LENGTH = 35000;
|
|
69
|
+
const truncationNote = "\n\n_(message truncated, ask me to elaborate on specific parts)_";
|
|
70
|
+
if (text.length > MAX_MAIN_LENGTH) {
|
|
71
|
+
accumulatedText = text.substring(0, MAX_MAIN_LENGTH - truncationNote.length) + truncationNote;
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
accumulatedText = text;
|
|
75
|
+
}
|
|
76
|
+
const displayText = isWorking ? accumulatedText + workingIndicator : accumulatedText;
|
|
77
|
+
if (messageTs) {
|
|
78
|
+
await slack.updateMessage(event.channel, messageTs, displayText);
|
|
79
|
+
}
|
|
80
|
+
else if (isThreaded) {
|
|
81
|
+
messageTs = await slack.postInThread(event.channel, rootTs, displayText);
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
messageTs = await slack.postMessage(event.channel, displayText);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
catch (err) {
|
|
88
|
+
log.logWarning("Slack replaceResponse error", err instanceof Error ? err.message : String(err));
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
await updatePromise;
|
|
92
|
+
},
|
|
93
|
+
respondInThread: async (text) => {
|
|
94
|
+
updatePromise = updatePromise.then(async () => {
|
|
95
|
+
try {
|
|
96
|
+
// For threaded sessions, anchor to the user's root thread
|
|
97
|
+
// For channel sessions, anchor to the main bot message
|
|
98
|
+
const threadAnchor = isThreaded ? rootTs : messageTs;
|
|
99
|
+
if (threadAnchor) {
|
|
100
|
+
// Truncate thread messages if too long (20K limit for safety)
|
|
101
|
+
const MAX_THREAD_LENGTH = 20000;
|
|
102
|
+
let threadText = text;
|
|
103
|
+
if (threadText.length > MAX_THREAD_LENGTH) {
|
|
104
|
+
threadText = `${threadText.substring(0, MAX_THREAD_LENGTH - 50)}\n\n_(truncated)_`;
|
|
105
|
+
}
|
|
106
|
+
const ts = await slack.postInThread(event.channel, threadAnchor, threadText);
|
|
107
|
+
threadMessageTs.push(ts);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
catch (err) {
|
|
111
|
+
log.logWarning("Slack respondInThread error", err instanceof Error ? err.message : String(err));
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
await updatePromise;
|
|
115
|
+
},
|
|
116
|
+
setTyping: async (isTyping) => {
|
|
117
|
+
if (isTyping && !messageTs) {
|
|
118
|
+
updatePromise = updatePromise.then(async () => {
|
|
119
|
+
try {
|
|
120
|
+
if (!messageTs) {
|
|
121
|
+
accumulatedText = eventFilename ? `_Starting event: ${eventFilename}_` : "_Thinking_";
|
|
122
|
+
if (isThreaded) {
|
|
123
|
+
messageTs = await slack.postInThread(event.channel, rootTs, accumulatedText + workingIndicator);
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
messageTs = await slack.postMessage(event.channel, accumulatedText + workingIndicator);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
catch (err) {
|
|
131
|
+
log.logWarning("Slack setTyping error", err instanceof Error ? err.message : String(err));
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
await updatePromise;
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
uploadFile: async (filePath, title) => {
|
|
138
|
+
await slack.uploadFile(event.channel, filePath, title);
|
|
139
|
+
},
|
|
140
|
+
setWorking: async (working) => {
|
|
141
|
+
updatePromise = updatePromise.then(async () => {
|
|
142
|
+
try {
|
|
143
|
+
isWorking = working;
|
|
144
|
+
if (messageTs) {
|
|
145
|
+
const displayText = isWorking ? accumulatedText + workingIndicator : accumulatedText;
|
|
146
|
+
await slack.updateMessage(event.channel, messageTs, displayText);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
catch (err) {
|
|
150
|
+
log.logWarning("Slack setWorking error", err instanceof Error ? err.message : String(err));
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
await updatePromise;
|
|
154
|
+
},
|
|
155
|
+
deleteResponse: async () => {
|
|
156
|
+
updatePromise = updatePromise.then(async () => {
|
|
157
|
+
// Delete thread messages first (in reverse order)
|
|
158
|
+
for (let i = threadMessageTs.length - 1; i >= 0; i--) {
|
|
159
|
+
try {
|
|
160
|
+
await slack.deleteMessage(event.channel, threadMessageTs[i]);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
// Ignore errors deleting thread messages
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
threadMessageTs.length = 0;
|
|
167
|
+
// Then delete main message
|
|
168
|
+
if (messageTs) {
|
|
169
|
+
await slack.deleteMessage(event.channel, messageTs);
|
|
170
|
+
messageTs = null;
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
await updatePromise;
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
return { message, responseCtx, platform };
|
|
177
|
+
}
|
|
178
|
+
//# sourceMappingURL=context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/adapters/slack/context.ts"],"names":[],"mappings":"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AC,EAAE,CAAC,EAAE,EAAE,CAAC;oBACtD,IAAI,CAAC;wBACJ,MAAM,KAAK,CAAC,aAAa,CAAC,KAAK,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC;oBAC9D,CAAC;oBAAC,MAAM,CAAC;wBACR,yCAAyC;oBAC1C,CAAC;gBACF,CAAC;gBACD,eAAe,CAAC,MAAM,GAAG,CAAC,CAAC;gBAC3B,2BAA2B;gBAC3B,IAAI,SAAS,EAAE,CAAC;oBACf,MAAM,KAAK,CAAC,aAAa,CAAC,KAAK,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;oBACpD,SAAS,GAAG,IAAI,CAAC;gBAClB,CAAC;YAAA,CACD,CAAC,CAAC;YACH,MAAM,aAAa,CAAC;QAAA,CACpB;KACD,CAAC;IAEF,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC;AAAA,CAC1C","sourcesContent":["import type { ChatMessage, ChatResponseContext, PlatformInfo } from \"../../adapter.js\";\nimport * as log from \"../../log.js\";\nimport type { SlackBot, SlackEvent } from \"./bot.js\";\n\nexport const SLACK_FORMATTING_GUIDE = `## Slack Formatting (mrkdwn, NOT Markdown)\nBold: *text*, Italic: _text_, Code: \\`code\\`, Block: \\`\\`\\`code\\`\\`\\`, Links: <url|text>\nDo NOT use **double asterisks** or [markdown](links).`;\n\nexport function createSlackAdapters(\n\tevent: SlackEvent,\n\tslack: SlackBot,\n\tisEvent?: boolean,\n): {\n\tmessage: ChatMessage;\n\tresponseCtx: ChatResponseContext & { setTyping(isTyping: boolean): Promise<void> };\n\tplatform: PlatformInfo;\n} {\n\tlet messageTs: string | null = null;\n\tconst threadMessageTs: string[] = [];\n\tlet accumulatedText = \"\";\n\tlet isWorking = true;\n\tconst workingIndicator = \" ...\";\n\tlet updatePromise = Promise.resolve();\n\n\tconst user = slack.getUser(event.user);\n\n\t// Extract event filename for status message\n\tconst eventFilename = isEvent ? event.text.match(/^\\[EVENT:([^:]+):/)?.[1] : undefined;\n\n\tconst rootTs = event.thread_ts ?? event.ts;\n\tconst isThreaded = !!event.thread_ts;\n\n\tconst message: ChatMessage = {\n\t\tid: event.ts,\n\t\tsessionKey: `${event.channel}:${rootTs}`,\n\t\tuserId: event.user,\n\t\tuserName: user?.userName,\n\t\ttext: event.text,\n\t\tattachments: (event.attachments || []).map((a) => ({ name: a.local, localPath: a.local })),\n\t};\n\n\tconst platform: PlatformInfo = {\n\t\tname: \"slack\",\n\t\tformattingGuide: SLACK_FORMATTING_GUIDE,\n\t\tchannels: slack.getAllChannels().map((c) => ({ id: c.id, name: c.name })),\n\t\tusers: slack.getAllUsers().map((u) => ({ id: u.id, userName: u.userName, displayName: u.displayName })),\n\t};\n\n\tconst responseCtx = {\n\t\trespond: async (text: string) => {\n\t\t\tupdatePromise = updatePromise.then(async () => {\n\t\t\t\ttry {\n\t\t\t\t\taccumulatedText = accumulatedText ? `${accumulatedText}\\n${text}` : text;\n\n\t\t\t\t\t// Truncate accumulated text if too long (Slack limit is 40K, we use 35K for safety)\n\t\t\t\t\tconst MAX_MAIN_LENGTH = 35000;\n\t\t\t\t\tconst truncationNote = \"\\n\\n_(message truncated, ask me to elaborate on specific parts)_\";\n\t\t\t\t\tif (accumulatedText.length > MAX_MAIN_LENGTH) {\n\t\t\t\t\t\taccumulatedText =\n\t\t\t\t\t\t\taccumulatedText.substring(0, MAX_MAIN_LENGTH - truncationNote.length) + truncationNote;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst displayText = isWorking ? accumulatedText + workingIndicator : accumulatedText;\n\n\t\t\t\t\tif (messageTs) {\n\t\t\t\t\t\tawait slack.updateMessage(event.channel, messageTs, displayText);\n\t\t\t\t\t} else if (isThreaded) {\n\t\t\t\t\t\t// Reply within the user's thread\n\t\t\t\t\t\tmessageTs = await slack.postInThread(event.channel, rootTs, displayText);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmessageTs = await slack.postMessage(event.channel, displayText);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (messageTs) {\n\t\t\t\t\t\tslack.logBotResponse(event.channel, text, messageTs);\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tlog.logWarning(\"Slack respond error\", err instanceof Error ? err.message : String(err));\n\t\t\t\t}\n\t\t\t});\n\t\t\tawait updatePromise;\n\t\t},\n\n\t\treplaceResponse: async (text: string) => {\n\t\t\tupdatePromise = updatePromise.then(async () => {\n\t\t\t\ttry {\n\t\t\t\t\t// Replace the accumulated text entirely, with truncation\n\t\t\t\t\tconst MAX_MAIN_LENGTH = 35000;\n\t\t\t\t\tconst truncationNote = \"\\n\\n_(message truncated, ask me to elaborate on specific parts)_\";\n\t\t\t\t\tif (text.length > MAX_MAIN_LENGTH) {\n\t\t\t\t\t\taccumulatedText = text.substring(0, MAX_MAIN_LENGTH - truncationNote.length) + truncationNote;\n\t\t\t\t\t} else {\n\t\t\t\t\t\taccumulatedText = text;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst displayText = isWorking ? accumulatedText + workingIndicator : accumulatedText;\n\n\t\t\t\t\tif (messageTs) {\n\t\t\t\t\t\tawait slack.updateMessage(event.channel, messageTs, displayText);\n\t\t\t\t\t} else if (isThreaded) {\n\t\t\t\t\t\tmessageTs = await slack.postInThread(event.channel, rootTs, displayText);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmessageTs = await slack.postMessage(event.channel, displayText);\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tlog.logWarning(\"Slack replaceResponse error\", err instanceof Error ? err.message : String(err));\n\t\t\t\t}\n\t\t\t});\n\t\t\tawait updatePromise;\n\t\t},\n\n\t\trespondInThread: async (text: string) => {\n\t\t\tupdatePromise = updatePromise.then(async () => {\n\t\t\t\ttry {\n\t\t\t\t\t// For threaded sessions, anchor to the user's root thread\n\t\t\t\t\t// For channel sessions, anchor to the main bot message\n\t\t\t\t\tconst threadAnchor = isThreaded ? rootTs : messageTs;\n\t\t\t\t\tif (threadAnchor) {\n\t\t\t\t\t\t// Truncate thread messages if too long (20K limit for safety)\n\t\t\t\t\t\tconst MAX_THREAD_LENGTH = 20000;\n\t\t\t\t\t\tlet threadText = text;\n\t\t\t\t\t\tif (threadText.length > MAX_THREAD_LENGTH) {\n\t\t\t\t\t\t\tthreadText = `${threadText.substring(0, MAX_THREAD_LENGTH - 50)}\\n\\n_(truncated)_`;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst ts = await slack.postInThread(event.channel, threadAnchor, threadText);\n\t\t\t\t\t\tthreadMessageTs.push(ts);\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tlog.logWarning(\"Slack respondInThread error\", err instanceof Error ? err.message : String(err));\n\t\t\t\t}\n\t\t\t});\n\t\t\tawait updatePromise;\n\t\t},\n\n\t\tsetTyping: async (isTyping: boolean) => {\n\t\t\tif (isTyping && !messageTs) {\n\t\t\t\tupdatePromise = updatePromise.then(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (!messageTs) {\n\t\t\t\t\t\t\taccumulatedText = eventFilename ? `_Starting event: ${eventFilename}_` : \"_Thinking_\";\n\t\t\t\t\t\t\tif (isThreaded) {\n\t\t\t\t\t\t\t\tmessageTs = await slack.postInThread(event.channel, rootTs, accumulatedText + workingIndicator);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tmessageTs = await slack.postMessage(event.channel, accumulatedText + workingIndicator);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tlog.logWarning(\"Slack setTyping error\", err instanceof Error ? err.message : String(err));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tawait updatePromise;\n\t\t\t}\n\t\t},\n\n\t\tuploadFile: async (filePath: string, title?: string) => {\n\t\t\tawait slack.uploadFile(event.channel, filePath, title);\n\t\t},\n\n\t\tsetWorking: async (working: boolean) => {\n\t\t\tupdatePromise = updatePromise.then(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tisWorking = working;\n\t\t\t\t\tif (messageTs) {\n\t\t\t\t\t\tconst displayText = isWorking ? accumulatedText + workingIndicator : accumulatedText;\n\t\t\t\t\t\tawait slack.updateMessage(event.channel, messageTs, displayText);\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tlog.logWarning(\"Slack setWorking error\", err instanceof Error ? err.message : String(err));\n\t\t\t\t}\n\t\t\t});\n\t\t\tawait updatePromise;\n\t\t},\n\n\t\tdeleteResponse: async () => {\n\t\t\tupdatePromise = updatePromise.then(async () => {\n\t\t\t\t// Delete thread messages first (in reverse order)\n\t\t\t\tfor (let i = threadMessageTs.length - 1; i >= 0; i--) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait slack.deleteMessage(event.channel, threadMessageTs[i]);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Ignore errors deleting thread messages\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthreadMessageTs.length = 0;\n\t\t\t\t// Then delete main message\n\t\t\t\tif (messageTs) {\n\t\t\t\t\tawait slack.deleteMessage(event.channel, messageTs);\n\t\t\t\t\tmessageTs = null;\n\t\t\t\t}\n\t\t\t});\n\t\t\tawait updatePromise;\n\t\t},\n\t};\n\n\treturn { message, responseCtx, platform };\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/adapters/slack/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,cAAc,CAAC","sourcesContent":["export * from \"./bot.js\";\nexport * from \"./context.js\";\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/adapters/slack/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,cAAc,CAAC","sourcesContent":["export * from \"./bot.js\";\nexport * from \"./context.js\";\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { AgentTool } from "@mariozechner/pi-agent-core";
|
|
2
|
+
declare const attachSchema: import("@sinclair/typebox").TObject<{
|
|
3
|
+
label: import("@sinclair/typebox").TString;
|
|
4
|
+
path: import("@sinclair/typebox").TString;
|
|
5
|
+
title: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
|
|
6
|
+
}>;
|
|
7
|
+
export declare function createAttachTool(): {
|
|
8
|
+
tool: AgentTool<typeof attachSchema>;
|
|
9
|
+
setUploadFunction: (fn: (filePath: string, title?: string) => Promise<void>) => void;
|
|
10
|
+
};
|
|
11
|
+
export {};
|
|
12
|
+
//# sourceMappingURL=attach.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attach.d.ts","sourceRoot":"","sources":["../../../../src/adapters/slack/tools/attach.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AAI7D,QAAA,MAAM,YAAY;;;;EAIhB,CAAC;AAEH,wBAAgB,gBAAgB,IAAI;IACnC,IAAI,EAAE,SAAS,CAAC,OAAO,YAAY,CAAC,CAAC;IACrC,iBAAiB,EAAE,CAAC,EAAE,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC;CACrF,CAwCA","sourcesContent":["import type { AgentTool } from \"@mariozechner/pi-agent-core\";\nimport { Type } from \"@sinclair/typebox\";\nimport { basename, resolve as resolvePath } from \"path\";\n\nconst attachSchema = Type.Object({\n\tlabel: Type.String({ description: \"Brief description of what you're sharing (shown to user)\" }),\n\tpath: Type.String({ description: \"Path to the file to attach\" }),\n\ttitle: Type.Optional(Type.String({ description: \"Title for the file (defaults to filename)\" })),\n});\n\nexport function createAttachTool(): {\n\ttool: AgentTool<typeof attachSchema>;\n\tsetUploadFunction: (fn: (filePath: string, title?: string) => Promise<void>) => void;\n} {\n\tlet uploadFn: ((filePath: string, title?: string) => Promise<void>) | null = null;\n\n\tconst tool: AgentTool<typeof attachSchema> = {\n\t\tname: \"attach\",\n\t\tlabel: \"attach\",\n\t\tdescription:\n\t\t\t\"Attach a file to your response. Use this to share files, images, or documents with the user. Only files from /workspace/ can be attached.\",\n\t\tparameters: attachSchema,\n\t\texecute: async (\n\t\t\t_toolCallId: string,\n\t\t\t{ path, title }: { label: string; path: string; title?: string },\n\t\t\tsignal?: AbortSignal,\n\t\t) => {\n\t\t\tif (!uploadFn) {\n\t\t\t\tthrow new Error(\"Upload function not configured\");\n\t\t\t}\n\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"Operation aborted\");\n\t\t\t}\n\n\t\t\tconst absolutePath = resolvePath(path);\n\t\t\tconst fileName = title || basename(absolutePath);\n\n\t\t\tawait uploadFn(absolutePath, fileName);\n\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\" as const, text: `Attached file: ${fileName}` }],\n\t\t\t\tdetails: undefined,\n\t\t\t};\n\t\t},\n\t};\n\n\treturn {\n\t\ttool,\n\t\tsetUploadFunction: (fn) => {\n\t\t\tuploadFn = fn;\n\t\t},\n\t};\n}\n"]}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { Type } from "@sinclair/typebox";
|
|
2
|
+
import { basename, resolve as resolvePath } from "path";
|
|
3
|
+
const attachSchema = Type.Object({
|
|
4
|
+
label: Type.String({ description: "Brief description of what you're sharing (shown to user)" }),
|
|
5
|
+
path: Type.String({ description: "Path to the file to attach" }),
|
|
6
|
+
title: Type.Optional(Type.String({ description: "Title for the file (defaults to filename)" })),
|
|
7
|
+
});
|
|
8
|
+
export function createAttachTool() {
|
|
9
|
+
let uploadFn = null;
|
|
10
|
+
const tool = {
|
|
11
|
+
name: "attach",
|
|
12
|
+
label: "attach",
|
|
13
|
+
description: "Attach a file to your response. Use this to share files, images, or documents with the user. Only files from /workspace/ can be attached.",
|
|
14
|
+
parameters: attachSchema,
|
|
15
|
+
execute: async (_toolCallId, { path, title }, signal) => {
|
|
16
|
+
if (!uploadFn) {
|
|
17
|
+
throw new Error("Upload function not configured");
|
|
18
|
+
}
|
|
19
|
+
if (signal?.aborted) {
|
|
20
|
+
throw new Error("Operation aborted");
|
|
21
|
+
}
|
|
22
|
+
const absolutePath = resolvePath(path);
|
|
23
|
+
const fileName = title || basename(absolutePath);
|
|
24
|
+
await uploadFn(absolutePath, fileName);
|
|
25
|
+
return {
|
|
26
|
+
content: [{ type: "text", text: `Attached file: ${fileName}` }],
|
|
27
|
+
details: undefined,
|
|
28
|
+
};
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
return {
|
|
32
|
+
tool,
|
|
33
|
+
setUploadFunction: (fn) => {
|
|
34
|
+
uploadFn = fn;
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=attach.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attach.js","sourceRoot":"","sources":["../../../../src/adapters/slack/tools/attach.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,MAAM,CAAC;AAExD,MAAM,YAAY,GAAG,IAAI,CAAC,MAAM,CAAC;IAChC,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,0DAA0D,EAAE,CAAC;IAC/F,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,4BAA4B,EAAE,CAAC;IAChE,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,2CAA2C,EAAE,CAAC,CAAC;CAC/F,CAAC,CAAC;AAEH,MAAM,UAAU,gBAAgB,GAG9B;IACD,IAAI,QAAQ,GAAiE,IAAI,CAAC;IAElF,MAAM,IAAI,GAAmC;QAC5C,IAAI,EAAE,QAAQ;QACd,KAAK,EAAE,QAAQ;QACf,WAAW,EACV,2IAA2I;QAC5I,UAAU,EAAE,YAAY;QACxB,OAAO,EAAE,KAAK,EACb,WAAmB,EACnB,EAAE,IAAI,EAAE,KAAK,EAAmD,EAChE,MAAoB,EACnB,EAAE,CAAC;YACJ,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACf,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;YACnD,CAAC;YAED,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;gBACrB,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;YACtC,CAAC;YAED,MAAM,YAAY,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;YACvC,MAAM,QAAQ,GAAG,KAAK,IAAI,QAAQ,CAAC,YAAY,CAAC,CAAC;YAEjD,MAAM,QAAQ,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC;YAEvC,OAAO;gBACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,kBAAkB,QAAQ,EAAE,EAAE,CAAC;gBACxE,OAAO,EAAE,SAAS;aAClB,CAAC;QAAA,CACF;KACD,CAAC;IAEF,OAAO;QACN,IAAI;QACJ,iBAAiB,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;YAC1B,QAAQ,GAAG,EAAE,CAAC;QAAA,CACd;KACD,CAAC;AAAA,CACF","sourcesContent":["import type { AgentTool } from \"@mariozechner/pi-agent-core\";\nimport { Type } from \"@sinclair/typebox\";\nimport { basename, resolve as resolvePath } from \"path\";\n\nconst attachSchema = Type.Object({\n\tlabel: Type.String({ description: \"Brief description of what you're sharing (shown to user)\" }),\n\tpath: Type.String({ description: \"Path to the file to attach\" }),\n\ttitle: Type.Optional(Type.String({ description: \"Title for the file (defaults to filename)\" })),\n});\n\nexport function createAttachTool(): {\n\ttool: AgentTool<typeof attachSchema>;\n\tsetUploadFunction: (fn: (filePath: string, title?: string) => Promise<void>) => void;\n} {\n\tlet uploadFn: ((filePath: string, title?: string) => Promise<void>) | null = null;\n\n\tconst tool: AgentTool<typeof attachSchema> = {\n\t\tname: \"attach\",\n\t\tlabel: \"attach\",\n\t\tdescription:\n\t\t\t\"Attach a file to your response. Use this to share files, images, or documents with the user. Only files from /workspace/ can be attached.\",\n\t\tparameters: attachSchema,\n\t\texecute: async (\n\t\t\t_toolCallId: string,\n\t\t\t{ path, title }: { label: string; path: string; title?: string },\n\t\t\tsignal?: AbortSignal,\n\t\t) => {\n\t\t\tif (!uploadFn) {\n\t\t\t\tthrow new Error(\"Upload function not configured\");\n\t\t\t}\n\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"Operation aborted\");\n\t\t\t}\n\n\t\t\tconst absolutePath = resolvePath(path);\n\t\t\tconst fileName = title || basename(absolutePath);\n\n\t\t\tawait uploadFn(absolutePath, fileName);\n\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\" as const, text: `Attached file: ${fileName}` }],\n\t\t\t\tdetails: undefined,\n\t\t\t};\n\t\t},\n\t};\n\n\treturn {\n\t\ttool,\n\t\tsetUploadFunction: (fn) => {\n\t\t\tuploadFn = fn;\n\t\t},\n\t};\n}\n"]}
|
package/dist/agent.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { ChatMessage, ChatResponseContext, PlatformInfo } from "./adapter.js";
|
|
2
|
+
import { type SandboxConfig } from "./sandbox.js";
|
|
3
|
+
export interface PendingMessage {
|
|
4
|
+
userName: string;
|
|
5
|
+
text: string;
|
|
6
|
+
attachments: {
|
|
7
|
+
local: string;
|
|
8
|
+
}[];
|
|
9
|
+
timestamp: number;
|
|
10
|
+
}
|
|
11
|
+
export interface AgentRunner {
|
|
12
|
+
run(message: ChatMessage, responseCtx: ChatResponseContext, platform: PlatformInfo): Promise<{
|
|
13
|
+
stopReason: string;
|
|
14
|
+
errorMessage?: string;
|
|
15
|
+
}>;
|
|
16
|
+
abort(): void;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Create a new AgentRunner for a channel.
|
|
20
|
+
* Sets up the session and subscribes to events once.
|
|
21
|
+
*
|
|
22
|
+
* Runner caching is handled by the caller (channelStates in main.ts).
|
|
23
|
+
* This is a stateless factory function.
|
|
24
|
+
*/
|
|
25
|
+
export declare function createRunner(sandboxConfig: SandboxConfig, sessionKey: string, channelId: string, channelDir: string, workspaceDir: string): Promise<AgentRunner>;
|
|
26
|
+
//# sourceMappingURL=agent.d.ts.map
|
|
@@ -0,0 +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;AAKnF,OAAO,EAAkB,KAAK,aAAa,EAAE,MAAM,cAAc,CAAC;AAGlE,MAAM,WAAW,cAAc;IAC9B,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;CAClB;AAED,MAAM,WAAW,WAAW;IAC3B,GAAG,CACF,OAAO,EAAE,WAAW,EACpB,WAAW,EAAE,mBAAmB,EAChC,QAAQ,EAAE,YAAY,GACpB,OAAO,CAAC;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC1D,KAAK,IAAI,IAAI,CAAC;CACd;AAwVD;;;;;;GAMG;AACH,wBAAsB,YAAY,CACjC,aAAa,EAAE,aAAa,EAC5B,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,MAAM,GAClB,OAAO,CAAC,WAAW,CAAC,CAmdtB","sourcesContent":["import { Agent, type AgentEvent } from \"@mariozechner/pi-agent-core\";\nimport { getModel, type ImageContent } from \"@mariozechner/pi-ai\";\nimport {\n\tAgentSession,\n\tAuthStorage,\n\tconvertToLlm,\n\tcreateExtensionRuntime,\n\tformatSkillsForPrompt,\n\tloadSkillsFromDir,\n\tModelRegistry,\n\ttype ResourceLoader,\n\tSessionManager,\n\ttype 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 type { AgentConfig } from \"./config.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\tuserName: string;\n\ttext: string;\n\tattachments: { local: string }[];\n\ttimestamp: number;\n}\n\nexport interface AgentRunner {\n\trun(\n\t\tmessage: ChatMessage,\n\t\tresponseCtx: ChatResponseContext,\n\t\tplatform: PlatformInfo,\n\t): Promise<{ stopReason: string; errorMessage?: string }>;\n\tabort(): void;\n}\n\nconst IMAGE_MIME_TYPES: Record<string, string> = {\n\tjpg: \"image/jpeg\",\n\tjpeg: \"image/jpeg\",\n\tpng: \"image/png\",\n\tgif: \"image/gif\",\n\twebp: \"image/webp\",\n};\n\nfunction getImageMimeType(filename: string): string | undefined {\n\treturn IMAGE_MIME_TYPES[filename.toLowerCase().split(\".\").pop() || \"\"];\n}\n\nasync function getMemory(channelDir: string): Promise<string> {\n\tconst parts: string[] = [];\n\n\t// Read workspace-level memory (shared across all channels)\n\tconst workspaceMemoryPath = join(channelDir, \"..\", \"MEMORY.md\");\n\tif (existsSync(workspaceMemoryPath)) {\n\t\ttry {\n\t\t\tconst content = (await readFile(workspaceMemoryPath, \"utf-8\")).trim();\n\t\t\tif (content) {\n\t\t\t\tparts.push(`### Global Workspace Memory\\n${content}`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlog.logWarning(\"Failed to read workspace memory\", `${workspaceMemoryPath}: ${error}`);\n\t\t}\n\t}\n\n\t// Read channel-specific memory\n\tconst channelMemoryPath = join(channelDir, \"MEMORY.md\");\n\tif (existsSync(channelMemoryPath)) {\n\t\ttry {\n\t\t\tconst content = (await readFile(channelMemoryPath, \"utf-8\")).trim();\n\t\t\tif (content) {\n\t\t\t\tparts.push(`### Channel-Specific Memory\\n${content}`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlog.logWarning(\"Failed to read channel memory\", `${channelMemoryPath}: ${error}`);\n\t\t}\n\t}\n\n\tif (parts.length === 0) {\n\t\treturn \"(no working memory yet)\";\n\t}\n\n\treturn parts.join(\"\\n\\n\");\n}\n\nfunction loadMamaSkills(channelDir: string, workspacePath: string): Skill[] {\n\tconst skillMap = new Map<string, Skill>();\n\n\t// channelDir is the host path (e.g., /Users/.../data/C0A34FL8PMH)\n\t// hostWorkspacePath is the parent directory on host\n\t// workspacePath is the container path (e.g., /workspace)\n\tconst hostWorkspacePath = join(channelDir, \"..\");\n\n\t// Helper to translate host paths to container paths\n\tconst translatePath = (hostPath: string): string => {\n\t\tif (hostPath.startsWith(hostWorkspacePath)) {\n\t\t\treturn workspacePath + hostPath.slice(hostWorkspacePath.length);\n\t\t}\n\t\treturn hostPath;\n\t};\n\n\t// Load workspace-level skills (global)\n\tconst workspaceSkillsDir = join(hostWorkspacePath, \"skills\");\n\tfor (const skill of loadSkillsFromDir({ dir: workspaceSkillsDir, source: \"workspace\" }).skills) {\n\t\t// Translate paths to container paths for system prompt\n\t\tskill.filePath = translatePath(skill.filePath);\n\t\tskill.baseDir = translatePath(skill.baseDir);\n\t\tskillMap.set(skill.name, skill);\n\t}\n\n\t// Load channel-specific skills (override workspace skills on collision)\n\tconst channelSkillsDir = join(channelDir, \"skills\");\n\tfor (const skill of loadSkillsFromDir({ dir: channelSkillsDir, source: \"channel\" }).skills) {\n\t\tskill.filePath = translatePath(skill.filePath);\n\t\tskill.baseDir = translatePath(skill.baseDir);\n\t\tskillMap.set(skill.name, skill);\n\t}\n\n\treturn Array.from(skillMap.values());\n}\n\nfunction buildSystemPrompt(\n\tworkspacePath: string,\n\tchannelId: string,\n\tmemory: string,\n\tsandboxConfig: SandboxConfig,\n\tplatform: PlatformInfo,\n\tskills: Skill[],\n\tmaxUsersInPrompt: number,\n): string {\n\tconst channelPath = `${workspacePath}/${channelId}`;\n\tconst isDocker = sandboxConfig.type === \"docker\";\n\n\t// Format channel mappings\n\tconst channelMappings =\n\t\tplatform.channels.length > 0\n\t\t\t? platform.channels.map((c) => `${c.id}\\t#${c.name}`).join(\"\\n\")\n\t\t\t: \"(no channels loaded)\";\n\n\t// Format user mappings (limited to maxUsersInPrompt)\n\tconst limitedUsers = platform.users.slice(0, maxUsersInPrompt);\n\tconst userCountNote = platform.users.length > maxUsersInPrompt ? ` (showing ${maxUsersInPrompt} of ${platform.users.length})` : \"\";\n\tconst userMappings =\n\t\tlimitedUsers.length > 0\n\t\t\t? limitedUsers.map((u) => `${u.id}\\t@${u.userName}\\t${u.displayName}`).join(\"\\n\")\n\t\t\t: \"(no users loaded)\";\n\n\tconst envDescription = isDocker\n\t\t? `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\t\t: `You are running directly on the host machine.\n- Bash working directory: ${process.cwd()}\n- Be careful with system modifications`;\n\n\treturn `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}${userCountNote}\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\tif (text.length <= maxLen) return text;\n\treturn `${text.substring(0, maxLen - 3)}...`;\n}\n\nfunction extractToolResultText(result: unknown): string {\n\tif (typeof result === \"string\") {\n\t\treturn result;\n\t}\n\n\tif (\n\t\tresult &&\n\t\ttypeof result === \"object\" &&\n\t\t\"content\" in result &&\n\t\tArray.isArray((result as { content: unknown }).content)\n\t) {\n\t\tconst content = (result as { content: Array<{ type: string; text?: string }> }).content;\n\t\tconst textParts: string[] = [];\n\t\tfor (const part of content) {\n\t\t\tif (part.type === \"text\" && part.text) {\n\t\t\t\ttextParts.push(part.text);\n\t\t\t}\n\t\t}\n\t\tif (textParts.length > 0) {\n\t\t\treturn textParts.join(\"\\n\");\n\t\t}\n\t}\n\n\treturn JSON.stringify(result);\n}\n\nfunction formatToolArgsForSlack(_toolName: string, args: Record<string, unknown>): string {\n\tconst lines: string[] = [];\n\n\tfor (const [key, value] of Object.entries(args)) {\n\t\tif (key === \"label\") continue;\n\n\t\tif (key === \"path\" && typeof value === \"string\") {\n\t\t\tconst offset = args.offset as number | undefined;\n\t\t\tconst limit = args.limit as number | undefined;\n\t\t\tif (offset !== undefined && limit !== undefined) {\n\t\t\t\tlines.push(`${value}:${offset}-${offset + limit}`);\n\t\t\t} else {\n\t\t\t\tlines.push(value);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (key === \"offset\" || key === \"limit\") continue;\n\n\t\tif (typeof value === \"string\") {\n\t\t\tlines.push(value);\n\t\t} else {\n\t\t\tlines.push(JSON.stringify(value));\n\t\t}\n\t}\n\n\treturn 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\tsandboxConfig: SandboxConfig,\n\tsessionKey: string,\n\tchannelId: string,\n\tchannelDir: string,\n\tworkspaceDir: string,\n): Promise<AgentRunner> {\n\tconst agentConfig = loadAgentConfig(workspaceDir);\n\tconst executor = createExecutor(sandboxConfig);\n\tconst workspacePath = executor.getWorkspacePath(channelDir.replace(`/${channelId}`, \"\"));\n\n\t// Create tools (per-runner, with per-runner upload function setter)\n\tconst { tools, setUploadFunction } = createMamaTools(executor);\n\n\t// Resolve model from config\n\t// Use 'as any' cast because agentConfig.provider/model are plain strings,\n\t// while getModel() has constrained generic types for known providers.\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tconst model = (getModel as any)(agentConfig.provider, agentConfig.model);\n\n\t// Initial system prompt (will be updated each run with fresh memory/channels/users/skills)\n\tconst memory = await getMemory(channelDir);\n\tconst skills = loadMamaSkills(channelDir, workspacePath);\n\tconst emptyPlatform: PlatformInfo = { name: \"slack\", formattingGuide: \"\", channels: [], users: [] };\n\tconst systemPrompt = buildSystemPrompt(workspacePath, channelId, memory, sandboxConfig, emptyPlatform, skills, agentConfig.maxUsersInPrompt ?? 50);\n\n\t// Create session manager and settings manager\n\t// Per-session context file: {channelDir}/sessions/{rootTs}/context.jsonl\n\tconst rootTs = sessionKey.includes(\":\") ? sessionKey.split(\":\").pop()! : sessionKey;\n\tconst sessionDir = join(channelDir, \"sessions\", rootTs);\n\tmkdirSync(sessionDir, { recursive: true });\n\tconst contextFile = join(sessionDir, \"context.jsonl\");\n\tconst sessionManager = SessionManager.open(contextFile, channelDir);\n\tconst settingsManager = createMamaSettingsManager(join(channelDir, \"..\"));\n\n\t// Create AuthStorage and ModelRegistry\n\t// Auth stored outside workspace so agent can't access it\n\tconst authStorage = AuthStorage.create(join(homedir(), \".pi\", \"mama\", \"auth.json\"));\n\tconst modelRegistry = new ModelRegistry(authStorage);\n\n\t// Create agent\n\tconst agent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt,\n\t\t\tmodel,\n\t\t\tthinkingLevel: (agentConfig.thinkingLevel as \"off\" | \"low\" | \"medium\" | \"high\" | undefined) ?? \"off\",\n\t\t\ttools,\n\t\t},\n\t\tconvertToLlm,\n\t\tgetApiKey: async () => {\n\t\t\tconst key = await modelRegistry.getApiKey(model);\n\t\t\tif (!key)\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No API key for provider \"${model.provider}\". Set the appropriate environment variable or configure via auth.json`,\n\t\t\t\t);\n\t\t\treturn key;\n\t\t},\n\t});\n\n\t// Load existing messages\n\tconst loadedSession = sessionManager.buildSessionContext();\n\tif (loadedSession.messages.length > 0) {\n\t\tagent.replaceMessages(loadedSession.messages);\n\t\tlog.logInfo(`[${channelId}] Loaded ${loadedSession.messages.length} messages from context.jsonl`);\n\t}\n\n\tconst resourceLoader: ResourceLoader = {\n\t\tgetExtensions: () => ({ extensions: [], errors: [], runtime: createExtensionRuntime() }),\n\t\tgetSkills: () => ({ skills: [], diagnostics: [] }),\n\t\tgetPrompts: () => ({ prompts: [], diagnostics: [] }),\n\t\tgetThemes: () => ({ themes: [], diagnostics: [] }),\n\t\tgetAgentsFiles: () => ({ agentsFiles: [] }),\n\t\tgetSystemPrompt: () => systemPrompt,\n\t\tgetAppendSystemPrompt: () => [],\n\t\tgetPathMetadata: () => new Map(),\n\t\textendResources: () => {},\n\t\treload: async () => {},\n\t};\n\n\tconst baseToolsOverride = Object.fromEntries(tools.map((tool) => [tool.name, tool]));\n\n\t// Create AgentSession wrapper\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd: process.cwd(),\n\t\tmodelRegistry,\n\t\tresourceLoader,\n\t\tbaseToolsOverride,\n\t});\n\n\t// Mutable per-run state - event handler references this\n\tconst runState = {\n\t\tresponseCtx: null as ChatResponseContext | null,\n\t\tlogCtx: null as { channelId: string; userName?: string; channelName?: string } | null,\n\t\tqueue: null as {\n\t\t\tenqueue(fn: () => Promise<void>, errorContext: string): void;\n\t\t\tenqueueMessage(text: string, target: \"main\" | \"thread\", errorContext: string, doLog?: boolean): void;\n\t\t} | null,\n\t\tpendingTools: new Map<string, { toolName: string; args: unknown; startTime: number }>(),\n\t\ttotalUsage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"stop\",\n\t\terrorMessage: undefined as string | undefined,\n\t};\n\n\t// Subscribe to events ONCE\n\tsession.subscribe(async (event) => {\n\t\t// Skip if no active run\n\t\tif (!runState.responseCtx || !runState.logCtx || !runState.queue) return;\n\n\t\tconst { responseCtx, logCtx, queue, pendingTools } = runState;\n\n\t\tif (event.type === \"tool_execution_start\") {\n\t\t\tconst agentEvent = event as AgentEvent & { type: \"tool_execution_start\" };\n\t\t\tconst args = agentEvent.args as { label?: string };\n\t\t\tconst label = args.label || agentEvent.toolName;\n\n\t\t\tpendingTools.set(agentEvent.toolCallId, {\n\t\t\t\ttoolName: agentEvent.toolName,\n\t\t\t\targs: agentEvent.args,\n\t\t\t\tstartTime: Date.now(),\n\t\t\t});\n\n\t\t\tlog.logToolStart(logCtx, agentEvent.toolName, label, agentEvent.args as Record<string, unknown>);\n\t\t\tqueue.enqueue(() => responseCtx.respond(`_→ ${label}_`), \"tool label\");\n\t\t} else if (event.type === \"tool_execution_end\") {\n\t\t\tconst agentEvent = event as AgentEvent & { type: \"tool_execution_end\" };\n\t\t\tconst resultStr = extractToolResultText(agentEvent.result);\n\t\t\tconst pending = pendingTools.get(agentEvent.toolCallId);\n\t\t\tpendingTools.delete(agentEvent.toolCallId);\n\n\t\t\tconst durationMs = pending ? Date.now() - pending.startTime : 0;\n\n\t\t\tif (agentEvent.isError) {\n\t\t\t\tlog.logToolError(logCtx, agentEvent.toolName, durationMs, resultStr);\n\t\t\t} else {\n\t\t\t\tlog.logToolSuccess(logCtx, agentEvent.toolName, durationMs, resultStr);\n\t\t\t}\n\n\t\t\t// Post args + result to thread\n\t\t\tconst label = pending?.args ? (pending.args as { label?: string }).label : undefined;\n\t\t\tconst argsFormatted = pending\n\t\t\t\t? formatToolArgsForSlack(agentEvent.toolName, pending.args as Record<string, unknown>)\n\t\t\t\t: \"(args not found)\";\n\t\t\tconst duration = (durationMs / 1000).toFixed(1);\n\t\t\tlet threadMessage = `*${agentEvent.isError ? \"✗\" : \"✓\"} ${agentEvent.toolName}*`;\n\t\t\tif (label) threadMessage += `: ${label}`;\n\t\t\tthreadMessage += ` (${duration}s)\\n`;\n\t\t\tif (argsFormatted) threadMessage += `\\`\\`\\`\\n${argsFormatted}\\n\\`\\`\\`\\n`;\n\t\t\tthreadMessage += `*Result:*\\n\\`\\`\\`\\n${resultStr}\\n\\`\\`\\``;\n\n\t\t\tqueue.enqueueMessage(threadMessage, \"thread\", \"tool result thread\", false);\n\n\t\t\tif (agentEvent.isError) {\n\t\t\t\tqueue.enqueue(() => responseCtx.respond(`_Error: ${truncate(resultStr, 200)}_`), \"tool error\");\n\t\t\t}\n\t\t} else if (event.type === \"message_start\") {\n\t\t\tconst agentEvent = event as AgentEvent & { type: \"message_start\" };\n\t\t\tif (agentEvent.message.role === \"assistant\") {\n\t\t\t\tlog.logResponseStart(logCtx);\n\t\t\t}\n\t\t} else if (event.type === \"message_end\") {\n\t\t\tconst agentEvent = event as AgentEvent & { type: \"message_end\" };\n\t\t\tif (agentEvent.message.role === \"assistant\") {\n\t\t\t\tconst assistantMsg = agentEvent.message as any;\n\n\t\t\t\tif (assistantMsg.stopReason) {\n\t\t\t\t\trunState.stopReason = assistantMsg.stopReason;\n\t\t\t\t}\n\t\t\t\tif (assistantMsg.errorMessage) {\n\t\t\t\t\trunState.errorMessage = assistantMsg.errorMessage;\n\t\t\t\t}\n\n\t\t\t\tif (assistantMsg.usage) {\n\t\t\t\t\trunState.totalUsage.input += assistantMsg.usage.input;\n\t\t\t\t\trunState.totalUsage.output += assistantMsg.usage.output;\n\t\t\t\t\trunState.totalUsage.cacheRead += assistantMsg.usage.cacheRead;\n\t\t\t\t\trunState.totalUsage.cacheWrite += assistantMsg.usage.cacheWrite;\n\t\t\t\t\trunState.totalUsage.cost.input += assistantMsg.usage.cost.input;\n\t\t\t\t\trunState.totalUsage.cost.output += assistantMsg.usage.cost.output;\n\t\t\t\t\trunState.totalUsage.cost.cacheRead += assistantMsg.usage.cost.cacheRead;\n\t\t\t\t\trunState.totalUsage.cost.cacheWrite += assistantMsg.usage.cost.cacheWrite;\n\t\t\t\t\trunState.totalUsage.cost.total += assistantMsg.usage.cost.total;\n\t\t\t\t}\n\n\t\t\t\tconst content = agentEvent.message.content;\n\t\t\t\tconst thinkingParts: string[] = [];\n\t\t\t\tconst textParts: string[] = [];\n\t\t\t\tfor (const part of content) {\n\t\t\t\t\tif (part.type === \"thinking\") {\n\t\t\t\t\t\tthinkingParts.push((part as any).thinking);\n\t\t\t\t\t} else if (part.type === \"text\") {\n\t\t\t\t\t\ttextParts.push((part as any).text);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst text = textParts.join(\"\\n\");\n\n\t\t\t\tfor (const thinking of thinkingParts) {\n\t\t\t\t\tlog.logThinking(logCtx, thinking);\n\t\t\t\t\tqueue.enqueueMessage(`_${thinking}_`, \"main\", \"thinking main\");\n\t\t\t\t\tqueue.enqueueMessage(`_${thinking}_`, \"thread\", \"thinking thread\", false);\n\t\t\t\t}\n\n\t\t\t\tif (text.trim()) {\n\t\t\t\t\tlog.logResponse(logCtx, text);\n\t\t\t\t\tqueue.enqueueMessage(text, \"main\", \"response main\");\n\t\t\t\t\tqueue.enqueueMessage(text, \"thread\", \"response thread\", false);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"auto_compaction_start\") {\n\t\t\tlog.logInfo(`Auto-compaction started (reason: ${(event as any).reason})`);\n\t\t\tqueue.enqueue(() => responseCtx.respond(\"_Compacting context..._\"), \"compaction start\");\n\t\t} else if (event.type === \"auto_compaction_end\") {\n\t\t\tconst compEvent = event as any;\n\t\t\tif (compEvent.result) {\n\t\t\t\tlog.logInfo(`Auto-compaction complete: ${compEvent.result.tokensBefore} tokens compacted`);\n\t\t\t} else if (compEvent.aborted) {\n\t\t\t\tlog.logInfo(\"Auto-compaction aborted\");\n\t\t\t}\n\t\t} else if (event.type === \"auto_retry_start\") {\n\t\t\tconst retryEvent = event as any;\n\t\t\tlog.logWarning(`Retrying (${retryEvent.attempt}/${retryEvent.maxAttempts})`, retryEvent.errorMessage);\n\t\t\tqueue.enqueue(\n\t\t\t\t() => responseCtx.respond(`_Retrying (${retryEvent.attempt}/${retryEvent.maxAttempts})..._`),\n\t\t\t\t\"retry\",\n\t\t\t);\n\t\t}\n\t});\n\n\t// Message limit constant\n\tconst SLACK_MAX_LENGTH = 40000;\n\tconst splitForSlack = (text: string): string[] => {\n\t\tif (text.length <= SLACK_MAX_LENGTH) return [text];\n\t\tconst parts: string[] = [];\n\t\tlet remaining = text;\n\t\tlet partNum = 1;\n\t\twhile (remaining.length > 0) {\n\t\t\tconst chunk = remaining.substring(0, SLACK_MAX_LENGTH - 50);\n\t\t\tremaining = remaining.substring(SLACK_MAX_LENGTH - 50);\n\t\t\tconst suffix = remaining.length > 0 ? `\\n_(continued ${partNum}...)_` : \"\";\n\t\t\tparts.push(chunk + suffix);\n\t\t\tpartNum++;\n\t\t}\n\t\treturn parts;\n\t};\n\n\treturn {\n\t\tasync run(\n\t\t\tmessage: ChatMessage,\n\t\t\tresponseCtx: ChatResponseContext,\n\t\t\tplatform: PlatformInfo,\n\t\t): Promise<{ stopReason: string; errorMessage?: string }> {\n\t\t\t// Extract channelId from sessionKey (format: \"channelId:rootTs\" or just \"channelId\")\n\t\t\tconst sessionChannel = message.sessionKey.split(\":\")[0];\n\n\t\t\t// Ensure channel directory exists\n\t\t\tawait mkdir(channelDir, { recursive: true });\n\n\t\t\t// Sync messages from log.jsonl that arrived while we were offline or busy\n\t\t\t// Exclude the current message (it will be added via prompt())\n\t\t\t// Default sync range is 2 days (handled by syncLogToSessionManager)\n\t\t\tconst syncedCount = await syncLogToSessionManager(sessionManager, channelDir, message.id);\n\t\t\tif (syncedCount > 0) {\n\t\t\t\tlog.logInfo(`[${channelId}] Synced ${syncedCount} messages from log.jsonl`);\n\t\t\t}\n\n\t\t\t// Reload messages from context.jsonl\n\t\t\t// This picks up any messages synced above\n\t\t\tconst reloadedSession = sessionManager.buildSessionContext();\n\t\t\tif (reloadedSession.messages.length > 0) {\n\t\t\t\tagent.replaceMessages(reloadedSession.messages);\n\t\t\t\tlog.logInfo(`[${channelId}] Reloaded ${reloadedSession.messages.length} messages from context`);\n\t\t\t}\n\n\t\t\t// Update system prompt with fresh memory, channel/user info, and skills\n\t\t\tconst memory = await getMemory(channelDir);\n\t\t\tconst skills = loadMamaSkills(channelDir, workspacePath);\n\t\t\tconst systemPrompt = buildSystemPrompt(workspacePath, channelId, memory, sandboxConfig, platform, skills, agentConfig.maxUsersInPrompt ?? 50);\n\t\t\tsession.agent.setSystemPrompt(systemPrompt);\n\n\t\t\t// Set up file upload function\n\t\t\tsetUploadFunction(async (filePath: string, title?: string) => {\n\t\t\t\tconst hostPath = translateToHostPath(filePath, channelDir, workspacePath, channelId);\n\t\t\t\tawait responseCtx.uploadFile(hostPath, title);\n\t\t\t});\n\n\t\t\t// Reset per-run state\n\t\t\trunState.responseCtx = responseCtx;\n\t\t\trunState.logCtx = {\n\t\t\t\tchannelId: sessionChannel,\n\t\t\t\tuserName: message.userName,\n\t\t\t\tchannelName: undefined,\n\t\t\t};\n\t\t\trunState.pendingTools.clear();\n\t\t\trunState.totalUsage = {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t};\n\t\t\trunState.stopReason = \"stop\";\n\t\t\trunState.errorMessage = undefined;\n\n\t\t\t// Create queue for this run\n\t\t\tlet queueChain = Promise.resolve();\n\t\t\trunState.queue = {\n\t\t\t\tenqueue(fn: () => Promise<void>, errorContext: string): void {\n\t\t\t\t\tqueueChain = queueChain.then(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait fn();\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\t\t\tlog.logWarning(`API error (${errorContext})`, errMsg);\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tawait responseCtx.respondInThread(`_Error: ${errMsg}_`);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t// Ignore\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\tenqueueMessage(text: string, target: \"main\" | \"thread\", errorContext: string, _doLog = true): void {\n\t\t\t\t\tconst parts = splitForSlack(text);\n\t\t\t\t\tfor (const part of parts) {\n\t\t\t\t\t\tthis.enqueue(\n\t\t\t\t\t\t\t() => (target === \"main\" ? responseCtx.respond(part) : responseCtx.respondInThread(part)),\n\t\t\t\t\t\t\terrorContext,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t};\n\n\t\t\t// Log context info\n\t\t\tlog.logInfo(`Context sizes - system: ${systemPrompt.length} chars, memory: ${memory.length} chars`);\n\t\t\tlog.logInfo(`Channels: ${platform.channels.length}, Users: ${platform.users.length}`);\n\n\t\t\t// Build user message with timestamp and username prefix\n\t\t\t// Format: \"[YYYY-MM-DD HH:MM:SS+HH:MM] [username]: message\" so LLM knows when and who\n\t\t\tconst now = new Date();\n\t\t\tconst pad = (n: number) => n.toString().padStart(2, \"0\");\n\t\t\tconst offset = -now.getTimezoneOffset();\n\t\t\tconst offsetSign = offset >= 0 ? \"+\" : \"-\";\n\t\t\tconst offsetHours = pad(Math.floor(Math.abs(offset) / 60));\n\t\t\tconst offsetMins = pad(Math.abs(offset) % 60);\n\t\t\tconst timestamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}${offsetSign}${offsetHours}:${offsetMins}`;\n\t\t\tlet userMessage = `[${timestamp}] [${message.userName || \"unknown\"}]: ${message.text}`;\n\n\t\t\tconst imageAttachments: ImageContent[] = [];\n\t\t\tconst nonImagePaths: string[] = [];\n\n\t\t\tfor (const a of message.attachments || []) {\n\t\t\t\t// a.localPath is the path relative to the workspace (same as old a.local)\n\t\t\t\tconst fullPath = `${workspacePath}/${a.localPath}`;\n\t\t\t\tconst mimeType = getImageMimeType(a.localPath);\n\n\t\t\t\tif (mimeType && existsSync(fullPath)) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\timageAttachments.push({\n\t\t\t\t\t\t\ttype: \"image\",\n\t\t\t\t\t\t\tmimeType,\n\t\t\t\t\t\t\tdata: readFileSync(fullPath).toString(\"base64\"),\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tnonImagePaths.push(fullPath);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnonImagePaths.push(fullPath);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (nonImagePaths.length > 0) {\n\t\t\t\tuserMessage += `\\n\\n<slack_attachments>\\n${nonImagePaths.join(\"\\n\")}\\n</slack_attachments>`;\n\t\t\t}\n\n\t\t\t// Debug: write context to last_prompt.jsonl\n\t\t\tconst debugContext = {\n\t\t\t\tsystemPrompt,\n\t\t\t\tmessages: session.messages,\n\t\t\t\tnewUserMessage: userMessage,\n\t\t\t\timageAttachmentCount: imageAttachments.length,\n\t\t\t};\n\t\t\tawait writeFile(join(channelDir, \"last_prompt.jsonl\"), JSON.stringify(debugContext, null, 2));\n\n\t\t\tawait session.prompt(userMessage, imageAttachments.length > 0 ? { images: imageAttachments } : undefined);\n\n\t\t\t// Wait for queued messages\n\t\t\tawait queueChain;\n\n\t\t\t// Handle error case - update main message and post error to thread\n\t\t\tif (runState.stopReason === \"error\" && runState.errorMessage) {\n\t\t\t\ttry {\n\t\t\t\t\tawait responseCtx.replaceResponse(\"_Sorry, something went wrong_\");\n\t\t\t\t\tawait responseCtx.respondInThread(`_Error: ${runState.errorMessage}_`);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tlog.logWarning(\"Failed to post error message\", errMsg);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Final message update\n\t\t\t\tconst messages = session.messages;\n\t\t\t\tconst lastAssistant = messages.filter((m) => m.role === \"assistant\").pop();\n\t\t\t\tconst finalText =\n\t\t\t\t\tlastAssistant?.content\n\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t.join(\"\\n\") || \"\";\n\n\t\t\t\t// Check for [SILENT] marker - delete message and thread instead of posting\n\t\t\t\tif (finalText.trim() === \"[SILENT]\" || finalText.trim().startsWith(\"[SILENT]\")) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait responseCtx.deleteResponse();\n\t\t\t\t\t\tlog.logInfo(\"Silent response - deleted message and thread\");\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\t\tlog.logWarning(\"Failed to delete message for silent response\", errMsg);\n\t\t\t\t\t}\n\t\t\t\t} else if (finalText.trim()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst mainText =\n\t\t\t\t\t\t\tfinalText.length > SLACK_MAX_LENGTH\n\t\t\t\t\t\t\t\t? `${finalText.substring(0, SLACK_MAX_LENGTH - 50)}\\n\\n_(see thread for full response)_`\n\t\t\t\t\t\t\t\t: finalText;\n\t\t\t\t\t\tawait responseCtx.replaceResponse(mainText);\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tconst errMsg = err instanceof Error ? err.message : String(err);\n\t\t\t\t\t\tlog.logWarning(\"Failed to replace message with final text\", errMsg);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Log usage summary with context info\n\t\t\tif (runState.totalUsage.cost.total > 0) {\n\t\t\t\t// Get last non-aborted assistant message for context calculation\n\t\t\t\tconst messages = session.messages;\n\t\t\t\tconst lastAssistantMessage = messages\n\t\t\t\t\t.slice()\n\t\t\t\t\t.reverse()\n\t\t\t\t\t.find((m) => m.role === \"assistant\" && (m as any).stopReason !== \"aborted\") as any;\n\n\t\t\t\tconst contextTokens = lastAssistantMessage\n\t\t\t\t\t? lastAssistantMessage.usage.input +\n\t\t\t\t\t\tlastAssistantMessage.usage.output +\n\t\t\t\t\t\tlastAssistantMessage.usage.cacheRead +\n\t\t\t\t\t\tlastAssistantMessage.usage.cacheWrite\n\t\t\t\t\t: 0;\n\t\t\t\tconst contextWindow = model.contextWindow || 200000;\n\n\t\t\t\tconst summary = log.logUsageSummary(runState.logCtx!, runState.totalUsage, contextTokens, contextWindow);\n\t\t\t\trunState.queue.enqueue(() => responseCtx.respondInThread(summary), \"usage summary\");\n\t\t\t\tawait queueChain;\n\t\t\t}\n\n\t\t\t// Clear run state\n\t\t\trunState.responseCtx = null;\n\t\t\trunState.logCtx = null;\n\t\t\trunState.queue = null;\n\n\t\t\treturn { stopReason: runState.stopReason, errorMessage: runState.errorMessage };\n\t\t},\n\n\t\tabort(): void {\n\t\t\tsession.abort();\n\t\t},\n\t};\n}\n\n/**\n * Translate container path back to host path for file operations\n */\nfunction translateToHostPath(\n\tcontainerPath: string,\n\tchannelDir: string,\n\tworkspacePath: string,\n\tchannelId: string,\n): string {\n\tif (workspacePath === \"/workspace\") {\n\t\tconst prefix = `/workspace/${channelId}/`;\n\t\tif (containerPath.startsWith(prefix)) {\n\t\t\treturn join(channelDir, containerPath.slice(prefix.length));\n\t\t}\n\t\tif (containerPath.startsWith(\"/workspace/\")) {\n\t\t\treturn join(channelDir, \"..\", containerPath.slice(\"/workspace/\".length));\n\t\t}\n\t}\n\treturn containerPath;\n}\n"]}
|