@geminixiang/mama 0.2.0-beta.2 → 0.2.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +67 -39
  2. package/dist/adapter.d.ts +14 -4
  3. package/dist/adapter.d.ts.map +1 -1
  4. package/dist/adapter.js.map +1 -1
  5. package/dist/adapters/discord/bot.d.ts +8 -5
  6. package/dist/adapters/discord/bot.d.ts.map +1 -1
  7. package/dist/adapters/discord/bot.js +210 -42
  8. package/dist/adapters/discord/bot.js.map +1 -1
  9. package/dist/adapters/discord/context.d.ts.map +1 -1
  10. package/dist/adapters/discord/context.js +83 -21
  11. package/dist/adapters/discord/context.js.map +1 -1
  12. package/dist/adapters/shared.d.ts +23 -0
  13. package/dist/adapters/shared.d.ts.map +1 -0
  14. package/dist/adapters/shared.js +57 -0
  15. package/dist/adapters/shared.js.map +1 -0
  16. package/dist/adapters/slack/bot.d.ts +8 -7
  17. package/dist/adapters/slack/bot.d.ts.map +1 -1
  18. package/dist/adapters/slack/bot.js +161 -27
  19. package/dist/adapters/slack/bot.js.map +1 -1
  20. package/dist/adapters/slack/branch-manager.d.ts +21 -0
  21. package/dist/adapters/slack/branch-manager.d.ts.map +1 -0
  22. package/dist/adapters/slack/branch-manager.js +96 -0
  23. package/dist/adapters/slack/branch-manager.js.map +1 -0
  24. package/dist/adapters/slack/context.d.ts.map +1 -1
  25. package/dist/adapters/slack/context.js +92 -56
  26. package/dist/adapters/slack/context.js.map +1 -1
  27. package/dist/adapters/slack/session.d.ts +3 -0
  28. package/dist/adapters/slack/session.d.ts.map +1 -0
  29. package/dist/adapters/slack/session.js +16 -0
  30. package/dist/adapters/slack/session.js.map +1 -0
  31. package/dist/adapters/telegram/bot.d.ts.map +1 -1
  32. package/dist/adapters/telegram/bot.js +11 -3
  33. package/dist/adapters/telegram/bot.js.map +1 -1
  34. package/dist/adapters/telegram/context.d.ts.map +1 -1
  35. package/dist/adapters/telegram/context.js +40 -14
  36. package/dist/adapters/telegram/context.js.map +1 -1
  37. package/dist/agent.d.ts +2 -1
  38. package/dist/agent.d.ts.map +1 -1
  39. package/dist/agent.js +69 -142
  40. package/dist/agent.js.map +1 -1
  41. package/dist/config.d.ts +2 -0
  42. package/dist/config.d.ts.map +1 -1
  43. package/dist/config.js +13 -1
  44. package/dist/config.js.map +1 -1
  45. package/dist/context.d.ts +11 -1
  46. package/dist/context.d.ts.map +1 -1
  47. package/dist/context.js +100 -16
  48. package/dist/context.js.map +1 -1
  49. package/dist/events.d.ts +7 -0
  50. package/dist/events.d.ts.map +1 -1
  51. package/dist/events.js +61 -30
  52. package/dist/events.js.map +1 -1
  53. package/dist/{login.d.ts → login/index.d.ts} +1 -1
  54. package/dist/login/index.d.ts.map +1 -0
  55. package/dist/{login.js → login/index.js} +1 -1
  56. package/dist/login/index.js.map +1 -0
  57. package/dist/{link-server.d.ts → login/portal.d.ts} +5 -4
  58. package/dist/login/portal.d.ts.map +1 -0
  59. package/dist/login/portal.js +1453 -0
  60. package/dist/login/portal.js.map +1 -0
  61. package/dist/{link-token.d.ts → login/session.d.ts} +1 -1
  62. package/dist/login/session.d.ts.map +1 -0
  63. package/dist/{link-token.js → login/session.js} +1 -1
  64. package/dist/login/session.js.map +1 -0
  65. package/dist/main.d.ts.map +1 -1
  66. package/dist/main.js +87 -15
  67. package/dist/main.js.map +1 -1
  68. package/dist/provisioner.d.ts +17 -2
  69. package/dist/provisioner.d.ts.map +1 -1
  70. package/dist/provisioner.js +84 -5
  71. package/dist/provisioner.js.map +1 -1
  72. package/dist/session-policy.d.ts +13 -0
  73. package/dist/session-policy.d.ts.map +1 -0
  74. package/dist/session-policy.js +23 -0
  75. package/dist/session-policy.js.map +1 -0
  76. package/dist/session-store.d.ts +26 -0
  77. package/dist/session-store.d.ts.map +1 -1
  78. package/dist/session-store.js +157 -0
  79. package/dist/session-store.js.map +1 -1
  80. package/dist/session-view/command.d.ts +5 -0
  81. package/dist/session-view/command.d.ts.map +1 -0
  82. package/dist/session-view/command.js +11 -0
  83. package/dist/session-view/command.js.map +1 -0
  84. package/dist/session-view/portal.d.ts +9 -0
  85. package/dist/session-view/portal.d.ts.map +1 -0
  86. package/dist/session-view/portal.js +766 -0
  87. package/dist/session-view/portal.js.map +1 -0
  88. package/dist/session-view/service.d.ts +34 -0
  89. package/dist/session-view/service.d.ts.map +1 -0
  90. package/dist/session-view/service.js +380 -0
  91. package/dist/session-view/service.js.map +1 -0
  92. package/dist/session-view/store.d.ts +16 -0
  93. package/dist/session-view/store.d.ts.map +1 -0
  94. package/dist/session-view/store.js +38 -0
  95. package/dist/session-view/store.js.map +1 -0
  96. package/dist/store.d.ts +3 -6
  97. package/dist/store.d.ts.map +1 -1
  98. package/dist/store.js +15 -35
  99. package/dist/store.js.map +1 -1
  100. package/dist/tools/event.d.ts +2 -0
  101. package/dist/tools/event.d.ts.map +1 -1
  102. package/dist/tools/event.js +21 -3
  103. package/dist/tools/event.js.map +1 -1
  104. package/dist/tools/index.d.ts +2 -0
  105. package/dist/tools/index.d.ts.map +1 -1
  106. package/dist/tools/index.js.map +1 -1
  107. package/package.json +1 -1
  108. package/dist/link-server.d.ts.map +0 -1
  109. package/dist/link-server.js +0 -899
  110. package/dist/link-server.js.map +0 -1
  111. package/dist/link-token.d.ts.map +0 -1
  112. package/dist/link-token.js.map +0 -1
  113. package/dist/login.d.ts.map +0 -1
  114. package/dist/login.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EACV,WAAW,EACX,mBAAmB,EAEnB,YAAY,EACb,MAAM,cAAc,CAAC;AAKtB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAiC,KAAK,aAAa,EAAE,MAAM,cAAc,CAAC;AAEjF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAgB/C,MAAM,WAAW,WAAW;IAC1B,GAAG,CACD,OAAO,EAAE,WAAW,EACpB,WAAW,EAAE,mBAAmB,EAChC,QAAQ,EAAE,YAAY,GACrB,OAAO,CAAC;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC1D,KAAK,IAAI,IAAI,CAAC;IACd,6DAA6D;IAC7D,cAAc,IAAI;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;CACrE;AA4WD;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,aAAa,EAAE,aAAa,EAC5B,UAAU,EAAE,MAAM,EAClB,cAAc,EAAE,MAAM,EACtB,eAAe,EAAE,MAAM,EACvB,YAAY,EAAE,MAAM,EACpB,YAAY,CAAC,EAAE,YAAY,EAC3B,YAAY,CAAC,EAAE,gBAAgB,EAC/B,WAAW,CAAC,EAAE,sBAAsB,GACnC,OAAO,CAAC,WAAW,CAAC,CAsxBtB","sourcesContent":["import { Agent, type AgentEvent } from \"@mariozechner/pi-agent-core\";\nimport { getModel, type ImageContent } from \"@mariozechner/pi-ai\";\nimport {\n AgentSession,\n AuthStorage,\n convertToLlm,\n DefaultResourceLoader,\n formatSkillsForPrompt,\n getAgentDir,\n loadSkillsFromDir,\n ModelRegistry,\n SessionManager,\n type Skill,\n} from \"@mariozechner/pi-coding-agent\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { mkdir, readFile, writeFile } from \"fs/promises\";\nimport { homedir } from \"os\";\nimport { join } from \"path\";\nimport type {\n ChatMessage,\n ChatResponseContext,\n ConversationKind,\n PlatformInfo,\n} from \"./adapter.js\";\nimport { loadAgentConfig } from \"./config.js\";\nimport { createMamaSettingsManager, syncLogToSessionManager } from \"./context.js\";\nimport { ActorExecutionResolver } from \"./execution-resolver.js\";\nimport * as log from \"./log.js\";\nimport type { UserBindingStore } from \"./bindings.js\";\nimport type { DockerContainerManager } from \"./provisioner.js\";\nimport { createExecutor, type Executor, type SandboxConfig } from \"./sandbox.js\";\nimport { addLifecycleBreadcrumb, metricAttributes } from \"./sentry.js\";\nimport type { VaultManager } from \"./vault.js\";\nimport {\n createManagedSessionFileAtPath,\n extractSessionSuffix,\n extractSessionUuid,\n forkThreadSessionFile,\n getChannelSessionDir,\n getThreadSessionFile,\n openManagedSession,\n resolveChannelSessionFile,\n resolveManagedSessionFile,\n tryResolveThreadSession,\n} from \"./session-store.js\";\nimport { createMamaTools } from \"./tools/index.js\";\nimport * as Sentry from \"@sentry/node\";\n\nexport interface AgentRunner {\n run(\n message: ChatMessage,\n responseCtx: ChatResponseContext,\n platform: PlatformInfo,\n ): Promise<{ stopReason: string; errorMessage?: string }>;\n abort(): void;\n /** Get current step info (tool name, label) for debugging */\n getCurrentStep(): { toolName?: string; label?: string } | undefined;\n}\n\nconst IMAGE_MIME_TYPES: Record<string, string> = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n gif: \"image/gif\",\n webp: \"image/webp\",\n};\n\nfunction getImageMimeType(filename: string): string | undefined {\n return IMAGE_MIME_TYPES[filename.toLowerCase().split(\".\").pop() || \"\"];\n}\n\nasync function getMemory(conversationDir: string): Promise<string> {\n const parts: string[] = [];\n\n // Read workspace-level memory (shared across all conversations)\n const workspaceMemoryPath = join(conversationDir, \"..\", \"MEMORY.md\");\n if (existsSync(workspaceMemoryPath)) {\n try {\n const content = (await readFile(workspaceMemoryPath, \"utf-8\")).trim();\n if (content) {\n parts.push(`### Global Workspace Memory\\n${content}`);\n }\n } catch (error) {\n log.logWarning(\"Failed to read workspace memory\", `${workspaceMemoryPath}: ${error}`);\n }\n }\n\n // Read conversation-specific memory\n const conversationMemoryPath = join(conversationDir, \"MEMORY.md\");\n if (existsSync(conversationMemoryPath)) {\n try {\n const content = (await readFile(conversationMemoryPath, \"utf-8\")).trim();\n if (content) {\n parts.push(`### Conversation-Specific Memory\\n${content}`);\n }\n } catch (error) {\n log.logWarning(\"Failed to read conversation memory\", `${conversationMemoryPath}: ${error}`);\n }\n }\n\n if (parts.length === 0) {\n return \"(no working memory yet)\";\n }\n\n return parts.join(\"\\n\\n\");\n}\n\nfunction loadMamaSkills(conversationDir: string, workspacePath: string): Skill[] {\n const skillMap = new Map<string, Skill>();\n\n // conversationDir is the host path (e.g., /Users/.../data/C0A34FL8PMH)\n // hostWorkspacePath is the parent directory on host\n // workspacePath is the container path (e.g., /workspace)\n const hostWorkspacePath = join(conversationDir, \"..\");\n\n // Helper to translate host paths to container paths\n const translatePath = (hostPath: string): string => {\n if (hostPath.startsWith(hostWorkspacePath)) {\n return workspacePath + hostPath.slice(hostWorkspacePath.length);\n }\n return hostPath;\n };\n\n // Load workspace-level skills (global)\n const workspaceSkillsDir = join(hostWorkspacePath, \"skills\");\n for (const skill of loadSkillsFromDir({ dir: workspaceSkillsDir, source: \"workspace\" }).skills) {\n // Translate paths to container paths for system prompt\n skill.filePath = translatePath(skill.filePath);\n skill.baseDir = translatePath(skill.baseDir);\n skillMap.set(skill.name, skill);\n }\n\n // Load conversation-specific skills (override workspace skills on collision)\n const conversationSkillsDir = join(conversationDir, \"skills\");\n for (const skill of loadSkillsFromDir({ dir: conversationSkillsDir, source: \"channel\" }).skills) {\n skill.filePath = translatePath(skill.filePath);\n skill.baseDir = translatePath(skill.baseDir);\n skillMap.set(skill.name, skill);\n }\n\n return Array.from(skillMap.values());\n}\n\nfunction buildSystemPrompt(\n workspacePath: string,\n conversationId: string,\n conversationKind: ConversationKind,\n currentUserId: string | undefined,\n memory: string,\n sandboxConfig: SandboxConfig,\n platform: PlatformInfo,\n skills: Skill[],\n): string {\n const conversationPath = `${workspacePath}/${conversationId}`;\n const isContainer = sandboxConfig.type === \"container\" || sandboxConfig.type === \"image\";\n const isImageSandbox = sandboxConfig.type === \"image\";\n const isFirecracker = sandboxConfig.type === \"firecracker\";\n\n // Format channel mappings\n const channelMappings =\n platform.channels.length > 0\n ? platform.channels.map((c) => `${c.id}\\t#${c.name}`).join(\"\\n\")\n : \"(no channels loaded)\";\n\n // Format user mappings\n const userMappings =\n platform.users.length > 0\n ? platform.users.map((u) => `${u.id}\\t@${u.userName}\\t${u.displayName}`).join(\"\\n\")\n : \"(no users loaded)\";\n\n const envDescription = isImageSandbox\n ? `You are running inside a managed per-user container.\n- Bash working directory: / (use cd or absolute paths)\n- Install tools with the image's package manager\n- Your changes persist for this user's container until it is recreated`\n : isContainer\n ? `You are running inside a shared container.\n- Bash working directory: / (use cd or absolute paths)\n- Install tools with the container's package manager\n- Your changes persist across sessions`\n : isFirecracker\n ? `You are running inside a Firecracker microVM.\n- Bash working directory: / (use cd or absolute paths)\n- Install tools with: apt-get install <package> (Debian-based)\n- Your changes persist across sessions`\n : `You are running directly on the host machine.\n- Bash working directory: ${process.cwd()}\n- Be careful with system modifications`;\n\n return `You are mama, a ${platform.name} bot assistant. Be concise. No emojis.\n\n## Context\n- For current date/time, use: date\n- You have access to previous conversation context including tool results from prior turns.\n- For older history beyond your context, search log.jsonl (contains user messages and your final responses, but not tool results).\n- User messages include a \\`[in-thread:TS]\\` marker when sent from within a Slack thread (TS is the root message timestamp). Without this marker, the message is a top-level channel message.\n\n${platform.formattingGuide}\n\n## Platform IDs\nChannels: ${channelMappings}\n\nUsers: ${userMappings}\n\nWhen mentioning users, use <@username> format (e.g., <@mario>).\n\n## Environment\n${envDescription}\n\n## Workspace Layout\n${workspacePath}/\n├── MEMORY.md # Global memory (all conversations)\n├── skills/ # Global CLI tools you create\n└── ${conversationId}/ # This conversation\n ├── MEMORY.md # Conversation-specific memory\n ├── log.jsonl # Message history (no tool results)\n ├── attachments/ # User-shared files\n ├── scratch/ # Your working directory\n └── skills/ # Conversation-specific tools\n\n## Skills (Custom CLI Tools)\nYou can create reusable CLI tools for recurring tasks (email, APIs, data processing, etc.).\n\n### Creating Skills\nStore in \\`${workspacePath}/skills/<name>/\\` (global) or \\`${conversationPath}/skills/<name>/\\` (conversation-specific).\nEach skill directory needs a \\`SKILL.md\\` with YAML frontmatter:\n\n\\`\\`\\`markdown\n---\nname: skill-name\ndescription: Short description of what this skill does\n---\n\n# Skill Name\n\nUsage instructions, examples, etc.\nScripts are in: {baseDir}/\n\\`\\`\\`\n\n\\`name\\` and \\`description\\` are required. Use \\`{baseDir}\\` as placeholder for the skill's directory path.\n\n### Available Skills\n${skills.length > 0 ? formatSkillsForPrompt(skills) : \"(no skills installed yet)\"}\n\n## Events\nYou can schedule events that wake you up at specific times or when external things happen. Events are JSON files in \\`${workspacePath}/events/\\`.\n\n### Event Types\n\n**Immediate** - Triggers as soon as harness sees the file. Use in scripts/webhooks to signal external events.\n\\`\\`\\`json\n{\"type\": \"immediate\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"New GitHub issue opened\"}\n\\`\\`\\`\n\n**One-shot** - Triggers once at a specific time. Use for reminders.\n\\`\\`\\`json\n{\"type\": \"one-shot\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"Remind Mario about dentist\", \"at\": \"2025-12-15T09:00:00+01:00\"}\n\\`\\`\\`\n\n**Periodic** - Triggers on a cron schedule. Use for recurring tasks.\n\\`\\`\\`json\n{\"type\": \"periodic\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"Check inbox and summarize\", \"schedule\": \"0 9 * * 1-5\", \"timezone\": \"${Intl.DateTimeFormat().resolvedOptions().timeZone}\"}\n\\`\\`\\`\n\n### Cron Format\n\\`minute hour day-of-month month day-of-week\\`\n- \\`0 9 * * *\\` = daily at 9:00\n- \\`0 9 * * 1-5\\` = weekdays at 9:00\n- \\`30 14 * * 1\\` = Mondays at 14:30\n- \\`0 0 1 * *\\` = first of each month at midnight\n\n### Timezones\nAll \\`at\\` timestamps must include offset (e.g., \\`+01:00\\`). Periodic events use IANA timezone names. The harness runs in ${Intl.DateTimeFormat().resolvedOptions().timeZone}. When users mention times without timezone, assume ${Intl.DateTimeFormat().resolvedOptions().timeZone}.\n\n### Platform and Credential Routing\nSet \\`platform\\` to the target bot platform (\\`${platform.name}\\` for this conversation). When only one platform is running, omitting \\`platform\\` is allowed for backward compatibility, but include it by default to avoid ambiguity.\n\nSet \\`userId\\` to the platform userId of whoever asked for the event. When the event fires, tool execution routes using that user's vault selection in per-user modes. In \\`container:<name>\\`, events use the container's single shared vault.\n\nPrefer the \\`event\\` tool over manually writing JSON files; it fills \\`platform\\`, \\`conversationId\\`, \\`conversationKind\\`, and \\`userId\\` for the current conversation automatically.\n\n### Creating Events\nUse unique filenames to avoid overwriting existing events. Include a timestamp or random suffix:\n\\`\\`\\`bash\ncat > ${workspacePath}/events/dentist-reminder-$(date +%s).json << 'EOF'\n{\"type\": \"one-shot\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"Dentist tomorrow\", \"at\": \"2025-12-14T09:00:00+01:00\"}\nEOF\n\\`\\`\\`\nOr check if file exists first before creating.\n\n### Managing Events\n- List: \\`ls ${workspacePath}/events/\\`\n- View: \\`cat ${workspacePath}/events/foo.json\\`\n- Delete/cancel: \\`rm ${workspacePath}/events/foo.json\\`\n\n### When Events Trigger\nYou receive a message like:\n\\`\\`\\`\n[EVENT:dentist-reminder.json:one-shot:2025-12-14T09:00:00+01:00] Dentist tomorrow\n\\`\\`\\`\nImmediate and one-shot events auto-delete after triggering. Periodic events persist until you delete them.\n\n### Silent Completion\nFor periodic events where there's nothing to report, respond with just \\`[SILENT]\\` (no other text). This deletes the status message and posts nothing to the platform. Use this to avoid spamming the channel when periodic checks find nothing actionable.\n\n### Debouncing\nWhen writing programs that create immediate events (email watchers, webhook handlers, etc.), always debounce. If 50 emails arrive in a minute, don't create 50 immediate events. Instead collect events over a window and create ONE immediate event summarizing what happened, or just signal \"new activity, check inbox\" rather than per-item events. Or simpler: use a periodic event to check for new items every N minutes instead of immediate events.\n\n### Limits\nMaximum 5 events can be queued. Don't create excessive immediate or periodic events.\n\n## Memory\nWrite to MEMORY.md files to persist context across conversations.\n- Global (${workspacePath}/MEMORY.md): skills, preferences, project info\n- Conversation (${conversationPath}/MEMORY.md): conversation-specific decisions, ongoing work\nUpdate when you learn something important or when asked to remember something.\n\n### Current Memory\n${memory}\n\n## System Configuration Log\nMaintain ${workspacePath}/SYSTEM.md to log all environment modifications:\n- Installed packages (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${isContainer ? \"Install jq: apk add jq\" : \"\"}\n${isFirecracker ? \"Install jq: apt-get install jq\" : \"\"}\n\n\\`\\`\\`bash\n# Recent messages\ntail -30 log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'\n\n# Search for specific topic\ngrep -i \"topic\" log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'\n\n# Messages from specific user\ngrep '\"userName\":\"mario\"' log.jsonl | tail -20 | jq -c '{date: .date[0:19], text}'\n\\`\\`\\`\n\n## Tools\n- bash: Run shell commands (primary tool). Install packages as needed.\n- read: Read files\n- write: Create/overwrite files\n- edit: Surgical file edits\n- attach: Share files to the platform\n\nEach tool requires a \"label\" parameter (shown to user).\n`;\n}\n\nfunction truncate(text: string, maxLen: number): string {\n if (text.length <= maxLen) return text;\n return `${text.substring(0, maxLen - 3)}...`;\n}\n\nfunction extractToolResultText(result: unknown): string {\n if (typeof result === \"string\") {\n return result;\n }\n\n if (\n result &&\n typeof result === \"object\" &&\n \"content\" in result &&\n Array.isArray((result as { content: unknown }).content)\n ) {\n const content = (result as { content: Array<{ type: string; text?: string }> }).content;\n const textParts: string[] = [];\n for (const part of content) {\n if (part.type === \"text\" && part.text) {\n textParts.push(part.text);\n }\n }\n if (textParts.length > 0) {\n return textParts.join(\"\\n\");\n }\n }\n\n return JSON.stringify(result);\n}\n\nfunction formatToolArgsForSlack(_toolName: string, args: Record<string, unknown>): string {\n const lines: string[] = [];\n\n for (const [key, value] of Object.entries(args)) {\n if (key === \"label\") continue;\n\n if (key === \"path\" && typeof value === \"string\") {\n const offset = args.offset as number | undefined;\n const limit = args.limit as number | undefined;\n if (offset !== undefined && limit !== undefined) {\n lines.push(`${value}:${offset}-${offset + limit}`);\n } else {\n lines.push(value);\n }\n continue;\n }\n\n if (key === \"offset\" || key === \"limit\") continue;\n\n if (typeof value === \"string\") {\n lines.push(value);\n } else {\n lines.push(JSON.stringify(value));\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n// ============================================================================\n// Agent runner\n// ============================================================================\n\n/**\n * Create a new AgentRunner for a channel.\n * Sets up the session and subscribes to events once.\n *\n * Runner caching is handled by the caller (channelStates in main.ts).\n * This is a stateless factory function.\n */\nexport async function createRunner(\n sandboxConfig: SandboxConfig,\n sessionKey: string,\n conversationId: string,\n conversationDir: string,\n workspaceDir: string,\n vaultManager?: VaultManager,\n bindingStore?: UserBindingStore,\n provisioner?: DockerContainerManager,\n): Promise<AgentRunner> {\n const agentConfig = loadAgentConfig(workspaceDir);\n\n // Initialize logger with settings from config\n log.initLogger({\n logFormat: agentConfig.logFormat,\n logLevel: agentConfig.logLevel,\n });\n\n const executionResolver =\n vaultManager &&\n sandboxConfig.type !== \"host\" &&\n (vaultManager.isEnabled() ||\n !!bindingStore ||\n sandboxConfig.type === \"container\" ||\n sandboxConfig.type === \"image\")\n ? new ActorExecutionResolver(sandboxConfig, vaultManager, bindingStore, provisioner)\n : undefined;\n let activeExecutor: Executor =\n executionResolver !== undefined\n ? createExecutor({ type: \"host\" })\n : createExecutor(sandboxConfig);\n const executor: Executor = {\n exec(command, options) {\n return activeExecutor.exec(command, options);\n },\n getWorkspacePath(hostPath) {\n return activeExecutor.getWorkspacePath(hostPath);\n },\n getSandboxConfig() {\n return activeExecutor.getSandboxConfig();\n },\n };\n const workspaceBase = conversationDir.replace(`/${conversationId}`, \"\");\n const getWorkspacePath = () => executor.getWorkspacePath(workspaceBase);\n let workspacePath = getWorkspacePath();\n\n // Create tools (per-runner, with per-runner upload function setter)\n const { tools, setUploadFunction, setEventContext } = createMamaTools(executor, workspaceDir);\n\n // Resolve model from config\n // Use 'as any' cast because agentConfig.provider/model are plain strings,\n // while getModel() has constrained generic types for known providers.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const model = (getModel as any)(agentConfig.provider, agentConfig.model);\n\n // Initial system prompt (will be updated each run with fresh memory/channels/users/skills)\n const memory = await getMemory(conversationDir);\n const skills = loadMamaSkills(conversationDir, workspacePath);\n const emptyPlatform: PlatformInfo = {\n name: \"slack\",\n formattingGuide: \"\",\n channels: [],\n users: [],\n };\n const systemPrompt = buildSystemPrompt(\n workspacePath,\n conversationId,\n \"shared\",\n undefined,\n memory,\n sandboxConfig,\n emptyPlatform,\n skills,\n );\n\n // Create session manager and settings manager\n // Conversation sessions use {conversationDir}/sessions/current.\n // Thread sessions use fixed files: {conversationDir}/sessions/{threadTs}.jsonl\n const sessionDir = getChannelSessionDir(conversationDir);\n const isThread = sessionKey.includes(\":\");\n\n let sessionManager!: SessionManager;\n let contextFile!: string;\n\n if (isThread) {\n const threadFile = getThreadSessionFile(conversationDir, sessionKey);\n const existing = tryResolveThreadSession(threadFile);\n if (existing) {\n contextFile = existing;\n sessionManager = openManagedSession(contextFile, sessionDir, conversationDir);\n } else {\n const conversationSource = resolveChannelSessionFile(conversationDir);\n if (conversationSource) {\n try {\n contextFile = forkThreadSessionFile(conversationSource, threadFile, conversationDir);\n sessionManager = openManagedSession(contextFile, sessionDir, conversationDir);\n } catch {\n contextFile = createManagedSessionFileAtPath(threadFile, conversationDir);\n sessionManager = openManagedSession(contextFile, sessionDir, conversationDir);\n }\n } else {\n contextFile = createManagedSessionFileAtPath(threadFile, conversationDir);\n sessionManager = openManagedSession(contextFile, sessionDir, conversationDir);\n }\n }\n } else {\n // Direct/shared session: normal resolve\n contextFile = resolveManagedSessionFile(sessionDir, conversationDir);\n sessionManager = openManagedSession(contextFile, sessionDir, conversationDir);\n }\n const sessionUuid = extractSessionUuid(contextFile);\n // Used for Slack thread filtering — for non-Slack platforms this is effectively a no-op\n const rootTs = extractSessionSuffix(sessionKey);\n const settingsManager = createMamaSettingsManager(join(conversationDir, \"..\"));\n\n // Create AuthStorage and ModelRegistry\n // Auth stored outside workspace so agent can't access it\n const authStorage = AuthStorage.create(join(homedir(), \".pi\", \"mama\", \"auth.json\"));\n const modelRegistry = ModelRegistry.create(authStorage);\n\n // Create agent\n const agent = new Agent({\n initialState: {\n systemPrompt,\n model,\n thinkingLevel:\n (agentConfig.thinkingLevel as \"off\" | \"low\" | \"medium\" | \"high\" | undefined) ?? \"off\",\n tools,\n },\n convertToLlm,\n getApiKey: async () => {\n const key = await modelRegistry.getApiKeyForProvider(model.provider);\n if (!key)\n throw new Error(\n `No API key for provider \"${model.provider}\". Set the appropriate environment variable or configure via auth.json`,\n );\n return key;\n },\n });\n\n // Load existing messages\n const loadedSession = sessionManager.buildSessionContext();\n if (loadedSession.messages.length > 0) {\n agent.state.messages = loadedSession.messages;\n log.logInfo(\n `[${conversationId}] Loaded ${loadedSession.messages.length} messages from context.jsonl`,\n );\n }\n\n // Load extensions, skills, prompts, themes via DefaultResourceLoader\n // This reads ~/.pi/agent/settings.json (packages, extensions enable/disable)\n // and discovers resources from standard locations + npm/git packages.\n const resourceLoader = new DefaultResourceLoader({\n cwd: workspaceDir,\n agentDir: getAgentDir(),\n systemPrompt,\n });\n try {\n await resourceLoader.reload();\n const extResult = resourceLoader.getExtensions();\n if (extResult.errors.length > 0) {\n for (const err of extResult.errors) {\n log.logWarning(`[${conversationId}] Extension load error: ${err.path}`, err.error);\n }\n }\n log.logInfo(\n `[${conversationId}] Loaded ${extResult.extensions.length} extension(s): ${extResult.extensions.map((e) => e.path).join(\", \")}`,\n );\n } catch (error) {\n log.logWarning(`[${conversationId}] Failed to load resources`, String(error));\n }\n\n const baseToolsOverride = Object.fromEntries(tools.map((tool) => [tool.name, tool]));\n\n // Create AgentSession wrapper\n const session = new AgentSession({\n agent,\n sessionManager,\n settingsManager,\n cwd: workspaceDir,\n modelRegistry,\n resourceLoader,\n baseToolsOverride,\n });\n\n // Mutable per-run state - event handler references this\n const runState = {\n responseCtx: null as ChatResponseContext | null,\n logCtx: null as {\n conversationId: string;\n userName?: string;\n conversationName?: string;\n sessionId?: string;\n } | null,\n queue: null as {\n enqueue(fn: () => Promise<void>, errorContext: string): void;\n enqueueMessage(\n text: string,\n target: \"main\" | \"thread\",\n errorContext: string,\n doLog?: boolean,\n ): void;\n } | null,\n pendingTools: new Map<string, { toolName: string; args: unknown; startTime: number }>(),\n totalUsage: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n },\n llmCallCount: 0,\n stopReason: \"stop\",\n errorMessage: undefined as string | undefined,\n };\n\n // Subscribe to events ONCE\n session.subscribe(async (event) => {\n // Skip if no active run\n if (!runState.responseCtx || !runState.logCtx || !runState.queue) return;\n\n const { responseCtx, logCtx, queue, pendingTools } = runState;\n const baseAttrs = { channel_id: logCtx.conversationId, session_id: logCtx.sessionId };\n\n if (event.type === \"tool_execution_start\") {\n const agentEvent = event as AgentEvent & { type: \"tool_execution_start\" };\n const args = agentEvent.args as { label?: string };\n const label = args.label || agentEvent.toolName;\n\n pendingTools.set(agentEvent.toolCallId, {\n toolName: agentEvent.toolName,\n args: agentEvent.args,\n startTime: Date.now(),\n });\n addLifecycleBreadcrumb(\"agent.tool.started\", {\n tool: agentEvent.toolName,\n ...baseAttrs,\n });\n\n log.logToolStart(\n logCtx,\n agentEvent.toolName,\n label,\n agentEvent.args as Record<string, unknown>,\n );\n // Tool labels are omitted from the main message to reduce Slack noise.\n // Tool execution details are still posted to the thread (see tool_execution_end).\n } else if (event.type === \"tool_execution_end\") {\n const agentEvent = event as AgentEvent & { type: \"tool_execution_end\" };\n const resultStr = extractToolResultText(agentEvent.result);\n const pending = pendingTools.get(agentEvent.toolCallId);\n pendingTools.delete(agentEvent.toolCallId);\n\n const durationMs = pending ? Date.now() - pending.startTime : 0;\n\n Sentry.metrics.count(\"agent.tool.calls\", 1, {\n attributes: metricAttributes({\n tool: agentEvent.toolName,\n error: String(agentEvent.isError),\n ...baseAttrs,\n }),\n });\n Sentry.metrics.distribution(\"agent.tool.duration\", durationMs, {\n unit: \"millisecond\",\n attributes: metricAttributes({\n tool: agentEvent.toolName,\n ...baseAttrs,\n }),\n });\n addLifecycleBreadcrumb(\"agent.tool.completed\", {\n tool: agentEvent.toolName,\n error: agentEvent.isError,\n duration_ms: durationMs,\n ...baseAttrs,\n });\n\n if (agentEvent.isError) {\n log.logToolError(logCtx, agentEvent.toolName, durationMs, resultStr);\n } else {\n log.logToolSuccess(logCtx, agentEvent.toolName, durationMs, resultStr);\n }\n\n // Post args + result to thread\n const label = pending?.args ? (pending.args as { label?: string }).label : undefined;\n const argsFormatted = pending\n ? formatToolArgsForSlack(agentEvent.toolName, pending.args as Record<string, unknown>)\n : \"(args not found)\";\n const duration = (durationMs / 1000).toFixed(1);\n let threadMessage = `*${agentEvent.isError ? \"✗\" : \"✓\"} ${agentEvent.toolName}*`;\n if (label) threadMessage += `: ${label}`;\n threadMessage += ` (${duration}s)\\n`;\n if (argsFormatted) threadMessage += `\\`\\`\\`\\n${argsFormatted}\\n\\`\\`\\`\\n`;\n threadMessage += `*Result:*\\n\\`\\`\\`\\n${resultStr}\\n\\`\\`\\``;\n\n // Only post thread details for tools with meaningful output (bash, attach).\n // Skip read/write/edit to reduce Slack noise — their results are in the log.\n const quietTools = new Set([\"read\", \"write\", \"edit\"]);\n if (!quietTools.has(agentEvent.toolName)) {\n queue.enqueueMessage(threadMessage, \"thread\", \"tool result thread\", false);\n }\n\n if (agentEvent.isError) {\n queue.enqueue(\n () => responseCtx.respond(`_Error: ${truncate(resultStr, 200)}_`),\n \"tool error\",\n );\n }\n } else if (event.type === \"message_start\") {\n const agentEvent = event as AgentEvent & { type: \"message_start\" };\n if (agentEvent.message.role === \"assistant\") {\n runState.llmCallCount += 1;\n addLifecycleBreadcrumb(\"agent.llm.call.started\", {\n call_index: runState.llmCallCount,\n provider: model.provider,\n model: agentConfig.model,\n ...baseAttrs,\n });\n log.logResponseStart(logCtx);\n }\n } else if (event.type === \"message_end\") {\n const agentEvent = event as AgentEvent & { type: \"message_end\" };\n if (agentEvent.message.role === \"assistant\") {\n const assistantMsg = agentEvent.message as any;\n\n if (assistantMsg.stopReason) {\n runState.stopReason = assistantMsg.stopReason;\n }\n if (assistantMsg.errorMessage) {\n runState.errorMessage = assistantMsg.errorMessage;\n }\n\n if (assistantMsg.usage) {\n runState.totalUsage.input += assistantMsg.usage.input;\n runState.totalUsage.output += assistantMsg.usage.output;\n runState.totalUsage.cacheRead += assistantMsg.usage.cacheRead;\n runState.totalUsage.cacheWrite += assistantMsg.usage.cacheWrite;\n runState.totalUsage.cost.input += assistantMsg.usage.cost.input;\n runState.totalUsage.cost.output += assistantMsg.usage.cost.output;\n runState.totalUsage.cost.cacheRead += assistantMsg.usage.cost.cacheRead;\n runState.totalUsage.cost.cacheWrite += assistantMsg.usage.cost.cacheWrite;\n runState.totalUsage.cost.total += assistantMsg.usage.cost.total;\n\n // Per-turn LLM metrics\n const llmAttributes = metricAttributes({\n provider: model.provider,\n model: agentConfig.model,\n ...baseAttrs,\n stop_reason: assistantMsg.stopReason,\n error: Boolean(assistantMsg.errorMessage),\n });\n Sentry.metrics.count(\"agent.llm.calls\", 1, { attributes: llmAttributes });\n Sentry.metrics.distribution(\"agent.llm.tokens_in\", assistantMsg.usage.input, {\n attributes: llmAttributes,\n });\n Sentry.metrics.distribution(\"agent.llm.tokens_out\", assistantMsg.usage.output, {\n attributes: llmAttributes,\n });\n if (assistantMsg.usage.cacheRead > 0) {\n Sentry.metrics.distribution(\"agent.llm.cache_read\", assistantMsg.usage.cacheRead, {\n attributes: llmAttributes,\n });\n }\n if (assistantMsg.usage.cacheWrite > 0) {\n Sentry.metrics.distribution(\"agent.llm.cache_write\", assistantMsg.usage.cacheWrite, {\n attributes: llmAttributes,\n });\n }\n Sentry.metrics.distribution(\"agent.llm.cost_per_turn\", assistantMsg.usage.cost.total, {\n attributes: llmAttributes,\n });\n addLifecycleBreadcrumb(\"agent.llm.call.completed\", {\n call_index: runState.llmCallCount,\n provider: model.provider,\n model: agentConfig.model,\n stop_reason: assistantMsg.stopReason,\n error: Boolean(assistantMsg.errorMessage),\n input_tokens: assistantMsg.usage.input,\n output_tokens: assistantMsg.usage.output,\n cost_total_usd: assistantMsg.usage.cost.total,\n });\n }\n\n const content = agentEvent.message.content;\n const thinkingParts: string[] = [];\n const textParts: string[] = [];\n for (const part of content) {\n if (part.type === \"thinking\") {\n thinkingParts.push((part as any).thinking);\n } else if (part.type === \"text\") {\n textParts.push((part as any).text);\n }\n }\n\n const text = textParts.join(\"\\n\");\n\n for (const thinking of thinkingParts) {\n log.logThinking(logCtx, thinking);\n queue.enqueueMessage(`_${thinking}_`, \"main\", \"thinking main\");\n queue.enqueueMessage(`_${thinking}_`, \"thread\", \"thinking thread\", false);\n }\n\n if (text.trim()) {\n log.logResponse(logCtx, text);\n queue.enqueueMessage(text, \"main\", \"response main\");\n // Only overflow to thread for texts that will be truncated in main\n if (text.length > SLACK_MAX_LENGTH) {\n queue.enqueueMessage(text, \"thread\", \"response thread\", false);\n }\n }\n }\n } else if (event.type === \"compaction_start\") {\n log.logInfo(`Auto-compaction started (reason: ${(event as any).reason})`);\n queue.enqueue(() => responseCtx.respond(\"_Compacting context..._\"), \"compaction start\");\n } else if (event.type === \"compaction_end\") {\n const compEvent = event as any;\n if (compEvent.result) {\n log.logInfo(`Auto-compaction complete: ${compEvent.result.tokensBefore} tokens compacted`);\n } else if (compEvent.aborted) {\n log.logInfo(\"Auto-compaction aborted\");\n }\n } else if (event.type === \"auto_retry_start\") {\n const retryEvent = event as any;\n log.logWarning(\n `Retrying (${retryEvent.attempt}/${retryEvent.maxAttempts})`,\n retryEvent.errorMessage,\n );\n queue.enqueue(\n () =>\n responseCtx.respond(`_Retrying (${retryEvent.attempt}/${retryEvent.maxAttempts})..._`),\n \"retry\",\n );\n }\n });\n\n // Message limit constant\n const SLACK_MAX_LENGTH = 40000;\n const splitForSlack = (text: string): string[] => {\n if (text.length <= SLACK_MAX_LENGTH) return [text];\n const parts: string[] = [];\n let remaining = text;\n let partNum = 1;\n while (remaining.length > 0) {\n const chunk = remaining.substring(0, SLACK_MAX_LENGTH - 50);\n remaining = remaining.substring(SLACK_MAX_LENGTH - 50);\n const suffix = remaining.length > 0 ? `\\n_(continued ${partNum}...)_` : \"\";\n parts.push(chunk + suffix);\n partNum++;\n }\n return parts;\n };\n\n return {\n async run(\n message: ChatMessage,\n responseCtx: ChatResponseContext,\n platform: PlatformInfo,\n ): Promise<{ stopReason: string; errorMessage?: string }> {\n // Extract conversationId from sessionKey (format: \"conversationId:rootTs\" or just \"conversationId\")\n const sessionConversation = message.sessionKey.split(\":\")[0];\n\n // Ensure conversation directory exists\n await mkdir(conversationDir, { recursive: true });\n\n if (executionResolver) {\n executionResolver.refresh();\n activeExecutor = await executionResolver.resolve({\n platform: platform.name,\n userId: message.userId,\n });\n workspacePath = getWorkspacePath();\n }\n\n // Sync messages from log.jsonl that arrived while we were offline or busy\n // Exclude the current message (it will be added via prompt())\n // Default sync range is 10 days (handled by syncLogToSessionManager)\n // Thread filter ensures only messages from this session's thread are synced\n const threadFilter = message.sessionKey.includes(\":\")\n ? { scope: \"thread\" as const, rootTs, threadTs: message.threadTs }\n : { scope: \"top-level\" as const, rootTs };\n const syncedCount = await syncLogToSessionManager(\n sessionManager,\n conversationDir,\n message.id,\n undefined,\n threadFilter,\n );\n if (syncedCount > 0) {\n log.logInfo(`[${conversationId}] Synced ${syncedCount} messages from log.jsonl`);\n }\n\n // Reload messages from context.jsonl\n // This picks up any messages synced above\n const reloadedSession = sessionManager.buildSessionContext();\n if (reloadedSession.messages.length > 0) {\n agent.state.messages = reloadedSession.messages;\n log.logInfo(\n `[${conversationId}] Reloaded ${reloadedSession.messages.length} messages from context`,\n );\n }\n\n // Update system prompt with fresh memory, channel/user info, and skills\n const memory = await getMemory(conversationDir);\n const skills = loadMamaSkills(conversationDir, workspacePath);\n const systemPrompt = buildSystemPrompt(\n workspacePath,\n conversationId,\n message.conversationKind,\n message.userId,\n memory,\n executor.getSandboxConfig(),\n platform,\n skills,\n );\n session.agent.state.systemPrompt = systemPrompt;\n\n setEventContext({\n platform: platform.name,\n conversationId,\n conversationKind: message.conversationKind,\n userId: message.userId,\n });\n\n // Set up file upload function\n setUploadFunction(async (filePath: string, title?: string) => {\n const hostPath = translateToHostPath(\n filePath,\n conversationDir,\n workspacePath,\n conversationId,\n );\n await responseCtx.uploadFile(hostPath, title);\n });\n\n // Reset per-run state\n runState.responseCtx = responseCtx;\n runState.logCtx = {\n conversationId: sessionConversation,\n userName: message.userName,\n conversationName: undefined,\n sessionId: sessionUuid,\n };\n runState.pendingTools.clear();\n runState.totalUsage = {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n };\n runState.llmCallCount = 0;\n runState.stopReason = \"stop\";\n runState.errorMessage = undefined;\n\n // Create queue for this run\n let queueChain = Promise.resolve();\n runState.queue = {\n enqueue(fn: () => Promise<void>, errorContext: string): void {\n queueChain = queueChain.then(async () => {\n try {\n await fn();\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(`API error (${errorContext})`, errMsg);\n try {\n // Split long error messages to avoid msg_too_long\n const errParts = splitForSlack(`_Error: ${errMsg}_`);\n for (const part of errParts) {\n await responseCtx.respondInThread(part);\n }\n } catch {\n // Ignore\n }\n }\n });\n },\n enqueueMessage(\n text: string,\n target: \"main\" | \"thread\",\n errorContext: string,\n _doLog = true,\n ): void {\n const parts = splitForSlack(text);\n for (const part of parts) {\n this.enqueue(\n () =>\n target === \"main\" ? responseCtx.respond(part) : responseCtx.respondInThread(part),\n errorContext,\n );\n }\n },\n };\n\n // Log context info\n log.logInfo(\n `Context sizes - system: ${systemPrompt.length} chars, memory: ${memory.length} chars`,\n );\n log.logInfo(`Channels: ${platform.channels.length}, Users: ${platform.users.length}`);\n\n // Build user message with timestamp and username prefix\n // Format: \"[YYYY-MM-DD HH:MM:SS+HH:MM] [username]: message\" so LLM knows when and who\n const now = new Date();\n const pad = (n: number) => n.toString().padStart(2, \"0\");\n const offset = -now.getTimezoneOffset();\n const offsetSign = offset >= 0 ? \"+\" : \"-\";\n const offsetHours = pad(Math.floor(Math.abs(offset) / 60));\n const offsetMins = pad(Math.abs(offset) % 60);\n const timestamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}${offsetSign}${offsetHours}:${offsetMins}`;\n const threadContext = message.threadTs ? ` [in-thread:${message.threadTs}]` : \"\";\n let userMessage = `[${timestamp}] [${message.userName || \"unknown\"}]${threadContext}: ${message.text}`;\n\n const imageAttachments: ImageContent[] = [];\n const nonImagePaths: string[] = [];\n\n for (const a of message.attachments || []) {\n // a.localPath is the path relative to the workspace.\n const fullPath = `${workspacePath}/${a.localPath}`;\n const mimeType = getImageMimeType(a.localPath);\n\n if (mimeType && existsSync(fullPath)) {\n try {\n imageAttachments.push({\n type: \"image\",\n mimeType,\n data: readFileSync(fullPath).toString(\"base64\"),\n });\n } catch {\n nonImagePaths.push(fullPath);\n }\n } else {\n nonImagePaths.push(fullPath);\n }\n }\n\n if (nonImagePaths.length > 0) {\n userMessage += `\\n\\n<slack_attachments>\\n${nonImagePaths.join(\"\\n\")}\\n</slack_attachments>`;\n }\n\n // Debug: write context to last_prompt.jsonl\n const debugContext = {\n systemPrompt,\n messages: session.messages,\n newUserMessage: userMessage,\n imageAttachmentCount: imageAttachments.length,\n };\n await writeFile(\n join(conversationDir, \"last_prompt.jsonl\"),\n JSON.stringify(debugContext, null, 2),\n );\n addLifecycleBreadcrumb(\"agent.prompt.sent\", {\n provider: model.provider,\n model: agentConfig.model,\n channel_id: sessionConversation,\n session_id: sessionUuid,\n attachment_count: message.attachments?.length ?? 0,\n image_attachment_count: imageAttachments.length,\n });\n\n await session.prompt(\n userMessage,\n imageAttachments.length > 0 ? { images: imageAttachments } : undefined,\n );\n\n // Wait for queued messages\n await queueChain;\n\n // Handle error case - update main message and post error to thread\n if (runState.stopReason === \"error\" && runState.errorMessage) {\n try {\n await responseCtx.replaceResponse(\"_Sorry, something went wrong_\");\n // Split long error messages to avoid msg_too_long\n const errorParts = splitForSlack(`_Error: ${runState.errorMessage}_`);\n for (const part of errorParts) {\n await responseCtx.respondInThread(part);\n }\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(\"Failed to post error message\", errMsg);\n }\n } else {\n // Final message update\n const messages = session.messages;\n const lastAssistant = messages.filter((m) => m.role === \"assistant\").pop();\n const finalText =\n lastAssistant?.content\n .filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\\n\") || \"\";\n\n // Check for [SILENT] marker - delete message and thread instead of posting\n if (finalText.trim() === \"[SILENT]\" || finalText.trim().startsWith(\"[SILENT]\")) {\n try {\n await responseCtx.deleteResponse();\n log.logInfo(\"Silent response - deleted message and thread\");\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(\"Failed to delete message for silent response\", errMsg);\n }\n } else if (finalText.trim()) {\n try {\n const mainText =\n finalText.length > SLACK_MAX_LENGTH\n ? `${finalText.substring(0, SLACK_MAX_LENGTH - 50)}\\n\\n_(see thread for full response)_`\n : finalText;\n await responseCtx.replaceResponse(mainText);\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(\"Failed to replace message with final text\", errMsg);\n }\n }\n }\n\n // Log usage summary with context info\n if (runState.totalUsage.cost.total > 0) {\n // Get last non-aborted assistant message for context calculation\n const messages = session.messages;\n const lastAssistantMessage = messages\n .slice()\n .reverse()\n .find((m) => m.role === \"assistant\" && (m as any).stopReason !== \"aborted\") as any;\n\n const contextTokens = lastAssistantMessage\n ? lastAssistantMessage.usage.input +\n lastAssistantMessage.usage.output +\n lastAssistantMessage.usage.cacheRead +\n lastAssistantMessage.usage.cacheWrite\n : 0;\n const contextWindow = model.contextWindow || 200000;\n\n // Run-level Sentry metrics\n const { totalUsage } = runState;\n const runMetricAttributes = metricAttributes({\n provider: model.provider,\n model: agentConfig.model,\n channel_id: sessionConversation,\n session_id: sessionUuid,\n stop_reason: runState.stopReason,\n llm_calls: runState.llmCallCount,\n });\n Sentry.metrics.distribution(\"agent.run.tokens_in\", totalUsage.input, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.tokens_out\", totalUsage.output, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.cache_read\", totalUsage.cacheRead, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.cache_write\", totalUsage.cacheWrite, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.cost\", totalUsage.cost.total, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.gauge(\"agent.context.utilization\", contextTokens / contextWindow, {\n unit: \"ratio\",\n attributes: runMetricAttributes,\n });\n\n const summary = log.logUsageSummary(\n runState.logCtx!,\n runState.totalUsage,\n contextTokens,\n contextWindow,\n );\n // Split long summaries to avoid msg_too_long\n const summaryParts = splitForSlack(summary);\n for (const part of summaryParts) {\n runState.queue!.enqueue(\n () => responseCtx.respondInThread(part, { style: \"muted\" }),\n \"usage summary\",\n );\n }\n await queueChain;\n }\n\n // Clear run state\n runState.responseCtx = null;\n runState.logCtx = null;\n runState.queue = null;\n\n return { stopReason: runState.stopReason, errorMessage: runState.errorMessage };\n },\n\n abort(): void {\n session.abort();\n },\n\n getCurrentStep(): { toolName?: string; label?: string } | undefined {\n const pending = runState.pendingTools;\n if (pending.size === 0) return undefined;\n // Get the first pending tool\n const first = pending.values().next().value;\n if (!first) return undefined;\n return {\n toolName: first.toolName,\n label: (first.args as { label?: string })?.label,\n };\n },\n };\n}\n\n/**\n * Translate container path back to host path for file operations\n */\nfunction translateToHostPath(\n containerPath: string,\n conversationDir: string,\n workspacePath: string,\n conversationId: string,\n): string {\n if (workspacePath === \"/workspace\") {\n const prefix = `/workspace/${conversationId}/`;\n if (containerPath.startsWith(prefix)) {\n return join(conversationDir, containerPath.slice(prefix.length));\n }\n if (containerPath.startsWith(\"/workspace/\")) {\n return join(conversationDir, \"..\", containerPath.slice(\"/workspace/\".length));\n }\n }\n return containerPath;\n}\n"]}
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EACV,WAAW,EACX,mBAAmB,EAGnB,YAAY,EACb,MAAM,cAAc,CAAC;AAKtB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAiC,KAAK,aAAa,EAAE,MAAM,cAAc,CAAC;AAEjF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAIL,KAAK,oBAAoB,EAE1B,MAAM,oBAAoB,CAAC;AAI5B,MAAM,WAAW,WAAW;IAC1B,GAAG,CACD,OAAO,EAAE,WAAW,EACpB,WAAW,EAAE,mBAAmB,EAChC,QAAQ,EAAE,YAAY,GACrB,OAAO,CAAC;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC1D,KAAK,IAAI,IAAI,CAAC;IACd,6DAA6D;IAC7D,cAAc,IAAI;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;CACrE;AA0WD;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,aAAa,EAAE,aAAa,EAC5B,UAAU,EAAE,MAAM,EAClB,cAAc,EAAE,MAAM,EACtB,eAAe,EAAE,MAAM,EACvB,YAAY,EAAE,MAAM,EACpB,YAAY,EAAE,oBAAoB,EAClC,YAAY,CAAC,EAAE,YAAY,EAC3B,YAAY,CAAC,EAAE,gBAAgB,EAC/B,WAAW,CAAC,EAAE,sBAAsB,GACnC,OAAO,CAAC,WAAW,CAAC,CAssBtB","sourcesContent":["import { Agent, type AgentEvent } from \"@mariozechner/pi-agent-core\";\nimport { getModel, type ImageContent } from \"@mariozechner/pi-ai\";\nimport {\n AgentSession,\n AuthStorage,\n convertToLlm,\n DefaultResourceLoader,\n formatSkillsForPrompt,\n getAgentDir,\n loadSkillsFromDir,\n ModelRegistry,\n type Skill,\n} from \"@mariozechner/pi-coding-agent\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { mkdir, readFile, writeFile } from \"fs/promises\";\nimport { homedir } from \"os\";\nimport { join } from \"path\";\nimport type {\n ChatMessage,\n ChatResponseContext,\n ChatToolResult,\n ConversationKind,\n PlatformInfo,\n} from \"./adapter.js\";\nimport { loadAgentConfig } from \"./config.js\";\nimport { createMamaSettingsManager, syncLogToSessionManager } from \"./context.js\";\nimport { ActorExecutionResolver } from \"./execution-resolver.js\";\nimport * as log from \"./log.js\";\nimport type { UserBindingStore } from \"./bindings.js\";\nimport type { DockerContainerManager } from \"./provisioner.js\";\nimport { createExecutor, type Executor, type SandboxConfig } from \"./sandbox.js\";\nimport { addLifecycleBreadcrumb, metricAttributes } from \"./sentry.js\";\nimport type { VaultManager } from \"./vault.js\";\nimport {\n extractSessionSuffix,\n extractSessionUuid,\n openManagedSession,\n type ResolvedSessionScope,\n type ThreadRootMessage,\n} from \"./session-store.js\";\nimport { createMamaTools } from \"./tools/index.js\";\nimport * as Sentry from \"@sentry/node\";\n\nexport interface AgentRunner {\n run(\n message: ChatMessage,\n responseCtx: ChatResponseContext,\n platform: PlatformInfo,\n ): Promise<{ stopReason: string; errorMessage?: string }>;\n abort(): void;\n /** Get current step info (tool name, label) for debugging */\n getCurrentStep(): { toolName?: string; label?: string } | undefined;\n}\n\nconst IMAGE_MIME_TYPES: Record<string, string> = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n gif: \"image/gif\",\n webp: \"image/webp\",\n};\n\nfunction getImageMimeType(filename: string): string | undefined {\n return IMAGE_MIME_TYPES[filename.toLowerCase().split(\".\").pop() || \"\"];\n}\n\nfunction buildThreadSessionName(message: ThreadRootMessage | null): string | undefined {\n const text = message?.text?.trim();\n if (!text) return undefined;\n const userLabel = message?.userName || message?.user || \"unknown\";\n return `[${userLabel}]: ${text}`;\n}\n\nasync function getMemory(conversationDir: string): Promise<string> {\n const parts: string[] = [];\n\n // Read workspace-level memory (shared across all conversations)\n const workspaceMemoryPath = join(conversationDir, \"..\", \"MEMORY.md\");\n if (existsSync(workspaceMemoryPath)) {\n try {\n const content = (await readFile(workspaceMemoryPath, \"utf-8\")).trim();\n if (content) {\n parts.push(`### Global Workspace Memory\\n${content}`);\n }\n } catch (error) {\n log.logWarning(\"Failed to read workspace memory\", `${workspaceMemoryPath}: ${error}`);\n }\n }\n\n // Read conversation-specific memory\n const conversationMemoryPath = join(conversationDir, \"MEMORY.md\");\n if (existsSync(conversationMemoryPath)) {\n try {\n const content = (await readFile(conversationMemoryPath, \"utf-8\")).trim();\n if (content) {\n parts.push(`### Conversation-Specific Memory\\n${content}`);\n }\n } catch (error) {\n log.logWarning(\"Failed to read conversation memory\", `${conversationMemoryPath}: ${error}`);\n }\n }\n\n if (parts.length === 0) {\n return \"(no working memory yet)\";\n }\n\n return parts.join(\"\\n\\n\");\n}\n\nfunction loadMamaSkills(conversationDir: string, workspacePath: string): Skill[] {\n const skillMap = new Map<string, Skill>();\n\n // conversationDir is the host path (e.g., /Users/.../data/C0A34FL8PMH)\n // hostWorkspacePath is the parent directory on host\n // workspacePath is the container path (e.g., /workspace)\n const hostWorkspacePath = join(conversationDir, \"..\");\n\n // Helper to translate host paths to container paths\n const translatePath = (hostPath: string): string => {\n if (hostPath.startsWith(hostWorkspacePath)) {\n return workspacePath + hostPath.slice(hostWorkspacePath.length);\n }\n return hostPath;\n };\n\n // Load workspace-level skills (global)\n const workspaceSkillsDir = join(hostWorkspacePath, \"skills\");\n for (const skill of loadSkillsFromDir({ dir: workspaceSkillsDir, source: \"workspace\" }).skills) {\n // Translate paths to container paths for system prompt\n skill.filePath = translatePath(skill.filePath);\n skill.baseDir = translatePath(skill.baseDir);\n skillMap.set(skill.name, skill);\n }\n\n // Load conversation-specific skills (override workspace skills on collision)\n const conversationSkillsDir = join(conversationDir, \"skills\");\n for (const skill of loadSkillsFromDir({ dir: conversationSkillsDir, source: \"channel\" }).skills) {\n skill.filePath = translatePath(skill.filePath);\n skill.baseDir = translatePath(skill.baseDir);\n skillMap.set(skill.name, skill);\n }\n\n return Array.from(skillMap.values());\n}\n\nfunction buildSystemPrompt(\n workspacePath: string,\n conversationId: string,\n conversationKind: ConversationKind,\n currentUserId: string | undefined,\n memory: string,\n sandboxConfig: SandboxConfig,\n platform: PlatformInfo,\n skills: Skill[],\n): string {\n const conversationPath = `${workspacePath}/${conversationId}`;\n const isContainer = sandboxConfig.type === \"container\" || sandboxConfig.type === \"image\";\n const isImageSandbox = sandboxConfig.type === \"image\";\n const isFirecracker = sandboxConfig.type === \"firecracker\";\n\n // Format channel mappings\n const channelMappings =\n platform.channels.length > 0\n ? platform.channels.map((c) => `${c.id}\\t#${c.name}`).join(\"\\n\")\n : \"(no channels loaded)\";\n\n // Format user mappings\n const userMappings =\n platform.users.length > 0\n ? platform.users.map((u) => `${u.id}\\t@${u.userName}\\t${u.displayName}`).join(\"\\n\")\n : \"(no users loaded)\";\n\n const envDescription = isImageSandbox\n ? `You are running inside a managed per-user container.\n- Bash working directory: / (use cd or absolute paths)\n- Install tools with the image's package manager\n- Your changes persist for this user's container until it is recreated`\n : isContainer\n ? `You are running inside a shared container.\n- Bash working directory: / (use cd or absolute paths)\n- Install tools with the container's package manager\n- Your changes persist across sessions`\n : isFirecracker\n ? `You are running inside a Firecracker microVM.\n- Bash working directory: / (use cd or absolute paths)\n- Install tools with: apt-get install <package> (Debian-based)\n- Your changes persist across sessions`\n : `You are running directly on the host machine.\n- Bash working directory: ${process.cwd()}\n- Be careful with system modifications`;\n\n return `You are mama, a ${platform.name} bot assistant. Be concise. No emojis.\n\n## Context\n- For current date/time, use: date\n- You have access to previous conversation context including tool results from prior turns.\n- For older human-readable history beyond your context, search \\`log.jsonl\\` (contains user messages and your final responses, but not tool results).\n- Structured session history with tool results lives in \\`${conversationPath}/sessions/\\`.\n- The active top-level session is selected by \\`${conversationPath}/sessions/current\\`, which points to a timestamped \\`.jsonl\\` file in the same directory.\n- Scoped/thread sessions use fixed files at \\`${conversationPath}/sessions/<scope_id>.jsonl\\` (for example \\`${conversationPath}/sessions/1777386320.800769.jsonl\\`).\n- User messages include a \\`[in-thread:TS]\\` marker when sent from within a platform thread/reply (TS is the thread or parent message identifier). Without this marker, the message is a top-level conversation message.\n\n${platform.formattingGuide}\n\n## Platform IDs\nChannels: ${channelMappings}\n\nUsers: ${userMappings}\n\nWhen mentioning users, use <@username> format (e.g., <@mario>).\n\n## Environment\n${envDescription}\n\n## Workspace Layout\n${workspacePath}/\n├── MEMORY.md # Global memory (all conversations)\n├── skills/ # Global CLI tools you create\n└── ${conversationId}/ # This conversation\n ├── MEMORY.md # Conversation-specific memory\n ├── log.jsonl # Human-readable message history (no tool results)\n ├── sessions/ # Structured session history used for context reconstruction\n │ ├── current # Active top-level session pointer\n │ ├── <timestamp>_<id>.jsonl # Top-level session files\n │ └── <scope_id>.jsonl # Scoped thread/reply session files\n ├── attachments/ # User-shared files\n ├── scratch/ # Your working directory\n └── skills/ # Conversation-specific tools\n\n## Skills (Custom CLI Tools)\nYou can create reusable CLI tools for recurring tasks (email, APIs, data processing, etc.).\n\n### Creating Skills\nStore in \\`${workspacePath}/skills/<name>/\\` (global) or \\`${conversationPath}/skills/<name>/\\` (conversation-specific).\nEach skill directory needs a \\`SKILL.md\\` with YAML frontmatter:\n\n\\`\\`\\`markdown\n---\nname: skill-name\ndescription: Short description of what this skill does\n---\n\n# Skill Name\n\nUsage instructions, examples, etc.\nScripts are in: {baseDir}/\n\\`\\`\\`\n\n\\`name\\` and \\`description\\` are required. Use \\`{baseDir}\\` as placeholder for the skill's directory path.\n\n### Available Skills\n${skills.length > 0 ? formatSkillsForPrompt(skills) : \"(no skills installed yet)\"}\n\n## Events\nYou can schedule events that wake you up at specific times or when external things happen. Events are JSON files in \\`${workspacePath}/events/\\`.\n\n### Event Types\n\n**Immediate** - Triggers as soon as harness sees the file. Use in scripts/webhooks to signal external events.\n\\`\\`\\`json\n{\"type\": \"immediate\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"New GitHub issue opened\"}\n\\`\\`\\`\n\n**One-shot** - Triggers once at a specific time. Use for reminders.\n\\`\\`\\`json\n{\"type\": \"one-shot\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"Remind Mario about dentist\", \"at\": \"2025-12-15T09:00:00+01:00\"}\n\\`\\`\\`\n\n**Periodic** - Triggers on a cron schedule. Use for recurring tasks.\n\\`\\`\\`json\n{\"type\": \"periodic\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"Check inbox and summarize\", \"schedule\": \"0 9 * * 1-5\", \"timezone\": \"${Intl.DateTimeFormat().resolvedOptions().timeZone}\"}\n\\`\\`\\`\n\n### Cron Format\n\\`minute hour day-of-month month day-of-week\\`\n- \\`0 9 * * *\\` = daily at 9:00\n- \\`0 9 * * 1-5\\` = weekdays at 9:00\n- \\`30 14 * * 1\\` = Mondays at 14:30\n- \\`0 0 1 * *\\` = first of each month at midnight\n\n### Timezones\nAll \\`at\\` timestamps must include offset (e.g., \\`+01:00\\`). Periodic events use IANA timezone names. The harness runs in ${Intl.DateTimeFormat().resolvedOptions().timeZone}. When users mention times without timezone, assume ${Intl.DateTimeFormat().resolvedOptions().timeZone}.\n\n### Platform and Credential Routing\nSet \\`platform\\` to the target bot platform (\\`${platform.name}\\` for this conversation). Include it explicitly to avoid ambiguity.\n\nSet \\`userId\\` to the platform userId of whoever asked for the event. When the event fires, tool execution routes using that user's vault selection in per-user modes. In \\`container:<name>\\`, events use the container's single shared vault.\n\nPrefer the \\`event\\` tool over manually writing JSON files; it fills \\`platform\\`, \\`conversationId\\`, \\`conversationKind\\`, and \\`userId\\` for the current conversation automatically.\n\n### Creating Events\nUse unique filenames to avoid overwriting existing events. Include a timestamp or random suffix:\n\\`\\`\\`bash\ncat > ${workspacePath}/events/dentist-reminder-$(date +%s).json << 'EOF'\n{\"type\": \"one-shot\", \"platform\": \"${platform.name}\", \"conversationId\": \"${conversationId}\", \"conversationKind\": \"${conversationKind}\", \"userId\": \"${currentUserId ?? \"<requester userId>\"}\", \"text\": \"Dentist tomorrow\", \"at\": \"2025-12-14T09:00:00+01:00\"}\nEOF\n\\`\\`\\`\nOr check if file exists first before creating.\n\n### Managing Events\n- List: \\`ls ${workspacePath}/events/\\`\n- View: \\`cat ${workspacePath}/events/foo.json\\`\n- Delete/cancel: \\`rm ${workspacePath}/events/foo.json\\`\n\n### When Events Trigger\nYou receive a message like:\n\\`\\`\\`\n[EVENT:dentist-reminder.json:one-shot:2025-12-14T09:00:00+01:00] Dentist tomorrow\n\\`\\`\\`\nImmediate and one-shot events auto-delete after triggering. Periodic events persist until you delete them.\n\n### Silent Completion\nFor periodic events where there's nothing to report, respond with just \\`[SILENT]\\` (no other text). This deletes the status message and posts nothing to the platform. Use this to avoid spamming the channel when periodic checks find nothing actionable.\n\n### Debouncing\nWhen writing programs that create immediate events (email watchers, webhook handlers, etc.), always debounce. If 50 emails arrive in a minute, don't create 50 immediate events. Instead collect events over a window and create ONE immediate event summarizing what happened, or just signal \"new activity, check inbox\" rather than per-item events. Or simpler: use a periodic event to check for new items every N minutes instead of immediate events.\n\n### Limits\nMaximum 5 events can be queued. Don't create excessive immediate or periodic events.\n\n## Memory\nWrite to MEMORY.md files to persist context across conversations.\n- Global (${workspacePath}/MEMORY.md): skills, preferences, project info\n- Conversation (${conversationPath}/MEMORY.md): conversation-specific decisions, ongoing work\nUpdate when you learn something important or when asked to remember something.\n\n### Current Memory\n${memory}\n\n## System Configuration Log\nMaintain ${workspacePath}/SYSTEM.md to log all environment modifications:\n- Installed packages (apt install, npm install, uv pip install)\n- Environment variables set\n- Config files modified (~/.gitconfig, cron jobs, etc.)\n- Skill dependencies installed\n\nUpdate this file whenever you modify the environment. On fresh container, read it first to restore your setup.\n\n## Log Queries (for older history)\nFormat: \\`{\"date\":\"...\",\"ts\":\"...\",\"user\":\"...\",\"userName\":\"...\",\"text\":\"...\",\"isBot\":false}\\`\nThe log contains user messages and your final responses (not tool calls/results).\nUse \\`log.jsonl\\` for quick grep-style history. Use \\`${conversationPath}/sessions/\\` when you need structured turns, tool outputs, or branch lineage.\n${isContainer ? \"Install jq: apt-get install jq\" : \"\"}\n${isFirecracker ? \"Install jq: apt-get install jq\" : \"\"}\n\n\\`\\`\\`bash\n# Recent messages\ntail -30 log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'\n\n# Search for specific topic\ngrep -i \"topic\" log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'\n\n# Messages from specific user\ngrep '\"userName\":\"mario\"' log.jsonl | tail -20 | jq -c '{date: .date[0:19], text}'\n\n# Inspect top-level session pointer and available session files\ncat sessions/current\nls -1 sessions/\n\\`\\`\\`\n\n## Tools\n- bash: Run shell commands (primary tool). Install packages as needed.\n- read: Read files\n- write: Create/overwrite files\n- edit: Surgical file edits\n- attach: Share files to the platform\n\nEach tool requires a \"label\" parameter (shown to user).\n`;\n}\n\nfunction truncate(text: string, maxLen: number): string {\n if (text.length <= maxLen) return text;\n return `${text.substring(0, maxLen - 3)}...`;\n}\n\n// Tools whose output is interesting in the structured session log but too noisy\n// to surface as a per-tool diagnostic to the user.\nconst QUIET_TOOLS = new Set([\"read\", \"write\", \"edit\"]);\n\n// Cap raw tool output before handing it to adapters. Bash output can be MB; without\n// this each adapter's splitter would fan it out into many sequential platform posts.\nconst TOOL_RESULT_DIAGNOSTIC_CAP = 8000;\n\nfunction extractToolResultText(result: unknown): string {\n if (typeof result === \"string\") {\n return result;\n }\n\n if (\n result &&\n typeof result === \"object\" &&\n \"content\" in result &&\n Array.isArray((result as { content: unknown }).content)\n ) {\n const content = (result as { content: Array<{ type: string; text?: string }> }).content;\n const textParts: string[] = [];\n for (const part of content) {\n if (part.type === \"text\" && part.text) {\n textParts.push(part.text);\n }\n }\n if (textParts.length > 0) {\n return textParts.join(\"\\n\");\n }\n }\n\n return JSON.stringify(result);\n}\n\n// ============================================================================\n// Agent runner\n// ============================================================================\n\n/**\n * Create a new AgentRunner for a channel.\n * Sets up the session and subscribes to events once.\n *\n * Runner caching is handled by the caller (channelStates in main.ts).\n * This is a stateless factory function.\n */\nexport async function createRunner(\n sandboxConfig: SandboxConfig,\n sessionKey: string,\n conversationId: string,\n conversationDir: string,\n workspaceDir: string,\n sessionScope: ResolvedSessionScope,\n vaultManager?: VaultManager,\n bindingStore?: UserBindingStore,\n provisioner?: DockerContainerManager,\n): Promise<AgentRunner> {\n const agentConfig = loadAgentConfig(workspaceDir);\n\n // Initialize logger with settings from config\n log.initLogger({\n logFormat: agentConfig.logFormat,\n logLevel: agentConfig.logLevel,\n });\n\n const executionResolver =\n vaultManager &&\n sandboxConfig.type !== \"host\" &&\n (vaultManager.isEnabled() ||\n !!bindingStore ||\n sandboxConfig.type === \"container\" ||\n sandboxConfig.type === \"image\")\n ? new ActorExecutionResolver(sandboxConfig, vaultManager, bindingStore, provisioner)\n : undefined;\n let activeExecutor: Executor =\n executionResolver !== undefined\n ? createExecutor({ type: \"host\" })\n : createExecutor(sandboxConfig);\n const executor: Executor = {\n exec(command, options) {\n return activeExecutor.exec(command, options);\n },\n getWorkspacePath(hostPath) {\n return activeExecutor.getWorkspacePath(hostPath);\n },\n getSandboxConfig() {\n return activeExecutor.getSandboxConfig();\n },\n };\n const workspaceBase = conversationDir.replace(`/${conversationId}`, \"\");\n const getWorkspacePath = () => executor.getWorkspacePath(workspaceBase);\n let workspacePath = getWorkspacePath();\n\n // Create tools (per-runner, with per-runner upload function setter)\n const { tools, setUploadFunction, setEventContext } = createMamaTools(executor, workspaceDir);\n\n // Resolve model from config\n // Use 'as any' cast because agentConfig.provider/model are plain strings,\n // while getModel() has constrained generic types for known providers.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const model = (getModel as any)(agentConfig.provider, agentConfig.model);\n\n // Initial system prompt (will be updated each run with fresh memory/channels/users/skills)\n const memory = await getMemory(conversationDir);\n const skills = loadMamaSkills(conversationDir, workspacePath);\n const emptyPlatform: PlatformInfo = {\n name: \"chat\",\n formattingGuide: \"\",\n channels: [],\n users: [],\n };\n const systemPrompt = buildSystemPrompt(\n workspacePath,\n conversationId,\n \"shared\",\n undefined,\n memory,\n sandboxConfig,\n emptyPlatform,\n skills,\n );\n\n // Create session manager and settings manager. Top-level/private sessions\n // use the conversation's current pointer; scoped sessions use fixed files.\n // Platform-specific branch/fork behavior is resolved before runner creation.\n const isThread = sessionKey.includes(\":\");\n const rootTs = extractSessionSuffix(sessionKey);\n const { sessionDir, contextFile, threadRootMessage } = sessionScope;\n const sessionManager = openManagedSession(contextFile, sessionDir, conversationDir);\n const threadSessionName = buildThreadSessionName(threadRootMessage);\n if (isThread && threadSessionName && sessionManager.getSessionName() !== threadSessionName) {\n sessionManager.appendSessionInfo(threadSessionName);\n }\n\n const sessionUuid = extractSessionUuid(contextFile);\n const settingsManager = createMamaSettingsManager(join(conversationDir, \"..\"));\n\n // Create AuthStorage and ModelRegistry\n // Auth stored outside workspace so agent can't access it\n const authStorage = AuthStorage.create(join(homedir(), \".pi\", \"mama\", \"auth.json\"));\n const modelRegistry = ModelRegistry.create(authStorage);\n\n // Create agent\n const agent = new Agent({\n initialState: {\n systemPrompt,\n model,\n thinkingLevel:\n (agentConfig.thinkingLevel as \"off\" | \"low\" | \"medium\" | \"high\" | undefined) ?? \"off\",\n tools,\n },\n convertToLlm,\n getApiKey: async () => {\n const key = await modelRegistry.getApiKeyForProvider(model.provider);\n if (!key)\n throw new Error(\n `No API key for provider \"${model.provider}\". Set the appropriate environment variable or configure via auth.json`,\n );\n return key;\n },\n });\n\n // Load existing messages\n const loadedSession = sessionManager.buildSessionContext();\n if (loadedSession.messages.length > 0) {\n agent.state.messages = loadedSession.messages;\n log.logInfo(\n `[${conversationId}] Loaded ${loadedSession.messages.length} messages from context.jsonl`,\n );\n }\n\n // Load extensions, skills, prompts, themes via DefaultResourceLoader\n // This reads ~/.pi/agent/settings.json (packages, extensions enable/disable)\n // and discovers resources from standard locations + npm/git packages.\n const resourceLoader = new DefaultResourceLoader({\n cwd: workspaceDir,\n agentDir: getAgentDir(),\n systemPrompt,\n });\n try {\n await resourceLoader.reload();\n const extResult = resourceLoader.getExtensions();\n if (extResult.errors.length > 0) {\n for (const err of extResult.errors) {\n log.logWarning(`[${conversationId}] Extension load error: ${err.path}`, err.error);\n }\n }\n log.logInfo(\n `[${conversationId}] Loaded ${extResult.extensions.length} extension(s): ${extResult.extensions.map((e) => e.path).join(\", \")}`,\n );\n } catch (error) {\n log.logWarning(`[${conversationId}] Failed to load resources`, String(error));\n }\n\n const baseToolsOverride = Object.fromEntries(tools.map((tool) => [tool.name, tool]));\n\n // Create AgentSession wrapper\n const session = new AgentSession({\n agent,\n sessionManager,\n settingsManager,\n cwd: workspaceDir,\n modelRegistry,\n resourceLoader,\n baseToolsOverride,\n });\n\n // Mutable per-run state - event handler references this\n const runState = {\n responseCtx: null as ChatResponseContext | null,\n logCtx: null as {\n conversationId: string;\n userName?: string;\n conversationName?: string;\n sessionId?: string;\n } | null,\n queue: null as {\n enqueue(fn: () => Promise<void>, errorContext: string): void;\n } | null,\n pendingTools: new Map<string, { toolName: string; args: unknown; startTime: number }>(),\n totalUsage: {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n },\n llmCallCount: 0,\n stopReason: \"stop\",\n errorMessage: undefined as string | undefined,\n };\n\n // Subscribe to events ONCE\n session.subscribe(async (event) => {\n // Skip if no active run\n if (!runState.responseCtx || !runState.logCtx || !runState.queue) return;\n\n const { responseCtx, logCtx, queue, pendingTools } = runState;\n const baseAttrs = { channel_id: logCtx.conversationId, session_id: logCtx.sessionId };\n\n if (event.type === \"tool_execution_start\") {\n const agentEvent = event as AgentEvent & { type: \"tool_execution_start\" };\n const args = agentEvent.args as { label?: string };\n const label = args.label || agentEvent.toolName;\n\n pendingTools.set(agentEvent.toolCallId, {\n toolName: agentEvent.toolName,\n args: agentEvent.args,\n startTime: Date.now(),\n });\n addLifecycleBreadcrumb(\"agent.tool.started\", {\n tool: agentEvent.toolName,\n ...baseAttrs,\n });\n\n log.logToolStart(\n logCtx,\n agentEvent.toolName,\n label,\n agentEvent.args as Record<string, unknown>,\n );\n } else if (event.type === \"tool_execution_end\") {\n const agentEvent = event as AgentEvent & { type: \"tool_execution_end\" };\n const resultStr = extractToolResultText(agentEvent.result);\n const pending = pendingTools.get(agentEvent.toolCallId);\n pendingTools.delete(agentEvent.toolCallId);\n\n const durationMs = pending ? Date.now() - pending.startTime : 0;\n\n Sentry.metrics.count(\"agent.tool.calls\", 1, {\n attributes: metricAttributes({\n tool: agentEvent.toolName,\n error: String(agentEvent.isError),\n ...baseAttrs,\n }),\n });\n Sentry.metrics.distribution(\"agent.tool.duration\", durationMs, {\n unit: \"millisecond\",\n attributes: metricAttributes({\n tool: agentEvent.toolName,\n ...baseAttrs,\n }),\n });\n addLifecycleBreadcrumb(\"agent.tool.completed\", {\n tool: agentEvent.toolName,\n error: agentEvent.isError,\n duration_ms: durationMs,\n ...baseAttrs,\n });\n\n if (agentEvent.isError) {\n log.logToolError(logCtx, agentEvent.toolName, durationMs, resultStr);\n } else {\n log.logToolSuccess(logCtx, agentEvent.toolName, durationMs, resultStr);\n }\n\n if (!QUIET_TOOLS.has(agentEvent.toolName)) {\n const toolResult: ChatToolResult = {\n toolName: agentEvent.toolName,\n label: pending?.args ? (pending.args as { label?: string }).label : undefined,\n args: pending?.args as Record<string, unknown> | undefined,\n result: truncate(resultStr, TOOL_RESULT_DIAGNOSTIC_CAP),\n isError: agentEvent.isError,\n durationMs,\n };\n queue.enqueue(() => responseCtx.respondToolResult(toolResult), \"tool result diagnostic\");\n }\n\n if (agentEvent.isError) {\n queue.enqueue(\n () => responseCtx.respond(`_Error: ${truncate(resultStr, 200)}_`),\n \"tool error\",\n );\n }\n } else if (event.type === \"message_start\") {\n const agentEvent = event as AgentEvent & { type: \"message_start\" };\n if (agentEvent.message.role === \"assistant\") {\n runState.llmCallCount += 1;\n addLifecycleBreadcrumb(\"agent.llm.call.started\", {\n call_index: runState.llmCallCount,\n provider: model.provider,\n model: agentConfig.model,\n ...baseAttrs,\n });\n log.logResponseStart(logCtx);\n }\n } else if (event.type === \"message_end\") {\n const agentEvent = event as AgentEvent & { type: \"message_end\" };\n if (agentEvent.message.role === \"assistant\") {\n const assistantMsg = agentEvent.message as any;\n\n if (assistantMsg.stopReason) {\n runState.stopReason = assistantMsg.stopReason;\n }\n if (assistantMsg.errorMessage) {\n runState.errorMessage = assistantMsg.errorMessage;\n }\n\n if (assistantMsg.usage) {\n runState.totalUsage.input += assistantMsg.usage.input;\n runState.totalUsage.output += assistantMsg.usage.output;\n runState.totalUsage.cacheRead += assistantMsg.usage.cacheRead;\n runState.totalUsage.cacheWrite += assistantMsg.usage.cacheWrite;\n runState.totalUsage.cost.input += assistantMsg.usage.cost.input;\n runState.totalUsage.cost.output += assistantMsg.usage.cost.output;\n runState.totalUsage.cost.cacheRead += assistantMsg.usage.cost.cacheRead;\n runState.totalUsage.cost.cacheWrite += assistantMsg.usage.cost.cacheWrite;\n runState.totalUsage.cost.total += assistantMsg.usage.cost.total;\n\n // Per-turn LLM metrics\n const llmAttributes = metricAttributes({\n provider: model.provider,\n model: agentConfig.model,\n ...baseAttrs,\n stop_reason: assistantMsg.stopReason,\n error: Boolean(assistantMsg.errorMessage),\n });\n Sentry.metrics.count(\"agent.llm.calls\", 1, { attributes: llmAttributes });\n Sentry.metrics.distribution(\"agent.llm.tokens_in\", assistantMsg.usage.input, {\n attributes: llmAttributes,\n });\n Sentry.metrics.distribution(\"agent.llm.tokens_out\", assistantMsg.usage.output, {\n attributes: llmAttributes,\n });\n if (assistantMsg.usage.cacheRead > 0) {\n Sentry.metrics.distribution(\"agent.llm.cache_read\", assistantMsg.usage.cacheRead, {\n attributes: llmAttributes,\n });\n }\n if (assistantMsg.usage.cacheWrite > 0) {\n Sentry.metrics.distribution(\"agent.llm.cache_write\", assistantMsg.usage.cacheWrite, {\n attributes: llmAttributes,\n });\n }\n Sentry.metrics.distribution(\"agent.llm.cost_per_turn\", assistantMsg.usage.cost.total, {\n attributes: llmAttributes,\n });\n addLifecycleBreadcrumb(\"agent.llm.call.completed\", {\n call_index: runState.llmCallCount,\n provider: model.provider,\n model: agentConfig.model,\n stop_reason: assistantMsg.stopReason,\n error: Boolean(assistantMsg.errorMessage),\n input_tokens: assistantMsg.usage.input,\n output_tokens: assistantMsg.usage.output,\n cost_total_usd: assistantMsg.usage.cost.total,\n });\n }\n\n const content = agentEvent.message.content;\n const thinkingParts: string[] = [];\n const textParts: string[] = [];\n for (const part of content) {\n if (part.type === \"thinking\") {\n thinkingParts.push((part as any).thinking);\n } else if (part.type === \"text\") {\n textParts.push((part as any).text);\n }\n }\n\n const text = textParts.join(\"\\n\");\n\n for (const thinking of thinkingParts) {\n log.logThinking(logCtx, thinking);\n queue.enqueue(() => responseCtx.respond(`_${thinking}_`), \"thinking main\");\n queue.enqueue(\n () => responseCtx.respondDiagnostic(`_${thinking}_`),\n \"thinking diagnostic\",\n );\n }\n\n if (text.trim()) {\n log.logResponse(logCtx, text);\n queue.enqueue(() => responseCtx.respond(text), \"response main\");\n }\n }\n } else if (event.type === \"compaction_start\") {\n log.logInfo(`Auto-compaction started (reason: ${(event as any).reason})`);\n queue.enqueue(() => responseCtx.respond(\"_Compacting context..._\"), \"compaction start\");\n } else if (event.type === \"compaction_end\") {\n const compEvent = event as any;\n if (compEvent.result) {\n log.logInfo(`Auto-compaction complete: ${compEvent.result.tokensBefore} tokens compacted`);\n } else if (compEvent.aborted) {\n log.logInfo(\"Auto-compaction aborted\");\n }\n } else if (event.type === \"auto_retry_start\") {\n const retryEvent = event as any;\n log.logWarning(\n `Retrying (${retryEvent.attempt}/${retryEvent.maxAttempts})`,\n retryEvent.errorMessage,\n );\n queue.enqueue(\n () =>\n responseCtx.respond(`_Retrying (${retryEvent.attempt}/${retryEvent.maxAttempts})..._`),\n \"retry\",\n );\n }\n });\n\n return {\n async run(\n message: ChatMessage,\n responseCtx: ChatResponseContext,\n platform: PlatformInfo,\n ): Promise<{ stopReason: string; errorMessage?: string }> {\n // Extract conversationId from sessionKey (format: \"conversationId:rootTs\" or just \"conversationId\")\n const sessionConversation = message.sessionKey.split(\":\")[0];\n\n // Ensure conversation directory exists\n await mkdir(conversationDir, { recursive: true });\n\n if (executionResolver) {\n executionResolver.refresh();\n activeExecutor = await executionResolver.resolve({\n platform: platform.name,\n userId: message.userId,\n });\n workspacePath = getWorkspacePath();\n }\n\n // Sync messages from log.jsonl that arrived while we were offline or busy\n // Exclude the current message (it will be added via prompt())\n // Default sync range is 10 days (handled by syncLogToSessionManager)\n // Thread filter ensures only messages from this session's thread are synced\n const threadFilter = message.sessionKey.includes(\":\")\n ? { scope: \"thread\" as const, rootTs, threadTs: message.threadTs }\n : { scope: \"top-level\" as const, rootTs };\n const syncedCount = await syncLogToSessionManager(\n sessionManager,\n conversationDir,\n message.id,\n undefined,\n threadFilter,\n );\n if (syncedCount > 0) {\n log.logInfo(`[${conversationId}] Synced ${syncedCount} messages from log.jsonl`);\n }\n\n // Reload messages from context.jsonl\n // This picks up any messages synced above\n const reloadedSession = sessionManager.buildSessionContext();\n if (reloadedSession.messages.length > 0) {\n agent.state.messages = reloadedSession.messages;\n log.logInfo(\n `[${conversationId}] Reloaded ${reloadedSession.messages.length} messages from context`,\n );\n }\n\n // Update system prompt with fresh memory, channel/user info, and skills\n const memory = await getMemory(conversationDir);\n const skills = loadMamaSkills(conversationDir, workspacePath);\n const systemPrompt = buildSystemPrompt(\n workspacePath,\n conversationId,\n message.conversationKind,\n message.userId,\n memory,\n executor.getSandboxConfig(),\n platform,\n skills,\n );\n session.agent.state.systemPrompt = systemPrompt;\n\n setEventContext({\n platform: platform.name,\n conversationId,\n conversationKind: message.conversationKind,\n userId: message.userId,\n sessionKey: message.sessionKey,\n // For Slack scheduled events, preserve thread targeting only when the\n // request was created inside an existing thread. Top-level reminders\n // should come back as top-level messages.\n threadTs: message.threadTs,\n });\n\n // Set up file upload function\n setUploadFunction(async (filePath: string, title?: string) => {\n const hostPath = translateToHostPath(\n filePath,\n conversationDir,\n workspacePath,\n conversationId,\n );\n await responseCtx.uploadFile(hostPath, title);\n });\n\n // Reset per-run state\n runState.responseCtx = responseCtx;\n runState.logCtx = {\n conversationId: sessionConversation,\n userName: message.userName,\n conversationName: undefined,\n sessionId: sessionUuid,\n };\n runState.pendingTools.clear();\n runState.totalUsage = {\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n };\n runState.llmCallCount = 0;\n runState.stopReason = \"stop\";\n runState.errorMessage = undefined;\n\n // Create queue for this run\n let queueChain = Promise.resolve();\n runState.queue = {\n enqueue(fn: () => Promise<void>, errorContext: string): void {\n queueChain = queueChain.then(async () => {\n try {\n await fn();\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(`API error (${errorContext})`, errMsg);\n try {\n await responseCtx.respondDiagnostic(`Error: ${errMsg}`, { style: \"error\" });\n } catch {\n // Ignore\n }\n }\n });\n },\n };\n\n // Log context info\n log.logInfo(\n `Context sizes - system: ${systemPrompt.length} chars, memory: ${memory.length} chars`,\n );\n log.logInfo(`Channels: ${platform.channels.length}, Users: ${platform.users.length}`);\n\n // Build user message with timestamp and username prefix\n // Format: \"[YYYY-MM-DD HH:MM:SS+HH:MM] [username]: message\" so LLM knows when and who\n const now = new Date();\n const pad = (n: number) => n.toString().padStart(2, \"0\");\n const offset = -now.getTimezoneOffset();\n const offsetSign = offset >= 0 ? \"+\" : \"-\";\n const offsetHours = pad(Math.floor(Math.abs(offset) / 60));\n const offsetMins = pad(Math.abs(offset) % 60);\n const timestamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}${offsetSign}${offsetHours}:${offsetMins}`;\n const threadContext = message.threadTs ? ` [in-thread:${message.threadTs}]` : \"\";\n let userMessage = `[${timestamp}] [${message.userName || \"unknown\"}]${threadContext}: ${message.text}`;\n\n const imageAttachments: ImageContent[] = [];\n const nonImagePaths: string[] = [];\n\n for (const a of message.attachments || []) {\n // a.localPath is the path relative to the workspace.\n const fullPath = `${workspacePath}/${a.localPath}`;\n const mimeType = getImageMimeType(a.localPath);\n\n if (mimeType && existsSync(fullPath)) {\n try {\n imageAttachments.push({\n type: \"image\",\n mimeType,\n data: readFileSync(fullPath).toString(\"base64\"),\n });\n } catch {\n nonImagePaths.push(fullPath);\n }\n } else {\n nonImagePaths.push(fullPath);\n }\n }\n\n if (nonImagePaths.length > 0) {\n userMessage += `\\n\\n<slack_attachments>\\n${nonImagePaths.join(\"\\n\")}\\n</slack_attachments>`;\n }\n\n // Debug: write context to last_prompt.jsonl\n const debugContext = {\n systemPrompt,\n messages: session.messages,\n newUserMessage: userMessage,\n imageAttachmentCount: imageAttachments.length,\n };\n await writeFile(\n join(conversationDir, \"last_prompt.jsonl\"),\n JSON.stringify(debugContext, null, 2),\n );\n addLifecycleBreadcrumb(\"agent.prompt.sent\", {\n provider: model.provider,\n model: agentConfig.model,\n channel_id: sessionConversation,\n session_id: sessionUuid,\n attachment_count: message.attachments?.length ?? 0,\n image_attachment_count: imageAttachments.length,\n });\n\n await session.prompt(\n userMessage,\n imageAttachments.length > 0 ? { images: imageAttachments } : undefined,\n );\n\n // Wait for queued messages\n await queueChain;\n\n // Handle error case - update main message and post error to thread\n if (runState.stopReason === \"error\" && runState.errorMessage) {\n try {\n await responseCtx.replaceResponse(\"_Sorry, something went wrong_\");\n await responseCtx.respondDiagnostic(`Error: ${runState.errorMessage}`, {\n style: \"error\",\n });\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(\"Failed to post error message\", errMsg);\n }\n } else {\n // Final message update\n const messages = session.messages;\n const lastAssistant = messages.filter((m) => m.role === \"assistant\").pop();\n const finalText =\n lastAssistant?.content\n .filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\\n\") || \"\";\n\n // Check for [SILENT] marker - delete message and thread instead of posting\n if (finalText.trim() === \"[SILENT]\" || finalText.trim().startsWith(\"[SILENT]\")) {\n try {\n await responseCtx.deleteResponse();\n log.logInfo(\"Silent response - deleted message and thread\");\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(\"Failed to delete message for silent response\", errMsg);\n }\n } else if (finalText.trim()) {\n try {\n await responseCtx.replaceResponse(finalText);\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log.logWarning(\"Failed to replace message with final text\", errMsg);\n }\n }\n }\n\n // Log usage summary with context info\n if (runState.totalUsage.cost.total > 0) {\n // Get last non-aborted assistant message for context calculation\n const messages = session.messages;\n const lastAssistantMessage = messages\n .slice()\n .reverse()\n .find((m) => m.role === \"assistant\" && (m as any).stopReason !== \"aborted\") as any;\n\n const contextTokens = lastAssistantMessage\n ? lastAssistantMessage.usage.input +\n lastAssistantMessage.usage.output +\n lastAssistantMessage.usage.cacheRead +\n lastAssistantMessage.usage.cacheWrite\n : 0;\n const contextWindow = model.contextWindow || 200000;\n\n // Run-level Sentry metrics\n const { totalUsage } = runState;\n const runMetricAttributes = metricAttributes({\n provider: model.provider,\n model: agentConfig.model,\n channel_id: sessionConversation,\n session_id: sessionUuid,\n stop_reason: runState.stopReason,\n llm_calls: runState.llmCallCount,\n });\n Sentry.metrics.distribution(\"agent.run.tokens_in\", totalUsage.input, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.tokens_out\", totalUsage.output, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.cache_read\", totalUsage.cacheRead, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.cache_write\", totalUsage.cacheWrite, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.distribution(\"agent.run.cost\", totalUsage.cost.total, {\n attributes: runMetricAttributes,\n });\n Sentry.metrics.gauge(\"agent.context.utilization\", contextTokens / contextWindow, {\n unit: \"ratio\",\n attributes: runMetricAttributes,\n });\n\n const summary = log.logUsageSummary(\n runState.logCtx!,\n runState.totalUsage,\n contextTokens,\n contextWindow,\n );\n if (platform.diagnostics?.showUsageSummary === true) {\n runState.queue!.enqueue(\n () => responseCtx.respondDiagnostic(summary, { style: \"muted\" }),\n \"usage summary\",\n );\n await queueChain;\n }\n }\n\n // Clear run state\n runState.responseCtx = null;\n runState.logCtx = null;\n runState.queue = null;\n\n return { stopReason: runState.stopReason, errorMessage: runState.errorMessage };\n },\n\n abort(): void {\n session.abort();\n },\n\n getCurrentStep(): { toolName?: string; label?: string } | undefined {\n const pending = runState.pendingTools;\n if (pending.size === 0) return undefined;\n // Get the first pending tool\n const first = pending.values().next().value;\n if (!first) return undefined;\n return {\n toolName: first.toolName,\n label: (first.args as { label?: string })?.label,\n };\n },\n };\n}\n\n/**\n * Translate container path back to host path for file operations\n */\nfunction translateToHostPath(\n containerPath: string,\n conversationDir: string,\n workspacePath: string,\n conversationId: string,\n): string {\n if (workspacePath === \"/workspace\") {\n const prefix = `/workspace/${conversationId}/`;\n if (containerPath.startsWith(prefix)) {\n return join(conversationDir, containerPath.slice(prefix.length));\n }\n if (containerPath.startsWith(\"/workspace/\")) {\n return join(conversationDir, \"..\", containerPath.slice(\"/workspace/\".length));\n }\n }\n return containerPath;\n}\n"]}
package/dist/agent.js CHANGED
@@ -11,7 +11,7 @@ import { ActorExecutionResolver } from "./execution-resolver.js";
11
11
  import * as log from "./log.js";
