@mariozechner/pi-mom 0.9.4 → 0.10.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/dist/agent.js CHANGED
@@ -3,10 +3,11 @@ import { getModel } from "@mariozechner/pi-ai";
3
3
  import { existsSync, readFileSync } from "fs";
4
4
  import { mkdir } from "fs/promises";
5
5
  import { join } from "path";
6
+ import * as log from "./log.js";
6
7
  import { createExecutor } from "./sandbox.js";
7
8
  import { createMomTools, setUploadFunction } from "./tools/index.js";
8
9
  // Hardcoded model for now
9
- const model = getModel("anthropic", "claude-opus-4-5");
10
+ const model = getModel("anthropic", "claude-sonnet-4-5");
10
11
  function getAnthropicApiKey() {
11
12
  const key = process.env.ANTHROPIC_OAUTH_TOKEN || process.env.ANTHROPIC_API_KEY;
12
13
  if (!key) {
@@ -25,9 +26,55 @@ function getRecentMessages(channelDir, count) {
25
26
  if (recentLines.length === 0) {
26
27
  return "(no message history yet)";
27
28
  }
28
- return recentLines.join("\n");
29
+ // Format as TSV for more concise system prompt
30
+ const formatted = [];
31
+ for (const line of recentLines) {
32
+ try {
33
+ const msg = JSON.parse(line);
34
+ const date = (msg.date || "").substring(0, 19);
35
+ const user = msg.userName || msg.user;
36
+ const text = msg.text || "";
37
+ const attachments = (msg.attachments || []).map((a) => a.local).join(",");
38
+ formatted.push(`${date}\t${user}\t${text}\t${attachments}`);
39
+ }
40
+ catch (error) { }
41
+ }
42
+ return formatted.join("\n");
43
+ }
44
+ function getMemory(channelDir) {
45
+ const parts = [];
46
+ // Read workspace-level memory (shared across all channels)
47
+ const workspaceMemoryPath = join(channelDir, "..", "MEMORY.md");
48
+ if (existsSync(workspaceMemoryPath)) {
49
+ try {
50
+ const content = readFileSync(workspaceMemoryPath, "utf-8").trim();
51
+ if (content) {
52
+ parts.push("### Global Workspace Memory\n" + content);
53
+ }
54
+ }
55
+ catch (error) {
56
+ log.logWarning("Failed to read workspace memory", `${workspaceMemoryPath}: ${error}`);
57
+ }
58
+ }
59
+ // Read channel-specific memory
60
+ const channelMemoryPath = join(channelDir, "MEMORY.md");
61
+ if (existsSync(channelMemoryPath)) {
62
+ try {
63
+ const content = readFileSync(channelMemoryPath, "utf-8").trim();
64
+ if (content) {
65
+ parts.push("### Channel-Specific Memory\n" + content);
66
+ }
67
+ }
68
+ catch (error) {
69
+ log.logWarning("Failed to read channel memory", `${channelMemoryPath}: ${error}`);
70
+ }
71
+ }
72
+ if (parts.length === 0) {
73
+ return "(no working memory yet)";
74
+ }
75
+ return parts.join("\n\n");
29
76
  }
30
- function buildSystemPrompt(workspacePath, channelId, recentMessages, sandboxConfig) {
77
+ function buildSystemPrompt(workspacePath, channelId, memory, sandboxConfig) {
31
78
  const channelPath = `${workspacePath}/${channelId}`;
32
79
  const isDocker = sandboxConfig.type === "docker";
33
80
  const envDescription = isDocker
@@ -38,8 +85,15 @@ function buildSystemPrompt(workspacePath, channelId, recentMessages, sandboxConf
38
85
  : `You are running directly on the host machine.
39
86
  - Be careful with system modifications
40
87
  - Use the system's package manager if needed`;
88
+ const currentDate = new Date().toISOString().split("T")[0]; // YYYY-MM-DD
89
+ const currentDateTime = new Date().toISOString(); // Full ISO 8601
41
90
  return `You are mom, a helpful Slack bot assistant.
42
91
 
92
+ ## Current Date and Time
93
+ - Date: ${currentDate}
94
+ - Full timestamp: ${currentDateTime}
95
+ - Use this when working with dates or searching logs
96
+
43
97
  ## Communication Style
44
98
  - Be concise and professional
45
99
  - Do not use emojis unless the user communicates informally with you
@@ -60,20 +114,89 @@ ${envDescription}
60
114
  ## Your Workspace
61
115
  Your working directory is: ${channelPath}
62
116
 
63
- ### Scratchpad
64
- Use ${channelPath}/scratch/ for temporary work like cloning repos, generating files, etc.
65
- This directory persists across conversations, so you can reference previous work.
117
+ ### Directory Structure
118
+ - ${workspacePath}/ - Root workspace (shared across all channels)
119
+ - MEMORY.md - GLOBAL memory visible to all channels (write global info here)
120
+ - ${channelId}/ - This channel's directory
121
+ - MEMORY.md - CHANNEL-SPECIFIC memory (only visible in this channel)
122
+ - scratch/ - Your working directory for files, repos, etc.
123
+ - log.jsonl - Message history in JSONL format (one JSON object per line)
124
+ - attachments/ - Files shared by users (managed by system, read-only)
125
+
126
+ ### Message History Format
127
+ Each line in log.jsonl contains:
128
+ {
129
+ "date": "2025-11-26T10:44:00.123Z", // ISO 8601 - easy to grep by date!
130
+ "ts": "1732619040.123456", // Slack timestamp or epoch ms
131
+ "user": "U123ABC", // User ID or "bot"
132
+ "userName": "mario", // User handle (optional)
133
+ "text": "message text",
134
+ "isBot": false
135
+ }
136
+
137
+ **⚠️ CRITICAL: Efficient Log Queries (Avoid Context Overflow)**
138
+
139
+ Log files can be VERY LARGE (100K+ lines). The problem is getting too MANY messages, not message length.
140
+ Each message can be up to 10k chars - that's fine. Use head/tail to LIMIT NUMBER OF MESSAGES (10-50 at a time).
141
+
142
+ **Install jq first (if not already):**
143
+ \`\`\`bash
144
+ ${isDocker ? "apk add jq" : "# jq should be available, or install via package manager"}
145
+ \`\`\`
146
+
147
+ **Essential query patterns:**
148
+ \`\`\`bash
149
+ # Last N messages (compact JSON output)
150
+ tail -20 log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text, attachments: [(.attachments // [])[].local]}'
151
+
152
+ # Or TSV format (easier to read)
153
+ tail -20 log.jsonl | jq -r '[.date[0:19], (.userName // .user), .text, ((.attachments // []) | map(.local) | join(","))] | @tsv'
154
+
155
+ # Search by date (LIMIT with head/tail!)
156
+ grep '"date":"2025-11-26' log.jsonl | tail -30 | jq -c '{date: .date[0:19], user: (.userName // .user), text, attachments: [(.attachments // [])[].local]}'
157
+
158
+ # Messages from specific user (count first, then limit)
159
+ grep '"userName":"mario"' log.jsonl | wc -l # Check count first
160
+ grep '"userName":"mario"' log.jsonl | tail -20 | jq -c '{date: .date[0:19], user: .userName, text, attachments: [(.attachments // [])[].local]}'
161
+
162
+ # Only count (when you just need the number)
163
+ grep '"isBot":false' log.jsonl | wc -l
164
+
165
+ # Messages with attachments only (limit!)
166
+ grep '"attachments":[{' log.jsonl | tail -10 | jq -r '[.date[0:16], (.userName // .user), .text, (.attachments | map(.local) | join(","))] | @tsv'
167
+ \`\`\`
168
+
169
+ **KEY RULE:** Always pipe through 'head -N' or 'tail -N' to limit results BEFORE parsing with jq!
170
+ \`\`\`
171
+
172
+ **Date filtering:**
173
+ - Today: grep '"date":"${currentDate}' log.jsonl
174
+ - Yesterday: grep '"date":"2025-11-25' log.jsonl
175
+ - Date range: grep '"date":"2025-11-(26|27|28)' log.jsonl
176
+ - Time range: grep -E '"date":"2025-11-26T(09|10|11):' log.jsonl
66
177
 
67
- ### Channel Data (read-only, managed by the system)
68
- - Message history: ${channelPath}/log.jsonl
69
- - Attachments from users: ${channelPath}/attachments/
178
+ ### Working Memory System
179
+ You can maintain working memory across conversations by writing MEMORY.md files.
70
180
 
71
- You can:
72
- - Configure tools and save credentials in your home directory
73
- - Create files and directories in your scratchpad
181
+ **IMPORTANT PATH RULES:**
182
+ - Global memory (all channels): ${workspacePath}/MEMORY.md
183
+ - Channel memory (this channel only): ${channelPath}/MEMORY.md
74
184
 
75
- ### Recent Messages (last 50)
76
- ${recentMessages}
185
+ **What to remember:**
186
+ - Project details and architecture → Global memory
187
+ - User preferences and coding style → Global memory
188
+ - Channel-specific context → Channel memory
189
+ - Recurring tasks and patterns → Appropriate memory file
190
+ - Credentials locations (never actual secrets) → Global memory
191
+ - Decisions made and their rationale → Appropriate memory file
192
+
193
+ **When to update:**
194
+ - After learning something important that will help in future conversations
195
+ - When user asks you to remember something
196
+ - When you discover project structure or conventions
197
+
198
+ ### Current Working Memory
199
+ ${memory}
77
200
 
78
201
  ## Tools
79
202
  You have access to: bash, read, edit, write, attach tools.
@@ -100,6 +223,61 @@ function truncate(text, maxLen) {
100
223
  return text;
101
224
  return text.substring(0, maxLen - 3) + "...";
102
225
  }
226
+ function extractToolResultText(result) {
227
+ // If it's already a string, return it
228
+ if (typeof result === "string") {
229
+ return result;
230
+ }
231
+ // If it's an object with content array (tool result format)
232
+ if (result &&
233
+ typeof result === "object" &&
234
+ "content" in result &&
235
+ Array.isArray(result.content)) {
236
+ const content = result.content;
237
+ const textParts = [];
238
+ for (const part of content) {
239
+ if (part.type === "text" && part.text) {
240
+ textParts.push(part.text);
241
+ }
242
+ }
243
+ if (textParts.length > 0) {
244
+ return textParts.join("\n");
245
+ }
246
+ }
247
+ // Fallback to JSON
248
+ return JSON.stringify(result);
249
+ }
250
+ function formatToolArgsForSlack(_toolName, args) {
251
+ const lines = [];
252
+ for (const [key, value] of Object.entries(args)) {
253
+ // Skip the label - it's already shown
254
+ if (key === "label")
255
+ continue;
256
+ // For read tool, format path with offset/limit
257
+ if (key === "path" && typeof value === "string") {
258
+ const offset = args.offset;
259
+ const limit = args.limit;
260
+ if (offset !== undefined && limit !== undefined) {
261
+ lines.push(`${value}:${offset}-${offset + limit}`);
262
+ }
263
+ else {
264
+ lines.push(value);
265
+ }
266
+ continue;
267
+ }
268
+ // Skip offset/limit since we already handled them
269
+ if (key === "offset" || key === "limit")
270
+ continue;
271
+ // For other values, format them
272
+ if (typeof value === "string") {
273
+ lines.push(value);
274
+ }
275
+ else {
276
+ lines.push(JSON.stringify(value));
277
+ }
278
+ }
279
+ return lines.join("\n");
280
+ }
103
281
  export function createAgentRunner(sandboxConfig) {
104
282
  let agent = null;
105
283
  const executor = createExecutor(sandboxConfig);
@@ -110,7 +288,8 @@ export function createAgentRunner(sandboxConfig) {
110
288
  const channelId = ctx.message.channel;
111
289
  const workspacePath = executor.getWorkspacePath(channelDir.replace(`/${channelId}`, ""));
112
290
  const recentMessages = getRecentMessages(channelDir, 50);
113
- const systemPrompt = buildSystemPrompt(workspacePath, channelId, recentMessages, sandboxConfig);
291
+ const memory = getMemory(channelDir);
292
+ const systemPrompt = buildSystemPrompt(workspacePath, channelId, memory, sandboxConfig);
114
293
  // Set up file upload function for the attach tool
115
294
  // For Docker, we need to translate paths back to host
116
295
  setUploadFunction(async (filePath, title) => {
@@ -131,8 +310,30 @@ export function createAgentRunner(sandboxConfig) {
131
310
  getApiKey: async () => getAnthropicApiKey(),
132
311
  }),
133
312
  });
134
- // Track pending tool calls to pair args with results
313
+ // Create logging context
314
+ const logCtx = {
315
+ channelId: ctx.message.channel,
316
+ userName: ctx.message.userName,
317
+ channelName: ctx.channelName,
318
+ };
319
+ // Track pending tool calls to pair args with results and timing
135
320
  const pendingTools = new Map();
321
+ // Track usage across all assistant messages in this run
322
+ const totalUsage = {
323
+ input: 0,
324
+ output: 0,
325
+ cacheRead: 0,
326
+ cacheWrite: 0,
327
+ cost: {
328
+ input: 0,
329
+ output: 0,
330
+ cacheRead: 0,
331
+ cacheWrite: 0,
332
+ total: 0,
333
+ },
334
+ };
335
+ // Track stop reason
336
+ let stopReason = "stop";
136
337
  // Subscribe to events
137
338
  agent.subscribe(async (event) => {
138
339
  switch (event.type) {
@@ -140,11 +341,16 @@ export function createAgentRunner(sandboxConfig) {
140
341
  const args = event.args;
141
342
  const label = args.label || event.toolName;
142
343
  // Store args to pair with result later
143
- pendingTools.set(event.toolCallId, { toolName: event.toolName, args: event.args });
344
+ pendingTools.set(event.toolCallId, {
345
+ toolName: event.toolName,
346
+ args: event.args,
347
+ startTime: Date.now(),
348
+ });
144
349
  // Log to console
145
- console.log(`\n[Tool] ${event.toolName}: ${JSON.stringify(event.args)}`);
350
+ log.logToolStart(logCtx, event.toolName, label, event.args);
146
351
  // Log to jsonl
147
352
  await store.logMessage(ctx.message.channel, {
353
+ date: new Date().toISOString(),
148
354
  ts: Date.now().toString(),
149
355
  user: "bot",
150
356
  text: `[Tool] ${event.toolName}: ${JSON.stringify(event.args)}`,
@@ -156,13 +362,20 @@ export function createAgentRunner(sandboxConfig) {
156
362
  break;
157
363
  }
158
364
  case "tool_execution_end": {
159
- const resultStr = typeof event.result === "string" ? event.result : JSON.stringify(event.result);
365
+ const resultStr = extractToolResultText(event.result);
160
366
  const pending = pendingTools.get(event.toolCallId);
161
367
  pendingTools.delete(event.toolCallId);
368
+ const durationMs = pending ? Date.now() - pending.startTime : 0;
162
369
  // Log to console
163
- console.log(`[Tool Result] ${event.isError ? "ERROR: " : ""}${truncate(resultStr, 1000)}\n`);
370
+ if (event.isError) {
371
+ log.logToolError(logCtx, event.toolName, durationMs, resultStr);
372
+ }
373
+ else {
374
+ log.logToolSuccess(logCtx, event.toolName, durationMs, resultStr);
375
+ }
164
376
  // Log to jsonl
165
377
  await store.logMessage(ctx.message.channel, {
378
+ date: new Date().toISOString(),
166
379
  ts: Date.now().toString(),
167
380
  user: "bot",
168
381
  text: `[Tool Result] ${event.toolName}: ${event.isError ? "ERROR: " : ""}${truncate(resultStr, 1000)}`,
@@ -170,15 +383,22 @@ export function createAgentRunner(sandboxConfig) {
170
383
  isBot: true,
171
384
  });
172
385
  // Post args + result together in thread
173
- const argsStr = pending ? JSON.stringify(pending.args, null, 2) : "(args not found)";
386
+ const label = pending?.args ? pending.args.label : undefined;
387
+ const argsFormatted = pending
388
+ ? formatToolArgsForSlack(event.toolName, pending.args)
389
+ : "(args not found)";
390
+ const duration = (durationMs / 1000).toFixed(1);
174
391
  const threadResult = truncate(resultStr, 2000);
175
- await ctx.respondInThread(`*[${event.toolName}]* ${event.isError ? "" : "✓"}\n` +
176
- "```\n" +
177
- argsStr +
178
- "\n```\n" +
179
- "*Result:*\n```\n" +
180
- threadResult +
181
- "\n```");
392
+ let threadMessage = `*${event.isError ? "" : "✓"} ${event.toolName}*`;
393
+ if (label) {
394
+ threadMessage += `: ${label}`;
395
+ }
396
+ threadMessage += ` (${duration}s)\n`;
397
+ if (argsFormatted) {
398
+ threadMessage += "```\n" + argsFormatted + "\n```\n";
399
+ }
400
+ threadMessage += "*Result:*\n```\n" + threadResult + "\n```";
401
+ await ctx.respondInThread(threadMessage);
182
402
  // Show brief error in main message if failed
183
403
  if (event.isError) {
184
404
  await ctx.respond(`_Error: ${truncate(resultStr, 200)}_`);
@@ -186,24 +406,33 @@ export function createAgentRunner(sandboxConfig) {
186
406
  break;
187
407
  }
188
408
  case "message_update": {
189
- const ev = event.assistantMessageEvent;
190
- // Stream deltas to console
191
- if (ev.type === "text_delta") {
192
- process.stdout.write(ev.delta);
193
- }
194
- else if (ev.type === "thinking_delta") {
195
- process.stdout.write(ev.delta);
196
- }
409
+ // No longer stream to console - just track that we're streaming
197
410
  break;
198
411
  }
199
412
  case "message_start":
200
413
  if (event.message.role === "assistant") {
201
- process.stdout.write("\n");
414
+ log.logResponseStart(logCtx);
202
415
  }
203
416
  break;
204
417
  case "message_end":
205
418
  if (event.message.role === "assistant") {
206
- process.stdout.write("\n");
419
+ const assistantMsg = event.message; // AssistantMessage type
420
+ // Track stop reason
421
+ if (assistantMsg.stopReason) {
422
+ stopReason = assistantMsg.stopReason;
423
+ }
424
+ // Accumulate usage
425
+ if (assistantMsg.usage) {
426
+ totalUsage.input += assistantMsg.usage.input;
427
+ totalUsage.output += assistantMsg.usage.output;
428
+ totalUsage.cacheRead += assistantMsg.usage.cacheRead;
429
+ totalUsage.cacheWrite += assistantMsg.usage.cacheWrite;
430
+ totalUsage.cost.input += assistantMsg.usage.cost.input;
431
+ totalUsage.cost.output += assistantMsg.usage.cost.output;
432
+ totalUsage.cost.cacheRead += assistantMsg.usage.cost.cacheRead;
433
+ totalUsage.cost.cacheWrite += assistantMsg.usage.cost.cacheWrite;
434
+ totalUsage.cost.total += assistantMsg.usage.cost.total;
435
+ }
207
436
  // Extract text from assistant message
208
437
  const content = event.message.content;
209
438
  let text = "";
@@ -214,13 +443,26 @@ export function createAgentRunner(sandboxConfig) {
214
443
  }
215
444
  if (text.trim()) {
216
445
  await ctx.respond(text);
446
+ log.logResponseComplete(logCtx, text.length);
217
447
  }
218
448
  }
219
449
  break;
220
450
  }
221
451
  });
222
452
  // Run the agent with user's message
223
- await agent.prompt(ctx.message.text || "(attached files)");
453
+ // Prepend recent messages to the user prompt (not system prompt) for better caching
454
+ const userPrompt = `Recent conversation history (last 50 messages):\n` +
455
+ `Format: date TAB user TAB text TAB attachments\n\n` +
456
+ `${recentMessages}\n\n` +
457
+ `---\n\n` +
458
+ `Current message: ${ctx.message.text || "(attached files)"}`;
459
+ await agent.prompt(userPrompt);
460
+ // Log usage summary if there was any usage
461
+ if (totalUsage.cost.total > 0) {
462
+ const summary = log.logUsageSummary(logCtx, totalUsage);
463
+ await ctx.respondInThread(summary);
464
+ }
465
+ return { stopReason };
224
466
  },
225
467
  abort() {
226
468
  agent?.abort();
package/dist/agent.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAmB,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AACxF,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,OAAO,EAAE,cAAc,EAAsB,MAAM,cAAc,CAAC;AAGlE,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErE,0BAA0B;AAC1B,MAAM,KAAK,GAAG,QAAQ,CAAC,WAAW,EAAE,iBAAiB,CAAC,CAAC;AAOvD,SAAS,kBAAkB,GAAW;IACrC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,qBAAqB,IAAI,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC;IAC/E,IAAI,CAAC,GAAG,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,GAAG,CAAC;AAAA,CACX;AAED,SAAS,iBAAiB,CAAC,UAAkB,EAAE,KAAa,EAAU;IACrE,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;IAC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C;oCAC1B,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC;gCACnB,CAAC;4BACF,CAAC;4BACD,IAAI,IAAI,CAAC,IAAI,EAAE,EAAE,CAAC;gCACjB,MAAM,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;4BACzB,CAAC;wBACF,CAAC;wBACD,MAAM;gBACR,CAAC;YAAA,CACD,CAAC,CAAC;YAEH,oCAAoC;YACpC,MAAM,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,IAAI,kBAAkB,CAAC,CAAC;QAAA,CAC3D;QAED,KAAK,GAAS;YACb,KAAK,EAAE,KAAK,EAAE,CAAC;QAAA,CACf;KACD,CAAC;AAAA,CACF;AAED;;GAEG;AACH,SAAS,mBAAmB,CAC3B,aAAqB,EACrB,UAAkB,EAClB,aAAqB,EACrB,SAAiB,EACR;IACT,IAAI,aAAa,KAAK,YAAY,EAAE,CAAC;QACpC,gEAAgE;QAChE,MAAM,MAAM,GAAG,cAAc,SAAS,GAAG,CAAC;QAC1C,IAAI,aAAa,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC;YACtC,OAAO,IAAI,CAAC,UAAU,EAAE,aAAa,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;QAC7D,CAAC;QACD,iCAAiC;QACjC,IAAI,aAAa,CAAC,UAAU,CAAC,aAAa,CAAC,EAAE,CAAC;YAC7C,OAAO,IAAI,CAAC,UAAU,EAAE,IAAI,EAAE,aAAa,CAAC,KAAK,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;QAC1E,CAAC;IACF,CAAC;IACD,mCAAmC;IACnC,OAAO,aAAa,CAAC;AAAA,CACrB","sourcesContent":["import { Agent, type AgentEvent, ProviderTransport } from \"@mariozechner/pi-agent-core\";\nimport { getModel } from \"@mariozechner/pi-ai\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { mkdir } from \"fs/promises\";\nimport { join } from \"path\";\n\nimport { createExecutor, type SandboxConfig } from \"./sandbox.js\";\nimport type { SlackContext } from \"./slack.js\";\nimport type { ChannelStore } from \"./store.js\";\nimport { createMomTools, setUploadFunction } from \"./tools/index.js\";\n\n// Hardcoded model for now\nconst model = getModel(\"anthropic\", \"claude-opus-4-5\");\n\nexport interface AgentRunner {\n\trun(ctx: SlackContext, channelDir: string, store: ChannelStore): Promise<void>;\n\tabort(): void;\n}\n\nfunction getAnthropicApiKey(): string {\n\tconst key = process.env.ANTHROPIC_OAUTH_TOKEN || process.env.ANTHROPIC_API_KEY;\n\tif (!key) {\n\t\tthrow new Error(\"ANTHROPIC_OAUTH_TOKEN or ANTHROPIC_API_KEY must be set\");\n\t}\n\treturn key;\n}\n\nfunction getRecentMessages(channelDir: string, count: number): string {\n\tconst logPath = join(channelDir, \"log.jsonl\");\n\tif (!existsSync(logPath)) {\n\t\treturn \"(no message history yet)\";\n\t}\n\n\tconst content = readFileSync(logPath, \"utf-8\");\n\tconst lines = content.trim().split(\"\\n\").filter(Boolean);\n\tconst recentLines = lines.slice(-count);\n\n\tif (recentLines.length === 0) {\n\t\treturn \"(no message history yet)\";\n\t}\n\n\treturn recentLines.join(\"\\n\");\n}\n\nfunction buildSystemPrompt(\n\tworkspacePath: string,\n\tchannelId: string,\n\trecentMessages: string,\n\tsandboxConfig: SandboxConfig,\n): string {\n\tconst channelPath = `${workspacePath}/${channelId}`;\n\tconst isDocker = sandboxConfig.type === \"docker\";\n\n\tconst envDescription = isDocker\n\t\t? `You are running inside a Docker container (Alpine Linux).\n- Install tools with: apk add <package>\n- Your changes persist across sessions\n- You have full control over this container`\n\t\t: `You are running directly on the host machine.\n- Be careful with system modifications\n- Use the system's package manager if needed`;\n\n\treturn `You are mom, a helpful Slack bot assistant.\n\n## Communication Style\n- Be concise and professional\n- Do not use emojis unless the user communicates informally with you\n- Get to the point quickly\n- If you need clarification, ask directly\n- Use Slack's mrkdwn format (NOT standard Markdown):\n - Bold: *text* (single asterisks)\n - Italic: _text_\n - Strikethrough: ~text~\n - Code: \\`code\\`\n - Code block: \\`\\`\\`code\\`\\`\\`\n - Links: <url|text>\n - Do NOT use **double asterisks** or [markdown](links)\n\n## Your Environment\n${envDescription}\n\n## Your Workspace\nYour working directory is: ${channelPath}\n\n### Scratchpad\nUse ${channelPath}/scratch/ for temporary work like cloning repos, generating files, etc.\nThis directory persists across conversations, so you can reference previous work.\n\n### Channel Data (read-only, managed by the system)\n- Message history: ${channelPath}/log.jsonl\n- Attachments from users: ${channelPath}/attachments/\n\nYou can:\n- Configure tools and save credentials in your home directory\n- Create files and directories in your scratchpad\n\n### Recent Messages (last 50)\n${recentMessages}\n\n## Tools\nYou have access to: bash, read, edit, write, attach tools.\n- bash: Run shell commands (this is your main tool)\n- read: Read files\n- edit: Edit files surgically\n- write: Create/overwrite files\n- attach: Share a file with the user in Slack\n\nEach tool requires a \"label\" parameter - brief description shown to the user.\n\n## Guidelines\n- Be concise and helpful\n- Use bash for most operations\n- If you need a tool, install it\n- If you need credentials, ask the user\n\n## CRITICAL\n- DO NOT USE EMOJIS. KEEP YOUR RESPONSES AS SHORT AS POSSIBLE.\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\nexport function createAgentRunner(sandboxConfig: SandboxConfig): AgentRunner {\n\tlet agent: Agent | null = null;\n\tconst executor = createExecutor(sandboxConfig);\n\n\treturn {\n\t\tasync run(ctx: SlackContext, channelDir: string, store: ChannelStore): Promise<void> {\n\t\t\t// Ensure channel directory exists\n\t\t\tawait mkdir(channelDir, { recursive: true });\n\n\t\t\tconst channelId = ctx.message.channel;\n\t\t\tconst workspacePath = executor.getWorkspacePath(channelDir.replace(`/${channelId}`, \"\"));\n\t\t\tconst recentMessages = getRecentMessages(channelDir, 50);\n\t\t\tconst systemPrompt = buildSystemPrompt(workspacePath, channelId, recentMessages, sandboxConfig);\n\n\t\t\t// Set up file upload function for the attach tool\n\t\t\t// For Docker, we need to translate paths back to host\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 ctx.uploadFile(hostPath, title);\n\t\t\t});\n\n\t\t\t// Create tools with executor\n\t\t\tconst tools = createMomTools(executor);\n\n\t\t\t// Create ephemeral agent\n\t\t\tagent = new Agent({\n\t\t\t\tinitialState: {\n\t\t\t\t\tsystemPrompt,\n\t\t\t\t\tmodel,\n\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\ttools,\n\t\t\t\t},\n\t\t\t\ttransport: new ProviderTransport({\n\t\t\t\t\tgetApiKey: async () => getAnthropicApiKey(),\n\t\t\t\t}),\n\t\t\t});\n\n\t\t\t// Track pending tool calls to pair args with results\n\t\t\tconst pendingTools = new Map<string, { toolName: string; args: unknown }>();\n\n\t\t\t// Subscribe to events\n\t\t\tagent.subscribe(async (event: AgentEvent) => {\n\t\t\t\tswitch (event.type) {\n\t\t\t\t\tcase \"tool_execution_start\": {\n\t\t\t\t\t\tconst args = event.args as { label?: string };\n\t\t\t\t\t\tconst label = args.label || event.toolName;\n\n\t\t\t\t\t\t// Store args to pair with result later\n\t\t\t\t\t\tpendingTools.set(event.toolCallId, { toolName: event.toolName, args: event.args });\n\n\t\t\t\t\t\t// Log to console\n\t\t\t\t\t\tconsole.log(`\\n[Tool] ${event.toolName}: ${JSON.stringify(event.args)}`);\n\n\t\t\t\t\t\t// Log to jsonl\n\t\t\t\t\t\tawait store.logMessage(ctx.message.channel, {\n\t\t\t\t\t\t\tts: Date.now().toString(),\n\t\t\t\t\t\t\tuser: \"bot\",\n\t\t\t\t\t\t\ttext: `[Tool] ${event.toolName}: ${JSON.stringify(event.args)}`,\n\t\t\t\t\t\t\tattachments: [],\n\t\t\t\t\t\t\tisBot: true,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t// Show label in main message only\n\t\t\t\t\t\tawait ctx.respond(`_${label}_`);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"tool_execution_end\": {\n\t\t\t\t\t\tconst resultStr = typeof event.result === \"string\" ? event.result : JSON.stringify(event.result);\n\t\t\t\t\t\tconst pending = pendingTools.get(event.toolCallId);\n\t\t\t\t\t\tpendingTools.delete(event.toolCallId);\n\n\t\t\t\t\t\t// Log to console\n\t\t\t\t\t\tconsole.log(`[Tool Result] ${event.isError ? \"ERROR: \" : \"\"}${truncate(resultStr, 1000)}\\n`);\n\n\t\t\t\t\t\t// Log to jsonl\n\t\t\t\t\t\tawait store.logMessage(ctx.message.channel, {\n\t\t\t\t\t\t\tts: Date.now().toString(),\n\t\t\t\t\t\t\tuser: \"bot\",\n\t\t\t\t\t\t\ttext: `[Tool Result] ${event.toolName}: ${event.isError ? \"ERROR: \" : \"\"}${truncate(resultStr, 1000)}`,\n\t\t\t\t\t\t\tattachments: [],\n\t\t\t\t\t\t\tisBot: true,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t// Post args + result together in thread\n\t\t\t\t\t\tconst argsStr = pending ? JSON.stringify(pending.args, null, 2) : \"(args not found)\";\n\t\t\t\t\t\tconst threadResult = truncate(resultStr, 2000);\n\t\t\t\t\t\tawait ctx.respondInThread(\n\t\t\t\t\t\t\t`*[${event.toolName}]* ${event.isError ? \"❌\" : \"✓\"}\\n` +\n\t\t\t\t\t\t\t\t\"```\\n\" +\n\t\t\t\t\t\t\t\targsStr +\n\t\t\t\t\t\t\t\t\"\\n```\\n\" +\n\t\t\t\t\t\t\t\t\"*Result:*\\n```\\n\" +\n\t\t\t\t\t\t\t\tthreadResult +\n\t\t\t\t\t\t\t\t\"\\n```\",\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\t// Show brief error in main message if failed\n\t\t\t\t\t\tif (event.isError) {\n\t\t\t\t\t\t\tawait ctx.respond(`_Error: ${truncate(resultStr, 200)}_`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"message_update\": {\n\t\t\t\t\t\tconst ev = event.assistantMessageEvent;\n\t\t\t\t\t\t// Stream deltas to console\n\t\t\t\t\t\tif (ev.type === \"text_delta\") {\n\t\t\t\t\t\t\tprocess.stdout.write(ev.delta);\n\t\t\t\t\t\t} else if (ev.type === \"thinking_delta\") {\n\t\t\t\t\t\t\tprocess.stdout.write(ev.delta);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"message_start\":\n\t\t\t\t\t\tif (event.message.role === \"assistant\") {\n\t\t\t\t\t\t\tprocess.stdout.write(\"\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"message_end\":\n\t\t\t\t\t\tif (event.message.role === \"assistant\") {\n\t\t\t\t\t\t\tprocess.stdout.write(\"\\n\");\n\t\t\t\t\t\t\t// Extract text from assistant message\n\t\t\t\t\t\t\tconst content = event.message.content;\n\t\t\t\t\t\t\tlet text = \"\";\n\t\t\t\t\t\t\tfor (const part of content) {\n\t\t\t\t\t\t\t\tif (part.type === \"text\") {\n\t\t\t\t\t\t\t\t\ttext += part.text;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (text.trim()) {\n\t\t\t\t\t\t\t\tawait ctx.respond(text);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// Run the agent with user's message\n\t\t\tawait agent.prompt(ctx.message.text || \"(attached files)\");\n\t\t},\n\n\t\tabort(): void {\n\t\t\tagent?.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\t// Docker mode - translate /workspace/channelId/... to host path\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\t// Maybe it's just /workspace/...\n\t\tif (containerPath.startsWith(\"/workspace/\")) {\n\t\t\treturn join(channelDir, \"..\", containerPath.slice(\"/workspace/\".length));\n\t\t}\n\t}\n\t// Host mode or already a host path\n\treturn containerPath;\n}\n"]}
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAmB,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AACxF,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,cAAc,EAAsB,MAAM,cAAc,CAAC;AAGlE,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErE,0BAA0B;AAC1B,MAAM,KAAK,GAAG,QAAQ,CAAC,WAAW,EAAE,mBAAmB,CAAC,CAAC;AAOzD,SAAS,kBAAkB,GAAW;IACrC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,qBAAqB,IAAI,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC;IAC/E,IAAI,CAAC,GAAG,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,GAAG,CAAC;AAAA,CACX;AAED,SAAS,iBAAiB,CAAC,UAAkB,EAAE,KAAa,EAAU;IACrE,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU,EAAE,WAAW,CAAC,C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AE,CAAC;YACtC,OAAO,IAAI,CAAC,UAAU,EAAE,aAAa,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;QAC7D,CAAC;QACD,iCAAiC;QACjC,IAAI,aAAa,CAAC,UAAU,CAAC,aAAa,CAAC,EAAE,CAAC;YAC7C,OAAO,IAAI,CAAC,UAAU,EAAE,IAAI,EAAE,aAAa,CAAC,KAAK,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;QAC1E,CAAC;IACF,CAAC;IACD,mCAAmC;IACnC,OAAO,aAAa,CAAC;AAAA,CACrB","sourcesContent":["import { Agent, type AgentEvent, ProviderTransport } from \"@mariozechner/pi-agent-core\";\nimport { getModel } from \"@mariozechner/pi-ai\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { mkdir } from \"fs/promises\";\nimport { join } from \"path\";\nimport * as log from \"./log.js\";\nimport { createExecutor, type SandboxConfig } from \"./sandbox.js\";\nimport type { SlackContext } from \"./slack.js\";\nimport type { ChannelStore } from \"./store.js\";\nimport { createMomTools, setUploadFunction } from \"./tools/index.js\";\n\n// Hardcoded model for now\nconst model = getModel(\"anthropic\", \"claude-sonnet-4-5\");\n\nexport interface AgentRunner {\n\trun(ctx: SlackContext, channelDir: string, store: ChannelStore): Promise<{ stopReason: string }>;\n\tabort(): void;\n}\n\nfunction getAnthropicApiKey(): string {\n\tconst key = process.env.ANTHROPIC_OAUTH_TOKEN || process.env.ANTHROPIC_API_KEY;\n\tif (!key) {\n\t\tthrow new Error(\"ANTHROPIC_OAUTH_TOKEN or ANTHROPIC_API_KEY must be set\");\n\t}\n\treturn key;\n}\n\nfunction getRecentMessages(channelDir: string, count: number): string {\n\tconst logPath = join(channelDir, \"log.jsonl\");\n\tif (!existsSync(logPath)) {\n\t\treturn \"(no message history yet)\";\n\t}\n\n\tconst content = readFileSync(logPath, \"utf-8\");\n\tconst lines = content.trim().split(\"\\n\").filter(Boolean);\n\tconst recentLines = lines.slice(-count);\n\n\tif (recentLines.length === 0) {\n\t\treturn \"(no message history yet)\";\n\t}\n\n\t// Format as TSV for more concise system prompt\n\tconst formatted: string[] = [];\n\tfor (const line of recentLines) {\n\t\ttry {\n\t\t\tconst msg = JSON.parse(line);\n\t\t\tconst date = (msg.date || \"\").substring(0, 19);\n\t\t\tconst user = msg.userName || msg.user;\n\t\t\tconst text = msg.text || \"\";\n\t\t\tconst attachments = (msg.attachments || []).map((a: { local: string }) => a.local).join(\",\");\n\t\t\tformatted.push(`${date}\\t${user}\\t${text}\\t${attachments}`);\n\t\t} catch (error) {}\n\t}\n\n\treturn formatted.join(\"\\n\");\n}\n\nfunction getMemory(channelDir: string): 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 = readFileSync(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 = readFileSync(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 buildSystemPrompt(\n\tworkspacePath: string,\n\tchannelId: string,\n\tmemory: string,\n\tsandboxConfig: SandboxConfig,\n): string {\n\tconst channelPath = `${workspacePath}/${channelId}`;\n\tconst isDocker = sandboxConfig.type === \"docker\";\n\n\tconst envDescription = isDocker\n\t\t? `You are running inside a Docker container (Alpine Linux).\n- Install tools with: apk add <package>\n- Your changes persist across sessions\n- You have full control over this container`\n\t\t: `You are running directly on the host machine.\n- Be careful with system modifications\n- Use the system's package manager if needed`;\n\n\tconst currentDate = new Date().toISOString().split(\"T\")[0]; // YYYY-MM-DD\n\tconst currentDateTime = new Date().toISOString(); // Full ISO 8601\n\n\treturn `You are mom, a helpful Slack bot assistant.\n\n## Current Date and Time\n- Date: ${currentDate}\n- Full timestamp: ${currentDateTime}\n- Use this when working with dates or searching logs\n\n## Communication Style\n- Be concise and professional\n- Do not use emojis unless the user communicates informally with you\n- Get to the point quickly\n- If you need clarification, ask directly\n- Use Slack's mrkdwn format (NOT standard Markdown):\n - Bold: *text* (single asterisks)\n - Italic: _text_\n - Strikethrough: ~text~\n - Code: \\`code\\`\n - Code block: \\`\\`\\`code\\`\\`\\`\n - Links: <url|text>\n - Do NOT use **double asterisks** or [markdown](links)\n\n## Your Environment\n${envDescription}\n\n## Your Workspace\nYour working directory is: ${channelPath}\n\n### Directory Structure\n- ${workspacePath}/ - Root workspace (shared across all channels)\n - MEMORY.md - GLOBAL memory visible to all channels (write global info here)\n - ${channelId}/ - This channel's directory\n - MEMORY.md - CHANNEL-SPECIFIC memory (only visible in this channel)\n - scratch/ - Your working directory for files, repos, etc.\n - log.jsonl - Message history in JSONL format (one JSON object per line)\n - attachments/ - Files shared by users (managed by system, read-only)\n\n### Message History Format\nEach line in log.jsonl contains:\n{\n \"date\": \"2025-11-26T10:44:00.123Z\", // ISO 8601 - easy to grep by date!\n \"ts\": \"1732619040.123456\", // Slack timestamp or epoch ms\n \"user\": \"U123ABC\", // User ID or \"bot\"\n \"userName\": \"mario\", // User handle (optional)\n \"text\": \"message text\",\n \"isBot\": false\n}\n\n**⚠️ CRITICAL: Efficient Log Queries (Avoid Context Overflow)**\n\nLog files can be VERY LARGE (100K+ lines). The problem is getting too MANY messages, not message length.\nEach message can be up to 10k chars - that's fine. Use head/tail to LIMIT NUMBER OF MESSAGES (10-50 at a time).\n\n**Install jq first (if not already):**\n\\`\\`\\`bash\n${isDocker ? \"apk add jq\" : \"# jq should be available, or install via package manager\"}\n\\`\\`\\`\n\n**Essential query patterns:**\n\\`\\`\\`bash\n# Last N messages (compact JSON output)\ntail -20 log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text, attachments: [(.attachments // [])[].local]}'\n\n# Or TSV format (easier to read)\ntail -20 log.jsonl | jq -r '[.date[0:19], (.userName // .user), .text, ((.attachments // []) | map(.local) | join(\",\"))] | @tsv'\n\n# Search by date (LIMIT with head/tail!)\ngrep '\"date\":\"2025-11-26' log.jsonl | tail -30 | jq -c '{date: .date[0:19], user: (.userName // .user), text, attachments: [(.attachments // [])[].local]}'\n\n# Messages from specific user (count first, then limit)\ngrep '\"userName\":\"mario\"' log.jsonl | wc -l # Check count first\ngrep '\"userName\":\"mario\"' log.jsonl | tail -20 | jq -c '{date: .date[0:19], user: .userName, text, attachments: [(.attachments // [])[].local]}'\n\n# Only count (when you just need the number)\ngrep '\"isBot\":false' log.jsonl | wc -l\n\n# Messages with attachments only (limit!)\ngrep '\"attachments\":[{' log.jsonl | tail -10 | jq -r '[.date[0:16], (.userName // .user), .text, (.attachments | map(.local) | join(\",\"))] | @tsv'\n\\`\\`\\`\n\n**KEY RULE:** Always pipe through 'head -N' or 'tail -N' to limit results BEFORE parsing with jq!\n\\`\\`\\`\n\n**Date filtering:**\n- Today: grep '\"date\":\"${currentDate}' log.jsonl\n- Yesterday: grep '\"date\":\"2025-11-25' log.jsonl\n- Date range: grep '\"date\":\"2025-11-(26|27|28)' log.jsonl\n- Time range: grep -E '\"date\":\"2025-11-26T(09|10|11):' log.jsonl\n\n### Working Memory System\nYou can maintain working memory across conversations by writing MEMORY.md files.\n\n**IMPORTANT PATH RULES:**\n- Global memory (all channels): ${workspacePath}/MEMORY.md\n- Channel memory (this channel only): ${channelPath}/MEMORY.md\n\n**What to remember:**\n- Project details and architecture → Global memory\n- User preferences and coding style → Global memory\n- Channel-specific context → Channel memory\n- Recurring tasks and patterns → Appropriate memory file\n- Credentials locations (never actual secrets) → Global memory\n- Decisions made and their rationale → Appropriate memory file\n\n**When to update:**\n- After learning something important that will help in future conversations\n- When user asks you to remember something\n- When you discover project structure or conventions\n\n### Current Working Memory\n${memory}\n\n## Tools\nYou have access to: bash, read, edit, write, attach tools.\n- bash: Run shell commands (this is your main tool)\n- read: Read files\n- edit: Edit files surgically\n- write: Create/overwrite files\n- attach: Share a file with the user in Slack\n\nEach tool requires a \"label\" parameter - brief description shown to the user.\n\n## Guidelines\n- Be concise and helpful\n- Use bash for most operations\n- If you need a tool, install it\n- If you need credentials, ask the user\n\n## CRITICAL\n- DO NOT USE EMOJIS. KEEP YOUR RESPONSES AS SHORT AS POSSIBLE.\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\t// If it's already a string, return it\n\tif (typeof result === \"string\") {\n\t\treturn result;\n\t}\n\n\t// If it's an object with content array (tool result format)\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\t// Fallback to JSON\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\t// Skip the label - it's already shown\n\t\tif (key === \"label\") continue;\n\n\t\t// For read tool, format path with offset/limit\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\t// Skip offset/limit since we already handled them\n\t\tif (key === \"offset\" || key === \"limit\") continue;\n\n\t\t// For other values, format them\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\nexport function createAgentRunner(sandboxConfig: SandboxConfig): AgentRunner {\n\tlet agent: Agent | null = null;\n\tconst executor = createExecutor(sandboxConfig);\n\n\treturn {\n\t\tasync run(ctx: SlackContext, channelDir: string, store: ChannelStore): Promise<{ stopReason: string }> {\n\t\t\t// Ensure channel directory exists\n\t\t\tawait mkdir(channelDir, { recursive: true });\n\n\t\t\tconst channelId = ctx.message.channel;\n\t\t\tconst workspacePath = executor.getWorkspacePath(channelDir.replace(`/${channelId}`, \"\"));\n\t\t\tconst recentMessages = getRecentMessages(channelDir, 50);\n\t\t\tconst memory = getMemory(channelDir);\n\t\t\tconst systemPrompt = buildSystemPrompt(workspacePath, channelId, memory, sandboxConfig);\n\n\t\t\t// Set up file upload function for the attach tool\n\t\t\t// For Docker, we need to translate paths back to host\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 ctx.uploadFile(hostPath, title);\n\t\t\t});\n\n\t\t\t// Create tools with executor\n\t\t\tconst tools = createMomTools(executor);\n\n\t\t\t// Create ephemeral agent\n\t\t\tagent = new Agent({\n\t\t\t\tinitialState: {\n\t\t\t\t\tsystemPrompt,\n\t\t\t\t\tmodel,\n\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\ttools,\n\t\t\t\t},\n\t\t\t\ttransport: new ProviderTransport({\n\t\t\t\t\tgetApiKey: async () => getAnthropicApiKey(),\n\t\t\t\t}),\n\t\t\t});\n\n\t\t\t// Create logging context\n\t\t\tconst logCtx = {\n\t\t\t\tchannelId: ctx.message.channel,\n\t\t\t\tuserName: ctx.message.userName,\n\t\t\t\tchannelName: ctx.channelName,\n\t\t\t};\n\n\t\t\t// Track pending tool calls to pair args with results and timing\n\t\t\tconst pendingTools = new Map<string, { toolName: string; args: unknown; startTime: number }>();\n\n\t\t\t// Track usage across all assistant messages in this run\n\t\t\tconst 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: {\n\t\t\t\t\tinput: 0,\n\t\t\t\t\toutput: 0,\n\t\t\t\t\tcacheRead: 0,\n\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\ttotal: 0,\n\t\t\t\t},\n\t\t\t};\n\n\t\t\t// Track stop reason\n\t\t\tlet stopReason = \"stop\";\n\n\t\t\t// Subscribe to events\n\t\t\tagent.subscribe(async (event: AgentEvent) => {\n\t\t\t\tswitch (event.type) {\n\t\t\t\t\tcase \"tool_execution_start\": {\n\t\t\t\t\t\tconst args = event.args as { label?: string };\n\t\t\t\t\t\tconst label = args.label || event.toolName;\n\n\t\t\t\t\t\t// Store args to pair with result later\n\t\t\t\t\t\tpendingTools.set(event.toolCallId, {\n\t\t\t\t\t\t\ttoolName: event.toolName,\n\t\t\t\t\t\t\targs: event.args,\n\t\t\t\t\t\t\tstartTime: Date.now(),\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t// Log to console\n\t\t\t\t\t\tlog.logToolStart(logCtx, event.toolName, label, event.args as Record<string, unknown>);\n\n\t\t\t\t\t\t// Log to jsonl\n\t\t\t\t\t\tawait store.logMessage(ctx.message.channel, {\n\t\t\t\t\t\t\tdate: new Date().toISOString(),\n\t\t\t\t\t\t\tts: Date.now().toString(),\n\t\t\t\t\t\t\tuser: \"bot\",\n\t\t\t\t\t\t\ttext: `[Tool] ${event.toolName}: ${JSON.stringify(event.args)}`,\n\t\t\t\t\t\t\tattachments: [],\n\t\t\t\t\t\t\tisBot: true,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t// Show label in main message only\n\t\t\t\t\t\tawait ctx.respond(`_${label}_`);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"tool_execution_end\": {\n\t\t\t\t\t\tconst resultStr = extractToolResultText(event.result);\n\t\t\t\t\t\tconst pending = pendingTools.get(event.toolCallId);\n\t\t\t\t\t\tpendingTools.delete(event.toolCallId);\n\n\t\t\t\t\t\tconst durationMs = pending ? Date.now() - pending.startTime : 0;\n\n\t\t\t\t\t\t// Log to console\n\t\t\t\t\t\tif (event.isError) {\n\t\t\t\t\t\t\tlog.logToolError(logCtx, event.toolName, durationMs, resultStr);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlog.logToolSuccess(logCtx, event.toolName, durationMs, resultStr);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Log to jsonl\n\t\t\t\t\t\tawait store.logMessage(ctx.message.channel, {\n\t\t\t\t\t\t\tdate: new Date().toISOString(),\n\t\t\t\t\t\t\tts: Date.now().toString(),\n\t\t\t\t\t\t\tuser: \"bot\",\n\t\t\t\t\t\t\ttext: `[Tool Result] ${event.toolName}: ${event.isError ? \"ERROR: \" : \"\"}${truncate(resultStr, 1000)}`,\n\t\t\t\t\t\t\tattachments: [],\n\t\t\t\t\t\t\tisBot: true,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\t// Post args + result together in thread\n\t\t\t\t\t\tconst label = pending?.args ? (pending.args as { label?: string }).label : undefined;\n\t\t\t\t\t\tconst argsFormatted = pending\n\t\t\t\t\t\t\t? formatToolArgsForSlack(event.toolName, pending.args as Record<string, unknown>)\n\t\t\t\t\t\t\t: \"(args not found)\";\n\t\t\t\t\t\tconst duration = (durationMs / 1000).toFixed(1);\n\t\t\t\t\t\tconst threadResult = truncate(resultStr, 2000);\n\n\t\t\t\t\t\tlet threadMessage = `*${event.isError ? \"✗\" : \"✓\"} ${event.toolName}*`;\n\t\t\t\t\t\tif (label) {\n\t\t\t\t\t\t\tthreadMessage += `: ${label}`;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthreadMessage += ` (${duration}s)\\n`;\n\n\t\t\t\t\t\tif (argsFormatted) {\n\t\t\t\t\t\t\tthreadMessage += \"```\\n\" + argsFormatted + \"\\n```\\n\";\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthreadMessage += \"*Result:*\\n```\\n\" + threadResult + \"\\n```\";\n\n\t\t\t\t\t\tawait ctx.respondInThread(threadMessage);\n\n\t\t\t\t\t\t// Show brief error in main message if failed\n\t\t\t\t\t\tif (event.isError) {\n\t\t\t\t\t\t\tawait ctx.respond(`_Error: ${truncate(resultStr, 200)}_`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"message_update\": {\n\t\t\t\t\t\t// No longer stream to console - just track that we're streaming\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase \"message_start\":\n\t\t\t\t\t\tif (event.message.role === \"assistant\") {\n\t\t\t\t\t\t\tlog.logResponseStart(logCtx);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"message_end\":\n\t\t\t\t\t\tif (event.message.role === \"assistant\") {\n\t\t\t\t\t\t\tconst assistantMsg = event.message as any; // AssistantMessage type\n\n\t\t\t\t\t\t\t// Track stop reason\n\t\t\t\t\t\t\tif (assistantMsg.stopReason) {\n\t\t\t\t\t\t\t\tstopReason = assistantMsg.stopReason;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Accumulate usage\n\t\t\t\t\t\t\tif (assistantMsg.usage) {\n\t\t\t\t\t\t\t\ttotalUsage.input += assistantMsg.usage.input;\n\t\t\t\t\t\t\t\ttotalUsage.output += assistantMsg.usage.output;\n\t\t\t\t\t\t\t\ttotalUsage.cacheRead += assistantMsg.usage.cacheRead;\n\t\t\t\t\t\t\t\ttotalUsage.cacheWrite += assistantMsg.usage.cacheWrite;\n\t\t\t\t\t\t\t\ttotalUsage.cost.input += assistantMsg.usage.cost.input;\n\t\t\t\t\t\t\t\ttotalUsage.cost.output += assistantMsg.usage.cost.output;\n\t\t\t\t\t\t\t\ttotalUsage.cost.cacheRead += assistantMsg.usage.cost.cacheRead;\n\t\t\t\t\t\t\t\ttotalUsage.cost.cacheWrite += assistantMsg.usage.cost.cacheWrite;\n\t\t\t\t\t\t\t\ttotalUsage.cost.total += assistantMsg.usage.cost.total;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Extract text from assistant message\n\t\t\t\t\t\t\tconst content = event.message.content;\n\t\t\t\t\t\t\tlet text = \"\";\n\t\t\t\t\t\t\tfor (const part of content) {\n\t\t\t\t\t\t\t\tif (part.type === \"text\") {\n\t\t\t\t\t\t\t\t\ttext += part.text;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (text.trim()) {\n\t\t\t\t\t\t\t\tawait ctx.respond(text);\n\t\t\t\t\t\t\t\tlog.logResponseComplete(logCtx, text.length);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// Run the agent with user's message\n\t\t\t// Prepend recent messages to the user prompt (not system prompt) for better caching\n\t\t\tconst userPrompt =\n\t\t\t\t`Recent conversation history (last 50 messages):\\n` +\n\t\t\t\t`Format: date TAB user TAB text TAB attachments\\n\\n` +\n\t\t\t\t`${recentMessages}\\n\\n` +\n\t\t\t\t`---\\n\\n` +\n\t\t\t\t`Current message: ${ctx.message.text || \"(attached files)\"}`;\n\n\t\t\tawait agent.prompt(userPrompt);\n\n\t\t\t// Log usage summary if there was any usage\n\t\t\tif (totalUsage.cost.total > 0) {\n\t\t\t\tconst summary = log.logUsageSummary(logCtx, totalUsage);\n\t\t\t\tawait ctx.respondInThread(summary);\n\t\t\t}\n\n\t\t\treturn { stopReason };\n\t\t},\n\n\t\tabort(): void {\n\t\t\tagent?.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\t// Docker mode - translate /workspace/channelId/... to host path\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\t// Maybe it's just /workspace/...\n\t\tif (containerPath.startsWith(\"/workspace/\")) {\n\t\t\treturn join(channelDir, \"..\", containerPath.slice(\"/workspace/\".length));\n\t\t}\n\t}\n\t// Host mode or already a host path\n\treturn containerPath;\n}\n"]}
package/dist/log.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ export interface LogContext {
2
+ channelId: string;
3
+ userName?: string;
4
+ channelName?: string;
5
+ }
6
+ export declare function logUserMessage(ctx: LogContext, text: string): void;
7
+ export declare function logToolStart(ctx: LogContext, toolName: string, label: string, args: Record<string, unknown>): void;
8
+ export declare function logToolSuccess(ctx: LogContext, toolName: string, durationMs: number, result: string): void;
9
+ export declare function logToolError(ctx: LogContext, toolName: string, durationMs: number, error: string): void;
10
+ export declare function logResponseStart(ctx: LogContext): void;
11
+ export declare function logResponseComplete(ctx: LogContext, charCount: number): void;
12
+ export declare function logDownloadStart(ctx: LogContext, filename: string, localPath: string): void;
13
+ export declare function logDownloadSuccess(ctx: LogContext, sizeKB: number): void;
14
+ export declare function logDownloadError(ctx: LogContext, filename: string, error: string): void;
15
+ export declare function logStopRequest(ctx: LogContext): void;
16
+ export declare function logWarning(message: string, details?: string): void;
17
+ export declare function logAgentError(ctx: LogContext | "system", error: string): void;
18
+ export declare function logUsageSummary(ctx: LogContext, usage: {
19
+ input: number;
20
+ output: number;
21
+ cacheRead: number;
22
+ cacheWrite: number;
23
+ cost: {
24
+ input: number;
25
+ output: number;
26
+ cacheRead: number;
27
+ cacheWrite: number;
28
+ total: number;
29
+ };
30
+ }): string;
31
+ export declare function logStartup(workingDir: string, sandbox: string): void;
32
+ export declare function logConnected(): void;
33
+ export declare function logDisconnected(): void;
34
+ //# sourceMappingURL=log.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log.d.ts","sourceRoot":"","sources":["../src/log.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,UAAU;IAC1B,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAiED,wBAAgB,cAAc,CAAC,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAElE;AAGD,wBAAgB,YAAY,CAAC,GAAG,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAWlH;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAY1G;AAED,wBAAgB,YAAY,CAAC,GAAG,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAUvG;AAGD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,UAAU,GAAG,IAAI,CAEtD;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chalk\";\n\nexport interface LogContext {\n\tchannelId: string;\n\tuserName?: string;\n\tchannelName?: string; // For display like #dev-team vs C16HET4EQ\n}\n\nfunction timestamp(): string {\n\tconst now = new Date();\n\tconst hh = String(now.getHours()).padStart(2, \"0\");\n\tconst mm = String(now.getMinutes()).padStart(2, \"0\");\n\tconst ss = String(now.getSeconds()).padStart(2, \"0\");\n\treturn `[${hh}:${mm}:${ss}]`;\n}\n\nfunction formatContext(ctx: LogContext): string {\n\t// DMs: [DM:username]\n\t// Channels: [#channel-name:username] or [C16HET4EQ:username] if no name\n\tif (ctx.channelId.startsWith(\"D\")) {\n\t\treturn `[DM:${ctx.userName || ctx.channelId}]`;\n\t}\n\tconst channel = ctx.channelName || ctx.channelId;\n\tconst user = ctx.userName || \"unknown\";\n\treturn `[${channel.startsWith(\"#\") ? channel : `#${channel}`}:${user}]`;\n}\n\nfunction truncate(text: string, maxLen: number): string {\n\tif (text.length <= maxLen) return text;\n\treturn text.substring(0, maxLen) + `\\n(truncated at ${maxLen} chars)`;\n}\n\nfunction formatToolArgs(args: Record<string, unknown>): string {\n\tconst lines: string[] = [];\n\n\tfor (const [key, value] of Object.entries(args)) {\n\t\t// Skip the label - it's already shown in the tool name\n\t\tif (key === \"label\") continue;\n\n\t\t// For read tool, format path with offset/limit\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\t// Skip offset/limit since we already handled them\n\t\tif (key === \"offset\" || key === \"limit\") continue;\n\n\t\t// For other values, format them\n\t\tif (typeof value === \"string\") {\n\t\t\t// Multi-line strings get indented\n\t\t\tif (value.includes(\"\\n\")) {\n\t\t\t\tlines.push(value);\n\t\t\t} else {\n\t\t\t\tlines.push(value);\n\t\t\t}\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// User messages\nexport function logUserMessage(ctx: LogContext, text: string): void {\n\tconsole.log(chalk.green(`${timestamp()} ${formatContext(ctx)} ${text}`));\n}\n\n// Tool execution\nexport function logToolStart(ctx: LogContext, toolName: string, label: string, args: Record<string, unknown>): void {\n\tconst formattedArgs = formatToolArgs(args);\n\tconsole.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ↳ ${toolName}: ${label}`));\n\tif (formattedArgs) {\n\t\t// Indent the args\n\t\tconst indented = formattedArgs\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => ` ${line}`)\n\t\t\t.join(\"\\n\");\n\t\tconsole.log(chalk.dim(indented));\n\t}\n}\n\nexport function logToolSuccess(ctx: LogContext, toolName: string, durationMs: number, result: string): void {\n\tconst duration = (durationMs / 1000).toFixed(1);\n\tconsole.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ✓ ${toolName} (${duration}s)`));\n\n\tconst truncated = truncate(result, 1000);\n\tif (truncated) {\n\t\tconst indented = truncated\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => ` ${line}`)\n\t\t\t.join(\"\\n\");\n\t\tconsole.log(chalk.dim(indented));\n\t}\n}\n\nexport function logToolError(ctx: LogContext, toolName: string, durationMs: number, error: string): void {\n\tconst duration = (durationMs / 1000).toFixed(1);\n\tconsole.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ✗ ${toolName} (${duration}s)`));\n\n\tconst truncated = truncate(error, 1000);\n\tconst indented = truncated\n\t\t.split(\"\\n\")\n\t\t.map((line) => ` ${line}`)\n\t\t.join(\"\\n\");\n\tconsole.log(chalk.dim(indented));\n}\n\n// Response streaming\nexport function logResponseStart(ctx: LogContext): void {\n\tconsole.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} → Streaming response...`));\n}\n\nexport function logResponseComplete(ctx: LogContext, charCount: number): void {\n\tconsole.log(\n\t\tchalk.yellow(`${timestamp()} ${formatContext(ctx)} ✓ Response sent (${charCount.toLocaleString()} chars)`),\n\t);\n}\n\n// Attachments\nexport function logDownloadStart(ctx: LogContext, filename: string, localPath: string): void {\n\tconsole.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ↓ Downloading attachment`));\n\tconsole.log(chalk.dim(` ${filename} → ${localPath}`));\n}\n\nexport function logDownloadSuccess(ctx: LogContext, sizeKB: number): void {\n\tconsole.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ✓ Downloaded (${sizeKB.toLocaleString()} KB)`));\n}\n\nexport function logDownloadError(ctx: LogContext, filename: string, error: string): void {\n\tconsole.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ✗ Download failed`));\n\tconsole.log(chalk.dim(` ${filename}: ${error}`));\n}\n\n// Control\nexport function logStopRequest(ctx: LogContext): void {\n\tconsole.log(chalk.green(`${timestamp()} ${formatContext(ctx)} stop`));\n\tconsole.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} ⊗ Stop requested - aborting`));\n}\n\n// System\nexport function logWarning(message: string, details?: string): void {\n\tconsole.log(chalk.yellow(`${timestamp()} [system] ⚠ ${message}`));\n\tif (details) {\n\t\tconst indented = details\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => ` ${line}`)\n\t\t\t.join(\"\\n\");\n\t\tconsole.log(chalk.dim(indented));\n\t}\n}\n\nexport function logAgentError(ctx: LogContext | \"system\", error: string): void {\n\tconst context = ctx === \"system\" ? \"[system]\" : formatContext(ctx);\n\tconsole.log(chalk.yellow(`${timestamp()} ${context} ✗ Agent error`));\n\tconst indented = error\n\t\t.split(\"\\n\")\n\t\t.map((line) => ` ${line}`)\n\t\t.join(\"\\n\");\n\tconsole.log(chalk.dim(indented));\n}\n\n// Usage summary\nexport function logUsageSummary(\n\tctx: LogContext,\n\tusage: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\tcost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };\n\t},\n): string {\n\tconst lines: string[] = [];\n\tlines.push(\"*Usage Summary*\");\n\tlines.push(`Tokens: ${usage.input.toLocaleString()} in, ${usage.output.toLocaleString()} out`);\n\tif (usage.cacheRead > 0 || usage.cacheWrite > 0) {\n\t\tlines.push(`Cache: ${usage.cacheRead.toLocaleString()} read, ${usage.cacheWrite.toLocaleString()} write`);\n\t}\n\tlines.push(\n\t\t`Cost: $${usage.cost.input.toFixed(4)} in, $${usage.cost.output.toFixed(4)} out` +\n\t\t\t(usage.cacheRead > 0 || usage.cacheWrite > 0\n\t\t\t\t? `, $${usage.cost.cacheRead.toFixed(4)} cache read, $${usage.cost.cacheWrite.toFixed(4)} cache write`\n\t\t\t\t: \"\"),\n\t);\n\tlines.push(`*Total: $${usage.cost.total.toFixed(4)}*`);\n\n\tconst summary = lines.join(\"\\n\");\n\n\t// Log to console\n\tconsole.log(chalk.yellow(`${timestamp()} ${formatContext(ctx)} 💰 Usage`));\n\tconsole.log(\n\t\tchalk.dim(\n\t\t\t` ${usage.input.toLocaleString()} in + ${usage.output.toLocaleString()} out` +\n\t\t\t\t(usage.cacheRead > 0 || usage.cacheWrite > 0\n\t\t\t\t\t? ` (${usage.cacheRead.toLocaleString()} cache read, ${usage.cacheWrite.toLocaleString()} cache write)`\n\t\t\t\t\t: \"\") +\n\t\t\t\t` = $${usage.cost.total.toFixed(4)}`,\n\t\t),\n\t);\n\n\treturn summary;\n}\n\n// Startup (no context needed)\nexport function logStartup(workingDir: string, sandbox: string): void {\n\tconsole.log(\"Starting mom bot...\");\n\tconsole.log(` Working directory: ${workingDir}`);\n\tconsole.log(` Sandbox: ${sandbox}`);\n}\n\nexport function logConnected(): void {\n\tconsole.log(\"⚡️ Mom bot connected and listening!\");\n\tconsole.log(\"\");\n}\n\nexport function logDisconnected(): void {\n\tconsole.log(\"Mom bot disconnected.\");\n}\n"]}