@geminixiang/mikan 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +324 -0
- package/LICENSE +22 -0
- package/README.md +297 -0
- package/dist/adapter.d.ts +134 -0
- package/dist/adapter.d.ts.map +1 -0
- package/dist/adapter.js +2 -0
- package/dist/adapter.js.map +1 -0
- package/dist/adapters/discord/bot.d.ts +63 -0
- package/dist/adapters/discord/bot.d.ts.map +1 -0
- package/dist/adapters/discord/bot.js +577 -0
- package/dist/adapters/discord/bot.js.map +1 -0
- package/dist/adapters/discord/context.d.ts +9 -0
- package/dist/adapters/discord/context.d.ts.map +1 -0
- package/dist/adapters/discord/context.js +245 -0
- package/dist/adapters/discord/context.js.map +1 -0
- package/dist/adapters/discord/index.d.ts +3 -0
- package/dist/adapters/discord/index.d.ts.map +1 -0
- package/dist/adapters/discord/index.js +3 -0
- package/dist/adapters/discord/index.js.map +1 -0
- package/dist/adapters/shared.d.ts +91 -0
- package/dist/adapters/shared.d.ts.map +1 -0
- package/dist/adapters/shared.js +191 -0
- package/dist/adapters/shared.js.map +1 -0
- package/dist/adapters/slack/bot.d.ts +139 -0
- package/dist/adapters/slack/bot.d.ts.map +1 -0
- package/dist/adapters/slack/bot.js +1272 -0
- package/dist/adapters/slack/bot.js.map +1 -0
- package/dist/adapters/slack/branch-manager.d.ts +28 -0
- package/dist/adapters/slack/branch-manager.d.ts.map +1 -0
- package/dist/adapters/slack/branch-manager.js +117 -0
- package/dist/adapters/slack/branch-manager.js.map +1 -0
- package/dist/adapters/slack/context.d.ts +12 -0
- package/dist/adapters/slack/context.d.ts.map +1 -0
- package/dist/adapters/slack/context.js +327 -0
- package/dist/adapters/slack/context.js.map +1 -0
- package/dist/adapters/slack/index.d.ts +3 -0
- package/dist/adapters/slack/index.d.ts.map +1 -0
- package/dist/adapters/slack/index.js +3 -0
- package/dist/adapters/slack/index.js.map +1 -0
- package/dist/adapters/slack/session.d.ts +38 -0
- package/dist/adapters/slack/session.d.ts.map +1 -0
- package/dist/adapters/slack/session.js +66 -0
- package/dist/adapters/slack/session.js.map +1 -0
- package/dist/adapters/slack/tools/attach.d.ts +12 -0
- package/dist/adapters/slack/tools/attach.d.ts.map +1 -0
- package/dist/adapters/slack/tools/attach.js +40 -0
- package/dist/adapters/slack/tools/attach.js.map +1 -0
- package/dist/adapters/telegram/bot.d.ts +51 -0
- package/dist/adapters/telegram/bot.d.ts.map +1 -0
- package/dist/adapters/telegram/bot.js +430 -0
- package/dist/adapters/telegram/bot.js.map +1 -0
- package/dist/adapters/telegram/context.d.ts +9 -0
- package/dist/adapters/telegram/context.d.ts.map +1 -0
- package/dist/adapters/telegram/context.js +190 -0
- package/dist/adapters/telegram/context.js.map +1 -0
- package/dist/adapters/telegram/html.d.ts +3 -0
- package/dist/adapters/telegram/html.d.ts.map +1 -0
- package/dist/adapters/telegram/html.js +98 -0
- package/dist/adapters/telegram/html.js.map +1 -0
- package/dist/adapters/telegram/index.d.ts +3 -0
- package/dist/adapters/telegram/index.d.ts.map +1 -0
- package/dist/adapters/telegram/index.js +3 -0
- package/dist/adapters/telegram/index.js.map +1 -0
- package/dist/agent.d.ts +36 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +1147 -0
- package/dist/agent.js.map +1 -0
- package/dist/commands/auto-reply.d.ts +5 -0
- package/dist/commands/auto-reply.d.ts.map +1 -0
- package/dist/commands/auto-reply.js +79 -0
- package/dist/commands/auto-reply.js.map +1 -0
- package/dist/commands/index.d.ts +5 -0
- package/dist/commands/index.d.ts.map +1 -0
- package/dist/commands/index.js +18 -0
- package/dist/commands/index.js.map +1 -0
- package/dist/commands/login.d.ts +5 -0
- package/dist/commands/login.d.ts.map +1 -0
- package/dist/commands/login.js +91 -0
- package/dist/commands/login.js.map +1 -0
- package/dist/commands/model.d.ts +14 -0
- package/dist/commands/model.d.ts.map +1 -0
- package/dist/commands/model.js +110 -0
- package/dist/commands/model.js.map +1 -0
- package/dist/commands/new.d.ts +5 -0
- package/dist/commands/new.d.ts.map +1 -0
- package/dist/commands/new.js +24 -0
- package/dist/commands/new.js.map +1 -0
- package/dist/commands/parse.d.ts +7 -0
- package/dist/commands/parse.d.ts.map +1 -0
- package/dist/commands/parse.js +17 -0
- package/dist/commands/parse.js.map +1 -0
- package/dist/commands/registry.d.ts +4 -0
- package/dist/commands/registry.d.ts.map +1 -0
- package/dist/commands/registry.js +9 -0
- package/dist/commands/registry.js.map +1 -0
- package/dist/commands/sandbox.d.ts +10 -0
- package/dist/commands/sandbox.d.ts.map +1 -0
- package/dist/commands/sandbox.js +83 -0
- package/dist/commands/sandbox.js.map +1 -0
- package/dist/commands/session-view.d.ts +5 -0
- package/dist/commands/session-view.d.ts.map +1 -0
- package/dist/commands/session-view.js +62 -0
- package/dist/commands/session-view.js.map +1 -0
- package/dist/commands/types.d.ts +41 -0
- package/dist/commands/types.d.ts.map +1 -0
- package/dist/commands/types.js +2 -0
- package/dist/commands/types.js.map +1 -0
- package/dist/commands/utils.d.ts +8 -0
- package/dist/commands/utils.d.ts.map +1 -0
- package/dist/commands/utils.js +14 -0
- package/dist/commands/utils.js.map +1 -0
- package/dist/config.d.ts +59 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +370 -0
- package/dist/config.js.map +1 -0
- package/dist/context.d.ts +17 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +24 -0
- package/dist/context.js.map +1 -0
- package/dist/conversation-history.d.ts +16 -0
- package/dist/conversation-history.d.ts.map +1 -0
- package/dist/conversation-history.js +144 -0
- package/dist/conversation-history.js.map +1 -0
- package/dist/download.d.ts +2 -0
- package/dist/download.d.ts.map +1 -0
- package/dist/download.js +89 -0
- package/dist/download.js.map +1 -0
- package/dist/env.d.ts +3 -0
- package/dist/env.d.ts.map +1 -0
- package/dist/env.js +12 -0
- package/dist/env.js.map +1 -0
- package/dist/events.d.ts +85 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +483 -0
- package/dist/events.js.map +1 -0
- package/dist/execution-resolver.d.ts +25 -0
- package/dist/execution-resolver.d.ts.map +1 -0
- package/dist/execution-resolver.js +167 -0
- package/dist/execution-resolver.js.map +1 -0
- package/dist/file-guards.d.ts +9 -0
- package/dist/file-guards.d.ts.map +1 -0
- package/dist/file-guards.js +56 -0
- package/dist/file-guards.js.map +1 -0
- package/dist/fs-atomic.d.ts +10 -0
- package/dist/fs-atomic.d.ts.map +1 -0
- package/dist/fs-atomic.js +45 -0
- package/dist/fs-atomic.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/instrument.d.ts +2 -0
- package/dist/instrument.d.ts.map +1 -0
- package/dist/instrument.js +10 -0
- package/dist/instrument.js.map +1 -0
- package/dist/log.d.ts +36 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +206 -0
- package/dist/log.js.map +1 -0
- package/dist/login/index.d.ts +42 -0
- package/dist/login/index.d.ts.map +1 -0
- package/dist/login/index.js +239 -0
- package/dist/login/index.js.map +1 -0
- package/dist/login/portal.d.ts +19 -0
- package/dist/login/portal.d.ts.map +1 -0
- package/dist/login/portal.js +1544 -0
- package/dist/login/portal.js.map +1 -0
- package/dist/login/session.d.ts +26 -0
- package/dist/login/session.d.ts.map +1 -0
- package/dist/login/session.js +56 -0
- package/dist/login/session.js.map +1 -0
- package/dist/main.d.ts +3 -0
- package/dist/main.d.ts.map +1 -0
- package/dist/main.js +366 -0
- package/dist/main.js.map +1 -0
- package/dist/provisioner.d.ts +83 -0
- package/dist/provisioner.d.ts.map +1 -0
- package/dist/provisioner.js +500 -0
- package/dist/provisioner.js.map +1 -0
- package/dist/runtime/conversation-orchestrator.d.ts +40 -0
- package/dist/runtime/conversation-orchestrator.d.ts.map +1 -0
- package/dist/runtime/conversation-orchestrator.js +183 -0
- package/dist/runtime/conversation-orchestrator.js.map +1 -0
- package/dist/runtime/index.d.ts +2 -0
- package/dist/runtime/index.d.ts.map +1 -0
- package/dist/runtime/index.js +2 -0
- package/dist/runtime/index.js.map +1 -0
- package/dist/runtime/session-runtime.d.ts +26 -0
- package/dist/runtime/session-runtime.d.ts.map +1 -0
- package/dist/runtime/session-runtime.js +221 -0
- package/dist/runtime/session-runtime.js.map +1 -0
- package/dist/sandbox/cloudflare.d.ts +15 -0
- package/dist/sandbox/cloudflare.d.ts.map +1 -0
- package/dist/sandbox/cloudflare.js +138 -0
- package/dist/sandbox/cloudflare.js.map +1 -0
- package/dist/sandbox/container.d.ts +16 -0
- package/dist/sandbox/container.d.ts.map +1 -0
- package/dist/sandbox/container.js +138 -0
- package/dist/sandbox/container.js.map +1 -0
- package/dist/sandbox/errors.d.ts +6 -0
- package/dist/sandbox/errors.d.ts.map +1 -0
- package/dist/sandbox/errors.js +11 -0
- package/dist/sandbox/errors.js.map +1 -0
- package/dist/sandbox/firecracker.d.ts +17 -0
- package/dist/sandbox/firecracker.d.ts.map +1 -0
- package/dist/sandbox/firecracker.js +212 -0
- package/dist/sandbox/firecracker.js.map +1 -0
- package/dist/sandbox/host.d.ts +11 -0
- package/dist/sandbox/host.d.ts.map +1 -0
- package/dist/sandbox/host.js +89 -0
- package/dist/sandbox/host.js.map +1 -0
- package/dist/sandbox/image.d.ts +5 -0
- package/dist/sandbox/image.d.ts.map +1 -0
- package/dist/sandbox/image.js +30 -0
- package/dist/sandbox/image.js.map +1 -0
- package/dist/sandbox/index.d.ts +22 -0
- package/dist/sandbox/index.d.ts.map +1 -0
- package/dist/sandbox/index.js +54 -0
- package/dist/sandbox/index.js.map +1 -0
- package/dist/sandbox/path-context.d.ts +4 -0
- package/dist/sandbox/path-context.d.ts.map +1 -0
- package/dist/sandbox/path-context.js +20 -0
- package/dist/sandbox/path-context.js.map +1 -0
- package/dist/sandbox/types.d.ts +67 -0
- package/dist/sandbox/types.d.ts.map +1 -0
- package/dist/sandbox/types.js +2 -0
- package/dist/sandbox/types.js.map +1 -0
- package/dist/sandbox/utils.d.ts +4 -0
- package/dist/sandbox/utils.d.ts.map +1 -0
- package/dist/sandbox/utils.js +51 -0
- package/dist/sandbox/utils.js.map +1 -0
- package/dist/sentry.d.ts +50 -0
- package/dist/sentry.d.ts.map +1 -0
- package/dist/sentry.js +257 -0
- package/dist/sentry.js.map +1 -0
- package/dist/session-view/command.d.ts +5 -0
- package/dist/session-view/command.d.ts.map +1 -0
- package/dist/session-view/command.js +7 -0
- package/dist/session-view/command.js.map +1 -0
- package/dist/session-view/portal.d.ts +16 -0
- package/dist/session-view/portal.d.ts.map +1 -0
- package/dist/session-view/portal.js +1822 -0
- package/dist/session-view/portal.js.map +1 -0
- package/dist/session-view/service.d.ts +34 -0
- package/dist/session-view/service.d.ts.map +1 -0
- package/dist/session-view/service.js +434 -0
- package/dist/session-view/service.js.map +1 -0
- package/dist/session-view/store.d.ts +18 -0
- package/dist/session-view/store.d.ts.map +1 -0
- package/dist/session-view/store.js +36 -0
- package/dist/session-view/store.js.map +1 -0
- package/dist/sessions/metadata.d.ts +15 -0
- package/dist/sessions/metadata.d.ts.map +1 -0
- package/dist/sessions/metadata.js +11 -0
- package/dist/sessions/metadata.js.map +1 -0
- package/dist/sessions/policy.d.ts +13 -0
- package/dist/sessions/policy.d.ts.map +1 -0
- package/dist/sessions/policy.js +23 -0
- package/dist/sessions/policy.js.map +1 -0
- package/dist/sessions/store.d.ts +103 -0
- package/dist/sessions/store.d.ts.map +1 -0
- package/dist/sessions/store.js +349 -0
- package/dist/sessions/store.js.map +1 -0
- package/dist/store.d.ts +58 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +152 -0
- package/dist/store.js.map +1 -0
- package/dist/tool-diagnostics.d.ts +2 -0
- package/dist/tool-diagnostics.d.ts.map +1 -0
- package/dist/tool-diagnostics.js +7 -0
- package/dist/tool-diagnostics.js.map +1 -0
- package/dist/tools/bash.d.ts +10 -0
- package/dist/tools/bash.d.ts.map +1 -0
- package/dist/tools/bash.js +80 -0
- package/dist/tools/bash.js.map +1 -0
- package/dist/tools/edit.d.ts +11 -0
- package/dist/tools/edit.d.ts.map +1 -0
- package/dist/tools/edit.js +133 -0
- package/dist/tools/edit.js.map +1 -0
- package/dist/tools/event.d.ts +62 -0
- package/dist/tools/event.d.ts.map +1 -0
- package/dist/tools/event.js +138 -0
- package/dist/tools/event.js.map +1 -0
- package/dist/tools/index.d.ts +14 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +23 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/read.d.ts +11 -0
- package/dist/tools/read.d.ts.map +1 -0
- package/dist/tools/read.js +136 -0
- package/dist/tools/read.js.map +1 -0
- package/dist/tools/truncate.d.ts +57 -0
- package/dist/tools/truncate.d.ts.map +1 -0
- package/dist/tools/truncate.js +184 -0
- package/dist/tools/truncate.js.map +1 -0
- package/dist/tools/write.d.ts +10 -0
- package/dist/tools/write.d.ts.map +1 -0
- package/dist/tools/write.js +33 -0
- package/dist/tools/write.js.map +1 -0
- package/dist/trigger.d.ts +31 -0
- package/dist/trigger.d.ts.map +1 -0
- package/dist/trigger.js +98 -0
- package/dist/trigger.js.map +1 -0
- package/dist/ui-copy.d.ts +12 -0
- package/dist/ui-copy.d.ts.map +1 -0
- package/dist/ui-copy.js +36 -0
- package/dist/ui-copy.js.map +1 -0
- package/dist/vault-routing.d.ts +4 -0
- package/dist/vault-routing.d.ts.map +1 -0
- package/dist/vault-routing.js +16 -0
- package/dist/vault-routing.js.map +1 -0
- package/dist/vault.d.ts +72 -0
- package/dist/vault.d.ts.map +1 -0
- package/dist/vault.js +281 -0
- package/dist/vault.js.map +1 -0
- package/package.json +83 -0
|
@@ -0,0 +1 @@
|
|
|
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,EAA2C,MAAM,uBAAuB,CA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C,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 Api, type ImageContent, type Model } 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 PlatformName,\n} from \"./adapter.js\";\nimport type { SessionViewTokenStoreLike } from \"./commands/types.js\";\nimport { loadAgentConfigForConversation } from \"./config.js\";\nimport { ActorExecutionResolver } from \"./execution-resolver.js\";\nimport * as log from \"./log.js\";\nimport { reportUserFacingError } from \"./sentry.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 \"./sessions/store.js\";\nimport { shouldSurfaceToolDiagnostic } from \"./tool-diagnostics.js\";\nimport { createMikanTools } 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 loadMikanSkills(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 mikan 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 mikan 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 mikan events directory.`;\n}\n\nexport function resolveTriggerAttribution(\n message: Pick<ChatMessage, \"id\" | \"text\" | \"userName\">,\n): string | undefined {\n const eventTextMatch = message.text.match(/^\\[EVENT:([^:]+):/);\n if (eventTextMatch) return `[event: ${eventTextMatch[1]}]`;\n const eventIdMatch = message.id.match(/^event:([^:]+)/);\n if (eventIdMatch) return `[event: ${eventIdMatch[1]}]`;\n if (message.userName) return `@${message.userName}`;\n return undefined;\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 isEventTrigger = false,\n triggerAttribution?: string,\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 eventTriggerInstructions = isEventTrigger\n ? `\n## Event Trigger 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 const attributionInstructions = triggerAttribution\n ? `\n## Attribution\nAlways end your final ${platform.name} response and any GitHub issue/PR comments or descriptions you write via tools with:\n_Triggered by ${triggerAttribution}_\n\nDo not add this to \\`[SILENT]\\` responses.\n`\n : \"\";\n\n return `You are mikan, 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- If a user asks about something that should exist in conversation history but is not found in the current context window, do not answer \"I don't know\" or \"I don't have that\". Instead, search the thread session, top-level session, and \\`log.jsonl\\` before responding.\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${eventTriggerInstructions}\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${attributionInstructions}\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 reportedLlmError: boolean;\n}\n\ninterface PreparedRunContext {\n sessionConversation: string;\n runQueue: ReturnType<typeof createRunQueue>;\n userMessage: string;\n imageAttachments: ImageContent[];\n triggerAttribution?: string;\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: Model<Api>;\n thinkingLevel: ThinkingLevel;\n tools: Awaited<ReturnType<typeof createMikanTools>>[\"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\", \"mikan\", \"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 reportedLlmError: false,\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 runState.reportedLlmError = false;\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\nexport function appendTriggerAttribution(\n text: string,\n triggerAttribution: string | undefined,\n): string {\n if (!triggerAttribution) return text;\n const suffix = `_Triggered by ${triggerAttribution}_`;\n if (text.trimEnd().endsWith(suffix)) return text;\n return `${text.trimEnd()}\\n\\n${suffix}`;\n}\n\nasync function finalizeRunResponse(\n responseCtx: ChatResponseContext,\n session: AgentSession,\n runState: RunnerSessionState,\n options?: {\n triggerAttribution?: string;\n createOverflowLink?: () => string;\n platform?: string;\n model?: Model<Api>;\n sessionConversation?: string;\n sessionUuid?: string;\n },\n): Promise<void> {\n if (runState.stopReason === \"error\" && runState.errorMessage) {\n if (!runState.reportedLlmError) {\n runState.reportedLlmError = true;\n reportUserFacingError(new Error(\"LLM run completed with error stop reason\"), {\n domain: \"llm\",\n surface: \"assistant_response\",\n operation: \"llm_turn\",\n severity: \"error\",\n platform: options?.platform,\n provider: options?.model?.provider,\n model: options?.model?.name,\n stopReason: runState.stopReason,\n context: {\n sessionConversation: options?.sessionConversation,\n sessionUuid: options?.sessionUuid,\n hasErrorMessage: true,\n llmCallCount: runState.llmCallCount,\n },\n });\n }\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 reportUserFacingError(err, {\n domain: \"chat_platform\",\n surface: \"final_response\",\n operation: \"finalize_error_response\",\n severity: \"error\",\n platform: options?.platform,\n context: {\n sessionConversation: options?.sessionConversation,\n sessionUuid: options?.sessionUuid,\n stopReason: runState.stopReason,\n },\n });\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(\n appendTriggerAttribution(finalText, options?.triggerAttribution),\n { createOverflowLink: options?.createOverflowLink },\n );\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 reportUserFacingError(err, {\n domain: \"chat_platform\",\n surface: \"final_response\",\n operation: \"replace_final_response\",\n severity: \"error\",\n platform: options?.platform,\n context: {\n sessionConversation: options?.sessionConversation,\n sessionUuid: options?.sessionUuid,\n finalTextLength: finalText.length,\n },\n });\n }\n}\n\ninterface UsageReportContext {\n session: AgentSession;\n runState: RunnerSessionState;\n responseCtx: ChatResponseContext;\n platform: PlatformInfo;\n model: Model<Api>;\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 = loadMikanSkills(conversationDir, pathContext.runtimeWorkspaceRoot);\n const triggerAttribution = resolveTriggerAttribution(message);\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 triggerAttribution,\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 triggerAttribution,\n pathContext,\n };\n}\n\nfunction attachSessionEventHandlers(params: {\n session: AgentSession;\n runState: RunnerSessionState;\n model: Model<Api>;\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 && shouldSurfaceToolDiagnostic(event.toolName)) {\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 sessionView?: {\n tokenStore: SessionViewTokenStoreLike;\n portalBaseUrl?: string;\n },\n): Promise<AgentRunner> {\n const agentConfig = loadAgentConfigForConversation(conversationDir);\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 } = createMikanTools(executor, workspaceDir);\n\n // Resolve model from config. Config stores provider/model as user-provided strings,\n // while getModel's public overload is narrowed to generated known providers.\n const model = getModel(agentConfig.provider as never, agentConfig.model as never) as Model<Api>;\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 = loadMikanSkills(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 const sessionViewTokenStore = sessionView?.tokenStore;\n const sessionViewPortalBaseUrl = sessionView?.portalBaseUrl;\n const createOverflowLink =\n sessionViewTokenStore && sessionViewPortalBaseUrl\n ? () => {\n const token = sessionViewTokenStore.create(\n platform.name as PlatformName,\n message.userId,\n conversationId,\n message.sessionKey,\n contextFile,\n message.userName,\n );\n return `${sessionViewPortalBaseUrl}/session?token=${token.token}`;\n }\n : undefined;\n\n await finalizeRunResponse(responseCtx, session, runState, {\n triggerAttribution: prepared.triggerAttribution,\n createOverflowLink,\n platform: platform.name,\n model,\n sessionConversation: prepared.sessionConversation,\n sessionUuid,\n });\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"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auto-reply.d.ts","sourceRoot":"","sources":["../../src/commands/auto-reply.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAkDjE,qBAAa,uBAAwB,YAAW,cAAc;IACtD,SAAS,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,CAoCzD;CACF","sourcesContent":["import { join } from \"path\";\nimport {\n type AutoReplyConfig,\n loadConversationAutoReplyConfig,\n saveConversationAutoReplyConfig,\n} from \"../config.js\";\nimport { matchCommand } from \"./parse.js\";\nimport type { CommandContext, CommandHandler } from \"./types.js\";\nimport { replyDiagnosticWithContext } from \"./utils.js\";\n\ntype AutoReplyAction = { type: \"status\" } | { type: \"on\" } | { type: \"off\" } | { type: \"invalid\" };\n\nconst AUTO_REPLY_COMMANDS = [\n \"auto-reply\",\n \"autoreply\",\n \"/auto-reply\",\n \"/autoreply\",\n \"/pi-auto-reply\",\n \"/pi-autoreply\",\n] as const;\n\nfunction parseAutoReplyCommand(text: string): AutoReplyAction | null {\n const matched = matchCommand(text, AUTO_REPLY_COMMANDS, { stripMention: true });\n if (!matched) return null;\n if (matched.args.length === 0) return { type: \"status\" };\n\n const lower = matched.args.join(\" \").toLowerCase();\n if (lower === \"status\") return { type: \"status\" };\n if (lower === \"on\" || lower === \"enable\" || lower === \"enabled\") return { type: \"on\" };\n if (lower === \"off\" || lower === \"disable\" || lower === \"disabled\") return { type: \"off\" };\n\n return { type: \"invalid\" };\n}\n\nfunction formatAutoReplyStatus(config: AutoReplyConfig): string {\n const status = `_Auto-reply is ${config.enabled ? \"enabled\" : \"disabled\"} for this channel._`;\n if (config.rules.length === 0) return status;\n\n return `${status}\\nCurrent rules:\\n\\`\\`\\`\\n${config.rules.join(\"\\n\")}\\n\\`\\`\\``;\n}\n\nfunction formatAutoReplyUsage(): string {\n return \"_Usage: `/pi-auto-reply on|off|status`_\";\n}\n\nfunction applyAction(current: AutoReplyConfig, action: AutoReplyAction): AutoReplyConfig {\n switch (action.type) {\n case \"status\":\n case \"invalid\":\n return current;\n case \"on\":\n return { ...current, enabled: true };\n case \"off\":\n return { ...current, enabled: false };\n }\n}\n\nexport class AutoReplyCommandHandler implements CommandHandler {\n async tryHandle(context: CommandContext): Promise<boolean> {\n const action = parseAutoReplyCommand(context.commandText);\n if (!action) return false;\n\n if (context.privateConversation) {\n await replyDiagnosticWithContext(\n context.responseCtx,\n \"_Auto Reply_\\n只能在 group/channel 裡設定。\",\n { style: \"muted\" },\n );\n return true;\n }\n\n if (action.type === \"invalid\") {\n await replyDiagnosticWithContext(context.responseCtx, formatAutoReplyUsage(), {\n style: \"muted\",\n });\n return true;\n }\n\n const conversationDir = join(context.services.workingDir, context.conversationId);\n const current = loadConversationAutoReplyConfig(conversationDir);\n const next = applyAction(current, action);\n if (action.type === \"on\" || (action.type === \"off\" && current.enabled)) {\n saveConversationAutoReplyConfig(conversationDir, next);\n }\n\n const status = formatAutoReplyStatus(next);\n const text =\n action.type === \"on\"\n ? `${status}\\nEdit rules at: \\`${join(conversationDir, \"auto-reply\")}\\``\n : status;\n await replyDiagnosticWithContext(context.responseCtx, text, {\n style: \"muted\",\n });\n return true;\n }\n}\n"]}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { join } from "path";
|
|
2
|
+
import { loadConversationAutoReplyConfig, saveConversationAutoReplyConfig, } from "../config.js";
|
|
3
|
+
import { matchCommand } from "./parse.js";
|
|
4
|
+
import { replyDiagnosticWithContext } from "./utils.js";
|
|
5
|
+
const AUTO_REPLY_COMMANDS = [
|
|
6
|
+
"auto-reply",
|
|
7
|
+
"autoreply",
|
|
8
|
+
"/auto-reply",
|
|
9
|
+
"/autoreply",
|
|
10
|
+
"/pi-auto-reply",
|
|
11
|
+
"/pi-autoreply",
|
|
12
|
+
];
|
|
13
|
+
function parseAutoReplyCommand(text) {
|
|
14
|
+
const matched = matchCommand(text, AUTO_REPLY_COMMANDS, { stripMention: true });
|
|
15
|
+
if (!matched)
|
|
16
|
+
return null;
|
|
17
|
+
if (matched.args.length === 0)
|
|
18
|
+
return { type: "status" };
|
|
19
|
+
const lower = matched.args.join(" ").toLowerCase();
|
|
20
|
+
if (lower === "status")
|
|
21
|
+
return { type: "status" };
|
|
22
|
+
if (lower === "on" || lower === "enable" || lower === "enabled")
|
|
23
|
+
return { type: "on" };
|
|
24
|
+
if (lower === "off" || lower === "disable" || lower === "disabled")
|
|
25
|
+
return { type: "off" };
|
|
26
|
+
return { type: "invalid" };
|
|
27
|
+
}
|
|
28
|
+
function formatAutoReplyStatus(config) {
|
|
29
|
+
const status = `_Auto-reply is ${config.enabled ? "enabled" : "disabled"} for this channel._`;
|
|
30
|
+
if (config.rules.length === 0)
|
|
31
|
+
return status;
|
|
32
|
+
return `${status}\nCurrent rules:\n\`\`\`\n${config.rules.join("\n")}\n\`\`\``;
|
|
33
|
+
}
|
|
34
|
+
function formatAutoReplyUsage() {
|
|
35
|
+
return "_Usage: `/pi-auto-reply on|off|status`_";
|
|
36
|
+
}
|
|
37
|
+
function applyAction(current, action) {
|
|
38
|
+
switch (action.type) {
|
|
39
|
+
case "status":
|
|
40
|
+
case "invalid":
|
|
41
|
+
return current;
|
|
42
|
+
case "on":
|
|
43
|
+
return { ...current, enabled: true };
|
|
44
|
+
case "off":
|
|
45
|
+
return { ...current, enabled: false };
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export class AutoReplyCommandHandler {
|
|
49
|
+
async tryHandle(context) {
|
|
50
|
+
const action = parseAutoReplyCommand(context.commandText);
|
|
51
|
+
if (!action)
|
|
52
|
+
return false;
|
|
53
|
+
if (context.privateConversation) {
|
|
54
|
+
await replyDiagnosticWithContext(context.responseCtx, "_Auto Reply_\n只能在 group/channel 裡設定。", { style: "muted" });
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
if (action.type === "invalid") {
|
|
58
|
+
await replyDiagnosticWithContext(context.responseCtx, formatAutoReplyUsage(), {
|
|
59
|
+
style: "muted",
|
|
60
|
+
});
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
const conversationDir = join(context.services.workingDir, context.conversationId);
|
|
64
|
+
const current = loadConversationAutoReplyConfig(conversationDir);
|
|
65
|
+
const next = applyAction(current, action);
|
|
66
|
+
if (action.type === "on" || (action.type === "off" && current.enabled)) {
|
|
67
|
+
saveConversationAutoReplyConfig(conversationDir, next);
|
|
68
|
+
}
|
|
69
|
+
const status = formatAutoReplyStatus(next);
|
|
70
|
+
const text = action.type === "on"
|
|
71
|
+
? `${status}\nEdit rules at: \`${join(conversationDir, "auto-reply")}\``
|
|
72
|
+
: status;
|
|
73
|
+
await replyDiagnosticWithContext(context.responseCtx, text, {
|
|
74
|
+
style: "muted",
|
|
75
|
+
});
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
//# sourceMappingURL=auto-reply.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auto-reply.js","sourceRoot":"","sources":["../../src/commands/auto-reply.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAEL,+BAA+B,EAC/B,+BAA+B,GAChC,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1C,OAAO,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AAIxD,MAAM,mBAAmB,GAAG;IAC1B,YAAY;IACZ,WAAW;IACX,aAAa;IACb,YAAY;IACZ,gBAAgB;IAChB,eAAe;CACP,CAAC;AAEX,SAAS,qBAAqB,CAAC,IAAY;IACzC,MAAM,OAAO,GAAG,YAAY,CAAC,IAAI,EAAE,mBAAmB,EAAE,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC;IAChF,IAAI,CAAC,OAAO;QAAE,OAAO,IAAI,CAAC;IAC1B,IAAI,OAAO,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;IAEzD,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;IACnD,IAAI,KAAK,KAAK,QAAQ;QAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;IAClD,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,CA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AE,OAAO,EAAE,CACnB,CAAC;YACF,OAAO,IAAI,CAAC;QACd,CAAC;QAED,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YAC9B,MAAM,0BAA0B,CAAC,OAAO,CAAC,WAAW,EAAE,oBAAoB,EAAE,EAAE;gBAC5E,KAAK,EAAE,OAAO;aACf,CAAC,CAAC;YACH,OAAO,IAAI,CAAC;QACd,CAAC;QAED,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;QAClF,MAAM,OAAO,GAAG,+BAA+B,CAAC,eAAe,CAAC,CAAC;QACjE,MAAM,IAAI,GAAG,WAAW,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC1C,IAAI,MAAM,CAAC,IAAI,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,KAAK,KAAK,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;YACvE,+BAA+B,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC;QACzD,CAAC;QAED,MAAM,MAAM,GAAG,qBAAqB,CAAC,IAAI,CAAC,CAAC;QAC3C,MAAM,IAAI,GACR,MAAM,CAAC,IAAI,KAAK,IAAI;YAClB,CAAC,CAAC,GAAG,MAAM,sBAAsB,IAAI,CAAC,eAAe,EAAE,YAAY,CAAC,IAAI;YACxE,CAAC,CAAC,MAAM,CAAC;QACb,MAAM,0BAA0B,CAAC,OAAO,CAAC,WAAW,EAAE,IAAI,EAAE;YAC1D,KAAK,EAAE,OAAO;SACf,CAAC,CAAC;QACH,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import { join } from \"path\";\nimport {\n type AutoReplyConfig,\n loadConversationAutoReplyConfig,\n saveConversationAutoReplyConfig,\n} from \"../config.js\";\nimport { matchCommand } from \"./parse.js\";\nimport type { CommandContext, CommandHandler } from \"./types.js\";\nimport { replyDiagnosticWithContext } from \"./utils.js\";\n\ntype AutoReplyAction = { type: \"status\" } | { type: \"on\" } | { type: \"off\" } | { type: \"invalid\" };\n\nconst AUTO_REPLY_COMMANDS = [\n \"auto-reply\",\n \"autoreply\",\n \"/auto-reply\",\n \"/autoreply\",\n \"/pi-auto-reply\",\n \"/pi-autoreply\",\n] as const;\n\nfunction parseAutoReplyCommand(text: string): AutoReplyAction | null {\n const matched = matchCommand(text, AUTO_REPLY_COMMANDS, { stripMention: true });\n if (!matched) return null;\n if (matched.args.length === 0) return { type: \"status\" };\n\n const lower = matched.args.join(\" \").toLowerCase();\n if (lower === \"status\") return { type: \"status\" };\n if (lower === \"on\" || lower === \"enable\" || lower === \"enabled\") return { type: \"on\" };\n if (lower === \"off\" || lower === \"disable\" || lower === \"disabled\") return { type: \"off\" };\n\n return { type: \"invalid\" };\n}\n\nfunction formatAutoReplyStatus(config: AutoReplyConfig): string {\n const status = `_Auto-reply is ${config.enabled ? \"enabled\" : \"disabled\"} for this channel._`;\n if (config.rules.length === 0) return status;\n\n return `${status}\\nCurrent rules:\\n\\`\\`\\`\\n${config.rules.join(\"\\n\")}\\n\\`\\`\\``;\n}\n\nfunction formatAutoReplyUsage(): string {\n return \"_Usage: `/pi-auto-reply on|off|status`_\";\n}\n\nfunction applyAction(current: AutoReplyConfig, action: AutoReplyAction): AutoReplyConfig {\n switch (action.type) {\n case \"status\":\n case \"invalid\":\n return current;\n case \"on\":\n return { ...current, enabled: true };\n case \"off\":\n return { ...current, enabled: false };\n }\n}\n\nexport class AutoReplyCommandHandler implements CommandHandler {\n async tryHandle(context: CommandContext): Promise<boolean> {\n const action = parseAutoReplyCommand(context.commandText);\n if (!action) return false;\n\n if (context.privateConversation) {\n await replyDiagnosticWithContext(\n context.responseCtx,\n \"_Auto Reply_\\n只能在 group/channel 裡設定。\",\n { style: \"muted\" },\n );\n return true;\n }\n\n if (action.type === \"invalid\") {\n await replyDiagnosticWithContext(context.responseCtx, formatAutoReplyUsage(), {\n style: \"muted\",\n });\n return true;\n }\n\n const conversationDir = join(context.services.workingDir, context.conversationId);\n const current = loadConversationAutoReplyConfig(conversationDir);\n const next = applyAction(current, action);\n if (action.type === \"on\" || (action.type === \"off\" && current.enabled)) {\n saveConversationAutoReplyConfig(conversationDir, next);\n }\n\n const status = formatAutoReplyStatus(next);\n const text =\n action.type === \"on\"\n ? `${status}\\nEdit rules at: \\`${join(conversationDir, \"auto-reply\")}\\``\n : status;\n await replyDiagnosticWithContext(context.responseCtx, text, {\n style: \"muted\",\n });\n return true;\n }\n}\n"]}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { CommandHandler } from "./types.js";
|
|
2
|
+
export { dispatchCommand } from "./registry.js";
|
|
3
|
+
export type { CommandContext, CommandHandler, CommandServices } from "./types.js";
|
|
4
|
+
export declare function defaultCommandHandlers(): CommandHandler[];
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
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"]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { AutoReplyCommandHandler } from "./auto-reply.js";
|
|
2
|
+
import { LoginCommandHandler } from "./login.js";
|
|
3
|
+
import { ModelCommandHandler } from "./model.js";
|
|
4
|
+
import { NewCommandHandler } from "./new.js";
|
|
5
|
+
import { SandboxCommandHandler } from "./sandbox.js";
|
|
6
|
+
import { SessionViewCommandHandler } from "./session-view.js";
|
|
7
|
+
export { dispatchCommand } from "./registry.js";
|
|
8
|
+
export function defaultCommandHandlers() {
|
|
9
|
+
return [
|
|
10
|
+
new LoginCommandHandler(),
|
|
11
|
+
new SessionViewCommandHandler(),
|
|
12
|
+
new AutoReplyCommandHandler(),
|
|
13
|
+
new ModelCommandHandler(),
|
|
14
|
+
new SandboxCommandHandler(),
|
|
15
|
+
new NewCommandHandler(),
|
|
16
|
+
];
|
|
17
|
+
}
|
|
18
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +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,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"]}
|
|
@@ -0,0 +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;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 `MIKAN_LINK_URL` or `MIKAN_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"]}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import * as log from "../log.js";
|
|
2
|
+
import { parseLoginCommand } from "../login/index.js";
|
|
3
|
+
import { resolveActorVaultKey } from "../vault-routing.js";
|
|
4
|
+
import { sharedVaultKey } from "../vault.js";
|
|
5
|
+
import { replyWithContext } from "./utils.js";
|
|
6
|
+
function ensureLoginVault(context) {
|
|
7
|
+
const { services, platformUserId, conversationId, vaultConversationId } = context;
|
|
8
|
+
return resolveActorVaultKey(services.sandbox, platformUserId, vaultConversationId ?? conversationId);
|
|
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
|
+
}
|
|
24
|
+
export class LoginCommandHandler {
|
|
25
|
+
async tryHandle(context) {
|
|
26
|
+
const parsed = parseLoginCommand(context.commandText);
|
|
27
|
+
if (!parsed)
|
|
28
|
+
return false;
|
|
29
|
+
if (!context.privateConversation) {
|
|
30
|
+
await replyWithContext(context.responseCtx, "為了保護你的憑證,`/login` 只能在與機器人的私訊中使用。請先私訊機器人,再重新執行 `/login`。");
|
|
31
|
+
return true;
|
|
32
|
+
}
|
|
33
|
+
if (parsed.action === "shared_list") {
|
|
34
|
+
const profiles = context.services.vaultManager.listSharedVaults();
|
|
35
|
+
await replyWithContext(context.responseCtx, profiles.length > 0
|
|
36
|
+
? `Shared login profiles:\n${profiles.map((name) => `- ${name}`).join("\n")}`
|
|
37
|
+
: "No shared login profiles found.");
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
if (parsed.action === "shared_delete") {
|
|
41
|
+
try {
|
|
42
|
+
const deleted = context.services.vaultManager.deleteSharedVault(parsed.name);
|
|
43
|
+
await replyWithContext(context.responseCtx, deleted
|
|
44
|
+
? `Deleted shared login profile \`${parsed.name}\`.`
|
|
45
|
+
: `Shared login profile \`${parsed.name}\` does not exist.`);
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
await replyWithContext(context.responseCtx, error instanceof Error ? error.message : String(error));
|
|
49
|
+
}
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
if (parsed.action === "copy_shared") {
|
|
53
|
+
try {
|
|
54
|
+
const vaultId = ensureLoginVault(context);
|
|
55
|
+
const result = context.services.vaultManager.copySharedVaultTo(parsed.name, vaultId);
|
|
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}` : ""}`);
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
await replyWithContext(context.responseCtx, error instanceof Error ? error.message : String(error));
|
|
61
|
+
}
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
if (!context.services.portalBaseUrl) {
|
|
65
|
+
await replyWithContext(context.responseCtx, "Login is not configured. Set `MIKAN_LINK_URL` or `MIKAN_LINK_PORT` on the server.");
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
const isSharedSetup = parsed.action === "shared_create" || parsed.action === "shared_update";
|
|
69
|
+
let vaultId;
|
|
70
|
+
try {
|
|
71
|
+
vaultId = isSharedSetup ? (sharedVaultKey(parsed.name) ?? "") : ensureLoginVault(context);
|
|
72
|
+
if (!vaultId) {
|
|
73
|
+
throw new Error(isSharedSetup ? `Invalid shared login profile name: ${parsed.name}` : "Invalid vault id");
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
log.logWarning(`[${context.conversationId}] Failed to prepare login vault for ${context.platform}/${context.platformUserId}`, error instanceof Error ? error.message : String(error));
|
|
78
|
+
await replyWithContext(context.responseCtx, "Login setup failed on the server. 請稍後重試,或聯絡管理員檢查 vault 儲存權限。");
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
const token = context.services.linkTokenStore.create(context.platform, context.platformUserId, context.conversationId, vaultId, "");
|
|
82
|
+
const vaultLabel = isSharedSetup
|
|
83
|
+
? `shared login profile (${parsed.name})`
|
|
84
|
+
: context.services.sandbox.type === "container"
|
|
85
|
+
? `container vault (${vaultId})`
|
|
86
|
+
: "your vault";
|
|
87
|
+
await replyWithContext(context.responseCtx, `Open this link to store credentials in ${vaultLabel} (expires in 15 minutes):\n${context.services.portalBaseUrl}/link?token=${token.token}`);
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
//# sourceMappingURL=login.js.map
|
|
@@ -0,0 +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,KAAK,UAAU,yBAAyB,CACtC,OAAuB,EACvB,OAAe;IAEf,IAAI,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,KAAK,OAAO;QAAE,OAAO,SAAS,CAAC;IAEhE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AAM,CAClD,OAAO,CAAC,QAAQ,EAChB,OAAO,CAAC,cAAc,EACtB,OAAO,CAAC,cAAc,EACtB,OAAO,EACP,EAAE,CACH,CAAC;QACF,MAAM,UAAU,GAAG,aAAa;YAC9B,CAAC,CAAC,yBAAyB,MAAM,CAAC,IAAI,GAAG;YACzC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,KAAK,WAAW;gBAC7C,CAAC,CAAC,oBAAoB,OAAO,GAAG;gBAChC,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 `MIKAN_LINK_URL` or `MIKAN_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"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import type { CommandContext, CommandHandler } from "./types.js";
|
|
3
|
+
export interface ParsedModelCommand {
|
|
4
|
+
command: "model" | "/model" | "/pi-model";
|
|
5
|
+
provider?: string;
|
|
6
|
+
model?: string;
|
|
7
|
+
thinkingLevel?: ThinkingLevel;
|
|
8
|
+
}
|
|
9
|
+
export declare function parseModelCommand(text: string): ParsedModelCommand | null;
|
|
10
|
+
export declare class ModelCommandHandler implements CommandHandler {
|
|
11
|
+
tryHandle(context: CommandContext): Promise<boolean>;
|
|
12
|
+
private isKnownModel;
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=model.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../src/commands/model.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAOnE,OAAO,KAAK,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAYjE,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,OAAO,GAAG,QAAQ,GAAG,WAAW,CAAC;IAC1C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,aAAa,CAAC,EAAE,aAAa,CAAC;CAC/B;AAID,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,kBAAkB,GAAG,IAAI,CAuBzE;AA8BD,qBAAa,mBAAoB,YAAW,cAAc;IAClD,SAAS,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,CA0EzD;IAED,OAAO,CAAC,YAAY;CAKrB","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { ThinkingLevel as PiAiThinkingLevel } from \"@earendil-works/pi-ai\";\nimport { AuthStorage, ModelRegistry } from \"@earendil-works/pi-coding-agent\";\nimport { homedir } from \"os\";\nimport { join } from \"path\";\nimport { loadAgentConfigForConversation, saveConversationModelConfig } from \"../config.js\";\nimport { matchCommand } from \"./parse.js\";\nimport type { CommandContext, CommandHandler } from \"./types.js\";\nimport { replyDiagnosticWithContext } from \"./utils.js\";\n\nconst PI_AI_THINKING_LEVELS = [\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n] satisfies PiAiThinkingLevel[];\nconst THINKING_LEVELS = new Set<ThinkingLevel>([\"off\", ...PI_AI_THINKING_LEVELS]);\n\nexport interface ParsedModelCommand {\n command: \"model\" | \"/model\" | \"/pi-model\";\n provider?: string;\n model?: string;\n thinkingLevel?: ThinkingLevel;\n}\n\nconst MODEL_COMMANDS = [\"model\", \"/model\", \"/pi-model\"] as const;\n\nexport function parseModelCommand(text: string): ParsedModelCommand | null {\n const matched = matchCommand(text, MODEL_COMMANDS);\n if (!matched) return null;\n\n if (matched.args.length === 0) {\n return { command: matched.command };\n }\n\n const spec = matched.args[0];\n const slash = spec.indexOf(\"/\");\n if (slash <= 0 || slash === spec.length - 1) {\n return { command: matched.command };\n }\n\n const modelSpec = spec.slice(slash + 1);\n const parsedModel = parseModelThinkingLevel(modelSpec);\n\n return {\n command: matched.command,\n provider: spec.slice(0, slash),\n model: parsedModel.model,\n thinkingLevel: parsedModel.thinkingLevel,\n };\n}\n\nfunction parseModelThinkingLevel(modelSpec: string): {\n model: string;\n thinkingLevel?: ThinkingLevel;\n} {\n const colon = modelSpec.lastIndexOf(\":\");\n if (colon <= 0 || colon === modelSpec.length - 1) {\n return { model: modelSpec };\n }\n\n const suffix = modelSpec.slice(colon + 1);\n if (!THINKING_LEVELS.has(suffix as ThinkingLevel)) {\n return { model: modelSpec };\n }\n\n return {\n model: modelSpec.slice(0, colon),\n thinkingLevel: suffix as ThinkingLevel,\n };\n}\n\nfunction formatModelSpec(provider: string, model: string, thinkingLevel?: ThinkingLevel): string {\n return `${provider}/${model}${thinkingLevel ? `:${thinkingLevel}` : \"\"}`;\n}\n\nfunction formatModelCommandSummary(lines: string[]): string {\n return [\"_Model_\", ...lines].join(\"\\n\");\n}\n\nexport class ModelCommandHandler implements CommandHandler {\n async tryHandle(context: CommandContext): Promise<boolean> {\n const parsed = parseModelCommand(context.commandText);\n if (!parsed) return false;\n\n const conversationDir = join(context.services.workingDir, context.conversationId);\n if (!parsed.provider || !parsed.model) {\n const current = loadAgentConfigForConversation(conversationDir);\n await replyDiagnosticWithContext(\n context.responseCtx,\n formatModelCommandSummary([\n `Current: \\`${formatModelSpec(current.provider, current.model, current.thinkingLevel)}\\``,\n \"\",\n \"Usage: `/pi-model provider/model[:thinking]`\",\n \"Example: `/pi-model anthropic/claude-sonnet-4-6:off`\",\n ]),\n { style: \"muted\" },\n );\n return true;\n }\n\n if (!this.isKnownModel(parsed.provider, parsed.model)) {\n await replyDiagnosticWithContext(\n context.responseCtx,\n formatModelCommandSummary([\n `找不到模型:\\`${formatModelSpec(parsed.provider, parsed.model, parsed.thinkingLevel)}\\``,\n \"請確認 provider/model 名稱,或先在 pi models.json 註冊自訂模型。\",\n ]),\n { style: \"muted\" },\n );\n return true;\n }\n\n if (!context.services.runtime) {\n await replyDiagnosticWithContext(\n context.responseCtx,\n formatModelCommandSummary([\n \"Model command is not configured correctly on the server. Please try again later.\",\n ]),\n { style: \"muted\" },\n );\n return true;\n }\n\n const switched = context.services.runtime.switchConversationModel(\n context.conversationId,\n parsed.provider,\n parsed.model,\n );\n if (!switched) {\n await replyDiagnosticWithContext(\n context.responseCtx,\n formatModelCommandSummary([\n \"目前這個 conversation 有執行中的工作,請等它完成或先 `/stop` 後再切換模型。\",\n ]),\n { style: \"muted\" },\n );\n return true;\n }\n\n saveConversationModelConfig(conversationDir, {\n provider: parsed.provider,\n model: parsed.model,\n ...(parsed.thinkingLevel ? { thinkingLevel: parsed.thinkingLevel } : {}),\n });\n\n await replyDiagnosticWithContext(\n context.responseCtx,\n formatModelCommandSummary([\n `Switched: \\`${formatModelSpec(parsed.provider, parsed.model, parsed.thinkingLevel)}\\``,\n \"下一則訊息會使用新模型。\",\n ]),\n { style: \"muted\" },\n );\n return true;\n }\n\n private isKnownModel(provider: string, model: string): boolean {\n const authStorage = AuthStorage.create(join(homedir(), \".pi\", \"mikan\", \"auth.json\"));\n const registry = ModelRegistry.create(authStorage);\n return registry.find(provider, model) !== undefined;\n }\n}\n"]}
|