12
12
  import { createExecutor } from "./sandbox.js";
13
13
  import { addLifecycleBreadcrumb, metricAttributes } from "./sentry.js";
14
- import { createManagedSessionFileAtPath, extractSessionSuffix, extractSessionUuid, forkThreadSessionFile, getChannelSessionDir, getThreadSessionFile, openManagedSession, resolveChannelSessionFile, resolveManagedSessionFile, tryResolveThreadSession, } from "./session-store.js";
14
+ import { extractSessionSuffix, extractSessionUuid, openManagedSession, } from "./session-store.js";
15
15
  import { createMamaTools } from "./tools/index.js";
16
16
  import * as Sentry from "@sentry/node";
17
17
  const IMAGE_MIME_TYPES = {
@@ -24,6 +24,13 @@ const IMAGE_MIME_TYPES = {
24
24
  function getImageMimeType(filename) {
25
25
  return IMAGE_MIME_TYPES[filename.toLowerCase().split(".").pop() || ""];
26
26
  }
27
+ function buildThreadSessionName(message) {
28
+ const text = message?.text?.trim();
29
+ if (!text)
30
+ return undefined;
31
+ const userLabel = message?.userName || message?.user || "unknown";
32
+ return `[${userLabel}]: ${text}`;
33
+ }
27
34
  async function getMemory(conversationDir) {
28
35
  const parts = [];
29
36
  // Read workspace-level memory (shared across all conversations)
@@ -123,8 +130,11 @@ function buildSystemPrompt(workspacePath, conversationId, conversationKind, curr
123
130
  ## Context
124
131
  - For current date/time, use: date
125
132
  - You have access to previous conversation context including tool results from prior turns.
126
- - For older history beyond your context, search log.jsonl (contains user messages and your final responses, but not tool results).
127
- - User messages include a \`[in-thread:TS]\` marker when sent from within a Slack thread (TS is the root message timestamp). Without this marker, the message is a top-level channel message.
133
+ - For older human-readable history beyond your context, search \`log.jsonl\` (contains user messages and your final responses, but not tool results).
134
+ - Structured session history with tool results lives in \`${conversationPath}/sessions/\`.
135
+ - The active top-level session is selected by \`${conversationPath}/sessions/current\`, which points to a timestamped \`.jsonl\` file in the same directory.
136
+ - Scoped/thread sessions use fixed files at \`${conversationPath}/sessions/<scope_id>.jsonl\` (for example \`${conversationPath}/sessions/1777386320.800769.jsonl\`).
137
+ - User messages include a \`[in-thread:TS]\` marker when sent from within a platform thread/reply (TS is the thread or parent message identifier). Without this marker, the message is a top-level conversation message.
128
138
 
129
139
  ${platform.formattingGuide}
130
140
 
@@ -144,7 +154,11 @@ ${workspacePath}/
144
154
  ├── skills/ # Global CLI tools you create
145
155
  └── ${conversationId}/ # This conversation
146
156
  ├── MEMORY.md # Conversation-specific memory
147
- ├── log.jsonl # Message history (no tool results)
157
+ ├── log.jsonl # Human-readable message history (no tool results)
158
+ ├── sessions/ # Structured session history used for context reconstruction
159
+ │ ├── current # Active top-level session pointer
160
+ │ ├── <timestamp>_<id>.jsonl # Top-level session files
161
+ │ └── <scope_id>.jsonl # Scoped thread/reply session files
148
162
  ├── attachments/ # User-shared files
149
163
  ├── scratch/ # Your working directory
150
164
  └── skills/ # Conversation-specific tools
@@ -204,7 +218,7 @@ You can schedule events that wake you up at specific times or when external thin
204
218
  All \`at\` timestamps must include offset (e.g., \`+01:00\`). Periodic events use IANA timezone names. The harness runs in ${Intl.DateTimeFormat().resolvedOptions().timeZone}. When users mention times without timezone, assume ${Intl.DateTimeFormat().resolvedOptions().timeZone}.
205
219
 
206
220
  ### Platform and Credential Routing
207
- Set \`platform\` to the target bot platform (\`${platform.name}\` for this conversation). When only one platform is running, omitting \`platform\` is allowed for backward compatibility, but include it by default to avoid ambiguity.
221
+ Set \`platform\` to the target bot platform (\`${platform.name}\` for this conversation). Include it explicitly to avoid ambiguity.
208
222
 
209
223
  Set \`userId\` to the platform userId of whoever asked for the event. When the event fires, tool execution routes using that user's vault selection in per-user modes. In \`container:<name>\`, events use the container's single shared vault.
210
224
 
@@ -251,7 +265,7 @@ ${memory}
251
265
 
252
266
  ## System Configuration Log
253
267
  Maintain ${workspacePath}/SYSTEM.md to log all environment modifications:
254
- - Installed packages (apk add, npm install, pip install)
268
+ - Installed packages (apt install, npm install, uv pip install)
255
269
  - Environment variables set
256
270
  - Config files modified (~/.gitconfig, cron jobs, etc.)
257
271
  - Skill dependencies installed
@@ -261,7 +275,8 @@ Update this file whenever you modify the environment. On fresh container, read i
261
275
  ## Log Queries (for older history)
262
276
  Format: \`{"date":"...","ts":"...","user":"...","userName":"...","text":"...","isBot":false}\`
263
277
  The log contains user messages and your final responses (not tool calls/results).
264
- ${isContainer ? "Install jq: apk add jq" : ""}
278
+ Use \`log.jsonl\` for quick grep-style history. Use \`${conversationPath}/sessions/\` when you need structured turns, tool outputs, or branch lineage.
279
+ ${isContainer ? "Install jq: apt-get install jq" : ""}
265
280
  ${isFirecracker ? "Install jq: apt-get install jq" : ""}
266
281
 
267
282
  \`\`\`bash
@@ -273,6 +288,10 @@ grep -i "topic" log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user
273
288
 
274
289
  # Messages from specific user
275
290
  grep '"userName":"mario"' log.jsonl | tail -20 | jq -c '{date: .date[0:19], text}'
291
+
292
+ # Inspect top-level session pointer and available session files
293
+ cat sessions/current
294
+ ls -1 sessions/
276
295
  \`\`\`
277
296
 
278
297
  ## Tools
@@ -290,6 +309,12 @@ function truncate(text, maxLen) {
290
309
  return text;
291
310
  return `${text.substring(0, maxLen - 3)}...`;
292
311
  }
312
+ // Tools whose output is interesting in the structured session log but too noisy
313
+ // to surface as a per-tool diagnostic to the user.
314
+ const QUIET_TOOLS = new Set(["read", "write", "edit"]);
315
+ // Cap raw tool output before handing it to adapters. Bash output can be MB; without
316
+ // this each adapter's splitter would fan it out into many sequential platform posts.
317
+ const TOOL_RESULT_DIAGNOSTIC_CAP = 8000;
293
318
  function extractToolResultText(result) {
294
319
  if (typeof result === "string") {
295
320
  return result;
@@ -311,33 +336,6 @@ function extractToolResultText(result) {
311
336
  }
312
337
  return JSON.stringify(result);
313
338
  }
314
- function formatToolArgsForSlack(_toolName, args) {
315
- const lines = [];
316
- for (const [key, value] of Object.entries(args)) {
317
- if (key === "label")
318
- continue;
319
- if (key === "path" && typeof value === "string") {
320
- const offset = args.offset;
321
- const limit = args.limit;
322
- if (offset !== undefined && limit !== undefined) {
323
- lines.push(`${value}:${offset}-${offset + limit}`);
324
- }
325
- else {
326
- lines.push(value);
327
- }
328
- continue;
329
- }
330
- if (key === "offset" || key === "limit")
331
- continue;
332
- if (typeof value === "string") {
333
- lines.push(value);
334
- }
335
- else {
336
- lines.push(JSON.stringify(value));
337
- }
338
- }
339
- return lines.join("\n");
340
- }
341
339
  // ============================================================================
342
340
  // Agent runner
343
341
  // ============================================================================
@@ -348,7 +346,7 @@ function formatToolArgsForSlack(_toolName, args) {
348
346
  * Runner caching is handled by the caller (channelStates in main.ts).
349
347
  * This is a stateless factory function.
350
348
  */
351
- export async function createRunner(sandboxConfig, sessionKey, conversationId, conversationDir, workspaceDir, vaultManager, bindingStore, provisioner) {
349
+ export async function createRunner(sandboxConfig, sessionKey, conversationId, conversationDir, workspaceDir, sessionScope, vaultManager, bindingStore, provisioner) {
352
350
  const agentConfig = loadAgentConfig(workspaceDir);
353
351
  // Initialize logger with settings from config
354
352
  log.initLogger({
@@ -391,52 +389,24 @@ export async function createRunner(sandboxConfig, sessionKey, conversationId, co
391
389
  const memory = await getMemory(conversationDir);
392
390
  const skills = loadMamaSkills(conversationDir, workspacePath);
393
391
  const emptyPlatform = {
394
- name: "slack",
392
+ name: "chat",
395
393
  formattingGuide: "",
396
394
  channels: [],
397
395
  users: [],
398
396
  };
399
397
  const systemPrompt = buildSystemPrompt(workspacePath, conversationId, "shared", undefined, memory, sandboxConfig, emptyPlatform, skills);
400
- // Create session manager and settings manager
401
- // Conversation sessions use {conversationDir}/sessions/current.
402
- // Thread sessions use fixed files: {conversationDir}/sessions/{threadTs}.jsonl
403
- const sessionDir = getChannelSessionDir(conversationDir);
398
+ // Create session manager and settings manager. Top-level/private sessions
399
+ // use the conversation's current pointer; scoped sessions use fixed files.
400
+ // Platform-specific branch/fork behavior is resolved before runner creation.
404
401
  const isThread = sessionKey.includes(":");
405
- let sessionManager;
406
- let contextFile;
407
- if (isThread) {
408
- const threadFile = getThreadSessionFile(conversationDir, sessionKey);
409
- const existing = tryResolveThreadSession(threadFile);
410
- if (existing) {
411
- contextFile = existing;
412
- sessionManager = openManagedSession(contextFile, sessionDir, conversationDir);
413
- }
414
- else {
415
- const conversationSource = resolveChannelSessionFile(conversationDir);
416
- if (conversationSource) {
417
- try {
418
- contextFile = forkThreadSessionFile(conversationSource, threadFile, conversationDir);
419
- sessionManager = openManagedSession(contextFile, sessionDir, conversationDir);
420
- }
421
- catch {
422
- contextFile = createManagedSessionFileAtPath(threadFile, conversationDir);
423
- sessionManager = openManagedSession(contextFile, sessionDir, conversationDir);
424
- }
425
- }
426
- else {
427
- contextFile = createManagedSessionFileAtPath(threadFile, conversationDir);
428
- sessionManager = openManagedSession(contextFile, sessionDir, conversationDir);
429
- }
430
- }
431
- }
432
- else {
433
- // Direct/shared session: normal resolve
434
- contextFile = resolveManagedSessionFile(sessionDir, conversationDir);
435
- sessionManager = openManagedSession(contextFile, sessionDir, conversationDir);
402
+ const rootTs = extractSessionSuffix(sessionKey);
403
+ const { sessionDir, contextFile, threadRootMessage } = sessionScope;
404
+ const sessionManager = openManagedSession(contextFile, sessionDir, conversationDir);
405
+ const threadSessionName = buildThreadSessionName(threadRootMessage);
406
+ if (isThread && threadSessionName && sessionManager.getSessionName() !== threadSessionName) {
407
+ sessionManager.appendSessionInfo(threadSessionName);
436
408
  }
437
409
  const sessionUuid = extractSessionUuid(contextFile);
438
- // Used for Slack thread filtering — for non-Slack platforms this is effectively a no-op
439
- const rootTs = extractSessionSuffix(sessionKey);
440
410
  const settingsManager = createMamaSettingsManager(join(conversationDir, ".."));
441
411
  // Create AuthStorage and ModelRegistry
442
412
  // Auth stored outside workspace so agent can't access it
@@ -534,8 +504,6 @@ export async function createRunner(sandboxConfig, sessionKey, conversationId, co
534
504
  ...baseAttrs,
535
505
  });
536
506
  log.logToolStart(logCtx, agentEvent.toolName, label, agentEvent.args);
537
- // Tool labels are omitted from the main message to reduce Slack noise.
538
- // Tool execution details are still posted to the thread (see tool_execution_end).
539
507
  }
540
508
  else if (event.type === "tool_execution_end") {
541
509
  const agentEvent = event;
@@ -569,24 +537,16 @@ export async function createRunner(sandboxConfig, sessionKey, conversationId, co
569
537
  else {
570
538
  log.logToolSuccess(logCtx, agentEvent.toolName, durationMs, resultStr);
571
539
  }
572
- // Post args + result to thread
573
- const label = pending?.args ? pending.args.label : undefined;
574
- const argsFormatted = pending
575
- ? formatToolArgsForSlack(agentEvent.toolName, pending.args)
576
- : "(args not found)";
577
- const duration = (durationMs / 1000).toFixed(1);
578
- let threadMessage = `*${agentEvent.isError ? "✗" : "✓"} ${agentEvent.toolName}*`;
579
- if (label)
580
- threadMessage += `: ${label}`;
581
- threadMessage += ` (${duration}s)\n`;
582
- if (argsFormatted)
583
- threadMessage += `\`\`\`\n${argsFormatted}\n\`\`\`\n`;
584
- threadMessage += `*Result:*\n\`\`\`\n${resultStr}\n\`\`\``;
585
- // Only post thread details for tools with meaningful output (bash, attach).
586
- // Skip read/write/edit to reduce Slack noise — their results are in the log.
587
- const quietTools = new Set(["read", "write", "edit"]);
588
- if (!quietTools.has(agentEvent.toolName)) {
589
- queue.enqueueMessage(threadMessage, "thread", "tool result thread", false);
540
+ if (!QUIET_TOOLS.has(agentEvent.toolName)) {
541
+ const toolResult = {
542
+ toolName: agentEvent.toolName,
543
+ label: pending?.args ? pending.args.label : undefined,
544
+ args: pending?.args,
545
+ result: truncate(resultStr, TOOL_RESULT_DIAGNOSTIC_CAP),
546
+ isError: agentEvent.isError,
547
+ durationMs,
548
+ };
549
+ queue.enqueue(() => responseCtx.respondToolResult(toolResult), "tool result diagnostic");
590
550
  }
591
551
  if (agentEvent.isError) {
592
552
  queue.enqueue(() => responseCtx.respond(`_Error: ${truncate(resultStr, 200)}_`), "tool error");
@@ -678,16 +638,12 @@ export async function createRunner(sandboxConfig, sessionKey, conversationId, co
678
638
  const text = textParts.join("\n");
679
639
  for (const thinking of thinkingParts) {
680
640
  log.logThinking(logCtx, thinking);
681
- queue.enqueueMessage(`_${thinking}_`, "main", "thinking main");
682
- queue.enqueueMessage(`_${thinking}_`, "thread", "thinking thread", false);
641
+ queue.enqueue(() => responseCtx.respond(`_${thinking}_`), "thinking main");
642
+ queue.enqueue(() => responseCtx.respondDiagnostic(`_${thinking}_`), "thinking diagnostic");
683
643
  }
684
644
  if (text.trim()) {
685
645
  log.logResponse(logCtx, text);
686
- queue.enqueueMessage(text, "main", "response main");
687
- // Only overflow to thread for texts that will be truncated in main
688
- if (text.length > SLACK_MAX_LENGTH) {
689
- queue.enqueueMessage(text, "thread", "response thread", false);
690
- }
646
+ queue.enqueue(() => responseCtx.respond(text), "response main");
691
647
  }
692
648
  }
693
649
  }
@@ -710,23 +666,6 @@ export async function createRunner(sandboxConfig, sessionKey, conversationId, co
710
666
  queue.enqueue(() => responseCtx.respond(`_Retrying (${retryEvent.attempt}/${retryEvent.maxAttempts})..._`), "retry");
711
667
  }
712
668
  });
713
- // Message limit constant
714
- const SLACK_MAX_LENGTH = 40000;
715
- const splitForSlack = (text) => {
716
- if (text.length <= SLACK_MAX_LENGTH)
717
- return [text];
718
- const parts = [];
719
- let remaining = text;
720
- let partNum = 1;
721
- while (remaining.length > 0) {
722
- const chunk = remaining.substring(0, SLACK_MAX_LENGTH - 50);
723
- remaining = remaining.substring(SLACK_MAX_LENGTH - 50);
724
- const suffix = remaining.length > 0 ? `\n_(continued ${partNum}...)_` : "";
725
- parts.push(chunk + suffix);
726
- partNum++;
727
- }
728
- return parts;
729
- };
730
669
  return {
731
670
  async run(message, responseCtx, platform) {
732
671
  // Extract conversationId from sessionKey (format: "conversationId:rootTs" or just "conversationId")
@@ -769,6 +708,11 @@ export async function createRunner(sandboxConfig, sessionKey, conversationId, co
769
708
  conversationId,
770
709
  conversationKind: message.conversationKind,
771
710
  userId: message.userId,
711
+ sessionKey: message.sessionKey,
712
+ // For Slack scheduled events, preserve thread targeting only when the
713
+ // request was created inside an existing thread. Top-level reminders
714
+ // should come back as top-level messages.
715
+ threadTs: message.threadTs,
772
716
  });
773
717
  // Set up file upload function
774
718
  setUploadFunction(async (filePath, title) => {
@@ -806,11 +750,7 @@ export async function createRunner(sandboxConfig, sessionKey, conversationId, co
806
750
  const errMsg = err instanceof Error ? err.message : String(err);
807
751
  log.logWarning(`API error (${errorContext})`, errMsg);
808
752
  try {
809
- // Split long error messages to avoid msg_too_long
810
- const errParts = splitForSlack(`_Error: ${errMsg}_`);
811
- for (const part of errParts) {
812
- await responseCtx.respondInThread(part);
813
- }
753
+ await responseCtx.respondDiagnostic(`Error: ${errMsg}`, { style: "error" });
814
754
  }
815
755
  catch {
816
756
  // Ignore
@@ -818,12 +758,6 @@ export async function createRunner(sandboxConfig, sessionKey, conversationId, co
818
758
  }
819
759
  });
820
760
  },
821
- enqueueMessage(text, target, errorContext, _doLog = true) {
822
- const parts = splitForSlack(text);
823
- for (const part of parts) {
824
- this.enqueue(() => target === "main" ? responseCtx.respond(part) : responseCtx.respondInThread(part), errorContext);
825
- }
826
- },
827
761
  };
828
762
  // Log context info
829
763
  log.logInfo(`Context sizes - system: ${systemPrompt.length} chars, memory: ${memory.length} chars`);
@@ -887,11 +821,9 @@ export async function createRunner(sandboxConfig, sessionKey, conversationId, co
887
821
  if (runState.stopReason === "error" && runState.errorMessage) {
888
822
  try {
889
823
  await responseCtx.replaceResponse("_Sorry, something went wrong_");
890
- // Split long error messages to avoid msg_too_long
891
- const errorParts = splitForSlack(`_Error: ${runState.errorMessage}_`);
892
- for (const part of errorParts) {
893
- await responseCtx.respondInThread(part);
894
- }
824
+ await responseCtx.respondDiagnostic(`Error: ${runState.errorMessage}`, {
825
+ style: "error",
826
+ });
895
827
  }
896
828
  catch (err) {
897
829
  const errMsg = err instanceof Error ? err.message : String(err);
@@ -919,10 +851,7 @@ export async function createRunner(sandboxConfig, sessionKey, conversationId, co
919
851
  }
920
852
  else if (finalText.trim()) {
921
853
  try {
922
- const mainText = finalText.length > SLACK_MAX_LENGTH
923
- ? `${finalText.substring(0, SLACK_MAX_LENGTH - 50)}\n\n_(see thread for full response)_`
924
- : finalText;
925
- await responseCtx.replaceResponse(mainText);
854
+ await responseCtx.replaceResponse(finalText);
926
855
  }
927
856
  catch (err) {
928
857
  const errMsg = err instanceof Error ? err.message : String(err);
@@ -975,12 +904,10 @@ export async function createRunner(sandboxConfig, sessionKey, conversationId, co
975
904
  attributes: runMetricAttributes,
976
905
  });
977
906
  const summary = log.logUsageSummary(runState.logCtx, runState.totalUsage, contextTokens, contextWindow);
978
- // Split long summaries to avoid msg_too_long
979
- const summaryParts = splitForSlack(summary);
980
- for (const part of summaryParts) {
981
- runState.queue.enqueue(() => responseCtx.respondInThread(part, { style: "muted" }), "usage summary");
907
+ if (platform.diagnostics?.showUsageSummary === true) {
908
+ runState.queue.enqueue(() => responseCtx.respondDiagnostic(summary, { style: "muted" }), "usage summary");
909
+ await queueChain;
982
910
  }
983
- await queueChain;
984
911
  }
985
912
  // Clear run state
986
913
  runState.responseCtx = null;