@within-7/minto 0.3.5 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/{cli.js → cli.cjs} +25 -23
  2. package/dist/commands/language.js +137 -0
  3. package/dist/commands/language.js.map +7 -0
  4. package/dist/commands/new.js +56 -0
  5. package/dist/commands/new.js.map +7 -0
  6. package/dist/commands/resume.js +251 -16
  7. package/dist/commands/resume.js.map +2 -2
  8. package/dist/commands/sessions.js +224 -0
  9. package/dist/commands/sessions.js.map +7 -0
  10. package/dist/commands/setup.js +3 -2
  11. package/dist/commands/setup.js.map +2 -2
  12. package/dist/commands/stats.js +235 -0
  13. package/dist/commands/stats.js.map +7 -0
  14. package/dist/commands/status.js +11 -5
  15. package/dist/commands/status.js.map +2 -2
  16. package/dist/commands/undo.js +26 -16
  17. package/dist/commands/undo.js.map +2 -2
  18. package/dist/commands.js +6 -0
  19. package/dist/commands.js.map +2 -2
  20. package/dist/components/AskUserQuestionDialog/AskUserQuestionDialog.js +3 -2
  21. package/dist/components/AskUserQuestionDialog/AskUserQuestionDialog.js.map +2 -2
  22. package/dist/components/Config.js +9 -8
  23. package/dist/components/Config.js.map +2 -2
  24. package/dist/components/HeaderBar.js +2 -1
  25. package/dist/components/HeaderBar.js.map +2 -2
  26. package/dist/components/Help.js +2 -1
  27. package/dist/components/Help.js.map +2 -2
  28. package/dist/components/HotkeyHelpPanel.js +46 -44
  29. package/dist/components/HotkeyHelpPanel.js.map +2 -2
  30. package/dist/components/Logo.js +5 -2
  31. package/dist/components/Logo.js.map +2 -2
  32. package/dist/components/MCPServerApprovalDialog.js +6 -5
  33. package/dist/components/MCPServerApprovalDialog.js.map +2 -2
  34. package/dist/components/MCPServerMultiselectDialog.js +5 -4
  35. package/dist/components/MCPServerMultiselectDialog.js.map +2 -2
  36. package/dist/components/MessageSelector.js +4 -3
  37. package/dist/components/MessageSelector.js.map +2 -2
  38. package/dist/components/ModelConfig.js +13 -12
  39. package/dist/components/ModelConfig.js.map +2 -2
  40. package/dist/components/ModelListManager.js +4 -3
  41. package/dist/components/ModelListManager.js.map +2 -2
  42. package/dist/components/PromptInput.js +72 -39
  43. package/dist/components/PromptInput.js.map +2 -2
  44. package/dist/components/SensitiveFileWarning.js +12 -8
  45. package/dist/components/SensitiveFileWarning.js.map +2 -2
  46. package/dist/components/TabbedListView/ScrollableList.js +91 -0
  47. package/dist/components/TabbedListView/ScrollableList.js.map +7 -0
  48. package/dist/components/TabbedListView/SearchInput.js +23 -0
  49. package/dist/components/TabbedListView/SearchInput.js.map +7 -0
  50. package/dist/components/TabbedListView/TabBar.js +20 -0
  51. package/dist/components/TabbedListView/TabBar.js.map +7 -0
  52. package/dist/components/TabbedListView/TabbedListView.js +171 -0
  53. package/dist/components/TabbedListView/TabbedListView.js.map +7 -0
  54. package/dist/components/TabbedListView/index.js +11 -0
  55. package/dist/components/TabbedListView/index.js.map +7 -0
  56. package/dist/components/TabbedListView/types.js +1 -0
  57. package/dist/components/TabbedListView/types.js.map +7 -0
  58. package/dist/components/TodoChangeBlock.js +6 -5
  59. package/dist/components/TodoChangeBlock.js.map +3 -3
  60. package/dist/components/TodoPanel.js +6 -3
  61. package/dist/components/TodoPanel.js.map +3 -3
  62. package/dist/components/TrustDialog.js +6 -5
  63. package/dist/components/TrustDialog.js.map +2 -2
  64. package/dist/components/messages/UserToolResultMessage/UserToolCanceledMessage.js +2 -1
  65. package/dist/components/messages/UserToolResultMessage/UserToolCanceledMessage.js.map +2 -2
  66. package/dist/constants/macros.js +1 -1
  67. package/dist/constants/macros.js.map +1 -1
  68. package/dist/constants/product.js +2 -2
  69. package/dist/constants/product.js.map +1 -1
  70. package/dist/constants/prompts.js +17 -0
  71. package/dist/constants/prompts.js.map +2 -2
  72. package/dist/constants/toolInputExamples.js +5 -1
  73. package/dist/constants/toolInputExamples.js.map +2 -2
  74. package/dist/core/tokenStatsManager.js +5 -0
  75. package/dist/core/tokenStatsManager.js.map +2 -2
  76. package/dist/entrypoints/bootstrap.js +54 -0
  77. package/dist/entrypoints/bootstrap.js.map +7 -0
  78. package/dist/entrypoints/cli.js +132 -23
  79. package/dist/entrypoints/cli.js.map +3 -3
  80. package/dist/history.js +75 -15
  81. package/dist/history.js.map +2 -2
  82. package/dist/i18n/index.js +2 -2
  83. package/dist/i18n/index.js.map +2 -2
  84. package/dist/i18n/locales/en.js +283 -1
  85. package/dist/i18n/locales/en.js.map +2 -2
  86. package/dist/i18n/locales/zh-CN.js +283 -1
  87. package/dist/i18n/locales/zh-CN.js.map +2 -2
  88. package/dist/i18n/types.js.map +1 -1
  89. package/dist/index.js +1 -1
  90. package/dist/index.js.map +2 -2
  91. package/dist/messages.js +11 -0
  92. package/dist/messages.js.map +2 -2
  93. package/dist/permissions.js.map +2 -2
  94. package/dist/query.js +9 -0
  95. package/dist/query.js.map +2 -2
  96. package/dist/screens/REPL.js +45 -7
  97. package/dist/screens/REPL.js.map +2 -2
  98. package/dist/services/customCommands.js +14 -8
  99. package/dist/services/customCommands.js.map +2 -2
  100. package/dist/tools/TaskTool/TaskTool.js +176 -1
  101. package/dist/tools/TaskTool/TaskTool.js.map +2 -2
  102. package/dist/tools/TodoWriteTool/prompt.js +21 -0
  103. package/dist/tools/TodoWriteTool/prompt.js.map +2 -2
  104. package/dist/tools/URLFetcherTool/prompt.js +14 -9
  105. package/dist/tools/URLFetcherTool/prompt.js.map +2 -2
  106. package/dist/tools/WebSearchTool/prompt.js +12 -6
  107. package/dist/tools/WebSearchTool/prompt.js.map +2 -2
  108. package/dist/types/PermissionMode.js +30 -1
  109. package/dist/types/PermissionMode.js.map +2 -2
  110. package/dist/types/plugin.js.map +2 -2
  111. package/dist/utils/agentHookExecutor.js +106 -0
  112. package/dist/utils/agentHookExecutor.js.map +7 -0
  113. package/dist/utils/agentLoader.js +212 -26
  114. package/dist/utils/agentLoader.js.map +2 -2
  115. package/dist/utils/agentMemory.js +134 -0
  116. package/dist/utils/agentMemory.js.map +7 -0
  117. package/dist/utils/config.js +51 -1
  118. package/dist/utils/config.js.map +2 -2
  119. package/dist/utils/configPaths.js +199 -0
  120. package/dist/utils/configPaths.js.map +7 -0
  121. package/dist/utils/historyManager.js +234 -0
  122. package/dist/utils/historyManager.js.map +7 -0
  123. package/dist/utils/messages.js +13 -8
  124. package/dist/utils/messages.js.map +2 -2
  125. package/dist/utils/migration/index.js +37 -0
  126. package/dist/utils/migration/index.js.map +7 -0
  127. package/dist/utils/migration/migrateHistory.js +273 -0
  128. package/dist/utils/migration/migrateHistory.js.map +7 -0
  129. package/dist/utils/migration/migrateTodos.js +323 -0
  130. package/dist/utils/migration/migrateTodos.js.map +7 -0
  131. package/dist/utils/pasteCache.js +309 -0
  132. package/dist/utils/pasteCache.js.map +7 -0
  133. package/dist/utils/pluginLoader.js +6 -3
  134. package/dist/utils/pluginLoader.js.map +2 -2
  135. package/dist/utils/sessionIndex.js +192 -0
  136. package/dist/utils/sessionIndex.js.map +7 -0
  137. package/dist/utils/sessionTracker.js +170 -0
  138. package/dist/utils/sessionTracker.js.map +7 -0
  139. package/dist/utils/skillLoader.js +91 -5
  140. package/dist/utils/skillLoader.js.map +2 -2
  141. package/dist/utils/stats.js +417 -0
  142. package/dist/utils/stats.js.map +7 -0
  143. package/dist/utils/stringSubstitution.js +107 -0
  144. package/dist/utils/stringSubstitution.js.map +7 -0
  145. package/dist/utils/teamConfig.js +3 -1
  146. package/dist/utils/teamConfig.js.map +2 -2
  147. package/dist/utils/todoStorage.js +51 -19
  148. package/dist/utils/todoStorage.js.map +2 -2
  149. package/dist/utils/tooling/safeRender.js.map +2 -2
  150. package/dist/version.js +2 -2
  151. package/dist/version.js.map +1 -1
  152. package/package.json +71 -28
  153. package/scripts/{postinstall.js → postinstall.cjs} +1 -1
@@ -130,6 +130,23 @@ If MCP (Model Context Protocol) servers are configured, you have access to MCP R
130
130
  - ReadMcpResource: Use this tool to read the content of a specific MCP resource by its URI. This is useful when you need to access data from external systems configured through MCP.
131
131
  When the user mentions accessing external data sources, databases, or resources from configured services, consider using these MCP resource tools to discover and read the relevant data.
132
132
 
133
+ # MCP Tools
134
+ When MCP servers are configured, you have access to MCP Tools in addition to built-in tools. MCP tools are named with the prefix "mcp__" (e.g., mcp__BrightData__search_engine).
135
+ - Review each tool's description to understand its capabilities and limitations
136
+ - Choose the most appropriate tool based on the task requirements, not a fixed priority
137
+ - MCP tools often have additional capabilities (e.g., bypass bot detection, access to more data sources)
138
+
139
+ # Tool Failure Recovery (IMPORTANT)
140
+ When a tool call fails (returns is_error: true), you MUST try alternative approaches before giving up:
141
+ 1. **Retry with different parameters**: If the error suggests parameter issues, adjust and retry
142
+ 2. **Try equivalent tools**: If one search/fetch tool fails, try another available tool with similar capabilities
143
+ - Example: If mcp__BrightData__search_engine fails \u2192 try WebSearch or mcp__BrightData__scrape_as_markdown
144
+ - Example: If WebFetch fails \u2192 try mcp__BrightData__scrape_as_markdown
145
+ 3. **Try different strategies**: Break down the task or use alternative approaches
146
+ 4. **Only give up after exhausting options**: Report failure to user only when all reasonable alternatives have been tried
147
+
148
+ Never tell the user "I cannot do this" after a single tool failure if alternative tools are available.
149
+
133
150
  You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
