@within-7/minto 0.1.6 → 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/cli.js +155 -37
- package/dist/Tool.js +38 -0
- package/dist/Tool.js.map +3 -3
- package/dist/commands/agents/AgentsCommand.js +52 -26
- package/dist/commands/agents/AgentsCommand.js.map +2 -2
- package/dist/commands/agents/constants.js +1 -1
- package/dist/commands/agents/constants.js.map +1 -1
- package/dist/commands/agents/index.js +1 -1
- package/dist/commands/bug.js +74 -7
- package/dist/commands/bug.js.map +3 -3
- package/dist/commands/clear.js +3 -0
- package/dist/commands/clear.js.map +2 -2
- package/dist/commands/compact.js +37 -0
- package/dist/commands/compact.js.map +2 -2
- package/dist/commands/context.js +84 -0
- package/dist/commands/context.js.map +7 -0
- package/dist/commands/ctx_viz.js +18 -10
- package/dist/commands/ctx_viz.js.map +2 -2
- package/dist/commands/doctor.js +158 -12
- package/dist/commands/doctor.js.map +2 -2
- package/dist/commands/export.js +156 -0
- package/dist/commands/export.js.map +7 -0
- package/dist/commands/mcp-interactive.js +21 -12
- package/dist/commands/mcp-interactive.js.map +2 -2
- package/dist/commands/model.js +6 -5
- package/dist/commands/model.js.map +2 -2
- package/dist/commands/permissions.js +86 -0
- package/dist/commands/permissions.js.map +7 -0
- package/dist/commands/quit.js +3 -1
- package/dist/commands/quit.js.map +2 -2
- package/dist/commands/sandbox.js +104 -0
- package/dist/commands/sandbox.js.map +7 -0
- package/dist/commands/status.js +58 -0
- package/dist/commands/status.js.map +7 -0
- package/dist/commands/tasks.js +108 -0
- package/dist/commands/tasks.js.map +7 -0
- package/dist/commands/todos.js +123 -0
- package/dist/commands/todos.js.map +7 -0
- package/dist/commands.js +20 -2
- package/dist/commands.js.map +2 -2
- package/dist/components/AgentThinkingBlock.js +10 -18
- package/dist/components/AgentThinkingBlock.js.map +2 -2
- package/dist/components/BackgroundTasksPanel.js +78 -29
- package/dist/components/BackgroundTasksPanel.js.map +2 -2
- package/dist/components/BashStreamingProgress.js +24 -0
- package/dist/components/BashStreamingProgress.js.map +7 -0
- package/dist/components/CollapsibleHint.js +14 -0
- package/dist/components/CollapsibleHint.js.map +7 -0
- package/dist/components/FileEditToolUpdatedMessage.js +1 -1
- package/dist/components/FileEditToolUpdatedMessage.js.map +2 -2
- package/dist/components/HotkeyHelpPanel.js +137 -0
- package/dist/components/HotkeyHelpPanel.js.map +7 -0
- package/dist/components/Logo.js +5 -5
- package/dist/components/Logo.js.map +2 -2
- package/dist/components/Message.js +23 -7
- package/dist/components/Message.js.map +3 -3
- package/dist/components/ModelConfig.js +16 -3
- package/dist/components/ModelConfig.js.map +2 -2
- package/dist/components/ModelListManager.js +3 -3
- package/dist/components/ModelListManager.js.map +2 -2
- package/dist/components/ModelSelector/ModelSelector.js +1 -1
- package/dist/components/Onboarding.js +19 -14
- package/dist/components/Onboarding.js.map +2 -2
- package/dist/components/ProgressBar.js +74 -0
- package/dist/components/ProgressBar.js.map +7 -0
- package/dist/components/PromptInput.js +156 -46
- package/dist/components/PromptInput.js.map +2 -2
- package/dist/components/RequestStatusIndicator.js +194 -0
- package/dist/components/RequestStatusIndicator.js.map +7 -0
- package/dist/components/Spinner.js +92 -27
- package/dist/components/Spinner.js.map +2 -2
- package/dist/components/SpinnerSymbol.js +21 -27
- package/dist/components/SpinnerSymbol.js.map +2 -2
- package/dist/components/StreamingBashOutput.js +9 -8
- package/dist/components/StreamingBashOutput.js.map +2 -2
- package/dist/components/SubagentBlock.js +1 -1
- package/dist/components/SubagentBlock.js.map +1 -1
- package/dist/components/SubagentProgress.js +10 -11
- package/dist/components/SubagentProgress.js.map +2 -2
- package/dist/components/TaskCard.js +16 -13
- package/dist/components/TaskCard.js.map +2 -2
- package/dist/components/TodoChangeBlock.js +1 -1
- package/dist/components/TodoChangeBlock.js.map +2 -2
- package/dist/components/TodoPanel.js +120 -29
- package/dist/components/TodoPanel.js.map +3 -3
- package/dist/components/TokenCounter.js +74 -0
- package/dist/components/TokenCounter.js.map +7 -0
- package/dist/components/TokenWarning.js +2 -1
- package/dist/components/TokenWarning.js.map +2 -2
- package/dist/components/TreeConnector.js +25 -0
- package/dist/components/TreeConnector.js.map +7 -0
- package/dist/components/TurnCompletionIndicator.js +18 -0
- package/dist/components/TurnCompletionIndicator.js.map +7 -0
- package/dist/components/messages/AssistantTextMessage.js +5 -2
- package/dist/components/messages/AssistantTextMessage.js.map +2 -2
- package/dist/components/messages/AssistantThinkingMessage.js +18 -3
- package/dist/components/messages/AssistantThinkingMessage.js.map +2 -2
- package/dist/components/messages/AssistantToolUseMessage.js +11 -8
- package/dist/components/messages/AssistantToolUseMessage.js.map +2 -2
- package/dist/components/messages/GroupRenderer.js +53 -0
- package/dist/components/messages/GroupRenderer.js.map +7 -0
- package/dist/components/messages/NestedTasksPreview.js +12 -0
- package/dist/components/messages/NestedTasksPreview.js.map +7 -0
- package/dist/components/messages/ParallelTasksGroupView.js +92 -0
- package/dist/components/messages/ParallelTasksGroupView.js.map +7 -0
- package/dist/components/messages/TaskInModuleView.js +198 -0
- package/dist/components/messages/TaskInModuleView.js.map +7 -0
- package/dist/components/messages/TaskOutputContent.js +53 -0
- package/dist/components/messages/TaskOutputContent.js.map +7 -0
- package/dist/components/messages/UserPromptMessage.js +1 -1
- package/dist/components/messages/UserPromptMessage.js.map +2 -2
- package/dist/components/messages/UserToolResultMessage/UserToolSuccessMessage.js +2 -3
- package/dist/components/messages/UserToolResultMessage/UserToolSuccessMessage.js.map +2 -2
- package/dist/components/permissions/FallbackPermissionRequest.js +4 -4
- package/dist/components/permissions/FallbackPermissionRequest.js.map +2 -2
- package/dist/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.js +4 -4
- package/dist/components/permissions/FilesystemPermissionRequest/FilesystemPermissionRequest.js.map +2 -2
- package/dist/constants/colors.js +48 -0
- package/dist/constants/colors.js.map +2 -2
- package/dist/constants/formatRules.js +102 -0
- package/dist/constants/formatRules.js.map +7 -0
- package/dist/constants/prompts.js +12 -34
- package/dist/constants/prompts.js.map +2 -2
- package/dist/constants/symbols.js +64 -6
- package/dist/constants/symbols.js.map +2 -2
- package/dist/constants/timing.js +5 -0
- package/dist/constants/timing.js.map +2 -2
- package/dist/core/config/defaults.js +84 -0
- package/dist/core/config/defaults.js.map +7 -0
- package/dist/core/config/index.js +111 -0
- package/dist/core/config/index.js.map +7 -0
- package/dist/core/config/loader.js +221 -0
- package/dist/core/config/loader.js.map +7 -0
- package/dist/core/config/migrations.js +128 -0
- package/dist/core/config/migrations.js.map +7 -0
- package/dist/core/config/schema.js +178 -0
- package/dist/core/config/schema.js.map +7 -0
- package/dist/core/costTracker.js +138 -0
- package/dist/core/costTracker.js.map +7 -0
- package/dist/core/index.js +5 -0
- package/dist/core/index.js.map +7 -0
- package/dist/core/permissions/auditLog.js +204 -0
- package/dist/core/permissions/auditLog.js.map +7 -0
- package/dist/core/permissions/engine/index.js +3 -0
- package/dist/core/permissions/engine/index.js.map +7 -0
- package/dist/core/permissions/engine/permissionEngine.js +106 -0
- package/dist/core/permissions/engine/permissionEngine.js.map +7 -0
- package/dist/core/permissions/engine/types.js +1 -0
- package/dist/core/permissions/engine/types.js.map +7 -0
- package/dist/core/permissions/index.js +84 -0
- package/dist/core/permissions/index.js.map +7 -0
- package/dist/core/permissions/ruleEngine.js +259 -0
- package/dist/core/permissions/ruleEngine.js.map +7 -0
- package/dist/core/permissions/rules/allowedToolsRule.js +62 -0
- package/dist/core/permissions/rules/allowedToolsRule.js.map +7 -0
- package/dist/core/permissions/rules/autoEscalationRule.js +291 -0
- package/dist/core/permissions/rules/autoEscalationRule.js.map +7 -0
- package/dist/core/permissions/rules/index.js +46 -0
- package/dist/core/permissions/rules/index.js.map +7 -0
- package/dist/core/permissions/rules/planModeRule.js +55 -0
- package/dist/core/permissions/rules/planModeRule.js.map +7 -0
- package/dist/core/permissions/rules/projectBoundaryRule.js +168 -0
- package/dist/core/permissions/rules/projectBoundaryRule.js.map +7 -0
- package/dist/core/permissions/rules/safeModeRule.js +65 -0
- package/dist/core/permissions/rules/safeModeRule.js.map +7 -0
- package/dist/core/permissions/rules/sensitivePathsRule.js +340 -0
- package/dist/core/permissions/rules/sensitivePathsRule.js.map +7 -0
- package/dist/core/permissions/types.js +127 -0
- package/dist/core/permissions/types.js.map +7 -0
- package/dist/core/tools/executor.js +143 -0
- package/dist/core/tools/executor.js.map +7 -0
- package/dist/core/tools/index.js +15 -0
- package/dist/core/tools/index.js.map +7 -0
- package/dist/core/tools/registry.js +183 -0
- package/dist/core/tools/registry.js.map +7 -0
- package/dist/core/tools/types.js +1 -0
- package/dist/core/tools/types.js.map +7 -0
- package/dist/cost-tracker.js +23 -15
- package/dist/cost-tracker.js.map +2 -2
- package/dist/entrypoints/cli.js +43 -43
- package/dist/entrypoints/cli.js.map +2 -2
- package/dist/entrypoints/mcp.js +12 -4
- package/dist/entrypoints/mcp.js.map +2 -2
- package/dist/history.js +14 -3
- package/dist/history.js.map +2 -2
- package/dist/hooks/useAgentTranscripts.js +116 -0
- package/dist/hooks/useAgentTranscripts.js.map +7 -0
- package/dist/hooks/useAnimationSync.js +53 -0
- package/dist/hooks/useAnimationSync.js.map +7 -0
- package/dist/hooks/useArrowKeyHistory.js +4 -2
- package/dist/hooks/useArrowKeyHistory.js.map +2 -2
- package/dist/hooks/useCanUseTool.js +3 -1
- package/dist/hooks/useCanUseTool.js.map +2 -2
- package/dist/hooks/useCancelRequest.js +4 -1
- package/dist/hooks/useCancelRequest.js.map +2 -2
- package/dist/hooks/useExitOnCtrlCD.js +9 -5
- package/dist/hooks/useExitOnCtrlCD.js.map +2 -2
- package/dist/hooks/useHookStatus.js +40 -0
- package/dist/hooks/useHookStatus.js.map +7 -0
- package/dist/hooks/useLogMessages.js +17 -1
- package/dist/hooks/useLogMessages.js.map +2 -2
- package/dist/hooks/useMessageGroups.js +43 -0
- package/dist/hooks/useMessageGroups.js.map +7 -0
- package/dist/hooks/useTerminalSize.js +62 -6
- package/dist/hooks/useTerminalSize.js.map +2 -2
- package/dist/hooks/useUnifiedCompletion.js +69 -0
- package/dist/hooks/useUnifiedCompletion.js.map +2 -2
- package/dist/i18n/index.js +109 -0
- package/dist/i18n/index.js.map +7 -0
- package/dist/i18n/locales/en.js +347 -0
- package/dist/i18n/locales/en.js.map +7 -0
- package/dist/i18n/locales/index.js +7 -0
- package/dist/i18n/locales/index.js.map +7 -0
- package/dist/i18n/locales/zh-CN.js +347 -0
- package/dist/i18n/locales/zh-CN.js.map +7 -0
- package/dist/i18n/types.js +8 -0
- package/dist/i18n/types.js.map +7 -0
- package/dist/query.js +175 -17
- package/dist/query.js.map +3 -3
- package/dist/screens/REPL.js +501 -192
- package/dist/screens/REPL.js.map +3 -3
- package/dist/services/adapters/chatCompletions.js +3 -1
- package/dist/services/adapters/chatCompletions.js.map +2 -2
- package/dist/services/adapters/messageNormalizer.js +354 -0
- package/dist/services/adapters/messageNormalizer.js.map +7 -0
- package/dist/services/adapters/responsesAPI.js +6 -3
- package/dist/services/adapters/responsesAPI.js.map +2 -2
- package/dist/services/checkpointManager.js +386 -0
- package/dist/services/checkpointManager.js.map +7 -0
- package/dist/services/claude.js +138 -11
- package/dist/services/claude.js.map +3 -3
- package/dist/services/compressionService.js +50 -1
- package/dist/services/compressionService.js.map +2 -2
- package/dist/services/contextMonitor.js +162 -0
- package/dist/services/contextMonitor.js.map +7 -0
- package/dist/services/customCommands.js +60 -41
- package/dist/services/customCommands.js.map +2 -2
- package/dist/services/hookExecutor.js +173 -1
- package/dist/services/hookExecutor.js.map +2 -2
- package/dist/services/intelligentCompactor.js +281 -0
- package/dist/services/intelligentCompactor.js.map +7 -0
- package/dist/services/lspConfig.js +109 -0
- package/dist/services/lspConfig.js.map +7 -0
- package/dist/services/mcpClient.js +273 -34
- package/dist/services/mcpClient.js.map +2 -2
- package/dist/services/modelOrchestrator.js +310 -0
- package/dist/services/modelOrchestrator.js.map +7 -0
- package/dist/services/openai.js +8 -1
- package/dist/services/openai.js.map +2 -2
- package/dist/services/outputStyles.js +138 -0
- package/dist/services/outputStyles.js.map +7 -0
- package/dist/services/plugins/index.js +5 -0
- package/dist/services/plugins/index.js.map +7 -0
- package/dist/services/plugins/lspServers.js +188 -0
- package/dist/services/plugins/lspServers.js.map +7 -0
- package/dist/services/plugins/pluginRuntime.js +229 -0
- package/dist/services/plugins/pluginRuntime.js.map +7 -0
- package/dist/services/plugins/pluginValidation.js +219 -0
- package/dist/services/plugins/pluginValidation.js.map +7 -0
- package/dist/services/plugins/skillMarketplace.js +556 -0
- package/dist/services/plugins/skillMarketplace.js.map +7 -0
- package/dist/services/responseStateManager.js +37 -3
- package/dist/services/responseStateManager.js.map +2 -2
- package/dist/services/sandbox/filesystemBoundary.js +300 -0
- package/dist/services/sandbox/filesystemBoundary.js.map +7 -0
- package/dist/services/sandbox/index.js +14 -0
- package/dist/services/sandbox/index.js.map +7 -0
- package/dist/services/sandbox/networkProxy.js +293 -0
- package/dist/services/sandbox/networkProxy.js.map +7 -0
- package/dist/services/sandbox/sandboxController.js +574 -0
- package/dist/services/sandbox/sandboxController.js.map +7 -0
- package/dist/services/sandbox/types.js +50 -0
- package/dist/services/sandbox/types.js.map +7 -0
- package/dist/services/sessionMemory.js +266 -0
- package/dist/services/sessionMemory.js.map +7 -0
- package/dist/services/taskRouter.js +324 -0
- package/dist/services/taskRouter.js.map +7 -0
- package/dist/tools/ArchitectTool/ArchitectTool.js +10 -3
- package/dist/tools/ArchitectTool/ArchitectTool.js.map +2 -2
- package/dist/tools/AskExpertModelTool/AskExpertModelTool.js +3 -0
- package/dist/tools/AskExpertModelTool/AskExpertModelTool.js.map +2 -2
- package/dist/tools/AskUserQuestionTool/AskUserQuestionTool.js +8 -1
- package/dist/tools/AskUserQuestionTool/AskUserQuestionTool.js.map +2 -2
- package/dist/tools/BaseTool.js +72 -0
- package/dist/tools/BaseTool.js.map +7 -0
- package/dist/tools/BashOutputTool/BashOutputToolResultMessage.js +3 -0
- package/dist/tools/BashOutputTool/BashOutputToolResultMessage.js.map +2 -2
- package/dist/tools/BashTool/BashTool.js +60 -3
- package/dist/tools/BashTool/BashTool.js.map +2 -2
- package/dist/tools/BashTool/BashToolResultMessage.js +3 -0
- package/dist/tools/BashTool/BashToolResultMessage.js.map +2 -2
- package/dist/tools/BashTool/OutputLine.js +54 -0
- package/dist/tools/BashTool/OutputLine.js.map +2 -2
- package/dist/tools/BashTool/prompt.js +192 -3
- package/dist/tools/BashTool/prompt.js.map +2 -2
- package/dist/tools/FileEditTool/FileEditTool.js +29 -4
- package/dist/tools/FileEditTool/FileEditTool.js.map +2 -2
- package/dist/tools/FileReadTool/FileReadTool.js +23 -4
- package/dist/tools/FileReadTool/FileReadTool.js.map +2 -2
- package/dist/tools/FileWriteTool/FileWriteTool.js +5 -5
- package/dist/tools/FileWriteTool/FileWriteTool.js.map +2 -2
- package/dist/tools/GlobTool/GlobTool.js +14 -3
- package/dist/tools/GlobTool/GlobTool.js.map +2 -2
- package/dist/tools/GrepTool/GrepTool.js +41 -7
- package/dist/tools/GrepTool/GrepTool.js.map +2 -2
- package/dist/tools/KillShellTool/KillShellToolResultMessage.js +3 -0
- package/dist/tools/KillShellTool/KillShellToolResultMessage.js.map +2 -2
- package/dist/tools/ListMcpResourcesTool/ListMcpResourcesTool.js +109 -0
- package/dist/tools/ListMcpResourcesTool/ListMcpResourcesTool.js.map +7 -0
- package/dist/tools/ListMcpResourcesTool/prompt.js +19 -0
- package/dist/tools/ListMcpResourcesTool/prompt.js.map +7 -0
- package/dist/tools/LspTool/LspTool.js +664 -0
- package/dist/tools/LspTool/LspTool.js.map +7 -0
- package/dist/tools/LspTool/prompt.js +27 -0
- package/dist/tools/LspTool/prompt.js.map +7 -0
- package/dist/tools/MCPTool/MCPTool.js +11 -4
- package/dist/tools/MCPTool/MCPTool.js.map +2 -2
- package/dist/tools/MemoryReadTool/MemoryReadTool.js +19 -6
- package/dist/tools/MemoryReadTool/MemoryReadTool.js.map +2 -2
- package/dist/tools/MemoryWriteTool/MemoryWriteTool.js +6 -6
- package/dist/tools/MemoryWriteTool/MemoryWriteTool.js.map +2 -2
- package/dist/tools/MultiEditTool/MultiEditTool.js +19 -2
- package/dist/tools/MultiEditTool/MultiEditTool.js.map +2 -2
- package/dist/tools/NotebookEditTool/NotebookEditTool.js +5 -1
- package/dist/tools/NotebookEditTool/NotebookEditTool.js.map +2 -2
- package/dist/tools/NotebookReadTool/NotebookReadTool.js +8 -4
- package/dist/tools/NotebookReadTool/NotebookReadTool.js.map +2 -2
- package/dist/tools/PlanModeTool/EnterPlanModeTool.js +74 -0
- package/dist/tools/PlanModeTool/EnterPlanModeTool.js.map +7 -0
- package/dist/tools/PlanModeTool/ExitPlanModeTool.js +108 -0
- package/dist/tools/PlanModeTool/ExitPlanModeTool.js.map +7 -0
- package/dist/tools/PlanModeTool/prompt.js +94 -0
- package/dist/tools/PlanModeTool/prompt.js.map +7 -0
- package/dist/tools/ReadMcpResourceTool/ReadMcpResourceTool.js +130 -0
- package/dist/tools/ReadMcpResourceTool/ReadMcpResourceTool.js.map +7 -0
- package/dist/tools/ReadMcpResourceTool/prompt.js +17 -0
- package/dist/tools/ReadMcpResourceTool/prompt.js.map +7 -0
- package/dist/tools/SkillTool/SkillTool.js +14 -3
- package/dist/tools/SkillTool/SkillTool.js.map +2 -2
- package/dist/tools/SlashCommandTool/SlashCommandTool.js +260 -0
- package/dist/tools/SlashCommandTool/SlashCommandTool.js.map +7 -0
- package/dist/tools/SlashCommandTool/prompt.js +35 -0
- package/dist/tools/SlashCommandTool/prompt.js.map +7 -0
- package/dist/tools/TaskOutputTool/TaskOutputTool.js +189 -0
- package/dist/tools/TaskOutputTool/TaskOutputTool.js.map +7 -0
- package/dist/tools/TaskOutputTool/prompt.js +15 -0
- package/dist/tools/TaskOutputTool/prompt.js.map +7 -0
- package/dist/tools/TaskTool/TaskTool.js +321 -146
- package/dist/tools/TaskTool/TaskTool.js.map +2 -2
- package/dist/tools/TaskTool/prompt.js.map +2 -2
- package/dist/tools/TodoWriteTool/TodoWriteTool.js +42 -73
- package/dist/tools/TodoWriteTool/TodoWriteTool.js.map +2 -2
- package/dist/tools/URLFetcherTool/URLFetcherTool.js +7 -1
- package/dist/tools/URLFetcherTool/URLFetcherTool.js.map +2 -2
- package/dist/tools/URLFetcherTool/cache.js +55 -8
- package/dist/tools/URLFetcherTool/cache.js.map +2 -2
- package/dist/tools/WebSearchTool/WebSearchTool.js +6 -1
- package/dist/tools/WebSearchTool/WebSearchTool.js.map +2 -2
- package/dist/tools.js +31 -2
- package/dist/tools.js.map +2 -2
- package/dist/types/hooks.js +4 -0
- package/dist/types/hooks.js.map +2 -2
- package/dist/types/marketplace.js.map +2 -2
- package/dist/types/messageGroup.js +36 -0
- package/dist/types/messageGroup.js.map +7 -0
- package/dist/types/plugin.js.map +2 -2
- package/dist/types/thinking.js +1 -0
- package/dist/types/thinking.js.map +7 -0
- package/dist/utils/BackgroundShellManager.js +136 -39
- package/dist/utils/BackgroundShellManager.js.map +2 -2
- package/dist/utils/MessageBatchBuffer.js +102 -0
- package/dist/utils/MessageBatchBuffer.js.map +7 -0
- package/dist/utils/PersistentShell.js +151 -1
- package/dist/utils/PersistentShell.js.map +2 -2
- package/dist/utils/agentLoader.js +1 -23
- package/dist/utils/agentLoader.js.map +2 -2
- package/dist/utils/agentTranscripts.js +641 -0
- package/dist/utils/agentTranscripts.js.map +7 -0
- package/dist/utils/animationManager.js +213 -0
- package/dist/utils/animationManager.js.map +7 -0
- package/dist/utils/animationSync.js +110 -0
- package/dist/utils/animationSync.js.map +7 -0
- package/dist/utils/asyncFile.js +215 -0
- package/dist/utils/asyncFile.js.map +7 -0
- package/dist/utils/backgroundAgentManager.js +231 -0
- package/dist/utils/backgroundAgentManager.js.map +7 -0
- package/dist/utils/config.js +63 -7
- package/dist/utils/config.js.map +2 -2
- package/dist/utils/conversationRecovery.js +19 -0
- package/dist/utils/conversationRecovery.js.map +2 -2
- package/dist/utils/exit.js +73 -0
- package/dist/utils/exit.js.map +7 -0
- package/dist/utils/format.js +73 -5
- package/dist/utils/format.js.map +2 -2
- package/dist/utils/generators.js +76 -6
- package/dist/utils/generators.js.map +2 -2
- package/dist/utils/globalErrorHandler.js +149 -0
- package/dist/utils/globalErrorHandler.js.map +7 -0
- package/dist/utils/groupHandlers/index.js +8 -0
- package/dist/utils/groupHandlers/index.js.map +7 -0
- package/dist/utils/groupHandlers/parallelTasksHandler.js +140 -0
- package/dist/utils/groupHandlers/parallelTasksHandler.js.map +7 -0
- package/dist/utils/groupHandlers/taskHandler.js +104 -0
- package/dist/utils/groupHandlers/taskHandler.js.map +7 -0
- package/dist/utils/groupHandlers/types.js +1 -0
- package/dist/utils/groupHandlers/types.js.map +7 -0
- package/dist/utils/logRotation.js +224 -0
- package/dist/utils/logRotation.js.map +7 -0
- package/dist/utils/marketplaceManager.js +3 -5
- package/dist/utils/marketplaceManager.js.map +2 -2
- package/dist/utils/memSafety.js +264 -0
- package/dist/utils/memSafety.js.map +7 -0
- package/dist/utils/messageGroupManager.js +274 -0
- package/dist/utils/messageGroupManager.js.map +7 -0
- package/dist/utils/messages.js +13 -4
- package/dist/utils/messages.js.map +2 -2
- package/dist/utils/model.js +119 -15
- package/dist/utils/model.js.map +3 -3
- package/dist/utils/permissions/filesystem.js +157 -5
- package/dist/utils/permissions/filesystem.js.map +2 -2
- package/dist/utils/plan/planMode.js +143 -0
- package/dist/utils/plan/planMode.js.map +7 -0
- package/dist/utils/pluginLoader.js +17 -21
- package/dist/utils/pluginLoader.js.map +2 -2
- package/dist/utils/ripgrep.js +55 -2
- package/dist/utils/ripgrep.js.map +2 -2
- package/dist/utils/sanitizeInput.js +32 -0
- package/dist/utils/sanitizeInput.js.map +7 -0
- package/dist/utils/secureKeyStorage.js +312 -0
- package/dist/utils/secureKeyStorage.js.map +7 -0
- package/dist/utils/session/sessionPlugins.js +67 -0
- package/dist/utils/session/sessionPlugins.js.map +7 -0
- package/dist/utils/taskDisplayUtils.js +257 -0
- package/dist/utils/taskDisplayUtils.js.map +7 -0
- package/dist/utils/teamConfig.js +2 -1
- package/dist/utils/teamConfig.js.map +2 -2
- package/dist/utils/todoStorage.js +92 -2
- package/dist/utils/todoStorage.js.map +2 -2
- package/dist/utils/toolTimeout.js +136 -0
- package/dist/utils/toolTimeout.js.map +7 -0
- package/dist/utils/tooling/safeRender.js +115 -0
- package/dist/utils/tooling/safeRender.js.map +7 -0
- package/dist/utils/userFriendlyError.js +346 -0
- package/dist/utils/userFriendlyError.js.map +7 -0
- package/dist/utils/vendor/ripgrep/arm64-darwin/rg +0 -0
- package/dist/version.js +2 -2
- package/dist/version.js.map +1 -1
- package/package.json +14 -4
- package/scripts/postinstall.js +128 -38
- package/dist/commands/agents.js +0 -2086
- package/dist/commands/agents.js.map +0 -7
- package/dist/commands/build.js +0 -74
- package/dist/commands/build.js.map +0 -7
- package/dist/commands/compression.js +0 -57
- package/dist/commands/compression.js.map +0 -7
- package/dist/commands/listen.js +0 -37
- package/dist/commands/listen.js.map +0 -7
- package/dist/commands/login.js +0 -37
- package/dist/commands/login.js.map +0 -7
- package/dist/commands/logout.js +0 -33
- package/dist/commands/logout.js.map +0 -7
- package/dist/commands/mcp.js +0 -40
- package/dist/commands/mcp.js.map +0 -7
- package/dist/commands/mcp_refresh.js +0 -40
- package/dist/commands/mcp_refresh.js.map +0 -7
- package/dist/commands/modelstatus.js +0 -21
- package/dist/commands/modelstatus.js.map +0 -7
- package/dist/commands/onboarding.js +0 -36
- package/dist/commands/onboarding.js.map +0 -7
- package/dist/commands/plugin-interactive.js +0 -446
- package/dist/commands/plugin-interactive.js.map +0 -7
- package/dist/commands/pr_comments.js +0 -61
- package/dist/commands/pr_comments.js.map +0 -7
- package/dist/commands/release-notes.js +0 -30
- package/dist/commands/release-notes.js.map +0 -7
- package/dist/commands/review.js +0 -51
- package/dist/commands/review.js.map +0 -7
- package/dist/components/Bug.js +0 -147
- package/dist/components/Bug.js.map +0 -7
- package/dist/components/ModelSelector.js +0 -2062
- package/dist/components/ModelSelector.js.map +0 -7
- package/dist/components/ModelStatusDisplay.js +0 -87
- package/dist/components/ModelStatusDisplay.js.map +0 -7
- package/dist/entrypoints/cli-wrapper.js +0 -61
- package/dist/entrypoints/cli-wrapper.js.map +0 -7
- package/dist/screens/Doctor.js +0 -22
- package/dist/screens/Doctor.js.map +0 -7
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/customCommands.ts"],
|
|
4
|
-
"sourcesContent": ["import { existsSync, readFileSync } from 'fs'\nimport { join } from 'path'\nimport { homedir } from 'os'\nimport { memoize } from 'lodash-es'\nimport type { MessageParam } from '@anthropic-ai/sdk/resources/index.mjs'\nimport type { Command } from '@commands'\nimport { getCwd } from '@utils/state'\nimport { execFile } from 'child_process'\nimport { promisify } from 'util'\nimport { loadAllPlugins } from '@utils/pluginLoader'\nimport type { LoadedPlugin, LoadedCommand } from '../types/plugin'\n\nconst execFileAsync = promisify(execFile)\n\n/**\n * Execute bash commands found in custom command content using !`command` syntax\n *\n * This function processes dynamic command execution within custom commands,\n * following the same security model as the main BashTool but with restricted scope.\n * Commands are executed in the current working directory with a timeout.\n *\n * @param content - The custom command content to process\n * @returns Promise<string> - Content with bash commands replaced by their output\n */\nexport async function executeBashCommands(content: string): Promise<string> {\n // Match patterns like !`git status` or !`command here`\n const bashCommandRegex = /!\\`([^`]+)\\`/g\n const matches = [...content.matchAll(bashCommandRegex)]\n\n if (matches.length === 0) {\n return content\n }\n\n let result = content\n\n for (const match of matches) {\n const fullMatch = match[0]\n const command = match[1].trim()\n\n try {\n // Parse command and args using simple shell parsing\n // This mirrors the approach used in the main BashTool but with stricter limits\n const parts = command.split(/\\s+/)\n const cmd = parts[0]\n const args = parts.slice(1)\n\n // Execute with conservative timeout (5s vs BashTool's 2min default)\n const { stdout, stderr } = await execFileAsync(cmd, args, {\n timeout: 5000,\n encoding: 'utf8',\n cwd: getCwd(), // Use current working directory for consistency\n })\n\n // Replace the bash command with its output, preferring stdout\n const output = stdout.trim() || stderr.trim() || '(no output)'\n result = result.replace(fullMatch, output)\n } catch (error) {\n console.warn(`Failed to execute bash command \"${command}\":`, error)\n result = result.replace(fullMatch, `(error executing: ${command})`)\n }\n }\n\n return result\n}\n\n/**\n * Resolve file references using @filepath syntax within custom commands\n *\n * This function implements file inclusion for custom commands, similar to how\n * the FileReadTool works but with inline processing. Files are read from the\n * current working directory and formatted as markdown code blocks.\n *\n * Security note: Files are read with the same permissions as the main process,\n * following the same security model as other file operations in the system.\n *\n * @param content - The custom command content to process\n * @returns Promise<string> - Content with file references replaced by file contents\n */\nexport async function resolveFileReferences(content: string): Promise<string> {\n // Match patterns like @src/file.js or @path/to/file.txt\n // Use consistent file mention pattern from mentionProcessor\n // Exclude agent and ask-model patterns to avoid conflicts\n const fileRefRegex = /@([a-zA-Z0-9/._-]+(?:\\.[a-zA-Z0-9]+)?)/g\n const matches = [...content.matchAll(fileRefRegex)]\n\n if (matches.length === 0) {\n return content\n }\n\n let result = content\n\n for (const match of matches) {\n const fullMatch = match[0]\n const filePath = match[1]\n\n // Skip agent mentions - these are handled by the mention processor\n if (filePath.startsWith('agent-')) {\n continue\n }\n\n try {\n // Resolve relative to current working directory\n // This maintains consistency with how other file operations work\n const fullPath = join(getCwd(), filePath)\n\n if (existsSync(fullPath)) {\n const fileContent = readFileSync(fullPath, { encoding: 'utf-8' })\n\n // Format file content with filename header for clarity\n // This matches the format used by FileReadTool for consistency\n const formattedContent = `\\n\\n## File: ${filePath}\\n\\`\\`\\`\\n${fileContent}\\n\\`\\`\\`\\n`\n result = result.replace(fullMatch, formattedContent)\n } else {\n result = result.replace(fullMatch, `(file not found: ${filePath})`)\n }\n } catch (error) {\n console.warn(`Failed to read file \"${filePath}\":`, error)\n result = result.replace(fullMatch, `(error reading: ${filePath})`)\n }\n }\n\n return result\n}\n\n/**\n * Validate and process allowed-tools specification from frontmatter\n *\n * This function handles tool restriction specifications in custom commands.\n * Currently it provides logging and validation structure - full enforcement\n * would require deep integration with the tool permission system.\n *\n * Future implementation should connect to src/permissions.ts and the\n * tool execution pipeline to enforce these restrictions.\n *\n * @param allowedTools - Array of tool names from frontmatter\n * @returns boolean - Currently always true, future will return actual validation result\n */\nfunction validateAllowedTools(allowedTools: string[] | undefined): boolean {\n // Log allowed tools for debugging and future integration\n if (allowedTools && allowedTools.length > 0) {\n // TODO: Integrate with src/permissions.ts tool permission system\n // TODO: Connect to Tool.tsx needsPermissions() mechanism\n }\n return true // Allow execution for now - future versions will enforce restrictions\n}\n\n/**\n * Frontmatter configuration for custom commands\n *\n * This interface defines the YAML frontmatter structure that can be used\n * to configure custom commands. It mirrors the Claude Desktop custom command\n * system for compatibility while adding Minto-specific enhancements.\n */\nexport interface CustomCommandFrontmatter {\n /** Display name for the command (overrides filename-based naming) */\n name?: string\n /** Brief description of what the command does */\n description?: string\n /** Alternative names that can be used to invoke this command */\n aliases?: string[]\n /** Whether this command is active and can be executed */\n enabled?: boolean\n /** Whether this command should be hidden from help output */\n hidden?: boolean\n /** Message to display while the command is running */\n progressMessage?: string\n /** Named arguments for legacy {arg} placeholder support */\n argNames?: string[]\n /** Tools that this command is restricted to use */\n 'allowed-tools'?: string[]\n}\n\n/**\n * Extended Command interface with scope information\n *\n * This extends the base Command interface to include scope metadata\n * for distinguishing between user-level and project-level commands.\n */\nexport interface CustomCommandWithScope {\n /** Command type - matches PromptCommand */\n type: 'prompt'\n /** Command name */\n name: string\n /** Command description */\n description: string\n /** Whether command is enabled */\n isEnabled: boolean\n /** Whether command is hidden */\n isHidden: boolean\n /** Command aliases */\n aliases?: string[]\n /** Progress message */\n progressMessage: string\n /** Argument names for legacy support */\n argNames?: string[]\n /** User-facing name function */\n userFacingName(): string\n /** Prompt generation function */\n getPromptForCommand(args: string): Promise<MessageParam[]>\n /** Scope indicates whether this is a user or project command */\n scope?: 'user' | 'project'\n}\n\n/**\n * Parsed custom command file representation\n *\n * This interface represents a fully parsed custom command file with\n * separated frontmatter and content sections.\n */\nexport interface CustomCommandFile {\n /** Parsed frontmatter configuration */\n frontmatter: CustomCommandFrontmatter\n /** Markdown content (without frontmatter) */\n content: string\n /** Absolute path to the source file */\n filePath: string\n}\n\n/**\n * Parse YAML frontmatter from markdown content\n *\n * This function extracts and parses YAML frontmatter from markdown files,\n * supporting the same syntax as Jekyll and other static site generators.\n * It handles basic YAML constructs including strings, booleans, and arrays.\n *\n * The parser is intentionally simple and focused on the specific needs of\n * custom commands rather than being a full YAML parser. Complex YAML features\n * like nested objects, multi-line strings, and advanced syntax are not supported.\n *\n * @param content - Raw markdown content with optional frontmatter\n * @returns Object containing parsed frontmatter and remaining content\n */\nexport function parseFrontmatter(content: string): {\n frontmatter: CustomCommandFrontmatter\n content: string\n} {\n const frontmatterRegex = /^---\\s*\\n([\\s\\S]*?)---\\s*\\n?/\n const match = content.match(frontmatterRegex)\n\n if (!match) {\n return { frontmatter: {}, content }\n }\n\n const yamlContent = match[1] || ''\n const markdownContent = content.slice(match[0].length)\n const frontmatter: CustomCommandFrontmatter = {}\n\n // Simple YAML parser for basic key-value pairs and arrays\n // This handles the subset of YAML needed for custom command configuration\n const lines = yamlContent.split('\\n')\n let currentKey: string | null = null\n let arrayItems: string[] = []\n let inArray = false\n\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed || trimmed.startsWith('#')) continue\n\n // Handle array item continuation (- item)\n if (inArray && trimmed.startsWith('-')) {\n const item = trimmed.slice(1).trim().replace(/['\"]/g, '')\n arrayItems.push(item)\n continue\n }\n\n // End array processing when we hit a new key\n if (inArray && trimmed.includes(':')) {\n if (currentKey) {\n ;(frontmatter as any)[currentKey] = arrayItems\n }\n inArray = false\n arrayItems = []\n currentKey = null\n }\n\n const colonIndex = trimmed.indexOf(':')\n if (colonIndex === -1) continue\n\n const key = trimmed.slice(0, colonIndex).trim()\n const value = trimmed.slice(colonIndex + 1).trim()\n\n // Handle inline arrays [item1, item2]\n if (value.startsWith('[') && value.endsWith(']')) {\n const items = value\n .slice(1, -1)\n .split(',')\n .map(s => s.trim().replace(/['\"]/g, ''))\n .filter(s => s.length > 0)\n ;(frontmatter as any)[key] = items\n }\n // Handle multi-line arrays (value is empty or [])\n else if (value === '' || value === '[]') {\n currentKey = key\n inArray = true\n arrayItems = []\n }\n // Handle boolean values\n else if (value === 'true' || value === 'false') {\n ;(frontmatter as any)[key] = value === 'true'\n }\n // Handle string values (remove quotes)\n else {\n ;(frontmatter as any)[key] = value.replace(/['\"]/g, '')\n }\n }\n\n // Handle final array if we ended in array mode\n if (inArray && currentKey) {\n ;(frontmatter as any)[currentKey] = arrayItems\n }\n\n return { frontmatter, content: markdownContent }\n}\n\n/**\n * Scan directory for markdown files using find command\n *\n * This function discovers .md files in the specified directory using the\n * system's find command. It's designed as a fallback when ripgrep is not\n * available, providing the same functionality with broader compatibility.\n *\n * The function includes timeout and signal handling for robustness,\n * especially important when scanning large directory trees.\n *\n * @param args - Legacy parameter for ripgrep compatibility (ignored)\n * @param directory - Directory to scan for markdown files\n * @param signal - AbortSignal for cancellation support\n * @returns Promise<string[]> - Array of absolute paths to .md files\n */\nasync function scanMarkdownFiles(\n args: string[], // Legacy parameter for ripgrep compatibility\n directory: string,\n signal: AbortSignal,\n): Promise<string[]> {\n try {\n // Use find command as fallback since ripgrep may not be available\n // This provides broader compatibility across different systems\n const { stdout } = await execFileAsync(\n 'find',\n [directory, '-name', '*.md', '-type', 'f'],\n { signal, timeout: 3000 },\n )\n return stdout\n .trim()\n .split('\\n')\n .filter(line => line.length > 0)\n } catch (error) {\n // If find fails or directory doesn't exist, return empty array\n // This ensures graceful degradation when directories are missing\n return []\n }\n}\n\n/**\n * Create a Command object from custom command file data\n *\n * This function transforms parsed custom command data into a Command object\n * that integrates with the main command system. It handles naming, scoping,\n * and prompt generation according to the project's command patterns.\n *\n * Command naming follows a hierarchical structure:\n * - Project commands: \"project:namespace:command\"\n * - User commands: \"user:namespace:command\"\n * - Namespace is derived from directory structure\n *\n * @param frontmatter - Parsed frontmatter configuration\n * @param content - Markdown content of the command\n * @param filePath - Absolute path to the command file\n * @param baseDir - Base directory for scope determination\n * @returns CustomCommandWithScope | null - Processed command or null if invalid\n */\nfunction createCustomCommand(\n frontmatter: CustomCommandFrontmatter,\n content: string,\n filePath: string,\n baseDir: string,\n): CustomCommandWithScope | null {\n // Extract command name with namespace support\n const relativePath = filePath.replace(baseDir + '/', '')\n const pathParts = relativePath.split('/')\n const fileName = pathParts[pathParts.length - 1].replace('.md', '')\n\n // Determine scope based on directory location\n // This follows the same pattern as Claude Desktop's command system\n const userClaudeDir = join(homedir(), '.claude', 'commands')\n const userMintoDir = join(homedir(), '.minto', 'commands')\n const scope: 'user' | 'project' =\n baseDir === userClaudeDir || baseDir === userMintoDir ? 'user' : 'project'\n const prefix = scope === 'user' ? 'user' : 'project'\n\n // Create proper command name with prefix and namespace\n let finalName: string\n if (frontmatter.name) {\n // If frontmatter specifies name, use it but ensure proper prefix\n finalName = frontmatter.name.startsWith(`${prefix}:`)\n ? frontmatter.name\n : `${prefix}:${frontmatter.name}`\n } else {\n // Generate name from file path, supporting directory-based namespacing\n if (pathParts.length > 1) {\n const namespace = pathParts.slice(0, -1).join(':')\n finalName = `${prefix}:${namespace}:${fileName}`\n } else {\n finalName = `${prefix}:${fileName}`\n }\n }\n\n // Extract configuration with sensible defaults\n const description = frontmatter.description || `Custom command: ${finalName}`\n const enabled = frontmatter.enabled !== false // Default to true\n const hidden = frontmatter.hidden === true // Default to false\n const aliases = frontmatter.aliases || []\n const progressMessage =\n frontmatter.progressMessage || `Running ${finalName}...`\n const argNames = frontmatter.argNames\n\n // Validate required fields\n if (!finalName) {\n console.warn(`Custom command file ${filePath} has no name, skipping`)\n return null\n }\n\n // Create the command object following the project's Command interface\n const command: CustomCommandWithScope = {\n type: 'prompt',\n name: finalName,\n description,\n isEnabled: enabled,\n isHidden: hidden,\n aliases,\n progressMessage,\n argNames,\n scope,\n userFacingName(): string {\n return finalName\n },\n async getPromptForCommand(args: string): Promise<MessageParam[]> {\n let prompt = content.trim()\n\n // Process argument substitution following legacy conventions\n // This supports both the official $ARGUMENTS format and legacy {arg} format\n\n // Step 1: Handle $ARGUMENTS placeholder (legacy command format)\n if (prompt.includes('$ARGUMENTS')) {\n prompt = prompt.replace(/\\$ARGUMENTS/g, args || '')\n }\n\n // Step 2: Legacy support for named argument placeholders\n if (argNames && argNames.length > 0) {\n const argValues = args.trim().split(/\\s+/)\n argNames.forEach((argName, index) => {\n const value = argValues[index] || ''\n prompt = prompt.replace(new RegExp(`\\\\{${argName}\\\\}`, 'g'), value)\n })\n }\n\n // Step 3: If args are provided but no placeholders used, append to prompt\n if (\n args.trim() &&\n !prompt.includes('$ARGUMENTS') &&\n (!argNames || argNames.length === 0)\n ) {\n prompt += `\\n\\nAdditional context: ${args}`\n }\n\n // Step 4: Add tool restrictions if specified\n const allowedTools = frontmatter['allowed-tools']\n if (\n allowedTools &&\n Array.isArray(allowedTools) &&\n allowedTools.length > 0\n ) {\n const allowedToolsStr = allowedTools.join(', ')\n prompt += `\\n\\nIMPORTANT: You are restricted to using only these tools: ${allowedToolsStr}. Do not use any other tools even if they might be helpful for the task.`\n }\n\n return [\n {\n role: 'user',\n content: prompt,\n },\n ]\n },\n }\n\n return command\n}\n\n/**\n * Load custom commands from .claude/commands/ directories\n *\n * This function scans both user-level and project-level command directories\n * for markdown files and processes them into Command objects. It follows the\n * same discovery pattern as Claude Desktop but with additional performance\n * optimizations and error handling.\n *\n * Directory structure:\n * - User commands: ~/.claude/commands/\n * - Project commands: {project}/.claude/commands/\n *\n * The function is memoized for performance but includes cache invalidation\n * based on directory contents and timestamps.\n *\n * @returns Promise<CustomCommandWithScope[]> - Array of loaded and enabled commands\n */\nexport const loadCustomCommands = memoize(\n async (): Promise<CustomCommandWithScope[]> => {\n // Support both .claude and .minto directories\n const userClaudeDir = join(homedir(), '.claude', 'commands')\n const projectClaudeDir = join(getCwd(), '.claude', 'commands')\n const userMintoDir = join(homedir(), '.minto', 'commands')\n const projectMintoDir = join(getCwd(), '.minto', 'commands')\n\n // Set up abort controller for timeout handling\n const abortController = new AbortController()\n const timeout = setTimeout(() => abortController.abort(), 3000)\n\n try {\n const startTime = Date.now()\n\n // Scan all four directories for .md files concurrently\n // This pattern matches the async loading used elsewhere in the project\n const [\n projectClaudeFiles,\n userClaudeFiles,\n projectMintoFiles,\n userMintoFiles,\n ] = await Promise.all([\n existsSync(projectClaudeDir)\n ? scanMarkdownFiles(\n ['--files', '--hidden', '--glob', '*.md'], // Legacy args for ripgrep compatibility\n projectClaudeDir,\n abortController.signal,\n )\n : Promise.resolve([]),\n existsSync(userClaudeDir)\n ? scanMarkdownFiles(\n ['--files', '--glob', '*.md'], // Legacy args for ripgrep compatibility\n userClaudeDir,\n abortController.signal,\n )\n : Promise.resolve([]),\n existsSync(projectMintoDir)\n ? scanMarkdownFiles(\n ['--files', '--hidden', '--glob', '*.md'], // Legacy args for ripgrep compatibility\n projectMintoDir,\n abortController.signal,\n )\n : Promise.resolve([]),\n existsSync(userMintoDir)\n ? scanMarkdownFiles(\n ['--files', '--glob', '*.md'], // Legacy args for ripgrep compatibility\n userMintoDir,\n abortController.signal,\n )\n : Promise.resolve([]),\n ])\n\n // Combine files with priority: project > user, minto > claude\n const projectFiles = [...projectMintoFiles, ...projectClaudeFiles]\n const userFiles = [...userMintoFiles, ...userClaudeFiles]\n const allFiles = [...projectFiles, ...userFiles]\n const duration = Date.now() - startTime\n\n // Log performance metrics for monitoring\n // This follows the same pattern as other performance-sensitive operations\n\n // Parse files and create command objects\n const commands: CustomCommandWithScope[] = []\n\n // Process project files first (higher priority)\n for (const filePath of projectFiles) {\n try {\n const content = readFileSync(filePath, { encoding: 'utf-8' })\n const { frontmatter, content: commandContent } =\n parseFrontmatter(content)\n // Determine which base directory this file is from\n const baseDir = filePath.includes('.minto/commands')\n ? projectMintoDir\n : projectClaudeDir\n const command = createCustomCommand(\n frontmatter,\n commandContent,\n filePath,\n baseDir,\n )\n\n if (command) {\n commands.push(command)\n }\n } catch (error) {\n console.warn(`Failed to load custom command from ${filePath}:`, error)\n }\n }\n\n // Process user files second (lower priority)\n for (const filePath of userFiles) {\n try {\n const content = readFileSync(filePath, { encoding: 'utf-8' })\n const { frontmatter, content: commandContent } =\n parseFrontmatter(content)\n // Determine which base directory this file is from\n const baseDir = filePath.includes('.minto/commands')\n ? userMintoDir\n : userClaudeDir\n const command = createCustomCommand(\n frontmatter,\n commandContent,\n filePath,\n baseDir,\n )\n\n if (command) {\n commands.push(command)\n }\n } catch (error) {\n console.warn(`Failed to load custom command from ${filePath}:`, error)\n }\n }\n\n // Filter enabled commands and log results\n const enabledCommands = commands.filter(cmd => cmd.isEnabled)\n\n // Log loading results for debugging and monitoring\n\n return enabledCommands\n } catch (error) {\n console.warn('Failed to load custom commands:', error)\n return []\n } finally {\n clearTimeout(timeout)\n }\n },\n // Memoization resolver based on current working directory and directory state\n // This ensures cache invalidation when directories change\n () => {\n const cwd = getCwd()\n const userClaudeDir = join(homedir(), '.claude', 'commands')\n const projectClaudeDir = join(cwd, '.claude', 'commands')\n const userMintoDir = join(homedir(), '.minto', 'commands')\n const projectMintoDir = join(cwd, '.minto', 'commands')\n\n // Create cache key that includes directory existence and timestamp\n // This provides reasonable cache invalidation without excessive file system checks\n return `${cwd}:${existsSync(userClaudeDir)}:${existsSync(projectClaudeDir)}:${existsSync(userMintoDir)}:${existsSync(projectMintoDir)}:${Math.floor(Date.now() / 60000)}`\n },\n)\n\n/**\n * Clear the custom commands cache to force reload\n *\n * This function invalidates the memoized cache for custom commands,\n * forcing the next invocation to re-scan the filesystem. It's useful\n * when commands are added, removed, or modified during runtime.\n *\n * This follows the same pattern as other cache invalidation functions\n * in the project, such as getCommands.cache.clear().\n */\nexport const reloadCustomCommands = (): void => {\n loadCustomCommands.cache.clear()\n}\n\n/**\n * Get custom command directories for help and diagnostic purposes\n *\n * This function returns the standard directory paths where custom commands\n * are expected to be found. It's used by help systems and diagnostic tools\n * to inform users about the proper directory structure.\n *\n * @returns Object containing user and project command directory paths\n */\nexport function getCustomCommandDirectories(): {\n userClaude: string\n projectClaude: string\n userMinto: string\n projectMinto: string\n} {\n return {\n userClaude: join(homedir(), '.claude', 'commands'),\n projectClaude: join(getCwd(), '.claude', 'commands'),\n userMinto: join(homedir(), '.minto', 'commands'),\n projectMinto: join(getCwd(), '.minto', 'commands'),\n }\n}\n\n/**\n * Check if custom commands are available in either directory\n *\n * This function provides a quick way to determine if custom commands\n * are configured without actually loading them. It's useful for conditional\n * UI elements and feature detection.\n *\n * @returns boolean - True if at least one command directory exists\n */\nexport function hasCustomCommands(): boolean {\n const { userClaude, projectClaude, userMinto, projectMinto } =\n getCustomCommandDirectories()\n return (\n existsSync(userClaude) ||\n existsSync(projectClaude) ||\n existsSync(userMinto) ||\n existsSync(projectMinto)\n )\n}\n\n/**\n * Load commands from installed plugins\n *\n * This function integrates the plugin system with the custom commands system\n * by loading all commands from installed plugins and converting them to the\n * standard Command interface used throughout the application.\n *\n * Commands from plugins are treated similarly to custom commands but with\n * additional metadata to track their source plugin. This enables proper\n * attribution and conflict resolution.\n *\n * Command naming follows the pattern:\n * - Plugin commands: \"plugin:plugin-name:command-name\"\n * - This prevents conflicts with user/project commands\n *\n * @returns Promise<CustomCommandWithScope[]> - Array of loaded plugin commands\n */\nexport const loadPluginCommands = memoize(\n async (): Promise<CustomCommandWithScope[]> => {\n try {\n const startTime = Date.now()\n const plugins = loadAllPlugins()\n const commands: CustomCommandWithScope[] = []\n\n // Process each plugin's commands\n for (const plugin of plugins) {\n if (!plugin.enabled) continue\n\n for (const pluginCommand of plugin.commands) {\n try {\n // Skip disabled commands\n if (pluginCommand.config.enabled === false) continue\n\n // Create fully qualified command name\n const commandName = pluginCommand.config.name || pluginCommand.name\n const qualifiedName = commandName.startsWith('plugin:')\n ? commandName\n : `plugin:${plugin.manifest.name}:${commandName}`\n\n // Convert LoadedCommand to CustomCommandWithScope\n const command: CustomCommandWithScope = {\n type: 'prompt',\n name: qualifiedName,\n description:\n pluginCommand.config.description ||\n `Plugin command from ${plugin.manifest.displayName || plugin.manifest.name}`,\n isEnabled: pluginCommand.config.enabled ?? true,\n isHidden: pluginCommand.config.hidden ?? false,\n aliases: pluginCommand.config.aliases || [],\n progressMessage:\n pluginCommand.config.progressMessage ||\n `Running ${commandName}...`,\n argNames: pluginCommand.config.argNames,\n scope: 'user', // Plugin commands are treated as user-scoped\n userFacingName(): string {\n return qualifiedName\n },\n async getPromptForCommand(args: string): Promise<MessageParam[]> {\n let prompt = pluginCommand.config.content.trim()\n\n // Process argument substitution following same conventions as custom commands\n\n // Step 1: Handle $ARGUMENTS placeholder\n if (prompt.includes('$ARGUMENTS')) {\n prompt = prompt.replace(/\\$ARGUMENTS/g, args || '')\n }\n\n // Step 2: Legacy support for named argument placeholders\n if (\n pluginCommand.config.argNames &&\n pluginCommand.config.argNames.length > 0\n ) {\n const argValues = args.trim().split(/\\s+/)\n pluginCommand.config.argNames.forEach((argName, index) => {\n const value = argValues[index] || ''\n prompt = prompt.replace(\n new RegExp(`\\\\{${argName}\\\\}`, 'g'),\n value,\n )\n })\n }\n\n // Step 3: If args provided but no placeholders, append to prompt\n if (\n args.trim() &&\n !prompt.includes('$ARGUMENTS') &&\n (!pluginCommand.config.argNames ||\n pluginCommand.config.argNames.length === 0)\n ) {\n prompt += `\\n\\nAdditional context: ${args}`\n }\n\n // Step 4: Add tool restrictions if specified\n const allowedTools = pluginCommand.config['allowed-tools']\n if (\n allowedTools &&\n Array.isArray(allowedTools) &&\n allowedTools.length > 0\n ) {\n const allowedToolsStr = allowedTools.join(', ')\n prompt += `\\n\\nIMPORTANT: You are restricted to using only these tools: ${allowedToolsStr}. Do not use any other tools even if they might be helpful for the task.`\n }\n\n // Step 5: Add plugin attribution\n prompt += `\\n\\n---\\n_Command provided by plugin: ${plugin.manifest.displayName || plugin.manifest.name} (${plugin.manifest.version})_`\n\n return [\n {\n role: 'user',\n content: prompt,\n },\n ]\n },\n }\n\n commands.push(command)\n } catch (error) {\n console.warn(\n `Failed to load command ${pluginCommand.name} from plugin ${plugin.manifest.name}:`,\n error,\n )\n }\n }\n }\n\n const duration = Date.now() - startTime\n\n // Log loading results for debugging and monitoring\n\n return commands\n } catch (error) {\n console.warn('Failed to load plugin commands:', error)\n return []\n }\n },\n // Memoization resolver based on current working directory\n // This ensures cache invalidation when plugins might change\n () => {\n const cwd = getCwd()\n // Cache key includes timestamp for periodic refresh (every minute)\n return `${cwd}:${Math.floor(Date.now() / 60000)}`\n },\n)\n\n/**\n * Clear the plugin commands cache to force reload\n *\n * This function invalidates the memoized cache for plugin commands,\n * forcing the next invocation to re-scan installed plugins. It's useful\n * when plugins are installed, removed, or modified during runtime.\n */\nexport const reloadPluginCommands = (): void => {\n loadPluginCommands.cache.clear()\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AACrB,SAAS,eAAe;AACxB,SAAS,eAAe;AAGxB,SAAS,cAAc;AACvB,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,SAAS,sBAAsB;
|
|
4
|
+
"sourcesContent": ["import { existsSync, readFileSync } from 'fs'\nimport { join } from 'path'\nimport { homedir } from 'os'\nimport { memoize } from 'lodash-es'\nimport type { MessageParam } from '@anthropic-ai/sdk/resources/index.mjs'\nimport type { Command } from '@commands'\nimport { getCwd } from '@utils/state'\nimport { execFile } from 'child_process'\nimport { promisify } from 'util'\nimport { loadAllPlugins } from '@utils/pluginLoader'\nimport type { LoadedPlugin, LoadedCommand } from '../types/plugin'\nimport {\n getCurrentProjectConfig,\n saveCurrentProjectConfig,\n} from '@utils/config'\n\nconst execFileAsync = promisify(execFile)\n\n/**\n * Check if a bash command is allowed based on project config permissions\n * This integrates with the same permission system used by BashTool\n */\nfunction isBashCommandAllowed(command: string): boolean {\n const projectConfig = getCurrentProjectConfig()\n const allowedTools = projectConfig?.allowedTools || []\n\n // Check if the command or its prefix is in allowed tools\n const parts = command.split(/\\s+/)\n const baseCommand = parts[0]\n\n // Check exact match\n if (allowedTools.includes(`Bash(${command})`)) {\n return true\n }\n\n // Check base command prefix match\n if (allowedTools.includes(`Bash(${baseCommand}:*)`)) {\n return true\n }\n\n // Safe commands that don't need permission\n const safeCommands = new Set([\n 'git',\n 'ls',\n 'pwd',\n 'date',\n 'which',\n 'echo',\n 'cat',\n 'head',\n 'tail',\n 'wc',\n 'sort',\n 'uniq',\n 'grep',\n 'find',\n 'dirname',\n 'basename',\n ])\n\n if (safeCommands.has(baseCommand)) {\n return true\n }\n\n return false\n}\n\n/**\n * Check if file read is allowed based on project config permissions\n * This integrates with the same permission system used by FileReadTool\n */\nfunction isFileReadAllowed(filePath: string): boolean {\n const projectConfig = getCurrentProjectConfig()\n const allowedTools = projectConfig?.allowedTools || []\n\n // File read is generally allowed - FileReadTool doesn't require permission\n // But we log it for audit purposes\n return true\n}\n\n/**\n * Execute bash commands found in custom command content using !`command` syntax\n *\n * This function processes dynamic command execution within custom commands,\n * following the same security model as the main BashTool but with restricted scope.\n * Commands are executed in the current working directory with a timeout.\n *\n * Security: Commands are checked against the permission system before execution.\n * Only safe commands (git, ls, etc.) or explicitly allowed commands will execute.\n *\n * @param content - The custom command content to process\n * @returns Promise<string> - Content with bash commands replaced by their output\n */\nexport async function executeBashCommands(content: string): Promise<string> {\n // Match patterns like !`git status` or !`command here`\n const bashCommandRegex = /!\\`([^`]+)\\`/g\n const matches = [...content.matchAll(bashCommandRegex)]\n\n if (matches.length === 0) {\n return content\n }\n\n let result = content\n\n for (const match of matches) {\n const fullMatch = match[0]\n const command = match[1].trim()\n\n // Security check: verify command is allowed\n if (!isBashCommandAllowed(command)) {\n console.warn(\n `Custom command bash execution denied: \"${command}\" - not in allowed list`,\n )\n result = result.replace(fullMatch, `(permission denied: ${command})`)\n continue\n }\n\n try {\n // Parse command and args using simple shell parsing\n // This mirrors the approach used in the main BashTool but with stricter limits\n const parts = command.split(/\\s+/)\n const cmd = parts[0]\n const args = parts.slice(1)\n\n // Execute with conservative timeout (5s vs BashTool's 2min default)\n const { stdout, stderr } = await execFileAsync(cmd, args, {\n timeout: 5000,\n encoding: 'utf8',\n cwd: getCwd(), // Use current working directory for consistency\n })\n\n // Replace the bash command with its output, preferring stdout\n const output = stdout.trim() || stderr.trim() || '(no output)'\n result = result.replace(fullMatch, output)\n } catch (error) {\n console.warn(`Failed to execute bash command \"${command}\":`, error)\n result = result.replace(fullMatch, `(error executing: ${command})`)\n }\n }\n\n return result\n}\n\n/**\n * Resolve file references using @filepath syntax within custom commands\n *\n * This function implements file inclusion for custom commands, similar to how\n * the FileReadTool works but with inline processing. Files are read from the\n * current working directory and formatted as markdown code blocks.\n *\n * Security note: Files are read with the same permissions as the main process,\n * following the same security model as other file operations in the system.\n *\n * @param content - The custom command content to process\n * @returns Promise<string> - Content with file references replaced by file contents\n */\nexport async function resolveFileReferences(content: string): Promise<string> {\n // Match patterns like @src/file.js or @path/to/file.txt\n // Use consistent file mention pattern from mentionProcessor\n // Exclude agent and ask-model patterns to avoid conflicts\n const fileRefRegex = /@([a-zA-Z0-9/._-]+(?:\\.[a-zA-Z0-9]+)?)/g\n const matches = [...content.matchAll(fileRefRegex)]\n\n if (matches.length === 0) {\n return content\n }\n\n let result = content\n\n for (const match of matches) {\n const fullMatch = match[0]\n const filePath = match[1]\n\n // Skip agent mentions - these are handled by the mention processor\n if (filePath.startsWith('agent-')) {\n continue\n }\n\n try {\n // Resolve relative to current working directory\n // This maintains consistency with how other file operations work\n const fullPath = join(getCwd(), filePath)\n\n if (existsSync(fullPath)) {\n const fileContent = readFileSync(fullPath, { encoding: 'utf-8' })\n\n // Format file content with filename header for clarity\n // This matches the format used by FileReadTool for consistency\n const formattedContent = `\\n\\n## File: ${filePath}\\n\\`\\`\\`\\n${fileContent}\\n\\`\\`\\`\\n`\n result = result.replace(fullMatch, formattedContent)\n } else {\n result = result.replace(fullMatch, `(file not found: ${filePath})`)\n }\n } catch (error) {\n console.warn(`Failed to read file \"${filePath}\":`, error)\n result = result.replace(fullMatch, `(error reading: ${filePath})`)\n }\n }\n\n return result\n}\n\n/**\n * Validate and process allowed-tools specification from frontmatter\n *\n * This function handles tool restriction specifications in custom commands.\n * When allowed-tools is specified, it adds instructions to the prompt to\n * restrict the assistant to only using those tools.\n *\n * Note: The actual enforcement happens at the prompt level - we instruct the\n * assistant to only use specific tools. This is consistent with how Claude Code\n * handles tool restrictions in agent configurations.\n *\n * @param allowedTools - Array of tool names from frontmatter\n * @returns boolean - True if validation passes\n */\nfunction validateAllowedTools(allowedTools: string[] | undefined): boolean {\n // Validation is always true - the restriction is enforced via prompt injection\n // in getPromptForCommand() which adds the tool restriction text\n return true\n}\n\n/**\n * Frontmatter configuration for custom commands\n *\n * This interface defines the YAML frontmatter structure that can be used\n * to configure custom commands. It mirrors the Claude Desktop custom command\n * system for compatibility while adding Minto-specific enhancements.\n */\nexport interface CustomCommandFrontmatter {\n /** Display name for the command (overrides filename-based naming) */\n name?: string\n /** Brief description of what the command does */\n description?: string\n /** Alternative names that can be used to invoke this command */\n aliases?: string[]\n /** Whether this command is active and can be executed */\n enabled?: boolean\n /** Whether this command should be hidden from help output */\n hidden?: boolean\n /** Message to display while the command is running */\n progressMessage?: string\n /** Named arguments for legacy {arg} placeholder support */\n argNames?: string[]\n /** Tools that this command is restricted to use */\n 'allowed-tools'?: string[]\n}\n\n/**\n * Extended Command interface with scope information\n *\n * This extends the base Command interface to include scope metadata\n * for distinguishing between user-level and project-level commands.\n */\nexport interface CustomCommandWithScope {\n /** Command type - matches PromptCommand */\n type: 'prompt'\n /** Command name */\n name: string\n /** Command description */\n description: string\n /** Whether command is enabled */\n isEnabled: boolean\n /** Whether command is hidden */\n isHidden: boolean\n /** Command aliases */\n aliases?: string[]\n /** Progress message */\n progressMessage: string\n /** Argument names for legacy support */\n argNames?: string[]\n /** User-facing name function */\n userFacingName(): string\n /** Prompt generation function */\n getPromptForCommand(args: string): Promise<MessageParam[]>\n /** Scope indicates whether this is a user or project command */\n scope?: 'user' | 'project'\n}\n\n/**\n * Parsed custom command file representation\n *\n * This interface represents a fully parsed custom command file with\n * separated frontmatter and content sections.\n */\nexport interface CustomCommandFile {\n /** Parsed frontmatter configuration */\n frontmatter: CustomCommandFrontmatter\n /** Markdown content (without frontmatter) */\n content: string\n /** Absolute path to the source file */\n filePath: string\n}\n\n/**\n * Parse YAML frontmatter from markdown content\n *\n * This function extracts and parses YAML frontmatter from markdown files,\n * supporting the same syntax as Jekyll and other static site generators.\n * It handles basic YAML constructs including strings, booleans, and arrays.\n *\n * The parser is intentionally simple and focused on the specific needs of\n * custom commands rather than being a full YAML parser. Complex YAML features\n * like nested objects, multi-line strings, and advanced syntax are not supported.\n *\n * @param content - Raw markdown content with optional frontmatter\n * @returns Object containing parsed frontmatter and remaining content\n */\nexport function parseFrontmatter(content: string): {\n frontmatter: CustomCommandFrontmatter\n content: string\n} {\n const frontmatterRegex = /^---\\s*\\n([\\s\\S]*?)---\\s*\\n?/\n const match = content.match(frontmatterRegex)\n\n if (!match) {\n return { frontmatter: {}, content }\n }\n\n const yamlContent = match[1] || ''\n const markdownContent = content.slice(match[0].length)\n const frontmatter: CustomCommandFrontmatter = {}\n\n // Simple YAML parser for basic key-value pairs and arrays\n // This handles the subset of YAML needed for custom command configuration\n const lines = yamlContent.split('\\n')\n let currentKey: string | null = null\n let arrayItems: string[] = []\n let inArray = false\n\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed || trimmed.startsWith('#')) continue\n\n // Handle array item continuation (- item)\n if (inArray && trimmed.startsWith('-')) {\n const item = trimmed.slice(1).trim().replace(/['\"]/g, '')\n arrayItems.push(item)\n continue\n }\n\n // End array processing when we hit a new key\n if (inArray && trimmed.includes(':')) {\n if (currentKey) {\n ;(frontmatter as any)[currentKey] = arrayItems\n }\n inArray = false\n arrayItems = []\n currentKey = null\n }\n\n const colonIndex = trimmed.indexOf(':')\n if (colonIndex === -1) continue\n\n const key = trimmed.slice(0, colonIndex).trim()\n const value = trimmed.slice(colonIndex + 1).trim()\n\n // Handle inline arrays [item1, item2]\n if (value.startsWith('[') && value.endsWith(']')) {\n const items = value\n .slice(1, -1)\n .split(',')\n .map(s => s.trim().replace(/['\"]/g, ''))\n .filter(s => s.length > 0)\n ;(frontmatter as any)[key] = items\n }\n // Handle multi-line arrays (value is empty or [])\n else if (value === '' || value === '[]') {\n currentKey = key\n inArray = true\n arrayItems = []\n }\n // Handle boolean values\n else if (value === 'true' || value === 'false') {\n ;(frontmatter as any)[key] = value === 'true'\n }\n // Handle string values (remove quotes)\n else {\n ;(frontmatter as any)[key] = value.replace(/['\"]/g, '')\n }\n }\n\n // Handle final array if we ended in array mode\n if (inArray && currentKey) {\n ;(frontmatter as any)[currentKey] = arrayItems\n }\n\n return { frontmatter, content: markdownContent }\n}\n\n/**\n * Scan directory for markdown files using find command\n *\n * This function discovers .md files in the specified directory using the\n * system's find command. It's designed as a fallback when ripgrep is not\n * available, providing the same functionality with broader compatibility.\n *\n * The function includes timeout and signal handling for robustness,\n * especially important when scanning large directory trees.\n *\n * @param args - Legacy parameter for ripgrep compatibility (ignored)\n * @param directory - Directory to scan for markdown files\n * @param signal - AbortSignal for cancellation support\n * @returns Promise<string[]> - Array of absolute paths to .md files\n */\nasync function scanMarkdownFiles(\n args: string[], // Legacy parameter for ripgrep compatibility\n directory: string,\n signal: AbortSignal,\n): Promise<string[]> {\n try {\n // Use find command as fallback since ripgrep may not be available\n // This provides broader compatibility across different systems\n const { stdout } = await execFileAsync(\n 'find',\n [directory, '-name', '*.md', '-type', 'f'],\n { signal, timeout: 3000 },\n )\n return stdout\n .trim()\n .split('\\n')\n .filter(line => line.length > 0)\n } catch (error) {\n // If find fails or directory doesn't exist, return empty array\n // This ensures graceful degradation when directories are missing\n return []\n }\n}\n\n/**\n * Create a Command object from custom command file data\n *\n * This function transforms parsed custom command data into a Command object\n * that integrates with the main command system. It handles naming, scoping,\n * and prompt generation according to the project's command patterns.\n *\n * Command naming follows a hierarchical structure:\n * - Project commands: \"project:namespace:command\"\n * - User commands: \"user:namespace:command\"\n * - Namespace is derived from directory structure\n *\n * @param frontmatter - Parsed frontmatter configuration\n * @param content - Markdown content of the command\n * @param filePath - Absolute path to the command file\n * @param baseDir - Base directory for scope determination\n * @returns CustomCommandWithScope | null - Processed command or null if invalid\n */\nfunction createCustomCommand(\n frontmatter: CustomCommandFrontmatter,\n content: string,\n filePath: string,\n baseDir: string,\n): CustomCommandWithScope | null {\n // Extract command name with namespace support\n const relativePath = filePath.replace(baseDir + '/', '')\n const pathParts = relativePath.split('/')\n const fileName = pathParts[pathParts.length - 1].replace('.md', '')\n\n // Determine scope based on directory location\n const userMintoDir = join(homedir(), '.minto', 'commands')\n const scope: 'user' | 'project' =\n baseDir === userMintoDir ? 'user' : 'project'\n const prefix = scope === 'user' ? 'user' : 'project'\n\n // Create proper command name with prefix and namespace\n let finalName: string\n if (frontmatter.name) {\n // If frontmatter specifies name, use it but ensure proper prefix\n finalName = frontmatter.name.startsWith(`${prefix}:`)\n ? frontmatter.name\n : `${prefix}:${frontmatter.name}`\n } else {\n // Generate name from file path, supporting directory-based namespacing\n if (pathParts.length > 1) {\n const namespace = pathParts.slice(0, -1).join(':')\n finalName = `${prefix}:${namespace}:${fileName}`\n } else {\n finalName = `${prefix}:${fileName}`\n }\n }\n\n // Extract configuration with sensible defaults\n const description = frontmatter.description || `Custom command: ${finalName}`\n const enabled = frontmatter.enabled !== false // Default to true\n const hidden = frontmatter.hidden === true // Default to false\n const aliases = frontmatter.aliases || []\n const progressMessage =\n frontmatter.progressMessage || `Running ${finalName}...`\n const argNames = frontmatter.argNames\n\n // Validate required fields\n if (!finalName) {\n console.warn(`Custom command file ${filePath} has no name, skipping`)\n return null\n }\n\n // Create the command object following the project's Command interface\n const command: CustomCommandWithScope = {\n type: 'prompt',\n name: finalName,\n description,\n isEnabled: enabled,\n isHidden: hidden,\n aliases,\n progressMessage,\n argNames,\n scope,\n userFacingName(): string {\n return finalName\n },\n async getPromptForCommand(args: string): Promise<MessageParam[]> {\n let prompt = content.trim()\n\n // Process argument substitution following legacy conventions\n // This supports both the official $ARGUMENTS format and legacy {arg} format\n\n // Step 1: Handle $ARGUMENTS placeholder (legacy command format)\n if (prompt.includes('$ARGUMENTS')) {\n prompt = prompt.replace(/\\$ARGUMENTS/g, args || '')\n }\n\n // Step 2: Legacy support for named argument placeholders\n if (argNames && argNames.length > 0) {\n const argValues = args.trim().split(/\\s+/)\n argNames.forEach((argName, index) => {\n const value = argValues[index] || ''\n prompt = prompt.replace(new RegExp(`\\\\{${argName}\\\\}`, 'g'), value)\n })\n }\n\n // Step 3: If args are provided but no placeholders used, append to prompt\n if (\n args.trim() &&\n !prompt.includes('$ARGUMENTS') &&\n (!argNames || argNames.length === 0)\n ) {\n prompt += `\\n\\nAdditional context: ${args}`\n }\n\n // Step 4: Add tool restrictions if specified\n const allowedTools = frontmatter['allowed-tools']\n if (\n allowedTools &&\n Array.isArray(allowedTools) &&\n allowedTools.length > 0\n ) {\n const allowedToolsStr = allowedTools.join(', ')\n prompt += `\\n\\nIMPORTANT: You are restricted to using only these tools: ${allowedToolsStr}. Do not use any other tools even if they might be helpful for the task.`\n }\n\n return [\n {\n role: 'user',\n content: prompt,\n },\n ]\n },\n }\n\n return command\n}\n\n/**\n * Load custom commands from .minto/commands/ directories\n *\n * This function scans both user-level and project-level command directories\n * for markdown files and processes them into Command objects.\n *\n * Directory structure:\n * - User commands: ~/.minto/commands/\n * - Project commands: {project}/.minto/commands/\n *\n * The function is memoized for performance but includes cache invalidation\n * based on directory contents and timestamps.\n *\n * @returns Promise<CustomCommandWithScope[]> - Array of loaded and enabled commands\n */\nexport const loadCustomCommands = memoize(\n async (): Promise<CustomCommandWithScope[]> => {\n const userMintoDir = join(homedir(), '.minto', 'commands')\n const projectMintoDir = join(getCwd(), '.minto', 'commands')\n\n // Set up abort controller for timeout handling\n const abortController = new AbortController()\n const timeout = setTimeout(() => abortController.abort(), 3000)\n\n try {\n const startTime = Date.now()\n\n // Scan directories for .md files concurrently\n const [projectMintoFiles, userMintoFiles] = await Promise.all([\n existsSync(projectMintoDir)\n ? scanMarkdownFiles(\n ['--files', '--hidden', '--glob', '*.md'],\n projectMintoDir,\n abortController.signal,\n )\n : Promise.resolve([]),\n existsSync(userMintoDir)\n ? scanMarkdownFiles(\n ['--files', '--glob', '*.md'],\n userMintoDir,\n abortController.signal,\n )\n : Promise.resolve([]),\n ])\n\n // Combine files with priority: project > user\n const projectFiles = [...projectMintoFiles]\n const userFiles = [...userMintoFiles]\n const allFiles = [...projectFiles, ...userFiles]\n const duration = Date.now() - startTime\n\n // Log performance metrics for monitoring\n // This follows the same pattern as other performance-sensitive operations\n\n // Parse files and create command objects\n const commands: CustomCommandWithScope[] = []\n\n // Process project files first (higher priority)\n for (const filePath of projectFiles) {\n try {\n const content = readFileSync(filePath, { encoding: 'utf-8' })\n const { frontmatter, content: commandContent } =\n parseFrontmatter(content)\n const command = createCustomCommand(\n frontmatter,\n commandContent,\n filePath,\n projectMintoDir,\n )\n\n if (command) {\n commands.push(command)\n }\n } catch (error) {\n console.warn(`Failed to load custom command from ${filePath}:`, error)\n }\n }\n\n // Process user files second (lower priority)\n for (const filePath of userFiles) {\n try {\n const content = readFileSync(filePath, { encoding: 'utf-8' })\n const { frontmatter, content: commandContent } =\n parseFrontmatter(content)\n const command = createCustomCommand(\n frontmatter,\n commandContent,\n filePath,\n userMintoDir,\n )\n\n if (command) {\n commands.push(command)\n }\n } catch (error) {\n console.warn(`Failed to load custom command from ${filePath}:`, error)\n }\n }\n\n // Filter enabled commands and log results\n const enabledCommands = commands.filter(cmd => cmd.isEnabled)\n\n // Log loading results for debugging and monitoring\n\n return enabledCommands\n } catch (error) {\n console.warn('Failed to load custom commands:', error)\n return []\n } finally {\n clearTimeout(timeout)\n }\n },\n // Memoization resolver based on current working directory and directory state\n // This ensures cache invalidation when directories change\n () => {\n const cwd = getCwd()\n const userMintoDir = join(homedir(), '.minto', 'commands')\n const projectMintoDir = join(cwd, '.minto', 'commands')\n\n // Create cache key that includes directory existence and timestamp\n // This provides reasonable cache invalidation without excessive file system checks\n return `${cwd}:${existsSync(userMintoDir)}:${existsSync(projectMintoDir)}:${Math.floor(Date.now() / 60000)}`\n },\n)\n\n/**\n * Clear the custom commands cache to force reload\n *\n * This function invalidates the memoized cache for custom commands,\n * forcing the next invocation to re-scan the filesystem. It's useful\n * when commands are added, removed, or modified during runtime.\n *\n * This follows the same pattern as other cache invalidation functions\n * in the project, such as getCommands.cache.clear().\n */\nexport const reloadCustomCommands = (): void => {\n loadCustomCommands.cache.clear()\n}\n\n/**\n * Get custom command directories for help and diagnostic purposes\n *\n * This function returns the standard directory paths where custom commands\n * are expected to be found. It's used by help systems and diagnostic tools\n * to inform users about the proper directory structure.\n *\n * @returns Object containing user and project command directory paths\n */\nexport function getCustomCommandDirectories(): {\n user: string\n project: string\n} {\n return {\n user: join(homedir(), '.minto', 'commands'),\n project: join(getCwd(), '.minto', 'commands'),\n }\n}\n\n/**\n * Check if custom commands are available in either directory\n *\n * This function provides a quick way to determine if custom commands\n * are configured without actually loading them. It's useful for conditional\n * UI elements and feature detection.\n *\n * @returns boolean - True if at least one command directory exists\n */\nexport function hasCustomCommands(): boolean {\n const { user, project } = getCustomCommandDirectories()\n return existsSync(user) || existsSync(project)\n}\n\n/**\n * Load commands from installed plugins\n *\n * This function integrates the plugin system with the custom commands system\n * by loading all commands from installed plugins and converting them to the\n * standard Command interface used throughout the application.\n *\n * Commands from plugins are treated similarly to custom commands but with\n * additional metadata to track their source plugin. This enables proper\n * attribution and conflict resolution.\n *\n * Command naming follows the pattern:\n * - Plugin commands: \"plugin:plugin-name:command-name\"\n * - This prevents conflicts with user/project commands\n *\n * @returns Promise<CustomCommandWithScope[]> - Array of loaded plugin commands\n */\nexport const loadPluginCommands = memoize(\n async (): Promise<CustomCommandWithScope[]> => {\n try {\n const startTime = Date.now()\n const plugins = loadAllPlugins()\n const commands: CustomCommandWithScope[] = []\n\n // Process each plugin's commands\n for (const plugin of plugins) {\n if (!plugin.enabled) continue\n\n for (const pluginCommand of plugin.commands) {\n try {\n // Skip disabled commands\n if (pluginCommand.config.enabled === false) continue\n\n // Create fully qualified command name\n const commandName = pluginCommand.config.name || pluginCommand.name\n const qualifiedName = commandName.startsWith('plugin:')\n ? commandName\n : `plugin:${plugin.manifest.name}:${commandName}`\n\n // Convert LoadedCommand to CustomCommandWithScope\n const command: CustomCommandWithScope = {\n type: 'prompt',\n name: qualifiedName,\n description:\n pluginCommand.config.description ||\n `Plugin command from ${plugin.manifest.displayName || plugin.manifest.name}`,\n isEnabled: pluginCommand.config.enabled ?? true,\n isHidden: pluginCommand.config.hidden ?? false,\n aliases: pluginCommand.config.aliases || [],\n progressMessage:\n pluginCommand.config.progressMessage ||\n `Running ${commandName}...`,\n argNames: pluginCommand.config.argNames,\n scope: 'user', // Plugin commands are treated as user-scoped\n userFacingName(): string {\n return qualifiedName\n },\n async getPromptForCommand(args: string): Promise<MessageParam[]> {\n let prompt = pluginCommand.config.content.trim()\n\n // Process argument substitution following same conventions as custom commands\n\n // Step 1: Handle $ARGUMENTS placeholder\n if (prompt.includes('$ARGUMENTS')) {\n prompt = prompt.replace(/\\$ARGUMENTS/g, args || '')\n }\n\n // Step 2: Legacy support for named argument placeholders\n if (\n pluginCommand.config.argNames &&\n pluginCommand.config.argNames.length > 0\n ) {\n const argValues = args.trim().split(/\\s+/)\n pluginCommand.config.argNames.forEach((argName, index) => {\n const value = argValues[index] || ''\n prompt = prompt.replace(\n new RegExp(`\\\\{${argName}\\\\}`, 'g'),\n value,\n )\n })\n }\n\n // Step 3: If args provided but no placeholders, append to prompt\n if (\n args.trim() &&\n !prompt.includes('$ARGUMENTS') &&\n (!pluginCommand.config.argNames ||\n pluginCommand.config.argNames.length === 0)\n ) {\n prompt += `\\n\\nAdditional context: ${args}`\n }\n\n // Step 4: Add tool restrictions if specified\n const allowedTools = pluginCommand.config['allowed-tools']\n if (\n allowedTools &&\n Array.isArray(allowedTools) &&\n allowedTools.length > 0\n ) {\n const allowedToolsStr = allowedTools.join(', ')\n prompt += `\\n\\nIMPORTANT: You are restricted to using only these tools: ${allowedToolsStr}. Do not use any other tools even if they might be helpful for the task.`\n }\n\n // Step 5: Add plugin attribution\n prompt += `\\n\\n---\\n_Command provided by plugin: ${plugin.manifest.displayName || plugin.manifest.name} (${plugin.manifest.version})_`\n\n return [\n {\n role: 'user',\n content: prompt,\n },\n ]\n },\n }\n\n commands.push(command)\n } catch (error) {\n console.warn(\n `Failed to load command ${pluginCommand.name} from plugin ${plugin.manifest.name}:`,\n error,\n )\n }\n }\n }\n\n const duration = Date.now() - startTime\n\n // Log loading results for debugging and monitoring\n\n return commands\n } catch (error) {\n console.warn('Failed to load plugin commands:', error)\n return []\n }\n },\n // Memoization resolver based on current working directory\n // This ensures cache invalidation when plugins might change\n () => {\n const cwd = getCwd()\n // Cache key includes timestamp for periodic refresh (every minute)\n return `${cwd}:${Math.floor(Date.now() / 60000)}`\n },\n)\n\n/**\n * Clear the plugin commands cache to force reload\n *\n * This function invalidates the memoized cache for plugin commands,\n * forcing the next invocation to re-scan installed plugins. It's useful\n * when plugins are installed, removed, or modified during runtime.\n */\nexport const reloadPluginCommands = (): void => {\n loadPluginCommands.cache.clear()\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AACrB,SAAS,eAAe;AACxB,SAAS,eAAe;AAGxB,SAAS,cAAc;AACvB,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,SAAS,sBAAsB;AAE/B;AAAA,EACE;AAAA,OAEK;AAEP,MAAM,gBAAgB,UAAU,QAAQ;AAMxC,SAAS,qBAAqB,SAA0B;AACtD,QAAM,gBAAgB,wBAAwB;AAC9C,QAAM,eAAe,eAAe,gBAAgB,CAAC;AAGrD,QAAM,QAAQ,QAAQ,MAAM,KAAK;AACjC,QAAM,cAAc,MAAM,CAAC;AAG3B,MAAI,aAAa,SAAS,QAAQ,OAAO,GAAG,GAAG;AAC7C,WAAO;AAAA,EACT;AAGA,MAAI,aAAa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
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { spawn } from "child_process";
|
|
2
|
+
import { EventEmitter } from "events";
|
|
2
3
|
import {
|
|
3
4
|
HookEvent
|
|
4
5
|
} from "../types/hooks.js";
|
|
@@ -10,6 +11,13 @@ const logInfo = (msg) => {
|
|
|
10
11
|
const logDebug = (msg, ...args) => {
|
|
11
12
|
if (process.env.DEBUG) console.log(`[DEBUG] ${msg}`, ...args);
|
|
12
13
|
};
|
|
14
|
+
const hookStatusEmitter = new EventEmitter();
|
|
15
|
+
function formatHookStatusMessage(event, toolName, hookName, success, errorMessage) {
|
|
16
|
+
const eventPart = toolName ? `${event}:${toolName}` : event;
|
|
17
|
+
const statusPart = success ? "succeeded" : "failed";
|
|
18
|
+
const detailPart = success ? "Success" : errorMessage || "Error";
|
|
19
|
+
return `${eventPart} hook ${statusPart}: ${detailPart}`;
|
|
20
|
+
}
|
|
13
21
|
async function executeHook(hook, input, options) {
|
|
14
22
|
if (hook.config.type !== "command" || !hook.config.command) {
|
|
15
23
|
return {
|
|
@@ -18,6 +26,7 @@ async function executeHook(hook, input, options) {
|
|
|
18
26
|
};
|
|
19
27
|
}
|
|
20
28
|
const timeout = hook.config.timeout || options.timeout || 3e4;
|
|
29
|
+
const toolName = "tool_name" in input ? input.tool_name : void 0;
|
|
21
30
|
try {
|
|
22
31
|
logDebug(`Executing hook: ${hook.name}`);
|
|
23
32
|
logDebug(`Command: ${hook.config.command}`);
|
|
@@ -28,14 +37,43 @@ async function executeHook(hook, input, options) {
|
|
|
28
37
|
});
|
|
29
38
|
if (result.timedOut) {
|
|
30
39
|
logError(`Hook ${hook.name} timed out after ${timeout}ms`);
|
|
40
|
+
const errorMsg = `Hook execution timed out after ${timeout}ms`;
|
|
41
|
+
hookStatusEmitter.emit("status", {
|
|
42
|
+
event: hook.event,
|
|
43
|
+
toolName,
|
|
44
|
+
success: false,
|
|
45
|
+
message: formatHookStatusMessage(
|
|
46
|
+
hook.event,
|
|
47
|
+
toolName,
|
|
48
|
+
hook.name,
|
|
49
|
+
false,
|
|
50
|
+
errorMsg
|
|
51
|
+
),
|
|
52
|
+
timestamp: Date.now(),
|
|
53
|
+
hookName: hook.name
|
|
54
|
+
});
|
|
31
55
|
return {
|
|
32
56
|
success: false,
|
|
33
57
|
timedOut: true,
|
|
34
|
-
error:
|
|
58
|
+
error: errorMsg
|
|
35
59
|
};
|
|
36
60
|
}
|
|
37
61
|
if (result.error) {
|
|
38
62
|
logError(`Hook ${hook.name} failed: ${result.error}`);
|
|
63
|
+
hookStatusEmitter.emit("status", {
|
|
64
|
+
event: hook.event,
|
|
65
|
+
toolName,
|
|
66
|
+
success: false,
|
|
67
|
+
message: formatHookStatusMessage(
|
|
68
|
+
hook.event,
|
|
69
|
+
toolName,
|
|
70
|
+
hook.name,
|
|
71
|
+
false,
|
|
72
|
+
result.error
|
|
73
|
+
),
|
|
74
|
+
timestamp: Date.now(),
|
|
75
|
+
hookName: hook.name
|
|
76
|
+
});
|
|
39
77
|
return {
|
|
40
78
|
success: false,
|
|
41
79
|
error: result.error
|
|
@@ -43,11 +81,27 @@ async function executeHook(hook, input, options) {
|
|
|
43
81
|
}
|
|
44
82
|
const output = parseHookOutput(result.stdout);
|
|
45
83
|
if (!output) {
|
|
84
|
+
hookStatusEmitter.emit("status", {
|
|
85
|
+
event: hook.event,
|
|
86
|
+
toolName,
|
|
87
|
+
success: true,
|
|
88
|
+
message: formatHookStatusMessage(hook.event, toolName, hook.name, true),
|
|
89
|
+
timestamp: Date.now(),
|
|
90
|
+
hookName: hook.name
|
|
91
|
+
});
|
|
46
92
|
return {
|
|
47
93
|
success: true
|
|
48
94
|
};
|
|
49
95
|
}
|
|
50
96
|
logDebug(`Hook ${hook.name} output:`, output);
|
|
97
|
+
hookStatusEmitter.emit("status", {
|
|
98
|
+
event: hook.event,
|
|
99
|
+
toolName,
|
|
100
|
+
success: true,
|
|
101
|
+
message: formatHookStatusMessage(hook.event, toolName, hook.name, true),
|
|
102
|
+
timestamp: Date.now(),
|
|
103
|
+
hookName: hook.name
|
|
104
|
+
});
|
|
51
105
|
return {
|
|
52
106
|
success: true,
|
|
53
107
|
decision: output.decision,
|
|
@@ -56,6 +110,20 @@ async function executeHook(hook, input, options) {
|
|
|
56
110
|
} catch (error) {
|
|
57
111
|
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
58
112
|
logError(`Hook ${hook.name} execution error: ${errorMsg}`);
|
|
113
|
+
hookStatusEmitter.emit("status", {
|
|
114
|
+
event: hook.event,
|
|
115
|
+
toolName,
|
|
116
|
+
success: false,
|
|
117
|
+
message: formatHookStatusMessage(
|
|
118
|
+
hook.event,
|
|
119
|
+
toolName,
|
|
120
|
+
hook.name,
|
|
121
|
+
false,
|
|
122
|
+
errorMsg
|
|
123
|
+
),
|
|
124
|
+
timestamp: Date.now(),
|
|
125
|
+
hookName: hook.name
|
|
126
|
+
});
|
|
59
127
|
return {
|
|
60
128
|
success: false,
|
|
61
129
|
error: errorMsg
|
|
@@ -259,14 +327,118 @@ function createSessionEndInput(sessionId, transcriptPath, reason) {
|
|
|
259
327
|
reason
|
|
260
328
|
};
|
|
261
329
|
}
|
|
330
|
+
function createPostToolUseFailureInput(sessionId, transcriptPath, toolName, toolInput, error, errorType) {
|
|
331
|
+
return {
|
|
332
|
+
hook_event_name: HookEvent.PostToolUseFailure,
|
|
333
|
+
session_id: sessionId,
|
|
334
|
+
transcript_path: transcriptPath,
|
|
335
|
+
cwd: getCwd(),
|
|
336
|
+
permission_mode: "default",
|
|
337
|
+
tool_name: toolName,
|
|
338
|
+
tool_input: toolInput,
|
|
339
|
+
error,
|
|
340
|
+
error_type: errorType
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
function createPermissionRequestInput(sessionId, transcriptPath, toolName, toolInput, permissionType, description) {
|
|
344
|
+
return {
|
|
345
|
+
hook_event_name: HookEvent.PermissionRequest,
|
|
346
|
+
session_id: sessionId,
|
|
347
|
+
transcript_path: transcriptPath,
|
|
348
|
+
cwd: getCwd(),
|
|
349
|
+
permission_mode: "default",
|
|
350
|
+
tool_name: toolName,
|
|
351
|
+
tool_input: toolInput,
|
|
352
|
+
permission_type: permissionType,
|
|
353
|
+
description
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
function createStopInput(sessionId, transcriptPath, stopHookActive) {
|
|
357
|
+
return {
|
|
358
|
+
hook_event_name: HookEvent.Stop,
|
|
359
|
+
session_id: sessionId,
|
|
360
|
+
transcript_path: transcriptPath,
|
|
361
|
+
cwd: getCwd(),
|
|
362
|
+
permission_mode: "default",
|
|
363
|
+
stop_hook_active: stopHookActive
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
function createSubagentStartInput(sessionId, transcriptPath, agentType, agentDescription, runInBackground) {
|
|
367
|
+
return {
|
|
368
|
+
hook_event_name: HookEvent.SubagentStart,
|
|
369
|
+
session_id: sessionId,
|
|
370
|
+
transcript_path: transcriptPath,
|
|
371
|
+
cwd: getCwd(),
|
|
372
|
+
permission_mode: "default",
|
|
373
|
+
agent_type: agentType,
|
|
374
|
+
agent_description: agentDescription,
|
|
375
|
+
run_in_background: runInBackground
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
function createSubagentStopInput(sessionId, transcriptPath, agentType, agentId, stopHookActive) {
|
|
379
|
+
return {
|
|
380
|
+
hook_event_name: HookEvent.SubagentStop,
|
|
381
|
+
session_id: sessionId,
|
|
382
|
+
transcript_path: transcriptPath,
|
|
383
|
+
cwd: getCwd(),
|
|
384
|
+
permission_mode: "default",
|
|
385
|
+
agent_type: agentType,
|
|
386
|
+
agent_id: agentId,
|
|
387
|
+
stop_hook_active: stopHookActive ?? false
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
function createNotificationInput(sessionId, transcriptPath, message) {
|
|
391
|
+
return {
|
|
392
|
+
hook_event_name: HookEvent.Notification,
|
|
393
|
+
session_id: sessionId,
|
|
394
|
+
transcript_path: transcriptPath,
|
|
395
|
+
cwd: getCwd(),
|
|
396
|
+
permission_mode: "default",
|
|
397
|
+
message
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
function createPreCompactInput(sessionId, transcriptPath, trigger, customInstructions) {
|
|
401
|
+
return {
|
|
402
|
+
hook_event_name: HookEvent.PreCompact,
|
|
403
|
+
session_id: sessionId,
|
|
404
|
+
transcript_path: transcriptPath,
|
|
405
|
+
cwd: getCwd(),
|
|
406
|
+
permission_mode: "default",
|
|
407
|
+
trigger,
|
|
408
|
+
custom_instructions: customInstructions
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
function createPostCompactInput(sessionId, transcriptPath, trigger, summary, compressionRatio, originalTokens, compressedTokens) {
|
|
412
|
+
return {
|
|
413
|
+
hook_event_name: HookEvent.PostCompact,
|
|
414
|
+
session_id: sessionId,
|
|
415
|
+
transcript_path: transcriptPath,
|
|
416
|
+
cwd: getCwd(),
|
|
417
|
+
permission_mode: "default",
|
|
418
|
+
trigger,
|
|
419
|
+
summary,
|
|
420
|
+
compression_ratio: compressionRatio,
|
|
421
|
+
original_tokens: originalTokens,
|
|
422
|
+
compressed_tokens: compressedTokens
|
|
423
|
+
};
|
|
424
|
+
}
|
|
262
425
|
export {
|
|
426
|
+
createNotificationInput,
|
|
427
|
+
createPermissionRequestInput,
|
|
428
|
+
createPostCompactInput,
|
|
429
|
+
createPostToolUseFailureInput,
|
|
263
430
|
createPostToolUseInput,
|
|
431
|
+
createPreCompactInput,
|
|
264
432
|
createPreToolUseInput,
|
|
265
433
|
createSessionEndInput,
|
|
266
434
|
createSessionStartInput,
|
|
435
|
+
createStopInput,
|
|
436
|
+
createSubagentStartInput,
|
|
437
|
+
createSubagentStopInput,
|
|
267
438
|
createUserPromptSubmitInput,
|
|
268
439
|
executeHook,
|
|
269
440
|
executeHooksForEvent,
|
|
441
|
+
hookStatusEmitter,
|
|
270
442
|
processHookDecisions
|
|
271
443
|
};
|
|
272
444
|
//# sourceMappingURL=hookExecutor.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/hookExecutor.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Hook Execution Engine\n *\n * Executes plugin hooks with bash command execution, JSON I/O,\n * and decision processing (approve/block/ask).\n *\n * Fully compatible with Claude Code CLI hooks specification.\n */\n\nimport { spawn } from 'child_process'\nimport { homedir } from 'os'\nimport { join } from 'path'\nimport {\n HookEvent,\n HookInput,\n HookOutput,\n HookDecision,\n PreToolUseInput,\n PostToolUseInput,\n UserPromptSubmitInput,\n SessionStartInput,\n SessionEndInput,\n} from '../types/hooks'\nimport { LoadedHook } from '../types/plugin'\nimport { getCwd } from '../utils/state'\nimport { logError } from '../utils/log'\n\n// Simple logging helpers\nconst logInfo = (msg: string) => {\n // Only log in debug mode to reduce noise\n if (process.env.DEBUG) console.log(`[INFO] ${msg}`)\n}\nconst logDebug = (msg: string, ...args: any[]) => {\n if (process.env.DEBUG) console.log(`[DEBUG] ${msg}`, ...args)\n}\n\n/**\n * Hook execution result\n */\nexport interface HookExecutionResult {\n success: boolean\n decision?: 'approve' | 'block' | 'ask'\n output?: HookOutput\n error?: string\n timedOut?: boolean\n}\n\n/**\n * Hook execution options\n */\nexport interface HookExecutionOptions {\n timeout?: number\n sessionId: string\n transcriptPath?: string\n pluginRoot: string\n}\n\n/**\n * Execute a hook with bash command\n */\nexport async function executeHook(\n hook: LoadedHook,\n input: HookInput,\n options: HookExecutionOptions,\n): Promise<HookExecutionResult> {\n // Only execute command-type hooks\n if (hook.config.type !== 'command' || !hook.config.command) {\n return {\n success: false,\n error: `Hook type \"${hook.config.type}\" not yet implemented`,\n }\n }\n\n const timeout = hook.config.timeout || options.timeout || 30000 // 30 seconds default\n\n try {\n logDebug(`Executing hook: ${hook.name}`)\n logDebug(`Command: ${hook.config.command}`)\n\n // Execute bash command with JSON input via stdin\n const result = await executeBashCommand(hook.config.command, input, {\n ...options,\n timeout,\n pluginRoot: options.pluginRoot,\n })\n\n if (result.timedOut) {\n logError(`Hook ${hook.name} timed out after ${timeout}ms`)\n return {\n success: false,\n timedOut: true,\n error: `Hook execution timed out after ${timeout}ms`,\n }\n }\n\n if (result.error) {\n logError(`Hook ${hook.name} failed: ${result.error}`)\n return {\n success: false,\n error: result.error,\n }\n }\n\n // Parse JSON output\n const output = parseHookOutput(result.stdout)\n\n if (!output) {\n // No output means hook executed successfully but didn't return decisions\n return {\n success: true,\n }\n }\n\n logDebug(`Hook ${hook.name} output:`, output)\n\n return {\n success: true,\n decision: output.decision,\n output,\n }\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error)\n logError(`Hook ${hook.name} execution error: ${errorMsg}`)\n return {\n success: false,\n error: errorMsg,\n }\n }\n}\n\n/**\n * Execute bash command with JSON stdin/stdout\n */\nasync function executeBashCommand(\n command: string,\n input: HookInput,\n options: {\n timeout: number\n sessionId: string\n transcriptPath?: string\n pluginRoot: string\n },\n): Promise<{\n stdout: string\n stderr: string\n error?: string\n timedOut?: boolean\n}> {\n return new Promise(resolve => {\n // Prepare environment variables\n const env = {\n ...process.env,\n CLAUDE_PLUGIN_ROOT: options.pluginRoot,\n CLAUDE_SESSION_ID: options.sessionId,\n CLAUDE_CWD: getCwd(),\n CLAUDE_TRANSCRIPT_PATH: options.transcriptPath || '',\n }\n\n // Spawn bash process\n const child = spawn('bash', ['-c', command], {\n env,\n cwd: getCwd(),\n })\n\n let stdout = ''\n let stderr = ''\n let timedOut = false\n\n // Set timeout\n const timer = setTimeout(() => {\n timedOut = true\n child.kill('SIGTERM')\n setTimeout(() => {\n if (!child.killed) {\n child.kill('SIGKILL')\n }\n }, 1000)\n }, options.timeout)\n\n // Collect stdout\n child.stdout?.on('data', data => {\n stdout += data.toString()\n })\n\n // Collect stderr\n child.stderr?.on('data', data => {\n stderr += data.toString()\n })\n\n // Handle completion\n child.on('close', code => {\n clearTimeout(timer)\n\n if (timedOut) {\n resolve({\n stdout: '',\n stderr: '',\n timedOut: true,\n })\n return\n }\n\n if (code !== 0 && code !== null) {\n resolve({\n stdout,\n stderr,\n error: `Command exited with code ${code}: ${stderr}`,\n })\n return\n }\n\n resolve({\n stdout,\n stderr,\n })\n })\n\n // Handle errors\n child.on('error', error => {\n clearTimeout(timer)\n resolve({\n stdout: '',\n stderr: '',\n error: `Failed to spawn process: ${error.message}`,\n })\n })\n\n // Send JSON input via stdin\n try {\n if (child.stdin) {\n child.stdin.write(JSON.stringify(input, null, 2))\n child.stdin.end()\n }\n } catch (error) {\n clearTimeout(timer)\n child.kill()\n resolve({\n stdout: '',\n stderr: '',\n error: `Failed to write to stdin: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n })\n}\n\n/**\n * Parse hook output JSON\n */\nfunction parseHookOutput(stdout: string): HookOutput | null {\n if (!stdout.trim()) {\n return null\n }\n\n try {\n // Try to extract JSON from output (hook might print other things)\n const jsonMatch = stdout.match(/\\{[\\s\\S]*\\}/)\n if (!jsonMatch) {\n logDebug('No JSON found in hook output')\n return null\n }\n\n const output = JSON.parse(jsonMatch[0]) as HookOutput\n\n // Validate decision if present\n if (output.decision) {\n if (!['approve', 'block', 'ask'].includes(output.decision)) {\n logError(`Invalid hook decision: ${output.decision}`)\n return null\n }\n }\n\n return output\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error)\n logError(`Failed to parse hook output JSON: ${errorMsg}`)\n logDebug('Raw output:', stdout)\n return null\n }\n}\n\n/**\n * Execute all matching hooks for an event\n */\nexport async function executeHooksForEvent(\n event: HookEvent,\n hooks: LoadedHook[],\n input: HookInput,\n options: HookExecutionOptions,\n): Promise<HookExecutionResult[]> {\n // Filter hooks for this event\n const matchingHooks = hooks.filter(hook => hook.event === event)\n\n if (matchingHooks.length === 0) {\n return []\n }\n\n logInfo(`Executing ${matchingHooks.length} hook(s) for event: ${event}`)\n\n // Execute all matching hooks in parallel (Claude Code behavior)\n const results = await Promise.all(\n matchingHooks.map(hook => executeHook(hook, input, options)),\n )\n\n return results\n}\n\n/**\n * Process hook decisions to determine final action\n */\nexport function processHookDecisions(results: HookExecutionResult[]): {\n shouldContinue: boolean\n shouldAskUser: boolean\n reason?: string\n} {\n // If any hook says \"block\", we block\n const blockedResult = results.find(r => r.success && r.decision === 'block')\n if (blockedResult) {\n return {\n shouldContinue: false,\n shouldAskUser: false,\n reason: blockedResult.output?.reason || 'Blocked by hook',\n }\n }\n\n // If any hook says \"ask\", we ask the user\n const askResult = results.find(r => r.success && r.decision === 'ask')\n if (askResult) {\n return {\n shouldContinue: false,\n shouldAskUser: true,\n reason: askResult.output?.reason || 'Hook requested user approval',\n }\n }\n\n // If any hook failed, we ask the user (fail-safe)\n const failedResult = results.find(r => !r.success)\n if (failedResult) {\n return {\n shouldContinue: false,\n shouldAskUser: true,\n reason: `Hook execution failed: ${failedResult.error}`,\n }\n }\n\n // All hooks approved or had no decision\n return {\n shouldContinue: true,\n shouldAskUser: false,\n }\n}\n\n/**\n * Create hook input for PreToolUse event\n */\nexport function createPreToolUseInput(\n sessionId: string,\n transcriptPath: string,\n toolName: string,\n toolInput: Record<string, unknown>,\n): PreToolUseInput {\n return {\n hook_event_name: HookEvent.PreToolUse,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n tool_name: toolName,\n tool_input: toolInput,\n }\n}\n\n/**\n * Create hook input for PostToolUse event\n */\nexport function createPostToolUseInput(\n sessionId: string,\n transcriptPath: string,\n toolName: string,\n toolInput: Record<string, unknown>,\n toolOutput: Record<string, unknown>,\n): PostToolUseInput {\n return {\n hook_event_name: HookEvent.PostToolUse,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n tool_name: toolName,\n tool_input: toolInput,\n tool_output: toolOutput,\n }\n}\n\n/**\n * Create hook input for UserPromptSubmit event\n */\nexport function createUserPromptSubmitInput(\n sessionId: string,\n transcriptPath: string,\n userPrompt: string,\n): UserPromptSubmitInput {\n return {\n hook_event_name: HookEvent.UserPromptSubmit,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n user_prompt: userPrompt,\n }\n}\n\n/**\n * Create hook input for SessionStart event\n */\nexport function createSessionStartInput(\n sessionId: string,\n transcriptPath: string,\n): SessionStartInput {\n return {\n hook_event_name: HookEvent.SessionStart,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n source: 'startup' as const,\n permission_mode: 'default',\n }\n}\n\n/**\n * Create hook input for SessionEnd event\n */\nexport function createSessionEndInput(\n sessionId: string,\n transcriptPath: string,\n reason: 'clear' | 'logout' | 'prompt_input_exit' | 'other',\n): SessionEndInput {\n return {\n hook_event_name: HookEvent.SessionEnd,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n reason: reason,\n }\n}\n"],
|
|
5
|
-
"mappings": "AASA,SAAS,aAAa;AAGtB;AAAA,EACE;AAAA,
|
|
4
|
+
"sourcesContent": ["/**\n * Hook Execution Engine\n *\n * Executes plugin hooks with bash command execution, JSON I/O,\n * and decision processing (approve/block/ask).\n *\n * Fully compatible with Claude Code CLI hooks specification.\n */\n\nimport { spawn } from 'child_process'\nimport { homedir } from 'os'\nimport { join } from 'path'\nimport { EventEmitter } from 'events'\nimport {\n HookEvent,\n HookInput,\n HookOutput,\n HookDecision,\n PreToolUseInput,\n PostToolUseInput,\n PostToolUseFailureInput,\n PermissionRequestInput,\n UserPromptSubmitInput,\n SessionStartInput,\n SessionEndInput,\n StopInput,\n SubagentStartInput,\n SubagentStopInput,\n NotificationInput,\n PreCompactInput,\n PostCompactInput,\n} from '../types/hooks'\nimport { LoadedHook, HookEvent as PluginHookEvent } from '../types/plugin'\nimport { getCwd } from '../utils/state'\nimport { logError } from '../utils/log'\n\n// Simple logging helpers\nconst logInfo = (msg: string) => {\n // Only log in debug mode to reduce noise\n if (process.env.DEBUG) console.log(`[INFO] ${msg}`)\n}\nconst logDebug = (msg: string, ...args: any[]) => {\n if (process.env.DEBUG) console.log(`[DEBUG] ${msg}`, ...args)\n}\n\n/**\n * Hook status event for verbose mode display\n */\nexport interface HookStatusEvent {\n /** Hook event type (PreToolUse, PostToolUse, etc.) */\n event: PluginHookEvent\n /** Tool name if applicable */\n toolName?: string\n /** Whether the hook succeeded */\n success: boolean\n /** Formatted status message */\n message: string\n /** Timestamp */\n timestamp: number\n /** Hook name */\n hookName: string\n}\n\n/**\n * Event emitter for hook status updates\n * Used by UI to display hook status in verbose mode\n */\nexport const hookStatusEmitter = new EventEmitter()\n\n/**\n * Format hook status message (like Claude Code: \"PreToolUse:Glob hook succeeded: Success\")\n */\nfunction formatHookStatusMessage(\n event: PluginHookEvent,\n toolName: string | undefined,\n hookName: string,\n success: boolean,\n errorMessage?: string,\n): string {\n const eventPart = toolName ? `${event}:${toolName}` : event\n const statusPart = success ? 'succeeded' : 'failed'\n const detailPart = success ? 'Success' : errorMessage || 'Error'\n return `${eventPart} hook ${statusPart}: ${detailPart}`\n}\n\n/**\n * Hook execution result\n */\nexport interface HookExecutionResult {\n success: boolean\n decision?: 'approve' | 'block' | 'ask'\n output?: HookOutput\n error?: string\n timedOut?: boolean\n}\n\n/**\n * Hook execution options\n */\nexport interface HookExecutionOptions {\n timeout?: number\n sessionId: string\n transcriptPath?: string\n pluginRoot: string\n}\n\n/**\n * Execute a hook with bash command\n */\nexport async function executeHook(\n hook: LoadedHook,\n input: HookInput,\n options: HookExecutionOptions,\n): Promise<HookExecutionResult> {\n // Only execute command-type hooks\n if (hook.config.type !== 'command' || !hook.config.command) {\n return {\n success: false,\n error: `Hook type \"${hook.config.type}\" not yet implemented`,\n }\n }\n\n const timeout = hook.config.timeout || options.timeout || 30000 // 30 seconds default\n\n // Extract tool name from input (needed for status events in both try and catch)\n const toolName =\n 'tool_name' in input ? (input.tool_name as string) : undefined\n\n try {\n logDebug(`Executing hook: ${hook.name}`)\n logDebug(`Command: ${hook.config.command}`)\n\n // Execute bash command with JSON input via stdin\n const result = await executeBashCommand(hook.config.command, input, {\n ...options,\n timeout,\n pluginRoot: options.pluginRoot,\n })\n\n if (result.timedOut) {\n logError(`Hook ${hook.name} timed out after ${timeout}ms`)\n const errorMsg = `Hook execution timed out after ${timeout}ms`\n hookStatusEmitter.emit('status', {\n event: hook.event,\n toolName,\n success: false,\n message: formatHookStatusMessage(\n hook.event,\n toolName,\n hook.name,\n false,\n errorMsg,\n ),\n timestamp: Date.now(),\n hookName: hook.name,\n } as HookStatusEvent)\n return {\n success: false,\n timedOut: true,\n error: errorMsg,\n }\n }\n\n if (result.error) {\n logError(`Hook ${hook.name} failed: ${result.error}`)\n hookStatusEmitter.emit('status', {\n event: hook.event,\n toolName,\n success: false,\n message: formatHookStatusMessage(\n hook.event,\n toolName,\n hook.name,\n false,\n result.error,\n ),\n timestamp: Date.now(),\n hookName: hook.name,\n } as HookStatusEvent)\n return {\n success: false,\n error: result.error,\n }\n }\n\n // Parse JSON output\n const output = parseHookOutput(result.stdout)\n\n if (!output) {\n // No output means hook executed successfully but didn't return decisions\n hookStatusEmitter.emit('status', {\n event: hook.event,\n toolName,\n success: true,\n message: formatHookStatusMessage(hook.event, toolName, hook.name, true),\n timestamp: Date.now(),\n hookName: hook.name,\n } as HookStatusEvent)\n return {\n success: true,\n }\n }\n\n logDebug(`Hook ${hook.name} output:`, output)\n\n // Emit success status event\n hookStatusEmitter.emit('status', {\n event: hook.event,\n toolName,\n success: true,\n message: formatHookStatusMessage(hook.event, toolName, hook.name, true),\n timestamp: Date.now(),\n hookName: hook.name,\n } as HookStatusEvent)\n\n return {\n success: true,\n decision: output.decision,\n output,\n }\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error)\n logError(`Hook ${hook.name} execution error: ${errorMsg}`)\n\n // Emit failure status event\n hookStatusEmitter.emit('status', {\n event: hook.event,\n toolName,\n success: false,\n message: formatHookStatusMessage(\n hook.event,\n toolName,\n hook.name,\n false,\n errorMsg,\n ),\n timestamp: Date.now(),\n hookName: hook.name,\n } as HookStatusEvent)\n\n return {\n success: false,\n error: errorMsg,\n }\n }\n}\n\n/**\n * Execute bash command with JSON stdin/stdout\n */\nasync function executeBashCommand(\n command: string,\n input: HookInput,\n options: {\n timeout: number\n sessionId: string\n transcriptPath?: string\n pluginRoot: string\n },\n): Promise<{\n stdout: string\n stderr: string\n error?: string\n timedOut?: boolean\n}> {\n return new Promise(resolve => {\n // Prepare environment variables\n const env = {\n ...process.env,\n CLAUDE_PLUGIN_ROOT: options.pluginRoot,\n CLAUDE_SESSION_ID: options.sessionId,\n CLAUDE_CWD: getCwd(),\n CLAUDE_TRANSCRIPT_PATH: options.transcriptPath || '',\n }\n\n // Spawn bash process\n const child = spawn('bash', ['-c', command], {\n env,\n cwd: getCwd(),\n })\n\n let stdout = ''\n let stderr = ''\n let timedOut = false\n\n // Set timeout\n const timer = setTimeout(() => {\n timedOut = true\n child.kill('SIGTERM')\n setTimeout(() => {\n if (!child.killed) {\n child.kill('SIGKILL')\n }\n }, 1000)\n }, options.timeout)\n\n // Collect stdout\n child.stdout?.on('data', data => {\n stdout += data.toString()\n })\n\n // Collect stderr\n child.stderr?.on('data', data => {\n stderr += data.toString()\n })\n\n // Handle completion\n child.on('close', code => {\n clearTimeout(timer)\n\n if (timedOut) {\n resolve({\n stdout: '',\n stderr: '',\n timedOut: true,\n })\n return\n }\n\n if (code !== 0 && code !== null) {\n resolve({\n stdout,\n stderr,\n error: `Command exited with code ${code}: ${stderr}`,\n })\n return\n }\n\n resolve({\n stdout,\n stderr,\n })\n })\n\n // Handle errors\n child.on('error', error => {\n clearTimeout(timer)\n resolve({\n stdout: '',\n stderr: '',\n error: `Failed to spawn process: ${error.message}`,\n })\n })\n\n // Send JSON input via stdin\n try {\n if (child.stdin) {\n child.stdin.write(JSON.stringify(input, null, 2))\n child.stdin.end()\n }\n } catch (error) {\n clearTimeout(timer)\n child.kill()\n resolve({\n stdout: '',\n stderr: '',\n error: `Failed to write to stdin: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n })\n}\n\n/**\n * Parse hook output JSON\n */\nfunction parseHookOutput(stdout: string): HookOutput | null {\n if (!stdout.trim()) {\n return null\n }\n\n try {\n // Try to extract JSON from output (hook might print other things)\n const jsonMatch = stdout.match(/\\{[\\s\\S]*\\}/)\n if (!jsonMatch) {\n logDebug('No JSON found in hook output')\n return null\n }\n\n const output = JSON.parse(jsonMatch[0]) as HookOutput\n\n // Validate decision if present\n if (output.decision) {\n if (!['approve', 'block', 'ask'].includes(output.decision)) {\n logError(`Invalid hook decision: ${output.decision}`)\n return null\n }\n }\n\n return output\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error)\n logError(`Failed to parse hook output JSON: ${errorMsg}`)\n logDebug('Raw output:', stdout)\n return null\n }\n}\n\n/**\n * Execute all matching hooks for an event\n */\nexport async function executeHooksForEvent(\n event: HookEvent,\n hooks: LoadedHook[],\n input: HookInput,\n options: HookExecutionOptions,\n): Promise<HookExecutionResult[]> {\n // Filter hooks for this event\n const matchingHooks = hooks.filter(hook => hook.event === event)\n\n if (matchingHooks.length === 0) {\n return []\n }\n\n logInfo(`Executing ${matchingHooks.length} hook(s) for event: ${event}`)\n\n // Execute all matching hooks in parallel (Claude Code behavior)\n const results = await Promise.all(\n matchingHooks.map(hook => executeHook(hook, input, options)),\n )\n\n return results\n}\n\n/**\n * Process hook decisions to determine final action\n */\nexport function processHookDecisions(results: HookExecutionResult[]): {\n shouldContinue: boolean\n shouldAskUser: boolean\n reason?: string\n} {\n // If any hook says \"block\", we block\n const blockedResult = results.find(r => r.success && r.decision === 'block')\n if (blockedResult) {\n return {\n shouldContinue: false,\n shouldAskUser: false,\n reason: blockedResult.output?.reason || 'Blocked by hook',\n }\n }\n\n // If any hook says \"ask\", we ask the user\n const askResult = results.find(r => r.success && r.decision === 'ask')\n if (askResult) {\n return {\n shouldContinue: false,\n shouldAskUser: true,\n reason: askResult.output?.reason || 'Hook requested user approval',\n }\n }\n\n // If any hook failed, we ask the user (fail-safe)\n const failedResult = results.find(r => !r.success)\n if (failedResult) {\n return {\n shouldContinue: false,\n shouldAskUser: true,\n reason: `Hook execution failed: ${failedResult.error}`,\n }\n }\n\n // All hooks approved or had no decision\n return {\n shouldContinue: true,\n shouldAskUser: false,\n }\n}\n\n/**\n * Create hook input for PreToolUse event\n */\nexport function createPreToolUseInput(\n sessionId: string,\n transcriptPath: string,\n toolName: string,\n toolInput: Record<string, unknown>,\n): PreToolUseInput {\n return {\n hook_event_name: HookEvent.PreToolUse,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n tool_name: toolName,\n tool_input: toolInput,\n }\n}\n\n/**\n * Create hook input for PostToolUse event\n */\nexport function createPostToolUseInput(\n sessionId: string,\n transcriptPath: string,\n toolName: string,\n toolInput: Record<string, unknown>,\n toolOutput: Record<string, unknown>,\n): PostToolUseInput {\n return {\n hook_event_name: HookEvent.PostToolUse,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n tool_name: toolName,\n tool_input: toolInput,\n tool_output: toolOutput,\n }\n}\n\n/**\n * Create hook input for UserPromptSubmit event\n */\nexport function createUserPromptSubmitInput(\n sessionId: string,\n transcriptPath: string,\n userPrompt: string,\n): UserPromptSubmitInput {\n return {\n hook_event_name: HookEvent.UserPromptSubmit,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n user_prompt: userPrompt,\n }\n}\n\n/**\n * Create hook input for SessionStart event\n */\nexport function createSessionStartInput(\n sessionId: string,\n transcriptPath: string,\n): SessionStartInput {\n return {\n hook_event_name: HookEvent.SessionStart,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n source: 'startup' as const,\n permission_mode: 'default',\n }\n}\n\n/**\n * Create hook input for SessionEnd event\n */\nexport function createSessionEndInput(\n sessionId: string,\n transcriptPath: string,\n reason: 'clear' | 'logout' | 'prompt_input_exit' | 'other',\n): SessionEndInput {\n return {\n hook_event_name: HookEvent.SessionEnd,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n reason: reason,\n }\n}\n\n/**\n * Create hook input for PostToolUseFailure event\n */\nexport function createPostToolUseFailureInput(\n sessionId: string,\n transcriptPath: string,\n toolName: string,\n toolInput: Record<string, unknown>,\n error: string,\n errorType?: string,\n): PostToolUseFailureInput {\n return {\n hook_event_name: HookEvent.PostToolUseFailure,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n tool_name: toolName,\n tool_input: toolInput,\n error,\n error_type: errorType,\n }\n}\n\n/**\n * Create hook input for PermissionRequest event\n */\nexport function createPermissionRequestInput(\n sessionId: string,\n transcriptPath: string,\n toolName: string,\n toolInput: Record<string, unknown>,\n permissionType: 'read' | 'write' | 'execute' | 'network' | 'other',\n description?: string,\n): PermissionRequestInput {\n return {\n hook_event_name: HookEvent.PermissionRequest,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n tool_name: toolName,\n tool_input: toolInput,\n permission_type: permissionType,\n description,\n }\n}\n\n/**\n * Create hook input for Stop event\n */\nexport function createStopInput(\n sessionId: string,\n transcriptPath: string,\n stopHookActive: boolean,\n): StopInput {\n return {\n hook_event_name: HookEvent.Stop,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n stop_hook_active: stopHookActive,\n }\n}\n\n/**\n * Create hook input for SubagentStart event\n */\nexport function createSubagentStartInput(\n sessionId: string,\n transcriptPath: string,\n agentType: string,\n agentDescription?: string,\n runInBackground?: boolean,\n): SubagentStartInput {\n return {\n hook_event_name: HookEvent.SubagentStart,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n agent_type: agentType,\n agent_description: agentDescription,\n run_in_background: runInBackground,\n }\n}\n\n/**\n * Create hook input for SubagentStop event\n */\nexport function createSubagentStopInput(\n sessionId: string,\n transcriptPath: string,\n agentType: string,\n agentId?: string,\n stopHookActive?: boolean,\n): SubagentStopInput {\n return {\n hook_event_name: HookEvent.SubagentStop,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n agent_type: agentType,\n agent_id: agentId,\n stop_hook_active: stopHookActive ?? false,\n }\n}\n\n/**\n * Create hook input for Notification event\n */\nexport function createNotificationInput(\n sessionId: string,\n transcriptPath: string,\n message: string,\n): NotificationInput {\n return {\n hook_event_name: HookEvent.Notification,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n message,\n }\n}\n\n/**\n * Create hook input for PreCompact event\n */\nexport function createPreCompactInput(\n sessionId: string,\n transcriptPath: string,\n trigger: 'manual' | 'auto',\n customInstructions: string,\n): PreCompactInput {\n return {\n hook_event_name: HookEvent.PreCompact,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n trigger,\n custom_instructions: customInstructions,\n }\n}\n\n/**\n * Create hook input for PostCompact event\n */\nexport function createPostCompactInput(\n sessionId: string,\n transcriptPath: string,\n trigger: 'manual' | 'auto',\n summary: string,\n compressionRatio: number,\n originalTokens: number,\n compressedTokens: number,\n): PostCompactInput {\n return {\n hook_event_name: HookEvent.PostCompact,\n session_id: sessionId,\n transcript_path: transcriptPath,\n cwd: getCwd(),\n permission_mode: 'default',\n trigger,\n summary,\n compression_ratio: compressionRatio,\n original_tokens: originalTokens,\n compressed_tokens: compressedTokens,\n }\n}\n"],
|
|
5
|
+
"mappings": "AASA,SAAS,aAAa;AAGtB,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,OAiBK;AAEP,SAAS,cAAc;AACvB,SAAS,gBAAgB;AAGzB,MAAM,UAAU,CAAC,QAAgB;AAE/B,MAAI,QAAQ,IAAI,MAAO,SAAQ,IAAI,UAAU,GAAG,EAAE;AACpD;AACA,MAAM,WAAW,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