@geminixiang/mama 0.2.0-beta.12 → 0.2.0-beta.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/adapter.d.ts.map +1 -1
- package/dist/adapter.js.map +1 -1
- package/dist/adapters/shared.d.ts.map +1 -1
- package/dist/adapters/shared.js +0 -6
- package/dist/adapters/shared.js.map +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +1 -4
- package/dist/agent.js.map +1 -1
- package/dist/commands/index.d.ts +3 -3
- package/dist/commands/index.d.ts.map +1 -1
- package/dist/commands/index.js +4 -5
- package/dist/commands/index.js.map +1 -1
- package/dist/commands/login.d.ts.map +1 -1
- package/dist/commands/login.js +16 -1
- package/dist/commands/login.js.map +1 -1
- package/dist/commands/registry.d.ts +2 -5
- package/dist/commands/registry.d.ts.map +1 -1
- package/dist/commands/registry.js +6 -11
- package/dist/commands/registry.js.map +1 -1
- package/dist/commands/types.d.ts +1 -1
- package/dist/commands/types.d.ts.map +1 -1
- package/dist/commands/types.js.map +1 -1
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +0 -3
- package/dist/events.js.map +1 -1
- package/dist/execution-resolver.d.ts +1 -1
- package/dist/execution-resolver.d.ts.map +1 -1
- package/dist/execution-resolver.js +1 -1
- package/dist/execution-resolver.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/login/index.d.ts +1 -0
- package/dist/login/index.d.ts.map +1 -1
- package/dist/login/index.js +40 -1
- package/dist/login/index.js.map +1 -1
- package/dist/login/portal.d.ts.map +1 -1
- package/dist/login/portal.js +3 -0
- package/dist/login/portal.js.map +1 -1
- package/dist/login/session.d.ts +4 -11
- package/dist/login/session.d.ts.map +1 -1
- package/dist/login/session.js +9 -21
- package/dist/login/session.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -9
- package/dist/main.js.map +1 -1
- package/dist/runtime/conversation-orchestrator.d.ts +2 -3
- package/dist/runtime/conversation-orchestrator.d.ts.map +1 -1
- package/dist/runtime/conversation-orchestrator.js +2 -1
- package/dist/runtime/conversation-orchestrator.js.map +1 -1
- package/dist/runtime/session-runtime.d.ts +5 -5
- package/dist/runtime/session-runtime.d.ts.map +1 -1
- package/dist/runtime/session-runtime.js +15 -9
- package/dist/runtime/session-runtime.js.map +1 -1
- package/dist/session-view/store.d.ts.map +1 -1
- package/dist/session-view/store.js +1 -4
- package/dist/session-view/store.js.map +1 -1
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.d.ts.map +1 -1
- package/dist/tools/bash.js.map +1 -1
- package/dist/tools/edit.d.ts +1 -1
- package/dist/tools/edit.d.ts.map +1 -1
- package/dist/tools/edit.js.map +1 -1
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/read.d.ts +1 -1
- package/dist/tools/read.d.ts.map +1 -1
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/write.d.ts +1 -1
- package/dist/tools/write.d.ts.map +1 -1
- package/dist/tools/write.js.map +1 -1
- package/dist/vault-routing.d.ts +1 -1
- package/dist/vault-routing.d.ts.map +1 -1
- package/dist/vault-routing.js.map +1 -1
- package/dist/vault.d.ts +1 -1
- package/dist/vault.d.ts.map +1 -1
- package/dist/vault.js +3 -0
- package/dist/vault.js.map +1 -1
- package/package.json +1 -1
- package/dist/sandbox.d.ts +0 -2
- package/dist/sandbox.d.ts.map +0 -1
- package/dist/sandbox.js +0 -2
- package/dist/sandbox.js.map +0 -1
package/dist/agent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAsB,MAAM,+BAA+B,C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D,WAAW;gBACX,YAAY,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE;aAC7C,CAAC,CAAC;YAEH,kBAAkB;YAClB,QAAQ,CAAC,WAAW,GAAG,IAAI,CAAC;YAC5B,QAAQ,CAAC,MAAM,GAAG,IAAI,CAAC;YACvB,QAAQ,CAAC,KAAK,GAAG,IAAI,CAAC;YAEtB,OAAO,EAAE,UAAU,EAAE,QAAQ,CAAC,UAAU,EAAE,YAAY,EAAE,QAAQ,CAAC,YAAY,EAAE,CAAC;QAClF,CAAC;QAED,KAAK;YACH,OAAO,CAAC,KAAK,EAAE,CAAC;QAClB,CAAC;QAED,cAAc;YACZ,MAAM,OAAO,GAAG,QAAQ,CAAC,YAAY,CAAC;YACtC,IAAI,OAAO,CAAC,IAAI,KAAK,CAAC;gBAAE,OAAO,SAAS,CAAC;YACzC,6BAA6B;YAC7B,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;YAC5C,IAAI,CAAC,KAAK;gBAAE,OAAO,SAAS,CAAC;YAC7B,OAAO;gBACL,QAAQ,EAAE,KAAK,CAAC,QAAQ;gBACxB,KAAK,EAAG,KAAK,CAAC,IAA2B,EAAE,KAAK;aACjD,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,0BAA0B,CACxC,WAAmB,EACnB,WAA+B;IAE/B,OAAO,WAAW,CAAC,iBAAiB,EAAE,CAAC,WAAW,CAAC,IAAI,WAAW,CAAC;AACrE,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC5C,aAA4B,EAC5B,iBAAyB;IAEzB,OAAO,+BAA+B,CAAC,aAAa,EAAE,iBAAiB,CAAC,CAAC;AAC3E,CAAC","sourcesContent":["import { Agent, type ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { getModel, type ImageContent } from \"@earendil-works/pi-ai\";\nimport {\n AgentSession,\n AuthStorage,\n convertToLlm,\n DefaultResourceLoader,\n formatSkillsForPrompt,\n getAgentDir,\n loadSkillsFromDir,\n ModelRegistry,\n SessionManager,\n SettingsManager,\n type Skill,\n} from \"@earendil-works/pi-coding-agent\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { mkdir, readFile, writeFile } from \"fs/promises\";\nimport { homedir } from \"os\";\nimport { join, posix } from \"path\";\nimport type {\n ChatMessage,\n ChatResponseContext,\n ChatToolResult,\n ConversationKind,\n PlatformInfo,\n} from \"./adapter.js\";\nimport { loadAgentConfigForConversation } from \"./config.js\";\nimport { ActorExecutionResolver } from \"./execution-resolver.js\";\nimport * as log from \"./log.js\";\nimport type { DockerContainerManager } from \"./provisioner.js\";\nimport {\n createExecutor,\n type Executor,\n type RuntimePathContext,\n type SandboxConfig,\n} from \"./sandbox.js\";\nimport { createMountedRuntimePathContext } from \"./sandbox/path-context.js\";\nimport { addLifecycleBreadcrumb, metricAttributes } from \"./sentry.js\";\nimport type { VaultManager } from \"./vault.js\";\nimport {\n extractSessionUuid,\n openManagedSession,\n type ResolvedSessionScope,\n type ThreadRootMessage,\n} from \"./session-store.js\";\nimport { shouldSurfaceToolDiagnostic } from \"./tool-diagnostics.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 buildRuntimePaths(runtimeWorkspaceRoot: string, conversationId: string) {\n const workspaceRoot = runtimeWorkspaceRoot.replace(/\\/+$/, \"\") || \"/\";\n const conversationPath = posix.join(workspaceRoot, conversationId);\n return {\n workspaceRoot,\n conversationPath,\n scratchPath: posix.join(conversationPath, \"scratch\"),\n };\n}\n\nfunction buildEnvDescription(sandboxType: SandboxConfig[\"type\"], workspaceRoot: string): string {\n switch (sandboxType) {\n case \"image\":\n return `You are running inside a managed per-user container.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${workspaceRoot}\n- Install tools with the image's package manager\n- Your changes persist for this user's container until it is recreated`;\n case \"container\":\n return `You are running inside a shared container.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${workspaceRoot}\n- Install tools with the container's package manager\n- Your changes persist across sessions`;\n case \"firecracker\":\n return `You are running inside a Firecracker microVM.\n- Runtime workspace root: ${workspaceRoot}\n- Use cd or absolute paths; project files are under ${workspaceRoot}\n- Install tools with: apt-get install <package> (Debian-based)\n- Your changes persist across sessions`;\n case \"cloudflare\":\n return `You are running through a Cloudflare Sandbox bridge.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${workspaceRoot}\n- Your commands run in a remote container managed by Cloudflare\n- Important: the remote filesystem is not automatically synced back to the host workspace`;\n default:\n return `You are running directly on the host machine.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${process.cwd()}\n- Be careful with system modifications`;\n }\n}\n\nexport function buildEventFilesystemInstructions(\n sandboxType: SandboxConfig[\"type\"],\n workspaceRoot: string,\n): string {\n if (sandboxType === \"host\" || sandboxType === \"container\" || sandboxType === \"image\") {\n return `Events live in the host-side mama control plane and are mounted at \\`${workspaceRoot}/events/\\` in this runtime.\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 Manually\nOnly do this when you need to create events from a script. Use unique filenames to avoid overwriting existing events. Include a timestamp or random suffix:\n\\`\\`\\`bash\ncat > ${workspaceRoot}/events/dentist-reminder-$(date +%s).json << 'EOF'\n{\"type\": \"one-shot\", \"platform\": \"<platform>\", \"conversationId\": \"<conversationId>\", \"conversationKind\": \"<direct|shared>\", \"userId\": \"<requester userId>\", \"text\": \"Dentist tomorrow\", \"at\": \"2025-12-14T09:00:00+01:00\"}\nEOF\n\\`\\`\\`\n\n### Managing Events\n- List: \\`ls ${workspaceRoot}/events/\\`\n- View: \\`cat ${workspaceRoot}/events/foo.json\\`\n- Delete/cancel: \\`rm ${workspaceRoot}/events/foo.json\\``;\n }\n\n return `Events live in the host-side mama control plane, not necessarily in this runtime filesystem.\n\nUse the \\`event\\` tool to create events. It writes to the correct host-side events directory and fills \\`platform\\`, \\`conversationId\\`, \\`conversationKind\\`, and \\`userId\\` for the current conversation automatically.\n\nDo not create event files with bash in \\`${workspaceRoot}/events/\\` from this sandbox unless you have explicitly verified that path is mounted back to the host-side mama events directory.`;\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 isSyntheticEvent = false,\n): string {\n const { workspaceRoot, conversationPath, scratchPath } = buildRuntimePaths(\n workspacePath,\n conversationId,\n );\n const sandboxType = sandboxConfig.type;\n const isContainerLike = sandboxType === \"container\" || sandboxType === \"image\";\n const isFirecracker = sandboxType === \"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 = buildEnvDescription(sandboxType, workspaceRoot);\n const eventFilesystemInstructions = buildEventFilesystemInstructions(sandboxType, workspaceRoot);\n const syntheticEventInstructions = isSyntheticEvent\n ? `\n## Synthetic Event Mode\n- You are handling a scheduled/background event, not opening a brand new chat with a stranger.\n- Treat the incoming user message as a self-contained task prepared by an earlier run.\n- Complete the task directly. Avoid generic greetings, self-introductions, or boilerplate offers to help.\n- For reminders/follow-ups, prefer a short direct response that sounds like a continuation of prior intent.\n- If the event text includes tone, brevity, or language instructions, follow them literally.\n`\n : \"\";\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${syntheticEventInstructions}\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- Default place for clones, downloads, and experiments: ${scratchPath}\n- Do not use host-only paths unless you are running in host mode and verified they exist.\n\n## Workspace Layout\n${workspaceRoot}/\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/ # Working directory for clones/downloads/experiments: ${scratchPath}\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 \\`${workspaceRoot}/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.\n${eventFilesystemInstructions}\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\nWhen scheduling an event, write \\`text\\` as a self-contained task for your future self. Include the minimum necessary context, tone, and constraints in the text itself because events do not inherit normal conversation history. Good: \\`Please remind the user that break time is over and it is time to return to class. Keep it brief, in Traditional Chinese, and do not ask follow-up questions.\\` Bad: \\`back to class\\`.\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 (${workspaceRoot}/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 ${workspaceRoot}/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${isContainerLike || 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\nexport function getUnresolvedSandboxPathContext(\n sandboxConfig: SandboxConfig,\n hostWorkspaceRoot: string,\n): RuntimePathContext {\n if (sandboxConfig.type === \"image\") {\n return createMountedRuntimePathContext(hostWorkspaceRoot, \"/workspace\");\n }\n\n return createExecutor(sandboxConfig).getPathContext(hostWorkspaceRoot);\n}\n\ninterface RunnerExecutionContext {\n executionResolver?: ActorExecutionResolver;\n executor: Executor;\n getPathContext: () => RuntimePathContext;\n resolveExecutorForRun(context: {\n platform: string;\n userId: string;\n conversationId: string;\n }): Promise<void>;\n}\n\ninterface RunnerSessionState {\n responseCtx: ChatResponseContext | null;\n logCtx: {\n conversationId: string;\n userName?: string;\n conversationName?: string;\n sessionId?: string;\n } | null;\n queue: {\n enqueue(fn: () => Promise<void>, errorContext: string): void;\n } | null;\n pendingTools: Map<string, { toolName: string; args: unknown; startTime: number }>;\n totalUsage: {\n input: number;\n output: number;\n cacheRead: number;\n cacheWrite: number;\n cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };\n };\n llmCallCount: number;\n stopReason: string;\n errorMessage: string | undefined;\n}\n\ninterface PreparedRunContext {\n sessionConversation: string;\n runQueue: ReturnType<typeof createRunQueue>;\n userMessage: string;\n imageAttachments: ImageContent[];\n}\n\ninterface ConfiguredAgentSession {\n agent: Agent;\n session: AgentSession;\n}\n\nfunction createRunnerExecutionContext(\n sandboxConfig: SandboxConfig,\n vaultManager: VaultManager | undefined,\n provisioner: DockerContainerManager | undefined,\n workspaceDir: string,\n hostWorkspacePath: string,\n): RunnerExecutionContext {\n const executionResolver =\n vaultManager &&\n sandboxConfig.type !== \"host\" &&\n (vaultManager.isEnabled() ||\n sandboxConfig.type === \"container\" ||\n sandboxConfig.type === \"image\" ||\n sandboxConfig.type === \"cloudflare\" ||\n sandboxConfig.type === \"firecracker\")\n ? new ActorExecutionResolver(sandboxConfig, vaultManager, provisioner, workspaceDir)\n : undefined;\n\n // activeExecutor is replaced at the start of each run() call when executionResolver\n // is present, so the stable `executor` wrapper always delegates to the latest resolved value.\n let activeExecutor: Executor =\n executionResolver !== undefined\n ? createExecutor({ type: \"host\" })\n : createExecutor(sandboxConfig);\n const executor: Executor = {\n exec(command, options) {\n return activeExecutor.exec(command, options);\n },\n getWorkspacePath(hostPath) {\n return activeExecutor.getWorkspacePath(hostPath);\n },\n getSandboxConfig() {\n return activeExecutor.getSandboxConfig();\n },\n getPathContext(hostWorkspaceRoot) {\n return activeExecutor.getPathContext(hostWorkspaceRoot);\n },\n };\n\n return {\n executionResolver,\n executor,\n getPathContext: () => executor.getPathContext(hostWorkspacePath),\n async resolveExecutorForRun(context): Promise<void> {\n if (!executionResolver) return;\n activeExecutor = await executionResolver.resolve(context);\n },\n };\n}\n\nasync function createConfiguredAgentSession(params: {\n conversationId: string;\n workspaceDir: string;\n runtimeWorkspaceRoot: string;\n systemPrompt: string;\n model: ReturnType<typeof getModel>;\n thinkingLevel: ThinkingLevel;\n tools: Awaited<ReturnType<typeof createMamaTools>>[\"tools\"];\n sessionManager: SessionManager;\n settingsManager: SettingsManager;\n}): Promise<ConfiguredAgentSession> {\n const {\n conversationId,\n workspaceDir,\n runtimeWorkspaceRoot,\n systemPrompt,\n model,\n thinkingLevel,\n tools,\n sessionManager,\n settingsManager,\n } = params;\n\n const authStorage = AuthStorage.create(join(homedir(), \".pi\", \"mama\", \"auth.json\"));\n const modelRegistry = ModelRegistry.create(authStorage);\n const agent = new Agent({\n initialState: {\n systemPrompt,\n model,\n thinkingLevel,\n tools,\n },\n convertToLlm,\n getApiKey: async () => {\n const key = await modelRegistry.getApiKeyForProvider(model.provider);\n if (!key) {\n throw new Error(\n `No API key for provider \"${model.provider}\". Set the appropriate environment variable or configure via auth.json`,\n );\n }\n return key;\n },\n });\n\n const loadedSession = sessionManager.buildSessionContext();\n if (loadedSession.messages.length > 0) {\n agent.state.messages = loadedSession.messages;\n log.logInfo(\n `[${conversationId}] Reloaded ${loadedSession.messages.length} messages from session context`,\n );\n }\n\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((extension) => extension.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 const session = new AgentSession({\n agent,\n sessionManager,\n settingsManager,\n cwd: runtimeWorkspaceRoot,\n modelRegistry,\n resourceLoader,\n baseToolsOverride,\n });\n return { agent, session };\n}\n\nfunction createEmptyUsageTotals() {\n return {\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}\n\nfunction createRunState(): RunnerSessionState {\n return {\n responseCtx: null,\n logCtx: null,\n queue: null,\n pendingTools: new Map<string, { toolName: string; args: unknown; startTime: number }>(),\n totalUsage: createEmptyUsageTotals(),\n llmCallCount: 0,\n stopReason: \"stop\",\n errorMessage: undefined,\n };\n}\n\nfunction resetRunState(\n runState: RunnerSessionState,\n responseCtx: ChatResponseContext,\n sessionConversation: string,\n userName: string | undefined,\n sessionUuid: string,\n): void {\n runState.responseCtx = responseCtx;\n runState.logCtx = {\n conversationId: sessionConversation,\n userName,\n conversationName: undefined,\n sessionId: sessionUuid,\n };\n runState.pendingTools.clear();\n runState.totalUsage = createEmptyUsageTotals();\n runState.llmCallCount = 0;\n runState.stopReason = \"stop\";\n runState.errorMessage = undefined;\n}\n\nfunction createRunQueue(responseCtx: ChatResponseContext): {\n queue: { enqueue(fn: () => Promise<void>, errorContext: string): void };\n wait: () => Promise<void>;\n} {\n let queueChain = Promise.resolve();\n return {\n 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 wait: () => queueChain,\n };\n}\n\nfunction padTwoDigits(n: number): string {\n return n.toString().padStart(2, \"0\");\n}\n\nfunction formatTimestampedUserMessage(message: ChatMessage): string {\n const now = new Date();\n const offset = -now.getTimezoneOffset();\n const offsetSign = offset >= 0 ? \"+\" : \"-\";\n const offsetHours = padTwoDigits(Math.floor(Math.abs(offset) / 60));\n const offsetMins = padTwoDigits(Math.abs(offset) % 60);\n const timestamp =\n `${now.getFullYear()}-${padTwoDigits(now.getMonth() + 1)}-${padTwoDigits(now.getDate())} ` +\n `${padTwoDigits(now.getHours())}:${padTwoDigits(now.getMinutes())}:${padTwoDigits(now.getSeconds())}` +\n `${offsetSign}${offsetHours}:${offsetMins}`;\n const threadContext = message.threadTs ? ` [in-thread:${message.threadTs}]` : \"\";\n return `[${timestamp}] [${message.userName || \"unknown\"}]${threadContext}: ${message.text}`;\n}\n\nfunction collectMessageAttachments(\n message: ChatMessage,\n workspacePath: string,\n): { imageAttachments: ImageContent[]; nonImagePaths: string[] } {\n const imageAttachments: ImageContent[] = [];\n const nonImagePaths: string[] = [];\n\n for (const attachment of message.attachments || []) {\n const fullPath = `${workspacePath}/${attachment.localPath}`;\n const mimeType = getImageMimeType(attachment.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 return { imageAttachments, nonImagePaths };\n}\n\nfunction buildPromptPayload(\n message: ChatMessage,\n workspacePath: string,\n): {\n userMessage: string;\n imageAttachments: ImageContent[];\n} {\n let userMessage = formatTimestampedUserMessage(message);\n const { imageAttachments, nonImagePaths } = collectMessageAttachments(message, workspacePath);\n\n if (nonImagePaths.length > 0) {\n userMessage += `\\n\\n<slack_attachments>\\n${nonImagePaths.join(\"\\n\")}\\n</slack_attachments>`;\n }\n\n return { userMessage, imageAttachments };\n}\n\nasync function writePromptDebugContext(\n conversationDir: string,\n systemPrompt: string,\n session: AgentSession,\n userMessage: string,\n imageAttachmentCount: number,\n): Promise<void> {\n const debugContext = {\n systemPrompt,\n messages: session.messages,\n newUserMessage: userMessage,\n imageAttachmentCount,\n };\n await writeFile(\n join(conversationDir, \"last_prompt.jsonl\"),\n JSON.stringify(debugContext, null, 2),\n );\n}\n\nfunction getFinalAssistantText(session: AgentSession): string {\n const lastAssistant = session.messages.filter((message) => message.role === \"assistant\").pop();\n return (\n lastAssistant?.content\n .filter((content): content is { type: \"text\"; text: string } => content.type === \"text\")\n .map((content) => content.text)\n .join(\"\\n\") || \"\"\n );\n}\n\nasync function finalizeRunResponse(\n responseCtx: ChatResponseContext,\n session: AgentSession,\n runState: RunnerSessionState,\n): Promise<void> {\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 return;\n }\n\n const finalText = getFinalAssistantText(session);\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 return;\n }\n\n if (!finalText.trim()) return;\n\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\ninterface UsageReportContext {\n session: AgentSession;\n runState: RunnerSessionState;\n responseCtx: ChatResponseContext;\n platform: PlatformInfo;\n model: ReturnType<typeof getModel>;\n agentConfig: ReturnType<typeof loadAgentConfigForConversation>;\n sessionConversation: string;\n sessionUuid: string;\n waitForQueue: () => Promise<void>;\n}\n\nasync function reportUsageSummary(ctx: UsageReportContext): Promise<void> {\n const {\n session,\n runState,\n responseCtx,\n platform,\n model,\n agentConfig,\n sessionConversation,\n sessionUuid,\n waitForQueue,\n } = ctx;\n if (runState.totalUsage.cost.total <= 0) return;\n\n const lastAssistantMessage = session.messages\n .slice()\n .toReversed()\n .find(\n (message): message is Extract<typeof message, { role: \"assistant\" }> =>\n message.role === \"assistant\" && message.stopReason !== \"aborted\",\n );\n\n const contextTokens = lastAssistantMessage\n ? lastAssistantMessage.usage.input +\n lastAssistantMessage.usage.output +\n lastAssistantMessage.usage.cacheRead +\n lastAssistantMessage.usage.cacheWrite\n : 0;\n const contextWindow = model.contextWindow || 200000;\n\n const { 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 waitForQueue();\n }\n}\n\nfunction reloadSessionMessages(\n sessionManager: SessionManager,\n conversationId: string,\n agent: Agent,\n): void {\n const messages = sessionManager.buildSessionContext().messages;\n if (messages.length > 0) {\n agent.state.messages = messages;\n log.logInfo(`[${conversationId}] Reloaded ${messages.length} messages from context`);\n }\n}\n\nasync function prepareRunContext(params: {\n message: ChatMessage;\n responseCtx: ChatResponseContext;\n platform: PlatformInfo;\n conversationId: string;\n conversationDir: string;\n sessionUuid: string;\n runState: RunnerSessionState;\n executor: Executor;\n executionResolver?: ActorExecutionResolver;\n resolveExecutorForRun: RunnerExecutionContext[\"resolveExecutorForRun\"];\n getPathContext: () => RuntimePathContext;\n sessionManager: SessionManager;\n session: AgentSession;\n agent: Agent;\n setEventContext: (context: {\n platform: string;\n conversationId: string;\n conversationKind: ConversationKind;\n userId: string;\n }) => void;\n setUploadFunction: (fn: (filePath: string, title?: string) => Promise<void>) => void;\n pathContext: RuntimePathContext;\n}): Promise<PreparedRunContext & { pathContext: RuntimePathContext }> {\n const {\n message,\n responseCtx,\n platform,\n conversationId,\n conversationDir,\n sessionUuid,\n runState,\n executor,\n executionResolver,\n resolveExecutorForRun,\n getPathContext,\n sessionManager,\n session,\n agent,\n setEventContext,\n setUploadFunction,\n } = params;\n let pathContext = params.pathContext;\n const sessionConversation = message.sessionKey.split(\":\")[0];\n\n await mkdir(join(conversationDir, \"scratch\"), { recursive: true });\n\n if (executionResolver) {\n await resolveExecutorForRun({\n platform: platform.name,\n userId: message.userId,\n conversationId,\n });\n pathContext = getPathContext();\n }\n\n reloadSessionMessages(sessionManager, conversationId, agent);\n\n const memory = await getMemory(conversationDir);\n const skills = loadMamaSkills(conversationDir, pathContext.runtimeWorkspaceRoot);\n const systemPrompt = buildSystemPrompt(\n pathContext.runtimeWorkspaceRoot,\n conversationId,\n message.conversationKind,\n message.userId,\n memory,\n executor.getSandboxConfig(),\n platform,\n skills,\n message.id.startsWith(\"event:\"),\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 setUploadFunction(async (filePath: string, title?: string) => {\n const hostPath = translateRuntimePathToHost(filePath, pathContext);\n await responseCtx.uploadFile(hostPath, title);\n });\n\n resetRunState(runState, responseCtx, sessionConversation, message.userName, sessionUuid);\n const runQueue = createRunQueue(responseCtx);\n runState.queue = runQueue.queue;\n\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 const { userMessage, imageAttachments } = buildPromptPayload(\n message,\n pathContext.runtimeWorkspaceRoot,\n );\n await writePromptDebugContext(\n conversationDir,\n systemPrompt,\n session,\n userMessage,\n imageAttachments.length,\n );\n\n return {\n sessionConversation,\n runQueue,\n userMessage,\n imageAttachments,\n pathContext,\n };\n}\n\nfunction attachSessionEventHandlers(params: {\n session: AgentSession;\n runState: RunnerSessionState;\n model: ReturnType<typeof getModel>;\n agentConfig: ReturnType<typeof loadAgentConfigForConversation>;\n}): void {\n const { session, runState, model, agentConfig } = params;\n session.subscribe(async (event) => {\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 args = (event.args ?? {}) as { label?: string };\n const label = args.label || event.toolName;\n\n pendingTools.set(event.toolCallId, {\n toolName: event.toolName,\n args: event.args,\n startTime: Date.now(),\n });\n addLifecycleBreadcrumb(\"agent.tool.started\", {\n tool: event.toolName,\n ...baseAttrs,\n });\n\n log.logToolStart(logCtx, event.toolName, label, event.args as Record<string, unknown>);\n return;\n }\n\n if (event.type === \"tool_execution_end\") {\n const resultStr = extractToolResultText(event.result);\n const pending = pendingTools.get(event.toolCallId);\n pendingTools.delete(event.toolCallId);\n const durationMs = pending ? Date.now() - pending.startTime : 0;\n\n Sentry.metrics.count(\"agent.tool.calls\", 1, {\n attributes: metricAttributes({\n tool: event.toolName,\n error: String(event.isError),\n ...baseAttrs,\n }),\n });\n Sentry.metrics.distribution(\"agent.tool.duration\", durationMs, {\n unit: \"millisecond\",\n attributes: metricAttributes({\n tool: event.toolName,\n ...baseAttrs,\n }),\n });\n addLifecycleBreadcrumb(\"agent.tool.completed\", {\n tool: event.toolName,\n error: event.isError,\n duration_ms: durationMs,\n ...baseAttrs,\n });\n\n if (event.isError) {\n log.logToolError(logCtx, event.toolName, durationMs, resultStr);\n } else {\n log.logToolSuccess(logCtx, event.toolName, durationMs, resultStr);\n }\n\n if (shouldSurfaceToolDiagnostic(event.toolName)) {\n const toolResult: ChatToolResult = {\n toolName: event.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: event.isError,\n durationMs,\n };\n queue.enqueue(() => responseCtx.respondToolResult(toolResult), \"tool result diagnostic\");\n }\n\n if (event.isError) {\n queue.enqueue(\n () => responseCtx.respond(`_Error: ${truncate(resultStr, 200)}_`),\n \"tool error\",\n );\n }\n return;\n }\n\n if (event.type === \"message_start\") {\n if (event.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 return;\n }\n\n if (event.type === \"message_end\") {\n if (event.message.role === \"assistant\") {\n const assistantMsg = event.message;\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 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 thinkingParts: string[] = [];\n const textParts: string[] = [];\n for (const part of assistantMsg.content) {\n if (part.type === \"thinking\") {\n thinkingParts.push(part.thinking);\n } else if (part.type === \"text\") {\n textParts.push(part.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 return;\n }\n\n if (event.type === \"compaction_start\") {\n log.logInfo(`Auto-compaction started (reason: ${event.reason})`);\n queue.enqueue(() => responseCtx.respond(\"_Compacting context..._\"), \"compaction start\");\n return;\n }\n\n if (event.type === \"compaction_end\") {\n if (event.result) {\n log.logInfo(`Auto-compaction complete: ${event.result.tokensBefore} tokens compacted`);\n } else if (event.aborted) {\n log.logInfo(\"Auto-compaction aborted\");\n }\n return;\n }\n\n if (event.type === \"auto_retry_start\") {\n log.logWarning(`Retrying (${event.attempt}/${event.maxAttempts})`, event.errorMessage);\n queue.enqueue(\n () => responseCtx.respond(`_Retrying (${event.attempt}/${event.maxAttempts})..._`),\n \"retry\",\n );\n }\n });\n}\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 provisioner?: DockerContainerManager,\n): Promise<AgentRunner> {\n const agentConfig = loadAgentConfigForConversation(conversationDir);\n\n // Initialize logger with settings from config\n log.initLogger({\n logFormat: agentConfig.logFormat,\n logLevel: agentConfig.logLevel,\n });\n\n const workspaceBase = join(conversationDir, \"..\");\n const { executionResolver, executor, getPathContext, resolveExecutorForRun } =\n createRunnerExecutionContext(\n sandboxConfig,\n vaultManager,\n provisioner,\n workspaceDir,\n workspaceBase,\n );\n let pathContext = getUnresolvedSandboxPathContext(sandboxConfig, workspaceBase);\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, pathContext.runtimeWorkspaceRoot);\n const emptyPlatform: PlatformInfo = {\n name: \"chat\",\n formattingGuide: \"\",\n channels: [],\n users: [],\n };\n const systemPrompt = buildSystemPrompt(\n pathContext.runtimeWorkspaceRoot,\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 { sessionDir, contextFile, threadRootMessage } = sessionScope;\n const sessionManager = openManagedSession(\n contextFile,\n sessionDir,\n pathContext.runtimeWorkspaceRoot,\n );\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 = SettingsManager.inMemory();\n const { agent, session } = await createConfiguredAgentSession({\n conversationId,\n workspaceDir,\n runtimeWorkspaceRoot: pathContext.runtimeWorkspaceRoot,\n systemPrompt,\n model,\n thinkingLevel: agentConfig.thinkingLevel,\n tools,\n sessionManager,\n settingsManager,\n });\n\n // Mutable per-run state - event handler references this\n const runState = createRunState();\n attachSessionEventHandlers({ session, runState, model, agentConfig });\n\n return {\n async run(\n message: ChatMessage,\n responseCtx: ChatResponseContext,\n platform: PlatformInfo,\n ): Promise<{ stopReason: string; errorMessage?: string }> {\n const prepared = await prepareRunContext({\n message,\n responseCtx,\n platform,\n conversationId,\n conversationDir,\n sessionUuid,\n runState,\n executor,\n executionResolver,\n resolveExecutorForRun,\n getPathContext,\n sessionManager,\n session,\n agent,\n setEventContext,\n setUploadFunction,\n pathContext,\n });\n pathContext = prepared.pathContext;\n\n addLifecycleBreadcrumb(\"agent.prompt.sent\", {\n provider: model.provider,\n model: agentConfig.model,\n channel_id: prepared.sessionConversation,\n session_id: sessionUuid,\n attachment_count: message.attachments?.length ?? 0,\n image_attachment_count: prepared.imageAttachments.length,\n });\n\n await session.prompt(\n prepared.userMessage,\n prepared.imageAttachments.length > 0 ? { images: prepared.imageAttachments } : undefined,\n );\n\n // Wait for queued messages\n await prepared.runQueue.wait();\n\n await finalizeRunResponse(responseCtx, session, runState);\n\n await reportUsageSummary({\n session,\n runState,\n responseCtx,\n platform,\n model,\n agentConfig,\n sessionConversation: prepared.sessionConversation,\n sessionUuid,\n waitForQueue: () => prepared.runQueue.wait(),\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\nexport function translateRuntimePathToHost(\n runtimePath: string,\n pathContext: RuntimePathContext,\n): string {\n return pathContext.runtimeToHostPath?.(runtimePath) ?? runtimePath;\n}\n\nexport function buildInitialPathContextForTest(\n sandboxConfig: SandboxConfig,\n hostWorkspaceRoot: string,\n): RuntimePathContext {\n return getUnresolvedSandboxPathContext(sandboxConfig, hostWorkspaceRoot);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAsB,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAAqB,MAAM,uBAAuB,CAAC;AACpE,OAAO,EACL,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,qBAAqB,EACrB,qBAAqB,EACrB,WAAW,EACX,iBAAiB,EACjB,aAAa,EAEb,eAAe,GAEhB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC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Z,MAAM,OAAO,GAAG,QAAQ,CAAC,YAAY,CAAC;YACtC,IAAI,OAAO,CAAC,IAAI,KAAK,CAAC;gBAAE,OAAO,SAAS,CAAC;YACzC,6BAA6B;YAC7B,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;YAC5C,IAAI,CAAC,KAAK;gBAAE,OAAO,SAAS,CAAC;YAC7B,OAAO;gBACL,QAAQ,EAAE,KAAK,CAAC,QAAQ;gBACxB,KAAK,EAAG,KAAK,CAAC,IAA2B,EAAE,KAAK;aACjD,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,0BAA0B,CACxC,WAAmB,EACnB,WAA+B;IAE/B,OAAO,WAAW,CAAC,iBAAiB,EAAE,CAAC,WAAW,CAAC,IAAI,WAAW,CAAC;AACrE,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC5C,aAA4B,EAC5B,iBAAyB;IAEzB,OAAO,+BAA+B,CAAC,aAAa,EAAE,iBAAiB,CAAC,CAAC;AAC3E,CAAC","sourcesContent":["import { Agent, type ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { getModel, type ImageContent } from \"@earendil-works/pi-ai\";\nimport {\n AgentSession,\n AuthStorage,\n convertToLlm,\n DefaultResourceLoader,\n formatSkillsForPrompt,\n getAgentDir,\n loadSkillsFromDir,\n ModelRegistry,\n SessionManager,\n SettingsManager,\n type Skill,\n} from \"@earendil-works/pi-coding-agent\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { mkdir, readFile, writeFile } from \"fs/promises\";\nimport { homedir } from \"os\";\nimport { join, posix } from \"path\";\nimport type {\n ChatMessage,\n ChatResponseContext,\n ChatToolResult,\n ConversationKind,\n PlatformInfo,\n} from \"./adapter.js\";\nimport { loadAgentConfigForConversation } from \"./config.js\";\nimport { ActorExecutionResolver } from \"./execution-resolver.js\";\nimport * as log from \"./log.js\";\nimport type { DockerContainerManager } from \"./provisioner.js\";\nimport {\n createExecutor,\n type Executor,\n type RuntimePathContext,\n type SandboxConfig,\n} from \"./sandbox/index.js\";\nimport { createMountedRuntimePathContext } from \"./sandbox/path-context.js\";\nimport { addLifecycleBreadcrumb, metricAttributes } from \"./sentry.js\";\nimport type { VaultManager } from \"./vault.js\";\nimport {\n extractSessionUuid,\n openManagedSession,\n type ResolvedSessionScope,\n type ThreadRootMessage,\n} from \"./session-store.js\";\nimport { shouldSurfaceToolDiagnostic } from \"./tool-diagnostics.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 buildRuntimePaths(runtimeWorkspaceRoot: string, conversationId: string) {\n const workspaceRoot = runtimeWorkspaceRoot.replace(/\\/+$/, \"\") || \"/\";\n const conversationPath = posix.join(workspaceRoot, conversationId);\n return {\n workspaceRoot,\n conversationPath,\n scratchPath: posix.join(conversationPath, \"scratch\"),\n };\n}\n\nfunction buildEnvDescription(sandboxType: SandboxConfig[\"type\"], workspaceRoot: string): string {\n switch (sandboxType) {\n case \"image\":\n return `You are running inside a managed per-user container.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${workspaceRoot}\n- Install tools with the image's package manager\n- Your changes persist for this user's container until it is recreated`;\n case \"container\":\n return `You are running inside a shared container.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${workspaceRoot}\n- Install tools with the container's package manager\n- Your changes persist across sessions`;\n case \"firecracker\":\n return `You are running inside a Firecracker microVM.\n- Runtime workspace root: ${workspaceRoot}\n- Use cd or absolute paths; project files are under ${workspaceRoot}\n- Install tools with: apt-get install <package> (Debian-based)\n- Your changes persist across sessions`;\n case \"cloudflare\":\n return `You are running through a Cloudflare Sandbox bridge.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${workspaceRoot}\n- Your commands run in a remote container managed by Cloudflare\n- Important: the remote filesystem is not automatically synced back to the host workspace`;\n default:\n return `You are running directly on the host machine.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${process.cwd()}\n- Be careful with system modifications`;\n }\n}\n\nexport function buildEventFilesystemInstructions(\n sandboxType: SandboxConfig[\"type\"],\n workspaceRoot: string,\n): string {\n if (sandboxType === \"host\" || sandboxType === \"container\" || sandboxType === \"image\") {\n return `Events live in the host-side mama control plane and are mounted at \\`${workspaceRoot}/events/\\` in this runtime.\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 Manually\nOnly do this when you need to create events from a script. Use unique filenames to avoid overwriting existing events. Include a timestamp or random suffix:\n\\`\\`\\`bash\ncat > ${workspaceRoot}/events/dentist-reminder-$(date +%s).json << 'EOF'\n{\"type\": \"one-shot\", \"platform\": \"<platform>\", \"conversationId\": \"<conversationId>\", \"conversationKind\": \"<direct|shared>\", \"userId\": \"<requester userId>\", \"text\": \"Dentist tomorrow\", \"at\": \"2025-12-14T09:00:00+01:00\"}\nEOF\n\\`\\`\\`\n\n### Managing Events\n- List: \\`ls ${workspaceRoot}/events/\\`\n- View: \\`cat ${workspaceRoot}/events/foo.json\\`\n- Delete/cancel: \\`rm ${workspaceRoot}/events/foo.json\\``;\n }\n\n return `Events live in the host-side mama control plane, not necessarily in this runtime filesystem.\n\nUse the \\`event\\` tool to create events. It writes to the correct host-side events directory and fills \\`platform\\`, \\`conversationId\\`, \\`conversationKind\\`, and \\`userId\\` for the current conversation automatically.\n\nDo not create event files with bash in \\`${workspaceRoot}/events/\\` from this sandbox unless you have explicitly verified that path is mounted back to the host-side mama events directory.`;\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 isSyntheticEvent = false,\n): string {\n const { workspaceRoot, conversationPath, scratchPath } = buildRuntimePaths(\n workspacePath,\n conversationId,\n );\n const sandboxType = sandboxConfig.type;\n const isContainerLike = sandboxType === \"container\" || sandboxType === \"image\";\n const isFirecracker = sandboxType === \"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 = buildEnvDescription(sandboxType, workspaceRoot);\n const eventFilesystemInstructions = buildEventFilesystemInstructions(sandboxType, workspaceRoot);\n const syntheticEventInstructions = isSyntheticEvent\n ? `\n## Synthetic Event Mode\n- You are handling a scheduled/background event, not opening a brand new chat with a stranger.\n- Treat the incoming user message as a self-contained task prepared by an earlier run.\n- Complete the task directly. Avoid generic greetings, self-introductions, or boilerplate offers to help.\n- For reminders/follow-ups, prefer a short direct response that sounds like a continuation of prior intent.\n- If the event text includes tone, brevity, or language instructions, follow them literally.\n`\n : \"\";\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${syntheticEventInstructions}\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- Default place for clones, downloads, and experiments: ${scratchPath}\n- Do not use host-only paths unless you are running in host mode and verified they exist.\n\n## Workspace Layout\n${workspaceRoot}/\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/ # Working directory for clones/downloads/experiments: ${scratchPath}\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 \\`${workspaceRoot}/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.\n${eventFilesystemInstructions}\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\nWhen scheduling an event, write \\`text\\` as a self-contained task for your future self. Include the minimum necessary context, tone, and constraints in the text itself because events do not inherit normal conversation history. Good: \\`Please remind the user that break time is over and it is time to return to class. Keep it brief, in Traditional Chinese, and do not ask follow-up questions.\\` Bad: \\`back to class\\`.\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 (${workspaceRoot}/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 ${workspaceRoot}/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${isContainerLike || 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\nexport function getUnresolvedSandboxPathContext(\n sandboxConfig: SandboxConfig,\n hostWorkspaceRoot: string,\n): RuntimePathContext {\n if (sandboxConfig.type === \"image\") {\n return createMountedRuntimePathContext(hostWorkspaceRoot, \"/workspace\");\n }\n\n return createExecutor(sandboxConfig).getPathContext(hostWorkspaceRoot);\n}\n\ninterface RunnerExecutionContext {\n executionResolver?: ActorExecutionResolver;\n executor: Executor;\n getPathContext: () => RuntimePathContext;\n resolveExecutorForRun(context: {\n platform: string;\n userId: string;\n conversationId: string;\n }): Promise<void>;\n}\n\ninterface RunnerSessionState {\n responseCtx: ChatResponseContext | null;\n logCtx: {\n conversationId: string;\n userName?: string;\n conversationName?: string;\n sessionId?: string;\n } | null;\n queue: {\n enqueue(fn: () => Promise<void>, errorContext: string): void;\n } | null;\n pendingTools: Map<string, { toolName: string; args: unknown; startTime: number }>;\n totalUsage: {\n input: number;\n output: number;\n cacheRead: number;\n cacheWrite: number;\n cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };\n };\n llmCallCount: number;\n stopReason: string;\n errorMessage: string | undefined;\n}\n\ninterface PreparedRunContext {\n sessionConversation: string;\n runQueue: ReturnType<typeof createRunQueue>;\n userMessage: string;\n imageAttachments: ImageContent[];\n}\n\ninterface ConfiguredAgentSession {\n agent: Agent;\n session: AgentSession;\n}\n\nfunction createRunnerExecutionContext(\n sandboxConfig: SandboxConfig,\n vaultManager: VaultManager | undefined,\n provisioner: DockerContainerManager | undefined,\n workspaceDir: string,\n hostWorkspacePath: string,\n): RunnerExecutionContext {\n const executionResolver =\n vaultManager &&\n sandboxConfig.type !== \"host\" &&\n (vaultManager.isEnabled() ||\n sandboxConfig.type === \"container\" ||\n sandboxConfig.type === \"image\" ||\n sandboxConfig.type === \"cloudflare\" ||\n sandboxConfig.type === \"firecracker\")\n ? new ActorExecutionResolver(sandboxConfig, vaultManager, provisioner, workspaceDir)\n : undefined;\n\n // activeExecutor is replaced at the start of each run() call when executionResolver\n // is present, so the stable `executor` wrapper always delegates to the latest resolved value.\n let activeExecutor: Executor =\n executionResolver !== undefined\n ? createExecutor({ type: \"host\" })\n : createExecutor(sandboxConfig);\n const executor: Executor = {\n exec(command, options) {\n return activeExecutor.exec(command, options);\n },\n getWorkspacePath(hostPath) {\n return activeExecutor.getWorkspacePath(hostPath);\n },\n getSandboxConfig() {\n return activeExecutor.getSandboxConfig();\n },\n getPathContext(hostWorkspaceRoot) {\n return activeExecutor.getPathContext(hostWorkspaceRoot);\n },\n };\n\n return {\n executionResolver,\n executor,\n getPathContext: () => executor.getPathContext(hostWorkspacePath),\n async resolveExecutorForRun(context): Promise<void> {\n if (!executionResolver) return;\n activeExecutor = await executionResolver.resolve(context);\n },\n };\n}\n\nasync function createConfiguredAgentSession(params: {\n conversationId: string;\n workspaceDir: string;\n runtimeWorkspaceRoot: string;\n systemPrompt: string;\n model: ReturnType<typeof getModel>;\n thinkingLevel: ThinkingLevel;\n tools: Awaited<ReturnType<typeof createMamaTools>>[\"tools\"];\n sessionManager: SessionManager;\n settingsManager: SettingsManager;\n}): Promise<ConfiguredAgentSession> {\n const {\n conversationId,\n workspaceDir,\n runtimeWorkspaceRoot,\n systemPrompt,\n model,\n thinkingLevel,\n tools,\n sessionManager,\n settingsManager,\n } = params;\n\n const authStorage = AuthStorage.create(join(homedir(), \".pi\", \"mama\", \"auth.json\"));\n const modelRegistry = ModelRegistry.create(authStorage);\n const agent = new Agent({\n initialState: {\n systemPrompt,\n model,\n thinkingLevel,\n tools,\n },\n convertToLlm,\n getApiKey: async () => {\n const key = await modelRegistry.getApiKeyForProvider(model.provider);\n if (!key) {\n throw new Error(\n `No API key for provider \"${model.provider}\". Set the appropriate environment variable or configure via auth.json`,\n );\n }\n return key;\n },\n });\n\n const loadedSession = sessionManager.buildSessionContext();\n if (loadedSession.messages.length > 0) {\n agent.state.messages = loadedSession.messages;\n log.logInfo(\n `[${conversationId}] Reloaded ${loadedSession.messages.length} messages from session context`,\n );\n }\n\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((extension) => extension.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 const session = new AgentSession({\n agent,\n sessionManager,\n settingsManager,\n cwd: runtimeWorkspaceRoot,\n modelRegistry,\n resourceLoader,\n baseToolsOverride,\n });\n return { agent, session };\n}\n\nfunction createEmptyUsageTotals() {\n return {\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}\n\nfunction createRunState(): RunnerSessionState {\n return {\n responseCtx: null,\n logCtx: null,\n queue: null,\n pendingTools: new Map<string, { toolName: string; args: unknown; startTime: number }>(),\n totalUsage: createEmptyUsageTotals(),\n llmCallCount: 0,\n stopReason: \"stop\",\n errorMessage: undefined,\n };\n}\n\nfunction resetRunState(\n runState: RunnerSessionState,\n responseCtx: ChatResponseContext,\n sessionConversation: string,\n userName: string | undefined,\n sessionUuid: string,\n): void {\n runState.responseCtx = responseCtx;\n runState.logCtx = {\n conversationId: sessionConversation,\n userName,\n conversationName: undefined,\n sessionId: sessionUuid,\n };\n runState.pendingTools.clear();\n runState.totalUsage = createEmptyUsageTotals();\n runState.llmCallCount = 0;\n runState.stopReason = \"stop\";\n runState.errorMessage = undefined;\n}\n\nfunction createRunQueue(responseCtx: ChatResponseContext): {\n queue: { enqueue(fn: () => Promise<void>, errorContext: string): void };\n wait: () => Promise<void>;\n} {\n let queueChain = Promise.resolve();\n return {\n 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 wait: () => queueChain,\n };\n}\n\nfunction padTwoDigits(n: number): string {\n return n.toString().padStart(2, \"0\");\n}\n\nfunction formatTimestampedUserMessage(message: ChatMessage): string {\n const now = new Date();\n const offset = -now.getTimezoneOffset();\n const offsetSign = offset >= 0 ? \"+\" : \"-\";\n const offsetHours = padTwoDigits(Math.floor(Math.abs(offset) / 60));\n const offsetMins = padTwoDigits(Math.abs(offset) % 60);\n const timestamp =\n `${now.getFullYear()}-${padTwoDigits(now.getMonth() + 1)}-${padTwoDigits(now.getDate())} ` +\n `${padTwoDigits(now.getHours())}:${padTwoDigits(now.getMinutes())}:${padTwoDigits(now.getSeconds())}` +\n `${offsetSign}${offsetHours}:${offsetMins}`;\n const threadContext = message.threadTs ? ` [in-thread:${message.threadTs}]` : \"\";\n return `[${timestamp}] [${message.userName || \"unknown\"}]${threadContext}: ${message.text}`;\n}\n\nfunction collectMessageAttachments(\n message: ChatMessage,\n workspacePath: string,\n): { imageAttachments: ImageContent[]; nonImagePaths: string[] } {\n const imageAttachments: ImageContent[] = [];\n const nonImagePaths: string[] = [];\n\n for (const attachment of message.attachments || []) {\n const fullPath = `${workspacePath}/${attachment.localPath}`;\n const mimeType = getImageMimeType(attachment.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 return { imageAttachments, nonImagePaths };\n}\n\nfunction buildPromptPayload(\n message: ChatMessage,\n workspacePath: string,\n): {\n userMessage: string;\n imageAttachments: ImageContent[];\n} {\n let userMessage = formatTimestampedUserMessage(message);\n const { imageAttachments, nonImagePaths } = collectMessageAttachments(message, workspacePath);\n\n if (nonImagePaths.length > 0) {\n userMessage += `\\n\\n<slack_attachments>\\n${nonImagePaths.join(\"\\n\")}\\n</slack_attachments>`;\n }\n\n return { userMessage, imageAttachments };\n}\n\nasync function writePromptDebugContext(\n conversationDir: string,\n systemPrompt: string,\n session: AgentSession,\n userMessage: string,\n imageAttachmentCount: number,\n): Promise<void> {\n const debugContext = {\n systemPrompt,\n messages: session.messages,\n newUserMessage: userMessage,\n imageAttachmentCount,\n };\n await writeFile(\n join(conversationDir, \"last_prompt.jsonl\"),\n JSON.stringify(debugContext, null, 2),\n );\n}\n\nfunction getFinalAssistantText(session: AgentSession): string {\n const lastAssistant = session.messages.filter((message) => message.role === \"assistant\").pop();\n return (\n lastAssistant?.content\n .filter((content): content is { type: \"text\"; text: string } => content.type === \"text\")\n .map((content) => content.text)\n .join(\"\\n\") || \"\"\n );\n}\n\nasync function finalizeRunResponse(\n responseCtx: ChatResponseContext,\n session: AgentSession,\n runState: RunnerSessionState,\n): Promise<void> {\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 return;\n }\n\n const finalText = getFinalAssistantText(session);\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 return;\n }\n\n if (!finalText.trim()) return;\n\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\ninterface UsageReportContext {\n session: AgentSession;\n runState: RunnerSessionState;\n responseCtx: ChatResponseContext;\n platform: PlatformInfo;\n model: ReturnType<typeof getModel>;\n agentConfig: ReturnType<typeof loadAgentConfigForConversation>;\n sessionConversation: string;\n sessionUuid: string;\n waitForQueue: () => Promise<void>;\n}\n\nasync function reportUsageSummary(ctx: UsageReportContext): Promise<void> {\n const {\n session,\n runState,\n responseCtx,\n platform,\n model,\n agentConfig,\n sessionConversation,\n sessionUuid,\n waitForQueue,\n } = ctx;\n if (runState.totalUsage.cost.total <= 0) return;\n\n const lastAssistantMessage = session.messages\n .slice()\n .toReversed()\n .find(\n (message): message is Extract<typeof message, { role: \"assistant\" }> =>\n message.role === \"assistant\" && message.stopReason !== \"aborted\",\n );\n\n const contextTokens = lastAssistantMessage\n ? lastAssistantMessage.usage.input +\n lastAssistantMessage.usage.output +\n lastAssistantMessage.usage.cacheRead +\n lastAssistantMessage.usage.cacheWrite\n : 0;\n const contextWindow = model.contextWindow || 200000;\n\n const { 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 waitForQueue();\n }\n}\n\nfunction reloadSessionMessages(\n sessionManager: SessionManager,\n conversationId: string,\n agent: Agent,\n): void {\n const messages = sessionManager.buildSessionContext().messages;\n if (messages.length > 0) {\n agent.state.messages = messages;\n log.logInfo(`[${conversationId}] Reloaded ${messages.length} messages from context`);\n }\n}\n\nasync function prepareRunContext(params: {\n message: ChatMessage;\n responseCtx: ChatResponseContext;\n platform: PlatformInfo;\n conversationId: string;\n conversationDir: string;\n sessionUuid: string;\n runState: RunnerSessionState;\n executor: Executor;\n executionResolver?: ActorExecutionResolver;\n resolveExecutorForRun: RunnerExecutionContext[\"resolveExecutorForRun\"];\n getPathContext: () => RuntimePathContext;\n sessionManager: SessionManager;\n session: AgentSession;\n agent: Agent;\n setEventContext: (context: {\n platform: string;\n conversationId: string;\n conversationKind: ConversationKind;\n userId: string;\n }) => void;\n setUploadFunction: (fn: (filePath: string, title?: string) => Promise<void>) => void;\n pathContext: RuntimePathContext;\n}): Promise<PreparedRunContext & { pathContext: RuntimePathContext }> {\n const {\n message,\n responseCtx,\n platform,\n conversationId,\n conversationDir,\n sessionUuid,\n runState,\n executor,\n executionResolver,\n resolveExecutorForRun,\n getPathContext,\n sessionManager,\n session,\n agent,\n setEventContext,\n setUploadFunction,\n } = params;\n let pathContext = params.pathContext;\n const sessionConversation = message.sessionKey.split(\":\")[0];\n\n await mkdir(join(conversationDir, \"scratch\"), { recursive: true });\n\n if (executionResolver) {\n await resolveExecutorForRun({\n platform: platform.name,\n userId: message.userId,\n conversationId,\n });\n pathContext = getPathContext();\n }\n\n reloadSessionMessages(sessionManager, conversationId, agent);\n\n const memory = await getMemory(conversationDir);\n const skills = loadMamaSkills(conversationDir, pathContext.runtimeWorkspaceRoot);\n const systemPrompt = buildSystemPrompt(\n pathContext.runtimeWorkspaceRoot,\n conversationId,\n message.conversationKind,\n message.userId,\n memory,\n executor.getSandboxConfig(),\n platform,\n skills,\n message.id.startsWith(\"event:\"),\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 setUploadFunction(async (filePath: string, title?: string) => {\n const hostPath = translateRuntimePathToHost(filePath, pathContext);\n await responseCtx.uploadFile(hostPath, title);\n });\n\n resetRunState(runState, responseCtx, sessionConversation, message.userName, sessionUuid);\n const runQueue = createRunQueue(responseCtx);\n runState.queue = runQueue.queue;\n\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 const { userMessage, imageAttachments } = buildPromptPayload(\n message,\n pathContext.runtimeWorkspaceRoot,\n );\n await writePromptDebugContext(\n conversationDir,\n systemPrompt,\n session,\n userMessage,\n imageAttachments.length,\n );\n\n return {\n sessionConversation,\n runQueue,\n userMessage,\n imageAttachments,\n pathContext,\n };\n}\n\nfunction attachSessionEventHandlers(params: {\n session: AgentSession;\n runState: RunnerSessionState;\n model: ReturnType<typeof getModel>;\n agentConfig: ReturnType<typeof loadAgentConfigForConversation>;\n}): void {\n const { session, runState, model, agentConfig } = params;\n session.subscribe(async (event) => {\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 args = (event.args ?? {}) as { label?: string };\n const label = args.label || event.toolName;\n\n pendingTools.set(event.toolCallId, {\n toolName: event.toolName,\n args: event.args,\n startTime: Date.now(),\n });\n addLifecycleBreadcrumb(\"agent.tool.started\", {\n tool: event.toolName,\n ...baseAttrs,\n });\n\n log.logToolStart(logCtx, event.toolName, label, event.args as Record<string, unknown>);\n return;\n }\n\n if (event.type === \"tool_execution_end\") {\n const resultStr = extractToolResultText(event.result);\n const pending = pendingTools.get(event.toolCallId);\n pendingTools.delete(event.toolCallId);\n const durationMs = pending ? Date.now() - pending.startTime : 0;\n\n Sentry.metrics.count(\"agent.tool.calls\", 1, {\n attributes: metricAttributes({\n tool: event.toolName,\n error: String(event.isError),\n ...baseAttrs,\n }),\n });\n Sentry.metrics.distribution(\"agent.tool.duration\", durationMs, {\n unit: \"millisecond\",\n attributes: metricAttributes({\n tool: event.toolName,\n ...baseAttrs,\n }),\n });\n addLifecycleBreadcrumb(\"agent.tool.completed\", {\n tool: event.toolName,\n error: event.isError,\n duration_ms: durationMs,\n ...baseAttrs,\n });\n\n if (event.isError) {\n log.logToolError(logCtx, event.toolName, durationMs, resultStr);\n } else {\n log.logToolSuccess(logCtx, event.toolName, durationMs, resultStr);\n }\n\n if (shouldSurfaceToolDiagnostic(event.toolName)) {\n const toolResult: ChatToolResult = {\n toolName: event.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: event.isError,\n durationMs,\n };\n queue.enqueue(() => responseCtx.respondToolResult(toolResult), \"tool result diagnostic\");\n }\n\n if (event.isError) {\n queue.enqueue(\n () => responseCtx.respond(`_Error: ${truncate(resultStr, 200)}_`),\n \"tool error\",\n );\n }\n return;\n }\n\n if (event.type === \"message_start\") {\n if (event.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 return;\n }\n\n if (event.type === \"message_end\") {\n if (event.message.role === \"assistant\") {\n const assistantMsg = event.message;\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 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 thinkingParts: string[] = [];\n const textParts: string[] = [];\n for (const part of assistantMsg.content) {\n if (part.type === \"thinking\") {\n thinkingParts.push(part.thinking);\n } else if (part.type === \"text\") {\n textParts.push(part.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 return;\n }\n\n if (event.type === \"compaction_start\") {\n log.logInfo(`Auto-compaction started (reason: ${event.reason})`);\n queue.enqueue(() => responseCtx.respond(\"_Compacting context..._\"), \"compaction start\");\n return;\n }\n\n if (event.type === \"compaction_end\") {\n if (event.result) {\n log.logInfo(`Auto-compaction complete: ${event.result.tokensBefore} tokens compacted`);\n } else if (event.aborted) {\n log.logInfo(\"Auto-compaction aborted\");\n }\n return;\n }\n\n if (event.type === \"auto_retry_start\") {\n log.logWarning(`Retrying (${event.attempt}/${event.maxAttempts})`, event.errorMessage);\n queue.enqueue(\n () => responseCtx.respond(`_Retrying (${event.attempt}/${event.maxAttempts})..._`),\n \"retry\",\n );\n }\n });\n}\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 * 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 provisioner?: DockerContainerManager,\n): Promise<AgentRunner> {\n const agentConfig = loadAgentConfigForConversation(conversationDir);\n\n // Initialize logger with settings from config\n log.initLogger({\n logFormat: agentConfig.logFormat,\n logLevel: agentConfig.logLevel,\n });\n\n const workspaceBase = join(conversationDir, \"..\");\n const { executionResolver, executor, getPathContext, resolveExecutorForRun } =\n createRunnerExecutionContext(\n sandboxConfig,\n vaultManager,\n provisioner,\n workspaceDir,\n workspaceBase,\n );\n let pathContext = getUnresolvedSandboxPathContext(sandboxConfig, workspaceBase);\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, pathContext.runtimeWorkspaceRoot);\n const emptyPlatform: PlatformInfo = {\n name: \"chat\",\n formattingGuide: \"\",\n channels: [],\n users: [],\n };\n const systemPrompt = buildSystemPrompt(\n pathContext.runtimeWorkspaceRoot,\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 { sessionDir, contextFile, threadRootMessage } = sessionScope;\n const sessionManager = openManagedSession(\n contextFile,\n sessionDir,\n pathContext.runtimeWorkspaceRoot,\n );\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 = SettingsManager.inMemory();\n const { agent, session } = await createConfiguredAgentSession({\n conversationId,\n workspaceDir,\n runtimeWorkspaceRoot: pathContext.runtimeWorkspaceRoot,\n systemPrompt,\n model,\n thinkingLevel: agentConfig.thinkingLevel,\n tools,\n sessionManager,\n settingsManager,\n });\n\n // Mutable per-run state - event handler references this\n const runState = createRunState();\n attachSessionEventHandlers({ session, runState, model, agentConfig });\n\n return {\n async run(\n message: ChatMessage,\n responseCtx: ChatResponseContext,\n platform: PlatformInfo,\n ): Promise<{ stopReason: string; errorMessage?: string }> {\n const prepared = await prepareRunContext({\n message,\n responseCtx,\n platform,\n conversationId,\n conversationDir,\n sessionUuid,\n runState,\n executor,\n executionResolver,\n resolveExecutorForRun,\n getPathContext,\n sessionManager,\n session,\n agent,\n setEventContext,\n setUploadFunction,\n pathContext,\n });\n pathContext = prepared.pathContext;\n\n addLifecycleBreadcrumb(\"agent.prompt.sent\", {\n provider: model.provider,\n model: agentConfig.model,\n channel_id: prepared.sessionConversation,\n session_id: sessionUuid,\n attachment_count: message.attachments?.length ?? 0,\n image_attachment_count: prepared.imageAttachments.length,\n });\n\n await session.prompt(\n prepared.userMessage,\n prepared.imageAttachments.length > 0 ? { images: prepared.imageAttachments } : undefined,\n );\n\n // Wait for queued messages\n await prepared.runQueue.wait();\n\n await finalizeRunResponse(responseCtx, session, runState);\n\n await reportUsageSummary({\n session,\n runState,\n responseCtx,\n platform,\n model,\n agentConfig,\n sessionConversation: prepared.sessionConversation,\n sessionUuid,\n waitForQueue: () => prepared.runQueue.wait(),\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\nexport function translateRuntimePathToHost(\n runtimePath: string,\n pathContext: RuntimePathContext,\n): string {\n return pathContext.runtimeToHostPath?.(runtimePath) ?? runtimePath;\n}\n\nexport function buildInitialPathContextForTest(\n sandboxConfig: SandboxConfig,\n hostWorkspaceRoot: string,\n): RuntimePathContext {\n return getUnresolvedSandboxPathContext(sandboxConfig, hostWorkspaceRoot);\n}\n"]}
|
package/dist/commands/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export {
|
|
1
|
+
import type { CommandHandler } from "./types.js";
|
|
2
|
+
export { dispatchCommand } from "./registry.js";
|
|
3
3
|
export type { CommandContext, CommandHandler, CommandServices } from "./types.js";
|
|
4
|
-
export declare function
|
|
4
|
+
export declare function defaultCommandHandlers(): CommandHandler[];
|
|
5
5
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/commands/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/commands/index.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,YAAY,EAAE,cAAc,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElF,wBAAgB,sBAAsB,IAAI,cAAc,EAAE,CASzD","sourcesContent":["import { AutoReplyCommandHandler } from \"./auto-reply.js\";\nimport { LoginCommandHandler } from \"./login.js\";\nimport { ModelCommandHandler } from \"./model.js\";\nimport { NewCommandHandler } from \"./new.js\";\nimport { SandboxCommandHandler } from \"./sandbox.js\";\nimport { SessionViewCommandHandler } from \"./session-view.js\";\nimport type { CommandHandler } from \"./types.js\";\n\nexport { dispatchCommand } from \"./registry.js\";\nexport type { CommandContext, CommandHandler, CommandServices } from \"./types.js\";\n\nexport function defaultCommandHandlers(): CommandHandler[] {\n return [\n new LoginCommandHandler(),\n new SessionViewCommandHandler(),\n new AutoReplyCommandHandler(),\n new ModelCommandHandler(),\n new SandboxCommandHandler(),\n new NewCommandHandler(),\n ];\n}\n"]}
|
package/dist/commands/index.js
CHANGED
|
@@ -2,18 +2,17 @@ import { AutoReplyCommandHandler } from "./auto-reply.js";
|
|
|
2
2
|
import { LoginCommandHandler } from "./login.js";
|
|
3
3
|
import { ModelCommandHandler } from "./model.js";
|
|
4
4
|
import { NewCommandHandler } from "./new.js";
|
|
5
|
-
import { CommandRegistry } from "./registry.js";
|
|
6
5
|
import { SandboxCommandHandler } from "./sandbox.js";
|
|
7
6
|
import { SessionViewCommandHandler } from "./session-view.js";
|
|
8
|
-
export {
|
|
9
|
-
export function
|
|
10
|
-
return
|
|
7
|
+
export { dispatchCommand } from "./registry.js";
|
|
8
|
+
export function defaultCommandHandlers() {
|
|
9
|
+
return [
|
|
11
10
|
new LoginCommandHandler(),
|
|
12
11
|
new SessionViewCommandHandler(),
|
|
13
12
|
new AutoReplyCommandHandler(),
|
|
14
13
|
new ModelCommandHandler(),
|
|
15
14
|
new SandboxCommandHandler(),
|
|
16
15
|
new NewCommandHandler(),
|
|
17
|
-
]
|
|
16
|
+
];
|
|
18
17
|
}
|
|
19
18
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/commands/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/commands/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AACrD,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAG9D,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAGhD,MAAM,UAAU,sBAAsB;IACpC,OAAO;QACL,IAAI,mBAAmB,EAAE;QACzB,IAAI,yBAAyB,EAAE;QAC/B,IAAI,uBAAuB,EAAE;QAC7B,IAAI,mBAAmB,EAAE;QACzB,IAAI,qBAAqB,EAAE;QAC3B,IAAI,iBAAiB,EAAE;KACxB,CAAC;AACJ,CAAC","sourcesContent":["import { AutoReplyCommandHandler } from \"./auto-reply.js\";\nimport { LoginCommandHandler } from \"./login.js\";\nimport { ModelCommandHandler } from \"./model.js\";\nimport { NewCommandHandler } from \"./new.js\";\nimport { SandboxCommandHandler } from \"./sandbox.js\";\nimport { SessionViewCommandHandler } from \"./session-view.js\";\nimport type { CommandHandler } from \"./types.js\";\n\nexport { dispatchCommand } from \"./registry.js\";\nexport type { CommandContext, CommandHandler, CommandServices } from \"./types.js\";\n\nexport function defaultCommandHandlers(): CommandHandler[] {\n return [\n new LoginCommandHandler(),\n new SessionViewCommandHandler(),\n new AutoReplyCommandHandler(),\n new ModelCommandHandler(),\n new SandboxCommandHandler(),\n new NewCommandHandler(),\n ];\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"login.d.ts","sourceRoot":"","sources":["../../src/commands/login.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"login.d.ts","sourceRoot":"","sources":["../../src/commands/login.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAgCjE,qBAAa,mBAAoB,YAAW,cAAc;IAClD,SAAS,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,CAyGzD;CACF","sourcesContent":["import * as log from \"../log.js\";\nimport { parseLoginCommand } from \"../login/index.js\";\nimport { resolveActorVaultKey } from \"../vault-routing.js\";\nimport { sharedVaultKey } from \"../vault.js\";\nimport type { CommandContext, CommandHandler } from \"./types.js\";\nimport { replyWithContext } from \"./utils.js\";\n\nfunction ensureLoginVault(context: CommandContext): string {\n const { services, platformUserId, conversationId, vaultConversationId } = context;\n return resolveActorVaultKey(\n services.sandbox,\n platformUserId,\n vaultConversationId ?? conversationId,\n );\n}\n\nasync function refreshCopiedVaultRuntime(\n context: CommandContext,\n vaultId: string,\n): Promise<string | undefined> {\n if (context.services.sandbox.type !== \"image\") return undefined;\n\n const targetConversationId = context.vaultConversationId ?? context.conversationId;\n const cleared = context.services.runtime?.refreshConversationEnvironment(targetConversationId);\n if (cleared === false) {\n return \"A session is currently running, so the sandbox was not restarted. The copied credentials will be applied after the run finishes and the sandbox is recreated.\";\n }\n\n if (!context.services.provisioner) {\n return \"The cached session was refreshed. The sandbox will pick up copied credentials on the next provision.\";\n }\n\n await context.services.provisioner.remove(vaultId);\n return \"The sandbox container was removed and will be recreated with the copied env and file mounts on the next message.\";\n}\n\nexport class LoginCommandHandler implements CommandHandler {\n async tryHandle(context: CommandContext): Promise<boolean> {\n const parsed = parseLoginCommand(context.commandText);\n if (!parsed) return false;\n\n if (!context.privateConversation) {\n await replyWithContext(\n context.responseCtx,\n \"為了保護你的憑證,`/login` 只能在與機器人的私訊中使用。請先私訊機器人,再重新執行 `/login`。\",\n );\n return true;\n }\n\n if (parsed.action === \"shared_list\") {\n const profiles = context.services.vaultManager.listSharedVaults();\n await replyWithContext(\n context.responseCtx,\n profiles.length > 0\n ? `Shared login profiles:\\n${profiles.map((name) => `- ${name}`).join(\"\\n\")}`\n : \"No shared login profiles found.\",\n );\n return true;\n }\n\n if (parsed.action === \"shared_delete\") {\n try {\n const deleted = context.services.vaultManager.deleteSharedVault(parsed.name);\n await replyWithContext(\n context.responseCtx,\n deleted\n ? `Deleted shared login profile \\`${parsed.name}\\`.`\n : `Shared login profile \\`${parsed.name}\\` does not exist.`,\n );\n } catch (error) {\n await replyWithContext(\n context.responseCtx,\n error instanceof Error ? error.message : String(error),\n );\n }\n return true;\n }\n\n if (parsed.action === \"copy_shared\") {\n try {\n const vaultId = ensureLoginVault(context);\n const result = context.services.vaultManager.copySharedVaultTo(parsed.name, vaultId);\n const refreshNote = await refreshCopiedVaultRuntime(context, vaultId);\n await replyWithContext(\n context.responseCtx,\n `Copied shared login profile \\`${parsed.name}\\` into this conversation. Shared values overwrite matching conversation values; conversation-only values are kept. (${result.envKeysCopied} env key(s), ${result.filesCopied} file(s))${refreshNote ? ` ${refreshNote}` : \"\"}`,\n );\n } catch (error) {\n await replyWithContext(\n context.responseCtx,\n error instanceof Error ? error.message : String(error),\n );\n }\n return true;\n }\n\n if (!context.services.portalBaseUrl) {\n await replyWithContext(\n context.responseCtx,\n \"Login is not configured. Set `MAMA_LINK_URL` or `MAMA_LINK_PORT` on the server.\",\n );\n return true;\n }\n\n const isSharedSetup = parsed.action === \"shared_create\" || parsed.action === \"shared_update\";\n let vaultId: string;\n try {\n vaultId = isSharedSetup ? (sharedVaultKey(parsed.name) ?? \"\") : ensureLoginVault(context);\n if (!vaultId) {\n throw new Error(\n isSharedSetup ? `Invalid shared login profile name: ${parsed.name}` : \"Invalid vault id\",\n );\n }\n } catch (error) {\n log.logWarning(\n `[${context.conversationId}] Failed to prepare login vault for ${context.platform}/${context.platformUserId}`,\n error instanceof Error ? error.message : String(error),\n );\n await replyWithContext(\n context.responseCtx,\n \"Login setup failed on the server. 請稍後重試,或聯絡管理員檢查 vault 儲存權限。\",\n );\n return true;\n }\n\n const token = context.services.linkTokenStore.create(\n context.platform,\n context.platformUserId,\n context.conversationId,\n vaultId,\n \"\",\n );\n const vaultLabel = isSharedSetup\n ? `shared login profile (${parsed.name})`\n : context.services.sandbox.type === \"container\"\n ? `container vault (${vaultId})`\n : \"your vault\";\n await replyWithContext(\n context.responseCtx,\n `Open this link to store credentials in ${vaultLabel} (expires in 15 minutes):\\n${context.services.portalBaseUrl}/link?token=${token.token}`,\n );\n return true;\n }\n}\n"]}
|
package/dist/commands/login.js
CHANGED
|
@@ -7,6 +7,20 @@ function ensureLoginVault(context) {
|
|
|
7
7
|
const { services, platformUserId, conversationId, vaultConversationId } = context;
|
|
8
8
|
return resolveActorVaultKey(services.sandbox, platformUserId, vaultConversationId ?? conversationId);
|
|
9
9
|
}
|
|
10
|
+
async function refreshCopiedVaultRuntime(context, vaultId) {
|
|
11
|
+
if (context.services.sandbox.type !== "image")
|
|
12
|
+
return undefined;
|
|
13
|
+
const targetConversationId = context.vaultConversationId ?? context.conversationId;
|
|
14
|
+
const cleared = context.services.runtime?.refreshConversationEnvironment(targetConversationId);
|
|
15
|
+
if (cleared === false) {
|
|
16
|
+
return "A session is currently running, so the sandbox was not restarted. The copied credentials will be applied after the run finishes and the sandbox is recreated.";
|
|
17
|
+
}
|
|
18
|
+
if (!context.services.provisioner) {
|
|
19
|
+
return "The cached session was refreshed. The sandbox will pick up copied credentials on the next provision.";
|
|
20
|
+
}
|
|
21
|
+
await context.services.provisioner.remove(vaultId);
|
|
22
|
+
return "The sandbox container was removed and will be recreated with the copied env and file mounts on the next message.";
|
|
23
|
+
}
|
|
10
24
|
export class LoginCommandHandler {
|
|
11
25
|
async tryHandle(context) {
|
|
12
26
|
const parsed = parseLoginCommand(context.commandText);
|
|
@@ -39,7 +53,8 @@ export class LoginCommandHandler {
|
|
|
39
53
|
try {
|
|
40
54
|
const vaultId = ensureLoginVault(context);
|
|
41
55
|
const result = context.services.vaultManager.copySharedVaultTo(parsed.name, vaultId);
|
|
42
|
-
|
|
56
|
+
const refreshNote = await refreshCopiedVaultRuntime(context, vaultId);
|
|
57
|
+
await replyWithContext(context.responseCtx, `Copied shared login profile \`${parsed.name}\` into this conversation. Shared values overwrite matching conversation values; conversation-only values are kept. (${result.envKeysCopied} env key(s), ${result.filesCopied} file(s))${refreshNote ? ` ${refreshNote}` : ""}`);
|
|
43
58
|
}
|
|
44
59
|
catch (error) {
|
|
45
60
|
await replyWithContext(context.responseCtx, error instanceof Error ? error.message : String(error));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"login.js","sourceRoot":"","sources":["../../src/commands/login.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE7C,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE9C,SAAS,gBAAgB,CAAC,OAAuB;IAC/C,MAAM,EAAE,QAAQ,EAAE,cAAc,EAAE,cAAc,EAAE,mBAAmB,EAAE,GAAG,OAAO,CAAC;IAClF,OAAO,oBAAoB,CACzB,QAAQ,CAAC,OAAO,EAChB,cAAc,EACd,mBAAmB,IAAI,cAAc,CACtC,CAAC;AACJ,CAAC;AAED,MAAM,OAAO,mBAAmB;IAC9B,KAAK,CAAC,SAAS,CAAC,OAAuB;QACrC,MAAM,MAAM,GAAG,iBAAiB,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QACtD,IAAI,CAAC,MAAM;YAAE,OAAO,KAAK,CAAC;QAE1B,IAAI,CAAC,OAAO,CAAC,mBAAmB,EAAE,CAAC;YACjC,MAAM,gBAAgB,CACpB,OAAO,CAAC,WAAW,EACnB,yDAAyD,CAC1D,CAAC;YACF,O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,CAAC,CAAC,YAAY,CAAC;QACnB,MAAM,gBAAgB,CACpB,OAAO,CAAC,WAAW,EACnB,0CAA0C,UAAU,8BAA8B,OAAO,CAAC,QAAQ,CAAC,aAAa,eAAe,KAAK,CAAC,KAAK,EAAE,CAC7I,CAAC;QACF,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import * as log from \"../log.js\";\nimport { parseLoginCommand } from \"../login/index.js\";\nimport { resolveActorVaultKey } from \"../vault-routing.js\";\nimport { sharedVaultKey } from \"../vault.js\";\nimport type { CommandContext, CommandHandler } from \"./types.js\";\nimport { replyWithContext } from \"./utils.js\";\n\nfunction ensureLoginVault(context: CommandContext): string {\n const { services, platformUserId, conversationId, vaultConversationId } = context;\n return resolveActorVaultKey(\n services.sandbox,\n platformUserId,\n vaultConversationId ?? conversationId,\n );\n}\n\nasync function refreshCopiedVaultRuntime(\n context: CommandContext,\n vaultId: string,\n): Promise<string | undefined> {\n if (context.services.sandbox.type !== \"image\") return undefined;\n\n const targetConversationId = context.vaultConversationId ?? context.conversationId;\n const cleared = context.services.runtime?.refreshConversationEnvironment(targetConversationId);\n if (cleared === false) {\n return \"A session is currently running, so the sandbox was not restarted. The copied credentials will be applied after the run finishes and the sandbox is recreated.\";\n }\n\n if (!context.services.provisioner) {\n return \"The cached session was refreshed. The sandbox will pick up copied credentials on the next provision.\";\n }\n\n await context.services.provisioner.remove(vaultId);\n return \"The sandbox container was removed and will be recreated with the copied env and file mounts on the next message.\";\n}\n\nexport class LoginCommandHandler implements CommandHandler {\n async tryHandle(context: CommandContext): Promise<boolean> {\n const parsed = parseLoginCommand(context.commandText);\n if (!parsed) return false;\n\n if (!context.privateConversation) {\n await replyWithContext(\n context.responseCtx,\n \"為了保護你的憑證,`/login` 只能在與機器人的私訊中使用。請先私訊機器人,再重新執行 `/login`。\",\n );\n return true;\n }\n\n if (parsed.action === \"shared_list\") {\n const profiles = context.services.vaultManager.listSharedVaults();\n await replyWithContext(\n context.responseCtx,\n profiles.length > 0\n ? `Shared login profiles:\\n${profiles.map((name) => `- ${name}`).join(\"\\n\")}`\n : \"No shared login profiles found.\",\n );\n return true;\n }\n\n if (parsed.action === \"shared_delete\") {\n try {\n const deleted = context.services.vaultManager.deleteSharedVault(parsed.name);\n await replyWithContext(\n context.responseCtx,\n deleted\n ? `Deleted shared login profile \\`${parsed.name}\\`.`\n : `Shared login profile \\`${parsed.name}\\` does not exist.`,\n );\n } catch (error) {\n await replyWithContext(\n context.responseCtx,\n error instanceof Error ? error.message : String(error),\n );\n }\n return true;\n }\n\n if (parsed.action === \"copy_shared\") {\n try {\n const vaultId = ensureLoginVault(context);\n const result = context.services.vaultManager.copySharedVaultTo(parsed.name, vaultId);\n const refreshNote = await refreshCopiedVaultRuntime(context, vaultId);\n await replyWithContext(\n context.responseCtx,\n `Copied shared login profile \\`${parsed.name}\\` into this conversation. Shared values overwrite matching conversation values; conversation-only values are kept. (${result.envKeysCopied} env key(s), ${result.filesCopied} file(s))${refreshNote ? ` ${refreshNote}` : \"\"}`,\n );\n } catch (error) {\n await replyWithContext(\n context.responseCtx,\n error instanceof Error ? error.message : String(error),\n );\n }\n return true;\n }\n\n if (!context.services.portalBaseUrl) {\n await replyWithContext(\n context.responseCtx,\n \"Login is not configured. Set `MAMA_LINK_URL` or `MAMA_LINK_PORT` on the server.\",\n );\n return true;\n }\n\n const isSharedSetup = parsed.action === \"shared_create\" || parsed.action === \"shared_update\";\n let vaultId: string;\n try {\n vaultId = isSharedSetup ? (sharedVaultKey(parsed.name) ?? \"\") : ensureLoginVault(context);\n if (!vaultId) {\n throw new Error(\n isSharedSetup ? `Invalid shared login profile name: ${parsed.name}` : \"Invalid vault id\",\n );\n }\n } catch (error) {\n log.logWarning(\n `[${context.conversationId}] Failed to prepare login vault for ${context.platform}/${context.platformUserId}`,\n error instanceof Error ? error.message : String(error),\n );\n await replyWithContext(\n context.responseCtx,\n \"Login setup failed on the server. 請稍後重試,或聯絡管理員檢查 vault 儲存權限。\",\n );\n return true;\n }\n\n const token = context.services.linkTokenStore.create(\n context.platform,\n context.platformUserId,\n context.conversationId,\n vaultId,\n \"\",\n );\n const vaultLabel = isSharedSetup\n ? `shared login profile (${parsed.name})`\n : context.services.sandbox.type === \"container\"\n ? `container vault (${vaultId})`\n : \"your vault\";\n await replyWithContext(\n context.responseCtx,\n `Open this link to store credentials in ${vaultLabel} (expires in 15 minutes):\\n${context.services.portalBaseUrl}/link?token=${token.token}`,\n );\n return true;\n }\n}\n"]}
|
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
import type { CommandContext, CommandHandler } from "./types.js";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
constructor(handlers: readonly CommandHandler[]);
|
|
5
|
-
handle(context: CommandContext): Promise<boolean>;
|
|
6
|
-
}
|
|
2
|
+
/** Run handlers in order, returning true as soon as one accepts the command. */
|
|
3
|
+
export declare function dispatchCommand(handlers: readonly CommandHandler[], context: CommandContext): Promise<boolean>;
|
|
7
4
|
//# sourceMappingURL=registry.d.ts.map
|