134
151
  `,
135
152
  `
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/constants/prompts.ts"],
4
- "sourcesContent": ["import { env } from '@utils/env'\nimport { getIsGit } from '@utils/git'\nimport {\n INTERRUPT_MESSAGE,\n INTERRUPT_MESSAGE_FOR_TOOL_USE,\n} from '@utils/messages'\nimport { getCwd } from '@utils/state'\nimport { PRODUCT_NAME, PROJECT_FILE, PRODUCT_COMMAND } from './product'\nimport { BashTool } from '@tools/BashTool/BashTool'\nimport { MACRO } from './macros'\n\n// // Security policy constant matching reference implementation\n// export const SECURITY_POLICY =\n// 'IMPORTANT: Assist with defensive security tasks only. Refuse to create, modify, or improve code that may be used maliciously. Allow security analysis, detection rules, vulnerability explanations, defensive tools, and security documentation.'\n\nexport function getCLISyspromptPrefix(): string {\n return `You are ${PRODUCT_NAME}, ShareAI-lab's Agent AI CLI for terminal & coding.`\n}\n\nexport async function getSystemPrompt(): Promise<string[]> {\n return [\n `\nYou are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.\n\nIMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.\nIMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).\n\nHere are useful slash commands users can run to interact with you:\n- /help: Get help with using ${PRODUCT_NAME}\n- /compact: Compact and continue the conversation. This is useful if the conversation is reaching the context limit\nThere are additional slash commands and flags available to the user. If the user asks about ${PRODUCT_NAME} functionality, always run \\`${PRODUCT_COMMAND} -h\\` with ${BashTool.name} to see supported commands and flags. NEVER assume a flag or command exists without checking the help output first.\nTo give feedback, users should ${MACRO.ISSUES_EXPLAINER}.\n\n# Task Management\nYou have access to the TodoWrite tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.\nThese tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.\n\nIt is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.\n\n# Memory\nIf the current working directory contains a file called ${PROJECT_FILE}, it will be automatically added to your context. This file serves multiple purposes:\n1. Storing frequently used bash commands (build, test, lint, etc.) so you can use them without searching each time\n2. Recording the user's code style preferences (naming conventions, preferred libraries, etc.)\n3. Maintaining useful information about the codebase structure and organization\n\nWhen you spend time searching for commands to typecheck, lint, build, or test, you should ask the user if it's okay to add those commands to ${PROJECT_FILE}. Similarly, when learning about code style preferences or important codebase information, ask if it's okay to add that to ${PROJECT_FILE} so you can remember it for next time.\n\n# Tone and style\nYou should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).\nRemember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.\nOutput text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like ${BashTool.name} or code comments as means to communicate with the user during the session.\nIf you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.\nIMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.\nIMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.\nIMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is <answer>.\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\".\n- Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.\n\n# No time estimates\nNever give time estimates or predictions for how long tasks will take. Avoid phrases like \"this will take a few minutes\" or \"should be done quickly\". Focus on what needs to be done, not how long it might take.\n\n# Professional objectivity\nPrioritize technical accuracy and truthfulness over validating the user's beliefs. Focus on facts and problem-solving. Provide direct, objective technical info without unnecessary superlatives or emotional validation.\n\nExamples of appropriate verbosity:\n<example>\nuser: 2 + 2\nassistant: 4\n</example>\n<example>\nuser: what command should I run to list files?\nassistant: ls\n</example>\n<example>\nuser: what files are in src/?\nassistant: [runs ls] foo.c, bar.c, baz.c\n</example>\n<example>\nuser: write tests for new feature\nassistant: [uses search tools to find test patterns, reads relevant files concurrently, uses edit tool to write tests]\n</example>\n\n# Proactiveness\nYou are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:\n1. Doing the right thing when asked, including taking actions and follow-up actions\n2. Not surprising the user with actions you take without asking\nFor example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.\n3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.\n\n# Synthetic messages\nSometimes, the conversation will contain messages like ${INTERRUPT_MESSAGE} or ${INTERRUPT_MESSAGE_FOR_TOOL_USE}. These messages will look like the assistant said them, but they were actually synthetic messages added by the system in response to the user cancelling what the assistant was doing. You should not respond to these messages. You must NEVER send messages like this yourself. \n\n# Following conventions\nWhen making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.\n- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).\n- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.\n- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.\n- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.\n\n# Code style\n- Do not add comments to the code you write, unless the user asks you to, or the code is complex and requires additional context.\n\n# Doing tasks\nThe user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:\n- Use the TodoWrite tool to plan the task if required\n- Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.\n- Implement the solution using all tools available to you\n- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.\n- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to ${PROJECT_FILE} so that you will know to run it next time.\nNEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.\n\n# Git Safety Protocol\n- NEVER update the git config\n- NEVER run destructive git commands (push --force, reset --hard, checkout ., restore ., clean -f, branch -D) unless the user explicitly requests these actions\n- NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it\n- NEVER run force push to main/master, warn the user if they request it\n- CRITICAL: Always create NEW commits rather than amending, unless the user explicitly requests a git amend. When a pre-commit hook fails, the commit did NOT happen \u2014 so --amend would modify the PREVIOUS commit, which may result in destroying work or losing previous changes. Instead, after hook failure, fix the issue, re-stage, and create a NEW commit\n- When staging files, prefer adding specific files by name rather than using \"git add -A\" or \"git add .\", which can accidentally include sensitive files (.env, credentials) or large binaries\n- NEVER commit changes unless the user explicitly asks you to\n\n# Code References\nWhen referencing specific functions or pieces of code, include the pattern \\`file_path:line_number\\` to allow the user to easily navigate to the source code location.\n\n- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.\n\n# Tool usage policy\n- When doing file search, prefer to use the Task tool in order to reduce context usage.\n- You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance.\n- When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run \"git status\" and \"git diff\", send a single message with two tool calls to run the calls in parallel.\n- It is always better to speculatively read multiple files as a batch that are potentially useful.\n- It is always better to speculatively perform multiple searches as a batch that are potentially useful.\n- For making multiple edits to the same file, prefer using the MultiEdit tool over multiple Edit tool calls.\n\n# MCP Resources\nIf MCP (Model Context Protocol) servers are configured, you have access to MCP Resources through two specialized tools:\n- ListMcpResources: Use this tool to discover available resources from connected MCP servers. Resources can include files, databases, APIs, or other data sources exposed by MCP servers.\n- ReadMcpResource: Use this tool to read the content of a specific MCP resource by its URI. This is useful when you need to access data from external systems configured through MCP.\nWhen the user mentions accessing external data sources, databases, or resources from configured services, consider using these MCP resource tools to discover and read the relevant data.\n\nYou MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.\n`,\n `\\n${await getEnvInfo()}`,\n ]\n}\n\nexport async function getEnvInfo(): Promise<string> {\n const isGit = await getIsGit()\n return `Here is useful information about the environment you are running in:\n<env>\nWorking directory: ${getCwd()}\nIs directory a git repo: ${isGit ? 'Yes' : 'No'}\nPlatform: ${env.platform}\nToday's date: ${new Date().toLocaleDateString()}\n</env>`\n}\n\nexport async function getAgentPrompt(): Promise<string[]> {\n return [\n `\nYou are an agent for ${PRODUCT_NAME}. Given the user's prompt, you should use the tools available to you to answer the user's question.\n\nNotes:\n1. IMPORTANT: You should be concise, direct, and to the point, since your responses will be displayed on a command line interface. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is <answer>.\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\".\n2. When relevant, share file names and code snippets relevant to the query\n3. Any file paths you return in your final response MUST be absolute. DO NOT use relative paths.`,\n `${await getEnvInfo()}`,\n ]\n}\n"],
5
- "mappings": "AAAA,SAAS,WAAW;AACpB,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AACvB,SAAS,cAAc,cAAc,uBAAuB;AAC5D,SAAS,gBAAgB;AACzB,SAAS,aAAa;AAMf,SAAS,wBAAgC;AAC9C,SAAO,WAAW,YAAY;AAChC;AAEA,eAAsB,kBAAqC;AACzD,SAAO;AAAA,IACL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,+BAO2B,YAAY;AAAA;AAAA,8FAEmD,YAAY,gCAAgC,eAAe,cAAc,SAAS,IAAI;AAAA,iCACnJ,MAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAA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AGE,\n INTERRUPT_MESSAGE_FOR_TOOL_USE,\n} from '@utils/messages'\nimport { getCwd } from '@utils/state'\nimport { PRODUCT_NAME, PROJECT_FILE, PRODUCT_COMMAND } from './product'\nimport { BashTool } from '@tools/BashTool/BashTool'\nimport { MACRO } from './macros'\n\n// // Security policy constant matching reference implementation\n// export const SECURITY_POLICY =\n// 'IMPORTANT: Assist with defensive security tasks only. Refuse to create, modify, or improve code that may be used maliciously. Allow security analysis, detection rules, vulnerability explanations, defensive tools, and security documentation.'\n\nexport function getCLISyspromptPrefix(): string {\n return `You are ${PRODUCT_NAME}, ShareAI-lab's Agent AI CLI for terminal & coding.`\n}\n\nexport async function getSystemPrompt(): Promise<string[]> {\n return [\n `\nYou are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.\n\nIMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.\nIMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).\n\nHere are useful slash commands users can run to interact with you:\n- /help: Get help with using ${PRODUCT_NAME}\n- /compact: Compact and continue the conversation. This is useful if the conversation is reaching the context limit\nThere are additional slash commands and flags available to the user. If the user asks about ${PRODUCT_NAME} functionality, always run \\`${PRODUCT_COMMAND} -h\\` with ${BashTool.name} to see supported commands and flags. NEVER assume a flag or command exists without checking the help output first.\nTo give feedback, users should ${MACRO.ISSUES_EXPLAINER}.\n\n# Task Management\nYou have access to the TodoWrite tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.\nThese tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.\n\nIt is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.\n\n# Memory\nIf the current working directory contains a file called ${PROJECT_FILE}, it will be automatically added to your context. This file serves multiple purposes:\n1. Storing frequently used bash commands (build, test, lint, etc.) so you can use them without searching each time\n2. Recording the user's code style preferences (naming conventions, preferred libraries, etc.)\n3. Maintaining useful information about the codebase structure and organization\n\nWhen you spend time searching for commands to typecheck, lint, build, or test, you should ask the user if it's okay to add those commands to ${PROJECT_FILE}. Similarly, when learning about code style preferences or important codebase information, ask if it's okay to add that to ${PROJECT_FILE} so you can remember it for next time.\n\n# Tone and style\nYou should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).\nRemember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.\nOutput text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like ${BashTool.name} or code comments as means to communicate with the user during the session.\nIf you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.\nIMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.\nIMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.\nIMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is <answer>.\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\".\n- Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.\n\n# No time estimates\nNever give time estimates or predictions for how long tasks will take. Avoid phrases like \"this will take a few minutes\" or \"should be done quickly\". Focus on what needs to be done, not how long it might take.\n\n# Professional objectivity\nPrioritize technical accuracy and truthfulness over validating the user's beliefs. Focus on facts and problem-solving. Provide direct, objective technical info without unnecessary superlatives or emotional validation.\n\nExamples of appropriate verbosity:\n<example>\nuser: 2 + 2\nassistant: 4\n</example>\n<example>\nuser: what command should I run to list files?\nassistant: ls\n</example>\n<example>\nuser: what files are in src/?\nassistant: [runs ls] foo.c, bar.c, baz.c\n</example>\n<example>\nuser: write tests for new feature\nassistant: [uses search tools to find test patterns, reads relevant files concurrently, uses edit tool to write tests]\n</example>\n\n# Proactiveness\nYou are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:\n1. Doing the right thing when asked, including taking actions and follow-up actions\n2. Not surprising the user with actions you take without asking\nFor example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.\n3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.\n\n# Synthetic messages\nSometimes, the conversation will contain messages like ${INTERRUPT_MESSAGE} or ${INTERRUPT_MESSAGE_FOR_TOOL_USE}. These messages will look like the assistant said them, but they were actually synthetic messages added by the system in response to the user cancelling what the assistant was doing. You should not respond to these messages. You must NEVER send messages like this yourself. \n\n# Following conventions\nWhen making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.\n- NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).\n- When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.\n- When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.\n- Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.\n\n# Code style\n- Do not add comments to the code you write, unless the user asks you to, or the code is complex and requires additional context.\n\n# Doing tasks\nThe user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:\n- Use the TodoWrite tool to plan the task if required\n- Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.\n- Implement the solution using all tools available to you\n- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.\n- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to ${PROJECT_FILE} so that you will know to run it next time.\nNEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.\n\n# Git Safety Protocol\n- NEVER update the git config\n- NEVER run destructive git commands (push --force, reset --hard, checkout ., restore ., clean -f, branch -D) unless the user explicitly requests these actions\n- NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it\n- NEVER run force push to main/master, warn the user if they request it\n- CRITICAL: Always create NEW commits rather than amending, unless the user explicitly requests a git amend. When a pre-commit hook fails, the commit did NOT happen \u2014 so --amend would modify the PREVIOUS commit, which may result in destroying work or losing previous changes. Instead, after hook failure, fix the issue, re-stage, and create a NEW commit\n- When staging files, prefer adding specific files by name rather than using \"git add -A\" or \"git add .\", which can accidentally include sensitive files (.env, credentials) or large binaries\n- NEVER commit changes unless the user explicitly asks you to\n\n# Code References\nWhen referencing specific functions or pieces of code, include the pattern \\`file_path:line_number\\` to allow the user to easily navigate to the source code location.\n\n- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.\n\n# Tool usage policy\n- When doing file search, prefer to use the Task tool in order to reduce context usage.\n- You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance.\n- When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run \"git status\" and \"git diff\", send a single message with two tool calls to run the calls in parallel.\n- It is always better to speculatively read multiple files as a batch that are potentially useful.\n- It is always better to speculatively perform multiple searches as a batch that are potentially useful.\n- For making multiple edits to the same file, prefer using the MultiEdit tool over multiple Edit tool calls.\n\n# MCP Resources\nIf MCP (Model Context Protocol) servers are configured, you have access to MCP Resources through two specialized tools:\n- ListMcpResources: Use this tool to discover available resources from connected MCP servers. Resources can include files, databases, APIs, or other data sources exposed by MCP servers.\n- ReadMcpResource: Use this tool to read the content of a specific MCP resource by its URI. This is useful when you need to access data from external systems configured through MCP.\nWhen the user mentions accessing external data sources, databases, or resources from configured services, consider using these MCP resource tools to discover and read the relevant data.\n\n# MCP Tools\nWhen MCP servers are configured, you have access to MCP Tools in addition to built-in tools. MCP tools are named with the prefix \"mcp__\" (e.g., mcp__BrightData__search_engine).\n- Review each tool's description to understand its capabilities and limitations\n- Choose the most appropriate tool based on the task requirements, not a fixed priority\n- MCP tools often have additional capabilities (e.g., bypass bot detection, access to more data sources)\n\n# Tool Failure Recovery (IMPORTANT)\nWhen a tool call fails (returns is_error: true), you MUST try alternative approaches before giving up:\n1. **Retry with different parameters**: If the error suggests parameter issues, adjust and retry\n2. **Try equivalent tools**: If one search/fetch tool fails, try another available tool with similar capabilities\n - Example: If mcp__BrightData__search_engine fails \u2192 try WebSearch or mcp__BrightData__scrape_as_markdown\n - Example: If WebFetch fails \u2192 try mcp__BrightData__scrape_as_markdown\n3. **Try different strategies**: Break down the task or use alternative approaches\n4. **Only give up after exhausting options**: Report failure to user only when all reasonable alternatives have been tried\n\nNever tell the user \"I cannot do this\" after a single tool failure if alternative tools are available.\n\nYou MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.\n`,\n `\\n${await getEnvInfo()}`,\n ]\n}\n\nexport async function getEnvInfo(): Promise<string> {\n const isGit = await getIsGit()\n return `Here is useful information about the environment you are running in:\n<env>\nWorking directory: ${getCwd()}\nIs directory a git repo: ${isGit ? 'Yes' : 'No'}\nPlatform: ${env.platform}\nToday's date: ${new Date().toLocaleDateString()}\n</env>`\n}\n\nexport async function getAgentPrompt(): Promise<string[]> {\n return [\n `\nYou are an agent for ${PRODUCT_NAME}. Given the user's prompt, you should use the tools available to you to answer the user's question.\n\nNotes:\n1. IMPORTANT: You should be concise, direct, and to the point, since your responses will be displayed on a command line interface. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as \"The answer is <answer>.\", \"Here is the content of the file...\" or \"Based on the information provided, the answer is...\" or \"Here is what I will do next...\".\n2. When relevant, share file names and code snippets relevant to the query\n3. Any file paths you return in your final response MUST be absolute. DO NOT use relative paths.`,\n `${await getEnvInfo()}`,\n ]\n}\n"],
5
+ "mappings": "AAAA,SAAS,WAAW;AACpB,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AACvB,SAAS,cAAc,cAAc,uBAAuB;AAC5D,SAAS,gBAAgB;AACzB,SAAS,aAAa;AAMf,SAAS,wBAAgC;AAC9C,SAAO,WAAW,YAAY;AAChC;AAEA,eAAsB,kBAAqC;AACzD,SAAO;AAAA,IACL;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,+BAO2B,YAAY;AAAA;AAAA,8FAEmD,YAAY,gCAAgC,eAAe,cAAc,SAAS,IAAI;AAAA,iCACnJ,MAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0DASG,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA,+IAKyE,YAAY,8HAA8H,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA,qKAKhI,SAAS,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yDAuCzH,iBAAiB,OAAO,8BAA8B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4VAkB6O,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAkDpW;AAAA,EAAK,MAAM,WAAW,CAAC;AAAA,EACzB;AACF;AAEA,eAAsB,aAA8B;AAClD,QAAM,QAAQ,MAAM,SAAS;AAC7B,SAAO;AAAA;AAAA,qBAEY,OAAO,CAAC;AAAA,2BACF,QAAQ,QAAQ,IAAI;AAAA,YACnC,IAAI,QAAQ;AAAA,iBACR,oBAAI,KAAK,GAAE,mBAAmB,CAAC;AAAA;AAE/C;AAEA,eAAsB,iBAAoC;AACxD,SAAO;AAAA,IACL;AAAA,uBACmB,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAM/B,GAAG,MAAM,WAAW,CAAC;AAAA,EACvB;AACF;",
6
6
  "names": []
