@shareai-lab/kode 1.1.16 → 1.1.19-dev.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/Logo.js +6 -1
- package/dist/components/Logo.js.map +2 -2
- package/dist/components/messages/AssistantToolUseMessage.js.map +2 -2
- package/dist/entrypoints/cli.js +57 -37
- package/dist/entrypoints/cli.js.map +3 -3
- package/dist/screens/REPL.js +5 -5
- package/dist/screens/REPL.js.map +2 -2
- package/dist/services/openai.js +10 -6
- package/dist/services/openai.js.map +2 -2
- package/dist/tools/TaskTool/TaskTool.js +44 -1
- package/dist/tools/TaskTool/TaskTool.js.map +2 -2
- package/dist/utils/autoUpdater.js +5 -7
- package/dist/utils/autoUpdater.js.map +2 -2
- package/dist/utils/generators.js.map +1 -1
- package/package.json +61 -2
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
overwriteLog
|
|
15
15
|
} from "../../utils/log.js";
|
|
16
16
|
import {
|
|
17
|
+
createAssistantMessage,
|
|
17
18
|
createUserMessage,
|
|
18
19
|
getLastAssistantMessageId,
|
|
19
20
|
INTERRUPT_MESSAGE,
|
|
@@ -94,12 +95,36 @@ ${prompt}`;
|
|
|
94
95
|
tools = tools.filter((tool) => toolFilter.includes(tool.name));
|
|
95
96
|
}
|
|
96
97
|
}
|
|
98
|
+
const modelToUse = effectiveModel;
|
|
99
|
+
yield {
|
|
100
|
+
type: "progress",
|
|
101
|
+
content: createAssistantMessage(`Starting agent: ${agentType}`),
|
|
102
|
+
normalizedMessages: normalizeMessages(messages),
|
|
103
|
+
tools
|
|
104
|
+
};
|
|
105
|
+
yield {
|
|
106
|
+
type: "progress",
|
|
107
|
+
content: createAssistantMessage(`Using model: ${modelToUse}`),
|
|
108
|
+
normalizedMessages: normalizeMessages(messages),
|
|
109
|
+
tools
|
|
110
|
+
};
|
|
111
|
+
yield {
|
|
112
|
+
type: "progress",
|
|
113
|
+
content: createAssistantMessage(`Task: ${description}`),
|
|
114
|
+
normalizedMessages: normalizeMessages(messages),
|
|
115
|
+
tools
|
|
116
|
+
};
|
|
117
|
+
yield {
|
|
118
|
+
type: "progress",
|
|
119
|
+
content: createAssistantMessage(`Prompt: ${prompt.length > 150 ? prompt.substring(0, 150) + "..." : prompt}`),
|
|
120
|
+
normalizedMessages: normalizeMessages(messages),
|
|
121
|
+
tools
|
|
122
|
+
};
|
|
97
123
|
const [taskPrompt, context, maxThinkingTokens] = await Promise.all([
|
|
98
124
|
getAgentPrompt(),
|
|
99
125
|
getContext(),
|
|
100
126
|
getMaxThinkingTokens(messages)
|
|
101
127
|
]);
|
|
102
|
-
const modelToUse = effectiveModel;
|
|
103
128
|
taskPrompt.push(`
|
|
104
129
|
IMPORTANT: You are currently running as ${modelToUse}. You do not need to consult ${modelToUse} via AskExpertModel since you ARE ${modelToUse}. Complete tasks directly using your capabilities.`);
|
|
105
130
|
let toolUseCount = 0;
|
|
@@ -148,6 +173,12 @@ IMPORTANT: You are currently running as ${modelToUse}. You do not need to consul
|
|
|
148
173
|
for (const content of message.message.content) {
|
|
149
174
|
if (content.type === "text" && content.text && content.text !== INTERRUPT_MESSAGE) {
|
|
150
175
|
const preview = content.text.length > 200 ? content.text.substring(0, 200) + "..." : content.text;
|
|
176
|
+
yield {
|
|
177
|
+
type: "progress",
|
|
178
|
+
content: createAssistantMessage(`${preview}`),
|
|
179
|
+
normalizedMessages: normalizedMessages2,
|
|
180
|
+
tools
|
|
181
|
+
};
|
|
151
182
|
} else if (content.type === "tool_use") {
|
|
152
183
|
toolUseCount++;
|
|
153
184
|
const toolMessage = normalizedMessages2.find(
|
|
@@ -170,6 +201,12 @@ IMPORTANT: You are currently running as ${modelToUse}. You do not need to consul
|
|
|
170
201
|
})
|
|
171
202
|
}
|
|
172
203
|
};
|
|
204
|
+
yield {
|
|
205
|
+
type: "progress",
|
|
206
|
+
content: modifiedMessage,
|
|
207
|
+
normalizedMessages: normalizedMessages2,
|
|
208
|
+
tools
|
|
209
|
+
};
|
|
173
210
|
}
|
|
174
211
|
}
|
|
175
212
|
}
|
|
@@ -190,6 +227,12 @@ IMPORTANT: You are currently running as ${modelToUse}. You do not need to consul
|
|
|
190
227
|
) + " tokens",
|
|
191
228
|
formatDuration(Date.now() - startTime)
|
|
192
229
|
];
|
|
230
|
+
yield {
|
|
231
|
+
type: "progress",
|
|
232
|
+
content: createAssistantMessage(`Task completed (${result.join(" \xB7 ")})`),
|
|
233
|
+
normalizedMessages,
|
|
234
|
+
tools
|
|
235
|
+
};
|
|
193
236
|
}
|
|
194
237
|
const data = lastMessage.message.content.filter((_) => _.type === "text");
|
|
195
238
|
yield {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/tools/TaskTool/TaskTool.tsx"],
|
|
4
|
-
"sourcesContent": ["import { TextBlock } from '@anthropic-ai/sdk/resources/index.mjs'\nimport chalk from 'chalk'\nimport { last, memoize } from 'lodash-es'\nimport { EOL } from 'os'\nimport React, { useState, useEffect } from 'react'\nimport { Box, Text } from 'ink'\nimport { z } from 'zod'\nimport { Tool, ValidationResult } from '../../Tool'\nimport { FallbackToolUseRejectedMessage } from '../../components/FallbackToolUseRejectedMessage'\nimport { getAgentPrompt } from '../../constants/prompts'\nimport { getContext } from '../../context'\nimport { hasPermissionsToUseTool } from '../../permissions'\nimport { AssistantMessage, Message as MessageType, query } from '../../query'\nimport { formatDuration, formatNumber } from '../../utils/format'\nimport {\n getMessagesPath,\n getNextAvailableLogSidechainNumber,\n overwriteLog,\n} from '../../utils/log.js'\nimport { applyMarkdown } from '../../utils/markdown'\nimport {\n createAssistantMessage,\n createUserMessage,\n getLastAssistantMessageId,\n INTERRUPT_MESSAGE,\n normalizeMessages,\n} from '../../utils/messages.js'\nimport { getModelManager } from '../../utils/model'\nimport { getMaxThinkingTokens } from '../../utils/thinking'\nimport { getTheme } from '../../utils/theme'\nimport { generateAgentId } from '../../utils/agentStorage'\nimport { debug as debugLogger } from '../../utils/debugLogger'\nimport { getTaskTools, getPrompt } from './prompt'\nimport { TOOL_NAME } from './constants'\nimport { getActiveAgents, getAgentByType, getAvailableAgentTypes } from '../../utils/agentLoader'\n\nconst inputSchema = z.object({\n description: z\n .string()\n .describe('A short (3-5 word) description of the task'),\n prompt: z.string().describe('The task for the agent to perform'),\n model_name: z\n .string()\n .optional()\n .describe(\n 'Optional: Specific model name to use for this task. If not provided, uses the default task model pointer.',\n ),\n subagent_type: z\n .string()\n .optional()\n .describe(\n 'The type of specialized agent to use for this task',\n ),\n})\n\nexport const TaskTool = {\n async prompt({ safeMode }) {\n // Match original Claude Code - prompt returns full agent descriptions\n return await getPrompt(safeMode)\n },\n name: TOOL_NAME,\n async description() {\n // Match original Claude Code exactly - simple description\n return \"Launch a new task\"\n },\n inputSchema,\n \n async *call(\n { description, prompt, model_name, subagent_type },\n {\n abortController,\n options: { safeMode = false, forkNumber, messageLogName, verbose },\n readFileTimestamps,\n },\n ): AsyncGenerator<{ type: 'result'; data: TextBlock[]; resultForAssistant?: string }, void, unknown> {\n const startTime = Date.now()\n \n // Default to general-purpose if no subagent_type specified\n const agentType = subagent_type || 'general-purpose'\n \n // Apply subagent configuration\n let effectivePrompt = prompt\n let effectiveModel = model_name || 'task'\n let toolFilter = null\n let temperature = undefined\n \n // Load agent configuration dynamically\n if (agentType) {\n const agentConfig = await getAgentByType(agentType)\n \n if (!agentConfig) {\n // If agent type not found, return helpful message instead of throwing\n const availableTypes = await getAvailableAgentTypes()\n const helpMessage = `Agent type '${agentType}' not found.\\n\\nAvailable agents:\\n${availableTypes.map(t => ` \u2022 ${t}`).join('\\n')}\\n\\nUse /agents command to manage agent configurations.`\n \n yield {\n type: 'result',\n data: [{ type: 'text', text: helpMessage }] as TextBlock[],\n resultForAssistant: helpMessage,\n }\n return\n }\n \n // Apply system prompt if configured\n if (agentConfig.systemPrompt) {\n effectivePrompt = `${agentConfig.systemPrompt}\\n\\n${prompt}`\n }\n \n // Apply model if not overridden by model_name parameter\n if (!model_name && agentConfig.model_name) {\n // Support inherit: keep pointer-based default\n if (agentConfig.model_name !== 'inherit') {\n effectiveModel = agentConfig.model_name as string\n }\n }\n \n // Store tool filter for later application\n toolFilter = agentConfig.tools\n \n // Note: temperature is not currently in our agent configs\n // but could be added in the future\n }\n \n const messages: MessageType[] = [createUserMessage(effectivePrompt)]\n let tools = await getTaskTools(safeMode)\n \n // Apply tool filtering if specified by subagent config\n if (toolFilter) {\n // Back-compat: ['*'] means all tools\n const isAllArray = Array.isArray(toolFilter) && toolFilter.length === 1 && toolFilter[0] === '*'\n if (toolFilter === '*' || isAllArray) {\n // no-op, keep all tools\n } else if (Array.isArray(toolFilter)) {\n tools = tools.filter(tool => toolFilter.includes(tool.name))\n }\n }\n\n // Skip initial progress yield - only yield results for Tool interface\n\n const [taskPrompt, context, maxThinkingTokens] = await Promise.all([\n getAgentPrompt(),\n getContext(),\n getMaxThinkingTokens(messages),\n ])\n\n // Model already resolved in effectiveModel variable above\n const modelToUse = effectiveModel\n \n // Inject model context to prevent self-referential expert consultations\n taskPrompt.push(`\\nIMPORTANT: You are currently running as ${modelToUse}. You do not need to consult ${modelToUse} via AskExpertModel since you ARE ${modelToUse}. Complete tasks directly using your capabilities.`)\n\n let toolUseCount = 0\n\n const getSidechainNumber = memoize(() =>\n getNextAvailableLogSidechainNumber(messageLogName, forkNumber),\n )\n\n // Generate unique Task ID for this task execution\n const taskId = generateAgentId()\n\n // \uD83D\uDD27 ULTRA SIMPLIFIED: Exact original AgentTool pattern\n // Build query options, adding temperature if specified\n const queryOptions = {\n safeMode,\n forkNumber,\n messageLogName,\n tools,\n commands: [],\n verbose,\n maxThinkingTokens,\n model: modelToUse,\n }\n \n // Add temperature if specified by subagent config\n if (temperature !== undefined) {\n queryOptions['temperature'] = temperature\n }\n \n for await (const message of query(\n messages,\n taskPrompt,\n context,\n hasPermissionsToUseTool,\n {\n abortController,\n options: queryOptions,\n messageId: getLastAssistantMessageId(messages),\n agentId: taskId,\n readFileTimestamps,\n setToolJSX: () => {}, // No-op implementation for TaskTool\n },\n )) {\n messages.push(message)\n\n overwriteLog(\n getMessagesPath(messageLogName, forkNumber, getSidechainNumber()),\n messages.filter(_ => _.type !== 'progress'),\n )\n\n if (message.type !== 'assistant') {\n continue\n }\n\n const normalizedMessages = normalizeMessages(messages)\n \n // Process tool uses and text content for better visibility\n for (const content of message.message.content) {\n if (content.type === 'text' && content.text && content.text !== INTERRUPT_MESSAGE) {\n // Show agent's reasoning/responses\n const preview = content.text.length > 200 ? content.text.substring(0, 200) + '...' : content.text\n // Skip progress yield - only yield results for Tool interface\n } else if (content.type === 'tool_use') {\n toolUseCount++\n \n // Show which tool is being used with agent context\n const toolMessage = normalizedMessages.find(\n _ =>\n _.type === 'assistant' &&\n _.message.content[0]?.type === 'tool_use' &&\n _.message.content[0].id === content.id,\n ) as AssistantMessage\n \n if (toolMessage) {\n // Clone and modify the message to show agent context\n const modifiedMessage = {\n ...toolMessage,\n message: {\n ...toolMessage.message,\n content: toolMessage.message.content.map(c => {\n if (c.type === 'tool_use' && c.id === content.id) {\n // Add agent context to tool name display\n return {\n ...c,\n name: c.name // Keep original name, UI will handle display\n }\n }\n return c\n })\n }\n }\n \n // Skip progress yield - only yield results for Tool interface\n }\n }\n }\n }\n\n const normalizedMessages = normalizeMessages(messages)\n const lastMessage = last(messages)\n if (lastMessage?.type !== 'assistant') {\n throw new Error('Last message was not an assistant message')\n }\n\n // \uD83D\uDD27 CRITICAL FIX: Match original AgentTool interrupt handling pattern exactly\n if (\n lastMessage.message.content.some(\n _ => _.type === 'text' && _.text === INTERRUPT_MESSAGE,\n )\n ) {\n // Skip progress yield - only yield final result\n } else {\n const result = [\n toolUseCount === 1 ? '1 tool use' : `${toolUseCount} tool uses`,\n formatNumber(\n (lastMessage.message.usage.cache_creation_input_tokens ?? 0) +\n (lastMessage.message.usage.cache_read_input_tokens ?? 0) +\n lastMessage.message.usage.input_tokens +\n lastMessage.message.usage.output_tokens,\n ) + ' tokens',\n formatDuration(Date.now() - startTime),\n ]\n // Skip progress yield - only yield final result\n }\n\n // Output is an AssistantMessage, but since TaskTool is a tool, it needs\n // to serialize its response to UserMessage-compatible content.\n const data = lastMessage.message.content.filter(_ => _.type === 'text')\n yield {\n type: 'result',\n data,\n resultForAssistant: this.renderResultForAssistant(data),\n }\n },\n\n isReadOnly() {\n return true // for now...\n },\n isConcurrencySafe() {\n return true // Task tool supports concurrent execution in official implementation\n },\n async validateInput(input, context) {\n if (!input.description || typeof input.description !== 'string') {\n return {\n result: false,\n message: 'Description is required and must be a string',\n }\n }\n if (!input.prompt || typeof input.prompt !== 'string') {\n return {\n result: false,\n message: 'Prompt is required and must be a string',\n }\n }\n\n // Model validation - similar to Edit tool error handling\n if (input.model_name) {\n const modelManager = getModelManager()\n const availableModels = modelManager.getAllAvailableModelNames()\n\n if (!availableModels.includes(input.model_name)) {\n return {\n result: false,\n message: `Model '${input.model_name}' does not exist. Available models: ${availableModels.join(', ')}`,\n meta: {\n model_name: input.model_name,\n availableModels,\n },\n }\n }\n }\n\n // Validate subagent_type if provided\n if (input.subagent_type) {\n const availableTypes = await getAvailableAgentTypes()\n if (!availableTypes.includes(input.subagent_type)) {\n return {\n result: false,\n message: `Agent type '${input.subagent_type}' does not exist. Available types: ${availableTypes.join(', ')}`,\n meta: {\n subagent_type: input.subagent_type,\n availableTypes,\n },\n }\n }\n }\n\n return { result: true }\n },\n async isEnabled() {\n return true\n },\n userFacingName(input?: any) {\n // Return agent name with proper prefix\n const agentType = input?.subagent_type || 'general-purpose'\n return `agent-${agentType}`\n },\n needsPermissions() {\n return false\n },\n renderResultForAssistant(data: TextBlock[]) {\n return data.map(block => block.type === 'text' ? block.text : '').join('\\n')\n },\n renderToolUseMessage({ description, prompt, model_name, subagent_type }, { verbose }) {\n if (!description || !prompt) return null\n\n const modelManager = getModelManager()\n const defaultTaskModel = modelManager.getModelName('task')\n const actualModel = model_name || defaultTaskModel\n const agentType = subagent_type || 'general-purpose'\n const promptPreview =\n prompt.length > 80 ? prompt.substring(0, 80) + '...' : prompt\n\n const theme = getTheme()\n \n if (verbose) {\n return (\n <Box flexDirection=\"column\">\n <Text>\n [{agentType}] {actualModel}: {description}\n </Text>\n <Box\n paddingLeft={2}\n borderLeftStyle=\"single\"\n borderLeftColor={theme.secondaryBorder}\n >\n <Text color={theme.secondaryText}>{promptPreview}</Text>\n </Box>\n </Box>\n )\n }\n\n // Simple display: agent type, model and description\n return `[${agentType}] ${actualModel}: ${description}`\n },\n renderToolUseRejectedMessage() {\n return <FallbackToolUseRejectedMessage />\n },\n renderToolResultMessage(content) {\n const theme = getTheme()\n\n if (Array.isArray(content)) {\n const textBlocks = content.filter(block => block.type === 'text')\n const totalLength = textBlocks.reduce(\n (sum, block) => sum + block.text.length,\n 0,\n )\n // \uD83D\uDD27 CRITICAL FIX: Use exact match for interrupt detection, not .includes()\n const isInterrupted = content.some(\n block =>\n block.type === 'text' && block.text === INTERRUPT_MESSAGE,\n )\n\n if (isInterrupted) {\n // \uD83D\uDD27 CRITICAL FIX: Match original system interrupt rendering exactly\n return (\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Text color={theme.error}>Interrupted by user</Text>\n </Box>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n <Box justifyContent=\"space-between\" width=\"100%\">\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Text>Task completed</Text>\n {textBlocks.length > 0 && (\n <Text color={theme.secondaryText}>\n {' '}\n ({totalLength} characters)\n </Text>\n )}\n </Box>\n </Box>\n </Box>\n )\n }\n\n return (\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Text color={theme.secondaryText}>Task completed</Text>\n </Box>\n )\n },\n} satisfies Tool<typeof inputSchema, TextBlock[]>\n"],
|
|
5
|
-
"mappings": "AAEA,SAAS,MAAM,eAAe;AAE9B,OAAO,WAAoC;AAC3C,SAAS,KAAK,YAAY;AAC1B,SAAS,SAAS;AAElB,SAAS,sCAAsC;AAC/C,SAAS,sBAAsB;AAC/B,SAAS,kBAAkB;AAC3B,SAAS,+BAA+B;AACxC,SAAmD,aAAa;AAChE,SAAS,gBAAgB,oBAAoB;AAC7C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,
|
|
4
|
+
"sourcesContent": ["import { TextBlock } from '@anthropic-ai/sdk/resources/index.mjs'\nimport chalk from 'chalk'\nimport { last, memoize } from 'lodash-es'\nimport { EOL } from 'os'\nimport React, { useState, useEffect } from 'react'\nimport { Box, Text } from 'ink'\nimport { z } from 'zod'\nimport { Tool, ValidationResult } from '../../Tool'\nimport { FallbackToolUseRejectedMessage } from '../../components/FallbackToolUseRejectedMessage'\nimport { getAgentPrompt } from '../../constants/prompts'\nimport { getContext } from '../../context'\nimport { hasPermissionsToUseTool } from '../../permissions'\nimport { AssistantMessage, Message as MessageType, query } from '../../query'\nimport { formatDuration, formatNumber } from '../../utils/format'\nimport {\n getMessagesPath,\n getNextAvailableLogSidechainNumber,\n overwriteLog,\n} from '../../utils/log.js'\nimport { applyMarkdown } from '../../utils/markdown'\nimport {\n createAssistantMessage,\n createUserMessage,\n getLastAssistantMessageId,\n INTERRUPT_MESSAGE,\n normalizeMessages,\n} from '../../utils/messages.js'\nimport { getModelManager } from '../../utils/model'\nimport { getMaxThinkingTokens } from '../../utils/thinking'\nimport { getTheme } from '../../utils/theme'\nimport { generateAgentId } from '../../utils/agentStorage'\nimport { debug as debugLogger } from '../../utils/debugLogger'\nimport { getTaskTools, getPrompt } from './prompt'\nimport { TOOL_NAME } from './constants'\nimport { getActiveAgents, getAgentByType, getAvailableAgentTypes } from '../../utils/agentLoader'\n\nconst inputSchema = z.object({\n description: z\n .string()\n .describe('A short (3-5 word) description of the task'),\n prompt: z.string().describe('The task for the agent to perform'),\n model_name: z\n .string()\n .optional()\n .describe(\n 'Optional: Specific model name to use for this task. If not provided, uses the default task model pointer.',\n ),\n subagent_type: z\n .string()\n .optional()\n .describe(\n 'The type of specialized agent to use for this task',\n ),\n})\n\nexport const TaskTool = {\n async prompt({ safeMode }) {\n // Match original Claude Code - prompt returns full agent descriptions\n return await getPrompt(safeMode)\n },\n name: TOOL_NAME,\n async description() {\n // Match original Claude Code exactly - simple description\n return \"Launch a new task\"\n },\n inputSchema,\n \n async *call(\n { description, prompt, model_name, subagent_type },\n {\n abortController,\n options: { safeMode = false, forkNumber, messageLogName, verbose },\n readFileTimestamps,\n },\n ): AsyncGenerator<\n | { type: 'result'; data: TextBlock[]; resultForAssistant?: string }\n | { type: 'progress'; content: any; normalizedMessages?: any[]; tools?: any[] },\n void,\n unknown\n > {\n const startTime = Date.now()\n \n // Default to general-purpose if no subagent_type specified\n const agentType = subagent_type || 'general-purpose'\n \n // Apply subagent configuration\n let effectivePrompt = prompt\n let effectiveModel = model_name || 'task'\n let toolFilter = null\n let temperature = undefined\n \n // Load agent configuration dynamically\n if (agentType) {\n const agentConfig = await getAgentByType(agentType)\n \n if (!agentConfig) {\n // If agent type not found, return helpful message instead of throwing\n const availableTypes = await getAvailableAgentTypes()\n const helpMessage = `Agent type '${agentType}' not found.\\n\\nAvailable agents:\\n${availableTypes.map(t => ` \u2022 ${t}`).join('\\n')}\\n\\nUse /agents command to manage agent configurations.`\n \n yield {\n type: 'result',\n data: [{ type: 'text', text: helpMessage }] as TextBlock[],\n resultForAssistant: helpMessage,\n }\n return\n }\n \n // Apply system prompt if configured\n if (agentConfig.systemPrompt) {\n effectivePrompt = `${agentConfig.systemPrompt}\\n\\n${prompt}`\n }\n \n // Apply model if not overridden by model_name parameter\n if (!model_name && agentConfig.model_name) {\n // Support inherit: keep pointer-based default\n if (agentConfig.model_name !== 'inherit') {\n effectiveModel = agentConfig.model_name as string\n }\n }\n \n // Store tool filter for later application\n toolFilter = agentConfig.tools\n \n // Note: temperature is not currently in our agent configs\n // but could be added in the future\n }\n \n const messages: MessageType[] = [createUserMessage(effectivePrompt)]\n let tools = await getTaskTools(safeMode)\n \n // Apply tool filtering if specified by subagent config\n if (toolFilter) {\n // Back-compat: ['*'] means all tools\n const isAllArray = Array.isArray(toolFilter) && toolFilter.length === 1 && toolFilter[0] === '*'\n if (toolFilter === '*' || isAllArray) {\n // no-op, keep all tools\n } else if (Array.isArray(toolFilter)) {\n tools = tools.filter(tool => toolFilter.includes(tool.name))\n }\n }\n\n // Model already resolved in effectiveModel variable above\n const modelToUse = effectiveModel\n\n // Display initial task information with separate progress lines\n yield {\n type: 'progress',\n content: createAssistantMessage(`Starting agent: ${agentType}`),\n normalizedMessages: normalizeMessages(messages),\n tools,\n }\n \n yield {\n type: 'progress', \n content: createAssistantMessage(`Using model: ${modelToUse}`),\n normalizedMessages: normalizeMessages(messages),\n tools,\n }\n \n yield {\n type: 'progress',\n content: createAssistantMessage(`Task: ${description}`),\n normalizedMessages: normalizeMessages(messages),\n tools,\n }\n \n yield {\n type: 'progress',\n content: createAssistantMessage(`Prompt: ${prompt.length > 150 ? prompt.substring(0, 150) + '...' : prompt}`),\n normalizedMessages: normalizeMessages(messages),\n tools,\n }\n\n const [taskPrompt, context, maxThinkingTokens] = await Promise.all([\n getAgentPrompt(),\n getContext(),\n getMaxThinkingTokens(messages),\n ])\n \n // Inject model context to prevent self-referential expert consultations\n taskPrompt.push(`\\nIMPORTANT: You are currently running as ${modelToUse}. You do not need to consult ${modelToUse} via AskExpertModel since you ARE ${modelToUse}. Complete tasks directly using your capabilities.`)\n\n let toolUseCount = 0\n\n const getSidechainNumber = memoize(() =>\n getNextAvailableLogSidechainNumber(messageLogName, forkNumber),\n )\n\n // Generate unique Task ID for this task execution\n const taskId = generateAgentId()\n\n // \uD83D\uDD27 ULTRA SIMPLIFIED: Exact original AgentTool pattern\n // Build query options, adding temperature if specified\n const queryOptions = {\n safeMode,\n forkNumber,\n messageLogName,\n tools,\n commands: [],\n verbose,\n maxThinkingTokens,\n model: modelToUse,\n }\n \n // Add temperature if specified by subagent config\n if (temperature !== undefined) {\n queryOptions['temperature'] = temperature\n }\n \n for await (const message of query(\n messages,\n taskPrompt,\n context,\n hasPermissionsToUseTool,\n {\n abortController,\n options: queryOptions,\n messageId: getLastAssistantMessageId(messages),\n agentId: taskId,\n readFileTimestamps,\n setToolJSX: () => {}, // No-op implementation for TaskTool\n },\n )) {\n messages.push(message)\n\n overwriteLog(\n getMessagesPath(messageLogName, forkNumber, getSidechainNumber()),\n messages.filter(_ => _.type !== 'progress'),\n )\n\n if (message.type !== 'assistant') {\n continue\n }\n\n const normalizedMessages = normalizeMessages(messages)\n \n // Process tool uses and text content for better visibility\n for (const content of message.message.content) {\n if (content.type === 'text' && content.text && content.text !== INTERRUPT_MESSAGE) {\n // Show agent's reasoning/responses\n const preview = content.text.length > 200 ? content.text.substring(0, 200) + '...' : content.text\n yield {\n type: 'progress',\n content: createAssistantMessage(`${preview}`),\n normalizedMessages,\n tools,\n }\n } else if (content.type === 'tool_use') {\n toolUseCount++\n \n // Show which tool is being used with agent context\n const toolMessage = normalizedMessages.find(\n _ =>\n _.type === 'assistant' &&\n _.message.content[0]?.type === 'tool_use' &&\n _.message.content[0].id === content.id,\n ) as AssistantMessage\n \n if (toolMessage) {\n // Clone and modify the message to show agent context\n const modifiedMessage = {\n ...toolMessage,\n message: {\n ...toolMessage.message,\n content: toolMessage.message.content.map(c => {\n if (c.type === 'tool_use' && c.id === content.id) {\n // Add agent context to tool name display\n return {\n ...c,\n name: c.name // Keep original name, UI will handle display\n }\n }\n return c\n })\n }\n }\n \n yield {\n type: 'progress',\n content: modifiedMessage,\n normalizedMessages,\n tools,\n }\n }\n }\n }\n }\n\n const normalizedMessages = normalizeMessages(messages)\n const lastMessage = last(messages)\n if (lastMessage?.type !== 'assistant') {\n throw new Error('Last message was not an assistant message')\n }\n\n // \uD83D\uDD27 CRITICAL FIX: Match original AgentTool interrupt handling pattern exactly\n if (\n lastMessage.message.content.some(\n _ => _.type === 'text' && _.text === INTERRUPT_MESSAGE,\n )\n ) {\n // Skip progress yield - only yield final result\n } else {\n const result = [\n toolUseCount === 1 ? '1 tool use' : `${toolUseCount} tool uses`,\n formatNumber(\n (lastMessage.message.usage.cache_creation_input_tokens ?? 0) +\n (lastMessage.message.usage.cache_read_input_tokens ?? 0) +\n lastMessage.message.usage.input_tokens +\n lastMessage.message.usage.output_tokens,\n ) + ' tokens',\n formatDuration(Date.now() - startTime),\n ]\n yield {\n type: 'progress',\n content: createAssistantMessage(`Task completed (${result.join(' \u00B7 ')})`),\n normalizedMessages,\n tools,\n }\n }\n\n // Output is an AssistantMessage, but since TaskTool is a tool, it needs\n // to serialize its response to UserMessage-compatible content.\n const data = lastMessage.message.content.filter(_ => _.type === 'text')\n yield {\n type: 'result',\n data,\n resultForAssistant: this.renderResultForAssistant(data),\n }\n },\n\n isReadOnly() {\n return true // for now...\n },\n isConcurrencySafe() {\n return true // Task tool supports concurrent execution in official implementation\n },\n async validateInput(input, context) {\n if (!input.description || typeof input.description !== 'string') {\n return {\n result: false,\n message: 'Description is required and must be a string',\n }\n }\n if (!input.prompt || typeof input.prompt !== 'string') {\n return {\n result: false,\n message: 'Prompt is required and must be a string',\n }\n }\n\n // Model validation - similar to Edit tool error handling\n if (input.model_name) {\n const modelManager = getModelManager()\n const availableModels = modelManager.getAllAvailableModelNames()\n\n if (!availableModels.includes(input.model_name)) {\n return {\n result: false,\n message: `Model '${input.model_name}' does not exist. Available models: ${availableModels.join(', ')}`,\n meta: {\n model_name: input.model_name,\n availableModels,\n },\n }\n }\n }\n\n // Validate subagent_type if provided\n if (input.subagent_type) {\n const availableTypes = await getAvailableAgentTypes()\n if (!availableTypes.includes(input.subagent_type)) {\n return {\n result: false,\n message: `Agent type '${input.subagent_type}' does not exist. Available types: ${availableTypes.join(', ')}`,\n meta: {\n subagent_type: input.subagent_type,\n availableTypes,\n },\n }\n }\n }\n\n return { result: true }\n },\n async isEnabled() {\n return true\n },\n userFacingName(input?: any) {\n // Return agent name with proper prefix\n const agentType = input?.subagent_type || 'general-purpose'\n return `agent-${agentType}`\n },\n needsPermissions() {\n return false\n },\n renderResultForAssistant(data: TextBlock[]) {\n return data.map(block => block.type === 'text' ? block.text : '').join('\\n')\n },\n renderToolUseMessage({ description, prompt, model_name, subagent_type }, { verbose }) {\n if (!description || !prompt) return null\n\n const modelManager = getModelManager()\n const defaultTaskModel = modelManager.getModelName('task')\n const actualModel = model_name || defaultTaskModel\n const agentType = subagent_type || 'general-purpose'\n const promptPreview =\n prompt.length > 80 ? prompt.substring(0, 80) + '...' : prompt\n\n const theme = getTheme()\n \n if (verbose) {\n return (\n <Box flexDirection=\"column\">\n <Text>\n [{agentType}] {actualModel}: {description}\n </Text>\n <Box\n paddingLeft={2}\n borderLeftStyle=\"single\"\n borderLeftColor={theme.secondaryBorder}\n >\n <Text color={theme.secondaryText}>{promptPreview}</Text>\n </Box>\n </Box>\n )\n }\n\n // Simple display: agent type, model and description\n return `[${agentType}] ${actualModel}: ${description}`\n },\n renderToolUseRejectedMessage() {\n return <FallbackToolUseRejectedMessage />\n },\n renderToolResultMessage(content) {\n const theme = getTheme()\n\n if (Array.isArray(content)) {\n const textBlocks = content.filter(block => block.type === 'text')\n const totalLength = textBlocks.reduce(\n (sum, block) => sum + block.text.length,\n 0,\n )\n // \uD83D\uDD27 CRITICAL FIX: Use exact match for interrupt detection, not .includes()\n const isInterrupted = content.some(\n block =>\n block.type === 'text' && block.text === INTERRUPT_MESSAGE,\n )\n\n if (isInterrupted) {\n // \uD83D\uDD27 CRITICAL FIX: Match original system interrupt rendering exactly\n return (\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Text color={theme.error}>Interrupted by user</Text>\n </Box>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n <Box justifyContent=\"space-between\" width=\"100%\">\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Text>Task completed</Text>\n {textBlocks.length > 0 && (\n <Text color={theme.secondaryText}>\n {' '}\n ({totalLength} characters)\n </Text>\n )}\n </Box>\n </Box>\n </Box>\n )\n }\n\n return (\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Text color={theme.secondaryText}>Task completed</Text>\n </Box>\n )\n },\n} satisfies Tool<typeof inputSchema, TextBlock[]>\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,MAAM,eAAe;AAE9B,OAAO,WAAoC;AAC3C,SAAS,KAAK,YAAY;AAC1B,SAAS,SAAS;AAElB,SAAS,sCAAsC;AAC/C,SAAS,sBAAsB;AAC/B,SAAS,kBAAkB;AAC3B,SAAS,+BAA+B;AACxC,SAAmD,aAAa;AAChE,SAAS,gBAAgB,oBAAoB;AAC7C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,4BAA4B;AACrC,SAAS,gBAAgB;AACzB,SAAS,uBAAuB;AAEhC,SAAS,cAAc,iBAAiB;AACxC,SAAS,iBAAiB;AAC1B,SAA0B,gBAAgB,8BAA8B;AAExE,MAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,aAAa,EACV,OAAO,EACP,SAAS,4CAA4C;AAAA,EACxD,QAAQ,EAAE,OAAO,EAAE,SAAS,mCAAmC;AAAA,EAC/D,YAAY,EACT,OAAO,EACP,SAAS,EACT;AAAA,IACC;AAAA,EACF;AAAA,EACF,eAAe,EACZ,OAAO,EACP,SAAS,EACT;AAAA,IACC;AAAA,EACF;AACJ,CAAC;AAEM,MAAM,WAAW;AAAA,EACtB,MAAM,OAAO,EAAE,SAAS,GAAG;AAEzB,WAAO,MAAM,UAAU,QAAQ;AAAA,EACjC;AAAA,EACA,MAAM;AAAA,EACN,MAAM,cAAc;AAElB,WAAO;AAAA,EACT;AAAA,EACA;AAAA,EAEA,OAAO,KACL,EAAE,aAAa,QAAQ,YAAY,cAAc,GACjD;AAAA,IACE;AAAA,IACA,SAAS,EAAE,WAAW,OAAO,YAAY,gBAAgB,QAAQ;AAAA,IACjE;AAAA,EACF,GAMA;AACA,UAAM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EJ;AAEA,WACE,oCAAC,OAAI,eAAc,SACjB,oCAAC,YAAK,qBAAoB,GAC1B,oCAAC,QAAK,OAAO,MAAM,iBAAe,gBAAc,CAClD;AAAA,EAEJ;AACF;",
|
|
6
6
|
"names": ["normalizedMessages"]
|
|
7
7
|
}
|
|
@@ -31,11 +31,6 @@ async function assertMinVersion() {
|
|
|
31
31
|
if (versionConfig.minVersion && lt(MACRO.VERSION, versionConfig.minVersion)) {
|
|
32
32
|
const suggestions = await getUpdateCommandSuggestions();
|
|
33
33
|
const cmdLines = suggestions.map((c) => ` ${c}`).join("\n");
|
|
34
|
-
console.error(`
|
|
35
|
-
\u60A8\u7684 ${PRODUCT_NAME} \u7248\u672C (${MACRO.VERSION}) \u8FC7\u4F4E\uFF0C\u9700\u8981\u5347\u7EA7\u5230 ${versionConfig.minVersion} \u6216\u66F4\u9AD8\u7248\u672C\u3002
|
|
36
|
-
\u8BF7\u624B\u52A8\u6267\u884C\u4EE5\u4E0B\u4EFB\u4E00\u547D\u4EE4\u8FDB\u884C\u5347\u7EA7\uFF1A
|
|
37
|
-
${cmdLines}
|
|
38
|
-
`);
|
|
39
34
|
process.exit(1);
|
|
40
35
|
}
|
|
41
36
|
} catch (error) {
|
|
@@ -337,8 +332,11 @@ async function checkAndNotifyUpdate() {
|
|
|
337
332
|
lastSuggestedVersion: latest
|
|
338
333
|
});
|
|
339
334
|
const suggestions = await getUpdateCommandSuggestions();
|
|
340
|
-
|
|
341
|
-
console.log(
|
|
335
|
+
console.log(`New version available: ${latest} (current: ${MACRO.VERSION})`);
|
|
336
|
+
console.log("Run the following command to update:");
|
|
337
|
+
for (const command of suggestions) {
|
|
338
|
+
console.log(` ${command}`);
|
|
339
|
+
}
|
|
342
340
|
} else {
|
|
343
341
|
saveGlobalConfig({ ...config, lastUpdateCheckAt: now });
|
|
344
342
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/autoUpdater.ts"],
|
|
4
|
-
"sourcesContent": ["import { homedir } from 'os'\nimport { join } from 'path'\nimport {\n existsSync,\n mkdirSync,\n appendFileSync,\n readFileSync,\n constants,\n writeFileSync,\n unlinkSync,\n statSync,\n} from 'fs'\nimport { platform } from 'process'\nimport { execFileNoThrow } from './execFileNoThrow'\nimport { spawn } from 'child_process'\nimport { logError } from './log'\nimport { accessSync } from 'fs'\nimport { CLAUDE_BASE_DIR } from './env'\nimport { logEvent, getDynamicConfig } from '../services/statsig'\nimport { lt, gt } from 'semver'\nimport { MACRO } from '../constants/macros'\nimport { PRODUCT_COMMAND, PRODUCT_NAME } from '../constants/product'\nimport { getGlobalConfig, saveGlobalConfig, isAutoUpdaterDisabled } from './config'\nimport { env } from './env'\nexport type InstallStatus =\n | 'success'\n | 'no_permissions'\n | 'install_failed'\n | 'in_progress'\n\nexport type AutoUpdaterResult = {\n version: string | null\n status: InstallStatus\n}\n\nexport type VersionConfig = {\n minVersion: string\n}\n\n/**\n * Checks if the current version meets the minimum required version from Statsig config\n * Terminates the process with an error message if the version is too old\n */\nexport async function assertMinVersion(): Promise<void> {\n try {\n const versionConfig = await getDynamicConfig<VersionConfig>(\n 'tengu_version_config',\n { minVersion: '0.0.0' },\n )\n\n if (\n versionConfig.minVersion &&\n lt(MACRO.VERSION, versionConfig.minVersion)\n ) {\n const suggestions = await getUpdateCommandSuggestions()\n const cmdLines = suggestions.map(c => ` ${c}`).join('\\n')\n console.error(`\n\u60A8\u7684 ${PRODUCT_NAME} \u7248\u672C (${MACRO.VERSION}) \u8FC7\u4F4E\uFF0C\u9700\u8981\u5347\u7EA7\u5230 ${versionConfig.minVersion} \u6216\u66F4\u9AD8\u7248\u672C\u3002\n\u8BF7\u624B\u52A8\u6267\u884C\u4EE5\u4E0B\u4EFB\u4E00\u547D\u4EE4\u8FDB\u884C\u5347\u7EA7\uFF1A\n${cmdLines}\n`)\n process.exit(1)\n }\n } catch (error) {\n logError(`Error checking minimum version: ${error}`)\n }\n}\n\n// Lock file for auto-updater to prevent concurrent updates\nexport const LOCK_FILE_PATH = join(CLAUDE_BASE_DIR, '.update.lock')\nconst LOCK_TIMEOUT_MS = 5 * 60 * 1000 // 5 minute timeout for locks\n\n/**\n * Attempts to acquire a lock for auto-updater\n * @returns {boolean} true if lock was acquired, false if another process holds the lock\n */\nfunction acquireLock(): boolean {\n try {\n // Ensure the base directory exists\n if (!existsSync(CLAUDE_BASE_DIR)) {\n mkdirSync(CLAUDE_BASE_DIR, { recursive: true })\n }\n\n // Check if lock file exists and is not stale\n if (existsSync(LOCK_FILE_PATH)) {\n const stats = statSync(LOCK_FILE_PATH)\n const age = Date.now() - stats.mtimeMs\n\n // If lock file is older than timeout, consider it stale\n if (age < LOCK_TIMEOUT_MS) {\n return false\n }\n\n // Lock is stale, we can take over\n try {\n unlinkSync(LOCK_FILE_PATH)\n } catch (err) {\n logError(`Failed to remove stale lock file: ${err}`)\n return false\n }\n }\n\n // Create lock file with current pid\n writeFileSync(LOCK_FILE_PATH, `${process.pid}`, 'utf8')\n return true\n } catch (err) {\n logError(`Failed to acquire lock: ${err}`)\n return false\n }\n}\n\n/**\n * Releases the update lock if it's held by this process\n */\nfunction releaseLock(): void {\n try {\n if (existsSync(LOCK_FILE_PATH)) {\n const lockData = readFileSync(LOCK_FILE_PATH, 'utf8')\n if (lockData === `${process.pid}`) {\n unlinkSync(LOCK_FILE_PATH)\n }\n }\n } catch (err) {\n logError(`Failed to release lock: ${err}`)\n }\n}\n\nexport async function checkNpmPermissions(): Promise<{\n hasPermissions: boolean\n npmPrefix: string | null\n}> {\n try {\n const prefixResult = await execFileNoThrow('npm', [\n '-g',\n 'config',\n 'get',\n 'prefix',\n ])\n if (prefixResult.code !== 0) {\n logError('Failed to check npm permissions')\n return { hasPermissions: false, npmPrefix: null }\n }\n\n const prefix = prefixResult.stdout.trim()\n\n let testWriteResult = false\n try {\n accessSync(prefix, constants.W_OK)\n testWriteResult = true\n } catch {\n testWriteResult = false\n }\n\n if (testWriteResult) {\n return { hasPermissions: true, npmPrefix: prefix }\n }\n\n logError('Insufficient permissions for global npm install.')\n return { hasPermissions: false, npmPrefix: prefix }\n } catch (error) {\n logError(`Failed to verify npm global install permissions: ${error}`)\n return { hasPermissions: false, npmPrefix: null }\n }\n}\n\nexport async function setupNewPrefix(prefix: string): Promise<void> {\n if (!acquireLock()) {\n // Log the lock contention to statsig\n logEvent('tengu_auto_updater_prefix_lock_contention', {\n pid: String(process.pid),\n currentVersion: MACRO.VERSION,\n prefix,\n })\n throw new Error('Another process is currently setting up npm prefix')\n }\n\n try {\n // Create directory if it doesn't exist\n if (!existsSync(prefix)) {\n mkdirSync(prefix, { recursive: true })\n }\n\n // Set npm prefix\n const setPrefix = await execFileNoThrow('npm', [\n '-g',\n 'config',\n 'set',\n 'prefix',\n prefix,\n ])\n\n if (setPrefix.code !== 0) {\n throw new Error(`Failed to set npm prefix: ${setPrefix.stderr}`)\n }\n\n // Update shell config files\n const pathUpdate = `\\n# npm global path\\nexport PATH=\"${prefix}/bin:$PATH\"\\n`\n\n if (platform === 'win32') {\n // On Windows, update user PATH environment variable\n const setxResult = await execFileNoThrow('setx', [\n 'PATH',\n `${process.env.PATH};${prefix}`,\n ])\n if (setxResult.code !== 0) {\n throw new Error(\n `Failed to update PATH on Windows: ${setxResult.stderr}`,\n )\n }\n } else {\n // Unix-like systems\n const shellConfigs = [\n // Bash\n join(homedir(), '.bashrc'),\n join(homedir(), '.bash_profile'),\n // Zsh\n join(homedir(), '.zshrc'),\n // Fish\n join(homedir(), '.config', 'fish', 'config.fish'),\n ]\n\n for (const config of shellConfigs) {\n if (existsSync(config)) {\n try {\n const content = readFileSync(config, 'utf8')\n if (!content.includes(prefix)) {\n if (config.includes('fish')) {\n // Fish shell has different syntax\n const fishPath = `\\n# npm global path\\nset -gx PATH ${prefix}/bin $PATH\\n`\n appendFileSync(config, fishPath)\n } else {\n appendFileSync(config, pathUpdate)\n }\n\n logEvent('npm_prefix_path_updated', {\n configPath: config,\n })\n }\n } catch (err) {\n // Log but don't throw - continue with other configs\n logEvent('npm_prefix_path_update_failed', {\n configPath: config,\n error:\n err instanceof Error\n ? err.message.slice(0, 200)\n : String(err).slice(0, 200),\n })\n logError(`Failed to update shell config ${config}: ${err}`)\n }\n }\n }\n }\n } finally {\n releaseLock()\n }\n}\n\nexport function getDefaultNpmPrefix(): string {\n return join(homedir(), '.npm-global')\n}\n\nexport function getPermissionsCommand(npmPrefix: string): string {\n const windowsCommand = `icacls \"${npmPrefix}\" /grant \"%USERNAME%:(OI)(CI)F\"`\n const prefixPath = npmPrefix || '$(npm -g config get prefix)'\n const unixCommand = `sudo chown -R $USER:$(id -gn) ${prefixPath} && sudo chmod -R u+w ${prefixPath}`\n\n return platform === 'win32' ? windowsCommand : unixCommand\n}\n\nexport async function getLatestVersion(): Promise<string | null> {\n // 1) Try npm CLI (fast when available)\n try {\n const abortController = new AbortController()\n setTimeout(() => abortController.abort(), 5000)\n const result = await execFileNoThrow(\n 'npm',\n ['view', MACRO.PACKAGE_URL, 'version'],\n abortController.signal,\n )\n if (result.code === 0) {\n const v = result.stdout.trim()\n if (v) return v\n }\n } catch {}\n\n // 2) Fallback: fetch npm registry (works in Bun/Node without npm)\n try {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), 5000)\n const res = await fetch(\n `https://registry.npmjs.org/${encodeURIComponent(MACRO.PACKAGE_URL)}`,\n {\n method: 'GET',\n headers: {\n Accept: 'application/vnd.npm.install-v1+json',\n 'User-Agent': `${PRODUCT_NAME}/${MACRO.VERSION}`,\n },\n signal: controller.signal,\n },\n )\n clearTimeout(timer)\n if (!res.ok) return null\n const json: any = await res.json().catch(() => null)\n const latest = json && json['dist-tags'] && json['dist-tags'].latest\n return typeof latest === 'string' ? latest : null\n } catch {\n return null\n }\n}\n\nexport async function installGlobalPackage(): Promise<InstallStatus> {\n // Detect preferred package manager and install accordingly\n if (!acquireLock()) {\n logError('Another process is currently installing an update')\n // Log the lock contention to statsig\n logEvent('tengu_auto_updater_lock_contention', {\n pid: String(process.pid),\n currentVersion: MACRO.VERSION,\n })\n return 'in_progress'\n }\n\n try {\n const manager = await detectPackageManager()\n if (manager === 'npm') {\n const { hasPermissions } = await checkNpmPermissions()\n if (!hasPermissions) {\n return 'no_permissions'\n }\n // Stream\u5B9E\u65F6\u8F93\u51FA\uFF0C\u51CF\u5C11\u7528\u6237\u7B49\u5F85\u611F\n const code = await runStreaming('npm', ['install', '-g', MACRO.PACKAGE_URL])\n if (code !== 0) {\n logError(`Failed to install new version via npm (exit ${code})`)\n return 'install_failed'\n }\n return 'success'\n }\n\n if (manager === 'bun') {\n const code = await runStreaming('bun', ['add', '-g', `${MACRO.PACKAGE_URL}@latest`])\n if (code !== 0) {\n logError(`Failed to install new version via bun (exit ${code})`)\n return 'install_failed'\n }\n return 'success'\n }\n\n // Fallback to npm if unknown\n const { hasPermissions } = await checkNpmPermissions()\n if (!hasPermissions) return 'no_permissions'\n const code = await runStreaming('npm', ['install', '-g', MACRO.PACKAGE_URL])\n if (code !== 0) return 'install_failed'\n return 'success'\n } finally {\n // Ensure we always release the lock\n releaseLock()\n }\n}\n\nexport type PackageManager = 'npm' | 'bun'\n\nexport async function detectPackageManager(): Promise<PackageManager> {\n // Respect explicit override if provided later via config/env (future-proof)\n try {\n // Heuristic 1: npm available and global root resolvable\n const npmRoot = await execFileNoThrow('npm', ['-g', 'root'])\n if (npmRoot.code === 0 && npmRoot.stdout.trim()) {\n return 'npm'\n }\n } catch {}\n\n try {\n // Heuristic 2: running on a system with bun and installed path hints bun\n const bunVer = await execFileNoThrow('bun', ['--version'])\n if (bunVer.code === 0) {\n // BUN_INSTALL defaults to ~/.bun; if our package lives under that tree, prefer bun\n // If npm not detected but bun is available, choose bun\n return 'bun'\n }\n } catch {}\n\n // Default to npm when uncertain\n return 'npm'\n}\n\nfunction runStreaming(cmd: string, args: string[]): Promise<number> {\n return new Promise(resolve => {\n // \u6253\u5370\u6B63\u5728\u4F7F\u7528\u7684\u5305\u7BA1\u7406\u5668\u4E0E\u547D\u4EE4\uFF0C\u589E\u5F3A\u900F\u660E\u5EA6\n try {\n // eslint-disable-next-line no-console\n console.log(`> ${cmd} ${args.join(' ')}`)\n } catch {}\n\n const child = spawn(cmd, args, {\n stdio: 'inherit',\n env: process.env,\n })\n child.on('close', code => resolve(code ?? 0))\n child.on('error', () => resolve(1))\n })\n}\n\n/**\n * Generate human-friendly update commands for the detected package manager.\n * Also includes an alternative manager command as fallback for users.\n */\nexport async function getUpdateCommandSuggestions(): Promise<string[]> {\n // Prefer Bun first, then npm (consistent, simple UX). Include @latest.\n return [\n `bun add -g ${MACRO.PACKAGE_URL}@latest`,\n `npm install -g ${MACRO.PACKAGE_URL}@latest`,\n ]\n}\n\n/**\n * Non-blocking update notifier (daily)\n * - Respects CI and disabled auto-updater\n * - Uses env.hasInternetAccess() to quickly skip offline cases\n * - Stores last check timestamp + last suggested version in global config\n */\nexport async function checkAndNotifyUpdate(): Promise<void> {\n try {\n if (process.env.NODE_ENV === 'test') return\n if (await isAutoUpdaterDisabled()) return\n if (await env.getIsDocker()) return\n if (!(await env.hasInternetAccess())) return\n\n const config: any = getGlobalConfig()\n const now = Date.now()\n const DAY_MS = 24 * 60 * 60 * 1000\n const lastCheck = Number(config.lastUpdateCheckAt || 0)\n if (lastCheck && now - lastCheck < DAY_MS) return\n\n const latest = await getLatestVersion()\n if (!latest) {\n // Still record the check to avoid spamming\n saveGlobalConfig({ ...config, lastUpdateCheckAt: now })\n return\n }\n\n if (gt(latest, MACRO.VERSION)) {\n // Update stored state and print a low-noise hint\n saveGlobalConfig({\n ...config,\n lastUpdateCheckAt: now,\n lastSuggestedVersion: latest,\n })\n const suggestions = await getUpdateCommandSuggestions()\n const first = suggestions[0]\n console.log(`New version available: ${latest}. Recommended: ${first}`)\n } else {\n saveGlobalConfig({ ...config, lastUpdateCheckAt: now })\n }\n } catch (error) {\n // Never block or throw; just log and move on\n logError(`update-notify: ${error}`)\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB;AACzB,SAAS,uBAAuB;AAChC,SAAS,aAAa;AACtB,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,SAAS,uBAAuB;AAChC,SAAS,UAAU,wBAAwB;AAC3C,SAAS,IAAI,UAAU;AACvB,SAAS,aAAa;AACtB,SAA0B,oBAAoB;AAC9C,SAAS,iBAAiB,kBAAkB,6BAA6B;AACzE,SAAS,WAAW;AAoBpB,eAAsB,mBAAkC;AACtD,MAAI;AACF,UAAM,gBAAgB,MAAM;AAAA,MAC1B;AAAA,MACA,EAAE,YAAY,QAAQ;AAAA,IACxB;AAEA,QACE,cAAc,cACd,GAAG,MAAM,SAAS,cAAc,UAAU,GAC1C;AACA,YAAM,cAAc,MAAM,4BAA4B;AACtD,YAAM,WAAW,YAAY,IAAI,OAAK,OAAO,CAAC,EAAE,EAAE,KAAK,IAAI;AAC3D,cAAQ,
|
|
4
|
+
"sourcesContent": ["import { homedir } from 'os'\nimport { join } from 'path'\nimport {\n existsSync,\n mkdirSync,\n appendFileSync,\n readFileSync,\n constants,\n writeFileSync,\n unlinkSync,\n statSync,\n} from 'fs'\nimport { platform } from 'process'\nimport { execFileNoThrow } from './execFileNoThrow'\nimport { spawn } from 'child_process'\nimport { logError } from './log'\nimport { accessSync } from 'fs'\nimport { CLAUDE_BASE_DIR } from './env'\nimport { logEvent, getDynamicConfig } from '../services/statsig'\nimport { lt, gt } from 'semver'\nimport { MACRO } from '../constants/macros'\nimport { PRODUCT_COMMAND, PRODUCT_NAME } from '../constants/product'\nimport { getGlobalConfig, saveGlobalConfig, isAutoUpdaterDisabled } from './config'\nimport { env } from './env'\nexport type InstallStatus =\n | 'success'\n | 'no_permissions'\n | 'install_failed'\n | 'in_progress'\n\nexport type AutoUpdaterResult = {\n version: string | null\n status: InstallStatus\n}\n\nexport type VersionConfig = {\n minVersion: string\n}\n\n/**\n * Checks if the current version meets the minimum required version from Statsig config\n * Terminates the process with an error message if the version is too old\n */\nexport async function assertMinVersion(): Promise<void> {\n try {\n const versionConfig = await getDynamicConfig<VersionConfig>(\n 'tengu_version_config',\n { minVersion: '0.0.0' },\n )\n\n if (\n versionConfig.minVersion &&\n lt(MACRO.VERSION, versionConfig.minVersion)\n ) {\n const suggestions = await getUpdateCommandSuggestions()\n const cmdLines = suggestions.map(c => ` ${c}`).join('\\n')\n process.exit(1)\n }\n } catch (error) {\n logError(`Error checking minimum version: ${error}`)\n }\n}\n\n// Lock file for auto-updater to prevent concurrent updates\nexport const LOCK_FILE_PATH = join(CLAUDE_BASE_DIR, '.update.lock')\nconst LOCK_TIMEOUT_MS = 5 * 60 * 1000 // 5 minute timeout for locks\n\n/**\n * Attempts to acquire a lock for auto-updater\n * @returns {boolean} true if lock was acquired, false if another process holds the lock\n */\nfunction acquireLock(): boolean {\n try {\n // Ensure the base directory exists\n if (!existsSync(CLAUDE_BASE_DIR)) {\n mkdirSync(CLAUDE_BASE_DIR, { recursive: true })\n }\n\n // Check if lock file exists and is not stale\n if (existsSync(LOCK_FILE_PATH)) {\n const stats = statSync(LOCK_FILE_PATH)\n const age = Date.now() - stats.mtimeMs\n\n // If lock file is older than timeout, consider it stale\n if (age < LOCK_TIMEOUT_MS) {\n return false\n }\n\n // Lock is stale, we can take over\n try {\n unlinkSync(LOCK_FILE_PATH)\n } catch (err) {\n logError(`Failed to remove stale lock file: ${err}`)\n return false\n }\n }\n\n // Create lock file with current pid\n writeFileSync(LOCK_FILE_PATH, `${process.pid}`, 'utf8')\n return true\n } catch (err) {\n logError(`Failed to acquire lock: ${err}`)\n return false\n }\n}\n\n/**\n * Releases the update lock if it's held by this process\n */\nfunction releaseLock(): void {\n try {\n if (existsSync(LOCK_FILE_PATH)) {\n const lockData = readFileSync(LOCK_FILE_PATH, 'utf8')\n if (lockData === `${process.pid}`) {\n unlinkSync(LOCK_FILE_PATH)\n }\n }\n } catch (err) {\n logError(`Failed to release lock: ${err}`)\n }\n}\n\nexport async function checkNpmPermissions(): Promise<{\n hasPermissions: boolean\n npmPrefix: string | null\n}> {\n try {\n const prefixResult = await execFileNoThrow('npm', [\n '-g',\n 'config',\n 'get',\n 'prefix',\n ])\n if (prefixResult.code !== 0) {\n logError('Failed to check npm permissions')\n return { hasPermissions: false, npmPrefix: null }\n }\n\n const prefix = prefixResult.stdout.trim()\n\n let testWriteResult = false\n try {\n accessSync(prefix, constants.W_OK)\n testWriteResult = true\n } catch {\n testWriteResult = false\n }\n\n if (testWriteResult) {\n return { hasPermissions: true, npmPrefix: prefix }\n }\n\n logError('Insufficient permissions for global npm install.')\n return { hasPermissions: false, npmPrefix: prefix }\n } catch (error) {\n logError(`Failed to verify npm global install permissions: ${error}`)\n return { hasPermissions: false, npmPrefix: null }\n }\n}\n\nexport async function setupNewPrefix(prefix: string): Promise<void> {\n if (!acquireLock()) {\n // Log the lock contention to statsig\n logEvent('tengu_auto_updater_prefix_lock_contention', {\n pid: String(process.pid),\n currentVersion: MACRO.VERSION,\n prefix,\n })\n throw new Error('Another process is currently setting up npm prefix')\n }\n\n try {\n // Create directory if it doesn't exist\n if (!existsSync(prefix)) {\n mkdirSync(prefix, { recursive: true })\n }\n\n // Set npm prefix\n const setPrefix = await execFileNoThrow('npm', [\n '-g',\n 'config',\n 'set',\n 'prefix',\n prefix,\n ])\n\n if (setPrefix.code !== 0) {\n throw new Error(`Failed to set npm prefix: ${setPrefix.stderr}`)\n }\n\n // Update shell config files\n const pathUpdate = `\\n# npm global path\\nexport PATH=\"${prefix}/bin:$PATH\"\\n`\n\n if (platform === 'win32') {\n // On Windows, update user PATH environment variable\n const setxResult = await execFileNoThrow('setx', [\n 'PATH',\n `${process.env.PATH};${prefix}`,\n ])\n if (setxResult.code !== 0) {\n throw new Error(\n `Failed to update PATH on Windows: ${setxResult.stderr}`,\n )\n }\n } else {\n // Unix-like systems\n const shellConfigs = [\n // Bash\n join(homedir(), '.bashrc'),\n join(homedir(), '.bash_profile'),\n // Zsh\n join(homedir(), '.zshrc'),\n // Fish\n join(homedir(), '.config', 'fish', 'config.fish'),\n ]\n\n for (const config of shellConfigs) {\n if (existsSync(config)) {\n try {\n const content = readFileSync(config, 'utf8')\n if (!content.includes(prefix)) {\n if (config.includes('fish')) {\n // Fish shell has different syntax\n const fishPath = `\\n# npm global path\\nset -gx PATH ${prefix}/bin $PATH\\n`\n appendFileSync(config, fishPath)\n } else {\n appendFileSync(config, pathUpdate)\n }\n\n logEvent('npm_prefix_path_updated', {\n configPath: config,\n })\n }\n } catch (err) {\n // Log but don't throw - continue with other configs\n logEvent('npm_prefix_path_update_failed', {\n configPath: config,\n error:\n err instanceof Error\n ? err.message.slice(0, 200)\n : String(err).slice(0, 200),\n })\n logError(`Failed to update shell config ${config}: ${err}`)\n }\n }\n }\n }\n } finally {\n releaseLock()\n }\n}\n\nexport function getDefaultNpmPrefix(): string {\n return join(homedir(), '.npm-global')\n}\n\nexport function getPermissionsCommand(npmPrefix: string): string {\n const windowsCommand = `icacls \"${npmPrefix}\" /grant \"%USERNAME%:(OI)(CI)F\"`\n const prefixPath = npmPrefix || '$(npm -g config get prefix)'\n const unixCommand = `sudo chown -R $USER:$(id -gn) ${prefixPath} && sudo chmod -R u+w ${prefixPath}`\n\n return platform === 'win32' ? windowsCommand : unixCommand\n}\n\nexport async function getLatestVersion(): Promise<string | null> {\n // 1) Try npm CLI (fast when available)\n try {\n const abortController = new AbortController()\n setTimeout(() => abortController.abort(), 5000)\n const result = await execFileNoThrow(\n 'npm',\n ['view', MACRO.PACKAGE_URL, 'version'],\n abortController.signal,\n )\n if (result.code === 0) {\n const v = result.stdout.trim()\n if (v) return v\n }\n } catch {}\n\n // 2) Fallback: fetch npm registry (works in Bun/Node without npm)\n try {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), 5000)\n const res = await fetch(\n `https://registry.npmjs.org/${encodeURIComponent(MACRO.PACKAGE_URL)}`,\n {\n method: 'GET',\n headers: {\n Accept: 'application/vnd.npm.install-v1+json',\n 'User-Agent': `${PRODUCT_NAME}/${MACRO.VERSION}`,\n },\n signal: controller.signal,\n },\n )\n clearTimeout(timer)\n if (!res.ok) return null\n const json: any = await res.json().catch(() => null)\n const latest = json && json['dist-tags'] && json['dist-tags'].latest\n return typeof latest === 'string' ? latest : null\n } catch {\n return null\n }\n}\n\nexport async function installGlobalPackage(): Promise<InstallStatus> {\n // Detect preferred package manager and install accordingly\n if (!acquireLock()) {\n logError('Another process is currently installing an update')\n // Log the lock contention to statsig\n logEvent('tengu_auto_updater_lock_contention', {\n pid: String(process.pid),\n currentVersion: MACRO.VERSION,\n })\n return 'in_progress'\n }\n\n try {\n const manager = await detectPackageManager()\n if (manager === 'npm') {\n const { hasPermissions } = await checkNpmPermissions()\n if (!hasPermissions) {\n return 'no_permissions'\n }\n // Stream\u5B9E\u65F6\u8F93\u51FA\uFF0C\u51CF\u5C11\u7528\u6237\u7B49\u5F85\u611F\n const code = await runStreaming('npm', ['install', '-g', MACRO.PACKAGE_URL])\n if (code !== 0) {\n logError(`Failed to install new version via npm (exit ${code})`)\n return 'install_failed'\n }\n return 'success'\n }\n\n if (manager === 'bun') {\n const code = await runStreaming('bun', ['add', '-g', `${MACRO.PACKAGE_URL}@latest`])\n if (code !== 0) {\n logError(`Failed to install new version via bun (exit ${code})`)\n return 'install_failed'\n }\n return 'success'\n }\n\n // Fallback to npm if unknown\n const { hasPermissions } = await checkNpmPermissions()\n if (!hasPermissions) return 'no_permissions'\n const code = await runStreaming('npm', ['install', '-g', MACRO.PACKAGE_URL])\n if (code !== 0) return 'install_failed'\n return 'success'\n } finally {\n // Ensure we always release the lock\n releaseLock()\n }\n}\n\nexport type PackageManager = 'npm' | 'bun'\n\nexport async function detectPackageManager(): Promise<PackageManager> {\n // Respect explicit override if provided later via config/env (future-proof)\n try {\n // Heuristic 1: npm available and global root resolvable\n const npmRoot = await execFileNoThrow('npm', ['-g', 'root'])\n if (npmRoot.code === 0 && npmRoot.stdout.trim()) {\n return 'npm'\n }\n } catch {}\n\n try {\n // Heuristic 2: running on a system with bun and installed path hints bun\n const bunVer = await execFileNoThrow('bun', ['--version'])\n if (bunVer.code === 0) {\n // BUN_INSTALL defaults to ~/.bun; if our package lives under that tree, prefer bun\n // If npm not detected but bun is available, choose bun\n return 'bun'\n }\n } catch {}\n\n // Default to npm when uncertain\n return 'npm'\n}\n\nfunction runStreaming(cmd: string, args: string[]): Promise<number> {\n return new Promise(resolve => {\n // \u6253\u5370\u6B63\u5728\u4F7F\u7528\u7684\u5305\u7BA1\u7406\u5668\u4E0E\u547D\u4EE4\uFF0C\u589E\u5F3A\u900F\u660E\u5EA6\n try {\n // eslint-disable-next-line no-console\n console.log(`> ${cmd} ${args.join(' ')}`)\n } catch {}\n\n const child = spawn(cmd, args, {\n stdio: 'inherit',\n env: process.env,\n })\n child.on('close', code => resolve(code ?? 0))\n child.on('error', () => resolve(1))\n })\n}\n\n/**\n * Generate human-friendly update commands for the detected package manager.\n * Also includes an alternative manager command as fallback for users.\n */\nexport async function getUpdateCommandSuggestions(): Promise<string[]> {\n // Prefer Bun first, then npm (consistent, simple UX). Include @latest.\n return [\n `bun add -g ${MACRO.PACKAGE_URL}@latest`,\n `npm install -g ${MACRO.PACKAGE_URL}@latest`,\n ]\n}\n\n/**\n * Non-blocking update notifier (daily)\n * - Respects CI and disabled auto-updater\n * - Uses env.hasInternetAccess() to quickly skip offline cases\n * - Stores last check timestamp + last suggested version in global config\n */\nexport async function checkAndNotifyUpdate(): Promise<void> {\n try {\n if (process.env.NODE_ENV === 'test') return\n if (await isAutoUpdaterDisabled()) return\n if (await env.getIsDocker()) return\n if (!(await env.hasInternetAccess())) return\n\n const config: any = getGlobalConfig()\n const now = Date.now()\n const DAY_MS = 24 * 60 * 60 * 1000\n const lastCheck = Number(config.lastUpdateCheckAt || 0)\n if (lastCheck && now - lastCheck < DAY_MS) return\n\n const latest = await getLatestVersion()\n if (!latest) {\n // Still record the check to avoid spamming\n saveGlobalConfig({ ...config, lastUpdateCheckAt: now })\n return\n }\n\n if (gt(latest, MACRO.VERSION)) {\n // Update stored state and print a low-noise hint\n saveGlobalConfig({\n ...config,\n lastUpdateCheckAt: now,\n lastSuggestedVersion: latest,\n })\n const suggestions = await getUpdateCommandSuggestions()\n console.log(`New version available: ${latest} (current: ${MACRO.VERSION})`)\n console.log('Run the following command to update:')\n for (const command of suggestions) {\n console.log(` ${command}`)\n }\n } else {\n saveGlobalConfig({ ...config, lastUpdateCheckAt: now })\n }\n } catch (error) {\n // Never block or throw; just log and move on\n logError(`update-notify: ${error}`)\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB;AACzB,SAAS,uBAAuB;AAChC,SAAS,aAAa;AACtB,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,SAAS,uBAAuB;AAChC,SAAS,UAAU,wBAAwB;AAC3C,SAAS,IAAI,UAAU;AACvB,SAAS,aAAa;AACtB,SAA0B,oBAAoB;AAC9C,SAAS,iBAAiB,kBAAkB,6BAA6B;AACzE,SAAS,WAAW;AAoBpB,eAAsB,mBAAkC;AACtD,MAAI;AACF,UAAM,gBAAgB,MAAM;AAAA,MAC1B;AAAA,MACA,EAAE,YAAY,QAAQ;AAAA,IACxB;AAEA,QACE,cAAc,cACd,GAAG,MAAM,SAAS,cAAc,UAAU,GAC1C;AACA,YAAM,cAAc,MAAM,4BAA4B;AACtD,YAAM,WAAW,YAAY,IAAI,OAAK,OAAO,CAAC,EAAE,EAAE,KAAK,IAAI;AAC3D,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF,SAAS,OAAO;A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AAK,EAAE;AAAA,EACpC;AACF;",
|
|
6
6
|
"names": ["hasPermissions", "code"]
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/generators.ts"],
|
|
4
|
-
"sourcesContent": ["const NO_VALUE = Symbol('NO_VALUE')\n\nexport async function lastX<A>(as: AsyncGenerator<A>): Promise<A> {\n let lastValue: A | typeof NO_VALUE = NO_VALUE\n for await (const a of as) {\n lastValue = a\n }\n if (lastValue === NO_VALUE) {\n throw new Error('No items in generator')\n }\n return lastValue\n}\n\ntype QueuedGenerator<A> = {\n done: boolean | void\n value: A | void\n generator: AsyncGenerator<A, void>\n promise: Promise<QueuedGenerator<A>>\n}\n\n// Run all generators concurrently up to a concurrency cap, yielding values as they come in\nexport async function* all<A>(\n generators: AsyncGenerator<A, void>[],\n concurrencyCap = Infinity,\n): AsyncGenerator<A, void> {\n const next = (generator: AsyncGenerator<A, void>) => {\n const promise: Promise<QueuedGenerator<A>> = generator\n .next()\n .then(({ done, value }) => ({\n done,\n value,\n generator,\n promise,\n }))\n return promise\n }\n const waiting = [...generators]\n const promises = new Set<Promise<QueuedGenerator<A>>>()\n\n // Start initial batch up to concurrency cap\n while (promises.size < concurrencyCap && waiting.length > 0) {\n const gen = waiting.shift()!\n promises.add(next(gen))\n }\n\n while (promises.size > 0) {\n const { done, value, generator, promise } = await Promise.race(promises)\n promises.delete(promise)\n\n if (!done) {\n promises.add(next(generator))\n //
|
|
4
|
+
"sourcesContent": ["const NO_VALUE = Symbol('NO_VALUE')\n\nexport async function lastX<A>(as: AsyncGenerator<A>): Promise<A> {\n let lastValue: A | typeof NO_VALUE = NO_VALUE\n for await (const a of as) {\n lastValue = a\n }\n if (lastValue === NO_VALUE) {\n throw new Error('No items in generator')\n }\n return lastValue\n}\n\ntype QueuedGenerator<A> = {\n done: boolean | void\n value: A | void\n generator: AsyncGenerator<A, void>\n promise: Promise<QueuedGenerator<A>>\n}\n\n// Run all generators concurrently up to a concurrency cap, yielding values as they come in\nexport async function* all<A>(\n generators: AsyncGenerator<A, void>[],\n concurrencyCap = Infinity,\n): AsyncGenerator<A, void> {\n const next = (generator: AsyncGenerator<A, void>) => {\n const promise: Promise<QueuedGenerator<A>> = generator\n .next()\n .then(({ done, value }) => ({\n done,\n value,\n generator,\n promise,\n }))\n return promise\n }\n const waiting = [...generators]\n const promises = new Set<Promise<QueuedGenerator<A>>>()\n\n // Start initial batch up to concurrency cap\n while (promises.size < concurrencyCap && waiting.length > 0) {\n const gen = waiting.shift()!\n promises.add(next(gen))\n }\n\n while (promises.size > 0) {\n const { done, value, generator, promise } = await Promise.race(promises)\n promises.delete(promise)\n\n if (!done) {\n promises.add(next(generator))\n // Yield non-undefined values from the generator\n if (value !== undefined) {\n yield value as A\n }\n } else if (waiting.length > 0) {\n // Start a new generator when one finishes\n const nextGen = waiting.shift()!\n promises.add(next(nextGen))\n }\n }\n}\n"],
|
|
5
5
|
"mappings": "AAAA,MAAM,WAAW,OAAO,UAAU;AAElC,eAAsB,MAAS,IAAmC;AAChE,MAAI,YAAiC;AACrC,mBAAiB,KAAK,IAAI;AACxB,gBAAY;AAAA,EACd;AACA,MAAI,cAAc,UAAU;AAC1B,UAAM,IAAI,MAAM,uBAAuB;AAAA,EACzC;AACA,SAAO;AACT;AAUA,gBAAuB,IACrB,YACA,iBAAiB,UACQ;AACzB,QAAM,OAAO,CAAC,cAAuC;AACnD,UAAM,UAAuC,UAC1C,KAAK,EACL,KAAK,CAAC,EAAE,MAAM,MAAM,OAAO;AAAA,MAC1B;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,EAAE;AACJ,WAAO;AAAA,EACT;AACA,QAAM,UAAU,CAAC,GAAG,UAAU;AAC9B,QAAM,WAAW,oBAAI,IAAiC;AAGtD,SAAO,SAAS,OAAO,kBAAkB,QAAQ,SAAS,GAAG;AAC3D,UAAM,MAAM,QAAQ,MAAM;AAC1B,aAAS,IAAI,KAAK,GAAG,CAAC;AAAA,EACxB;AAEA,SAAO,SAAS,OAAO,GAAG;AACxB,UAAM,EAAE,MAAM,OAAO,WAAW,QAAQ,IAAI,MAAM,QAAQ,KAAK,QAAQ;AACvE,aAAS,OAAO,OAAO;AAEvB,QAAI,CAAC,MAAM;AACT,eAAS,IAAI,KAAK,SAAS,CAAC;AAE5B,UAAI,UAAU,QAAW;AACvB,cAAM;AAAA,MACR;AAAA,IACF,WAAW,QAAQ,SAAS,GAAG;AAE7B,YAAM,UAAU,QAAQ,MAAM;AAC9B,eAAS,IAAI,KAAK,OAAO,CAAC;AAAA,IAC5B;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shareai-lab/kode",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.19-dev.1",
|
|
4
4
|
"bin": {
|
|
5
5
|
"kode": "cli.js",
|
|
6
6
|
"kwa": "cli.js",
|
|
@@ -40,6 +40,65 @@
|
|
|
40
40
|
"lint:fix": "eslint . --ext .ts,.tsx,.js --fix",
|
|
41
41
|
"test": "bun test",
|
|
42
42
|
"typecheck": "tsc --noEmit",
|
|
43
|
-
"prepare": ""
|
|
43
|
+
"prepare": "",
|
|
44
|
+
"publish:dev": "node scripts/publish-dev.js",
|
|
45
|
+
"publish:release": "node scripts/publish-release.js"
|
|
46
|
+
},
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"@anthropic-ai/bedrock-sdk": "^0.12.6",
|
|
49
|
+
"@anthropic-ai/sdk": "^0.39.0",
|
|
50
|
+
"@anthropic-ai/vertex-sdk": "^0.7.0",
|
|
51
|
+
"@commander-js/extra-typings": "^13.1.0",
|
|
52
|
+
"@inkjs/ui": "^2.0.0",
|
|
53
|
+
"@modelcontextprotocol/sdk": "^1.15.1",
|
|
54
|
+
"@shareai-lab/kode": "^1.1.21-dev.1",
|
|
55
|
+
"@statsig/client-core": "^3.18.2",
|
|
56
|
+
"@statsig/js-client": "^3.18.2",
|
|
57
|
+
"@types/lodash-es": "^4.17.12",
|
|
58
|
+
"@types/react": "^19.1.8",
|
|
59
|
+
"ansi-escapes": "^7.0.0",
|
|
60
|
+
"chalk": "^5.4.1",
|
|
61
|
+
"cli-highlight": "^2.1.11",
|
|
62
|
+
"cli-table3": "^0.6.5",
|
|
63
|
+
"commander": "^13.1.0",
|
|
64
|
+
"debug": "^4.4.1",
|
|
65
|
+
"diff": "^7.0.0",
|
|
66
|
+
"dotenv": "^16.6.1",
|
|
67
|
+
"env-paths": "^3.0.0",
|
|
68
|
+
"figures": "^6.1.0",
|
|
69
|
+
"glob": "^11.0.3",
|
|
70
|
+
"gray-matter": "^4.0.3",
|
|
71
|
+
"highlight.js": "^11.11.1",
|
|
72
|
+
"ink": "^5.2.1",
|
|
73
|
+
"ink-link": "^4.1.0",
|
|
74
|
+
"ink-select-input": "^6.2.0",
|
|
75
|
+
"ink-text-input": "^6.0.0",
|
|
76
|
+
"lodash-es": "^4.17.21",
|
|
77
|
+
"lru-cache": "^11.1.0",
|
|
78
|
+
"marked": "^15.0.12",
|
|
79
|
+
"nanoid": "^5.1.5",
|
|
80
|
+
"node-fetch": "^3.3.2",
|
|
81
|
+
"node-html-parser": "^7.0.1",
|
|
82
|
+
"openai": "^4.104.0",
|
|
83
|
+
"turndown": "^7.2.0",
|
|
84
|
+
"react": "18.3.1",
|
|
85
|
+
"semver": "^7.7.2",
|
|
86
|
+
"shell-quote": "^1.8.3",
|
|
87
|
+
"spawn-rx": "^5.1.2",
|
|
88
|
+
"string-width": "^7.2.0",
|
|
89
|
+
"strip-ansi": "^7.1.0",
|
|
90
|
+
"tsx": "^4.20.3",
|
|
91
|
+
"undici": "^7.11.0",
|
|
92
|
+
"wrap-ansi": "^9.0.0",
|
|
93
|
+
"zod": "^3.25.76",
|
|
94
|
+
"zod-to-json-schema": "^3.24.6"
|
|
95
|
+
},
|
|
96
|
+
"devDependencies": {
|
|
97
|
+
"@types/bun": "latest",
|
|
98
|
+
"@types/jest": "^30.0.0",
|
|
99
|
+
"@types/node": "^24.1.0",
|
|
100
|
+
"bun-types": "latest",
|
|
101
|
+
"prettier": "^3.6.2",
|
|
102
|
+
"typescript": "^5.9.2"
|
|
44
103
|
}
|
|
45
104
|
}
|