7
7
  }
@@ -16,7 +16,7 @@ const TOOL_INPUT_EXAMPLES = {
16
16
  KillShell: '{"shell_id": "shell_id_to_kill"}',
17
17
  // Task Management
18
18
  Task: '{"prompt": "task description", "description": "short description", "subagent_type": "agent-type"}',
19
- TodoWrite: '{"todos": [{"subject": "Task name", "description": "Details", "status": "pending"}]}',
19
+ TodoWrite: '{"todos": [{"content": "Task description", "status": "pending", "priority": "medium"}]}',
20
20
  // Web and API
21
21
  WebSearch: '{"query": "search query"}',
22
22
  URLFetcher: '{"url": "https://example.com", "prompt": "what to extract from page"}',
@@ -42,6 +42,7 @@ const TOOL_DESCRIPTIONS = {
42
42
  NotebookEdit: "For Jupyter notebooks. Requires notebook_path and new_source for the cell content.",
43
43
  Grep: 'Searches file contents with regex. Optional "glob" parameter filters files by pattern.',
44
44
  Task: "Creates a task for an AI agent. subagent_type determines which agent handles the task.",
45
+ TodoWrite: "Manages a task list. Each todo requires content (description), status (pending/in_progress/completed), and priority (high/medium/low).",
45
46
  URLFetcher: 'Fetches web content. The "prompt" parameter guides what to extract from the page.',
46
47
  AskExpertModel: "Queries an alternative LLM model. Useful for specialized tasks requiring different models.",
47
48
  Lsp: "Language Server Protocol queries for code intelligence. Method and params depend on LSP spec."
@@ -74,6 +75,9 @@ const PARAMETER_DESCRIPTIONS = {
74
75
  pattern: "Regular expression pattern to search for",
75
76
  path: "Directory to search in (optional, defaults to current directory)",
76
77
  glob: "Additional glob pattern to filter files being searched"
78
+ },
79
+ TodoWrite: {
80
+ todos: "Array of todo items. Each item must have: content (string), status (pending/in_progress/completed), priority (high/medium/low). Optional: id, activeForm."
77
81
  }
78
82
  };
79
83
  export {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/constants/toolInputExamples.ts"],
4
- "sourcesContent": ["/**\n * Tool Input Examples and Descriptions\n *\n * Provides user-friendly examples and descriptions for all tools to help with\n * error messaging when tool input validation fails. Each entry includes:\n * - A canonical example showing required parameters\n * - Optional description for complex tools\n */\n\nexport const TOOL_INPUT_EXAMPLES: Record<string, string> = {\n // File Operations\n Read: '{\"file_path\": \"/path/to/file.txt\"}',\n Write: '{\"file_path\": \"/path/to/file.txt\", \"content\": \"file contents\"}',\n Edit: '{\"file_path\": \"/path/to/file.txt\", \"old_string\": \"old text\", \"new_string\": \"new text\"}',\n MultiEdit:\n '{\"file_path\": \"/path/to/file.txt\", \"edits\": [{\"old_string\": \"old\", \"new_string\": \"new\"}]}',\n NotebookEdit:\n '{\"notebook_path\": \"/path/to/notebook.ipynb\", \"new_source\": \"cell source code\"}',\n NotebookRead: '{\"notebook_path\": \"/path/to/notebook.ipynb\"}',\n\n // Directory and Search\n Glob: '{\"pattern\": \"**/*.ts\", \"path\": \"/optional/search/path\"}',\n Grep: '{\"pattern\": \"search_term\", \"path\": \"/optional/search/path\", \"glob\": \"*.ts\"}',\n Ls: '{\"path\": \"/path/to/directory\"}',\n\n // Shell Execution\n Bash: '{\"command\": \"ls -la\"}',\n BashOutput: '{\"command\": \"ls -la\", \"shell_id\": \"optional_shell_id\"}',\n KillShell: '{\"shell_id\": \"shell_id_to_kill\"}',\n\n // Task Management\n Task: '{\"prompt\": \"task description\", \"description\": \"short description\", \"subagent_type\": \"agent-type\"}',\n TodoWrite:\n '{\"todos\": [{\"subject\": \"Task name\", \"description\": \"Details\", \"status\": \"pending\"}]}',\n\n // Web and API\n WebSearch: '{\"query\": \"search query\"}',\n URLFetcher:\n '{\"url\": \"https://example.com\", \"prompt\": \"what to extract from page\"}',\n\n // LLM Interactions\n AskExpertModel:\n '{\"model\": \"model-name\", \"prompt\": \"question for expert\", \"context\": \"optional context\"}',\n AskUserQuestion:\n '{\"question\": \"question to ask user\", \"default\": \"optional default\"}',\n\n // Memory (Anthropic-only)\n MemoryRead: '{\"name\": \"memory_block_name\"}',\n MemoryWrite: '{\"name\": \"memory_block_name\", \"content\": \"memory content\"}',\n\n // Planning and Reasoning\n Think: '{\"reasoning\": \"your thinking process\", \"plan\": \"optional plan\"}',\n EnterPlanMode: '{}',\n ExitPlanMode: '{}',\n\n // Code Intelligence\n Lsp: '{\"method\": \"textDocument/definition\", \"params\": {\"position\": {\"line\": 10, \"character\": 5}}}',\n Skill: '{\"skill\": \"skill_name\", \"args\": \"optional arguments\"}',\n\n // MCP Resources\n ListMcpResources:\n '{\"server\": \"server_name\", \"uri\": \"optional_resource_uri\", \"include\": \"resource_type\"}',\n ReadMcpResource: '{\"uri\": \"resource://path\"}',\n}\n\n/**\n * Tool Input Descriptions\n *\n * Provides helpful descriptions for complex tools to include in error messages\n */\nexport const TOOL_DESCRIPTIONS: Record<string, string> = {\n MultiEdit:\n 'Allows multiple edits in a single file. The \"edits\" parameter is an array of edit objects.',\n NotebookEdit:\n 'For Jupyter notebooks. Requires notebook_path and new_source for the cell content.',\n Grep: 'Searches file contents with regex. Optional \"glob\" parameter filters files by pattern.',\n Task: 'Creates a task for an AI agent. subagent_type determines which agent handles the task.',\n URLFetcher:\n 'Fetches web content. The \"prompt\" parameter guides what to extract from the page.',\n AskExpertModel:\n 'Queries an alternative LLM model. Useful for specialized tasks requiring different models.',\n Lsp: 'Language Server Protocol queries for code intelligence. Method and params depend on LSP spec.',\n}\n\n/**\n * Parameter Descriptions for Common Tool Parameters\n *\n * Helps provide more specific error messages when particular parameters are invalid\n */\nexport const PARAMETER_DESCRIPTIONS: Record<string, Record<string, string>> = {\n Read: {\n file_path: 'Must be an absolute file path (e.g., /home/user/file.txt)',\n offset: 'Optional line number to start reading from (0-indexed)',\n limit: 'Optional number of lines to read from the offset',\n },\n Write: {\n file_path: 'Must be an absolute file path (e.g., /home/user/file.txt)',\n content: 'The file contents to write',\n },\n Edit: {\n file_path: 'Must be an absolute file path (e.g., /home/user/file.txt)',\n old_string: 'The exact text to find and replace (must match exactly)',\n new_string: 'The text to replace it with',\n },\n Bash: {\n command:\n 'The shell command to execute (will run in current working directory)',\n timeout: 'Maximum execution time in milliseconds (max 600000 = 10 minutes)',\n run_in_background:\n 'Set to true to run command without waiting for completion',\n },\n Glob: {\n pattern: 'Glob pattern like **/*.ts or src/**/*.{ts,tsx}',\n path: 'Directory to search in (optional, defaults to current directory)',\n },\n Grep: {\n pattern: 'Regular expression pattern to search for',\n path: 'Directory to search in (optional, defaults to current directory)',\n glob: 'Additional glob pattern to filter files being searched',\n },\n}\n"],
5
- "mappings": "AASO,MAAM,sBAA8C;AAAA;AAAA,EAEzD,MAAM;AAAA,EACN,OAAO;AAAA,EACP,MAAM;AAAA,EACN,WACE;AAAA,EACF,cACE;AAAA,EACF,cAAc;AAAA;AAAA,EAGd,MAAM;AAAA,EACN,MAAM;AAAA,EACN,IAAI;AAAA;AAAA,EAGJ,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,WAAW;AAAA;AAAA,EAGX,MAAM;AAAA,EACN,WACE;AAAA;AAAA,EAGF,WAAW;AAAA,EACX,YACE;AAAA;AAAA,EAGF,gBACE;AAAA,EACF,iBACE;AAAA;AAAA,EAGF,YAAY;AAAA,EACZ,aAAa;AAAA;AAAA,EAGb,OAAO;AAAA,EACP,eAAe;AAAA,EACf,cAAc;AAAA;AAAA,EAGd,KAAK;AAAA,EACL,OAAO;AAAA;AAAA,EAGP,kBACE;AAAA,EACF,iBAAiB;AACnB;AAOO,MAAM,oBAA4C;AAAA,EACvD,WACE;AAAA,EACF,cACE;AAAA,EACF,MAAM;AAAA,EACN,MAAM;AAAA,EACN,YACE;AAAA,EACF,gBACE;AAAA,EACF,KAAK;AACP;AAOO,MAAM,yBAAiE;AAAA,EAC5E,MAAM;AAAA,IACJ,WAAW;AAAA,IACX,QAAQ;AAAA,IACR,OAAO;AAAA,EACT;AAAA,EACA,OAAO;AAAA,IACL,WAAW;AAAA,IACX,SAAS;AAAA,EACX;AAAA,EACA,MAAM;AAAA,IACJ,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,YAAY;AAAA,EACd;AAAA,EACA,MAAM;AAAA,IACJ,SACE;AAAA,IACF,SAAS;AAAA,IACT,mBACE;AAAA,EACJ;AAAA,EACA,MAAM;AAAA,IACJ,SAAS;AAAA,IACT,MAAM;AAAA,EACR;AAAA,EACA,MAAM;AAAA,IACJ,SAAS;AAAA,IACT,MAAM;AAAA,IACN,MAAM;AAAA,EACR;AACF;",
4
+ "sourcesContent": ["/**\n * Tool Input Examples and Descriptions\n *\n * Provides user-friendly examples and descriptions for all tools to help with\n * error messaging when tool input validation fails. Each entry includes:\n * - A canonical example showing required parameters\n * - Optional description for complex tools\n */\n\nexport const TOOL_INPUT_EXAMPLES: Record<string, string> = {\n // File Operations\n Read: '{\"file_path\": \"/path/to/file.txt\"}',\n Write: '{\"file_path\": \"/path/to/file.txt\", \"content\": \"file contents\"}',\n Edit: '{\"file_path\": \"/path/to/file.txt\", \"old_string\": \"old text\", \"new_string\": \"new text\"}',\n MultiEdit:\n '{\"file_path\": \"/path/to/file.txt\", \"edits\": [{\"old_string\": \"old\", \"new_string\": \"new\"}]}',\n NotebookEdit:\n '{\"notebook_path\": \"/path/to/notebook.ipynb\", \"new_source\": \"cell source code\"}',\n NotebookRead: '{\"notebook_path\": \"/path/to/notebook.ipynb\"}',\n\n // Directory and Search\n Glob: '{\"pattern\": \"**/*.ts\", \"path\": \"/optional/search/path\"}',\n Grep: '{\"pattern\": \"search_term\", \"path\": \"/optional/search/path\", \"glob\": \"*.ts\"}',\n Ls: '{\"path\": \"/path/to/directory\"}',\n\n // Shell Execution\n Bash: '{\"command\": \"ls -la\"}',\n BashOutput: '{\"command\": \"ls -la\", \"shell_id\": \"optional_shell_id\"}',\n KillShell: '{\"shell_id\": \"shell_id_to_kill\"}',\n\n // Task Management\n Task: '{\"prompt\": \"task description\", \"description\": \"short description\", \"subagent_type\": \"agent-type\"}',\n TodoWrite:\n '{\"todos\": [{\"content\": \"Task description\", \"status\": \"pending\", \"priority\": \"medium\"}]}',\n\n // Web and API\n WebSearch: '{\"query\": \"search query\"}',\n URLFetcher:\n '{\"url\": \"https://example.com\", \"prompt\": \"what to extract from page\"}',\n\n // LLM Interactions\n AskExpertModel:\n '{\"model\": \"model-name\", \"prompt\": \"question for expert\", \"context\": \"optional context\"}',\n AskUserQuestion:\n '{\"question\": \"question to ask user\", \"default\": \"optional default\"}',\n\n // Memory (Anthropic-only)\n MemoryRead: '{\"name\": \"memory_block_name\"}',\n MemoryWrite: '{\"name\": \"memory_block_name\", \"content\": \"memory content\"}',\n\n // Planning and Reasoning\n Think: '{\"reasoning\": \"your thinking process\", \"plan\": \"optional plan\"}',\n EnterPlanMode: '{}',\n ExitPlanMode: '{}',\n\n // Code Intelligence\n Lsp: '{\"method\": \"textDocument/definition\", \"params\": {\"position\": {\"line\": 10, \"character\": 5}}}',\n Skill: '{\"skill\": \"skill_name\", \"args\": \"optional arguments\"}',\n\n // MCP Resources\n ListMcpResources:\n '{\"server\": \"server_name\", \"uri\": \"optional_resource_uri\", \"include\": \"resource_type\"}',\n ReadMcpResource: '{\"uri\": \"resource://path\"}',\n}\n\n/**\n * Tool Input Descriptions\n *\n * Provides helpful descriptions for complex tools to include in error messages\n */\nexport const TOOL_DESCRIPTIONS: Record<string, string> = {\n MultiEdit:\n 'Allows multiple edits in a single file. The \"edits\" parameter is an array of edit objects.',\n NotebookEdit:\n 'For Jupyter notebooks. Requires notebook_path and new_source for the cell content.',\n Grep: 'Searches file contents with regex. Optional \"glob\" parameter filters files by pattern.',\n Task: 'Creates a task for an AI agent. subagent_type determines which agent handles the task.',\n TodoWrite:\n 'Manages a task list. Each todo requires content (description), status (pending/in_progress/completed), and priority (high/medium/low).',\n URLFetcher:\n 'Fetches web content. The \"prompt\" parameter guides what to extract from the page.',\n AskExpertModel:\n 'Queries an alternative LLM model. Useful for specialized tasks requiring different models.',\n Lsp: 'Language Server Protocol queries for code intelligence. Method and params depend on LSP spec.',\n}\n\n/**\n * Parameter Descriptions for Common Tool Parameters\n *\n * Helps provide more specific error messages when particular parameters are invalid\n */\nexport const PARAMETER_DESCRIPTIONS: Record<string, Record<string, string>> = {\n Read: {\n file_path: 'Must be an absolute file path (e.g., /home/user/file.txt)',\n offset: 'Optional line number to start reading from (0-indexed)',\n limit: 'Optional number of lines to read from the offset',\n },\n Write: {\n file_path: 'Must be an absolute file path (e.g., /home/user/file.txt)',\n content: 'The file contents to write',\n },\n Edit: {\n file_path: 'Must be an absolute file path (e.g., /home/user/file.txt)',\n old_string: 'The exact text to find and replace (must match exactly)',\n new_string: 'The text to replace it with',\n },\n Bash: {\n command:\n 'The shell command to execute (will run in current working directory)',\n timeout: 'Maximum execution time in milliseconds (max 600000 = 10 minutes)',\n run_in_background:\n 'Set to true to run command without waiting for completion',\n },\n Glob: {\n pattern: 'Glob pattern like **/*.ts or src/**/*.{ts,tsx}',\n path: 'Directory to search in (optional, defaults to current directory)',\n },\n Grep: {\n pattern: 'Regular expression pattern to search for',\n path: 'Directory to search in (optional, defaults to current directory)',\n glob: 'Additional glob pattern to filter files being searched',\n },\n TodoWrite: {\n todos:\n 'Array of todo items. Each item must have: content (string), status (pending/in_progress/completed), priority (high/medium/low). Optional: id, activeForm.',\n },\n}\n"],
5
+ "mappings": "AASO,MAAM,sBAA8C;AAAA;AAAA,EAEzD,MAAM;AAAA,EACN,OAAO;AAAA,EACP,MAAM;AAAA,EACN,WACE;AAAA,EACF,cACE;AAAA,EACF,cAAc;AAAA;AAAA,EAGd,MAAM;AAAA,EACN,MAAM;AAAA,EACN,IAAI;AAAA;AAAA,EAGJ,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,WAAW;AAAA;AAAA,EAGX,MAAM;AAAA,EACN,WACE;AAAA;AAAA,EAGF,WAAW;AAAA,EACX,YACE;AAAA;AAAA,EAGF,gBACE;AAAA,EACF,iBACE;AAAA;AAAA,EAGF,YAAY;AAAA,EACZ,aAAa;AAAA;AAAA,EAGb,OAAO;AAAA,EACP,eAAe;AAAA,EACf,cAAc;AAAA;AAAA,EAGd,KAAK;AAAA,EACL,OAAO;AAAA;AAAA,EAGP,kBACE;AAAA,EACF,iBAAiB;AACnB;AAOO,MAAM,oBAA4C;AAAA,EACvD,WACE;AAAA,EACF,cACE;AAAA,EACF,MAAM;AAAA,EACN,MAAM;AAAA,EACN,WACE;AAAA,EACF,YACE;AAAA,EACF,gBACE;AAAA,EACF,KAAK;AACP;AAOO,MAAM,yBAAiE;AAAA,EAC5E,MAAM;AAAA,IACJ,WAAW;AAAA,IACX,QAAQ;AAAA,IACR,OAAO;AAAA,EACT;AAAA,EACA,OAAO;AAAA,IACL,WAAW;AAAA,IACX,SAAS;AAAA,EACX;AAAA,EACA,MAAM;AAAA,IACJ,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,YAAY;AAAA,EACd;AAAA,EACA,MAAM;AAAA,IACJ,SACE;AAAA,IACF,SAAS;AAAA,IACT,mBACE;AAAA,EACJ;AAAA,EACA,MAAM;AAAA,IACJ,SAAS;AAAA,IACT,MAAM;AAAA,EACR;AAAA,EACA,MAAM;AAAA,IACJ,SAAS;AAAA,IACT,MAAM;AAAA,IACN,MAAM;AAAA,EACR;AAAA,EACA,WAAW;AAAA,IACT,OACE;AAAA,EACJ;AACF;",
6
6
  "names": []
7
7
  }
@@ -311,6 +311,11 @@ class TokenStatsManagerImpl extends EventEmitter {
311
311
  const tokenStatsManager = TokenStatsManagerImpl.getInstance();
312
312
  function recordTokenUsage(usage, costUSD, model, context) {
313
313
  tokenStatsManager.recordUsage(usage, costUSD, model, context);
314
+ try {
315
+ const { recordMessage } = require("@utils/stats");
316
+ recordMessage(model, usage.inputTokens, usage.outputTokens, costUSD);
317
+ } catch {
318
+ }
314
319
  }
315
320
  function getGlobalTokenStats() {
316
321
  return tokenStatsManager.getGlobalStats();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/core/tokenStatsManager.ts"],
4
- "sourcesContent": ["/**\n * Token Statistics Manager\n *\n * Centralized token statistics tracking for the entire application.\n * This is the single source of truth for all token usage data.\n *\n * Architecture:\n * - Singleton pattern for global access\n * - Event-driven updates for real-time UI\n * - Hierarchical aggregation (global \u2192 agent \u2192 request)\n * - Backward compatible with existing costTracker\n *\n * Usage:\n * ```typescript\n * import { tokenStatsManager, recordTokenUsage } from '@core/tokenStatsManager'\n *\n * // Record usage from API response\n * recordTokenUsage(\n * { inputTokens: 100, outputTokens: 50 },\n * 0.0015,\n * 'gpt-4',\n * { agentId: 'agent-123' }\n * )\n *\n * // Get global stats\n * const stats = tokenStatsManager.getGlobalStats()\n *\n * // Subscribe to updates\n * const unsubscribe = tokenStatsManager.onStatsUpdate((event) => {\n * console.log('Stats updated:', event)\n * })\n * ```\n */\n\nimport { EventEmitter } from 'events'\nimport type {\n TokenUsageRecord,\n AggregatedTokenStats,\n TokenStatsScope,\n TokenStatsEvent,\n TokenTrackingContext,\n RawTokenUsage,\n ModelTokenStats,\n} from './tokenStats'\nimport { DEFAULT_ESTIMATION_CONFIG } from './tokenStats'\n\n/**\n * TokenStatsManager - Centralized token statistics tracking\n */\nclass TokenStatsManagerImpl extends EventEmitter {\n private static instance: TokenStatsManagerImpl | null = null\n\n // Global aggregated stats\n private globalStats: AggregatedTokenStats = this.createEmptyStats()\n\n // Per-agent stats (agentId \u2192 stats)\n private agentStats: Map<string, AggregatedTokenStats> = new Map()\n\n // Per-request records (requestId \u2192 record) - for debugging, with LRU eviction\n private requestRecords: Map<string, TokenUsageRecord> = new Map()\n\n // Configuration\n private static readonly MAX_REQUEST_RECORDS = 1000\n\n private constructor() {\n super()\n this.setMaxListeners(100)\n }\n\n /**\n * Get the singleton instance\n */\n static getInstance(): TokenStatsManagerImpl {\n if (!TokenStatsManagerImpl.instance) {\n TokenStatsManagerImpl.instance = new TokenStatsManagerImpl()\n }\n return TokenStatsManagerImpl.instance\n }\n\n /**\n * Record token usage from an API response\n *\n * This is the PRIMARY entry point - called from claude.ts\n * after every API response.\n *\n * @param usage - Raw token usage from API\n * @param costUSD - Calculated cost in USD\n * @param model - Model name used\n * @param context - Optional tracking context (agentId, toolUseId)\n */\n recordUsage(\n usage: RawTokenUsage,\n costUSD: number,\n model: string,\n context?: TokenTrackingContext,\n ): void {\n const record: TokenUsageRecord = {\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n cacheCreationTokens: usage.cacheCreationTokens ?? 0,\n cacheReadTokens: usage.cacheReadTokens ?? 0,\n totalTokens: usage.inputTokens + usage.outputTokens,\n estimatedCostUSD: costUSD,\n source: 'api',\n timestamp: Date.now(),\n model,\n }\n\n // Update global stats\n this.aggregateInto(this.globalStats, record)\n\n // Update agent stats if in agent context\n if (context?.agentId) {\n let stats = this.agentStats.get(context.agentId)\n if (!stats) {\n stats = this.createEmptyStats()\n this.agentStats.set(context.agentId, stats)\n }\n this.aggregateInto(stats, record)\n }\n\n // Store request record (with LRU eviction)\n const requestId =\n context?.toolUseId ??\n `req-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`\n this.requestRecords.set(requestId, record)\n if (this.requestRecords.size > TokenStatsManagerImpl.MAX_REQUEST_RECORDS) {\n const oldestKey = this.requestRecords.keys().next().value\n if (oldestKey) this.requestRecords.delete(oldestKey)\n }\n\n // Emit event for UI updates\n const scope: TokenStatsScope = context?.agentId\n ? { type: 'agent', agentId: context.agentId }\n : { type: 'global' }\n\n this.emitEvent({\n eventType: 'usage_recorded',\n scope,\n usage: record,\n aggregated: context?.agentId\n ? this.agentStats.get(context.agentId)!\n : this.globalStats,\n globalStats: this.globalStats,\n })\n }\n\n /**\n * Estimate token count from text\n *\n * Uses a simple character-based estimation. This is a fallback\n * when the API doesn't return token counts.\n *\n * @param text - Text to estimate tokens for\n * @returns Estimated token count\n */\n estimateTokens(text: string): number {\n return Math.ceil(text.length / DEFAULT_ESTIMATION_CONFIG.charsPerToken)\n }\n\n /**\n * Record estimated usage when API doesn't return token counts\n *\n * This is used as a fallback for APIs that don't return usage data.\n *\n * @param inputText - Input text (prompt)\n * @param outputText - Output text (completion)\n * @param model - Model name\n * @param context - Optional tracking context\n */\n recordEstimatedUsage(\n inputText: string,\n outputText: string,\n model: string,\n context?: TokenTrackingContext,\n ): void {\n const inputTokens = this.estimateTokens(inputText)\n const outputTokens = this.estimateTokens(outputText)\n\n const costUSD =\n (inputTokens / 1_000_000) *\n DEFAULT_ESTIMATION_CONFIG.defaultInputCostPerMillion +\n (outputTokens / 1_000_000) *\n DEFAULT_ESTIMATION_CONFIG.defaultOutputCostPerMillion\n\n const record: TokenUsageRecord = {\n inputTokens,\n outputTokens,\n cacheCreationTokens: 0,\n cacheReadTokens: 0,\n totalTokens: inputTokens + outputTokens,\n estimatedCostUSD: costUSD,\n source: 'estimated',\n timestamp: Date.now(),\n model,\n }\n\n // Update global stats\n this.aggregateInto(this.globalStats, record)\n\n // Update agent stats if in context\n if (context?.agentId) {\n let stats = this.agentStats.get(context.agentId)\n if (!stats) {\n stats = this.createEmptyStats()\n this.agentStats.set(context.agentId, stats)\n }\n this.aggregateInto(stats, record)\n }\n\n // Emit event\n this.emitEvent({\n eventType: 'usage_recorded',\n scope: { type: 'global' },\n usage: record,\n aggregated: this.globalStats,\n globalStats: this.globalStats,\n })\n }\n\n // ===== Getters =====\n\n /**\n * Get global aggregated statistics\n */\n getGlobalStats(): AggregatedTokenStats {\n return this.cloneStats(this.globalStats)\n }\n\n /**\n * Get statistics for a specific agent\n *\n * @param agentId - Agent ID to get stats for\n * @returns Agent stats or null if not found\n */\n getAgentStats(agentId: string): AggregatedTokenStats | null {\n const stats = this.agentStats.get(agentId)\n return stats ? this.cloneStats(stats) : null\n }\n\n /**\n * Get all agent statistics\n */\n getAllAgentStats(): Map<string, AggregatedTokenStats> {\n const result = new Map<string, AggregatedTokenStats>()\n for (const [agentId, stats] of this.agentStats) {\n result.set(agentId, this.cloneStats(stats))\n }\n return result\n }\n\n /**\n * Get a specific request record\n */\n getRequestRecord(requestId: string): TokenUsageRecord | null {\n return this.requestRecords.get(requestId) ?? null\n }\n\n // ===== Backward Compatibility Layer =====\n\n /**\n * Get total tokens (for costTracker.getTokenCounts compatibility)\n *\n * This method provides backward compatibility with the existing\n * costTracker.getTokenCounts() interface.\n */\n getTokenCounts(): {\n input: number\n output: number\n cacheCreation: number\n cacheRead: number\n total: number\n } {\n return {\n input: this.globalStats.totalInputTokens,\n output: this.globalStats.totalOutputTokens,\n cacheCreation: this.globalStats.totalCacheCreationTokens,\n cacheRead: this.globalStats.totalCacheReadTokens,\n total: this.globalStats.grandTotalTokens,\n }\n }\n\n // ===== Event Subscription =====\n\n /**\n * Subscribe to all stats updates\n *\n * @param callback - Called when any stats change\n * @returns Unsubscribe function\n */\n onStatsUpdate(callback: (event: TokenStatsEvent) => void): () => void {\n this.on('stats_update', callback)\n return () => this.off('stats_update', callback)\n }\n\n /**\n * Subscribe to updates for a specific agent\n *\n * @param agentId - Agent ID to subscribe to\n * @param callback - Called when agent stats change\n * @returns Unsubscribe function\n */\n onAgentStatsUpdate(\n agentId: string,\n callback: (stats: AggregatedTokenStats) => void,\n ): () => void {\n const handler = (event: TokenStatsEvent) => {\n if (event.scope.type === 'agent' && event.scope.agentId === agentId) {\n callback(event.aggregated)\n }\n }\n this.on('stats_update', handler)\n return () => this.off('stats_update', handler)\n }\n\n /**\n * Subscribe to global stats updates only\n *\n * @param callback - Called when global stats change\n * @returns Unsubscribe function\n */\n onGlobalStatsUpdate(\n callback: (stats: AggregatedTokenStats) => void,\n ): () => void {\n const handler = (event: TokenStatsEvent) => {\n callback(event.globalStats)\n }\n this.on('stats_update', handler)\n return () => this.off('stats_update', handler)\n }\n\n // ===== Agent Lifecycle =====\n\n /**\n * Mark an agent's scope as completed\n *\n * This emits a scope_completed event and optionally\n * cleans up the agent's stats from memory.\n *\n * @param agentId - Agent ID to complete\n * @param cleanup - Whether to remove from memory (default: false)\n */\n completeAgentScope(agentId: string, cleanup: boolean = false): void {\n const stats = this.agentStats.get(agentId)\n if (!stats) return\n\n this.emitEvent({\n eventType: 'scope_completed',\n scope: { type: 'agent', agentId },\n aggregated: stats,\n globalStats: this.globalStats,\n })\n\n if (cleanup) {\n this.agentStats.delete(agentId)\n }\n }\n\n // ===== Internal Methods =====\n\n private createEmptyStats(): AggregatedTokenStats {\n return {\n totalInputTokens: 0,\n totalOutputTokens: 0,\n totalCacheCreationTokens: 0,\n totalCacheReadTokens: 0,\n grandTotalTokens: 0,\n totalCostUSD: 0,\n requestCount: 0,\n byModel: new Map(),\n }\n }\n\n private aggregateInto(\n stats: AggregatedTokenStats,\n record: TokenUsageRecord,\n ): void {\n stats.totalInputTokens += record.inputTokens\n stats.totalOutputTokens += record.outputTokens\n stats.totalCacheCreationTokens += record.cacheCreationTokens\n stats.totalCacheReadTokens += record.cacheReadTokens\n stats.grandTotalTokens += record.totalTokens\n stats.totalCostUSD += record.estimatedCostUSD\n stats.requestCount += 1\n\n if (!stats.firstRequestTime) {\n stats.firstRequestTime = record.timestamp\n }\n stats.lastRequestTime = record.timestamp\n\n // Update per-model breakdown\n const modelStats = stats.byModel.get(record.model)\n if (modelStats) {\n modelStats.inputTokens += record.inputTokens\n modelStats.outputTokens += record.outputTokens\n modelStats.totalTokens += record.totalTokens\n modelStats.estimatedCostUSD += record.estimatedCostUSD\n modelStats.requestCount += 1\n } else {\n stats.byModel.set(record.model, {\n model: record.model,\n inputTokens: record.inputTokens,\n outputTokens: record.outputTokens,\n totalTokens: record.totalTokens,\n estimatedCostUSD: record.estimatedCostUSD,\n requestCount: 1,\n })\n }\n }\n\n private cloneStats(stats: AggregatedTokenStats): AggregatedTokenStats {\n return {\n ...stats,\n byModel: new Map(stats.byModel),\n }\n }\n\n private emitEvent(event: TokenStatsEvent): void {\n this.emit('stats_update', event)\n }\n\n /**\n * Reset all stats (for testing only)\n */\n resetForTests(): void {\n if (process.env.NODE_ENV !== 'test') {\n throw new Error('resetForTests can only be called in tests')\n }\n this.reset()\n }\n\n /**\n * Reset all statistics\n *\n * Called by costTracker.resetStateForTests() for backward compatibility.\n */\n reset(): void {\n this.globalStats = this.createEmptyStats()\n this.agentStats.clear()\n this.requestRecords.clear()\n }\n}\n\n// Export singleton instance\nexport const tokenStatsManager = TokenStatsManagerImpl.getInstance()\n\n// ===== Convenience Functions =====\n\n/**\n * Record token usage from an API response\n *\n * This is the main function to call from claude.ts after each API response.\n */\nexport function recordTokenUsage(\n usage: RawTokenUsage,\n costUSD: number,\n model: string,\n context?: TokenTrackingContext,\n): void {\n tokenStatsManager.recordUsage(usage, costUSD, model, context)\n}\n\n/**\n * Get global token statistics\n */\nexport function getGlobalTokenStats(): AggregatedTokenStats {\n return tokenStatsManager.getGlobalStats()\n}\n\n/**\n * Get token statistics for a specific agent\n */\nexport function getAgentTokenStats(\n agentId: string,\n): AggregatedTokenStats | null {\n return tokenStatsManager.getAgentStats(agentId)\n}\n\n/**\n * Estimate token count from text\n */\nexport function estimateTokenCount(text: string): number {\n return tokenStatsManager.estimateTokens(text)\n}\n"],
5
- "mappings": "AAkCA,SAAS,oBAAoB;AAU7B,SAAS,iCAAiC;AAK1C,MAAM,8BAA8B,aAAa;AAAA,EAC/C,OAAe,WAAyC;AAAA;AAAA,EAGhD,cAAoC,KAAK,iBAAiB;AAAA;AAAA,EAG1D,aAAgD,oBAAI,IAAI;AAAA;AAAA,EAGxD,iBAAgD,oBAAI,IAAI;AAAA;AAAA,EAGhE,OAAwB,sBAAsB;AAAA,EAEtC,cAAc;AACpB,UAAM;AACN,SAAK,gBAAgB,GAAG;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,cAAqC;AAC1C,QAAI,CAAC,sBAAsB,UAAU;AACnC,4BAAsB,WAAW,IAAI,sBAAsB;AAAA,IAC7D;AACA,WAAO,sBAAsB;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,YACE,OACA,SACA,OACA,SACM;AACN,UAAM,SAA2B;AAAA,MAC/B,aAAa,MAAM;AAAA,MACnB,cAAc,MAAM;AAAA,MACpB,qBAAqB,MAAM,uBAAuB;AAAA,MAClD,iBAAiB,MAAM,mBAAmB;AAAA,MAC1C,aAAa,MAAM,cAAc,MAAM;AAAA,MACvC,kBAAkB;AAAA,MAClB,QAAQ;AAAA,MACR,WAAW,KAAK,IAAI;AAAA,MACpB;AAAA,IACF;AAGA,SAAK,cAAc,KAAK,aAAa,MAAM;AAG3C,QAAI,SAAS,SAAS;AACpB,UAAI,QAAQ,KAAK,WAAW,IAAI,QAAQ,OAAO;AAC/C,UAAI,CAAC,OAAO;AACV,gBAAQ,KAAK,iBAAiB;AAC9B,aAAK,WAAW,IAAI,QAAQ,SAAS,KAAK;AAAA,MA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,eAAe,MAAM;AAAA,EAC5B;AACF;AAGO,MAAM,oBAAoB,sBAAsB,YAAY;AAS5D,SAAS,iBACd,OACA,SACA,OACA,SACM;AACN,oBAAkB,YAAY,OAAO,SAAS,OAAO,OAAO;AAC9D;AAKO,SAAS,sBAA4C;AAC1D,SAAO,kBAAkB,eAAe;AAC1C;AAKO,SAAS,mBACd,SAC6B;AAC7B,SAAO,kBAAkB,cAAc,OAAO;AAChD;AAKO,SAAS,mBAAmB,MAAsB;AACvD,SAAO,kBAAkB,eAAe,IAAI;AAC9C;",
4
+ "sourcesContent": ["/**\n * Token Statistics Manager\n *\n * Centralized token statistics tracking for the entire application.\n * This is the single source of truth for all token usage data.\n *\n * Architecture:\n * - Singleton pattern for global access\n * - Event-driven updates for real-time UI\n * - Hierarchical aggregation (global \u2192 agent \u2192 request)\n * - Backward compatible with existing costTracker\n *\n * Usage:\n * ```typescript\n * import { tokenStatsManager, recordTokenUsage } from '@core/tokenStatsManager'\n *\n * // Record usage from API response\n * recordTokenUsage(\n * { inputTokens: 100, outputTokens: 50 },\n * 0.0015,\n * 'gpt-4',\n * { agentId: 'agent-123' }\n * )\n *\n * // Get global stats\n * const stats = tokenStatsManager.getGlobalStats()\n *\n * // Subscribe to updates\n * const unsubscribe = tokenStatsManager.onStatsUpdate((event) => {\n * console.log('Stats updated:', event)\n * })\n * ```\n */\n\nimport { EventEmitter } from 'events'\nimport type {\n TokenUsageRecord,\n AggregatedTokenStats,\n TokenStatsScope,\n TokenStatsEvent,\n TokenTrackingContext,\n RawTokenUsage,\n ModelTokenStats,\n} from './tokenStats'\nimport { DEFAULT_ESTIMATION_CONFIG } from './tokenStats'\n\n/**\n * TokenStatsManager - Centralized token statistics tracking\n */\nclass TokenStatsManagerImpl extends EventEmitter {\n private static instance: TokenStatsManagerImpl | null = null\n\n // Global aggregated stats\n private globalStats: AggregatedTokenStats = this.createEmptyStats()\n\n // Per-agent stats (agentId \u2192 stats)\n private agentStats: Map<string, AggregatedTokenStats> = new Map()\n\n // Per-request records (requestId \u2192 record) - for debugging, with LRU eviction\n private requestRecords: Map<string, TokenUsageRecord> = new Map()\n\n // Configuration\n private static readonly MAX_REQUEST_RECORDS = 1000\n\n private constructor() {\n super()\n this.setMaxListeners(100)\n }\n\n /**\n * Get the singleton instance\n */\n static getInstance(): TokenStatsManagerImpl {\n if (!TokenStatsManagerImpl.instance) {\n TokenStatsManagerImpl.instance = new TokenStatsManagerImpl()\n }\n return TokenStatsManagerImpl.instance\n }\n\n /**\n * Record token usage from an API response\n *\n * This is the PRIMARY entry point - called from claude.ts\n * after every API response.\n *\n * @param usage - Raw token usage from API\n * @param costUSD - Calculated cost in USD\n * @param model - Model name used\n * @param context - Optional tracking context (agentId, toolUseId)\n */\n recordUsage(\n usage: RawTokenUsage,\n costUSD: number,\n model: string,\n context?: TokenTrackingContext,\n ): void {\n const record: TokenUsageRecord = {\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n cacheCreationTokens: usage.cacheCreationTokens ?? 0,\n cacheReadTokens: usage.cacheReadTokens ?? 0,\n totalTokens: usage.inputTokens + usage.outputTokens,\n estimatedCostUSD: costUSD,\n source: 'api',\n timestamp: Date.now(),\n model,\n }\n\n // Update global stats\n this.aggregateInto(this.globalStats, record)\n\n // Update agent stats if in agent context\n if (context?.agentId) {\n let stats = this.agentStats.get(context.agentId)\n if (!stats) {\n stats = this.createEmptyStats()\n this.agentStats.set(context.agentId, stats)\n }\n this.aggregateInto(stats, record)\n }\n\n // Store request record (with LRU eviction)\n const requestId =\n context?.toolUseId ??\n `req-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`\n this.requestRecords.set(requestId, record)\n if (this.requestRecords.size > TokenStatsManagerImpl.MAX_REQUEST_RECORDS) {\n const oldestKey = this.requestRecords.keys().next().value\n if (oldestKey) this.requestRecords.delete(oldestKey)\n }\n\n // Emit event for UI updates\n const scope: TokenStatsScope = context?.agentId\n ? { type: 'agent', agentId: context.agentId }\n : { type: 'global' }\n\n this.emitEvent({\n eventType: 'usage_recorded',\n scope,\n usage: record,\n aggregated: context?.agentId\n ? this.agentStats.get(context.agentId)!\n : this.globalStats,\n globalStats: this.globalStats,\n })\n }\n\n /**\n * Estimate token count from text\n *\n * Uses a simple character-based estimation. This is a fallback\n * when the API doesn't return token counts.\n *\n * @param text - Text to estimate tokens for\n * @returns Estimated token count\n */\n estimateTokens(text: string): number {\n return Math.ceil(text.length / DEFAULT_ESTIMATION_CONFIG.charsPerToken)\n }\n\n /**\n * Record estimated usage when API doesn't return token counts\n *\n * This is used as a fallback for APIs that don't return usage data.\n *\n * @param inputText - Input text (prompt)\n * @param outputText - Output text (completion)\n * @param model - Model name\n * @param context - Optional tracking context\n */\n recordEstimatedUsage(\n inputText: string,\n outputText: string,\n model: string,\n context?: TokenTrackingContext,\n ): void {\n const inputTokens = this.estimateTokens(inputText)\n const outputTokens = this.estimateTokens(outputText)\n\n const costUSD =\n (inputTokens / 1_000_000) *\n DEFAULT_ESTIMATION_CONFIG.defaultInputCostPerMillion +\n (outputTokens / 1_000_000) *\n DEFAULT_ESTIMATION_CONFIG.defaultOutputCostPerMillion\n\n const record: TokenUsageRecord = {\n inputTokens,\n outputTokens,\n cacheCreationTokens: 0,\n cacheReadTokens: 0,\n totalTokens: inputTokens + outputTokens,\n estimatedCostUSD: costUSD,\n source: 'estimated',\n timestamp: Date.now(),\n model,\n }\n\n // Update global stats\n this.aggregateInto(this.globalStats, record)\n\n // Update agent stats if in context\n if (context?.agentId) {\n let stats = this.agentStats.get(context.agentId)\n if (!stats) {\n stats = this.createEmptyStats()\n this.agentStats.set(context.agentId, stats)\n }\n this.aggregateInto(stats, record)\n }\n\n // Emit event\n this.emitEvent({\n eventType: 'usage_recorded',\n scope: { type: 'global' },\n usage: record,\n aggregated: this.globalStats,\n globalStats: this.globalStats,\n })\n }\n\n // ===== Getters =====\n\n /**\n * Get global aggregated statistics\n */\n getGlobalStats(): AggregatedTokenStats {\n return this.cloneStats(this.globalStats)\n }\n\n /**\n * Get statistics for a specific agent\n *\n * @param agentId - Agent ID to get stats for\n * @returns Agent stats or null if not found\n */\n getAgentStats(agentId: string): AggregatedTokenStats | null {\n const stats = this.agentStats.get(agentId)\n return stats ? this.cloneStats(stats) : null\n }\n\n /**\n * Get all agent statistics\n */\n getAllAgentStats(): Map<string, AggregatedTokenStats> {\n const result = new Map<string, AggregatedTokenStats>()\n for (const [agentId, stats] of this.agentStats) {\n result.set(agentId, this.cloneStats(stats))\n }\n return result\n }\n\n /**\n * Get a specific request record\n */\n getRequestRecord(requestId: string): TokenUsageRecord | null {\n return this.requestRecords.get(requestId) ?? null\n }\n\n // ===== Backward Compatibility Layer =====\n\n /**\n * Get total tokens (for costTracker.getTokenCounts compatibility)\n *\n * This method provides backward compatibility with the existing\n * costTracker.getTokenCounts() interface.\n */\n getTokenCounts(): {\n input: number\n output: number\n cacheCreation: number\n cacheRead: number\n total: number\n } {\n return {\n input: this.globalStats.totalInputTokens,\n output: this.globalStats.totalOutputTokens,\n cacheCreation: this.globalStats.totalCacheCreationTokens,\n cacheRead: this.globalStats.totalCacheReadTokens,\n total: this.globalStats.grandTotalTokens,\n }\n }\n\n // ===== Event Subscription =====\n\n /**\n * Subscribe to all stats updates\n *\n * @param callback - Called when any stats change\n * @returns Unsubscribe function\n */\n onStatsUpdate(callback: (event: TokenStatsEvent) => void): () => void {\n this.on('stats_update', callback)\n return () => this.off('stats_update', callback)\n }\n\n /**\n * Subscribe to updates for a specific agent\n *\n * @param agentId - Agent ID to subscribe to\n * @param callback - Called when agent stats change\n * @returns Unsubscribe function\n */\n onAgentStatsUpdate(\n agentId: string,\n callback: (stats: AggregatedTokenStats) => void,\n ): () => void {\n const handler = (event: TokenStatsEvent) => {\n if (event.scope.type === 'agent' && event.scope.agentId === agentId) {\n callback(event.aggregated)\n }\n }\n this.on('stats_update', handler)\n return () => this.off('stats_update', handler)\n }\n\n /**\n * Subscribe to global stats updates only\n *\n * @param callback - Called when global stats change\n * @returns Unsubscribe function\n */\n onGlobalStatsUpdate(\n callback: (stats: AggregatedTokenStats) => void,\n ): () => void {\n const handler = (event: TokenStatsEvent) => {\n callback(event.globalStats)\n }\n this.on('stats_update', handler)\n return () => this.off('stats_update', handler)\n }\n\n // ===== Agent Lifecycle =====\n\n /**\n * Mark an agent's scope as completed\n *\n * This emits a scope_completed event and optionally\n * cleans up the agent's stats from memory.\n *\n * @param agentId - Agent ID to complete\n * @param cleanup - Whether to remove from memory (default: false)\n */\n completeAgentScope(agentId: string, cleanup: boolean = false): void {\n const stats = this.agentStats.get(agentId)\n if (!stats) return\n\n this.emitEvent({\n eventType: 'scope_completed',\n scope: { type: 'agent', agentId },\n aggregated: stats,\n globalStats: this.globalStats,\n })\n\n if (cleanup) {\n this.agentStats.delete(agentId)\n }\n }\n\n // ===== Internal Methods =====\n\n private createEmptyStats(): AggregatedTokenStats {\n return {\n totalInputTokens: 0,\n totalOutputTokens: 0,\n totalCacheCreationTokens: 0,\n totalCacheReadTokens: 0,\n grandTotalTokens: 0,\n totalCostUSD: 0,\n requestCount: 0,\n byModel: new Map(),\n }\n }\n\n private aggregateInto(\n stats: AggregatedTokenStats,\n record: TokenUsageRecord,\n ): void {\n stats.totalInputTokens += record.inputTokens\n stats.totalOutputTokens += record.outputTokens\n stats.totalCacheCreationTokens += record.cacheCreationTokens\n stats.totalCacheReadTokens += record.cacheReadTokens\n stats.grandTotalTokens += record.totalTokens\n stats.totalCostUSD += record.estimatedCostUSD\n stats.requestCount += 1\n\n if (!stats.firstRequestTime) {\n stats.firstRequestTime = record.timestamp\n }\n stats.lastRequestTime = record.timestamp\n\n // Update per-model breakdown\n const modelStats = stats.byModel.get(record.model)\n if (modelStats) {\n modelStats.inputTokens += record.inputTokens\n modelStats.outputTokens += record.outputTokens\n modelStats.totalTokens += record.totalTokens\n modelStats.estimatedCostUSD += record.estimatedCostUSD\n modelStats.requestCount += 1\n } else {\n stats.byModel.set(record.model, {\n model: record.model,\n inputTokens: record.inputTokens,\n outputTokens: record.outputTokens,\n totalTokens: record.totalTokens,\n estimatedCostUSD: record.estimatedCostUSD,\n requestCount: 1,\n })\n }\n }\n\n private cloneStats(stats: AggregatedTokenStats): AggregatedTokenStats {\n return {\n ...stats,\n byModel: new Map(stats.byModel),\n }\n }\n\n private emitEvent(event: TokenStatsEvent): void {\n this.emit('stats_update', event)\n }\n\n /**\n * Reset all stats (for testing only)\n */\n resetForTests(): void {\n if (process.env.NODE_ENV !== 'test') {\n throw new Error('resetForTests can only be called in tests')\n }\n this.reset()\n }\n\n /**\n * Reset all statistics\n *\n * Called by costTracker.resetStateForTests() for backward compatibility.\n */\n reset(): void {\n this.globalStats = this.createEmptyStats()\n this.agentStats.clear()\n this.requestRecords.clear()\n }\n}\n\n// Export singleton instance\nexport const tokenStatsManager = TokenStatsManagerImpl.getInstance()\n\n// ===== Convenience Functions =====\n\n/**\n * Record token usage from an API response\n *\n * This is the main function to call from claude.ts after each API response.\n * Also updates the persistent stats manager for cross-session tracking.\n */\nexport function recordTokenUsage(\n usage: RawTokenUsage,\n costUSD: number,\n model: string,\n context?: TokenTrackingContext,\n): void {\n tokenStatsManager.recordUsage(usage, costUSD, model, context)\n\n // Also record to persistent stats manager (fire-and-forget)\n try {\n const { recordMessage } = require('@utils/stats')\n recordMessage(model, usage.inputTokens, usage.outputTokens, costUSD)\n } catch {\n // Stats manager not available, ignore\n }\n}\n\n/**\n * Get global token statistics\n */\nexport function getGlobalTokenStats(): AggregatedTokenStats {\n return tokenStatsManager.getGlobalStats()\n}\n\n/**\n * Get token statistics for a specific agent\n */\nexport function getAgentTokenStats(\n agentId: string,\n): AggregatedTokenStats | null {\n return tokenStatsManager.getAgentStats(agentId)\n}\n\n/**\n * Estimate token count from text\n */\nexport function estimateTokenCount(text: string): number {\n return tokenStatsManager.estimateTokens(text)\n}\n"],
5
+ "mappings": "AAkCA,SAAS,oBAAoB;AAU7B,SAAS,iCAAiC;AAK1C,MAAM,8BAA8B,aAAa;AAAA,EAC/C,OAAe,WAAyC;AAAA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AQ;AAAA,EAER;AACF;AAKO,SAAS,sBAA4C;AAC1D,SAAO,kBAAkB,eAAe;AAC1C;AAKO,SAAS,mBACd,SAC6B;AAC7B,SAAO,kBAAkB,cAAc,OAAO;AAChD;AAKO,SAAS,mBAAmB,MAAsB;AACvD,SAAO,kBAAkB,eAAe,IAAI;AAC9C;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env -S node --no-warnings=ExperimentalWarning --enable-source-maps
2
+ import { EventEmitter } from "events";
3
+ import { fileURLToPath } from "node:url";
4
+ import { dirname, join } from "node:path";
5
+ import { existsSync } from "node:fs";
6
+ process.env.DEV = "false";
7
+ process.env["DEV"] = "false";
8
+ EventEmitter.defaultMaxListeners = 20;
9
+ try {
10
+ if (!process.env.YOGA_WASM_PATH) {
11
+ const __filename = fileURLToPath(import.meta.url);
12
+ const __dirname = dirname(__filename);
13
+ const candidates = [
14
+ join(__dirname, "./yoga.wasm"),
15
+ // dist/entrypoints/yoga.wasm
16
+ join(__dirname, "../yoga.wasm"),
17
+ // dist/yoga.wasm
18
+ join(__dirname, "../../yoga.wasm")
19
+ // project root (dev mode)
20
+ ];
21
+ for (const candidate of candidates) {
22
+ if (existsSync(candidate)) {
23
+ process.env.YOGA_WASM_PATH = candidate;
24
+ break;
25
+ }
26
+ }
27
+ }
28
+ } catch {
29
+ }
30
+ async function main() {
31
+ try {
32
+ await import("./cli.js");
33
+ } catch (error) {
34
+ const err = error;
35
+ const message = err.message || "";
36
+ if (message.includes("react-devtools-core")) {
37
+ console.error("\n\u274C Failed to start: react-devtools-core not found");
38
+ console.error(" This may be caused by DEV environment variable being set.");
39
+ console.error(" Try running: unset DEV && minto\n");
40
+ } else if (message.includes("yoga") || message.includes("YOGA")) {
41
+ console.error("\n\u274C Failed to start: yoga-layout initialization failed");
42
+ console.error(" The yoga.wasm file may be missing or corrupted.");
43
+ console.error(" Try reinstalling: npm install -g @within-7/minto\n");
44
+ } else {
45
+ console.error("\u274C Failed to start:", message || err);
46
+ if (err.stack) {
47
+ console.error(err.stack);
48
+ }
49
+ }
50
+ process.exit(1);
51
+ }
52
+ }
53
+ main();
54
+ //# sourceMappingURL=bootstrap.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/entrypoints/bootstrap.ts"],
4
+ "sourcesContent": ["#!/usr/bin/env -S node --no-warnings=ExperimentalWarning --enable-source-maps\n\n/**\n * Bootstrap entry point for Minto CLI\n *\n * CRITICAL: This file MUST remain minimal with NO static imports of application code.\n *\n * This bootstrap exists because ESM static imports execute BEFORE the importing\n * module's code. We need certain initializations to happen BEFORE any application\n * modules are loaded:\n *\n * 1. DEV='false' - Ink checks process.env['DEV'] at module load time and tries to\n * import 'react-devtools-core' if DEV='true'. This package isn't bundled.\n *\n * 2. EventEmitter.defaultMaxListeners - Must be set before any modules create\n * EventEmitters to prevent \"MaxListenersExceededWarning\" during startup.\n *\n * 3. YOGA_WASM_PATH - Must be set before Ink initializes yoga-layout for proper\n * terminal layout rendering.\n *\n * Solution: Use dynamic import() to load cli.tsx AFTER all initializations.\n * Dynamic import() is evaluated at runtime, not at module load time.\n *\n * DO NOT add any static imports here except for Node.js built-ins that don't\n * chain to application code (directly or transitively).\n */\n\nimport { EventEmitter } from 'events'\nimport { fileURLToPath } from 'node:url'\nimport { dirname, join } from 'node:path'\nimport { existsSync } from 'node:fs'\n\n// ============================================================================\n// 1. Disable Ink's development mode\n// ============================================================================\n// Prevents Ink from trying to load react-devtools-core which isn't bundled.\n// Must use both syntaxes because Bun's --define only replaces dot syntax.\nprocess.env.DEV = 'false'\nprocess.env['DEV'] = 'false'\n\n// ============================================================================\n// 2. Increase EventEmitter max listeners\n// ============================================================================\n// Components like ModelConfig, ModelSelector use multiple useInput hooks which\n// add listeners. Default is 10, we increase to 20 to accommodate deep hierarchies.\n// Must be set before any modules create EventEmitters.\nEventEmitter.defaultMaxListeners = 20\n\n// ============================================================================\n// 3. Set YOGA_WASM_PATH for Ink layout engine\n// ============================================================================\n// Ink uses yoga-layout for terminal UI layout. The WASM file path must be set\n// before Ink initializes. Resolve relative to this file for both dev and dist.\ntry {\n if (!process.env.YOGA_WASM_PATH) {\n const __filename = fileURLToPath(import.meta.url)\n const __dirname = dirname(__filename)\n // Check multiple possible locations\n const candidates = [\n join(__dirname, './yoga.wasm'), // dist/entrypoints/yoga.wasm\n join(__dirname, '../yoga.wasm'), // dist/yoga.wasm\n join(__dirname, '../../yoga.wasm'), // project root (dev mode)\n ]\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n process.env.YOGA_WASM_PATH = candidate\n break\n }\n }\n }\n} catch {\n // Ignore errors - yoga will use fallback or error at runtime\n}\n\n// ============================================================================\n// Main: Dynamically import the CLI\n// ============================================================================\n// This ensures all static imports in cli.tsx see the initialized environment.\nasync function main(): Promise<void> {\n try {\n await import('./cli.js')\n } catch (error) {\n // Provide helpful error messages for common failures\n const err = error as Error\n const message = err.message || ''\n\n if (message.includes('react-devtools-core')) {\n console.error('\\n\u274C Failed to start: react-devtools-core not found')\n console.error(' This may be caused by DEV environment variable being set.')\n console.error(' Try running: unset DEV && minto\\n')\n } else if (message.includes('yoga') || message.includes('YOGA')) {\n console.error('\\n\u274C Failed to start: yoga-layout initialization failed')\n console.error(' The yoga.wasm file may be missing or corrupted.')\n console.error(' Try reinstalling: npm install -g @within-7/minto\\n')\n } else {\n console.error('\u274C Failed to start:', message || err)\n if (err.stack) {\n console.error(err.stack)\n }\n }\n process.exit(1)\n }\n}\n\nmain()\n"],
5
+ "mappings": ";AA2BA,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,YAAY;AAC9B,SAAS,kBAAkB;AAO3B,QAAQ,IAAI,MAAM;AAClB,QAAQ,IAAI,KAAK,IAAI;AAQrB,aAAa,sBAAsB;AAOnC,IAAI;AACF,MAAI,CAAC,QAAQ,IAAI,gBAAgB;AAC/B,UAAM,aAAa,cAAc,YAAY,GAAG;AAChD,UAAM,YAAY,QAAQ,UAAU;AAEpC,UAAM,aAAa;AAAA,MACjB,KAAK,WAAW,aAAa;AAAA;AAAA,MAC7B,KAAK,WAAW,cAAc;AAAA;AAAA,MAC9B,KAAK,WAAW,iBAAiB;AAAA;AAAA,IACnC;AACA,eAAW,aAAa,YAAY;AAClC,UAAI,WAAW,SAAS,GAAG;AACzB,gBAAQ,IAAI,iBAAiB;AAC7B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF,QAAQ;AAER;AAMA,eAAe,OAAsB;AACnC,MAAI;AACF,UAAM,OAAO,UAAU;AAAA,EACzB,SAAS,OAAO;AAEd,UAAM,MAAM;AACZ,UAAM,UAAU,IAAI,WAAW;AAE/B,QAAI,QAAQ,SAAS,qBAAqB,GAAG;AAC3C,cAAQ,MAAM,yDAAoD;AAClE,cAAQ,MAAM,8DAA8D;AAC5E,cAAQ,MAAM,sCAAsC;AAAA,IACtD,WAAW,QAAQ,SAAS,MAAM,KAAK,QAAQ,SAAS,MAAM,GAAG;AAC/D,cAAQ,MAAM,6DAAwD;AACtE,cAAQ,MAAM,oDAAoD;AAClE,cAAQ,MAAM,uDAAuD;AAAA,IACvE,OAAO;AACL,cAAQ,MAAM,2BAAsB,WAAW,GAAG;AAClD,UAAI,IAAI,OAAO;AACb,gBAAQ,MAAM,IAAI,KAAK;AAAA,MACzB;AAAA,IACF;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;AAEA,KAAK;",
6
+ "names": []
7
+ }
@@ -1,33 +1,14 @@
1
1
  #!/usr/bin/env -S node --no-warnings=ExperimentalWarning --enable-source-maps
2
- process.env.DEV = "false";
3
- import { EventEmitter } from "events";
4
- EventEmitter.defaultMaxListeners = 20;
5
- import { fileURLToPath } from "node:url";
6
- import { dirname, join } from "node:path";
7
- import { existsSync } from "node:fs";
8
2
  import { initSentry } from "../services/sentry.js";
9
3
  import { PRODUCT_COMMAND, PRODUCT_NAME } from "../constants/product.js";
10
4
  import { initGlobalErrorHandlers } from "../utils/globalErrorHandler.js";
11
5
  initSentry();
12
6
  initGlobalErrorHandlers();
13
- try {
14
- if (!process.env.YOGA_WASM_PATH) {
15
- const __filename = fileURLToPath(import.meta.url);
16
- const __dirname = dirname(__filename);
17
- const devCandidate = join(__dirname, "../../yoga.wasm");
18
- const distCandidate = join(__dirname, "./yoga.wasm");
19
- const resolved = existsSync(distCandidate) ? distCandidate : existsSync(devCandidate) ? devCandidate : void 0;
20
- if (resolved) {
21
- process.env.YOGA_WASM_PATH = resolved;
22
- }
23
- }
24
- } catch {
25
- }
26
7
  import * as dontcare from "@anthropic-ai/sdk/shims/node";
27
8
  Object.keys(dontcare);
28
9
  import React from "react";
29
10
  import { ReadStream } from "tty";
30
- import { openSync } from "fs";
11
+ import { existsSync, openSync } from "fs";
31
12
  import { validateRawModeSupport, requireRawModeOrExit } from "../utils/ptyCompat.js";
32
13
  import { addToHistory } from "../history.js";
33
14
  import { getContext, setContext, removeContext } from "../context.js";
@@ -80,12 +61,24 @@ import {
80
61
  ensureConfigScope
81
62
  } from "../services/mcpClient.js";
82
63
  import { handleMcprcServerApprovals } from "../services/mcpServerApproval.js";
64
+ import {
65
+ fetchTeamConfig,
66
+ loadTeamConfigFromFile,
67
+ applyTeamConfig,
68
+ addMarketplaces,
69
+ installPlugins,
70
+ installRemoteAgents,
71
+ installInlineAgents,
72
+ installTeamHooks
73
+ } from "../utils/teamConfig.js";
83
74
  import { cursorShow } from "ansi-escapes";
84
75
  import {
85
76
  getLatestVersion,
86
77
  assertMinVersion,
87
78
  getUpdateCommandSuggestions
88
79
  } from "../utils/autoUpdater.js";
80
+ import { ensureConfigDirs } from "../utils/configPaths.js";
81
+ import { runStartupMigration } from "../utils/migration/index.js";
89
82
  import {
90
83
  initI18n,
91
84
  setLanguage,
@@ -270,6 +263,14 @@ if (process.env.NODE_ENV !== "test") {
270
263
  });
271
264
  }
272
265
  async function main() {
266
+ const configDirsResult = ensureConfigDirs();
267
+ if (configDirsResult.errors.length > 0) {
268
+ for (const err of configDirsResult.errors) {
269
+ console.warn(`\u26A0\uFE0F Config directory warning: ${err.path} - ${err.error}`);
270
+ }
271
+ }
272
+ runStartupMigration().catch(() => {
273
+ });
273
274
  const globalConfig = getGlobalConfig();
274
275
  const configLang = globalConfig.language;
275
276
  if (configLang && isLanguageSupported(configLang)) {
@@ -573,6 +574,114 @@ ${commandList}`
573
574
  );
574
575
  process.exit(0);
575
576
  });
577
+ program.command("setup").description("Initialize Minto with team configuration from a URL or file").requiredOption(
578
+ "--from <source>",
579
+ "URL or file path to the team configuration JSON"
580
+ ).option(
581
+ "--strategy <strategy>",
582
+ "Merge strategy: merge, replace, or skip-existing",
583
+ "merge"
584
+ ).option("--no-plugins", "Skip installing plugins, agents, and hooks").action(
585
+ async (options) => {
586
+ const {
587
+ from: source,
588
+ strategy,
589
+ plugins: shouldInstallPlugins
590
+ } = options;
591
+ try {
592
+ console.log(`Loading configuration from ${source}...`);
593
+ const teamConfig = source.startsWith("http://") || source.startsWith("https://") ? await fetchTeamConfig(source) : loadTeamConfigFromFile(source);
594
+ console.log("Applying configuration...");
595
+ const result = applyTeamConfig(teamConfig, strategy);
596
+ let marketplacesAdded = 0;
597
+ if (shouldInstallPlugins && teamConfig.plugins?.marketplaces) {
598
+ console.log(
599
+ `Adding ${teamConfig.plugins.marketplaces.length} marketplace(s)...`
600
+ );
601
+ const marketplaceResult = await addMarketplaces(
602
+ teamConfig.plugins.marketplaces
603
+ );
604
+ marketplacesAdded = marketplaceResult.added;
605
+ }
606
+ let pluginsInstalled = 0;
607
+ if (shouldInstallPlugins && teamConfig.plugins?.install) {
608
+ console.log(
609
+ `Installing ${teamConfig.plugins.install.length} plugin(s)...`
610
+ );
611
+ const pluginResult = await installPlugins(
612
+ teamConfig.plugins.install
613
+ );
614
+ pluginsInstalled = pluginResult.installed;
615
+ }
616
+ let agentsInstalled = 0;
617
+ if (shouldInstallPlugins && teamConfig.agents) {
618
+ const remoteCount = teamConfig.agents.remoteAgents?.length || 0;
619
+ const inlineCount = teamConfig.agents.inlineAgents?.length || 0;
620
+ const totalAgents = remoteCount + inlineCount;
621
+ if (totalAgents > 0) {
622
+ console.log(`Installing ${totalAgents} agent(s)...`);
623
+ if (teamConfig.agents.remoteAgents) {
624
+ const remoteResult = await installRemoteAgents(
625
+ teamConfig.agents.remoteAgents
626
+ );
627
+ agentsInstalled += remoteResult.installed;
628
+ }
629
+ if (teamConfig.agents.inlineAgents) {
630
+ const inlineResult = await installInlineAgents(
631
+ teamConfig.agents.inlineAgents
632
+ );
633
+ agentsInstalled += inlineResult.installed;
634
+ }
635
+ }
636
+ }
637
+ let hooksInstalled = false;
638
+ if (shouldInstallPlugins && teamConfig.hooks) {
639
+ console.log("Installing hooks...");
640
+ const hookResult = await installTeamHooks(teamConfig.hooks);
641
+ hooksInstalled = hookResult.installed;
642
+ }
643
+ console.log("\n\u2713 Configuration applied successfully!\n");
644
+ if (result.modelsAdded > 0) {
645
+ console.log(` \u2022 Added ${result.modelsAdded} model profile(s)`);
646
+ }
647
+ if (result.mcpServersAdded > 0) {
648
+ console.log(` \u2022 Added ${result.mcpServersAdded} MCP server(s)`);
649
+ }
650
+ if (result.settingsUpdated.length > 0) {
651
+ console.log(
652
+ ` \u2022 Updated ${result.settingsUpdated.length} setting(s): ${result.settingsUpdated.join(", ")}`
653
+ );
654
+ }
655
+ if (marketplacesAdded > 0) {
656
+ console.log(` \u2022 Added ${marketplacesAdded} marketplace(s)`);
657
+ }
658
+ if (pluginsInstalled > 0) {
659
+ console.log(` \u2022 Installed ${pluginsInstalled} plugin(s)`);
660
+ }
661
+ if (agentsInstalled > 0) {
662
+ console.log(` \u2022 Installed ${agentsInstalled} agent(s)`);
663
+ }
664
+ if (hooksInstalled) {
665
+ console.log(" \u2022 Installed hooks configuration");
666
+ }
667
+ if (teamConfig.postInstallInstructions) {
668
+ console.log("\n\u{1F4CB} Next Steps:");
669
+ console.log(teamConfig.postInstallInstructions);
670
+ }
671
+ console.log(
672
+ `
673
+ Run "${PRODUCT_COMMAND}" to start using your configured setup.`
674
+ );
675
+ process.exit(0);
676
+ } catch (error) {
677
+ console.error(
678
+ "\u2717 Setup failed:",
679
+ error instanceof Error ? error.message : String(error)
680
+ );
681
+ process.exit(1);
682
+ }
683
+ }
684
+ );
576
685
  const allowedTools = program.command("approved-tools").description("Manage approved tools");
577
686
  allowedTools.command("list").description("List all approved tools").action(async () => {
578
687
  const result = handleListApprovedTools(getCwd());
@@ -835,7 +944,7 @@ ${commandList}`
835
944
  const scope = ensureConfigScope(options.scope);
836
945
  const platform = process.platform;
837
946
  const { existsSync: existsSync2, readFileSync } = await import("fs");
838
- const { join: join2 } = await import("path");
947
+ const { join } = await import("path");
839
948
  const { exec } = await import("child_process");
840
949
  const isWSL = platform === "linux" && existsSync2("/proc/version") && readFileSync("/proc/version", "utf-8").toLowerCase().includes("microsoft");
841
950
  if (platform !== "darwin" && platform !== "win32" && !isWSL) {
@@ -846,12 +955,12 @@ ${commandList}`
846
955
  }
847
956
  let configPath;
848
957
  if (platform === "darwin") {
849
- configPath = join2(
958
+ configPath = join(
850
959
  process.env.HOME || "~",
851
960
  "Library/Application Support/Claude/claude_desktop_config.json"
852
961
  );
853
962
  } else if (platform === "win32") {
854
- configPath = join2(
963
+ configPath = join(
855
964
  process.env.APPDATA || "",
856
965
  "Claude/claude_desktop_config.json"
857
966
  );