oricore 1.5.0 → 1.5.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/{chunk-DO76AL42.js → chunk-D5X6YFSK.js} +2 -1
- package/dist/{chunk-4QYFQSAC.js → chunk-MZNH54NB.js} +128 -75
- package/dist/chunk-MZNH54NB.js.map +1 -0
- package/dist/{chunk-OYWDQD3F.js → chunk-XBRIUBK5.js} +2 -2
- package/dist/history-FS6CASR6.js +8 -0
- package/dist/index.cjs +416 -89
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +240 -4
- package/dist/index.d.ts +240 -4
- package/dist/index.js +282 -10
- package/dist/index.js.map +1 -1
- package/dist/{session-QMS6OYG2.js → session-W73HJB5Q.js} +4 -4
- package/dist/undici-NSB7IUB7.js +5 -0
- package/package.json +2 -1
- package/src/index.ts +12 -0
- package/src/skill/bundled.ts +225 -0
- package/src/skill/skill.ts +260 -4
- package/src/tools/tool.ts +14 -4
- package/src/tools/tools/skill.ts +86 -8
- package/dist/chunk-4QYFQSAC.js.map +0 -1
- package/dist/history-AGNMX5YW.js +0 -8
- package/dist/undici-326ZBRKH.js +0 -5
- /package/dist/{chunk-DO76AL42.js.map → chunk-D5X6YFSK.js.map} +0 -0
- /package/dist/{chunk-OYWDQD3F.js.map → chunk-XBRIUBK5.js.map} +0 -0
- /package/dist/{history-AGNMX5YW.js.map → history-FS6CASR6.js.map} +0 -0
- /package/dist/{session-QMS6OYG2.js.map → session-W73HJB5Q.js.map} +0 -0
- /package/dist/{undici-326ZBRKH.js.map → undici-NSB7IUB7.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/history.ts","../src/core/query.ts","../src/core/loop.ts","../src/core/at.ts","../src/core/constants.ts","../src/utils/list.ts","../src/utils/ignore.ts","../src/utils/randomUUID.ts","../src/core/message.ts","../src/core/promptCache.ts","../src/core/usage.ts","../src/utils/safeParseJson.ts","../src/core/model/models.ts","../src/core/model/providers.ts","../src/utils/apiKeyRotation.ts","../src/core/model/utils.ts","../src/utils/proxy.ts","../src/core/model/proxy.ts","../src/core/model/aliases.ts","../src/core/model/resolution.ts","../src/core/config.ts","../src/core/configValidation.ts","../src/core/plugin.ts","../src/tools/tool.ts","../src/tools/tools/askUserQuestion.ts","../src/tools/tools/bash.ts","../src/utils/bash/constants.ts","../src/utils/bash/security.ts","../src/utils/background-detection.ts","../src/utils/error.ts","../src/utils/shell-execution.ts","../node_modules/ansi-regex/index.js","../node_modules/strip-ansi/index.js","../src/utils/system-encoding.ts","../src/utils/bash/output.ts","../src/tools/tools/edit.ts","../src/utils/applyEdit.ts","../src/tools/tools/fetch.ts","../src/utils/safeStringify.ts","../src/tools/tools/glob.ts","../src/tools/tools/grep.ts","../src/utils/ripgrep.ts","../src/utils/isLocal.ts","../src/tools/tools/ls.ts","../src/tools/tools/read.ts","../src/utils/pdf-parser.ts","../src/tools/tools/skill.ts","../src/tools/tools/task.ts","../src/tools/tools/todo.ts","../src/tools/tools/write.ts","../src/utils/messageNormalization.ts","../src/utils/language.ts","../src/core/compact.ts","../src/compression.ts","../src/utils/tokenCounter.ts"],"sourcesContent":["import type {\n LanguageModelV3Message,\n LanguageModelV3ToolResultPart,\n} from '@ai-sdk/provider';\nimport createDebug from 'debug';\nimport { COMPACT_MESSAGE, compact } from './compact';\nimport { MIN_TOKEN_THRESHOLD } from './constants';\nimport { Compression, type CompressionConfig, type PruneResult, isOverflow } from '../compression';\nimport type {\n Message,\n NormalizedMessage,\n ToolResultPart2,\n UserContent,\n} from '../core/message';\nimport type { ModelInfo } from '../core/model';\nimport { Usage } from '../core/usage';\nimport { randomUUID } from '../utils/randomUUID';\n\nexport type OnMessage = (message: NormalizedMessage) => Promise<void>;\nexport type HistoryOpts = {\n messages: NormalizedMessage[];\n onMessage?: OnMessage;\n compressionConfig?: CompressionConfig;\n};\n\nconst debug = createDebug('oricore:history');\n\nexport class History {\n messages: NormalizedMessage[];\n onMessage?: OnMessage;\n compressionConfig: CompressionConfig;\n constructor(opts: HistoryOpts) {\n this.messages = opts.messages || [];\n this.onMessage = opts.onMessage;\n this.compressionConfig = opts.compressionConfig || Compression.DEFAULT_CONFIG;\n }\n\n async addMessage(message: Message, uuid?: string): Promise<void> {\n const lastMessage = this.messages[this.messages.length - 1];\n const normalizedMessage: NormalizedMessage = {\n parentUuid: lastMessage?.uuid || null,\n uuid: uuid || randomUUID(),\n ...message,\n type: 'message',\n timestamp: new Date().toISOString(),\n };\n this.messages.push(normalizedMessage);\n await this.onMessage?.(normalizedMessage);\n }\n\n getMessagesToUuid(uuid: string): NormalizedMessage[] {\n // Build a map for O(1) lookups\n const messageMap = new Map<string, NormalizedMessage>();\n for (const message of this.messages) {\n messageMap.set(message.uuid, message);\n }\n\n // Find the target message\n const targetMessage = messageMap.get(uuid);\n if (!targetMessage) {\n // Target doesn't exist, return empty array\n return [];\n }\n\n // Walk backward from target to root\n const pathUuids = new Set<string>();\n let current: NormalizedMessage | undefined = targetMessage;\n while (current) {\n pathUuids.add(current.uuid);\n if (current.parentUuid === null) break;\n const parent = messageMap.get(current.parentUuid);\n if (!parent) break;\n current = parent;\n }\n\n // Filter messages to keep only those in the path, maintaining order\n return this.messages.filter((msg) => pathUuids.has(msg.uuid));\n }\n\n toLanguageV2Messages(): LanguageModelV3Message[] {\n return this.messages.map((message: NormalizedMessage) => {\n if (message.role === 'user') {\n const content = message.content as UserContent;\n if (typeof content === 'string') {\n return {\n role: 'user',\n content: [{ type: 'text', text: content }],\n } as LanguageModelV3Message;\n } else {\n const normalizedContent = content.map((part: any) => {\n if (part.type === 'text') {\n return { type: 'text', text: part.text };\n } else if (part.type === 'image') {\n const isBase64 = part.data.includes(';base64,');\n const data = isBase64\n ? part.data.split(';base64,')[1]\n : part.data;\n return {\n type: 'file',\n data,\n mediaType: part.mimeType,\n };\n } else if (part.type === 'tool_result') {\n // Compatible with old message format\n return part;\n } else {\n throw new Error(\n `Not implemented with type: ${part.type} of role: user`,\n );\n }\n });\n return {\n role: 'user',\n content: normalizedContent,\n } as LanguageModelV3Message;\n }\n } else if (message.role === 'assistant') {\n if (typeof message.content === 'string') {\n return {\n role: 'assistant',\n content: [{ type: 'text', text: message.content }],\n } as LanguageModelV3Message;\n } else {\n const normalizedContent = message.content.map((part: any) => {\n if (part.type === 'text') {\n return { type: 'text', text: part.text };\n } else if (part.type === 'reasoning') {\n return {\n type: 'reasoning',\n text: part.text,\n ...(part.providerMetadata && {\n providerMetadata: part.providerMetadata,\n }),\n };\n } else if (part.type === 'tool_use') {\n return {\n type: 'tool-call',\n toolCallId: part.id,\n toolName: part.name,\n input: part.input,\n ...(part.providerMetadata && {\n providerMetadata: part.providerMetadata,\n }),\n };\n } else {\n throw new Error(\n `Not implemented with type: ${part.type} of role: assistant`,\n );\n }\n });\n return {\n role: 'assistant',\n content: normalizedContent,\n } as LanguageModelV3Message;\n }\n } else if (message.role === 'system') {\n return {\n role: 'system',\n content: message.content,\n };\n } else if (message.role === 'tool') {\n return {\n role: 'tool',\n content: message.content.map((part: ToolResultPart2) => {\n const llmContent = part.result.llmContent;\n const output = (() => {\n if (typeof llmContent === 'string') {\n return { type: 'text', value: llmContent };\n } else if (Array.isArray(llmContent)) {\n return {\n type: 'content',\n value: llmContent.map((part) => {\n if (part.type === 'text') {\n return { type: 'text', value: part.text };\n } else if (part.type === 'image') {\n const isBase64 = part.data.includes(';base64,');\n const data = isBase64\n ? part.data.split(';base64,')[1]\n : part.data;\n return { type: 'media', data, mediaType: part.mimeType };\n } else {\n throw new Error(\n `Not implemented with type: ${(part as any).type} of role: tool`,\n );\n }\n }),\n };\n }\n })();\n return {\n type: 'tool-result',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output,\n };\n }) as LanguageModelV3ToolResultPart[],\n } as LanguageModelV3Message;\n } else {\n throw new Error(`Unsupported message role: ${message}.`);\n }\n });\n }\n\n #shouldCompress(model: ModelInfo, usage: Usage): boolean {\n if (usage.totalTokens < MIN_TOKEN_THRESHOLD) {\n return false;\n }\n\n const { context, output } = model.model.limit ?? { context: 0, output: 0 };\n\n // Use the new isOverflow function from compression module\n const result = isOverflow(\n {\n input: usage.totalTokens, // Total tokens used in last turn\n output: 0, // Not used by isOverflow (it only checks input param)\n cacheRead: 0, // Usage class doesn't track cache read tokens separately\n },\n { context, output },\n this.compressionConfig,\n );\n\n return result;\n }\n\n #getLastAssistantUsage(): Usage {\n let sessionStart = 0;\n let lastAssistantMessage: NormalizedMessage | null = null;\n\n // Single pass from end to beginning to find both session boundary and last assistant message\n for (let i = this.messages.length - 1; i >= 0; i--) {\n const message = this.messages[i];\n\n // Record the last assistant message we encounter\n if (message.role === 'assistant' && !lastAssistantMessage) {\n lastAssistantMessage = message;\n }\n\n // Find session boundary\n if (message.parentUuid === null) {\n sessionStart = i;\n break;\n }\n }\n\n // If we found an assistant message and it's within the current session\n if (lastAssistantMessage) {\n const assistantIndex = this.messages.indexOf(lastAssistantMessage);\n if (assistantIndex >= sessionStart) {\n return Usage.fromAssistantMessage(lastAssistantMessage);\n }\n }\n\n return Usage.empty();\n }\n\n async compress(model: ModelInfo, language?: string) {\n if (this.messages.length === 0) {\n return { compressed: false };\n }\n const usage = this.#getLastAssistantUsage();\n const shouldCompress = this.#shouldCompress(model, usage);\n if (!shouldCompress) {\n return { compressed: false };\n }\n\n // Step 1: Try Pruning first\n debug('[compress] Step 1: Attempting pruning...');\n const pruneResult = Compression.prune(\n this.messages,\n this.compressionConfig,\n );\n if (pruneResult.pruned) {\n debug(`[compress] Pruned ${pruneResult.prunedCount} tool outputs`);\n\n // Recalculate usage, check if Compaction is still needed\n const newUsage = this.#getLastAssistantUsage();\n const stillNeedsCompaction = this.#shouldCompress(model, newUsage);\n if (!stillNeedsCompaction) {\n debug('[compress] Pruning was sufficient, skipping compaction');\n return { compressed: false, pruned: true, pruneResult };\n }\n }\n\n // Step 2: Execute Compaction\n debug('[compress] Step 2: Executing compaction...');\n let summary: string | null = null;\n try {\n summary = await compact({\n messages: this.messages,\n model,\n language,\n });\n } catch (error) {\n debug('Compact failed:', error);\n\n // Graceful degradation: instead of throwing, use a simple summary\n const fallbackSummary = this.#generateFallbackSummary();\n debug('Using fallback summary due to compaction failure');\n\n const summaryMessage: NormalizedMessage = {\n parentUuid: null,\n uuid: randomUUID(),\n role: 'user',\n content: [{ type: 'text', text: fallbackSummary }],\n uiContent: COMPACT_MESSAGE,\n type: 'message',\n timestamp: new Date().toISOString(),\n };\n this.messages = [summaryMessage];\n await this.onMessage?.(summaryMessage);\n\n return {\n compressed: true,\n summary: fallbackSummary,\n fallback: true,\n error: error instanceof Error ? error.message : String(error),\n pruned: pruneResult.pruned,\n pruneResult,\n };\n }\n if (!summary || summary.trim().length === 0) {\n // If summary is empty, use fallback\n const fallbackSummary = this.#generateFallbackSummary();\n debug('Generated summary is empty, using fallback');\n\n const summaryMessage: NormalizedMessage = {\n parentUuid: null,\n uuid: randomUUID(),\n role: 'user',\n content: [{ type: 'text', text: fallbackSummary }],\n uiContent: COMPACT_MESSAGE,\n type: 'message',\n timestamp: new Date().toISOString(),\n };\n this.messages = [summaryMessage];\n await this.onMessage?.(summaryMessage);\n\n return {\n compressed: true,\n summary: fallbackSummary,\n fallback: true,\n pruned: pruneResult.pruned,\n pruneResult,\n };\n }\n\n const summaryMessage: NormalizedMessage = {\n parentUuid: null,\n uuid: randomUUID(),\n role: 'user',\n content: [{ type: 'text', text: summary }],\n uiContent: COMPACT_MESSAGE,\n type: 'message',\n timestamp: new Date().toISOString(),\n };\n this.messages = [summaryMessage];\n await this.onMessage?.(summaryMessage);\n debug('Generated summary:', summary);\n return {\n compressed: true,\n summary,\n fallback: false,\n pruned: pruneResult.pruned,\n pruneResult,\n };\n }\n\n /**\n * Generate a simple fallback summary when AI compression fails\n * This ensures the conversation can continue even if compression fails\n */\n #generateFallbackSummary(): string {\n const messageCount = this.messages.length;\n const lastUserMessage = [...this.messages]\n .reverse()\n .find((m) => m.role === 'user');\n\n const recentTools = new Set<string>();\n for (let i = this.messages.length - 1; i >= 0 && recentTools.size < 5; i--) {\n const msg = this.messages[i];\n if (msg.role === 'tool') {\n for (const part of msg.content as any[]) {\n if (part.type === 'tool-result') {\n recentTools.add(part.toolName);\n }\n }\n }\n }\n\n const sections: string[] = [];\n\n sections.push(`<conversation_overview>`);\n sections.push(\n `Previous conversation contained ${messageCount} messages. `,\n );\n if (lastUserMessage) {\n const content =\n typeof lastUserMessage.content === 'string'\n ? lastUserMessage.content\n : JSON.stringify(lastUserMessage.content);\n const preview =\n content.length > 100\n ? content.substring(0, 100) + '...'\n : content;\n sections.push(`Last user message was about: \"${preview}\"`);\n }\n sections.push(`</conversation_overview>`);\n\n if (recentTools.size > 0) {\n sections.push(`\\n<recent_actions>`);\n sections.push(`Recent tools used: ${Array.from(recentTools).join(', ')}`);\n sections.push(`</recent_actions>`);\n }\n\n sections.push(`\\n<note>`);\n sections.push(\n `This is an auto-generated summary due to compression unavailability. `,\n );\n sections.push(`The conversation history has been compressed to continue the session. `,\n );\n sections.push(`</note>`);\n\n return sections.join('\\n');\n }\n}\n","import assert from 'assert';\nimport type { Context } from '../core/context';\nimport { type ResponseFormat, runLoop, type ThinkingConfig } from '../core/loop';\nimport type { NormalizedMessage } from '../core/message';\nimport { type ModelInfo, resolveModelWithContext } from '../core/model';\nimport { Tools } from '../tools/tool';\nimport { randomUUID } from '../utils/randomUUID';\n\nexport async function query(opts: {\n userPrompt: string;\n messages?: NormalizedMessage[];\n context?: Context;\n model?: ModelInfo;\n systemPrompt?: string;\n onMessage?: (message: NormalizedMessage) => Promise<void>;\n thinking?: ThinkingConfig | false;\n responseFormat?: ResponseFormat;\n}) {\n const messages: NormalizedMessage[] = [\n ...(opts.messages || []),\n {\n role: 'user',\n content: opts.userPrompt,\n type: 'message',\n timestamp: new Date().toISOString(),\n uuid: randomUUID(),\n parentUuid: null,\n },\n ];\n assert(opts.model || opts.context, 'model or context is required');\n const model =\n opts.model || (await resolveModelWithContext(null, opts.context!)).model!;\n return await runLoop({\n input: messages,\n model,\n tools: new Tools([]),\n cwd: '',\n systemPrompt: opts.systemPrompt || '',\n onMessage: async (message) => {\n await opts.onMessage?.(message);\n },\n autoCompact: false,\n thinking: opts.thinking !== false ? opts.thinking : undefined,\n responseFormat: opts.responseFormat,\n });\n}\n","import type {\n LanguageModelV3,\n LanguageModelV3FunctionTool,\n LanguageModelV3Message,\n LanguageModelV3Prompt,\n SharedV3Headers,\n} from '@ai-sdk/provider';\nimport createDebug from 'debug';\nimport { At } from './at';\nimport { History, type OnMessage } from '../core/history';\nimport {\n type AssistantContent,\n createToolResultPart2,\n type NormalizedMessage,\n type ToolUsePart,\n} from '../core/message';\nimport type { ModelInfo } from '../core/model';\nimport { addPromptCache } from './promptCache';\nimport type {\n ToolApprovalResult,\n ToolParams,\n ToolResult,\n Tools,\n ToolUse,\n} from '../tools/tool';\nimport { Usage } from '../core/usage';\nimport { randomUUID } from '../utils/randomUUID';\nimport { safeParseJson } from '../utils/safeParseJson';\n\nconst DEFAULT_MAX_TURNS = 50;\nconst DEFAULT_ERROR_RETRY_TURNS = 10;\n\nconst debug = createDebug('oricore:loop');\n\nasync function exponentialBackoffWithCancellation(\n attempt: number,\n signal?: AbortSignal,\n): Promise<void> {\n const baseDelay = 1000;\n const delay = baseDelay * Math.pow(2, attempt - 1);\n const checkInterval = 100;\n\n const startTime = Date.now();\n while (Date.now() - startTime < delay) {\n if (signal?.aborted) {\n throw new Error('Cancelled during retry backoff');\n }\n await new Promise((resolve) =>\n setTimeout(\n resolve,\n Math.min(checkInterval, delay - (Date.now() - startTime)),\n ),\n );\n }\n}\n\nexport type LoopResult =\n | {\n success: true;\n data: Record<string, any>;\n metadata: {\n turnsCount: number;\n toolCallsCount: number;\n duration: number;\n };\n }\n | {\n success: false;\n error: {\n type: 'tool_denied' | 'max_turns_exceeded' | 'api_error' | 'canceled';\n message: string;\n details?: Record<string, any>;\n };\n };\n\ntype StreamResultBase = {\n requestId: string;\n prompt: LanguageModelV3Prompt;\n model: ModelInfo;\n tools: LanguageModelV3FunctionTool[];\n};\nexport type StreamResult = StreamResultBase & {\n request?: {\n body?: unknown;\n };\n response?: {\n headers?: SharedV3Headers;\n statusCode?: number;\n body?: unknown;\n };\n error?: any;\n};\n\nexport type ResponseFormat =\n | {\n type: 'text';\n }\n | {\n type: 'json';\n schema?: any;\n name?: string;\n description?: string;\n };\nexport type ReasoningEffort = 'low' | 'medium' | 'high' | 'max';\nexport type ThinkingConfig = {\n effort: ReasoningEffort;\n};\n\ntype RunLoopOpts = {\n input?: string | NormalizedMessage[];\n history?: History;\n model: ModelInfo;\n tools: Tools;\n cwd: string;\n systemPrompt?: string;\n maxTurns?: number;\n errorRetryTurns?: number;\n signal?: AbortSignal;\n llmsContexts?: string[];\n autoCompact?: boolean;\n language?: string;\n thinking?: ThinkingConfig;\n temperature?: number;\n responseFormat?: ResponseFormat;\n onTextDelta?: (text: string) => Promise<void>;\n onText?: (text: string) => Promise<void>;\n onReasoning?: (text: string) => Promise<void>;\n onStreamResult?: (result: StreamResult) => Promise<void>;\n onChunk?: (chunk: any, requestId: string) => Promise<void>;\n onToolUse?: (toolUse: ToolUse) => Promise<ToolUse>;\n onToolResult?: (\n toolUse: ToolUse,\n toolResult: ToolResult,\n approved: boolean,\n ) => Promise<ToolResult>;\n onTurn?: (turn: {\n usage: Usage;\n startTime: Date;\n endTime: Date;\n }) => Promise<void>;\n onToolApprove?: (toolUse: ToolUse) => Promise<ToolApprovalResult>;\n onMessage?: OnMessage;\n};\n\nexport async function runLoop(opts: RunLoopOpts): Promise<LoopResult> {\n const startTime = Date.now();\n let turnsCount = 0;\n let toolCallsCount = 0;\n let finalText = '';\n let lastUsage = Usage.empty();\n const totalUsage = Usage.empty();\n\n // Create or use history\n let history: History;\n if (opts.history) {\n // Use existing history (for session continuation)\n history = opts.history;\n // Set onMessage callback if not already set\n if (!history.onMessage && opts.onMessage) {\n history.onMessage = opts.onMessage;\n }\n // Add new input to history if provided\n if (opts.input !== undefined) {\n const lastMessage = history.messages[history.messages.length - 1];\n const parentUuid = lastMessage?.uuid || null;\n const inputMessages: NormalizedMessage[] = Array.isArray(opts.input)\n ? opts.input\n : [\n {\n role: 'user',\n content: opts.input,\n type: 'message',\n timestamp: new Date().toISOString(),\n uuid: randomUUID(),\n parentUuid,\n },\n ];\n for (const msg of inputMessages) {\n await history.addMessage(msg);\n }\n }\n } else if (opts.input !== undefined) {\n // Create new history from input (for single requests)\n history = new History({\n messages: [],\n onMessage: opts.onMessage,\n });\n const inputMessages: NormalizedMessage[] = Array.isArray(opts.input)\n ? opts.input\n : [\n {\n role: 'user',\n content: opts.input,\n type: 'message',\n timestamp: new Date().toISOString(),\n uuid: randomUUID(),\n parentUuid: null,\n },\n ];\n for (const msg of inputMessages) {\n await history.addMessage(msg);\n }\n } else {\n throw new Error('Either input or history must be provided to runLoop');\n }\n\n const maxTurns = opts.maxTurns ?? DEFAULT_MAX_TURNS;\n const abortController = new AbortController();\n\n // Listen to external signal and synchronize with internal abortController\n // This ensures that when session.cancel is triggered, the LLM request is immediately aborted\n const abortHandler = () => {\n if (!abortController.signal.aborted) {\n abortController.abort();\n }\n };\n if (opts.signal) {\n opts.signal.addEventListener('abort', abortHandler, { once: true });\n }\n\n // Cleanup function to remove event listener\n const cleanup = () => {\n if (opts.signal) {\n opts.signal.removeEventListener('abort', abortHandler);\n }\n };\n\n const createCancelError = (): LoopResult => ({\n success: false,\n error: {\n type: 'canceled',\n message: 'Operation was canceled',\n details: { turnsCount, history, usage: totalUsage },\n },\n });\n\n try {\n let shouldAtNormalize = true;\n let shouldThinking = true;\n while (true) {\n // Must use separate abortController to prevent ReadStream locking\n if (opts.signal?.aborted && !abortController.signal.aborted) {\n abortController.abort();\n return createCancelError();\n }\n\n const startTime = new Date();\n turnsCount++;\n\n if (turnsCount > maxTurns) {\n return {\n success: false,\n error: {\n type: 'max_turns_exceeded',\n message: `Maximum turns (${maxTurns}) exceeded`,\n details: {\n turnsCount,\n history,\n usage: totalUsage,\n },\n },\n };\n }\n if (opts.autoCompact) {\n const compressed = await history.compress(opts.model, opts.language);\n if (compressed.compressed) {\n debug('history compressed', compressed);\n }\n }\n lastUsage.reset();\n\n const systemPromptMessage = {\n role: 'system',\n content: opts.systemPrompt || '',\n } as LanguageModelV3Message;\n const llmsContexts = opts.llmsContexts || [];\n const llmsContextMessages = llmsContexts.map((llmsContext) => {\n return {\n role: 'system',\n content: llmsContext,\n } as LanguageModelV3Message;\n });\n let prompt: LanguageModelV3Prompt = [\n systemPromptMessage,\n ...llmsContextMessages,\n ...history.toLanguageV2Messages(),\n ];\n\n if (shouldAtNormalize) {\n // add file and directory contents for the last user prompt\n prompt = At.normalizeLanguageV2Prompt({\n input: prompt,\n cwd: opts.cwd,\n });\n shouldAtNormalize = false;\n }\n\n prompt = addPromptCache(prompt, opts.model);\n\n let text = '';\n let reasoning = '';\n const toolCalls: Array<{\n providerMetadata?: any;\n toolCallId: string;\n toolName: string;\n input: string;\n }> = [];\n\n const requestId = randomUUID();\n const m: LanguageModelV3 = await opts.model._mCreator();\n const tools = opts.tools.toLanguageV2Tools();\n\n // Get thinking config from model variants\n let thinkingConfig: Record<string, any> | undefined = undefined;\n if (shouldThinking && opts.thinking) {\n thinkingConfig = {\n providerOptions: {\n [opts.model.provider.id]:\n opts.model.model.variants?.[opts.thinking.effort],\n },\n };\n shouldThinking = false;\n }\n\n let retryCount = 0;\n const errorRetryTurns = opts.errorRetryTurns ?? DEFAULT_ERROR_RETRY_TURNS;\n let reasoningProviderMetadata: any | undefined = undefined;\n\n while (retryCount <= errorRetryTurns) {\n if (opts.signal?.aborted) {\n return createCancelError();\n }\n\n try {\n const result = await m.doStream({\n prompt: prompt,\n tools,\n toolChoice: { type: 'auto' },\n abortSignal: abortController.signal,\n ...thinkingConfig,\n ...(opts.temperature !== undefined && {\n temperature: opts.temperature,\n }),\n ...(opts.responseFormat !== undefined && {\n responseFormat: opts.responseFormat,\n }),\n });\n opts.onStreamResult?.({\n requestId,\n prompt,\n model: opts.model,\n tools,\n request: result.request,\n response: result.response,\n });\n\n let finishChunkReceived = false;\n for await (const chunk of result.stream) {\n if (opts.signal?.aborted) {\n return createCancelError();\n }\n await opts.onChunk?.(chunk, requestId);\n switch (chunk.type) {\n case 'text-delta': {\n const textDelta = chunk.delta;\n text += textDelta;\n await opts.onTextDelta?.(textDelta);\n break;\n }\n case 'reasoning-delta':\n reasoning += chunk.delta;\n break;\n case 'reasoning-end':\n if (chunk.providerMetadata) {\n reasoningProviderMetadata = chunk.providerMetadata;\n }\n break;\n case 'tool-call':\n toolCalls.push({\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n input: chunk.input,\n ...(chunk.providerMetadata && {\n providerMetadata: chunk.providerMetadata,\n }),\n });\n break;\n case 'finish':\n finishChunkReceived = true;\n lastUsage = Usage.fromEventUsage(chunk.usage);\n totalUsage.add(lastUsage);\n if (toolCalls.length === 0 && text.trim() === '') {\n const error = new Error(\n 'Empty response: no text or tool calls received',\n );\n (error as any).isRetryable = true;\n throw error;\n }\n break;\n case 'error': {\n const message = (() => {\n if ((chunk as any).error.message) {\n return (chunk as any).error.message;\n }\n try {\n const message = JSON.parse(\n (chunk as any).error.value?.details,\n )?.error?.message;\n if (message) {\n return message;\n }\n } catch (_e) {}\n return JSON.stringify(chunk.error);\n })();\n const error = new Error(message);\n (error as any).isRetryable = false;\n const value = (chunk.error as any).value;\n if (value) {\n (error as any).statusCode = value?.status;\n }\n throw error;\n }\n default:\n break;\n }\n }\n\n // Check if stream ended without receiving finish chunk and no content\n if (\n !finishChunkReceived &&\n toolCalls.length === 0 &&\n text.trim() === ''\n ) {\n const error = new Error(\n 'Empty response: stream ended without any chunks',\n );\n (error as any).isRetryable = true;\n throw error;\n }\n\n break;\n } catch (error: any) {\n const nextRetryCount = retryCount + 1;\n const retryDelayMs = 1000 * Math.pow(2, nextRetryCount - 1);\n const retryStartTime = Date.now();\n opts.onStreamResult?.({\n requestId,\n prompt,\n model: opts.model,\n tools,\n response: {\n statusCode: error.statusCode,\n headers: error.responseHeaders,\n body: error.responseBody,\n },\n error: {\n data: error.data || error.message,\n isRetryable: error.isRetryable,\n retryAttempt: retryCount,\n maxRetries: errorRetryTurns,\n retryDelayMs,\n retryStartTime,\n },\n });\n\n if (error.isRetryable && retryCount < errorRetryTurns) {\n retryCount++;\n try {\n await exponentialBackoffWithCancellation(retryCount, opts.signal);\n } catch {\n return createCancelError();\n }\n continue;\n }\n\n let parsedResponseBody: {\n error?: { message?: string; metadata?: Record<string, unknown> };\n } | null = null;\n if (typeof error.responseBody === 'string') {\n try {\n parsedResponseBody = JSON.parse(error.responseBody);\n } catch {}\n }\n return {\n success: false,\n error: {\n type: 'api_error',\n message:\n parsedResponseBody?.error?.message ??\n (error instanceof Error\n ? error.message\n : 'Unknown streaming error'),\n details: {\n code: error.data?.error?.code,\n status: error.data?.error?.status,\n url: error.url,\n error,\n stack: error.stack,\n retriesAttempted: retryCount,\n ...(parsedResponseBody?.error?.metadata && {\n metadata: parsedResponseBody.error.metadata,\n }),\n },\n },\n };\n }\n }\n\n // Exit early if cancellation signal is received\n if (opts.signal?.aborted) {\n return createCancelError();\n }\n\n await opts.onText?.(text);\n\n // some model may return multiple \\n in the end of the reasoning\n // e.g. antigravity/gemini-3-pro-high\n if (reasoning) {\n reasoning = reasoning.trim();\n }\n\n if (reasoning) {\n await opts.onReasoning?.(reasoning);\n }\n\n const endTime = new Date();\n opts.onTurn?.({\n usage: lastUsage,\n startTime,\n endTime,\n });\n const model = `${opts.model.provider.id}/${opts.model.model.id}`;\n const assistantContent: AssistantContent = [];\n if (reasoning) {\n assistantContent.push({\n type: 'reasoning',\n text: reasoning,\n ...(reasoningProviderMetadata && {\n providerMetadata: reasoningProviderMetadata,\n }),\n });\n }\n if (text) {\n finalText = text;\n assistantContent.push({\n type: 'text',\n text: text,\n });\n }\n for (const toolCall of toolCalls) {\n const tool = opts.tools.get(toolCall.toolName);\n // compatible with models that may return an empty value instead of a JSON string for input\n const input = safeParseJson(toolCall.input);\n const description = tool?.getDescription?.({\n params: input,\n cwd: opts.cwd,\n });\n const displayName = tool?.displayName;\n const toolUse: ToolUsePart = {\n type: 'tool_use',\n id: toolCall.toolCallId,\n name: toolCall.toolName,\n input: input,\n };\n if (description) {\n toolUse.description = description;\n }\n if (displayName) {\n toolUse.displayName = displayName;\n }\n if (toolCall.providerMetadata) {\n // @ts-ignore\n toolUse.providerMetadata = toolCall.providerMetadata;\n }\n assistantContent.push(toolUse);\n }\n await history.addMessage(\n {\n role: 'assistant',\n content: assistantContent,\n text,\n model,\n usage: {\n input_tokens: lastUsage.promptTokens,\n output_tokens: lastUsage.completionTokens,\n },\n },\n requestId,\n );\n if (!toolCalls.length) {\n break;\n }\n\n const toolResults: {\n toolCallId: string;\n toolName: string;\n input: Record<string, any>;\n result: ToolResult;\n }[] = [];\n\n // Helper function to add denied results for unprocessed tools\n const addDeniedResultsForRemainingTools = async () => {\n const processedToolCallIds = new Set(\n toolResults.map((tr) => tr.toolCallId),\n );\n for (const remainingToolCall of toolCalls) {\n if (!processedToolCallIds.has(remainingToolCall.toolCallId)) {\n const remainingToolUse: ToolUse = {\n name: remainingToolCall.toolName,\n params: safeParseJson(remainingToolCall.input),\n callId: remainingToolCall.toolCallId,\n };\n let remainingToolResult: ToolResult = {\n llmContent:\n 'Error: Tool execution was skipped due to previous tool denial.',\n isError: true,\n };\n if (opts.onToolResult) {\n remainingToolResult = await opts.onToolResult(\n remainingToolUse,\n remainingToolResult,\n false,\n );\n }\n toolResults.push({\n toolCallId: remainingToolCall.toolCallId,\n toolName: remainingToolCall.toolName,\n input: safeParseJson(remainingToolCall.input),\n result: remainingToolResult,\n });\n }\n }\n };\n\n const approvedToolUses: ToolUse[] = [];\n let earlyReturn: LoopResult | null = null;\n\n for (const toolCall of toolCalls) {\n let toolUse: ToolUse = {\n name: toolCall.toolName,\n params: safeParseJson(toolCall.input),\n callId: toolCall.toolCallId,\n };\n if (opts.onToolUse) {\n toolUse = await opts.onToolUse(toolUse as ToolUse);\n }\n let approved = true;\n let updatedParams: ToolParams | undefined = undefined;\n let denyReason: string | undefined = undefined;\n\n if (opts.onToolApprove) {\n const approvalResult = await opts.onToolApprove(toolUse as ToolUse);\n if (typeof approvalResult === 'object') {\n approved = approvalResult.approved;\n updatedParams = approvalResult.params;\n denyReason = approvalResult.denyReason;\n } else {\n approved = approvalResult;\n }\n }\n\n if (approved) {\n if (updatedParams) {\n toolUse.params = { ...toolUse.params, ...updatedParams };\n }\n approvedToolUses.push(toolUse);\n } else {\n let message = 'Error: Tool execution was denied by user.';\n if (denyReason) {\n message = `Tool use rejected with user message: ${denyReason}`;\n }\n let toolResult: ToolResult = {\n llmContent: message,\n isError: true,\n };\n if (opts.onToolResult) {\n toolResult = await opts.onToolResult(toolUse, toolResult, false);\n }\n toolResults.push({\n toolCallId: toolUse.callId,\n toolName: toolUse.name,\n input: toolUse.params,\n result: toolResult,\n });\n\n if (!denyReason) {\n await addDeniedResultsForRemainingTools();\n await history.addMessage({\n role: 'tool',\n content: toolResults.map((tr) =>\n createToolResultPart2(\n tr.toolCallId,\n tr.toolName,\n tr.input,\n tr.result,\n ),\n ),\n });\n earlyReturn = {\n success: false,\n error: {\n type: 'tool_denied',\n message,\n details: {\n toolUse,\n history,\n usage: totalUsage,\n },\n },\n };\n break;\n }\n await addDeniedResultsForRemainingTools();\n break;\n }\n }\n\n if (earlyReturn) {\n return earlyReturn;\n }\n\n // Execute approved tools in parallel\n if (approvedToolUses.length > 0) {\n const executionResults = await Promise.allSettled(\n approvedToolUses.map(async (toolUse) => {\n let toolResult = await opts.tools.invoke(\n toolUse.name,\n JSON.stringify(toolUse.params),\n toolUse.callId,\n );\n if (opts.onToolResult) {\n toolResult = await opts.onToolResult(toolUse, toolResult, true);\n }\n return {\n toolCallId: toolUse.callId,\n toolName: toolUse.name,\n input: toolUse.params,\n result: toolResult,\n };\n }),\n );\n\n toolCallsCount += approvedToolUses.length;\n turnsCount -= approvedToolUses.length;\n\n for (let i = 0; i < executionResults.length; i++) {\n const settledResult = executionResults[i];\n if (settledResult.status === 'fulfilled') {\n toolResults.push(settledResult.value);\n } else {\n const failedToolUse = approvedToolUses[i];\n let errorResult: ToolResult = {\n llmContent: `Tool execution error: ${settledResult.reason instanceof Error ? settledResult.reason.message : String(settledResult.reason)}`,\n isError: true,\n };\n if (opts.onToolResult) {\n errorResult = await opts.onToolResult(\n failedToolUse,\n errorResult,\n true,\n );\n }\n toolResults.push({\n toolCallId: failedToolUse.callId,\n toolName: failedToolUse.name,\n input: failedToolUse.params,\n result: errorResult,\n });\n }\n }\n }\n\n // Check for cancellation before adding tool results\n // session.cancel already handles adding tool results for incomplete tools\n if (opts.signal?.aborted) {\n return createCancelError();\n }\n\n if (toolResults.length) {\n await history.addMessage({\n role: 'tool',\n content: toolResults.map((tr) =>\n createToolResultPart2(\n tr.toolCallId,\n tr.toolName,\n tr.input,\n tr.result,\n ),\n ),\n });\n }\n }\n } finally {\n // Cleanup: remove event listener to prevent memory leaks\n cleanup();\n }\n\n const duration = Date.now() - startTime;\n return {\n success: true,\n data: {\n text: finalText,\n history,\n usage: totalUsage,\n },\n metadata: {\n turnsCount,\n toolCallsCount,\n duration,\n },\n };\n}\n","import type { LanguageModelV3Prompt } from '@ai-sdk/provider';\nimport fs from 'fs';\nimport path from 'pathe';\nimport { IMAGE_EXTENSIONS } from './constants';\nimport { createFileTree, listDirectory, printTree } from '../utils/list';\n\nconst MAX_LINE_LENGTH_TEXT_FILE = 2000;\nconst MAX_LINES_TO_READ = 2000;\nconst MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB\n\ninterface AtPath {\n path: string;\n lineRange?: {\n start: number; // 起始行号(包含)\n end?: number; // 结束行号(包含),undefined 表示只读取单行\n };\n}\n\nexport class At {\n private userPrompt: string;\n private cwd: string;\n constructor(opts: { userPrompt: string; cwd: string }) {\n this.userPrompt = opts.userPrompt;\n this.cwd = opts.cwd;\n }\n\n getContent() {\n const prompt = this.userPrompt || '';\n const ats = this.extractAtPaths(prompt);\n const fileEntries: Array<{\n filePath: string;\n lineRange?: { start: number; end?: number };\n }> = [];\n const directories: string[] = [];\n\n // Step 1: Classify files vs directories\n for (const at of ats) {\n const filePath = path.resolve(this.cwd, at.path);\n if (fs.existsSync(filePath)) {\n if (fs.statSync(filePath).isFile()) {\n fileEntries.push({ filePath, lineRange: at.lineRange });\n } else if (fs.statSync(filePath).isDirectory()) {\n directories.push(filePath);\n const dirFiles = this.getAllFilesInDirectory(filePath);\n // For directories, don't apply line ranges\n for (const dirFile of dirFiles) {\n fileEntries.push({ filePath: dirFile });\n }\n } else {\n throw new Error(`${filePath} is not a file or directory`);\n }\n }\n }\n\n // Step 2: Process separately and merge\n let result = '';\n if (fileEntries.length > 0) {\n result += this.renderFilesToXml(fileEntries);\n }\n if (directories.length > 0) {\n result += this.renderDirectoriesToTree(directories);\n }\n\n return result || null;\n }\n\n private extractAtPaths(prompt: string): AtPath[] {\n const pathsMap = new Map<string, AtPath>();\n // Match @path or @\"path\" optionally followed by :lineRange\n // The unquoted group should not match ':' to allow line range parsing\n const regex =\n /@(\"(?<quoted>[^\"]+)\"|(?<unquoted>(?:[^\\\\ :]|\\\\ )+))(?::(?<lineRange>\\d+(?:-\\d+)?))?/g;\n let match: RegExpExecArray | null = regex.exec(prompt);\n while (match !== null) {\n const groups = match.groups;\n if (!groups) {\n match = regex.exec(prompt);\n continue;\n }\n\n let filePath = groups.quoted || groups.unquoted;\n // Unescape spaces for unquoted paths\n if (groups.unquoted) {\n filePath = filePath.replace(/\\\\ /g, ' ');\n }\n\n // Parse line range if present\n let lineRange: { start: number; end?: number } | undefined;\n if (groups.lineRange) {\n const rangeMatch = groups.lineRange.match(/^(\\d+)(?:-(\\d+))?$/);\n if (rangeMatch) {\n const start = Number.parseInt(rangeMatch[1], 10);\n const end = rangeMatch[2]\n ? Number.parseInt(rangeMatch[2], 10)\n : start;\n lineRange = { start, end };\n }\n }\n\n // Create unique key based on path and line range\n const key = `${filePath}:${lineRange ? `${lineRange.start}-${lineRange.end}` : 'all'}`;\n if (!pathsMap.has(key)) {\n pathsMap.set(key, { path: filePath, lineRange });\n }\n\n match = regex.exec(prompt);\n }\n return Array.from(pathsMap.values());\n }\n\n private renderDirectoriesToTree(directories: string[]): string {\n let treeOutput = '';\n\n for (const dir of directories) {\n try {\n // Get file list using existing utility\n const fileList = listDirectory(dir, this.cwd).sort();\n\n // Handle empty directories\n if (fileList.length === 0) {\n treeOutput += `\\n<directory_structure path=\"${path.relative(this.cwd, dir)}\">\\n(Empty directory)\\n</directory_structure>`;\n continue;\n }\n\n // Build and format tree\n const tree = createFileTree(fileList);\n const treeString = printTree(dir, tree);\n\n treeOutput += `\\n<directory_structure path=\"${path.relative(this.cwd, dir)}\">\\n<!-- This is a directory listing. Content is not included. -->\\n${treeString}\\n</directory_structure>`;\n } catch (error) {\n // Handle permission errors gracefully\n treeOutput += `\\n<directory_structure path=\"${path.relative(this.cwd, dir)}\">\\nError: Unable to read directory\\n</directory_structure>`;\n }\n }\n\n return treeOutput;\n }\n\n renderFilesToXml(\n fileEntries: Array<{\n filePath: string;\n lineRange?: { start: number; end?: number };\n }>,\n ): string {\n const processedFiles = fileEntries\n .filter(\n (entry) =>\n !IMAGE_EXTENSIONS.has(path.extname(entry.filePath).toLowerCase()),\n )\n .map((entry) => {\n // Single file size limit cannot exceed 10MB\n const stat = fs.statSync(entry.filePath);\n if (stat.size > MAX_FILE_SIZE) {\n return {\n content: '// File too large to display',\n metadata: `File size: ${Math.round(stat.size / 1024 / 1024)}MB (skipped)`,\n file: entry.filePath,\n };\n }\n const content = fs.readFileSync(entry.filePath, 'utf-8');\n if (content === undefined || content === null) {\n throw new Error(`Failed to read file: ${entry.filePath}`);\n }\n const result = this.processFileContent(content, entry.lineRange);\n return {\n content: result.content,\n metadata: result.metadata,\n file: entry.filePath,\n };\n });\n\n const fileContents = processedFiles\n .map(\n (result) =>\n `\n <file>\n <path>${path.relative(this.cwd, result.file)}</path>\n <metadata>${result.metadata}</metadata>\n <content><![CDATA[${result.content}]]></content>\n </file>`,\n )\n .join('');\n\n return `<files>This section contains the contents of the repository's files.\\n${fileContents}\\n</files>`;\n }\n\n getAllFilesInDirectory(dirPath: string): string[] {\n const files: string[] = [];\n const traverse = (currentPath: string) => {\n try {\n const items = fs.readdirSync(currentPath);\n for (const item of items) {\n const itemPath = path.join(currentPath, item);\n const stat = fs.statSync(itemPath);\n if (stat.isFile()) {\n files.push(itemPath);\n } else if (stat.isDirectory()) {\n // Skip hidden directories and common ignore patterns\n if (\n !item.startsWith('.') &&\n !['node_modules', 'dist', 'build'].includes(item)\n ) {\n traverse(itemPath);\n }\n }\n }\n } catch {\n // Skip directories that can't be read\n console.warn(`Warning: Could not read directory ${currentPath}`);\n }\n };\n traverse(dirPath);\n return files;\n }\n\n private truncateLine(line: string): string {\n if (line.length <= MAX_LINE_LENGTH_TEXT_FILE) {\n return line;\n }\n return line.substring(0, MAX_LINE_LENGTH_TEXT_FILE) + '... [truncated]';\n }\n\n private processFileContent(\n content: string,\n lineRange?: { start: number; end?: number },\n ): {\n content: string;\n metadata: string;\n } {\n const allLines = content.split(/\\r?\\n/);\n const totalLines = allLines.length;\n\n // Handle line range if specified\n if (lineRange) {\n const { start, end } = lineRange;\n\n // Validate line numbers\n if (start < 1 || (end !== undefined && end < start)) {\n return {\n content: '',\n metadata: 'Invalid line range',\n };\n }\n\n // Convert to 0-based indexing and clamp to file bounds\n const startIdx = Math.max(0, start - 1);\n const endIdx = Math.min(totalLines, end ?? start);\n\n // Extract the specified lines\n const selectedLines = allLines.slice(startIdx, endIdx);\n\n // Truncate long lines\n const processedLines = selectedLines.map((line) =>\n this.truncateLine(line),\n );\n\n const actualStart = startIdx + 1;\n const actualEnd = endIdx;\n const displayRange =\n actualStart === actualEnd\n ? `Line ${actualStart}`\n : `Lines ${actualStart}-${actualEnd}`;\n\n return {\n content: processedLines.join('\\n'),\n metadata: `${displayRange} of ${totalLines} total lines`,\n };\n }\n\n // If file doesn't exceed limit, process all lines\n if (totalLines <= MAX_LINES_TO_READ) {\n const processedLines = allLines.map((line) => this.truncateLine(line));\n return {\n content: processedLines.join('\\n'),\n metadata: `Complete file (${totalLines} lines)`,\n };\n }\n\n // If file exceeds limit, only read first MAX_LINES_TO_READ lines\n const selectedLines = allLines.slice(0, MAX_LINES_TO_READ);\n const truncatedLines = selectedLines.map((line) => this.truncateLine(line));\n\n return {\n content: truncatedLines.join('\\n'),\n metadata: `Showing first ${MAX_LINES_TO_READ} lines of ${totalLines} total lines`,\n };\n }\n\n static normalizeLanguageV2Prompt(opts: {\n input: LanguageModelV3Prompt;\n cwd: string;\n }): LanguageModelV3Prompt {\n const lastUserMessage = [...opts.input].reverse().find((item) => {\n return 'role' in item && item.role === 'user';\n });\n if (!lastUserMessage) {\n return opts.input;\n }\n const content = lastUserMessage.content;\n for (const item of content) {\n if (item.type === 'text') {\n const userPrompt = item.text;\n const at = new At({\n userPrompt,\n cwd: opts.cwd,\n });\n const content = at.getContent();\n if (content) {\n item.text += `\\n\\n${content}`;\n }\n }\n }\n return opts.input;\n }\n}\n","export const PRODUCT_NAME = 'OriCore';\nexport const PRODUCT_ASCII_ART = `\n█▀█ █▀▄ █ █▀▀ █▀█ █▀▄ █▀▀\n█▄█ █▀▄ █ █▄▄ █▄█ █▀▄ ██▄\n`.trim();\nexport const DEFAULT_OUTPUT_STYLE_NAME = 'Default';\nexport const IMAGE_EXTENSIONS = new Set([\n '.png',\n '.jpg',\n '.jpeg',\n '.gif',\n '.webp',\n]);\n\nexport const BINARY_EXTENSIONS = new Set([\n // Executables\n '.exe',\n '.dll',\n '.so',\n '.dylib',\n '.bin',\n '.class',\n '.o',\n '.obj',\n // Archives\n '.zip',\n '.tar',\n '.gz',\n '.rar',\n '.7z',\n '.jar',\n '.war',\n // Database\n '.db',\n '.sqlite',\n '.sqlite3',\n '.parquet',\n '.h5',\n // Media (Non-image)\n '.mp3',\n '.mp4',\n '.wav',\n '.avi',\n '.mov',\n '.mkv',\n // System\n '.ds_store',\n 'thumbs.db',\n]);\nexport const CANCELED_MESSAGE_TEXT = '[Request interrupted by user]';\n\nexport enum TOOL_NAMES {\n TODO_WRITE = 'todoWrite',\n BASH = 'bash',\n BASH_OUTPUT = 'bash_output',\n KILL_BASH = 'kill_bash',\n GREP = 'grep',\n ASK_USER_QUESTION = 'AskUserQuestion',\n READ = 'read',\n GLOB = 'glob',\n WRITE = 'write',\n EDIT = 'edit',\n LS = 'ls',\n TASK = 'task',\n SKILL = 'skill',\n}\n\nexport const BASH_EVENTS = {\n PROMPT_BACKGROUND: 'bash:prompt_background',\n MOVE_TO_BACKGROUND: 'bash:move_to_background',\n BACKGROUND_MOVED: 'bash:background_moved',\n} as const;\n\n// ============================================\n// Compression Constants\n// ============================================\n\n// Compaction configuration\nexport const COMPACTION_OUTPUT_TOKEN_MAX = 8_192; // Reserved output tokens for compression\nexport const COMPACTION_TRIGGER_RATIO = 0.7; // Trigger compression when context usage exceeds 70%\n\n// Pruning configuration\nexport const PRUNE_PROTECT_THRESHOLD = 40_000; // Protect threshold: recent 40k tokens not pruned\nexport const PRUNE_MINIMUM = 20_000; // Minimum prune amount: skip if below this\nexport const PRUNE_PROTECT_TURNS = 2; // Protect recent 2 conversation turns\n// Protected tools list (avoid losing main context information when pruning)\nexport const PRUNE_PROTECTED_TOOLS = [TOOL_NAMES.SKILL, TOOL_NAMES.TASK];\n\n// Truncation configuration\nexport const TRUNCATE_MAX_LINES = 2000; // Maximum lines\nexport const TRUNCATE_MAX_BYTES = 50 * 1024; // Maximum bytes (50KB)\n\n// Reserve 20% buffer for small models\nexport const MIN_TOKEN_THRESHOLD = 32_000 * 0.8;\n\nexport const BACKGROUND_THRESHOLD_MS = 2000;\n\nexport enum AGENT_TYPE {\n EXPLORE = 'Explore',\n PLAN = 'Plan',\n GENERAL_PURPOSE = 'GeneralPurpose',\n}\n","import createDebug from 'debug';\nimport fs from 'fs';\nimport { basename, join, relative, sep } from 'pathe';\nimport { isIgnored } from './ignore';\nexport const MAX_FILES = 1000;\nexport const TRUNCATED_MESSAGE = `There are more than ${MAX_FILES} files in the repository. Use the LS tool (passing a specific path), Bash tool, and other tools to explore nested directories. The first ${MAX_FILES} files and directories are included below:\\n\\n`;\n\nconst debug = createDebug('oricore:utils:list');\n\n// List of product names to check for ignore files\nconst PRODUCT_NAMES = ['oricore', 'takumi', 'kwaipilot'];\n\nexport function listDirectory(\n initialPath: string,\n cwd: string,\n maxFiles: number = MAX_FILES,\n) {\n const results: string[] = [];\n const queue = [initialPath];\n while (queue.length > 0) {\n if (results.length > maxFiles) {\n return results;\n }\n const path = queue.shift()!;\n if (skip(path)) {\n continue;\n }\n if (path !== initialPath) {\n results.push(relative(cwd, path) + sep);\n }\n let children: fs.Dirent[];\n try {\n children = fs.readdirSync(path, { withFileTypes: true });\n } catch (e) {\n // eg. EPERM, EACCES, ENOENT, etc.\n // Silently skip directories we don't have permission to read\n debug(`[LsTool] Error listing directory: ${path}`, e);\n continue;\n }\n for (const child of children) {\n if (child.name === 'node_modules') {\n continue;\n }\n\n const childPath = join(path, child.name);\n\n // Skip if ignored by any of the product-specific ignore files\n if (isIgnored(childPath, cwd, PRODUCT_NAMES)) {\n continue;\n }\n\n if (child.isDirectory()) {\n queue.push(childPath + sep);\n } else {\n if (skip(childPath)) {\n continue;\n }\n results.push(relative(cwd, childPath));\n if (results.length > maxFiles) {\n return results;\n }\n }\n }\n }\n return results;\n}\n\nconst SKIP_DOT_FILES = new Set([\n '.git',\n '.env',\n '.vscode',\n '.idea',\n '.bashrc',\n '.bash_profile',\n '.zshrc',\n '.zprofile',\n '.profile',\n '.DS_Store',\n '.localized',\n 'Thumbs.db',\n 'desktop.ini',\n]);\n\nfunction skip(path: string) {\n const name = basename(path);\n if (path !== '.' && SKIP_DOT_FILES.has(name)) {\n return true;\n }\n return false;\n}\n\nexport function listRootDirectory(rootPath: string): string[] {\n const results: string[] = [];\n try {\n const children = fs.readdirSync(rootPath, { withFileTypes: true });\n for (const child of children) {\n if (child.name === 'node_modules' || child.name.startsWith('.')) {\n continue;\n }\n\n const childPath = join(rootPath, child.name);\n\n // Skip if ignored by any of the product-specific ignore files\n if (isIgnored(childPath, rootPath, PRODUCT_NAMES)) {\n continue;\n }\n\n if (child.isDirectory()) {\n results.push(child.name + sep);\n } else {\n results.push(child.name);\n }\n }\n } catch (e) {\n // Silently skip root directories we don't have permission to read\n }\n return results;\n}\n\ntype TreeNode = {\n name: string;\n path: string;\n type: 'file' | 'directory';\n children?: TreeNode[];\n};\n\nexport function createFileTree(sortedPaths: string[]): TreeNode[] {\n const root: TreeNode[] = [];\n\n for (const path of sortedPaths) {\n const parts = path.split(sep);\n let currentLevel = root;\n let currentPath = '';\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i]!;\n if (!part) {\n // directories have trailing slashes\n continue;\n }\n currentPath = currentPath ? `${currentPath}${sep}${part}` : part;\n const isLastPart = i === parts.length - 1;\n\n const existingNode = currentLevel.find((node) => node.name === part);\n\n if (existingNode) {\n currentLevel = existingNode.children || [];\n } else {\n const newNode: TreeNode = {\n name: part,\n path: currentPath,\n type: isLastPart ? 'file' : 'directory',\n };\n\n if (!isLastPart) {\n newNode.children = [];\n }\n\n currentLevel.push(newNode);\n currentLevel = newNode.children || [];\n }\n }\n }\n\n return root;\n}\n\n/**\n * eg.\n * - src/\n * - index.ts\n * - utils/\n * - file.ts\n */\nexport function printTree(\n cwd: string,\n tree: TreeNode[],\n level = 0,\n prefix = '',\n): string {\n let result = '';\n\n // Add absolute path at root level\n if (level === 0) {\n result += `- ${cwd}${sep}\\n`;\n prefix = ' ';\n }\n\n for (const node of tree) {\n // Add the current node to the result\n result += `${prefix}${'-'} ${node.name}${node.type === 'directory' ? sep : ''}\\n`;\n\n // Recursively print children if they exist\n if (node.children && node.children.length > 0) {\n result += printTree(cwd, node.children, level + 1, `${prefix} `);\n }\n }\n\n return result;\n}\n","import fs from 'fs';\nimport { homedir } from 'os';\nimport { join, relative, sep } from 'pathe';\n\n/**\n * Gets the global gitignore file path\n */\nfunction getGlobalGitignorePath(): string | null {\n // Check common default locations\n const commonPaths = [\n join(homedir(), '.gitignore_global'),\n join(homedir(), '.config', 'git', 'ignore'),\n join(homedir(), '.gitignore'),\n ];\n\n for (const path of commonPaths) {\n try {\n if (fs.existsSync(path)) {\n return path;\n }\n } catch (_e) {\n // Continue to next path\n }\n }\n\n return null;\n}\n\n/**\n * Gets the repository-specific exclude file path\n */\nfunction getRepoExcludePath(rootPath: string): string {\n return join(rootPath, '.git', 'info', 'exclude');\n}\n\nfunction parseIgnoreFiles(\n rootPath: string,\n productNames: string[],\n): {\n patterns: string[];\n negationPatterns: string[];\n} {\n const gitignorePath = join(rootPath, '.gitignore');\n const globalGitignorePath = getGlobalGitignorePath();\n const repoExcludePath = getRepoExcludePath(rootPath);\n\n const patterns: string[] = [];\n const negationPatterns: string[] = [];\n\n // Parse global gitignore first (lowest precedence)\n if (globalGitignorePath) {\n try {\n const globalContent = fs.readFileSync(globalGitignorePath, 'utf8');\n const {\n patterns: globalPatterns,\n negationPatterns: globalNegationPatterns,\n } = parseIgnoreContent(globalContent);\n patterns.push(...globalPatterns);\n negationPatterns.push(...globalNegationPatterns);\n } catch (_e) {\n // Global gitignore doesn't exist or can't be read\n }\n }\n\n // Parse .git/info/exclude second\n try {\n const repoExcludeContent = fs.readFileSync(repoExcludePath, 'utf8');\n const {\n patterns: excludePatterns,\n negationPatterns: excludeNegationPatterns,\n } = parseIgnoreContent(repoExcludeContent);\n patterns.push(...excludePatterns);\n negationPatterns.push(...excludeNegationPatterns);\n } catch (_e) {\n // .git/info/exclude doesn't exist or can't be read\n }\n\n // Parse .gitignore third\n try {\n const gitignoreContent = fs.readFileSync(gitignorePath, 'utf8');\n const { patterns: gitPatterns, negationPatterns: gitNegationPatterns } =\n parseIgnoreContent(gitignoreContent);\n patterns.push(...gitPatterns);\n negationPatterns.push(...gitNegationPatterns);\n } catch (_e) {\n // .gitignore doesn't exist or can't be read\n }\n\n // Parse all product-specific ignore files (highest precedence)\n for (const productName of productNames) {\n const productIgnorePath = join(\n rootPath,\n `.${productName.toLowerCase()}ignore`,\n );\n try {\n const productIgnoreContent = fs.readFileSync(productIgnorePath, 'utf8');\n const {\n patterns: productPatterns,\n negationPatterns: productNegationPatterns,\n } = parseIgnoreContent(productIgnoreContent);\n patterns.push(...productPatterns);\n negationPatterns.push(...productNegationPatterns);\n } catch (_e) {\n // Product-specific ignore file doesn't exist or can't be read\n }\n }\n\n return { patterns, negationPatterns };\n}\n\n/**\n * Parses ignore file content and returns patterns\n */\nfunction parseIgnoreContent(content: string): {\n patterns: string[];\n negationPatterns: string[];\n} {\n const lines = content.split('\\n');\n const patterns: string[] = [];\n const negationPatterns: string[] = [];\n\n for (const line of lines) {\n const trimmed = line.trim();\n\n // Skip empty lines and comments\n if (!trimmed || trimmed.startsWith('#')) {\n continue;\n }\n\n // Handle negation patterns (starting with !)\n if (trimmed.startsWith('!')) {\n const pattern = trimmed.slice(1);\n negationPatterns.push(normalizePattern(pattern));\n continue;\n }\n\n patterns.push(normalizePattern(trimmed));\n }\n\n return { patterns, negationPatterns };\n}\n\n/**\n * Normalizes ignore patterns for simple pattern matching\n */\nfunction normalizePattern(pattern: string): string {\n let normalized = pattern;\n\n // Handle leading slash (root-relative patterns)\n if (normalized.startsWith('/')) {\n normalized = normalized.slice(1);\n }\n\n // Handle trailing slash (directory-only patterns)\n if (normalized.endsWith('/')) {\n normalized = normalized.slice(0, -1);\n }\n\n return normalized;\n}\n\n/**\n * Simple pattern matching for ignore patterns\n * Supports basic wildcards * and ** but not full glob syntax\n */\nfunction matchesPattern(filePath: string, pattern: string): boolean {\n // Exact match\n if (filePath === pattern) {\n return true;\n }\n\n // Handle ** (match any number of directories)\n if (pattern.includes('**')) {\n const parts = pattern.split('**');\n if (parts.length === 2) {\n const [prefix, suffix] = parts;\n const prefixMatch = prefix === '' || filePath.startsWith(prefix);\n const suffixMatch = suffix === '' || filePath.endsWith(suffix);\n return prefixMatch && suffixMatch;\n }\n }\n\n // Handle single * wildcard\n if (pattern.includes('*')) {\n const regex = new RegExp('^' + pattern.replace(/\\*/g, '[^/]*') + '$');\n return regex.test(filePath);\n }\n\n // Directory pattern - match if file is under the directory\n if (filePath.startsWith(pattern + '/')) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Checks if a file or directory should be ignored based on ignore rules\n */\nexport function isIgnored(\n filePath: string,\n rootPath: string,\n productNames: string[] = ['oricore'],\n): boolean {\n const { patterns, negationPatterns } = parseIgnoreFiles(\n rootPath,\n productNames,\n );\n\n // If no patterns, nothing is ignored\n if (patterns.length === 0 && negationPatterns.length === 0) {\n return false;\n }\n\n // Get relative path from root\n const relativePath = relative(rootPath, filePath);\n\n // Normalize path separators for cross-platform compatibility\n const normalizedPath = relativePath.split(sep).join('/');\n\n // Check if any ignore pattern matches\n let isIgnoredByPattern = false;\n for (const pattern of patterns) {\n if (matchesPattern(normalizedPath, pattern)) {\n isIgnoredByPattern = true;\n break;\n }\n }\n\n // If not ignored by any pattern, it's not ignored\n if (!isIgnoredByPattern) {\n return false;\n }\n\n // Check negation patterns - these override ignore patterns\n for (const pattern of negationPatterns) {\n if (matchesPattern(normalizedPath, pattern)) {\n return false; // Negation pattern matches, so don't ignore\n }\n }\n\n return true; // Ignored by pattern and no negation applies\n}\n\nexport function parseProductIgnorePatterns(\n rootPath: string,\n productNames: string[],\n): string[] {\n const patterns: string[] = [];\n\n for (const productName of productNames) {\n const ignorePath = join(rootPath, `.${productName.toLowerCase()}ignore`);\n try {\n const content = fs.readFileSync(ignorePath, 'utf8');\n const { patterns: parsed } = parseIgnoreContent(content);\n patterns.push(...parsed);\n } catch (_e) {\n // File doesn't exist\n }\n }\n\n return patterns;\n}\n\nexport function matchesAnyPattern(\n filePath: string,\n patterns: string[],\n): boolean {\n for (const pattern of patterns) {\n if (matchesPattern(filePath, pattern)) {\n return true;\n }\n }\n return false;\n}\n","/**\n * Generate a random UUID v4 compatible string\n * Compatible with Node.js 18+ without using crypto module\n */\nexport function randomUUID(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n","import { CANCELED_MESSAGE_TEXT } from './constants';\nimport type { ToolResult } from '../tools/tool';\nimport { randomUUID } from '../utils/randomUUID';\n\nexport type SystemMessage = {\n role: 'system';\n content: string;\n};\nexport type TextPart = {\n type: 'text';\n text: string;\n};\n\nexport type ImagePart = {\n type: 'image';\n data: string;\n mimeType: string;\n};\n\nexport type FilePart = {\n type: 'file';\n filename?: string;\n data: string;\n mimeType: string;\n};\n\nexport type UserContent = string | Array<TextPart | ImagePart>;\n\nexport type ToolUsePart = {\n type: 'tool_use';\n id: string;\n name: string;\n input: Record<string, any>;\n displayName?: string;\n description?: string;\n};\nexport type ReasoningPart = {\n type: 'reasoning';\n text: string;\n};\nexport type AssistantContent =\n | string\n | Array<TextPart | ReasoningPart | ToolUsePart>;\nexport type AssistantMessage = {\n role: 'assistant';\n content: AssistantContent;\n text: string;\n model: string;\n usage: {\n input_tokens: number;\n output_tokens: number;\n cache_read_input_tokens?: number;\n cache_creation_input_tokens?: number;\n };\n};\nexport type UserMessage = {\n role: 'user';\n content: UserContent;\n hidden?: boolean;\n};\nexport type ToolMessage = {\n role: 'user';\n content: ToolContent;\n};\nexport type ToolMessage2 = {\n role: 'tool';\n content: ToolResultPart2[];\n};\nexport type ToolResultPart2 = {\n type: 'tool-result';\n toolCallId: string;\n toolName: string;\n input: Record<string, any>;\n result: ToolResult;\n agentId?: string;\n agentType?: string;\n // Pruning fields\n pruned?: boolean;\n prunedAt?: number;\n};\nexport type ToolContent = Array<ToolResultPart>;\nexport type ToolResultPart = {\n type: 'tool_result';\n id: string;\n name: string;\n input: Record<string, any>;\n result: ToolResult;\n agentId?: string;\n agentType?: string;\n};\n\nexport type Message =\n | SystemMessage\n | UserMessage\n | AssistantMessage\n | ToolMessage\n | ToolMessage2;\nexport type NormalizedMessage = Message & {\n type: 'message';\n timestamp: string;\n uuid: string;\n parentUuid: string | null;\n uiContent?: string;\n metadata?: {\n agentId?: string;\n agentType?: string;\n [key: string]: any;\n };\n};\n\nexport type SDKSystemMessage = {\n type: 'system';\n subtype: 'init';\n sessionId: string;\n model: string;\n cwd: string;\n tools: string[];\n};\n\nexport type SDKResultMessage = {\n type: 'result';\n subtype: 'success' | 'error';\n isError: boolean;\n content: string;\n sessionId: string;\n __result?: any;\n usage?: { input_tokens: number; output_tokens: number };\n};\n\nexport function toolResultPart2ToToolResultPart(\n part: ToolResultPart2,\n): ToolResultPart {\n return {\n type: 'tool_result',\n id: part.toolCallId,\n name: part.toolName,\n input: part.input,\n result: part.result,\n agentId: part.agentId,\n agentType: part.agentType,\n };\n}\n\nexport function createToolResultPart2(\n toolCallId: string,\n toolName: string,\n input: Record<string, any>,\n result: ToolResult,\n): ToolResultPart2 {\n const part: ToolResultPart2 = {\n type: 'tool-result',\n toolCallId,\n toolName,\n input,\n result,\n };\n\n if (result.metadata?.agentId) {\n part.agentId = result.metadata.agentId;\n part.agentType = result.metadata.agentType;\n }\n\n return part;\n}\n\nexport function createUserMessage(\n content: string,\n parentUuid: string | null,\n): NormalizedMessage {\n return {\n parentUuid,\n uuid: randomUUID(),\n role: 'user',\n content,\n type: 'message',\n timestamp: new Date().toISOString(),\n };\n}\n\nexport function isToolResultMessage(message: Message) {\n return (\n Array.isArray(message.content) &&\n message.content.length === 1 &&\n message.content[0].type === 'tool_result'\n );\n}\n\nexport function isCanceledMessage(message: Message) {\n return (\n message.role === 'user' &&\n Array.isArray(message.content) &&\n message.content.length === 1 &&\n message.content[0].type === 'text' &&\n message.content[0].text === CANCELED_MESSAGE_TEXT\n );\n}\n\nexport function isUserTextMessage(message: Message) {\n return (\n message.role === 'user' &&\n !isToolResultMessage(message) &&\n !isCanceledMessage(message) &&\n !isUserBashCommandMessage(message) &&\n !isUserBashOutputMessage(message)\n );\n}\n\nexport function isUserBashCommandMessage(message: Message) {\n return (\n message.role === 'user' &&\n typeof message.content === 'string' &&\n message.content.startsWith('<bash-input>')\n );\n}\n\nexport function isUserBashOutputMessage(message: Message) {\n return (\n message.role === 'user' &&\n typeof message.content === 'string' &&\n message.content.startsWith('<bash-stdout>')\n );\n}\n\nexport function getMessageText(message: Message) {\n if (\n 'uiContent' in message &&\n message.uiContent &&\n typeof message.uiContent === 'string'\n ) {\n return message.uiContent;\n }\n return typeof message.content === 'string'\n ? message.content\n : message.content\n .filter((c) => c.type === 'text')\n .map((c) => c.text)\n .join('');\n}\n\n/**\n * Finds tool uses in the last assistant message that don't have corresponding tool results.\n * This is useful for identifying incomplete tool executions, such as when a session is canceled\n * before all tools have finished executing.\n *\n * @param messages - Array of normalized messages to analyze\n * @returns Object containing the assistant message and incomplete tool uses, or null if none found\n */\nexport function findIncompleteToolUses(messages: NormalizedMessage[]): {\n assistantMessage: NormalizedMessage;\n incompleteToolUses: ToolUsePart[];\n} | null {\n if (messages.length === 0) {\n return null;\n }\n\n // Find the last assistant message\n let lastAssistantMessage: NormalizedMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === 'assistant') {\n lastAssistantMessage = messages[i];\n break;\n }\n }\n\n if (!lastAssistantMessage || !Array.isArray(lastAssistantMessage.content)) {\n return null;\n }\n\n // Extract all tool_use from the assistant message\n const toolUses = lastAssistantMessage.content.filter(\n (part): part is ToolUsePart => part.type === 'tool_use',\n );\n\n if (toolUses.length === 0) {\n return null;\n }\n\n // Find all tool_result messages after the assistant message\n const assistantIndex = messages.lastIndexOf(lastAssistantMessage);\n const subsequentMessages = messages.slice(assistantIndex + 1);\n\n // Collect all tool_result IDs from subsequent messages\n const completedToolIds = new Set<string>();\n for (const msg of subsequentMessages) {\n if (msg.role === 'tool' && Array.isArray(msg.content)) {\n for (const part of msg.content) {\n if (part.type === 'tool-result') {\n completedToolIds.add(part.toolCallId);\n }\n }\n }\n }\n\n // Find tool_uses that don't have corresponding tool_results\n const incompleteToolUses = toolUses.filter(\n (toolUse) => !completedToolIds.has(toolUse.id),\n );\n\n if (incompleteToolUses.length === 0) {\n return null;\n }\n\n return {\n assistantMessage: lastAssistantMessage,\n incompleteToolUses,\n };\n}\n","import type { LanguageModelV3Prompt } from '@ai-sdk/provider';\nimport type { ModelInfo } from './model';\n\nexport function addPromptCache(\n prompt: LanguageModelV3Prompt,\n model: ModelInfo,\n): LanguageModelV3Prompt {\n const modelId = model.model.id.toLowerCase();\n const providerId = model.provider.id;\n\n const shouldCache =\n modelId.includes('claude') ||\n modelId.includes('sonnet') ||\n modelId.includes('opus');\n\n if (!shouldCache) {\n return prompt;\n }\n\n const providerOptions = {\n anthropic: { cacheControl: { type: 'ephemeral' } },\n openrouter: { cacheControl: { type: 'ephemeral' } },\n bedrock: { cachePoint: { type: 'ephemeral' } },\n openaiCompatible: { cache_control: { type: 'ephemeral' } },\n };\n\n const system = prompt.filter((msg) => msg.role === 'system').slice(0, 2);\n const nonSystem = prompt.filter((msg) => msg.role !== 'system').slice(-2);\n const toCache = new Set([...system, ...nonSystem]);\n\n return prompt.map((message) => {\n if (!toCache.has(message)) return message;\n\n if (\n providerId !== 'anthropic' &&\n Array.isArray(message.content) &&\n message.content.length > 0\n ) {\n const content = [...message.content];\n const last = content[content.length - 1];\n if (last && typeof last === 'object') {\n content[content.length - 1] = {\n ...last,\n providerOptions: { ...last.providerOptions, ...providerOptions },\n };\n return { ...message, content };\n }\n }\n\n return {\n ...message,\n providerOptions: { ...message.providerOptions, ...providerOptions },\n };\n }) as LanguageModelV3Prompt;\n}\n","import type { AssistantMessage } from '../core/message';\n\nexport class Usage {\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n\n constructor(init?: Partial<Usage>) {\n this.promptTokens = init?.promptTokens ?? 0;\n this.completionTokens = init?.completionTokens ?? 0;\n this.totalTokens = init?.totalTokens ?? 0;\n }\n\n static empty(): Usage {\n return new Usage();\n }\n\n static fromEventUsage(eventUsage: any): Usage {\n // Handle AI SDK v6 format (nested objects with total property)\n // See: LanguageModelV3Usage interface\n // ref https://github.com/vercel/ai/blob/main/packages/openai-compatible/src/chat/convert-openai-compatible-chat-usage.ts#L3\n const inputTokens =\n typeof eventUsage?.inputTokens === 'object'\n ? eventUsage?.inputTokens?.total\n : eventUsage?.inputTokens;\n\n const outputTokens =\n typeof eventUsage?.outputTokens === 'object'\n ? eventUsage?.outputTokens?.total\n : eventUsage?.outputTokens;\n\n const promptTokens = eventUsage?.promptTokens ?? inputTokens ?? 0;\n\n const completionTokens = eventUsage?.completionTokens ?? outputTokens ?? 0;\n\n const totalTokens =\n eventUsage?.totalTokens ?? promptTokens + completionTokens;\n\n return new Usage({\n promptTokens: Number.isNaN(promptTokens) ? 0 : promptTokens,\n completionTokens: Number.isNaN(completionTokens) ? 0 : completionTokens,\n totalTokens: Number.isNaN(totalTokens) ? 0 : totalTokens,\n });\n }\n\n static fromAssistantMessage(message: AssistantMessage): Usage {\n return new Usage({\n promptTokens: message.usage?.input_tokens,\n completionTokens: message.usage?.output_tokens,\n totalTokens: message.usage?.input_tokens + message.usage?.output_tokens,\n });\n }\n\n add(other: Usage): void {\n this.promptTokens += other.promptTokens;\n this.completionTokens += other.completionTokens;\n this.totalTokens += other.totalTokens;\n }\n\n reset(): void {\n this.promptTokens = 0;\n this.completionTokens = 0;\n this.totalTokens = 0;\n }\n\n clone(): Usage {\n return new Usage({\n promptTokens: this.promptTokens,\n completionTokens: this.completionTokens,\n totalTokens: this.totalTokens,\n });\n }\n\n isValid(): boolean {\n return (\n this.promptTokens >= 0 &&\n this.completionTokens >= 0 &&\n this.totalTokens >= 0\n );\n }\n}\n","import createDebug from 'debug';\nimport { jsonrepair } from 'jsonrepair';\n\nconst debug = createDebug('oricore:utils:safeParseJson');\n\nexport function safeParseJson(json: string) {\n try {\n return JSON.parse(json);\n } catch (_error) {\n // try to repair the json\n try {\n debug('safeParseJson failed, trying to repair', _error);\n const repairedJson = jsonrepair(json);\n return JSON.parse(repairedJson);\n } catch (_repairError) {\n debug('safeParseJson failed, repair failed', _repairError);\n return {};\n }\n }\n}\n","import type { ModelMap } from './types';\n\nexport const models: ModelMap = {\n 'deepseek-v3-0324': {\n name: 'DeepSeek-V3-0324',\n shortName: 'DeepSeek V3',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2024-06',\n release_date: '2025-03-24',\n last_updated: '2025-03-24',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 128000, output: 8192 },\n },\n 'deepseek-v3-1': {\n name: 'DeepSeek V3.1',\n shortName: 'DeepSeek V3.1',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-07',\n release_date: '2025-08-21',\n last_updated: '2025-08-21',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 163840, output: 163840 },\n },\n 'deepseek-v3-1-terminus': {\n name: 'DeepSeek V3.1 Terminus',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-07',\n release_date: '2025-09-22',\n last_updated: '2025-09-22',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 131072, output: 65536 },\n },\n 'deepseek-v3-2-exp': {\n name: 'DeepSeek V3.2 Exp',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-09',\n release_date: '2025-09-29',\n last_updated: '2025-09-29',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 131072, output: 65536 },\n },\n 'deepseek-v3.2': {\n name: 'DeepSeek V3.2',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-12',\n release_date: '2025-12-01',\n last_updated: '2025-12-01',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 131072, output: 65536 },\n },\n 'deepseek-v3.2-speciale': {\n name: 'DeepSeek V3.2 Speciale',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: false,\n knowledge: '2025-12',\n release_date: '2025-12-01',\n last_updated: '2025-12-01',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 131072, output: 131072 },\n },\n 'deepseek-r1-0528': {\n name: 'DeepSeek-R1-0528',\n shortName: 'DeepSeek R1',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2024-06',\n release_date: '2025-05-28',\n last_updated: '2025-05-28',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 65536, output: 8192 },\n },\n 'doubao-seed-1.6': {\n name: 'Doubao Seed 1.6',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-01',\n release_date: '2025-06-11',\n last_updated: '2025-09-23',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: true,\n limit: { context: 163840, output: 163840 },\n },\n 'kimi-k2': {\n name: 'Kimi K2',\n attachment: false,\n reasoning: false,\n temperature: true,\n tool_call: true,\n knowledge: '2024-10',\n release_date: '2025-07-11',\n last_updated: '2025-07-11',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 131072, output: 16384 },\n },\n 'kimi-k2-turbo-preview': {\n name: 'Kimi K2 Turbo',\n attachment: false,\n reasoning: false,\n temperature: true,\n tool_call: true,\n knowledge: '2024-10',\n release_date: '2025-07-14',\n last_updated: '2025-07-14',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 131072, output: 16384 },\n },\n 'kimi-k2-0905': {\n name: 'Kimi K2 Instruct 0905',\n shortName: 'Kimi K2 0905',\n attachment: false,\n reasoning: false,\n temperature: true,\n tool_call: true,\n knowledge: '2024-10',\n release_date: '2025-09-05',\n last_updated: '2025-09-05',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 262144, output: 16384 },\n },\n 'kimi-k2-thinking': {\n name: 'Kimi K2 Thinking',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2024-08',\n release_date: '2025-11-06',\n last_updated: '2025-11-06',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 262144, output: 262144 },\n },\n 'kimi-k2-thinking-turbo': {\n name: 'Kimi K2 Thinking Turbo',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2024-08',\n release_date: '2025-11-06',\n last_updated: '2025-11-06',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 262144, output: 262144 },\n },\n 'kimi-k2.5': {\n name: 'Kimi K2.5',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-01',\n release_date: '2026-01-27',\n last_updated: '2026-01-27',\n modalities: { input: ['text', 'image', 'video'], output: ['text'] },\n open_weights: true,\n limit: { context: 262144, output: 262144 },\n },\n 'qwen3-coder-480b-a35b-instruct': {\n name: 'Qwen3 Coder 480B A35B Instruct',\n shortName: 'Qwen3 Coder',\n attachment: false,\n reasoning: false,\n temperature: true,\n tool_call: true,\n knowledge: '2025-04',\n release_date: '2025-07-23',\n last_updated: '2025-07-23',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 262144, output: 66536 },\n },\n 'qwen3-coder-plus': {\n name: 'Qwen3 Coder Plus',\n attachment: false,\n reasoning: false,\n temperature: true,\n tool_call: true,\n knowledge: '2025-04',\n release_date: '2025-07-23',\n last_updated: '2025-07-23',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 1048576, output: 65536 },\n },\n 'qwen3-235b-a22b-07-25': {\n name: 'Qwen3 235B A22B Instruct 2507',\n shortName: 'Qwen3',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-04',\n release_date: '2025-04-28',\n last_updated: '2025-07-21',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 262144, output: 131072 },\n },\n 'qwen3-max': {\n name: 'Qwen3 Max',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-09',\n release_date: '2025-09-05',\n last_updated: '2025-09-05',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: false,\n limit: { context: 262144, output: 32768 },\n },\n 'gemini-2.5-flash': {\n name: 'Gemini 2.5 Flash',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-01',\n release_date: '2025-03-20',\n last_updated: '2025-06-05',\n modalities: {\n input: ['text', 'image', 'audio', 'video', 'pdf'],\n output: ['text'],\n },\n open_weights: false,\n limit: { context: 1048576, output: 65536 },\n },\n 'gemini-2.5-flash-preview-09-2025': {\n name: 'Gemini 2.5 Flash Preview 2025 09',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-01',\n release_date: '2025-09-25',\n last_updated: '2025-09-25',\n modalities: {\n input: ['text', 'image', 'audio', 'video', 'pdf'],\n output: ['text'],\n },\n open_weights: false,\n limit: { context: 1048576, output: 65536 },\n },\n 'gemini-2.5-flash-lite-preview-06-17': {\n name: 'Gemini 2.5 Flash Lite Preview 06-17',\n shortName: 'Gemini 2.5 Flash Lite',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-01',\n release_date: '2025-06-17',\n last_updated: '2025-06-17',\n modalities: {\n input: ['text', 'image', 'audio', 'video', 'pdf'],\n output: ['text'],\n },\n open_weights: false,\n limit: { context: 65536, output: 65536 },\n },\n 'gemini-2.5-pro': {\n name: 'Gemini 2.5 Pro',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-01',\n release_date: '2025-03-20',\n last_updated: '2025-06-05',\n modalities: {\n input: ['text', 'image', 'audio', 'video', 'pdf'],\n output: ['text'],\n },\n open_weights: false,\n limit: { context: 1048576, output: 65536 },\n },\n 'gemini-3-pro-preview': {\n name: 'Gemini 3 Pro Preview',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-01',\n release_date: '2025-01-01',\n last_updated: '2025-01-01',\n modalities: {\n input: ['text', 'image', 'audio', 'video', 'pdf'],\n output: ['text'],\n },\n open_weights: false,\n limit: { context: 200000, output: 65536 },\n },\n 'gemini-3.1-pro-preview': {\n name: 'Gemini 3.1 Pro Preview',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-01',\n release_date: '2026-02-19',\n last_updated: '2026-02-19',\n modalities: {\n input: ['text', 'image', 'audio', 'video', 'pdf'],\n output: ['text'],\n },\n open_weights: false,\n limit: { context: 1048576, output: 65536 },\n },\n 'gemini-3-flash-preview': {\n name: 'Gemini 3 Flash Preview',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-01',\n release_date: '2025-12-17',\n last_updated: '2025-12-17',\n modalities: {\n input: ['text', 'image', 'video', 'audio', 'pdf'],\n output: ['text'],\n },\n open_weights: false,\n limit: { context: 1048576, output: 65536 },\n },\n 'grok-4': {\n name: 'Grok 4',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-07',\n release_date: '2025-07-09',\n last_updated: '2025-07-09',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: false,\n limit: { context: 256000, output: 64000 },\n },\n 'grok-code-fast-1': {\n name: 'Grok Code Fast 1',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-08',\n release_date: '2025-08-20',\n last_updated: '2025-08-20',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 256000, output: 32000 },\n },\n 'grok-4-fast': {\n name: 'Grok 4 Fast',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2024-11',\n release_date: '2025-08-19',\n last_updated: '2025-08-19',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 2000000, output: 2000000 },\n },\n 'grok-4.1-fast': {\n name: 'Grok 4.1 Fast',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-10',\n release_date: '2025-11-19',\n last_updated: '2025-11-19',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 2000000, output: 2000000 },\n },\n 'claude-3-5-sonnet-20241022': {\n name: 'Claude Sonnet 3.5 v2',\n shortName: 'Sonnet 3.5',\n attachment: true,\n reasoning: false,\n temperature: true,\n tool_call: true,\n knowledge: '2024-04-30',\n release_date: '2024-10-22',\n last_updated: '2024-10-22',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 200000, output: 8192 },\n },\n 'claude-3-7-sonnet': {\n name: 'Claude Sonnet 3.7',\n shortName: 'Sonnet 3.7',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2024-10-31',\n release_date: '2025-02-19',\n last_updated: '2025-02-19',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 200000, output: 64000 },\n },\n 'claude-4-sonnet': {\n name: 'Claude Sonnet 4',\n shortName: 'Sonnet 4',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-03-31',\n release_date: '2025-05-22',\n last_updated: '2025-05-22',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 200000, output: 64000 },\n },\n 'claude-4-opus': {\n name: 'Claude Opus 4',\n shortName: 'Opus 4',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-03-31',\n release_date: '2025-05-22',\n last_updated: '2025-05-22',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 200000, output: 32000 },\n },\n 'gpt-oss-120b': {\n name: 'GPT OSS 120B',\n shortName: 'GPT OSS',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-08',\n release_date: '2025-08-05',\n last_updated: '2025-08-05',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 131072, output: 32768 },\n },\n 'gpt-5.1-codex': {\n name: 'GPT-5.1-Codex',\n attachment: false,\n reasoning: true,\n temperature: false,\n tool_call: true,\n knowledge: '2024-09-30',\n release_date: '2025-11-13',\n last_updated: '2025-11-13',\n modalities: {\n input: ['text', 'image'],\n output: ['text'],\n },\n open_weights: false,\n limit: { context: 400000, output: 128000 },\n },\n 'gpt-5.1-codex-mini': {\n name: 'GPT-5.1-Codex-mini',\n attachment: false,\n reasoning: true,\n temperature: false,\n tool_call: true,\n knowledge: '2024-09-30',\n release_date: '2025-11-13',\n last_updated: '2025-11-13',\n modalities: {\n input: ['text', 'image'],\n output: ['text'],\n },\n open_weights: false,\n limit: { context: 400000, output: 100000 },\n },\n 'gpt-5.1-codex-max': {\n name: 'GPT 5.1 Codex Max',\n attachment: true,\n reasoning: true,\n temperature: false,\n tool_call: true,\n knowledge: '2024-09-30',\n release_date: '2025-11-13',\n last_updated: '2025-11-13',\n modalities: {\n input: ['text', 'image'],\n output: ['text'],\n },\n open_weights: false,\n limit: { context: 400000, output: 128000 },\n },\n 'gpt-5.1': {\n name: 'GPT-5.1',\n attachment: true,\n reasoning: true,\n temperature: false,\n tool_call: true,\n knowledge: '2024-09-30',\n release_date: '2025-11-13',\n last_updated: '2025-11-13',\n modalities: {\n input: ['text', 'image'],\n output: ['text'],\n },\n open_weights: false,\n limit: { context: 400000, output: 128000 },\n },\n 'gpt-5': {\n name: 'GPT-5',\n attachment: true,\n reasoning: true,\n temperature: false,\n tool_call: true,\n knowledge: '2024-09-30',\n release_date: '2025-08-07',\n last_updated: '2025-08-07',\n modalities: {\n input: ['text', 'audio', 'image', 'video'],\n output: ['text', 'audio', 'image'],\n },\n open_weights: false,\n limit: { context: 400000, output: 128000 },\n },\n 'gpt-5-mini': {\n name: 'GPT-5 Mini',\n attachment: true,\n reasoning: true,\n temperature: false,\n tool_call: true,\n knowledge: '2024-05-30',\n release_date: '2025-08-07',\n last_updated: '2025-08-07',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 272000, output: 128000 },\n },\n 'gpt-5-codex': {\n name: 'GPT-5-Codex',\n attachment: false,\n reasoning: true,\n temperature: false,\n tool_call: true,\n knowledge: '2024-09-30',\n release_date: '2025-09-15',\n last_updated: '2025-09-15',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 128000, output: 64000 },\n },\n 'gpt-5.2': {\n name: 'GPT-5.2',\n attachment: true,\n reasoning: true,\n temperature: false,\n tool_call: true,\n knowledge: '2025-08-31',\n release_date: '2025-12-11',\n last_updated: '2025-12-11',\n modalities: { input: ['text', 'image'], output: ['text', 'image'] },\n open_weights: false,\n limit: { context: 400000, output: 128000 },\n },\n 'gpt-5.2-pro': {\n name: 'GPT-5.2 Pro',\n attachment: true,\n reasoning: true,\n temperature: false,\n tool_call: true,\n knowledge: '2025-08-31',\n release_date: '2025-12-11',\n last_updated: '2025-12-11',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 400000, output: 128000 },\n },\n 'gpt-5.2-codex': {\n name: 'GPT-5.2-Codex',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-08-31',\n release_date: '2026-01-14',\n last_updated: '2026-01-14',\n modalities: {\n input: ['text', 'image'],\n output: ['text'],\n },\n open_weights: false,\n limit: { context: 400000, output: 128000 },\n },\n 'gpt-5.3-codex': {\n name: 'GPT-5.3 Codex',\n attachment: true,\n reasoning: true,\n temperature: false,\n tool_call: true,\n knowledge: '2025-08-31',\n release_date: '2026-02-05',\n last_updated: '2026-02-05',\n modalities: { input: ['text', 'image', 'pdf'], output: ['text'] },\n open_weights: false,\n limit: { context: 400000, output: 128000 },\n },\n 'gpt-4.1': {\n name: 'GPT-4.1',\n attachment: true,\n reasoning: false,\n temperature: true,\n tool_call: true,\n knowledge: '2024-04',\n release_date: '2025-04-14',\n last_updated: '2025-04-14',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 1047576, output: 32768 },\n },\n 'gpt-4': {\n name: 'GPT-4',\n attachment: true,\n reasoning: false,\n temperature: true,\n tool_call: true,\n knowledge: '2023-11',\n release_date: '2023-11-06',\n last_updated: '2024-04-09',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: false,\n limit: { context: 8192, output: 8192 },\n },\n 'gpt-4o': {\n name: 'GPT-4o',\n attachment: true,\n reasoning: false,\n temperature: true,\n tool_call: true,\n knowledge: '2023-09',\n release_date: '2024-05-13',\n last_updated: '2024-05-13',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 128000, output: 16384 },\n },\n o3: {\n name: 'o3',\n attachment: true,\n reasoning: true,\n temperature: false,\n tool_call: true,\n knowledge: '2024-05',\n release_date: '2025-04-16',\n last_updated: '2025-04-16',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 200000, output: 100000 },\n },\n 'o3-pro': {\n name: 'o3-pro',\n attachment: true,\n reasoning: true,\n temperature: false,\n tool_call: true,\n knowledge: '2024-05',\n release_date: '2025-06-10',\n last_updated: '2025-06-10',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 200000, output: 100000 },\n },\n 'o3-mini': {\n name: 'o3-mini',\n attachment: false,\n reasoning: true,\n temperature: false,\n tool_call: true,\n knowledge: '2024-05',\n release_date: '2024-12-20',\n last_updated: '2025-01-29',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: false,\n limit: { context: 200000, output: 100000 },\n },\n 'o4-mini': {\n name: 'o4-mini',\n attachment: true,\n reasoning: true,\n temperature: false,\n tool_call: true,\n knowledge: '2024-05',\n release_date: '2025-04-16',\n last_updated: '2025-04-16',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 200000, output: 100000 },\n },\n 'glm-4.5': {\n name: 'GLM-4.5',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-04',\n release_date: '2025-07-28',\n last_updated: '2025-07-28',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 131072, output: 98304 },\n },\n 'glm-4.5-air': {\n name: 'GLM-4.5-Air',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-04',\n release_date: '2025-07-28',\n last_updated: '2025-07-28',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 131072, output: 98304 },\n },\n 'glm-4.5-flash': {\n name: 'GLM-4.5-Flash',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-04',\n release_date: '2025-07-28',\n last_updated: '2025-07-28',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 131072, output: 98304 },\n },\n 'glm-4.5v': {\n name: 'GLM-4.5V',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-04',\n release_date: '2025-08-11',\n last_updated: '2025-08-11',\n modalities: { input: ['text', 'image', 'video'], output: ['text'] },\n open_weights: true,\n limit: { context: 64000, output: 16384 },\n },\n 'glm-4.6': {\n name: 'GLM-4.6',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-04',\n release_date: '2025-09-30',\n last_updated: '2025-09-30',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 204800, output: 131072 },\n },\n 'glm-4.6v': {\n name: 'GLM-4.6V',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-04',\n release_date: '2025-12-08',\n last_updated: '2025-12-08',\n modalities: { input: ['text', 'image', 'video'], output: ['text'] },\n open_weights: true,\n limit: { context: 131072, output: 24000 },\n },\n 'glm-4.7': {\n name: 'GLM-4.7',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-04',\n release_date: '2025-12-22',\n last_updated: '2025-12-22',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 204800, output: 131072 },\n },\n 'glm-5': {\n name: 'GLM-5',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-06',\n release_date: '2026-02-10',\n last_updated: '2026-02-10',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 262144, output: 131072 },\n },\n 'sonoma-dusk-alpha': {\n name: 'Sonoma Dusk Alpha',\n attachment: true,\n reasoning: false,\n temperature: false,\n tool_call: true,\n knowledge: '2024-09',\n release_date: '2024-09-05',\n last_updated: '2024-09-05',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 2000000, output: 2000000 },\n },\n 'sonoma-sky-alpha': {\n name: 'Sonoma Sky Alpha',\n attachment: true,\n reasoning: false,\n temperature: false,\n tool_call: true,\n knowledge: '2024-09',\n release_date: '2024-09-05',\n last_updated: '2024-09-05',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 2000000, output: 2000000 },\n },\n 'claude-4.1-opus': {\n name: 'Claude Opus 4.1',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-03-31',\n release_date: '2025-08-05',\n last_updated: '2025-08-05',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 200000, output: 32000 },\n },\n 'claude-4-5-sonnet': {\n name: 'Claude Sonnet 4.5 (Preview)',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-03-31',\n release_date: '2025-09-29',\n last_updated: '2025-09-29',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 200000, output: 32000 },\n },\n 'claude-haiku-4-5': {\n name: 'Claude Haiku 4.5',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-02-31',\n release_date: '2025-10-15',\n last_updated: '2025-10-15',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 200000, output: 64000 },\n },\n 'claude-opus-4-5': {\n name: 'Claude Opus 4.5',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-03-31',\n release_date: '2025-11-24',\n last_updated: '2025-11-24',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 200000, output: 64000 },\n },\n 'claude-opus-4-6': {\n name: 'Claude Opus 4.6',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-05-31',\n release_date: '2026-02-05',\n last_updated: '2026-02-05',\n modalities: { input: ['text', 'image', 'pdf'], output: ['text'] },\n open_weights: false,\n limit: { context: 200000, output: 128000 },\n },\n 'claude-sonnet-4-6': {\n name: 'Claude Sonnet 4.6',\n shortName: 'Sonnet 4.6',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-07-31',\n release_date: '2026-02-17',\n last_updated: '2026-02-17',\n modalities: { input: ['text', 'image', 'pdf'], output: ['text'] },\n open_weights: false,\n limit: { context: 1000000, output: 64000 },\n },\n 'ling-1t': {\n name: 'InclusionAI Ling-1T',\n attachment: true,\n reasoning: false,\n temperature: true,\n tool_call: true,\n knowledge: '2025-10-09',\n release_date: '2025-10-09',\n last_updated: '2025-10-09',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: false,\n limit: { context: 128000, output: 32000 },\n },\n 'ring-1t': {\n name: 'InclusionAI Ring-1T',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-10-14',\n release_date: '2025-10-14',\n last_updated: '2025-10-14',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: false,\n limit: { context: 128000, output: 32000 },\n },\n 'ring-flash-2.0': {\n name: 'InclusionAI Ring-flash-2.0',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-09-09',\n release_date: '2025-09-15',\n last_updated: '2025-09-16',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: false,\n limit: { context: 128000, output: 32000 },\n },\n 'ling-flash-2.0': {\n name: 'InclusionAI Ling-flash-2.0',\n attachment: true,\n reasoning: false,\n temperature: true,\n tool_call: true,\n knowledge: '2025-09-09',\n release_date: '2025-09-15',\n last_updated: '2025-09-16',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: false,\n limit: { context: 128000, output: 32000 },\n },\n 'ring-mini-2.0': {\n name: 'InclusionAI Ring-mini-2.0',\n attachment: true,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-09-09',\n release_date: '2025-09-15',\n last_updated: '2025-09-16',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: false,\n limit: { context: 128000, output: 32000 },\n },\n 'ling-mini-2.0': {\n name: 'InclusionAI Ling-mini-2.0',\n attachment: true,\n reasoning: false,\n temperature: true,\n tool_call: true,\n knowledge: '2025-09-09',\n release_date: '2025-09-15',\n last_updated: '2025-09-16',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: false,\n limit: { context: 128000, output: 32000 },\n },\n 'minimax-m2': {\n name: 'Minimax-M2',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '',\n release_date: '2025-10-27',\n last_updated: '2025-10-27',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 196608, output: 64000 },\n },\n 'sherlock-dash-alpha': {\n name: 'Sherlock Dash Alpha',\n attachment: true,\n reasoning: false,\n temperature: false,\n tool_call: true,\n knowledge: 'unknown',\n release_date: '2025-11-15',\n last_updated: '2025-11-15',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 1840000, output: 64000 },\n },\n 'sherlock-think-alpha': {\n name: 'Sherlock Think Alpha',\n attachment: true,\n reasoning: true,\n temperature: false,\n tool_call: true,\n knowledge: 'unknown',\n release_date: '2025-11-15',\n last_updated: '2025-11-15',\n modalities: { input: ['text', 'image'], output: ['text'] },\n open_weights: false,\n limit: { context: 1840000, output: 64000 },\n },\n 'mimo-v2-flash': {\n name: 'MiMo V2 Flash',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '2025-12',\n release_date: '2025-12-17',\n last_updated: '2025-12-17',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 131072, output: 32768 },\n },\n 'minimax-m2.1': {\n name: 'MiniMax-M2.1',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '',\n release_date: '2025-12-23',\n last_updated: '2025-12-23',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 204800, output: 131072 },\n },\n 'minimax-m2.5': {\n name: 'MiniMax M2.5',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '',\n release_date: '2026-02-13',\n last_updated: '2026-02-13',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 204800, output: 131072 },\n },\n 'minimax-m2.7': {\n name: 'MiniMax M2.7',\n attachment: false,\n reasoning: true,\n temperature: true,\n tool_call: true,\n knowledge: '',\n release_date: '2026-03-18',\n last_updated: '2026-03-18',\n modalities: { input: ['text'], output: ['text'] },\n open_weights: true,\n limit: { context: 204800, output: 131072 },\n },\n};\n","import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createCerebras } from '@ai-sdk/cerebras';\nimport { createGoogleGenerativeAI } from '@ai-sdk/google';\nimport { createHuggingFace } from '@ai-sdk/huggingface';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport { createXai } from '@ai-sdk/xai';\nimport { createAihubmix } from '@aihubmix/ai-sdk-provider';\nimport {\n createOpenRouter,\n} from '@openrouter/ai-sdk-provider';\nimport type { LanguageModelV3, LanguageModelV3Middleware } from '@ai-sdk/provider';\nimport {\n extractReasoningMiddleware,\n} from 'ai';\nimport assert from 'assert';\n\nimport type { Provider, ProvidersMap, ModelMap } from './types';\nimport { models } from './models';\nimport { getProviderBaseURL, getProviderApiKey } from './utils';\nimport { withProxyConfig } from './proxy';\nimport { mergeSystemMessagesMiddleware } from '../../utils/mergeSystemMessagesMiddleware';\n\nexport const defaultModelCreator = (name: string, provider: Provider): LanguageModelV3 => {\n if (provider.id !== 'openai') {\n assert(provider.api, `Provider ${provider.id} must have an api`);\n }\n const baseURL = getProviderBaseURL(provider);\n const apiKey = getProviderApiKey(provider);\n assert(baseURL, 'baseURL is required');\n const model = createOpenAICompatible(\n withProxyConfig(\n {\n name: provider.id,\n baseURL,\n apiKey,\n },\n provider,\n ),\n )(name);\n return model as unknown as LanguageModelV3;\n};\n\nexport const defaultAnthropicModelCreator = (\n name: string,\n provider: Provider,\n): LanguageModelV3 => {\n const baseURL = getProviderBaseURL(provider);\n const apiKey = getProviderApiKey(provider);\n return createAnthropic(\n withProxyConfig({ apiKey, baseURL }, provider),\n ).chat(name) as LanguageModelV3;\n};\n\nexport const openaiModelCreator = (\n name: string,\n provider: Provider,\n): LanguageModelV3 => {\n if (provider.id !== 'openai') {\n assert(provider.api, `Provider ${provider.id} must have an api`);\n }\n const baseURL = getProviderBaseURL(provider);\n const apiKey = getProviderApiKey(provider);\n return createOpenAI(\n withProxyConfig(\n {\n baseURL,\n apiKey,\n },\n provider,\n ),\n ).chat(name);\n};\n\nexport const openaiModelResponseCreator = (\n name: string,\n provider: Provider,\n): LanguageModelV3 => {\n if (provider.id !== 'openai') {\n assert(provider.api, `Provider ${provider.id} must have an api`);\n }\n const baseURL = getProviderBaseURL(provider);\n const apiKey = getProviderApiKey(provider);\n return createOpenAI(\n withProxyConfig(\n {\n baseURL,\n apiKey,\n },\n provider,\n ),\n ).responses(name);\n};\n\nexport const createModelCreatorCompatible = (opts?: {\n headers?: Record<string, string>;\n fetch?: any;\n middlewares?: LanguageModelV3Middleware[];\n}) => {\n return (name: string, provider: Provider): LanguageModelV3 => {\n if (provider.id !== 'openai') {\n assert(provider.api, `Provider ${provider.id} must have an api`);\n }\n const baseURL = getProviderBaseURL(provider);\n const apiKey = getProviderApiKey(provider);\n assert(baseURL, 'baseURL is required');\n const model = createOpenAICompatible(\n withProxyConfig(\n {\n name: provider.id,\n baseURL,\n apiKey,\n headers: opts?.headers,\n fetch: opts?.fetch,\n },\n provider,\n ),\n )(name);\n return model as unknown as LanguageModelV3;\n };\n};\n\nexport const providers: ProvidersMap = {\n openai: {\n id: 'openai',\n source: 'built-in',\n env: ['OPENAI_API_KEY'],\n apiEnv: ['OPENAI_API_BASE'],\n name: 'OpenAI',\n doc: 'https://platform.openai.com/docs/models',\n models: {\n 'glm-4.7': models['glm-4.7'],\n 'gpt-4.1': models['gpt-4.1'],\n 'gpt-4': models['gpt-4'],\n 'gpt-4o': models['gpt-4o'],\n o3: models['o3'],\n 'o3-mini': models['o3-mini'],\n 'o4-mini': models['o4-mini'],\n 'gpt-5.1': models['gpt-5.1'],\n 'gpt-5.1-codex': models['gpt-5.1-codex'],\n 'gpt-5.1-codex-mini': models['gpt-5.1-codex-mini'],\n 'gpt-5.1-codex-max': models['gpt-5.1-codex-max'],\n 'gpt-5': models['gpt-5'],\n 'gpt-5-mini': models['gpt-5-mini'],\n 'gpt-5-codex': models['gpt-5-codex'],\n 'gpt-5.2': models['gpt-5.2'],\n 'gpt-5.2-pro': models['gpt-5.2-pro'],\n 'gpt-5.2-codex': models['gpt-5.2-codex'],\n 'gpt-5.3-codex': models['gpt-5.3-codex'],\n },\n createModel: openaiModelCreator,\n },\n google: {\n id: 'google',\n source: 'built-in',\n env: ['GOOGLE_API_KEY', 'GOOGLE_GENERATIVE_AI_API_KEY'],\n apiEnv: ['GOOGLE_GENERATIVE_AI_API_BASE'],\n name: 'Google',\n doc: 'https://ai.google.dev/gemini-api/docs/pricing',\n models: {\n 'gemini-2.5-flash': models['gemini-2.5-flash'],\n 'gemini-2.5-flash-preview-09-2025':\n models['gemini-2.5-flash-preview-09-2025'],\n 'gemini-2.5-flash-lite': models['gemini-2.5-flash-lite-preview-06-17'],\n 'gemini-2.5-pro': models['gemini-2.5-pro'],\n 'gemini-3-pro-preview': models['gemini-3-pro-preview'],\n 'gemini-3.1-pro-preview': models['gemini-3.1-pro-preview'],\n 'gemini-3-flash-preview': models['gemini-3-flash-preview'],\n },\n createModel(name, provider) {\n const baseURL = getProviderBaseURL(provider);\n const apiKey = getProviderApiKey(provider);\n return createGoogleGenerativeAI(\n withProxyConfig({ apiKey, baseURL }, provider),\n )(name);\n },\n },\n deepseek: {\n id: 'deepseek',\n source: 'built-in',\n env: ['DEEPSEEK_API_KEY'],\n name: 'DeepSeek',\n api: 'https://api.deepseek.com',\n apiEnv: ['DEEPSEEK_API_BASE'],\n doc: 'https://platform.deepseek.com/api-docs/pricing',\n models: {\n 'deepseek-chat': models['deepseek-v3.2'],\n 'deepseek-reasoner': models['deepseek-r1-0528'],\n },\n createModel: defaultModelCreator,\n },\n xai: {\n id: 'xai',\n source: 'built-in',\n env: ['XAI_API_KEY'],\n apiEnv: ['XAI_BASE_URL'],\n name: 'xAI',\n doc: 'https://xai.com/docs/models',\n models: {\n 'grok-4-1-fast': models['grok-4.1-fast'],\n 'grok-4-1-fast-non-reasoning': {\n ...models['grok-4.1-fast'],\n reasoning: false,\n },\n 'grok-4': models['grok-4'],\n 'grok-4-fast': models['grok-4-fast'],\n 'grok-code-fast-1': models['grok-code-fast-1'],\n },\n createModel(name, provider) {\n const api = getProviderBaseURL(provider);\n const apiKey = getProviderApiKey(provider);\n return createXai({\n baseURL: api,\n apiKey,\n }).chat(name);\n },\n },\n anthropic: {\n id: 'anthropic',\n source: 'built-in',\n env: ['ANTHROPIC_API_KEY'],\n apiEnv: ['ANTHROPIC_API_BASE'],\n name: 'Anthropic',\n doc: 'https://docs.anthropic.com/en/docs/models',\n models: {\n 'claude-opus-4-20250514': models['claude-4-opus'],\n 'claude-opus-4-1-20250805': models['claude-4.1-opus'],\n 'claude-sonnet-4-20250514': models['claude-4-sonnet'],\n 'claude-sonnet-4-5-20250929': models['claude-4-5-sonnet'],\n 'claude-3-7-sonnet-20250219': models['claude-3-7-sonnet'],\n 'claude-3-7-sonnet-20250219-thinking': models['claude-3-7-sonnet'],\n 'claude-3-5-sonnet-20241022': models['claude-3-5-sonnet-20241022'],\n 'claude-haiku-4-5': models['claude-haiku-4-5'],\n 'claude-opus-4-5': models['claude-opus-4-5'],\n 'claude-opus-4-6': models['claude-opus-4-6'],\n 'claude-sonnet-4-6': models['claude-sonnet-4-6'],\n },\n apiFormat: 'anthropic',\n headers: {\n 'X-Title': 'OriCore',\n 'HTTP-Referer': 'https://github.com/lyw405/oricore',\n },\n createModel: defaultAnthropicModelCreator,\n },\n aihubmix: {\n id: 'aihubmix',\n source: 'built-in',\n env: ['AIHUBMIX_API_KEY'],\n name: 'AIHubMix',\n api: 'https://aihubmix.com/v1',\n doc: 'https://docs.aihubmix.com/',\n models: {\n 'gemini-2.5-pro': models['gemini-2.5-pro'],\n 'gemini-2.5-flash': models['gemini-2.5-flash'],\n 'gemini-2.5-flash-lite': models['gemini-2.5-flash-lite-preview-06-17'],\n 'DeepSeek-R1': models['deepseek-r1-0528'],\n 'DeepSeek-V3': models['deepseek-v3-0324'],\n 'claude-opus-4-20250514': models['claude-4-opus'],\n 'claude-opus-4-1': models['claude-4.1-opus'],\n 'claude-sonnet-4-20250514': models['claude-4-sonnet'],\n 'claude-sonnet-4-5': models['claude-4-5-sonnet'],\n 'claude-3-7-sonnet-20250219': models['claude-3-7-sonnet'],\n 'claude-3-5-sonnet-20241022': models['claude-3-5-sonnet-20241022'],\n 'gpt-4.1': models['gpt-4.1'],\n 'gpt-4': models['gpt-4'],\n 'gpt-4o': models['gpt-4o'],\n o3: models['o3'],\n 'o3-mini': models['o3-mini'],\n 'o4-mini': models['o4-mini'],\n 'gpt-5': models['gpt-5'],\n 'gpt-5-mini': models['gpt-5-mini'],\n 'glm-4.6': models['glm-4.6'],\n 'kimi-k2-thinking': models['kimi-k2-thinking'],\n 'kimi-k2-turbo-preview': models['kimi-k2-turbo-preview'],\n },\n createModel(name, provider) {\n const apiKey = getProviderApiKey(provider);\n return createAihubmix(\n withProxyConfig(\n {\n apiKey,\n headers: {\n 'APP-Code': 'TPQW7551',\n },\n },\n provider,\n ),\n ).chat(name);\n },\n },\n openrouter: {\n id: 'openrouter',\n source: 'built-in',\n env: ['OPENROUTER_API_KEY', 'OPEN_ROUTER_API_KEY'],\n name: 'OpenRouter',\n doc: 'https://openrouter.ai/docs/models',\n models: {\n 'anthropic/claude-3.5-sonnet': models['claude-3-5-sonnet-20241022'],\n 'anthropic/claude-3.7-sonnet': models['claude-3-7-sonnet'],\n 'anthropic/claude-sonnet-4': models['claude-4-sonnet'],\n 'anthropic/claude-sonnet-4.5': models['claude-4-5-sonnet'],\n 'anthropic/claude-haiku-4.5': models['claude-haiku-4-5'],\n 'anthropic/claude-opus-4': models['claude-4-opus'],\n 'anthropic/claude-opus-4.1': models['claude-4.1-opus'],\n 'anthropic/claude-opus-4.5': models['claude-opus-4-5'],\n 'anthropic/claude-sonnet-4.6': models['claude-sonnet-4-6'],\n 'anthropic/claude-opus-4.6': models['claude-opus-4-6'],\n 'deepseek/deepseek-r1-0528': models['deepseek-r1-0528'],\n 'deepseek/deepseek-chat-v3-0324': models['deepseek-v3-0324'],\n 'deepseek/deepseek-chat-v3.1': models['deepseek-v3-1'],\n 'deepseek/deepseek-v3.1-terminus': models['deepseek-v3-1-terminus'],\n 'deepseek/deepseek-v3.2-exp': models['deepseek-v3-2-exp'],\n 'deepseek/deepseek-v3.2': models['deepseek-v3.2'],\n 'deepseek/deepseek-v3.2-speciale': models['deepseek-v3.2-speciale'],\n 'openai/gpt-4.1': models['gpt-4.1'],\n 'openai/gpt-4': models['gpt-4'],\n 'openai/gpt-4o': models['gpt-4o'],\n 'openai/o3': models['o3'],\n 'openai/o3-pro': models['o3-pro'],\n 'openai/o3-mini': models['o3-mini'],\n 'openai/o4-mini': models['o4-mini'],\n 'openai/gpt-oss-120b': models['gpt-oss-120b'],\n 'openai/gpt-5.1-codex': models['gpt-5.1-codex'],\n 'openai/gpt-5.1-codex-mini': models['gpt-5.1-codex-mini'],\n 'openai/gpt-5.1-codex-max': models['gpt-5.1-codex-max'],\n 'openai/gpt-5.1': models['gpt-5.1'],\n 'openai/gpt-5': models['gpt-5'],\n 'openai/gpt-5-mini': models['gpt-5-mini'],\n 'openai/gpt-5-codex': models['gpt-5-codex'],\n 'openai/gpt-5.2': models['gpt-5.2'],\n 'openai/gpt-5.2-pro': models['gpt-5.2-pro'],\n 'openai/gpt-5.2-codex': models['gpt-5.2-codex'],\n 'openai/gpt-5.3-codex': models['gpt-5.3-codex'],\n 'google/gemini-3-flash-preview': models['gemini-3-flash-preview'],\n 'google/gemini-3-pro-preview': models['gemini-3-pro-preview'],\n 'moonshotai/kimi-k2': models['kimi-k2'],\n 'moonshotai/kimi-k2-0905': models['kimi-k2-0905'],\n 'moonshotai/kimi-k2-thinking': models['kimi-k2-thinking'],\n 'moonshotai/kimi-k2.5': models['kimi-k2.5'],\n 'qwen/qwen3-coder': models['qwen3-coder-480b-a35b-instruct'],\n 'qwen/qwen3-max': models['qwen3-max'],\n 'x-ai/grok-code-fast-1': models['grok-code-fast-1'],\n 'x-ai/grok-4': models['grok-4'],\n 'x-ai/grok-4-fast': models['grok-4-fast'],\n 'x-ai/grok-4.1-fast': models['grok-4.1-fast'],\n 'z-ai/glm-4.5': models['glm-4.5'],\n 'z-ai/glm-4.5v': models['glm-4.5v'],\n 'z-ai/glm-4.6': models['glm-4.6'],\n 'z-ai/glm-4.6v': models['glm-4.6v'],\n 'z-ai/glm-4.7': models['glm-4.7'],\n 'z-ai/glm-5': models['glm-5'],\n 'minimax/minimax-m2': models['minimax-m2'],\n 'minimax/minimax-m2.5': models['minimax-m2.5'],\n 'openrouter/sherlock-dash-alpha': models['sherlock-dash-alpha'],\n 'openrouter/sherlock-think-alpha': models['sherlock-think-alpha'],\n 'xiaomi/mimo-v2-flash:free': models['mimo-v2-flash'],\n },\n createModel(name, provider) {\n const baseURL = getProviderBaseURL(provider);\n const apiKey = getProviderApiKey(provider);\n return createOpenRouter(\n withProxyConfig(\n {\n apiKey,\n baseURL,\n },\n provider,\n ),\n ).chat(name) as unknown as LanguageModelV3;\n },\n },\n moonshotai: {\n id: 'moonshotai',\n source: 'built-in',\n env: ['MOONSHOT_API_KEY'],\n name: 'Moonshot',\n api: 'https://api.moonshot.ai/v1',\n doc: 'https://platform.moonshot.ai/docs/api/chat',\n models: {\n 'kimi-k2-0905-preview': models['kimi-k2-0905'],\n 'kimi-k2-turbo-preview': models['kimi-k2-turbo-preview'],\n 'kimi-k2-thinking': models['kimi-k2-thinking'],\n 'kimi-k2-thinking-turbo': models['kimi-k2-thinking-turbo'],\n 'kimi-k2.5': models['kimi-k2.5'],\n },\n createModel: defaultModelCreator,\n },\n 'moonshotai-cn': {\n id: 'moonshotai-cn',\n source: 'built-in',\n env: ['MOONSHOT_API_KEY'],\n name: 'MoonshotCN',\n api: 'https://api.moonshot.cn/v1',\n doc: 'https://platform.moonshot.cn/docs/api/chat',\n models: {\n 'kimi-k2-0905-preview': models['kimi-k2-0905'],\n 'kimi-k2-turbo-preview': models['kimi-k2-turbo-preview'],\n 'kimi-k2-thinking': models['kimi-k2-thinking'],\n 'kimi-k2-thinking-turbo': models['kimi-k2-thinking-turbo'],\n 'kimi-k2.5': models['kimi-k2.5'],\n },\n createModel: defaultModelCreator,\n },\n groq: {\n id: 'groq',\n source: 'built-in',\n env: ['GROQ_API_KEY'],\n name: 'Groq',\n api: 'https://api.groq.com/openai/v1',\n doc: 'https://console.groq.com/docs/models',\n models: {},\n createModel: defaultModelCreator,\n },\n siliconflow: {\n id: 'siliconflow',\n source: 'built-in',\n env: ['SILICONFLOW_API_KEY'],\n name: 'SiliconFlow',\n api: 'https://api.siliconflow.com/v1',\n doc: 'https://docs.siliconflow.com',\n models: {\n 'Qwen/Qwen3-235B-A22B-Instruct-2507': models['qwen3-235b-a22b-07-25'],\n 'Qwen/Qwen3-Coder-480B-A35B-Instruct':\n models['qwen3-coder-480b-a35b-instruct'],\n 'moonshotai/Kimi-K2-Instruct-0905': models['kimi-k2-0905'],\n 'moonshotai/Kimi-K2-Instruct': models['kimi-k2'],\n 'deepseek-ai/DeepSeek-R1': models['deepseek-r1-0528'],\n 'deepseek-ai/DeepSeek-V3.1': models['deepseek-v3-1'],\n 'deepseek-ai/DeepSeek-V3': models['deepseek-v3-0324'],\n 'zai-org/GLM-4.5': models['glm-4.5'],\n },\n createModel: defaultModelCreator,\n },\n 'siliconflow-cn': {\n id: 'siliconflow-cn',\n source: 'built-in',\n env: ['SILICONFLOW_API_KEY'],\n name: 'SiliconFlow CN',\n api: 'https://api.siliconflow.cn/v1',\n doc: 'https://docs.siliconflow.cn',\n models: {\n 'Qwen/Qwen3-235B-A22B-Instruct-2507': models['qwen3-235b-a22b-07-25'],\n 'Qwen/Qwen3-Coder-480B-A35B-Instruct':\n models['qwen3-coder-480b-a35b-instruct'],\n 'moonshotai/Kimi-K2-Instruct-0905': models['kimi-k2-0905'],\n 'moonshotai/Kimi-K2-Instruct': models['kimi-k2'],\n 'deepseek-ai/DeepSeek-R1': models['deepseek-r1-0528'],\n 'deepseek-ai/DeepSeek-V3.1': models['deepseek-v3-1'],\n 'deepseek-ai/DeepSeek-V3': models['deepseek-v3-0324'],\n 'zai-org/GLM-4.5': models['glm-4.5'],\n 'Pro/moonshotai/Kimi-K2.5': models['kimi-k2-5'],\n 'Pro/zai-org/GLM-5': models['glm-5'],\n 'Pro/zai-org/GLM-4.7': models['glm-4.7'],\n 'Pro/MiniMaxAI/MiniMax-M2.5': models['minimax-m2.5'],\n 'Pro/deepseek-ai/DeepSeek-V3.2': models['deepseek-v3.2'],\n },\n createModel: defaultModelCreator,\n },\n modelscope: {\n id: 'modelscope',\n source: 'built-in',\n env: ['MODELSCOPE_API_KEY'],\n name: 'ModelScope',\n api: 'https://api-inference.modelscope.cn/v1',\n doc: 'https://modelscope.cn/docs/model-service/API-Inference/intro',\n models: {\n 'Qwen/Qwen3-Coder-480B-A35B-Instruct':\n models['qwen3-coder-480b-a35b-instruct'],\n 'Qwen/Qwen3-235B-A22B-Instruct-2507': models['qwen3-235b-a22b-07-25'],\n 'ZhipuAI/GLM-4.5': models['glm-4.5'],\n 'ZhipuAI/GLM-4.5V': models['glm-4.5v'],\n 'ZhipuAI/GLM-4.6': models['glm-4.6'],\n 'ZhipuAI/GLM-5': models['glm-5'],\n 'deepseek-ai/DeepSeek-V3.2': models['deepseek-v3.2'],\n 'deepseek-ai/DeepSeek-V3.2-Speciale': models['deepseek-v3.2-speciale'],\n },\n createModel: defaultModelCreator,\n },\n volcengine: {\n id: 'volcengine',\n source: 'built-in',\n env: ['VOLCENGINE_API_KEY'],\n name: 'VolcEngine',\n api: 'https://ark.cn-beijing.volces.com/api/v3',\n doc: 'https://www.volcengine.com/docs/82379/1330310',\n models: {\n 'deepseek-v3-1-250821': models['deepseek-v3-1'],\n 'deepseek-v3-1-terminus': models['deepseek-v3-1-terminus'],\n 'doubao-seed-1-6-250615': models['doubao-seed-1.6'],\n 'kimi-k2-250905': models['kimi-k2-0905'],\n },\n createModel: defaultModelCreator,\n },\n 'zai-coding-plan': {\n id: 'zai-coding-plan',\n source: 'built-in',\n env: ['ZHIPU_API_KEY'],\n name: 'Z.AI Coding Plan',\n api: 'https://api.z.ai/api/coding/paas/v4',\n doc: 'https://docs.z.ai/devpack/overview',\n models: {\n 'glm-4.5-flash': models['glm-4.5-flash'],\n 'glm-4.5': models['glm-4.5'],\n 'glm-4.5-air': models['glm-4.5-air'],\n 'glm-4.5v': models['glm-4.5v'],\n 'glm-4.6': models['glm-4.6'],\n 'glm-4.6v': models['glm-4.6v'],\n 'glm-4.7': models['glm-4.7'],\n 'glm-5': models['glm-5'],\n },\n createModel: defaultModelCreator,\n },\n 'zhipuai-coding-plan': {\n id: 'zhipuai-coding-plan',\n source: 'built-in',\n env: ['ZHIPU_API_KEY'],\n name: 'Zhipu AI Coding Plan',\n api: 'https://open.bigmodel.cn/api/coding/paas/v4',\n doc: 'https://docs.bigmodel.cn/cn/coding-plan/overview',\n models: {\n 'glm-4.6': models['glm-4.6'],\n 'glm-4.5v': models['glm-4.5v'],\n 'glm-4.5-air': models['glm-4.5-air'],\n 'glm-4.5': models['glm-4.5'],\n 'glm-4.5-flash': models['glm-4.5-flash'],\n 'glm-4.6v': models['glm-4.6v'],\n 'glm-4.7': models['glm-4.7'],\n 'glm-5': models['glm-5'],\n },\n createModel: defaultModelCreator,\n },\n 'bailian-coding-plan': {\n id: 'bailian-coding-plan',\n source: 'built-in',\n env: ['BAILIAN_CODING_API_KEY'],\n name: 'BaiLian Coding Plan',\n api: 'https://coding.dashscope.aliyuncs.com/apps/anthropic/v1',\n doc: 'https://www.aliyun.com/benefit/scene/codingplan',\n apiFormat: 'anthropic',\n models: {\n 'qwen3.5-plus': models['qwen3-5-plus'],\n 'qwen3-max-2026-01-23': models['qwen3-max'],\n 'qwen3-coder-next': models['qwen3-coder-plus'],\n 'qwen3-coder-plus': models['qwen3-coder-plus'],\n 'MiniMax-M2.5': models['minimax-m2.5'],\n 'glm-5': models['glm-5'],\n 'glm-4.7': models['glm-4.7'],\n 'kimi-k2.5': models['kimi-k2-5'],\n },\n createModel: defaultAnthropicModelCreator,\n },\n zhipuai: {\n id: 'zhipuai',\n source: 'built-in',\n env: ['ZHIPU_API_KEY'],\n name: 'Zhipu AI',\n api: 'https://open.bigmodel.cn/api/paas/v4',\n doc: 'https://docs.z.ai/guides/overview/pricing',\n models: {\n 'glm-4.6': models['glm-4.6'],\n 'glm-4.5v': models['glm-4.5v'],\n 'glm-4.5-air': models['glm-4.5-air'],\n 'glm-4.5': models['glm-4.5'],\n 'glm-4.5-flash': models['glm-4.5-flash'],\n 'glm-4.6v': models['glm-4.6v'],\n 'glm-4.7': models['glm-4.7'],\n 'glm-5': models['glm-5'],\n },\n createModel: defaultModelCreator,\n },\n zenmux: {\n id: 'zenmux',\n source: 'built-in',\n env: ['ZENMUX_API_KEY'],\n name: 'ZenMux',\n api: 'https://zenmux.ai/api/v1',\n doc: 'https://docs.zenmux.ai/',\n models: {\n 'inclusionai/ling-1t': models['ling-1t'],\n 'inclusionai/ring-1t': models['ring-1t'],\n 'inclusionai/ring-flash-2.0': models['ring-flash-2.0'],\n 'inclusionai/ling-flash-2.0': models['ling-flash-2.0'],\n 'inclusionai/ring-mini-2.0': models['ring-mini-2.0'],\n 'inclusionai/ling-mini-2.0': models['ling-mini-2.0'],\n 'google/gemini-3-flash-preview': models['gemini-3-flash-preview'],\n 'google/gemini-3-pro-preview': models['gemini-3-pro-preview'],\n 'openai/gpt-5.1': models['gpt-5.1'],\n 'openai/gpt-5.1-codex': models['gpt-5.1-codex'],\n 'openai/gpt-5.1-codex-mini': models['gpt-5.1-codex-mini'],\n 'openai/gpt-5.2': models['gpt-5.2'],\n 'openai/gpt-5.2-pro': models['gpt-5.2-pro'],\n 'openai/gpt-5.2-codex': models['gpt-5.2-codex'],\n 'openai/gpt-5.3-codex': models['gpt-5.3-codex'],\n 'anthropic/claude-sonnet-4.5': models['claude-4-5-sonnet'],\n 'anthropic/claude-opus-4.1': models['claude-4.1-opus'],\n 'anthropic/claude-opus-4.5': models['claude-opus-4-5'],\n 'anthropic/claude-opus-4.6': models['claude-opus-4-6'],\n 'z-ai/glm-4.6': models['glm-4.6'],\n 'z-ai/glm-4.6v': models['glm-4.6v'],\n 'z-ai/glm-4.6v-flash': models['glm-4.6v'],\n 'z-ai/glm-4.7': models['glm-4.7'],\n 'z-ai/glm-5': models['glm-5'],\n 'deepseek/deepseek-v3.2-speciale': models['deepseek-v3.2-speciale'],\n 'deepseek/deepseek-chat': models['deepseek-v3-2-exp'],\n 'deepseek/deepseek-reasoner': models['deepseek-r1-0528'],\n 'minimax/minimax-m2.5': models['minimax-m2.5'],\n },\n headers: {\n 'X-Title': 'OriCore',\n 'HTTP-Referer': 'https://github.com/lyw405/oricore',\n },\n },\n minimax: {\n id: 'minimax',\n source: 'built-in',\n env: ['MINIMAX_API_KEY'],\n name: 'Minimax',\n api: 'https://api.minimaxi.io/anthropic/v1',\n doc: 'https://platform.minimaxi.io/docs/guides/quickstart',\n models: {\n 'minimax-m2': models['minimax-m2'],\n 'minimax-m2.1': models['minimax-m2.1'],\n 'minimax-m2.5': models['minimax-m2.5'],\n 'minimax-m2.7': models['minimax-m2.7'],\n },\n createModel(name, provider) {\n const baseURL = getProviderBaseURL(provider);\n const apiKey = getProviderApiKey(provider);\n return createAnthropic(\n withProxyConfig({ baseURL, apiKey }, provider),\n ).chat(name);\n },\n },\n 'minimax-cn': {\n id: 'minimax-cn',\n source: 'built-in',\n env: ['MINIMAX_API_KEY'],\n name: 'Minimax CN',\n api: 'https://api.minimaxi.com/anthropic/v1',\n doc: 'https://platform.minimaxi.com/docs/guides/quickstart',\n models: {\n 'minimax-m2': models['minimax-m2'],\n 'minimax-m2.1': models['minimax-m2.1'],\n 'minimax-m2.5': models['minimax-m2.5'],\n 'minimax-m2.7': models['minimax-m2.7'],\n },\n createModel(name, provider) {\n const baseURL = getProviderBaseURL(provider);\n const apiKey = getProviderApiKey(provider);\n return createAnthropic(\n withProxyConfig({ baseURL, apiKey }, provider),\n ).chat(name);\n },\n },\n xiaomi: {\n id: 'xiaomi',\n source: 'built-in',\n env: ['MIMO_API_KEY'],\n name: 'Xiaomi Mimo',\n api: 'https://api.xiaomimimo.com/v1',\n doc: 'https://platform.xiaomimimo.com/',\n models: {\n 'mimo-v2-flash': models['mimo-v2-flash'],\n },\n createModel: createModelCreatorCompatible({}),\n },\n cerebras: {\n id: 'cerebras',\n source: 'built-in',\n env: ['CEREBRAS_API_KEY'],\n name: 'Cerebras',\n doc: 'https://cerebras.ai/docs',\n models: {\n 'zai-glm-4.6': models['glm-4.6'],\n 'zai-glm-4.7': {\n ...models['glm-4.7'],\n limit: { context: 64000, output: 40000 },\n },\n 'gpt-oss-120b': {\n ...models['gpt-oss-120b'],\n limit: { context: 65000, output: 32000 },\n },\n },\n headers: {\n 'X-Cerebras-3rd-Party-Integration': 'OriCore',\n },\n createModel(name, provider) {\n const apiKey = getProviderApiKey(provider);\n return createCerebras(\n withProxyConfig(\n {\n apiKey,\n },\n provider,\n ),\n )(name);\n },\n },\n huggingface: {\n id: 'huggingface',\n source: 'built-in',\n env: ['HUGGINGFACE_API_KEY'],\n name: 'Hugging Face',\n doc: 'https://huggingface.co/docs/inference-providers/index',\n models: {\n 'zai-org/GLM-4.7': models['glm-4.7'],\n 'XiaomiMiMo/MiMo-V2-Flash': models['mimo-v2-flash'],\n 'Qwen/Qwen3-Coder-480B-A35B-Instruct':\n models['qwen3-coder-480b-a35b-instruct'],\n },\n createModel(name, provider) {\n const apiKey = getProviderApiKey(provider);\n return createHuggingFace({\n apiKey,\n }).languageModel(name) as unknown as LanguageModelV3;\n },\n },\n poe: {\n id: 'poe',\n source: 'built-in',\n env: ['POE_API_KEY'],\n name: 'Poe',\n api: 'https://api.poe.com/v1',\n doc: 'https://poe.com',\n models: {\n 'Claude-Opus-4.5': models['claude-4-opus'],\n 'Claude-Sonnet-4.5': models['claude-4-5-sonnet'],\n 'Gemini-3-Pro': models['gemini-3-pro-preview'],\n 'Gemini-2.5-Pro': models['gemini-2.5-pro'],\n 'Gemini-2.5-Flash': models['gemini-2.5-flash'],\n 'GPT-5.1': models['gpt-5.1'],\n 'GPT-5.1-Codex': models['gpt-5.1-codex'],\n 'Grok-4.1-Fast-Non-Reasoning': {\n ...models['grok-4.1-fast'],\n reasoning: false,\n },\n 'Grok-4.1-Fast': models['grok-4.1-fast'],\n },\n createModel: defaultModelCreator,\n },\n nvidia: {\n id: 'nvidia',\n source: 'built-in',\n env: ['NVIDIA_API_KEY'],\n name: 'NVIDIA',\n api: 'https://integrate.api.nvidia.com/v1/',\n doc: 'https://nvidia.com/',\n models: {\n 'z-ai/glm4.7': models['glm-4.7'],\n 'minimaxai/minimax-m2.1': models['minimax-m2.1'],\n 'moonshotai/kimi-k2-thinking': models['kimi-k2-thinking'],\n 'openai/gpt-oss-120b': models['gpt-oss-120b'],\n 'qwen/qwen3-coder-480b-a35b-instruct':\n models['qwen3-coder-480b-a35b-instruct'],\n },\n createModel: createModelCreatorCompatible({\n middlewares: [\n extractReasoningMiddleware({\n tagName: 'think',\n }) as LanguageModelV3Middleware,\n ],\n }),\n },\n canopywave: {\n id: 'canopywave',\n source: 'built-in',\n env: ['CANOPYWAVE_API_KEY'],\n name: 'CanopyWave',\n api: 'https://inference.canopywave.io/v1',\n doc: 'https://canopywave.io/',\n models: {\n 'minimax/minimax-m2.1': models['minimax-m2.1'],\n 'zai/glm-4.7': models['glm-4.7'],\n 'moonshotai/kimi-k2-thinking': models['kimi-k2-thinking'],\n 'moonshotai/kimi-k2.5': models['kimi-k2.5'],\n 'deepseek/deepseek-chat-v3.2': models['deepseek-v3-2-exp'],\n 'openai/gpt-oss-120b': models['gpt-oss-120b'],\n 'xiaomimimo/mimo-v2-flash': models['mimo-v2-flash'],\n },\n createModel: defaultModelCreator,\n },\n modelwatch: {\n id: 'modelwatch',\n source: 'built-in',\n env: ['MODELWATCH_API_KEY'],\n name: 'ModelWatch',\n api: 'https://hub.modelwatch.dev/v1/',\n doc: 'https://hub.modelwatch.dev/',\n models: {\n 'qwen3-coder-plus': models['qwen3-coder-plus'],\n 'glm-4.7': models['glm-4.7'],\n 'gemini-2.5-flash': models['gemini-2.5-flash'],\n 'gemini-3-flash': models['gemini-3-flash-preview'],\n 'gemini-3-pro-preview': models['gemini-3-pro-preview'],\n 'claude-4-5-sonnet': models['claude-4-5-sonnet'],\n 'claude-haiku-4-5': models['claude-haiku-4-5'],\n 'claude-opus-4-5': models['claude-opus-4-5'],\n 'claude-sonnet-4-6': models['claude-sonnet-4-6'],\n 'claude-opus-4-6': models['claude-opus-4-6'],\n 'gpt-5.1': models['gpt-5.1'],\n 'gpt-5.1-codex-max': models['gpt-5.1-codex-max'],\n 'gpt-5.1-codex': models['gpt-5.1-codex'],\n 'gpt-5.1-codex-mini': models['gpt-5.1-codex-mini'],\n 'gpt-5.2': models['gpt-5.2'],\n 'gpt-5.2-codex': models['gpt-5.2-codex'],\n 'gpt-5.3-codex': models['gpt-5.3-codex'],\n },\n createModel: (name, provider) => {\n if (name.startsWith('claude-') || name.startsWith('gemini-')) {\n return defaultAnthropicModelCreator(name, provider);\n }\n if (name.startsWith('gpt-')) {\n return openaiModelResponseCreator(name, provider);\n }\n return defaultModelCreator(name, provider);\n },\n },\n kilo: {\n id: 'kilo',\n source: 'built-in',\n env: ['KILO_API_KEY'],\n name: 'Kilo',\n api: 'https://api.kilo.ai/api/gateway',\n doc: 'https://kilo.ai',\n apiFormat: 'openai',\n models: {\n 'z-ai/glm-5': models['glm-5'],\n 'z-ai/glm-5:free': models['glm-5'],\n 'z-ai/glm-4.7': models['glm-4.7'],\n 'anthropic/claude-opus-4.6': models['claude-opus-4-6'],\n 'anthropic/claude-sonnet-4.6': models['claude-sonnet-4-6'],\n 'anthropic/claude-haiku-4.5': models['claude-haiku-4-5'],\n 'anthropic/claude-sonnet-4.5': models['claude-4-5-sonnet'],\n 'google/gemini-3-flash-preview': models['gemini-3-flash-preview'],\n 'google/gemini-3-pro-preview': models['gemini-3-pro-preview'],\n 'minimax/minimax-m2.5:free': models['minimax-m2.5'],\n 'minimax/minimax-m2.5': models['minimax-m2.5'],\n 'moonshotai/kimi-k2.5': models['kimi-k2-5'],\n },\n createModel: (name, provider) => {\n if (name.includes('claude-')) {\n return defaultAnthropicModelCreator(name, provider);\n }\n if (name.includes('gemini-')) {\n return defaultAnthropicModelCreator(name, provider);\n }\n return defaultModelCreator(name, provider);\n },\n },\n};\n","let lastSelectedIndex = -1;\n\nexport function rotateApiKey(apiKey: string): string {\n if (!apiKey || !apiKey.includes(',')) {\n return apiKey;\n }\n\n const keys = apiKey.split(',').map((key) => key.trim());\n if (keys.length === 0) {\n return '';\n }\n\n let randomIndex: number;\n do {\n randomIndex = Math.floor(Math.random() * keys.length);\n } while (keys.length > 1 && randomIndex === lastSelectedIndex);\n\n lastSelectedIndex = randomIndex;\n return keys[randomIndex];\n}\n\nexport function resetRotationIndex(): void {\n lastSelectedIndex = -1;\n}\n","import type { Provider } from './types';\nimport { rotateApiKey } from '../../utils/apiKeyRotation';\n\n/**\n * Get the base URL for a provider.\n * Priority: provider.options.baseURL > provider.apiEnv > provider.api\n */\nexport function getProviderBaseURL(provider: Provider): string | undefined {\n if (provider.options?.baseURL) {\n return provider.options.baseURL;\n }\n let api = provider.api;\n for (const env of provider.apiEnv || []) {\n if (process.env[env]) {\n api = process.env[env];\n break;\n }\n }\n return api;\n}\n\n/**\n * Strip quotes from the beginning and end of a string.\n * Handles both single quotes (') and double quotes (\").\n */\nfunction stripQuotes(value: string): string {\n if (!value || value.length < 2) {\n return value;\n }\n\n const firstChar = value[0];\n const lastChar = value[value.length - 1];\n\n // Check if both ends have matching quotes\n if (\n (firstChar === '\"' && lastChar === '\"') ||\n (firstChar === \"'\" && lastChar === \"'\")\n ) {\n return value.slice(1, -1);\n }\n\n return value;\n}\n\n/**\n * Get the API key for a provider.\n * Priority: provider.options.apiKey > provider.env\n *\n * Automatically strips quotes from both ends of the API key\n * to handle cases where users accidentally include them.\n */\nexport function getProviderApiKey(provider: Provider): string {\n const apiKey = (() => {\n if (provider.options?.apiKey) {\n const key = provider.options.apiKey;\n // Strip quotes if present (handles user input like 'key' or \"key\")\n return stripQuotes(key);\n }\n const envs = provider.env || [];\n for (const env of envs) {\n if (process.env[env]) {\n const key = process.env[env];\n // Strip quotes if present (handles .env files with KEY='value')\n return stripQuotes(key);\n }\n }\n return '';\n })();\n const key = rotateApiKey(apiKey);\n return key;\n}\n","/**\n * HTTP Proxy utilities for AI model providers\n * Handles proxy configuration and custom fetch implementation\n */\n\nimport type { Dispatcher, RequestInit as UndiciRequestInit } from 'undici';\nimport { ProxyAgent } from 'undici';\n\n// Module-level cache for ProxyAgent instances (one per unique proxy URL)\nconst proxyAgents = new Map<string, ProxyAgent>();\n\n// Module-level cache for undici fetch\nlet undiciFetch: typeof import('undici').fetch | null = null;\n\n/**\n * Validate proxy URL format\n * @param proxyUrl - Proxy URL to validate\n * @returns true if valid, false otherwise\n */\nfunction isValidProxyUrl(proxyUrl: string): boolean {\n try {\n const url = new URL(proxyUrl);\n // Support http, https, socks5, socks4 protocols\n return ['http:', 'https:', 'socks5:', 'socks4:'].includes(url.protocol);\n } catch {\n return false;\n }\n}\n\n/**\n * Create a custom fetch function that uses the specified proxy\n * This wraps undici's fetch with the ProxyAgent\n *\n * Why needed: Bun's native fetch doesn't support HTTP_PROXY env vars,\n * so we use undici's fetch with ProxyAgent to handle proxy requests\n *\n * @param proxyUrl - Proxy URL (e.g., http://127.0.0.1:7890 or socks5://127.0.0.1:1080)\n * @returns A fetch-compatible function that routes requests through the configured proxy\n * @example\n * const proxyFetch = createProxyFetch('http://127.0.0.1:7890');\n * await proxyFetch('https://api.openai.com/v1/models');\n */\nexport function createProxyFetch(proxyUrl: string) {\n // Validate proxy URL format\n if (!isValidProxyUrl(proxyUrl)) {\n console.warn(\n `[Proxy] Invalid proxy URL format: ${proxyUrl}. Expected format: http://host:port, https://host:port, or socks5://host:port`,\n );\n return fetch;\n }\n\n // Get or create ProxyAgent for this URL\n let proxyAgent = proxyAgents.get(proxyUrl);\n\n if (!proxyAgent) {\n try {\n proxyAgent = new ProxyAgent(proxyUrl);\n proxyAgents.set(proxyUrl, proxyAgent);\n } catch (error) {\n console.error(\n `[Proxy] Failed to create ProxyAgent for ${proxyUrl}:`,\n error,\n );\n // Return native fetch as fallback\n return fetch;\n }\n }\n\n // Return a fetch-compatible function\n return async (input: string | URL | Request, init?: RequestInit) => {\n // Lazy load undici fetch (cached at module level)\n if (!undiciFetch) {\n undiciFetch = (await import('undici')).fetch;\n }\n\n // Handle different input types properly\n let url: string;\n let requestInit: RequestInit | undefined = init;\n\n if (input instanceof Request) {\n // Extract all request properties, not just URL\n url = input.url;\n requestInit = {\n method: input.method,\n headers: input.headers,\n body: input.body,\n ...init, // Allow overrides\n };\n } else if (input instanceof URL) {\n url = input.toString();\n } else {\n url = String(input);\n }\n\n // undici fetch with ProxyAgent dispatcher\n // Use undici's RequestInit type to avoid compatibility issues\n return undiciFetch(url, {\n ...requestInit,\n dispatcher: proxyAgent,\n } as UndiciRequestInit);\n };\n}\n","import type { Provider } from './types';\nimport { createProxyFetch } from '../../utils/proxy';\n\n/**\n * Inject proxy support into AI SDK configuration.\n * Priority: Provider-level proxy > Global proxy\n * Also merges provider-level headers with config headers\n *\n * @param config - SDK configuration object\n * @param provider - Provider configuration\n * @returns Config with proxy fetch injected if proxy is configured\n */\nfunction withProxyConfig<T extends Record<string, any>>(\n config: T,\n provider: Provider,\n): T {\n const proxyUrl = provider.options?.httpProxy;\n const providerHeaders = provider.headers;\n const optionsHeaders = provider.options?.headers;\n\n const result: any = {\n ...config,\n };\n\n // Merge headers: provider.headers + provider.options.headers + config.headers\n if (providerHeaders || optionsHeaders || config.headers) {\n result.headers = {\n ...(providerHeaders || {}),\n ...(optionsHeaders || {}),\n ...(config.headers || {}),\n };\n }\n\n if (proxyUrl) {\n const proxyFetch = createProxyFetch(proxyUrl);\n result.fetch = proxyFetch;\n }\n\n return result;\n}\n\nexport { withProxyConfig };\n","import type { ModelAlias } from './types';\n\n// value format: provider/model\nexport const modelAlias: ModelAlias = {\n flash: 'google/gemini-2.5-flash',\n gemini: 'google/gemini-3-pro-preview',\n glm: 'openai/glm-4.7',\n grok: 'xai/grok-4-1-fast',\n sonnet: 'anthropic/claude-sonnet-4-5-20250929',\n haiku: 'anthropic/claude-haiku-4-5',\n opus: 'anthropic/claude-opus-4-5',\n};\n","import assert from 'assert';\nimport defu from 'defu';\nimport type { LanguageModelV3 } from '@ai-sdk/provider';\nimport type { Context } from '../context';\nimport { ConfigManager, type ProviderConfig } from '../config';\nimport { PluginHookType } from '../plugin';\nimport type { Model, Provider, ProvidersMap, ModelAlias, ModelInfo } from './types';\nimport { providers, defaultModelCreator, defaultAnthropicModelCreator, openaiModelResponseCreator } from './providers';\nimport { modelAlias } from './aliases';\nimport type { ModelMap } from './types';\nimport { models } from './models';\n\n// ApiFormat type for provider API formats\ntype ApiFormat = 'anthropic' | 'openai' | 'responses';\n\n/**\n * Transform model reasoning capabilities into provider-specific variants\n * This function generates thinking/reasoning configurations for different effort levels\n */\nfunction transformVariants(model: Model, provider: Provider): Record<string, any> {\n if (!model.reasoning) {\n return {};\n }\n\n const id = (model.id || '').toLowerCase();\n\n // These models use their own reasoning mechanism without variants\n // bailian-coding-plan handles kimi/minimax/glm with special on/off toggle\n if (provider.id === 'bailian-coding-plan') {\n if (id.includes('kimi') || id.includes('minimax') || id.includes('glm')) {\n return {\n on: {\n thinking: {\n type: 'enabled' as const,\n },\n },\n };\n }\n }\n\n if (\n id.includes('deepseek') ||\n id.includes('minimax') ||\n id.includes('glm') ||\n id.includes('mistral') ||\n // id.includes(\"kimi\") ||\n id.includes('grok')\n ) {\n return {};\n }\n\n // Special provider handling\n if (provider.id === 'xiaomi') {\n return {\n on: {\n thinking: {\n type: 'enabled',\n },\n },\n };\n }\n\n if (provider.id === 'xai') {\n return {\n low: {\n // https://ai-sdk.dev/providers/ai-sdk-providers/xai#provider-options\n // Only supported by grok-3-mini and grok-3-mini-fast models?\n // reasoningEffort: 'low',\n },\n };\n }\n\n if (['openrouter', 'zenmux', 'wanqing'].includes(provider.id)) {\n return {\n low: {\n reasoning: {\n enabled: true,\n effort: 'low' as const,\n },\n },\n medium: {\n reasoning: {\n enabled: true,\n effort: 'medium' as const,\n },\n },\n high: {\n reasoning: {\n enabled: true,\n max_tokens: 31999,\n },\n },\n };\n }\n\n if (provider.id === 'modelwatch' && id.startsWith('gpt-')) {\n return {\n low: {\n reasoningEffort: 'low' as const,\n reasoningSummary: 'detailed',\n },\n medium: {\n reasoningEffort: 'medium' as const,\n reasoningSummary: 'detailed',\n },\n high: {\n reasoningEffort: 'high' as const,\n reasoningSummary: 'detailed',\n },\n };\n }\n\n if (provider.id === 'modelwatch' && id.startsWith('claude-')) {\n return {\n low: {\n thinking: {\n type: 'enabled' as const,\n budgetTokens: 1024,\n },\n },\n high: {\n thinking: {\n type: 'enabled' as const,\n budgetTokens: 31999,\n },\n },\n };\n }\n\n if (id.startsWith('gemini-')) {\n return {\n low: {\n thinkingConfig: {\n thinkingBudget: 1024,\n includeThoughts: true,\n },\n },\n high: {\n thinkingConfig: {\n thinkingBudget: 31999,\n includeThoughts: true,\n },\n },\n };\n }\n\n if (provider.id === 'google') {\n return {\n low: {\n thinkingConfig: {\n thinkingBudget: 1024,\n includeThoughts: true,\n },\n },\n high: {\n thinkingConfig: {\n thinkingBudget: 31999,\n includeThoughts: true,\n },\n },\n };\n }\n\n // OpenAI-compatible format: low, medium, high reasoning efforts\n if (provider.apiFormat === 'openai') {\n const WIDELY_SUPPORTED_EFFORTS = ['low', 'medium', 'high'];\n return Object.fromEntries(\n WIDELY_SUPPORTED_EFFORTS.map((effort) => [\n effort,\n {\n reasoningEffort: effort,\n },\n ]),\n );\n }\n\n // Anthropic format: high and max efforts with budget tokens\n if (provider.apiFormat === 'anthropic') {\n return {\n high: {\n thinking: {\n type: 'enabled',\n budgetTokens: Math.min(\n 16_000,\n Math.floor(model.limit.output / 2 - 1),\n ),\n },\n },\n max: {\n thinking: {\n type: 'enabled',\n budgetTokens: Math.min(31_999, model.limit.output - 1),\n },\n },\n };\n }\n\n return {};\n}\n\n/**\n * Normalize a model definition by merging with base model info and adding variants\n */\nfunction normalizeModel(\n modelId: string,\n model: Partial<Model> | string,\n provider: Provider,\n): Model {\n let actualModel: Partial<Model> = {};\n let extraInfo: Partial<Model> = {};\n\n if (typeof model === 'string') {\n actualModel = models[model.toLowerCase()] || {};\n } else {\n const splitModelId = modelId.split('/').slice(-1)[0].toLowerCase();\n actualModel = models[splitModelId] || {};\n extraInfo = { ...model };\n }\n\n if (!actualModel.limit) {\n actualModel.limit = {\n context: 256000,\n output: 256000,\n };\n }\n\n const m = {\n ...actualModel,\n ...extraInfo,\n } as Model;\n\n if (!m.variants) {\n const variants = transformVariants(m, provider);\n m.variants = variants;\n }\n\n return m;\n}\n\n/**\n * Apply global proxy to all providers without provider-level proxy\n */\nfunction applyGlobalProxyToProviders(\n providersMap: ProvidersMap,\n globalHttpProxy: string,\n): ProvidersMap {\n return Object.fromEntries(\n Object.entries(providersMap).map(([id, prov]) => {\n const provider = prov as Provider;\n // Skip if provider already has its own proxy\n if (provider.options?.httpProxy) {\n return [id, provider];\n }\n // Apply global proxy\n return [\n id,\n {\n ...provider,\n options: {\n ...provider.options,\n httpProxy: globalHttpProxy,\n },\n },\n ];\n }),\n );\n}\n\n/**\n * Merge config providers with hooked providers\n */\nfunction mergeConfigProviders(\n hookedProviders: ProvidersMap,\n configProviders: Record<string, ProviderConfig>,\n): ProvidersMap {\n const mergedProviders = { ...hookedProviders };\n Object.entries(configProviders).forEach(([providerId, config]) => {\n let provider = mergedProviders[providerId] || {};\n provider = defu(config, provider) as Provider;\n\n // Set default createModel if apiFormat is anthropic\n if (provider.apiFormat === 'anthropic' && !provider.createModel) {\n provider.createModel = defaultAnthropicModelCreator;\n }\n\n // Set default createModel if not set\n if (!provider.createModel) {\n provider.createModel = defaultModelCreator;\n }\n\n // Process models\n if (provider.models) {\n for (const modelId in provider.models) {\n provider.models[modelId] = normalizeModel(\n modelId,\n provider.models[modelId],\n provider,\n );\n }\n }\n\n if (!provider.id) {\n provider.id = providerId;\n }\n if (!provider.name) {\n provider.name = providerId;\n }\n mergedProviders[providerId] = provider;\n });\n return mergedProviders;\n}\n\nfunction isPromise(m: any): m is Promise<LanguageModelV3> {\n return m instanceof Promise;\n}\n\n/**\n * Resolve a model by name from providers and modelAlias\n */\nexport async function resolveModel(\n name: string,\n providersMap: ProvidersMap,\n aliases: ModelAlias,\n globalConfigDir: string,\n setGlobalConfig: (key: string, value: string, isGlobal: boolean) => void,\n): Promise<ModelInfo> {\n const alias = aliases[name];\n if (alias) {\n name = alias;\n }\n const [providerStr, ...modelNameArr] = name.split('/');\n const provider = providersMap[providerStr];\n assert(\n provider,\n `Provider ${providerStr} not found, valid providers: ${Object.keys(providersMap).join(', ')}`,\n );\n const modelId = modelNameArr.join('/');\n const model = provider.models[modelId] as Model;\n assert(\n model,\n `Model ${modelId} not found in provider ${providerStr}, valid models: ${Object.keys(provider.models).join(', ')}`,\n );\n model.id = modelId;\n const mCreator = async () => {\n let m: LanguageModelV3 | Promise<LanguageModelV3> = provider.createModel!(\n modelId,\n provider,\n {\n globalConfigDir,\n setGlobalConfig,\n },\n );\n if (isPromise(m)) {\n m = await m;\n }\n return m;\n };\n return {\n provider,\n model,\n _mCreator: mCreator,\n };\n}\n\n/**\n * Main entry point to resolve model with context\n */\nexport async function resolveModelWithContext(\n name: string | null,\n context: Context,\n) {\n const hookedProviders = await context.apply({\n hook: 'provider',\n args: [\n {\n models,\n providers,\n },\n ],\n memo: providers,\n type: PluginHookType.SeriesLast,\n });\n\n let finalProviders = context.config.provider\n ? mergeConfigProviders(hookedProviders, context.config.provider)\n : hookedProviders;\n\n // Apply global proxy to ALL providers that don't have provider-level proxy\n if (context.config.httpProxy) {\n finalProviders = applyGlobalProxyToProviders(\n finalProviders,\n context.config.httpProxy,\n );\n }\n\n const hookedModelAlias = await context.apply({\n hook: 'modelAlias',\n args: [],\n memo: modelAlias,\n type: PluginHookType.SeriesLast,\n });\n const modelName = name || context.config.model;\n let model = null;\n let error = null;\n try {\n model = modelName\n ? await resolveModel(\n modelName,\n finalProviders,\n hookedModelAlias,\n context.paths.globalConfigDir,\n (key, value, isGlobal) => {\n const configManager = new ConfigManager(\n context.cwd,\n context.productName,\n {},\n );\n configManager.setConfig(isGlobal, key, value);\n },\n )\n : null;\n } catch (err) {\n error = err;\n }\n\n return {\n providers: finalProviders,\n modelAlias: hookedModelAlias,\n model,\n error,\n };\n}\n\n// Re-export types\nexport type { Model, Provider, ProvidersMap, ModelAlias, ModelInfo, ModelMap };\n","import defu from 'defu';\nimport fs from 'fs';\nimport { homedir } from 'os';\nimport path from 'pathe';\nimport type { Provider } from '../core/model';\nimport {\n assertValidConfig,\n formatValidationErrors,\n type ValidationResult,\n validateConfig,\n} from './configValidation';\n\nexport type McpStdioServerConfig = {\n type: 'stdio';\n command: string;\n args: string[];\n env?: Record<string, string>;\n disable?: boolean;\n};\nexport type McpSSEServerConfig = {\n type: 'sse';\n url: string;\n disable?: boolean;\n headers?: Record<string, string>;\n};\nexport type McpHttpServerConfig = {\n type: 'http';\n url: string;\n disable?: boolean;\n headers?: Record<string, string>;\n};\nexport type McpServerConfig =\n | McpStdioServerConfig\n | McpSSEServerConfig\n | McpHttpServerConfig;\n\nexport type ApprovalMode = 'default' | 'autoEdit' | 'yolo';\n\nexport type AgentConfig = {\n model?: string;\n // Reserved for future extensions\n};\n\nexport type CommitConfig = {\n language: string;\n systemPrompt?: string;\n model?: string;\n};\n\nexport type ProviderConfig = Partial<Omit<Provider, 'createModel'>>;\n\nexport type DesktopConfig = {\n theme?: 'light' | 'dark' | 'system';\n sendMessageWith?: 'enter' | 'cmdEnter';\n terminalFont?: string;\n terminalFontSize?: number;\n};\n\nexport type Config = {\n model: string;\n planModel: string;\n smallModel?: string;\n visionModel?: string;\n language: string;\n quiet: boolean;\n approvalMode: ApprovalMode;\n plugins: string[];\n mcpServers: Record<string, McpServerConfig>;\n provider?: Record<string, ProviderConfig>;\n systemPrompt?: string;\n todo?: boolean;\n /**\n * Controls whether automatic conversation compression is enabled.\n * When set to false, conversation history will accumulate and context limit will be exceeded.\n *\n * @default true\n */\n autoCompact?: boolean;\n commit?: CommitConfig;\n outputStyle?: string;\n outputFormat?: 'text' | 'stream-json' | 'json';\n autoUpdate?: boolean;\n temperature?: number;\n httpProxy?: string;\n desktop?: DesktopConfig;\n /**\n * Extensions configuration for third-party custom agents.\n * Allows arbitrary nested configuration without validation.\n */\n extensions?: Record<string, any>;\n /**\n * Tools configuration for enabling/disabling specific tools.\n * Key is the tool name, value is boolean (false to disable).\n */\n tools?: Record<string, boolean>;\n /**\n * Agent configuration for customizing agent behavior per agent type.\n * Example: { explore: { model: \"anthropic/claude-haiku-4\" } }\n */\n agent?: Record<string, AgentConfig>;\n /**\n * Notification configuration.\n * - true: play default sound (Funk/warning)\n * - false: disabled\n * - string: custom sound name (e.g., \"Glass\", \"Ping\")\n * - object: extended notification config (reserved for future use, e.g., url)\n */\n notification?: boolean | string;\n};\n\nconst DEFAULT_CONFIG: Partial<Config> = {\n language: 'English',\n quiet: false,\n approvalMode: 'default',\n plugins: [],\n mcpServers: {},\n provider: {},\n todo: true,\n autoCompact: true,\n outputFormat: 'text',\n autoUpdate: true,\n extensions: {},\n tools: {},\n agent: {},\n desktop: {\n theme: 'light',\n sendMessageWith: 'enter',\n },\n};\nconst VALID_CONFIG_KEYS = [\n ...Object.keys(DEFAULT_CONFIG),\n 'model',\n 'planModel',\n 'smallModel',\n 'visionModel',\n 'systemPrompt',\n 'todo',\n 'autoCompact',\n 'commit',\n 'outputStyle',\n 'autoUpdate',\n 'provider',\n 'temperature',\n 'httpProxy',\n 'extensions',\n 'tools',\n 'agent',\n 'notification',\n];\nconst ARRAY_CONFIG_KEYS = ['plugins'];\nconst OBJECT_CONFIG_KEYS = [\n 'mcpServers',\n 'commit',\n 'provider',\n 'extensions',\n 'tools',\n 'desktop',\n 'agent',\n];\nconst BOOLEAN_CONFIG_KEYS = ['quiet', 'todo', 'autoCompact', 'autoUpdate'];\nexport const GLOBAL_ONLY_KEYS = ['desktop'];\n\nfunction assertGlobalAllowed(global: boolean, key: string) {\n const rootKey = key.split('.')[0];\n if (!global && GLOBAL_ONLY_KEYS.includes(rootKey)) {\n throw new Error(`Config key '${rootKey}' can only be set globally`);\n }\n}\n\nexport class ConfigManager {\n globalConfig: Partial<Config>;\n projectConfig: Partial<Config>;\n argvConfig: Partial<Config>;\n globalConfigPath: string;\n projectConfigPath: string;\n private validationEnabled: boolean = false;\n\n constructor(cwd: string, productName: string, argvConfig: Partial<Config>) {\n const lowerProductName = productName.toLowerCase();\n const globalConfigPath = path.join(\n homedir(),\n `.${lowerProductName}`,\n 'config.json',\n );\n const projectConfigPath = path.join(\n cwd,\n `.${lowerProductName}`,\n 'config.json',\n );\n const projectLocalConfigPath = path.join(\n cwd,\n `.${lowerProductName}`,\n 'config.local.json',\n );\n this.globalConfigPath = globalConfigPath;\n this.projectConfigPath = projectConfigPath;\n this.globalConfig = loadConfig(globalConfigPath);\n this.projectConfig = defu(\n loadConfig(projectConfigPath),\n loadConfig(projectLocalConfigPath),\n );\n this.argvConfig = argvConfig;\n }\n\n get config() {\n const config = defu(\n this.argvConfig,\n defu(this.projectConfig, defu(this.globalConfig, DEFAULT_CONFIG)),\n ) as Config;\n config.planModel = config.planModel || config.model;\n config.smallModel = config.smallModel || config.model;\n config.visionModel = config.visionModel || config.model;\n\n // Validate config if enabled\n if (this.validationEnabled) {\n assertValidConfig(config);\n }\n\n return config;\n }\n\n /**\n * Enable configuration validation\n * When enabled, invalid configurations will throw errors\n */\n enableValidation(): void {\n this.validationEnabled = true;\n }\n\n /**\n * Disable configuration validation\n */\n disableValidation(): void {\n this.validationEnabled = false;\n }\n\n /**\n * Validate the current configuration\n * Returns validation result without throwing\n */\n validate(): ValidationResult {\n const config = defu(\n this.argvConfig,\n defu(this.projectConfig, defu(this.globalConfig, DEFAULT_CONFIG)),\n ) as Config;\n config.planModel = config.planModel || config.model;\n config.smallModel = config.smallModel || config.model;\n config.visionModel = config.visionModel || config.model;\n\n return validateConfig(config);\n }\n\n /**\n * Get validation errors as a formatted string\n */\n getValidationErrors(): string {\n const result = this.validate();\n if (result.valid) {\n return 'Configuration is valid';\n }\n return formatValidationErrors(result);\n }\n\n removeConfig(global: boolean, key: string, values?: string[]) {\n assertGlobalAllowed(global, key);\n const config = global ? this.globalConfig : this.projectConfig;\n const configPath = global ? this.globalConfigPath : this.projectConfigPath;\n\n if (key.includes('.')) {\n // Handle dot notation for nested keys\n const keys = key.split('.');\n const rootKey = keys[0];\n\n if (!VALID_CONFIG_KEYS.includes(rootKey)) {\n throw new Error(`Invalid config key: ${rootKey}`);\n }\n\n if (!OBJECT_CONFIG_KEYS.includes(rootKey)) {\n throw new Error(\n `Config key '${rootKey}' does not support nested properties`,\n );\n }\n\n // Navigate to the nested property\n let current: any = config[rootKey as keyof Config];\n if (!current) {\n return; // Nothing to remove\n }\n\n // Navigate to the parent of the target property\n for (let i = 1; i < keys.length - 1; i++) {\n if (!current[keys[i]]) {\n return; // Path doesn't exist, nothing to remove\n }\n current = current[keys[i]];\n }\n\n const lastKey = keys[keys.length - 1];\n\n if (values) {\n // Remove specific values from array\n if (Array.isArray(current[lastKey])) {\n current[lastKey] = current[lastKey].filter(\n (v: string) => !values.includes(v),\n );\n }\n } else {\n // Delete the property\n delete current[lastKey];\n }\n } else {\n // Handle flat keys\n if (!VALID_CONFIG_KEYS.includes(key)) {\n throw new Error(`Invalid config key: ${key}`);\n }\n\n if (values) {\n (config[key as keyof Config] as any) = (\n config[key as keyof Config] as string[]\n ).filter((v) => !values.includes(v));\n } else {\n delete config[key as keyof Config];\n }\n }\n\n saveConfig(configPath, config, DEFAULT_CONFIG);\n }\n\n addConfig(global: boolean, key: string, values: string[]) {\n assertGlobalAllowed(global, key);\n if (!VALID_CONFIG_KEYS.includes(key)) {\n throw new Error(`Invalid config key: ${key}`);\n }\n const config = global ? this.globalConfig : this.projectConfig;\n const configPath = global ? this.globalConfigPath : this.projectConfigPath;\n if (ARRAY_CONFIG_KEYS.includes(key)) {\n (config[key as keyof Config] as any) = [\n ...((config[key as keyof Config] as string[]) || []),\n ...values,\n ];\n } else if (OBJECT_CONFIG_KEYS.includes(key)) {\n (config[key as keyof Config] as any) = {\n ...(config[key as keyof Config] as Record<string, McpServerConfig>),\n ...values,\n };\n }\n saveConfig(configPath, config, DEFAULT_CONFIG);\n }\n\n getConfig(global: boolean, key: string): any {\n const config = global ? this.globalConfig : this.projectConfig;\n\n const getValue = (conf: Partial<Config>) => {\n if (!key.includes('.')) {\n return conf[key as keyof Config];\n }\n\n const keys = key.split('.');\n const rootKey = keys[0];\n\n if (!VALID_CONFIG_KEYS.includes(rootKey)) {\n throw new Error(`Invalid config key: ${rootKey}`);\n }\n\n let current: any = conf[rootKey as keyof Config];\n for (let i = 1; i < keys.length; i++) {\n if (current === undefined || current === null) {\n return undefined;\n }\n current = current[keys[i]];\n }\n\n return current;\n };\n\n const value = getValue(config);\n if (value !== undefined) {\n return value;\n }\n return getValue(DEFAULT_CONFIG);\n }\n\n setConfig(global: boolean, key: string, value: string) {\n assertGlobalAllowed(global, key);\n const config = global ? this.globalConfig : this.projectConfig;\n const configPath = global ? this.globalConfigPath : this.projectConfigPath;\n\n if (key.includes('.')) {\n // Handle dot notation for nested keys\n const keys = key.split('.');\n const rootKey = keys[0];\n\n if (!VALID_CONFIG_KEYS.includes(rootKey)) {\n throw new Error(`Invalid config key: ${rootKey}`);\n }\n\n if (!OBJECT_CONFIG_KEYS.includes(rootKey)) {\n throw new Error(\n `Config key '${rootKey}' does not support nested properties`,\n );\n }\n\n // Initialize the root object if it doesn't exist\n if (!config[rootKey as keyof Config]) {\n (config[rootKey as keyof Config] as any) = {};\n }\n\n // Navigate to the nested property and set the value\n let current: any = config[rootKey as keyof Config];\n for (let i = 1; i < keys.length - 1; i++) {\n if (!current[keys[i]]) {\n current[keys[i]] = {};\n }\n current = current[keys[i]];\n }\n\n const lastKey = keys[keys.length - 1];\n current[lastKey] = value;\n } else {\n // Handle flat keys\n if (!VALID_CONFIG_KEYS.includes(key)) {\n throw new Error(`Invalid config key: ${key}`);\n }\n\n let newValue: any = value;\n if (BOOLEAN_CONFIG_KEYS.includes(key)) {\n if (typeof value === 'boolean') {\n newValue = value;\n } else {\n newValue = value === 'true';\n }\n }\n if (ARRAY_CONFIG_KEYS.includes(key)) {\n newValue = JSON.parse(value);\n }\n if (OBJECT_CONFIG_KEYS.includes(key)) {\n newValue = JSON.parse(value);\n }\n (config[key as keyof Config] as any) = newValue;\n }\n\n saveConfig(configPath, config, DEFAULT_CONFIG);\n }\n\n updateConfig(global: boolean, newConfig: Partial<Config>) {\n Object.keys(newConfig).forEach((key) => {\n if (!VALID_CONFIG_KEYS.includes(key)) {\n throw new Error(`Invalid config key: ${key}`);\n }\n assertGlobalAllowed(global, key);\n });\n let config = global ? this.globalConfig : this.projectConfig;\n const configPath = global ? this.globalConfigPath : this.projectConfigPath;\n config = defu(newConfig, config);\n if (global) {\n this.globalConfig = config;\n } else {\n this.projectConfig = config;\n }\n saveConfig(configPath, config, DEFAULT_CONFIG);\n }\n}\n\nfunction loadConfig(file: string) {\n if (!fs.existsSync(file)) {\n return {};\n }\n try {\n return JSON.parse(fs.readFileSync(file, 'utf-8'));\n } catch (error) {\n throw new Error(`Unable to read config file ${file}: ${error}`);\n }\n}\n\nfunction saveConfig(\n file: string,\n config: Partial<Config>,\n defaultConfig: Partial<Config>,\n) {\n const filteredConfig = Object.fromEntries(\n Object.entries(config).filter(\n ([key, value]) =>\n JSON.stringify(value) !==\n JSON.stringify(defaultConfig[key as keyof Config]),\n ),\n );\n const dir = path.dirname(file);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n fs.writeFileSync(file, JSON.stringify(filteredConfig, null, 2), 'utf-8');\n}\n","/**\n * Configuration Validation\n * Runtime validation for engine configuration\n */\n\nimport type { Config, McpServerConfig } from './config';\nimport { z } from 'zod';\n\n/**\n * Validation result\n */\nexport interface ValidationResult {\n valid: boolean;\n errors: ValidationError[];\n warnings: ValidationWarning[];\n}\n\nexport interface ValidationError {\n path: string;\n message: string;\n value?: any;\n}\n\nexport interface ValidationWarning {\n path: string;\n message: string;\n value?: any;\n}\n\n/**\n * MCP server configuration schema\n */\nconst McpServerConfigSchema = z.object({\n type: z.enum(['stdio', 'sse', 'http']).optional(),\n command: z.string().optional(),\n args: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n url: z.string().optional(),\n disable: z.boolean().optional(),\n timeout: z.number().positive().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n});\n\n/**\n * Provider configuration schema\n */\nconst ProviderConfigSchema = z.object({\n apiKey: z.string().optional(),\n apiKeys: z.array(z.string()).optional(),\n baseURL: z.string().optional(),\n proxy: z.string().optional(),\n});\n\n/**\n * Agent configuration schema\n */\nconst AgentConfigSchema = z.object({\n model: z.string().optional(),\n tools: z.array(z.string()).optional(),\n disallowedTools: z.array(z.string()).optional(),\n forkContext: z.boolean().optional(),\n color: z.string().optional(),\n});\n\n/**\n * Main configuration schema\n */\nconst ConfigSchema = z.object({\n // Model configuration\n model: z.string().min(1, 'Model cannot be empty'),\n planModel: z.string().optional(),\n smallModel: z.string().optional(),\n visionModel: z.string().optional(),\n\n // Behavior configuration\n language: z.string().optional(),\n quiet: z.boolean().optional(),\n approvalMode: z.enum(['default', 'autoEdit', 'yolo']).optional(),\n autoCompact: z.boolean().optional(),\n temperature: z\n .number()\n .min(0, 'Temperature must be at least 0')\n .max(2, 'Temperature must be at most 2')\n .optional(),\n\n // Feature flags\n plugins: z.array(z.string()).optional(),\n tools: z.record(z.string(), z.boolean()).optional(),\n todo: z.boolean().optional(),\n\n // MCP servers\n mcpServers: z.record(z.string(), z.any()).optional(), // Validated separately\n\n // Provider extensions\n provider: z.record(z.string(), z.any()).optional(), // Validated separately\n\n // Extensions\n extensions: z.record(z.string(), z.any()).optional(),\n\n // Agents\n agent: z.record(z.string(), z.any()).optional(), // Validated separately\n});\n\n/**\n * Validate a configuration object\n */\nexport function validateConfig(config: Partial<Config>): ValidationResult {\n const errors: ValidationError[] = [];\n const warnings: ValidationWarning[] = [];\n\n // Validate main config structure\n const mainResult = ConfigSchema.safeParse(config);\n if (!mainResult.success) {\n for (const issue of mainResult.error.issues) {\n errors.push({\n path: issue.path.join('.'),\n message: issue.message,\n value: getNestedValue(config, issue.path as (string | number)[]),\n });\n }\n }\n\n // Validate MCP servers if present\n if (config.mcpServers) {\n for (const [name, mcpConfig] of Object.entries(config.mcpServers)) {\n const mcpResult = McpServerConfigSchema.safeParse(mcpConfig);\n if (!mcpResult.success) {\n for (const issue of mcpResult.error.issues) {\n errors.push({\n path: `mcpServers.${name}.${issue.path.join('.')}`,\n message: issue.message,\n value: getNestedValue(mcpConfig, issue.path as (string | number)[]),\n });\n }\n }\n\n // Additional validation: MCP server must have either command or url\n const mcp = mcpConfig as any;\n if (!mcp.disable && !mcp.command && !mcp.url) {\n errors.push({\n path: `mcpServers.${name}`,\n message: 'MCP server must have either \"command\" or \"url\" configured',\n value: mcp,\n });\n }\n\n // Warning: stdio type requires command\n if (mcp.type === 'stdio' && !mcp.command) {\n warnings.push({\n path: `mcpServers.${name}`,\n message: 'stdio MCP server type requires \"command\" to be set',\n value: mcp,\n });\n }\n\n // Warning: http/sse type requires url\n if ((mcp.type === 'http' || mcp.type === 'sse') && !mcp.url) {\n warnings.push({\n path: `mcpServers.${name}`,\n message: `${mcp.type} MCP server type requires \"url\" to be set`,\n value: mcp,\n });\n }\n }\n }\n\n // Validate provider configs if present\n if (config.provider) {\n for (const [name, providerConfig] of Object.entries(config.provider)) {\n const providerResult = ProviderConfigSchema.safeParse(providerConfig);\n if (!providerResult.success) {\n for (const issue of providerResult.error.issues) {\n errors.push({\n path: `provider.${name}.${issue.path.join('.')}`,\n message: issue.message,\n value: getNestedValue(providerConfig, issue.path as (string | number)[]),\n });\n }\n }\n\n // Warning: Multiple API keys detected but no apiKey (single)\n const provider = providerConfig as any;\n if (provider.apiKeys && provider.apiKeys.length > 1 && !provider.apiKey) {\n warnings.push({\n path: `provider.${name}`,\n message: 'Multiple API keys detected - rotation will be used',\n value: { apiKeyCount: provider.apiKeys.length },\n });\n }\n }\n }\n\n // Validate agent configs if present\n if (config.agent) {\n for (const [name, agentConfig] of Object.entries(config.agent)) {\n const agentResult = AgentConfigSchema.safeParse(agentConfig);\n if (!agentResult.success) {\n for (const issue of agentResult.error.issues) {\n errors.push({\n path: `agent.${name}.${issue.path.join('.')}`,\n message: issue.message,\n value: getNestedValue(agentConfig, issue.path as (string | number)[]),\n });\n }\n }\n }\n }\n\n // Validate temperature range\n if (config.temperature !== undefined) {\n if (config.temperature < 0 || config.temperature > 2) {\n errors.push({\n path: 'temperature',\n message: 'Temperature must be between 0 and 2',\n value: config.temperature,\n });\n }\n }\n\n // Validate language code format\n if (config.language) {\n const languageCodeRegex = /^[a-z]{2}(-[A-Z]{2})?$/;\n if (!languageCodeRegex.test(config.language)) {\n warnings.push({\n path: 'language',\n message: 'Language code should be in ISO 639-1 format (e.g., \"en\", \"zh-CN\")',\n value: config.language,\n });\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n}\n\n/**\n * Get nested value from object using path array\n */\nfunction getNestedValue(obj: any, path: (string | number)[]): any {\n let current = obj;\n for (const key of path) {\n if (current == null) {\n return undefined;\n }\n current = current[key];\n }\n return current;\n}\n\n/**\n * Format validation errors for display\n */\nexport function formatValidationErrors(result: ValidationResult): string {\n const lines: string[] = [];\n\n if (result.errors.length > 0) {\n lines.push('Configuration errors:');\n for (const error of result.errors) {\n const valueStr =\n error.value !== undefined ? ` (got: ${JSON.stringify(error.value)})` : '';\n lines.push(` - ${error.path}: ${error.message}${valueStr}`);\n }\n }\n\n if (result.warnings.length > 0) {\n if (lines.length > 0) lines.push('');\n lines.push('Configuration warnings:');\n for (const warning of result.warnings) {\n const valueStr =\n warning.value !== undefined\n ? ` (value: ${JSON.stringify(warning.value)})`\n : '';\n lines.push(` - ${warning.path}: ${warning.message}${valueStr}`);\n }\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Assert that configuration is valid, throws if not\n */\nexport function assertValidConfig(config: Partial<Config>): void {\n const result = validateConfig(config);\n if (!result.valid) {\n throw new Error(\n `Invalid configuration:\\n${formatValidationErrors(result)}`,\n );\n }\n}\n","import type { AnthropicProvider } from '@ai-sdk/anthropic';\nimport type { OpenAIProvider } from '@ai-sdk/openai';\nimport type { OpenAICompatibleProvider } from '@ai-sdk/openai-compatible';\nimport type { LanguageModelV3 } from '@ai-sdk/provider';\nimport defu from 'defu';\nimport type {\n AgentExecutionResult,\n PluginAgentDefinition,\n} from '../agent/agent/types';\nimport type { Config } from './config';\nimport type { Context, ContextCreateOpts } from './context';\nimport type { LoopResult } from './loop';\nimport type { ModelAlias, ModelMap, Provider, ProvidersMap } from './model';\n// NodeBridgeHandlers is CLI-specific, not needed in engine\n// import type { NodeBridgeHandlers } from './nodeBridge.types';\nimport type { OutputStyle } from './outputStyle';\n// SlashCommand is CLI-specific, not needed in engine\n// import type { SlashCommand } from '../slash-commands/types';\nimport type { Tool, ToolResult, ToolUse } from '../tools/tool';\nimport type { Usage } from './usage';\n\nexport enum PluginHookType {\n First = 'first',\n Series = 'series',\n SeriesMerge = 'seriesMerge',\n SeriesLast = 'seriesLast',\n Parallel = 'parallel',\n}\n\nexport type PluginApplyOpts = {\n hook: keyof Plugin;\n args: any[];\n memo?: any;\n type: PluginHookType;\n pluginContext: any;\n};\n\nexport class PluginManager {\n #plugins: Plugin[] = [];\n constructor(rawPlugins: Plugin[]) {\n this.#plugins = [\n ...rawPlugins.filter((p) => p.enforce === 'pre'),\n ...rawPlugins.filter((p) => !p.enforce),\n ...rawPlugins.filter((p) => p.enforce === 'post'),\n ];\n }\n\n async apply({\n hook,\n args,\n memo,\n type = PluginHookType.Series,\n pluginContext,\n }: PluginApplyOpts) {\n const plugins = this.#plugins.filter((p) => !!p[hook]);\n if (type === PluginHookType.First) {\n for (const plugin of plugins) {\n const hookFn: any = plugin[hook];\n if (typeof hookFn === 'function') {\n const result = await hookFn.apply(pluginContext, args);\n if (result != null) {\n return result;\n }\n }\n }\n return null;\n } else if (type === PluginHookType.Parallel) {\n const results = await Promise.all(\n plugins.map((p) => {\n const hookFn: any = p[hook];\n if (typeof hookFn === 'function') {\n return hookFn.apply(pluginContext, args);\n }\n return null;\n }),\n );\n return results.filter((r) => r != null);\n } else if (type === PluginHookType.Series) {\n for (const plugin of plugins) {\n const hookFn: any = plugin[hook];\n if (typeof hookFn === 'function') {\n await hookFn.apply(pluginContext, args);\n }\n }\n } else if (type === PluginHookType.SeriesLast) {\n let result = memo;\n for (const plugin of plugins) {\n const hookFn: any = plugin[hook];\n if (typeof hookFn === 'function') {\n result = await hookFn.apply(pluginContext, [result, ...args]);\n }\n }\n return result;\n } else if (type === PluginHookType.SeriesMerge) {\n let result = memo;\n const isArray = Array.isArray(result);\n for (const plugin of plugins) {\n const hookFn: any = plugin[hook];\n if (typeof hookFn === 'function') {\n if (isArray) {\n result = result.concat(await hookFn.apply(pluginContext, args));\n } else {\n result = defu(await hookFn.apply(pluginContext, args), result);\n }\n }\n }\n return result;\n } else {\n throw new Error(`Invalid hook type: ${type}`);\n }\n }\n}\n\ntype PluginContext = Context;\n\ntype TempPluginContext = ContextCreateOpts & {\n pluginManager: PluginManager;\n config: Config;\n apply: (opts: PluginApplyOpts) => Promise<any> | any;\n};\n\ntype Enforce = 'pre' | 'post';\n\nexport type GeneralInfo = Record<\n string,\n | string\n | {\n enforce: Enforce;\n text: string;\n }\n>;\n\ntype Status = Record<\n string,\n {\n description?: string;\n items: string[];\n }\n>;\n\nexport type Plugin = {\n enforce?: Enforce;\n name?: string;\n\n // initialize\n config?: (\n this: TempPluginContext,\n opts: { config: Config; argvConfig: Record<string, any> },\n ) => Partial<Config> | Promise<Partial<Config>>;\n // slashCommand is CLI-specific, not needed in engine\n // slashCommand?: (\n // this: PluginContext,\n // ) => Promise<SlashCommand[]> | SlashCommand[];\n skill?: (this: PluginContext) => Promise<string[]> | string[];\n outputStyle?: (this: PluginContext) => Promise<OutputStyle[]> | OutputStyle[];\n provider?: (\n this: PluginContext,\n providers: ProvidersMap,\n opts: {\n models: ModelMap;\n defaultModelCreator: (\n name: string,\n provider: Provider,\n ) => LanguageModelV3;\n createOpenAI: (options: any) => OpenAIProvider;\n createOpenAICompatible: (options: any) => OpenAICompatibleProvider;\n createAnthropic: (options: any) => AnthropicProvider;\n },\n ) => Promise<ProvidersMap> | ProvidersMap;\n modelAlias?: (\n this: PluginContext,\n modelAlias: ModelAlias,\n ) => Promise<ModelAlias> | ModelAlias;\n\n // workflow\n // NOTICE: initialized may be called multiple times when it's runned\n // for different file paths\n initialized?: (\n this: PluginContext,\n opts: {\n cwd: string;\n quiet: boolean;\n },\n ) => Promise<void> | void;\n destroy?: (this: PluginContext) => Promise<void> | void;\n\n // session\n context?: (\n this: PluginContext,\n opts: {\n userPrompt: string | null;\n sessionId: string;\n },\n ) => Promise<Record<string, string> | {}> | Record<string, string> | {};\n env?: (\n this: PluginContext,\n opts: {\n userPrompt: string | null;\n sessionId: string;\n },\n ) => Promise<Record<string, string> | {}> | Record<string, string> | {};\n userPrompt?: (\n this: PluginContext,\n userPrompt: string,\n opts: { sessionId: string },\n ) => Promise<string> | string;\n systemPrompt?: (\n this: PluginContext,\n systemPrompt: string,\n opts: { isPlan?: boolean; sessionId: string },\n ) => Promise<string> | string;\n tool?: (\n this: PluginContext,\n opts: { isPlan?: boolean; sessionId: string },\n ) => Promise<Tool[]> | Tool[];\n toolUse?: (\n this: PluginContext,\n toolUse: ToolUse,\n opts: { sessionId: string },\n ) => Promise<ToolUse> | ToolUse;\n toolResult?: (\n this: PluginContext,\n toolResult: ToolResult,\n opts: {\n toolUse: ToolUse;\n approved: boolean;\n sessionId: string;\n },\n ) => Promise<ToolResult> | ToolResult;\n query?: (\n this: PluginContext,\n opts: {\n usage: Usage;\n startTime: Date;\n endTime: Date;\n sessionId: string;\n },\n ) => Promise<void> | void;\n conversation?: (\n this: PluginContext,\n opts: {\n userPrompt: string | null;\n result: LoopResult;\n startTime: Date;\n endTime: Date;\n sessionId: string;\n },\n ) => Promise<void> | void;\n\n // slash commands\n // /status\n status?: (this: PluginContext) => Promise<Status> | Status;\n\n // agent\n agent?: (\n this: PluginContext,\n ) => Promise<PluginAgentDefinition[]> | PluginAgentDefinition[];\n\n // Telemetry hook for collecting usage analytics\n telemetry?: (\n this: PluginContext,\n opts: {\n name: string;\n payload: Record<string, any>;\n },\n ) => Promise<void> | void;\n\n stop?: (\n this: PluginContext,\n opts: {\n sessionId: string;\n result: LoopResult;\n usage: Usage;\n turnsCount: number;\n toolCallsCount: number;\n duration: number;\n model: string;\n },\n ) => Promise<void> | void;\n\n subagentStop?: (\n this: PluginContext,\n opts: {\n parentSessionId: string;\n agentId: string;\n agentType: string;\n result: AgentExecutionResult;\n usage: { inputTokens: number; outputTokens: number };\n totalToolCalls: number;\n totalDuration: number;\n model: string;\n },\n ) => Promise<void> | void;\n\n // nodeBridgeHandler is CLI-specific, not needed in engine\n // nodeBridgeHandler?: (\n // this: PluginContext,\n // ) => Promise<NodeBridgeHandlers> | NodeBridgeHandlers;\n};\n","import type { LanguageModelV3FunctionTool } from '@ai-sdk/provider';\nimport path from 'pathe';\nimport * as z from 'zod';\nimport type { Context } from '../core/context';\nimport type { ImagePart, TextPart } from '../core/message';\nimport { resolveModelWithContext } from '../core/model';\nimport { PluginHookType } from '../core/plugin';\nimport { createAskUserQuestionTool } from './tools/askUserQuestion';\nimport {\n createBashOutputTool,\n createBashTool,\n createKillBashTool,\n} from './tools/bash';\nimport { createEditTool } from './tools/edit';\nimport { createFetchTool } from './tools/fetch';\nimport { createGlobTool } from './tools/glob';\nimport { createGrepTool } from './tools/grep';\nimport { createLSTool } from './tools/ls';\nimport { createReadTool } from './tools/read';\nimport { createSkillTool } from './tools/skill';\nimport { createTaskTool } from './tools/task';\nimport { createTodoTool, type TodoItem } from './tools/todo';\nimport { createWriteTool } from './tools/write';\n\ntype ResolveToolsOpts = {\n context: Context;\n sessionId: string;\n write?: boolean;\n todo?: boolean;\n askUserQuestion?: boolean;\n signal?: AbortSignal;\n task?: boolean;\n isPlan?: boolean;\n};\n\nexport async function resolveTools(opts: ResolveToolsOpts) {\n const { cwd, productName, paths } = opts.context;\n const sessionId = opts.sessionId;\n const model = (\n await resolveModelWithContext(\n opts.context.config.smallModel || opts.context.config.model,\n opts.context,\n )\n ).model!;\n const hasSkills =\n opts.context.skillManager &&\n opts.context.skillManager.getSkills().length > 0;\n const readonlyTools = [\n createReadTool({ cwd, productName }),\n createLSTool({ cwd }),\n createGlobTool({ cwd }),\n createGrepTool({ cwd }),\n createFetchTool({ model, fetch: opts.context.fetch }),\n ];\n const askUserQuestionTools = opts.askUserQuestion\n ? [createAskUserQuestionTool()]\n : [];\n const writeTools = opts.write\n ? [\n createWriteTool({ cwd }),\n createEditTool({ cwd }),\n createBashTool({\n cwd,\n backgroundTaskManager: opts.context.backgroundTaskManager,\n messageBus: opts.context.messageBus,\n }),\n ]\n : [];\n const todoTools = (() => {\n if (!opts.todo) return [];\n const { todoWriteTool } = createTodoTool({\n filePath: path.join(paths.globalConfigDir, 'todos', `${sessionId}.json`),\n });\n return [todoWriteTool];\n })();\n // Bash background tools\n const backgroundTools: any[] = opts.write\n ? [\n createBashOutputTool({\n backgroundTaskManager: opts.context.backgroundTaskManager,\n }),\n createKillBashTool({\n backgroundTaskManager: opts.context.backgroundTaskManager,\n }),\n ]\n : [];\n\n const mcpTools = await getMcpTools(opts.context);\n\n let allTools = [\n ...readonlyTools,\n ...askUserQuestionTools,\n ...writeTools,\n ...todoTools,\n ...backgroundTools,\n ...mcpTools,\n ];\n\n // Add skill tool if skills are available\n // Note: skill tool is added after initial tool list so it can reference allTools for fork execution\n if (hasSkills) {\n const skillTool = createSkillTool({\n skillManager: opts.context.skillManager!,\n context: opts.context,\n tools: allTools,\n sessionId: opts.sessionId,\n signal: opts.signal,\n });\n allTools = [...allTools, skillTool];\n }\n\n // 1. First, execute plugin hook to allow plugins to add/modify tools\n let availableTools = allTools;\n try {\n availableTools = await opts.context.apply({\n hook: 'tool',\n args: [{ isPlan: opts.isPlan, sessionId: opts.sessionId }],\n memo: allTools,\n type: PluginHookType.SeriesMerge,\n });\n } catch (error) {\n console.warn('[resolveTools] Plugin tool hook failed:', error);\n }\n\n // 2. Then, filter all tools (including plugin-injected ones) by config\n const toolsConfig = opts.context.config.tools;\n if (toolsConfig && Object.keys(toolsConfig).length > 0) {\n availableTools = availableTools.filter((tool) => {\n // Only explicitly set to false will disable the tool\n return toolsConfig[tool.name] !== false;\n });\n }\n\n const taskTools = (() => {\n // Task tool is only available in quiet mode\n if (!opts.task) return [];\n if (!opts.context.agentManager) return [];\n const tool = createTaskTool({\n context: opts.context,\n tools: availableTools,\n sessionId: opts.sessionId,\n signal: opts.signal,\n });\n if (toolsConfig && toolsConfig[tool.name] === false) {\n return [];\n }\n return [tool];\n })();\n\n return [...availableTools, ...taskTools];\n}\n\nasync function getMcpTools(context: Context): Promise<Tool[]> {\n try {\n const mcpManager = context.mcpManager;\n await mcpManager.initAsync();\n return await mcpManager.getAllTools();\n } catch (error) {\n console.warn('Failed to load MCP tools:', error);\n return [];\n }\n}\n\nexport class Tools {\n tools: Record<string, Tool>;\n constructor(tools: Tool[]) {\n this.tools = tools.reduce(\n (acc, tool) => {\n acc[tool.name] = tool;\n return acc;\n },\n {} as Record<string, Tool>,\n );\n }\n\n get(toolName: string) {\n return this.tools[toolName];\n }\n\n length() {\n return Object.keys(this.tools).length;\n }\n\n async invoke(\n toolName: string,\n args: string,\n toolCallId: string,\n ): Promise<ToolResult> {\n const tool = this.tools[toolName];\n if (!tool) {\n return {\n llmContent: `Tool ${toolName} not found`,\n isError: true,\n };\n }\n // // @ts-expect-error\n // const result = validateToolParams(tool.parameters, args);\n // if (!result.success) {\n // return {\n // llmContent: `Invalid tool parameters: ${result.error}`,\n // isError: true,\n // };\n // }\n let argsObj: any;\n try {\n argsObj = JSON.parse(args);\n } catch (error) {\n return {\n llmContent: `Tool parameters parse failed: ${error}`,\n isError: true,\n };\n }\n return await tool.execute(argsObj, toolCallId);\n }\n\n toLanguageV2Tools(): LanguageModelV3FunctionTool[] {\n return Object.entries(this.tools).map(([key, tool]) => {\n // parameters of mcp tools is not zod object\n const isMCP = key.startsWith('mcp__');\n const schema = isMCP ? tool.parameters : z.toJSONSchema(tool.parameters);\n // some providers have a limit on the description length, so we need to truncate it\n // e.g. megallm.io has a limit of 1024 characters\n const limit = process.env.TOOL_DESCRIPTION_LIMIT\n ? Math.floor(parseInt(process.env.TOOL_DESCRIPTION_LIMIT, 10))\n : 0;\n const desc =\n limit > 0 && tool.description.length > limit\n ? `${tool.description.slice(0, limit - 3)}...`\n : tool.description;\n return {\n type: 'function',\n name: key,\n description: desc,\n inputSchema: schema as LanguageModelV3FunctionTool['inputSchema'],\n providerOptions: {},\n };\n });\n }\n}\n\n// function validateToolParams(schema: z.ZodObject<any>, params: string) {\n// try {\n// if (isZodObject(schema)) {\n// const parsedParams = JSON.parse(params);\n// const result = schema.safeParse(parsedParams);\n// if (!result.success) {\n// return {\n// success: false,\n// error: `Parameter validation failed: ${result.error.message}`,\n// };\n// }\n// return {\n// success: true,\n// message: 'Tool parameters validated successfully',\n// };\n// }\n// return {\n// success: true,\n// message: 'Tool parameters validated successfully',\n// };\n// } catch (error) {\n// return {\n// success: false,\n// error: error,\n// };\n// }\n// }\n\nexport type ToolUse = {\n name: string;\n params: Record<string, any>;\n callId: string;\n};\n\nexport type ToolUseResult = {\n toolUse: ToolUse;\n result: any;\n approved: boolean;\n};\n\nexport interface Tool<TSchema extends z.ZodTypeAny = z.ZodTypeAny> {\n name: string;\n description: string;\n getDescription?: ({\n params,\n cwd,\n }: {\n params: z.output<TSchema>;\n cwd: string;\n }) => string;\n displayName?: string;\n execute: (\n params: z.output<TSchema>,\n toolCallId?: string,\n ) => Promise<ToolResult> | ToolResult;\n approval?: ToolApprovalInfo;\n parameters: TSchema;\n}\n\ntype ApprovalContext = {\n toolName: string;\n params: Record<string, any>;\n approvalMode: string;\n context: any;\n};\n\nexport type ApprovalCategory = 'read' | 'write' | 'command' | 'network' | 'ask';\n\ntype ToolApprovalInfo = {\n needsApproval?: (context: ApprovalContext) => Promise<boolean> | boolean;\n category?: ApprovalCategory;\n};\n\ntype TodoWriteReturnDisplay = {\n type: 'todo_write';\n oldTodos: TodoItem[];\n newTodos: TodoItem[];\n};\n\ntype DiffViewerReturnDisplay = {\n type: 'diff_viewer';\n originalContent: string | { inputKey: string };\n newContent: string | { inputKey: string };\n filePath: string;\n [key: string]: any;\n};\n\ntype AgentResultReturnDisplay = {\n type: 'agent_result';\n agentId: string;\n agentType: string;\n description: string;\n prompt: string;\n content: string;\n stats: {\n toolCalls: number;\n duration: number;\n tokens: {\n input: number;\n output: number;\n };\n };\n status: 'completed' | 'failed';\n};\n\nexport type ReturnDisplay =\n | string\n | DiffViewerReturnDisplay\n | TodoWriteReturnDisplay\n | AgentResultReturnDisplay;\n\nexport type ToolResult = {\n llmContent: string | (TextPart | ImagePart)[];\n returnDisplay?: ReturnDisplay;\n isError?: boolean;\n metadata?: {\n agentId?: string;\n agentType?: string;\n [key: string]: any;\n };\n};\n\nexport function createTool<TSchema extends z.ZodTypeAny>(config: {\n name: string;\n displayName?: string;\n description: string;\n parameters: TSchema;\n execute: (\n params: z.output<TSchema>,\n toolCallId?: string,\n ) => Promise<ToolResult> | ToolResult;\n approval?: ToolApprovalInfo;\n getDescription?: ({\n params,\n cwd,\n }: {\n params: z.output<TSchema>;\n cwd: string;\n }) => string;\n}): Tool<TSchema> {\n return {\n name: config.name,\n displayName: config.displayName,\n description: config.description,\n getDescription: config.getDescription,\n parameters: config.parameters,\n execute: config.execute,\n approval: config.approval,\n };\n}\n\nexport type ToolParams = Record<string, unknown>;\n\nexport type ToolApprovalResult =\n | boolean\n | {\n approved: boolean;\n params?: ToolParams;\n denyReason?: string;\n };\n","import { z } from 'zod';\nimport { TOOL_NAMES } from '../../core/constants';\nimport { createTool } from '../tool';\n\nconst MAX_HEADER_LENGTH = 12;\n\nconst QuestionOptionSchema = z.object({\n label: z\n .string()\n .describe(\n 'The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice.',\n ),\n description: z\n .string()\n .describe(\n 'Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications.',\n ),\n});\n\nconst QuestionSchema = z.object({\n question: z\n .string()\n .describe(\n 'The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: \"Which library should we use for date formatting?\" If multiSelect is true, phrase it accordingly, e.g. \"Which features do you want to enable?',\n ),\n header: z\n .string()\n .describe(\n `Very short label displayed as a chip/tag (max ${MAX_HEADER_LENGTH} chars). Examples: \"Auth method\", \"Library\", \"Approach\".`,\n ),\n options: z\n .array(QuestionOptionSchema)\n .min(2)\n .max(4)\n .describe(\n `The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no 'Other' option, that will be provided automatically.`,\n ),\n multiSelect: z\n .boolean()\n .optional()\n .default(false)\n .describe(\n 'Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive.',\n ),\n});\n\nconst AskUserQuestionInputSchema = z\n .object({\n questions: z\n .array(QuestionSchema)\n .min(1)\n .max(4)\n .describe('Questions to ask the user (1-4 questions)'),\n answers: z\n .array(z.object({ question: z.string(), answer: z.string() }))\n .optional()\n .describe('User answers collected by the permission component'),\n })\n .refine(\n (data) => {\n const questionTexts = data.questions.map((q) => q.question);\n return questionTexts.length === new Set(questionTexts).size;\n },\n {\n message:\n 'Question texts must be unique, option labels must be unique within each question',\n },\n )\n .refine(\n (data) => {\n for (const question of data.questions) {\n const labels = question.options.map((o) => o.label);\n if (labels.length !== new Set(labels).size) {\n return false;\n }\n }\n return true;\n },\n {\n message: 'Option labels must be unique within each question',\n },\n );\n\nexport type QuestionOption = z.infer<typeof QuestionOptionSchema>;\nexport type Question = z.infer<typeof QuestionSchema>;\nexport type AskUserQuestionInput = z.infer<typeof AskUserQuestionInputSchema>;\n\nconst TOOL_DESCRIPTION = `\nUse this tool when you need to ask the user questions during execution. This allows you to:\n1. Gather user preferences or requirements\n2. Clarify ambiguous instructions\n3. Get decisions on implementation choices as you work\n4. Offer choices to the user about what direction to take.\n\nUsage notes:\n- Users will always be able to select \"Other\" to provide custom text input\n- Use multiSelect: true to allow multiple answers to be selected for a question\n- If you recommend a specific option, make that the first option in the list and add \"(Recommended)\" at the end\n of the label\n`;\n\nexport function createAskUserQuestionTool() {\n return createTool({\n name: TOOL_NAMES.ASK_USER_QUESTION,\n description: TOOL_DESCRIPTION,\n parameters: AskUserQuestionInputSchema,\n async execute({ questions, answers }) {\n if (!answers || answers.length === 0) {\n return {\n isError: true,\n llmContent: 'No answers provided by user',\n };\n }\n\n const answerSummary = answers\n .map(({ question, answer }) => `\"${question}\" = \"${answer}\"`)\n .join(', ');\n\n const displayText = answers\n .map(({ question, answer }) => `· ${question} → ${answer}`)\n .join('\\n');\n\n return {\n llmContent: `User has answered your questions: ${answerSummary}. You can now continue with the user's answers in mind.`,\n returnDisplay: `User has answered your questions:\\n${displayText}`,\n };\n },\n approval: {\n // Always require user input, even in yolo mode\n category: 'ask',\n needsApproval: () => true,\n },\n });\n}\n","/**\n * Bash tool implementation.\n *\n * Provides shell command execution with security validation and background task support.\n *\n * Architecture:\n * - Security validation: bash/security.ts\n * - Output processing: bash/output.ts\n * - Constants: bash/constants.ts\n * - Tool creation and command execution: this file\n */\nimport crypto from 'crypto';\nimport createDebug from 'debug';\nimport fs from 'fs';\nimport os from 'os';\nimport path from 'pathe';\nimport { z } from 'zod';\nimport type { BackgroundTaskManager } from '../../core/backgroundTaskManager';\nimport { BASH_EVENTS, TOOL_NAMES } from '../../core/constants';\nimport type { MessageBus } from '../../communication/messageBus';\nimport { createTool } from '../tool';\nimport { shouldRunInBackground } from '../../utils/background-detection';\nimport { getErrorMessage } from '../../utils/error';\nimport { shellExecute } from '../../utils/shell-execution';\n// Import security functions\nimport {\n getCommandRoot,\n hasCommandSubstitution,\n isBannedCommand,\n isHighRiskCommand,\n validateCommand,\n} from '../../utils/bash/security';\n// Import output functions\nimport {\n formatExecutionResult,\n getMaxOutputLimit,\n trimEmptyLines,\n truncateOutput,\n} from '../../utils/bash/output';\n// Import constants\nimport {\n BANNED_COMMANDS,\n BACKGROUND_CHECK_INTERVAL,\n DEFAULT_TIMEOUT,\n MAX_TIMEOUT,\n} from '../../utils/bash/constants';\n\n// Re-export functions for testing compatibility\nexport {\n getCommandRoot,\n hasCommandSubstitution,\n isHighRiskCommand,\n};\nexport { getMaxOutputLimit, trimEmptyLines, truncateOutput };\n\nconst debug = createDebug('oricore:tools:bash');\n\n// ============================================================================\n// Local Types\n// ============================================================================\n\n/** Local type definition for bash background events. */\ntype BashPromptBackgroundEvent = {\n taskId: string;\n command: string;\n currentOutput: string;\n};\n\n// ============================================================================\n// Background Task Helpers\n// ============================================================================\n\n/**\n * Extract background PIDs from temp file created by pgrep.\n * Returns non-PID lines via console.error for debugging.\n */\nfunction extractBackgroundPIDs(\n tempFilePath: string,\n mainPid: number | null | undefined,\n isWindows: boolean,\n): number[] {\n if (isWindows || !fs.existsSync(tempFilePath)) {\n return [];\n }\n\n const pgrepLines = fs\n .readFileSync(tempFilePath, 'utf8')\n .split('\\n')\n .filter(Boolean);\n\n const backgroundPIDs: number[] = [];\n for (const line of pgrepLines) {\n if (/^\\d+$/.test(line)) {\n const pgrepPid = Number(line);\n if (pgrepPid !== mainPid) {\n backgroundPIDs.push(pgrepPid);\n }\n }\n }\n\n return backgroundPIDs;\n}\n\n/**\n * Create result object for background task.\n */\nfunction createBackgroundResult(\n command: string,\n backgroundTaskId: string,\n outputBuffer: string,\n): { shouldReturn: true; result: { llmContent: string; backgroundTaskId: string } } {\n const truncated = truncateOutput(outputBuffer);\n return {\n shouldReturn: true,\n result: {\n llmContent: [\n 'Command has been moved to background execution.',\n `Task ID: ${backgroundTaskId}`,\n `Command: ${command}`,\n '',\n 'Initial output:',\n truncated,\n '',\n 'Use bash_output tool with task_id to read further output.',\n 'Use kill_bash tool with task_id to terminate the task.',\n ].join('\\n'),\n backgroundTaskId,\n },\n };\n}\n\n/**\n * Create a promise that resolves when background transition occurs or command completes.\n */\nfunction createBackgroundCheckPromise(\n movedToBackgroundRef: { value: boolean },\n backgroundTaskIdRef: { value: string | undefined },\n outputBufferRef: { value: string },\n command: string,\n resultPromise: Promise<any>,\n): Promise<{ shouldReturn: boolean; result: any }> {\n return new Promise<{ shouldReturn: boolean; result: any }>((resolve) => {\n let checkInterval: NodeJS.Timeout | null = null;\n\n checkInterval = setInterval(() => {\n if (movedToBackgroundRef.value && backgroundTaskIdRef.value) {\n if (checkInterval) clearInterval(checkInterval);\n resolve(\n createBackgroundResult(\n command,\n backgroundTaskIdRef.value,\n outputBufferRef.value,\n ),\n );\n }\n }, 100);\n\n resultPromise\n .then(() => {\n if (checkInterval) clearInterval(checkInterval);\n if (!movedToBackgroundRef.value) {\n resolve({ shouldReturn: false, result: null });\n }\n })\n .catch(() => {\n if (checkInterval) clearInterval(checkInterval);\n resolve({ shouldReturn: false, result: null });\n });\n });\n}\n\n// ============================================================================\n// Command Execution\n// ============================================================================\n\nasync function executeCommand(\n command: string,\n timeout: number,\n cwd: string,\n runInBackground: boolean | undefined,\n backgroundTaskManager: BackgroundTaskManager,\n messageBus: MessageBus | undefined,\n pendingBackgroundMoves: Map<string, { moveToBackground: () => void }>,\n) {\n const actualTimeout = Math.min(timeout, MAX_TIMEOUT);\n\n // Validate command\n const validationError = validateCommand(command);\n if (validationError) {\n return {\n isError: true,\n llmContent: validationError,\n };\n }\n\n // Setup execution environment\n const isWindows = os.platform() === 'win32';\n const tempFileName = `shell_pgrep_${crypto.randomBytes(6).toString('hex')}.tmp`;\n const tempFilePath = path.join(os.tmpdir(), tempFileName);\n const shell = process.env.SHELL || '/bin/bash';\n const isFish = !isWindows && shell.endsWith('/fish');\n\n // Generate wrapped command for shell execution\n const wrappedCommand = isWindows\n ? command\n : (() => {\n let cmd = command.trim();\n if (!cmd.endsWith('&')) cmd += ';';\n if (isFish) {\n return `begin; ${cmd} end; set __code $status; pgrep -g 0 >${tempFilePath} 2>&1; exit $__code`;\n }\n return `{ ${cmd} }; __code=$?; pgrep -g 0 >${tempFilePath} 2>&1; exit $__code;`;\n })();\n\n debug('wrappedCommand', wrappedCommand);\n\n // Cleanup function\n const cleanupTempFile = () => {\n try {\n if (!isWindows && fs.existsSync(tempFilePath)) {\n fs.unlinkSync(tempFilePath);\n }\n } catch {\n // Ignore cleanup errors\n }\n };\n\n // State management\n const startTime = Date.now();\n let hasOutput = false;\n const outputBufferRef = { value: '' };\n const movedToBackgroundRef = { value: false };\n const backgroundTaskIdRef: { value: string | undefined } = { value: undefined };\n const isCommandCompletedRef = { value: false };\n let backgroundCheckInterval: ReturnType<typeof setInterval> | null = null;\n let backgroundPromptEmitted = false;\n\n // Execute command\n const { result: resultPromise, pid } = shellExecute(\n wrappedCommand,\n cwd,\n actualTimeout,\n (event) => {\n if (movedToBackgroundRef.value) {\n if (event.type === 'data' && backgroundTaskIdRef.value) {\n backgroundTaskManager.appendOutput(\n backgroundTaskIdRef.value,\n event.chunk,\n );\n }\n return;\n }\n\n if (event.type === 'data') {\n hasOutput = true;\n outputBufferRef.value += event.chunk;\n\n // Start background check if not already started\n if (!backgroundCheckInterval) {\n backgroundCheckInterval = setInterval(() => {\n if (movedToBackgroundRef.value || isCommandCompletedRef.value) {\n if (backgroundCheckInterval) clearInterval(backgroundCheckInterval);\n backgroundCheckInterval = null;\n return;\n }\n\n const elapsed = Date.now() - startTime;\n if (\n shouldRunInBackground(\n command,\n elapsed,\n hasOutput,\n isCommandCompletedRef.value,\n runInBackground,\n ) &&\n !backgroundPromptEmitted\n ) {\n backgroundPromptEmitted = true;\n\n // Trigger background transition\n if (runInBackground === true) {\n if (!movedToBackgroundRef.value) {\n movedToBackgroundRef.value = true;\n const backgroundPIDs = extractBackgroundPIDs(\n tempFilePath,\n pid,\n isWindows,\n );\n const pgid =\n backgroundPIDs.length > 0\n ? backgroundPIDs[0]\n : (pid ?? undefined);\n const backgroundTaskId =\n backgroundTaskManager.createTask({\n command,\n pid: pid ?? 0,\n pgid,\n });\n\n resultPromise.then((result) => {\n const status = result.cancelled\n ? 'killed'\n : result.exitCode === 0\n ? 'completed'\n : 'failed';\n backgroundTaskManager.updateTaskStatus(\n backgroundTaskId,\n status,\n result.exitCode,\n );\n });\n\n backgroundTaskIdRef.value = backgroundTaskId;\n }\n } else if (messageBus) {\n const tempTaskId = `temp_${crypto\n .randomBytes(6)\n .toString('hex')}`;\n pendingBackgroundMoves.set(tempTaskId, {\n moveToBackground: () => {\n movedToBackgroundRef.value = true;\n const backgroundPIDs = extractBackgroundPIDs(\n tempFilePath,\n pid,\n isWindows,\n );\n const pgid =\n backgroundPIDs.length > 0\n ? backgroundPIDs[0]\n : (pid ?? undefined);\n const backgroundTaskId =\n backgroundTaskManager.createTask({\n command,\n pid: pid ?? 0,\n pgid,\n });\n\n resultPromise.then((result) => {\n const status = result.cancelled\n ? 'killed'\n : result.exitCode === 0\n ? 'completed'\n : 'failed';\n backgroundTaskManager.updateTaskStatus(\n backgroundTaskId,\n status,\n result.exitCode,\n );\n });\n\n backgroundTaskIdRef.value = backgroundTaskId;\n },\n });\n\n const promptEvent: BashPromptBackgroundEvent = {\n taskId: tempTaskId,\n command,\n currentOutput: outputBufferRef.value,\n };\n\n messageBus.emitEvent(BASH_EVENTS.PROMPT_BACKGROUND, promptEvent);\n }\n\n if (backgroundCheckInterval) clearInterval(backgroundCheckInterval);\n backgroundCheckInterval = null;\n }\n }, BACKGROUND_CHECK_INTERVAL);\n }\n }\n },\n );\n\n // Monitor command completion\n resultPromise.finally(() => {\n isCommandCompletedRef.value = true;\n if (backgroundCheckInterval) {\n clearInterval(backgroundCheckInterval);\n backgroundCheckInterval = null;\n }\n });\n\n // Clear background prompt if needed\n const clearBackgroundPromptIfNeeded = () => {\n if (backgroundPromptEmitted && messageBus && !movedToBackgroundRef.value) {\n messageBus.emitEvent(BASH_EVENTS.BACKGROUND_MOVED, {});\n }\n };\n\n // Wait for background transition or command completion\n try {\n const backgroundCheckResult = await Promise.race([\n createBackgroundCheckPromise(\n movedToBackgroundRef,\n backgroundTaskIdRef,\n outputBufferRef,\n command,\n resultPromise,\n ),\n resultPromise.then(() => ({ shouldReturn: false, result: null })),\n ]);\n\n if (backgroundCheckResult.shouldReturn) {\n cleanupTempFile();\n clearBackgroundPromptIfNeeded();\n return backgroundCheckResult.result;\n }\n } catch (error) {\n cleanupTempFile();\n clearBackgroundPromptIfNeeded();\n throw error;\n }\n\n const result = await resultPromise;\n cleanupTempFile();\n clearBackgroundPromptIfNeeded();\n\n const backgroundPIDs = extractBackgroundPIDs(tempFilePath, result.pid, isWindows);\n\n const formatted = formatExecutionResult(\n result,\n command,\n wrappedCommand,\n cwd,\n backgroundPIDs,\n );\n debug('llmContent', formatted.llmContent);\n\n return formatted;\n}\n\n// ============================================================================\n// Tool Creation Functions\n// ============================================================================\n\nexport function createBashOutputTool(opts: {\n backgroundTaskManager: BackgroundTaskManager;\n}) {\n const { backgroundTaskManager } = opts;\n\n return createTool({\n name: TOOL_NAMES.BASH_OUTPUT,\n description: `Retrieve output from a background bash task.\n\nUsage:\n- Accepts a task_id parameter to identify the background task\n- Returns the accumulated stdout and stderr output\n- Shows current task status (running/completed/killed/failed)\n- Use this to monitor or check output from long-running background tasks\n- Task IDs are returned when commands are moved to background`,\n parameters: z.object({\n task_id: z.string().describe('The ID of the background task'),\n }),\n getDescription: ({ params }) => {\n if (!params.task_id || typeof params.task_id !== 'string') {\n return 'Read background task output';\n }\n return `Read output from task: ${params.task_id}`;\n },\n execute: async ({ task_id }) => {\n const task = backgroundTaskManager.getTask(task_id);\n if (!task) {\n return {\n isError: true,\n llmContent: `Task ${task_id} not found. Use bash tool to see available tasks.`,\n };\n }\n\n const lines = [\n `Command: ${task.command}`,\n `Status: ${task.status}`,\n `PID: ${task.pid}`,\n `Created: ${new Date(task.createdAt).toISOString()}`,\n '',\n 'Output:',\n task.output || '(no output yet)',\n ];\n\n if (task.exitCode !== null) {\n lines.push('', `Exit Code: ${task.exitCode}`);\n }\n\n return {\n llmContent: lines.join('\\n'),\n };\n },\n approval: {\n category: 'read',\n needsApproval: async () => false,\n },\n });\n}\n\nexport function createKillBashTool(opts: {\n backgroundTaskManager: BackgroundTaskManager;\n}) {\n const { backgroundTaskManager } = opts;\n\n return createTool({\n name: TOOL_NAMES.KILL_BASH,\n description: `Terminate a running background bash task.\n\nUsage:\n- Accepts a task_id parameter to identify the task to kill\n- Sends SIGTERM first, then SIGKILL if needed (Unix-like systems)\n- Returns success or failure status\n- Use this when you need to stop a long-running background task`,\n parameters: z.object({\n task_id: z\n .string()\n .describe('The ID of the background task to terminate'),\n }),\n getDescription: ({ params }) => {\n if (!params.task_id || typeof params.task_id !== 'string') {\n return 'Terminate background task';\n }\n return `Terminate task: ${params.task_id}`;\n },\n execute: async ({ task_id }) => {\n const task = backgroundTaskManager.getTask(task_id);\n if (!task) {\n return {\n isError: true,\n llmContent: `Task ${task_id} not found. Use bash tool to see available tasks.`,\n };\n }\n\n if (task.status !== 'running') {\n return {\n isError: true,\n llmContent: `Task ${task_id} is not running (status: ${task.status}). Cannot terminate.`,\n };\n }\n\n const success = await backgroundTaskManager.killTask(task_id);\n return {\n llmContent: success\n ? `Successfully terminated task ${task_id} (${task.command})`\n : `Failed to terminate task ${task_id}. Process may have already exited.`,\n isError: !success,\n };\n },\n approval: {\n category: 'command',\n needsApproval: async (context) => {\n return context.approvalMode !== 'yolo';\n },\n },\n });\n}\n\nexport function createBashTool(opts: {\n cwd: string;\n backgroundTaskManager: BackgroundTaskManager;\n messageBus?: MessageBus;\n}) {\n const { cwd, backgroundTaskManager, messageBus } = opts;\n\n // Track pending background moves\n const pendingBackgroundMoves = new Map<\n string,\n { moveToBackground: () => void }\n >();\n\n // Add background move listener only if messageBus is available\n if (messageBus) {\n messageBus.onEvent(\n BASH_EVENTS.MOVE_TO_BACKGROUND,\n ({ taskId }: { taskId: string }) => {\n const pendingMove = pendingBackgroundMoves.get(taskId);\n if (pendingMove) {\n pendingMove.moveToBackground();\n pendingBackgroundMoves.delete(taskId);\n messageBus.emitEvent(BASH_EVENTS.BACKGROUND_MOVED, { taskId });\n }\n },\n );\n }\n\n return createTool({\n name: TOOL_NAMES.BASH,\n description:\n `Run shell commands in the terminal, ensuring proper handling and security measures.\n\nBackground Execution:\n- Set run_in_background=true to force background execution\n- Background tasks return a task_id for use with ${\n TOOL_NAMES.BASH_OUTPUT\n } and ${TOOL_NAMES.KILL_BASH} tools\n- Initial output shown when moved to background\n\nBefore using this tool, please follow these steps:\n- Verify that the command is not one of the banned commands: ${BANNED_COMMANDS.join(\n ', ',\n )}.\n- Always quote file paths that contain spaces with double quotes (e.g., cd \"path with spaces/file.txt\")\n- Capture the output of the command.\n\nNotes:\n- The command argument is required.\n- You can specify an optional timeout in milliseconds (up to ${MAX_TIMEOUT}ms / 10 minutes). If not specified, commands will timeout after 2 minutes.\n- VERY IMPORTANT: You MUST avoid using search commands like \\`find\\` and \\`grep\\`. Instead use grep and glob tool to search. You MUST avoid read tools like \\`cat\\`, \\`head\\`, \\`tail\\`, and \\`ls\\`, and use \\`read\\` and \\`ls\\` tool to read files.\n- If you _still_ need to run \\`grep\\`, STOP. ALWAYS USE ripgrep at \\`rg\\` first, which all users have pre-installed.\n- When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).\n- Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of \\`cd\\`. You may use \\`cd\\` if the User explicitly requests it.\n- Don't add \\`<command>\\` wrapper to the command.\n\n<good-example>\npytest /foo/bar/tests\n</good-example>\n<bad-example>\ncd /foo/bar && pytest tests\n</bad-example>\n<bad-example>\n<command>pytest /foo/bar/tests</command>\n</bad-example>\n`.trim(),\n parameters: z.object({\n command: z.string().describe('The command to execute'),\n timeout: z\n .number()\n .optional()\n .describe(`Optional timeout in milliseconds (max ${MAX_TIMEOUT})`),\n run_in_background: z\n .boolean()\n .optional()\n .describe(\n 'Set to true to run this command in the background. Use bash_output to read output later.',\n ),\n description: z\n .string()\n .optional()\n .describe(`Clear, concise description of what this command does in 5-10 words, in active voice. Examples:\nInput: ls\nOutput: List files in current directory\n\nInput: git status\nOutput: Show working tree status\n\nInput: npm install\nOutput: Install package dependencies\n\nInput: mkdir foo\nOutput: Create directory 'foo'\n `),\n }),\n getDescription: ({ params }) => {\n if (!params.command || typeof params.command !== 'string') {\n return 'No command provided';\n }\n const command = params.command.trim();\n return command.length > 100 ? `${command.substring(0, 97)}...` : command;\n },\n execute: async ({\n command,\n timeout = DEFAULT_TIMEOUT,\n run_in_background,\n }) => {\n try {\n if (!command) {\n return {\n llmContent: 'Error: Command cannot be empty.',\n isError: true,\n };\n }\n return await executeCommand(\n command,\n timeout || DEFAULT_TIMEOUT,\n cwd,\n run_in_background,\n backgroundTaskManager,\n messageBus,\n pendingBackgroundMoves,\n );\n } catch (e) {\n return {\n isError: true,\n llmContent:\n e instanceof Error\n ? `Command execution failed: ${getErrorMessage(e)}`\n : 'Command execution failed.',\n };\n }\n },\n approval: {\n category: 'command',\n needsApproval: async (context) => {\n const { params, approvalMode } = context;\n const command = params.command as string;\n if (!command) {\n return false;\n }\n // Always require approval for high-risk commands\n if (isHighRiskCommand(command)) {\n return true;\n }\n // Check if command is banned (these should never be approved)\n const commandRoot = getCommandRoot(command);\n if (commandRoot && isBannedCommand(commandRoot)) {\n return true; // This will be denied by approval system\n }\n // For other commands, defer to approval mode settings\n return approvalMode !== 'yolo';\n },\n },\n });\n}\n","/**\n * Bash tool constants.\n * Centralized configuration for timeout, output limits, and background check intervals.\n */\n\n/** Default timeout for command execution (2 minutes). */\nexport const DEFAULT_TIMEOUT = 2 * 60 * 1000;\n\n/** Maximum timeout allowed for command execution (10 minutes). */\nexport const MAX_TIMEOUT = 10 * 60 * 1000;\n\n/** Background task check interval in milliseconds. */\nexport const BACKGROUND_CHECK_INTERVAL = 500;\n\n/** Default output limit in characters. */\nexport const DEFAULT_OUTPUT_LIMIT = 30_000;\n\n/** Maximum output limit in characters. */\nexport const MAX_OUTPUT_LIMIT = 150_000;\n\n/** Environment variable name for custom output limit. */\nexport const ENV_OUTPUT_LIMIT = 'BASH_MAX_OUTPUT_LENGTH';\n\n/**\n * List of banned commands that should never be executed.\n */\nexport const BANNED_COMMANDS: readonly string[] = [\n 'alias',\n 'aria2c',\n 'axel',\n 'bash',\n 'chrome',\n 'curl',\n 'curlie',\n 'eval',\n 'firefox',\n 'fish',\n 'http-prompt',\n 'httpie',\n 'links',\n 'lynx',\n 'nc',\n 'rm',\n 'safari',\n 'sh',\n 'source',\n 'telnet',\n 'w3m',\n 'wget',\n 'xh',\n 'zsh',\n];\n","/**\n * Bash command security validation utilities.\n * Provides functions to validate shell commands and detect security risks.\n */\n\nimport { BANNED_COMMANDS } from './constants';\n\n/**\n * Extract the root command from a command string.\n * @example\n * getCommandRoot(\"git status\") // \"git\"\n * getCommandRoot(\"/usr/bin/node test.js\") // \"node\"\n */\nexport function getCommandRoot(command: string): string | undefined {\n const root = command\n .trim()\n .replace(/[{}()]/g, '')\n .split(/[\\s;&|]+/)[0]\n ?.split(/[/\\\\]/)\n .pop();\n return root || undefined;\n}\n\n/**\n * Check if command contains command substitution ($() or backticks)\n * outside of safe contexts.\n *\n * Safe contexts:\n * - Inside single quotes (everything is literal)\n * - Escaped backticks inside double quotes\n *\n * @param command - The command string to check\n * @returns true if command substitution is detected\n */\nexport function hasCommandSubstitution(command: string): boolean {\n let inSingleQuote = false;\n let inDoubleQuote = false;\n let escaped = false;\n\n for (let i = 0; i < command.length; i++) {\n const char = command[i];\n\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === '\\\\') {\n escaped = true;\n continue;\n }\n\n if (char === \"'\" && !inDoubleQuote) {\n inSingleQuote = !inSingleQuote;\n continue;\n }\n\n if (char === '\"' && !inSingleQuote) {\n inDoubleQuote = !inDoubleQuote;\n continue;\n }\n\n if (inSingleQuote) {\n continue;\n }\n\n if (char === '`') {\n return true;\n }\n\n if (char === '$' && command[i + 1] === '(') {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Split command by pipe segments, handling quoted strings correctly.\n * @example\n * splitPipelineSegments('echo \"test|value\" | grep test')\n * // [\"echo \"test|value\"\", \"grep test\"]\n */\nfunction splitPipelineSegments(command: string): string[] {\n const segments: string[] = [];\n let current = '';\n let inSingleQuote = false;\n let inDoubleQuote = false;\n let escaped = false;\n\n for (let i = 0; i < command.length; i++) {\n const char = command[i];\n\n if (escaped) {\n current += char;\n escaped = false;\n continue;\n }\n\n if (char === '\\\\') {\n escaped = true;\n current += char;\n continue;\n }\n\n if (char === \"'\" && !inDoubleQuote) {\n inSingleQuote = !inSingleQuote;\n current += char;\n continue;\n }\n\n if (char === '\"' && !inSingleQuote) {\n inDoubleQuote = !inDoubleQuote;\n current += char;\n continue;\n }\n\n if (char === '|' && !inSingleQuote && !inDoubleQuote) {\n if (current.trim()) {\n segments.push(current.trim());\n }\n current = '';\n continue;\n }\n\n current += char;\n }\n\n if (current.trim()) {\n segments.push(current.trim());\n }\n\n return segments;\n}\n\n/** High risk patterns for command segments. */\nconst HIGH_RISK_PATTERNS = [\n /rm\\s+.*(-rf|--recursive)/i,\n /sudo/i,\n /dd\\s+if=/i,\n /mkfs/i,\n /fdisk/i,\n /format/i,\n /del\\s+.*\\/[qs]/i,\n];\n\n/**\n * Check if a single command segment is high risk.\n */\nfunction isSegmentHighRisk(segment: string): boolean {\n if (hasCommandSubstitution(segment)) {\n return true;\n }\n\n const commandRoot = getCommandRoot(segment);\n if (!commandRoot) {\n return true;\n }\n\n return (\n HIGH_RISK_PATTERNS.some((pattern) => pattern.test(segment)) ||\n BANNED_COMMANDS.includes(commandRoot.toLowerCase())\n );\n}\n\n/**\n * Check if command is high risk with pipeline segment fallback evaluation.\n *\n * Implements the same approach as codex PR #7544:\n * - First check the full command\n * - If command contains pipes, evaluate each segment separately\n * - If any segment is high risk, the entire command is high risk\n *\n * @param command - The command to check\n * @returns true if the command is high risk\n */\nexport function isHighRiskCommand(command: string): boolean {\n // Legacy patterns for specific dangerous combinations\n const legacyDangerousCombinations = [/curl.*\\|.*sh/i, /wget.*\\|.*sh/i];\n\n // Quick check for legacy dangerous combinations\n if (legacyDangerousCombinations.some((pattern) => pattern.test(command))) {\n return true;\n }\n\n // Check if command contains pipeline\n if (command.includes('|')) {\n // Split by pipeline and evaluate each segment\n const segments = splitPipelineSegments(command);\n\n // Fallback evaluation: check each segment independently\n for (const segment of segments) {\n if (isSegmentHighRisk(segment)) {\n return true;\n }\n }\n\n return false;\n }\n\n // For non-pipeline commands, use segment risk check\n return isSegmentHighRisk(command);\n}\n\n/**\n * Validate a command and return an error message if invalid.\n *\n * @param command - The command to validate\n * @returns null if valid, error message otherwise\n */\nexport function validateCommand(command: string): string | null {\n if (!command.trim()) {\n return 'Command cannot be empty.';\n }\n\n const commandRoot = getCommandRoot(command);\n if (!commandRoot) {\n return 'Could not identify command root.';\n }\n\n if (hasCommandSubstitution(command)) {\n return 'Command substitution is not allowed for security reasons.';\n }\n\n return null;\n}\n\n/**\n * Check if a command root is in the banned commands list.\n */\nexport function isBannedCommand(commandRoot: string): boolean {\n return BANNED_COMMANDS.includes(commandRoot.toLowerCase());\n}\n","import { BACKGROUND_THRESHOLD_MS } from '../core/constants';\nimport { getCommandRoot } from './bash/security';\n\nconst DEV_COMMANDS = [\n 'npm',\n 'pnpm',\n 'yarn',\n 'tnpm',\n 'cnpm',\n 'node',\n 'python',\n 'python3',\n 'go',\n 'cargo',\n 'make',\n 'docker',\n 'webpack',\n 'vite',\n 'jest',\n 'pytest',\n];\n\n// Re-export for backward compatibility\nexport { getCommandRoot } from './bash/security';\n\nexport function shouldRunInBackground(\n command: string,\n elapsedMs: number,\n hasOutput: boolean,\n isCommandCompleted: boolean,\n userRequested?: boolean,\n): boolean {\n // If command is completed, never move to background\n if (isCommandCompleted) {\n return false;\n }\n\n // Basic condition checks\n if (elapsedMs < BACKGROUND_THRESHOLD_MS || !hasOutput) {\n return false;\n }\n\n // User explicitly requested background execution\n if (userRequested) {\n return true;\n }\n\n // Check if it's a development command\n const commandRoot = getCommandRoot(command);\n if (!commandRoot) {\n return false;\n }\n\n return DEV_COMMANDS.includes(commandRoot.toLowerCase());\n}\n","import { TOOL_NAMES } from '../core/constants';\n\nexport function getErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n try {\n return String(error);\n } catch {\n return 'Failed to get error details';\n }\n}\n\nexport class MaxFileReadLengthExceededError extends Error {\n public readonly maxFileLength: number;\n public readonly fileLength: number;\n constructor(fileLength: number, maxFileLength: number) {\n super(\n `File content (${fileLength} characters) exceeds maximum allowed length (${maxFileLength} characters). Please use offset and limit parameters to read specific portions of the file, or use the ${TOOL_NAMES.GREP} tool to search for specific content.`,\n );\n this.name = 'MaxFileReadLengthExceededError';\n this.maxFileLength = maxFileLength;\n this.fileLength = fileLength;\n }\n}\n\nexport class MaxFileReadTokenExceededError extends Error {\n public readonly maxTokens: number;\n public readonly tokenCount: number;\n constructor(tokenCount: number, maxTokens: number) {\n super(\n `File content (${tokenCount} tokens) exceeds maximum allowed tokens (${maxTokens}). Please use offset and limit parameters to read specific portions of the file, or use the ${TOOL_NAMES.GREP} tool to search for specific content.`,\n );\n this.name = 'MaxFileReadTokenExceededError';\n this.maxTokens = maxTokens;\n this.tokenCount = tokenCount;\n }\n}\n","/**\n * Shell execution implementation with robust output handling and binary detection.\n * This implementation references the shell execution service from Google Gemini CLI,\n * with enhanced encoding detection and binary output handling capabilities.\n *\n * Based on Apache License, thanks to the original work:\n * ref: https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/services/shellExecutionService.ts\n */\nimport { spawn } from 'child_process';\nimport os from 'os';\nimport stripAnsi from 'strip-ansi';\nimport { TextDecoder } from 'util';\nimport { getCachedEncodingForBufferSync } from './system-encoding';\n\nconst SIGKILL_TIMEOUT_MS = 200;\nconst MAX_OUTPUT_SIZE = 100 * 1024 * 1024; // 100MB limit to prevent memory overflow\nconst BINARY_SNIFF_CHUNK_SIZE = 1024; // Process binary detection in smaller chunks\n\nexport interface ShellExecutionResult {\n /** The raw, unprocessed output buffer. */\n rawOutput: Buffer;\n /** The combined, decoded stdout and stderr as a string. */\n output: string;\n /** The decoded stdout as a string. */\n stdout: string;\n /** The decoded stderr as a string. */\n stderr: string;\n /** The process exit code, or null if terminated by a signal. */\n exitCode: number | null;\n /** The signal that terminated the process, if any. */\n signal: NodeJS.Signals | null;\n /** An error object if the process failed to spawn. */\n error: Error | null;\n /** The process ID of the spawned shell. */\n pid: number | undefined;\n /** Whether the execution was cancelled due to timeout or manual termination. */\n cancelled: boolean;\n}\n\nexport interface ShellExecutionHandle {\n /** The process ID of the spawned shell. */\n pid: number | undefined;\n /** A promise that resolves with the complete execution result. */\n result: Promise<ShellExecutionResult>;\n}\n\nexport type ShellOutputEvent =\n | {\n /** The event contains a chunk of output data. */\n type: 'data';\n /** The stream from which the data originated. */\n stream: 'stdout' | 'stderr';\n /** The decoded string chunk. */\n chunk: string;\n }\n | {\n /** Signals that the output stream has been identified as binary. */\n type: 'binary_detected';\n }\n | {\n /** Provides progress updates for a binary stream. */\n type: 'binary_progress';\n /** The total number of bytes received so far. */\n bytesReceived: number;\n };\n\nconst MAX_SNIFF_SIZE = 4096;\n\nexport function shellExecute(\n commandToExecute: string,\n cwd: string,\n timeout: number,\n // Reserved for future streaming output\n onOutputEvent?: (event: ShellOutputEvent) => void,\n): ShellExecutionHandle {\n const isWindows = os.platform() === 'win32';\n const shell = isWindows ? 'cmd.exe' : process.env.SHELL || '/bin/bash';\n const isFish = !isWindows && shell.endsWith('/fish');\n const isTTY = process.stdout.isTTY;\n const shellArgs = isWindows\n ? ['/c', commandToExecute]\n : isFish\n ? ['-l', '-c', commandToExecute]\n : isTTY\n ? ['-il', '-c', commandToExecute]\n : ['-l', '-c', commandToExecute];\n\n const child = spawn(shell, shellArgs, {\n cwd,\n stdio: ['ignore', 'pipe', 'pipe'],\n detached: !isWindows, // Use process groups on non-Windows for robust killing\n env: {\n ...process.env,\n TAKUMI_AI_CLI: '1',\n },\n });\n\n const result = new Promise<ShellExecutionResult>((resolve) => {\n // Use decoders to handle multi-byte characters safely (for streaming output).\n let stdoutDecoder: TextDecoder | null = null;\n let stderrDecoder: TextDecoder | null = null;\n\n // Use arrays to collect chunks, then join at the end for better performance\n const stdoutChunks: string[] = [];\n const stderrChunks: string[] = [];\n const outputChunks: Buffer[] = [];\n let totalOutputSize = 0;\n let error: Error | null = null;\n let exited = false;\n let cancelled = false;\n\n let isStreamingRawContent = true;\n let binaryDetected = false;\n let sniffBuffer = Buffer.alloc(0);\n let sniffedBytes = 0;\n\n const handleOutput = (data: Buffer, stream: 'stdout' | 'stderr') => {\n // Check memory limit to prevent overflow\n totalOutputSize += data.length;\n if (totalOutputSize > MAX_OUTPUT_SIZE) {\n cancelled = true;\n abortHandler();\n return;\n }\n\n if (!stdoutDecoder || !stderrDecoder) {\n const encoding = getCachedEncodingForBufferSync(data);\n try {\n stdoutDecoder = new TextDecoder(encoding);\n stderrDecoder = new TextDecoder(encoding);\n } catch {\n // If the encoding is not supported, fall back to utf-8.\n // This can happen on some platforms for certain encodings like 'utf-32le'.\n stdoutDecoder = new TextDecoder('utf-8');\n stderrDecoder = new TextDecoder('utf-8');\n }\n }\n\n outputChunks.push(data);\n\n // Optimized binary detection - avoid repeated Buffer.concat operations\n if (\n !binaryDetected &&\n isStreamingRawContent &&\n sniffedBytes < MAX_SNIFF_SIZE\n ) {\n const remainingSniffSize = Math.min(\n MAX_SNIFF_SIZE - sniffedBytes,\n BINARY_SNIFF_CHUNK_SIZE,\n );\n const dataToSniff = data.subarray(\n 0,\n Math.min(data.length, remainingSniffSize),\n );\n\n if (dataToSniff.length > 0) {\n sniffBuffer = Buffer.concat([sniffBuffer, dataToSniff]);\n sniffedBytes = sniffBuffer.length;\n\n if (isBinary(sniffBuffer)) {\n binaryDetected = true;\n isStreamingRawContent = false;\n onOutputEvent?.({ type: 'binary_detected' });\n }\n }\n }\n\n const decodedChunk =\n stream === 'stdout'\n ? stdoutDecoder.decode(data, { stream: true })\n : stderrDecoder.decode(data, { stream: true });\n const strippedChunk = stripAnsi(decodedChunk);\n\n // Collect chunks in arrays instead of string concatenation\n if (stream === 'stdout') {\n stdoutChunks.push(strippedChunk);\n } else {\n stderrChunks.push(strippedChunk);\n }\n\n if (isStreamingRawContent) {\n onOutputEvent?.({ type: 'data', stream, chunk: strippedChunk });\n } else {\n // Use cached totalOutputSize instead of reduce\n onOutputEvent?.({\n type: 'binary_progress',\n bytesReceived: totalOutputSize,\n });\n }\n };\n\n child.stdout.on('data', (data) => handleOutput(data, 'stdout'));\n child.stderr.on('data', (data) => handleOutput(data, 'stderr'));\n child.on('error', (err) => {\n error = err;\n });\n\n const abortHandler = async () => {\n if (child.pid && !exited) {\n if (isWindows) {\n spawn('taskkill', ['/pid', child.pid.toString(), '/f', '/t']);\n } else {\n try {\n // Kill the entire process group (negative PID).\n // SIGTERM first, then SIGKILL if it doesn't die.\n process.kill(-child.pid, 'SIGTERM');\n await new Promise((res) => setTimeout(res, SIGKILL_TIMEOUT_MS));\n if (!exited) {\n process.kill(-child.pid, 'SIGKILL');\n }\n } catch (_e) {\n // Fall back to killing just the main process if group kill fails.\n if (!exited) child.kill('SIGKILL');\n }\n }\n }\n };\n\n // Set up timeout\n const timeoutId = setTimeout(() => {\n cancelled = true;\n abortHandler();\n }, timeout);\n\n child.on('exit', (code, signal) => {\n exited = true;\n clearTimeout(timeoutId);\n\n // Flush any remaining decoder content\n if (stdoutDecoder) {\n const finalStdoutChunk = stripAnsi(stdoutDecoder.decode());\n if (finalStdoutChunk) {\n stdoutChunks.push(finalStdoutChunk);\n }\n }\n if (stderrDecoder) {\n const finalStderrChunk = stripAnsi(stderrDecoder.decode());\n if (finalStderrChunk) {\n stderrChunks.push(finalStderrChunk);\n }\n }\n\n // Join chunks efficiently at the end\n const stdout = stdoutChunks.join('');\n const stderr = stderrChunks.join('');\n const finalBuffer =\n outputChunks.length > 0 ? Buffer.concat(outputChunks) : Buffer.alloc(0);\n\n resolve({\n rawOutput: finalBuffer,\n output: stdout + (stderr ? `\\n${stderr}` : ''),\n stdout,\n stderr,\n exitCode: code,\n signal,\n error,\n pid: child.pid,\n cancelled,\n });\n });\n });\n\n return { pid: child.pid, result };\n}\n\nexport function isBinary(\n data: Buffer | null | undefined,\n sampleSize = 512,\n): boolean {\n if (!data || data.length === 0) {\n return false;\n }\n\n const sample = data.length > sampleSize ? data.subarray(0, sampleSize) : data;\n\n // Use indexOf for faster null byte detection\n // This is significantly faster than iterating through each byte\n return sample.indexOf(0) !== -1;\n}\n","export default function ansiRegex({onlyFirst = false} = {}) {\n\t// Valid string terminator sequences are BEL, ESC\\, and 0x9c\n\tconst ST = '(?:\\\\u0007|\\\\u001B\\\\u005C|\\\\u009C)';\n\n\t// OSC sequences only: ESC ] ... ST (non-greedy until the first ST)\n\tconst osc = `(?:\\\\u001B\\\\][\\\\s\\\\S]*?${ST})`;\n\n\t// CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :) then final byte\n\tconst csi = '[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:\\\\d{1,4}(?:[;:]\\\\d{0,4})*)?[\\\\dA-PR-TZcf-nq-uy=><~]';\n\n\tconst pattern = `${osc}|${csi}`;\n\n\treturn new RegExp(pattern, onlyFirst ? undefined : 'g');\n}\n","import ansiRegex from 'ansi-regex';\n\nconst regex = ansiRegex();\n\nexport default function stripAnsi(string) {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError(`Expected a \\`string\\`, got \\`${typeof string}\\``);\n\t}\n\n\t// Fast path: ANSI codes require ESC (7-bit) or CSI (8-bit) introducer\n\tif (!string.includes('\\u001B') && !string.includes('\\u009B')) {\n\t\treturn string;\n\t}\n\n\t// Even though the regex is global, we don't need to reset the `.lastIndex`\n\t// because unlike `.exec()` and `.test()`, `.replace()` does it automatically\n\t// and doing it manually has a performance penalty.\n\treturn string.replace(regex, '');\n}\n","import { detect as chardetDetect } from 'chardet';\nimport { execSync } from 'child_process';\nimport os from 'os';\n\ntype SystemEncoding = string | null;\ntype CacheState = 'uninitialized' | 'checking' | 'cached';\n\ninterface EncodingCache {\n state: CacheState;\n value: SystemEncoding;\n}\n\n// Enhanced cache with state tracking to prevent multiple concurrent system calls\nlet encodingCache: EncodingCache = {\n state: 'uninitialized',\n value: null,\n};\n\n// Promise to handle concurrent calls during system encoding detection\nlet pendingSystemEncodingDetection: Promise<SystemEncoding> | null = null;\n\n/**\n * Windows code page to encoding mapping with comprehensive coverage\n */\nconst WINDOWS_CODE_PAGE_MAP = new Map<number, string>([\n // DOS code pages\n [437, 'cp437'],\n [850, 'cp850'],\n [852, 'cp852'],\n [866, 'cp866'],\n\n // Asian code pages\n [874, 'windows-874'], // Thai\n [932, 'shift_jis'], // Japanese\n [936, 'gb2312'], // Simplified Chinese\n [949, 'euc-kr'], // Korean\n [950, 'big5'], // Traditional Chinese\n\n // Unicode\n [1200, 'utf-16le'],\n [1201, 'utf-16be'],\n [65001, 'utf-8'],\n\n // Windows code pages\n [1250, 'windows-1250'], // Central European\n [1251, 'windows-1251'], // Cyrillic\n [1252, 'windows-1252'], // Western European\n [1253, 'windows-1253'], // Greek\n [1254, 'windows-1254'], // Turkish\n [1255, 'windows-1255'], // Hebrew\n [1256, 'windows-1256'], // Arabic\n [1257, 'windows-1257'], // Baltic\n [1258, 'windows-1258'], // Vietnamese\n]);\n\n/**\n * Common encoding aliases for normalization\n */\nconst ENCODING_ALIASES = new Map<string, string>([\n ['utf8', 'utf-8'],\n ['ascii', 'ascii'],\n ['latin1', 'iso-8859-1'],\n ['iso88591', 'iso-8859-1'],\n]);\n\n/**\n * Reset the encoding cache - useful for testing or when system configuration changes\n */\nexport function resetEncodingCache(): void {\n encodingCache = {\n state: 'uninitialized',\n value: null,\n };\n pendingSystemEncodingDetection = null;\n}\n\n/**\n * Returns the system encoding with caching and fallback to buffer detection.\n * Handles concurrent calls gracefully and provides robust error recovery.\n *\n * @param buffer - Buffer to analyze if system detection fails\n * @returns The detected encoding or 'utf-8' as ultimate fallback\n */\nexport async function getCachedEncodingForBuffer(\n buffer: Buffer,\n): Promise<string> {\n const systemEncoding = await getSystemEncodingCached();\n\n if (systemEncoding) {\n return systemEncoding;\n }\n\n // Fallback to buffer-specific detection\n const bufferEncoding = detectEncodingFromBuffer(buffer);\n return bufferEncoding || 'utf-8';\n}\n\n/**\n * Synchronous version for backward compatibility\n * Note: This may block on first call if system encoding hasn't been cached\n */\nexport function getCachedEncodingForBufferSync(buffer: Buffer): string {\n // If we have a cached result, use it\n if (encodingCache.state === 'cached') {\n return encodingCache.value || detectEncodingFromBuffer(buffer) || 'utf-8';\n }\n\n // If not cached, do synchronous detection\n if (encodingCache.state === 'uninitialized') {\n encodingCache.state = 'cached';\n encodingCache.value = getSystemEncodingSync();\n }\n\n return encodingCache.value || detectEncodingFromBuffer(buffer) || 'utf-8';\n}\n\n/**\n * Get system encoding with caching and concurrent call handling\n */\nasync function getSystemEncodingCached(): Promise<SystemEncoding> {\n if (encodingCache.state === 'cached') {\n return encodingCache.value;\n }\n\n if (encodingCache.state === 'checking' && pendingSystemEncodingDetection) {\n return pendingSystemEncodingDetection;\n }\n\n encodingCache.state = 'checking';\n pendingSystemEncodingDetection = Promise.resolve(getSystemEncodingSync());\n\n try {\n const result = await pendingSystemEncodingDetection;\n encodingCache.state = 'cached';\n encodingCache.value = result;\n return result;\n } catch (error) {\n encodingCache.state = 'uninitialized';\n console.warn('Failed to detect system encoding:', error);\n return null;\n } finally {\n pendingSystemEncodingDetection = null;\n }\n}\n\n/**\n * Detects system encoding based on platform with improved error handling\n *\n * @returns The system encoding or null if detection fails\n */\nexport function getSystemEncodingSync(): SystemEncoding {\n try {\n return os.platform() === 'win32' ? getWindowsEncoding() : getUnixEncoding();\n } catch (error) {\n console.warn('System encoding detection failed:', error);\n return null;\n }\n}\n\n/**\n * Get encoding on Windows systems using chcp command\n */\nfunction getWindowsEncoding(): SystemEncoding {\n try {\n const output = execSync('chcp', {\n encoding: 'utf8',\n timeout: 5000,\n windowsHide: true,\n });\n\n const match = output.match(/:\\s*(\\d+)/);\n if (!match) {\n throw new Error(`Cannot parse chcp output: \"${output.trim()}\"`);\n }\n\n const codePage = parseInt(match[1], 10);\n if (isNaN(codePage)) {\n throw new Error(`Invalid code page number: \"${match[1]}\"`);\n }\n\n return windowsCodePageToEncoding(codePage);\n } catch (error) {\n console.warn(\n `Windows encoding detection failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n return null;\n }\n}\n\n/**\n * Get encoding on Unix-like systems using environment variables and locale\n */\nfunction getUnixEncoding(): SystemEncoding {\n const env = process.env;\n let locale = env.LC_ALL || env.LC_CTYPE || env.LANG;\n\n // Try environment variables first\n if (locale) {\n const encoding = parseLocaleEncoding(locale);\n if (encoding) {\n return encoding;\n }\n }\n\n // Fallback to locale command\n try {\n locale = execSync('locale charmap', {\n encoding: 'utf8',\n timeout: 5000,\n stdio: ['ignore', 'pipe', 'ignore'], // Suppress stderr\n })\n .toString()\n .trim();\n\n return parseLocaleEncoding(locale);\n } catch (error) {\n console.warn('Failed to get locale charmap:', error);\n return null;\n }\n}\n\n/**\n * Parse encoding from locale string with better handling of various formats\n */\nfunction parseLocaleEncoding(locale: string): SystemEncoding {\n if (!locale) {\n return null;\n }\n\n // Handle format like \"en_US.UTF-8\" or \"en_US.utf8\"\n const match = locale.match(/\\.([^@]+)/);\n if (match && match[1]) {\n return normalizeEncoding(match[1]);\n }\n\n // Handle cases where locale is just the encoding name\n if (locale && !locale.includes('.') && !locale.includes('_')) {\n return normalizeEncoding(locale);\n }\n\n return null;\n}\n\n/**\n * Normalize encoding name to standard format\n */\nfunction normalizeEncoding(encoding: string): string {\n const normalized = encoding.toLowerCase().replace(/[-_]/g, '');\n const alias = ENCODING_ALIASES.get(normalized);\n return alias || encoding.toLowerCase();\n}\n\n/**\n * Convert Windows code page to encoding with comprehensive mapping\n *\n * @param cp - Windows code page number\n * @returns Corresponding encoding name or null if unmapped\n */\nexport function windowsCodePageToEncoding(cp: number): SystemEncoding {\n const encoding = WINDOWS_CODE_PAGE_MAP.get(cp);\n\n if (!encoding) {\n console.warn(`Unknown Windows code page: ${cp}`);\n return null;\n }\n\n return encoding;\n}\n\n/**\n * Detect encoding from buffer using chardet with enhanced error handling\n *\n * @param buffer - Buffer to analyze\n * @returns Detected encoding in lowercase or null if detection fails\n */\nexport function detectEncodingFromBuffer(buffer: Buffer): SystemEncoding {\n if (!buffer || buffer.length === 0) {\n return null;\n }\n\n try {\n const detected = chardetDetect(buffer);\n\n if (typeof detected === 'string' && detected.length > 0) {\n return normalizeEncoding(detected);\n }\n\n return null;\n } catch (error) {\n console.warn('Chardet encoding detection failed:', error);\n return null;\n }\n}\n\n// Maintain backward compatibility\nexport const getSystemEncoding = getSystemEncodingSync;\n","/**\n * Bash output processing utilities.\n * Provides functions to format, truncate, and process command output.\n */\n\nimport { getErrorMessage } from '../error';\nimport {\n DEFAULT_OUTPUT_LIMIT,\n ENV_OUTPUT_LIMIT,\n MAX_OUTPUT_LIMIT,\n} from './constants';\n\n/**\n * Remove leading and trailing empty lines from content.\n * Preserves middle empty lines and indentation.\n *\n * @param content - The content to trim\n * @returns Content with leading/trailing empty lines removed\n */\nexport function trimEmptyLines(content: string): string {\n const lines = content.split('\\n');\n\n let start = 0;\n while (start < lines.length && lines[start].trim() === '') {\n start++;\n }\n\n let end = lines.length - 1;\n while (end > start && lines[end].trim() === '') {\n end--;\n }\n\n return lines.slice(start, end + 1).join('\\n');\n}\n\n/**\n * Get the maximum output limit from environment or default.\n *\n * @returns The maximum output limit in characters\n */\nexport function getMaxOutputLimit(): number {\n const envValue = process.env[ENV_OUTPUT_LIMIT];\n if (!envValue) return DEFAULT_OUTPUT_LIMIT;\n\n const limit = parseInt(envValue, 10);\n if (isNaN(limit) || limit <= 0) return DEFAULT_OUTPUT_LIMIT;\n\n return Math.min(limit, MAX_OUTPUT_LIMIT);\n}\n\n/**\n * Truncate output to specified limit, showing line count if truncated.\n *\n * @param content - The content to truncate\n * @param limit - Optional limit (defaults to getMaxOutputLimit())\n * @returns Truncated content with notice if truncated\n */\nexport function truncateOutput(content: string, limit?: number): string {\n const trimmed = trimEmptyLines(content);\n const maxLimit = limit ?? getMaxOutputLimit();\n\n if (trimmed.length <= maxLimit) {\n return trimmed;\n }\n\n const kept = trimmed.slice(0, maxLimit);\n const droppedContent = trimmed.slice(maxLimit);\n const droppedLines = droppedContent.split('\\n').length;\n\n return `${kept}\\n\\n... [${droppedLines} lines truncated] ...`;\n}\n\n/**\n * Format shell execution result for display.\n *\n * @param result - The shell execution result\n * @param command - The original command\n * @param wrappedCommand - The wrapped command for shell execution\n * @param cwd - The current working directory\n * @param backgroundPIDs - List of background process IDs\n * @returns Formatted result with llmContent and returnDisplay\n */\nexport function formatExecutionResult(\n result: {\n output: string;\n stdout?: string;\n stderr?: string;\n exitCode: number | null;\n signal: NodeJS.Signals | null;\n error?: Error | null;\n pid?: number;\n cancelled?: boolean;\n },\n command: string,\n wrappedCommand: string,\n cwd: string,\n backgroundPIDs: number[],\n): { llmContent: string; returnDisplay: string } {\n let llmContent = '';\n if (result.cancelled) {\n llmContent = 'Command execution timed out and was cancelled.';\n if (result.output.trim()) {\n llmContent += ` Below is the output (on stdout and stderr) before it was cancelled:\\n${result.output}`;\n } else {\n llmContent += ' There was no output before it was cancelled.';\n }\n } else {\n const finalError = result.error\n ? result.error.message.replace(wrappedCommand, command)\n : '(none)';\n llmContent = [\n `Command: ${command}`,\n `Directory: ${cwd || '(root)'}`,\n `Stdout: ${result.stdout || '(empty)'}`,\n `Stderr: ${result.stderr || '(empty)'}`,\n `Error: ${finalError}`,\n `Exit Code: ${result.exitCode ?? '(none)'}`,\n `Signal: ${result.signal ?? '(none)'}`,\n `Background PIDs: ${\n backgroundPIDs.length ? backgroundPIDs.join(', ') : '(none)'\n }`,\n `Process Group PGID: ${result.pid ?? '(none)'}`,\n ].join('\\n');\n }\n\n let message = '';\n if (result.output) {\n const safeOutput = typeof result.output === 'string' ? result.output : String(result.output);\n if (safeOutput.trim()) {\n message = truncateOutput(safeOutput);\n }\n } else if (result.cancelled) {\n message = 'Command execution timed out and was cancelled.';\n } else if (result.signal) {\n message = `Command execution was terminated by signal ${result.signal}.`;\n } else if (result.error) {\n message = `Command failed: ${getErrorMessage(result.error)}`;\n } else if (result.exitCode !== null && result.exitCode !== 0) {\n message = `Command exited with code: ${result.exitCode}`;\n } else {\n message = 'Command executed successfully.';\n }\n\n return { llmContent, returnDisplay: message };\n}\n","import fs from 'fs';\nimport path from 'pathe';\nimport { z } from 'zod';\nimport { TOOL_NAMES } from '../../core/constants';\nimport { createTool } from '../tool';\nimport { applyEdits } from '../../utils/applyEdit';\n\nexport function createEditTool(opts: { cwd: string }) {\n return createTool({\n name: TOOL_NAMES.EDIT,\n description: `\nPerforms exact string replacements in files.\n\nUsage:\n- You must use your ${TOOL_NAMES.READ} tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.\n- When editing text from ${TOOL_NAMES.READ} tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.\n- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.\n- The edit will FAIL if \\`old_string\\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \\`replace_all\\` to change every instance of \\`old_string\\`.\n- Use \\`replace_all\\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.\n- For moving or renaming files, you should generally use the ${TOOL_NAMES.BASH} tool with the 'mv' command instead.\n- For larger edits, use the ${TOOL_NAMES.WRITE} tool to overwrite files.\n- For file creation, use the ${TOOL_NAMES.WRITE} tool.\n`.trim(),\n parameters: z.object({\n file_path: z.string().describe('The path of the file to modify'),\n old_string: z.string().describe('The text to replace'),\n new_string: z\n .string()\n .describe('The text to replace the old_string with'),\n replace_all: z\n .boolean()\n .default(false)\n .describe(\n 'Whether to replace all occurrences of old_string with new_string',\n ),\n }),\n getDescription: ({ params, cwd }) => {\n if (!params.file_path || typeof params.file_path !== 'string') {\n return 'No file path provided';\n }\n return path.relative(cwd, params.file_path);\n },\n execute: async ({ file_path, old_string, new_string, replace_all }) => {\n if (old_string === new_string) {\n return {\n isError: true,\n llmContent: 'new_string must differ from old_string',\n };\n }\n try {\n const cwd = opts.cwd;\n const fullFilePath = path.isAbsolute(file_path)\n ? file_path\n : path.resolve(cwd, file_path);\n const relativeFilePath = path.relative(cwd, fullFilePath);\n const { patch, updatedFile, startLineNumber } = applyEdits(\n cwd,\n fullFilePath,\n [{ old_string, new_string, replace_all }],\n );\n const dir = path.dirname(fullFilePath);\n fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(fullFilePath, updatedFile, 'utf-8');\n return {\n llmContent: `File ${file_path} successfully edited.`,\n returnDisplay: {\n type: 'diff_viewer',\n filePath: relativeFilePath,\n originalContent: { inputKey: 'old_string' },\n newContent: { inputKey: 'new_string' },\n absoluteFilePath: fullFilePath,\n startLineNumber,\n },\n };\n } catch (e) {\n return {\n isError: true,\n llmContent: e instanceof Error ? e.message : 'Unknown error',\n };\n }\n },\n approval: {\n category: 'write',\n },\n });\n}\n","import * as Diff from 'diff';\nimport { readFileSync } from 'fs';\nimport { isAbsolute, resolve } from 'pathe';\n\nexport interface Edit {\n old_string: string;\n new_string: string;\n replace_all?: boolean;\n}\n\nexport interface Hunk {\n oldStart: number;\n oldLines: number;\n newStart: number;\n newLines: number;\n lines: string[];\n}\n\n/**\n * Calculate Levenshtein distance between two strings\n * Used for similarity calculation in BlockAnchorReplacer\n */\nfunction levenshtein(a: string, b: string): number {\n const matrix: number[][] = [];\n\n // Initialize matrix\n for (let i = 0; i <= b.length; i++) {\n matrix[i] = [i];\n }\n for (let j = 0; j <= a.length; j++) {\n matrix[0][j] = j;\n }\n\n // Fill matrix\n for (let i = 1; i <= b.length; i++) {\n for (let j = 1; j <= a.length; j++) {\n if (b.charAt(i - 1) === a.charAt(j - 1)) {\n matrix[i][j] = matrix[i - 1][j - 1];\n } else {\n matrix[i][j] = Math.min(\n matrix[i - 1][j - 1] + 1, // substitution\n matrix[i][j - 1] + 1, // insertion\n matrix[i - 1][j] + 1, // deletion\n );\n }\n }\n }\n\n return matrix[b.length][a.length];\n}\n\n/**\n * Try line-trimmed matching: ignore leading/trailing whitespace on each line\n * Solves indentation difference issues\n * Returns null if multiple matches found to avoid ambiguity\n */\nfunction tryLineTrimmedMatch(content: string, oldStr: string): string | null {\n const contentLines = content.split('\\n');\n const searchLines = oldStr.split('\\n');\n const matches: string[] = [];\n\n for (let i = 0; i <= contentLines.length - searchLines.length; i++) {\n let isMatch = true;\n for (let j = 0; j < searchLines.length; j++) {\n if (contentLines[i + j].trim() !== searchLines[j].trim()) {\n isMatch = false;\n break;\n }\n }\n\n if (isMatch) {\n const matchedLines = contentLines.slice(i, i + searchLines.length);\n matches.push(matchedLines.join('\\n'));\n }\n }\n\n if (matches.length === 1) {\n return matches[0];\n }\n\n return null;\n}\n\n/**\n * Try block anchor matching: use first/last lines as anchors + Levenshtein similarity\n * Solves code blocks with slight modifications in middle lines\n * Requires at least 3 lines\n *\n * Similarity thresholds:\n * - Single candidate: 0.0 (more lenient)\n * - Multiple candidates: 0.3 (more strict)\n */\nfunction tryBlockAnchorMatch(content: string, oldStr: string): string | null {\n const SINGLE_CANDIDATE_SIMILARITY_THRESHOLD = 0.5;\n const MULTIPLE_CANDIDATES_SIMILARITY_THRESHOLD = 0.3;\n\n const contentLines = content.split('\\n');\n const searchLines = oldStr.split('\\n');\n\n // Require at least 3 lines for this strategy\n if (searchLines.length < 3) {\n return null;\n }\n\n const firstLine = searchLines[0].trim();\n const lastLine = searchLines[searchLines.length - 1].trim();\n\n // Collect all candidates where first and last lines match\n const candidates: Array<{ startLine: number; endLine: number }> = [];\n\n for (let i = 0; i < contentLines.length; i++) {\n if (contentLines[i].trim() !== firstLine) continue;\n\n for (let j = i + 2; j < contentLines.length; j++) {\n if (contentLines[j].trim() === lastLine) {\n candidates.push({ startLine: i, endLine: j });\n }\n }\n }\n\n if (candidates.length === 0) {\n return null;\n }\n\n // Helper function to calculate similarity for a candidate\n const calculateSimilarity = (candidate: {\n startLine: number;\n endLine: number;\n }): number => {\n const blockSize = candidate.endLine - candidate.startLine + 1;\n const middleLines = Math.min(blockSize - 2, searchLines.length - 2);\n\n if (middleLines <= 0) return 1.0; // Only first and last lines, already matched\n\n let totalSimilarity = 0;\n\n for (let k = 1; k <= middleLines; k++) {\n const contentLine = contentLines[candidate.startLine + k];\n const searchLine = searchLines[k];\n const maxLen = Math.max(contentLine.length, searchLine.length);\n\n if (maxLen === 0) {\n totalSimilarity += 1.0;\n } else {\n const distance = levenshtein(contentLine, searchLine);\n totalSimilarity += 1 - distance / maxLen;\n }\n }\n\n return totalSimilarity / middleLines;\n };\n\n // Single candidate scenario - use more lenient threshold\n if (candidates.length === 1) {\n const candidate = candidates[0];\n const similarity = calculateSimilarity(candidate);\n\n if (similarity >= SINGLE_CANDIDATE_SIMILARITY_THRESHOLD) {\n const matchedLines = contentLines.slice(\n candidate.startLine,\n candidate.endLine + 1,\n );\n return matchedLines.join('\\n');\n }\n\n return null;\n }\n\n // Multiple candidates scenario - find best match above threshold\n let bestMatch: string | null = null;\n let maxSimilarity = -1;\n\n for (const candidate of candidates) {\n const similarity = calculateSimilarity(candidate);\n\n if (\n similarity > maxSimilarity &&\n similarity >= MULTIPLE_CANDIDATES_SIMILARITY_THRESHOLD\n ) {\n maxSimilarity = similarity;\n const matchedLines = contentLines.slice(\n candidate.startLine,\n candidate.endLine + 1,\n );\n bestMatch = matchedLines.join('\\n');\n }\n }\n\n return bestMatch;\n}\n\n/**\n * Try whitespace-normalized matching: replace all consecutive whitespace with single space\n * Solves extra spaces and tab mixing issues\n * Returns null if multiple matches found to avoid ambiguity\n */\nfunction tryWhitespaceNormalizedMatch(\n content: string,\n oldStr: string,\n): string | null {\n const normalize = (text: string) => text.replace(/\\s+/g, ' ').trim();\n const normalizedOld = normalize(oldStr);\n const lines = content.split('\\n');\n const matches: string[] = [];\n\n // Single-line matching\n for (const line of lines) {\n if (normalize(line) === normalizedOld) {\n matches.push(line);\n }\n }\n\n if (matches.length === 1) {\n return matches[0];\n }\n\n // Multi-line matching\n const oldLines = oldStr.split('\\n');\n if (oldLines.length > 1) {\n const multiLineMatches: string[] = [];\n for (let i = 0; i <= lines.length - oldLines.length; i++) {\n const block = lines.slice(i, i + oldLines.length).join('\\n');\n if (normalize(block) === normalizedOld) {\n multiLineMatches.push(block);\n }\n }\n if (multiLineMatches.length === 1) {\n return multiLineMatches[0];\n }\n }\n\n return null;\n}\n\n/**\n * Unescape string (handle LLM over-escaping issues)\n * Reference: unescapeStringForGeminiBug in edit-logic-analysis.md\n */\nfunction unescapeStringForGeminiBug(inputString: string): string {\n return inputString.replace(\n /\\\\+(n|t|r|'|\"|`|\\\\|\\n)/g,\n (match, capturedChar) => {\n switch (capturedChar) {\n case 'n':\n return '\\n';\n case 't':\n return '\\t';\n case 'r':\n return '\\r';\n case \"'\":\n return \"'\";\n case '\"':\n return '\"';\n case '`':\n return '`';\n case '\\\\':\n return '\\\\';\n case '\\n':\n return '\\n';\n default:\n return match;\n }\n },\n );\n}\n\n/**\n * Try escape-normalized matching: handle over-escaped strings\n * Solves LLM-generated \\\\n, \\\\t escape issues\n */\nfunction tryEscapeNormalizedMatch(\n content: string,\n oldStr: string,\n): string | null {\n const unescaped = unescapeStringForGeminiBug(oldStr);\n\n // Direct matching\n if (content.includes(unescaped)) {\n return unescaped;\n }\n\n // Multi-line block matching\n const lines = content.split('\\n');\n const unescapedLines = unescaped.split('\\n');\n\n if (unescapedLines.length > 1) {\n for (let i = 0; i <= lines.length - unescapedLines.length; i++) {\n const block = lines.slice(i, i + unescapedLines.length).join('\\n');\n if (unescapeStringForGeminiBug(block) === unescaped) {\n return block;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Remove common indentation from text\n */\nfunction removeCommonIndentation(text: string): string {\n const lines = text.split('\\n');\n const nonEmptyLines = lines.filter((line) => line.trim().length > 0);\n\n if (nonEmptyLines.length === 0) return text;\n\n // Find minimum indentation\n const minIndent = Math.min(\n ...nonEmptyLines.map((line) => {\n const match = line.match(/^(\\s*)/);\n return match ? match[1].length : 0;\n }),\n );\n\n // Remove minimum common indentation\n return lines\n .map((line) => (line.trim().length === 0 ? line : line.slice(minIndent)))\n .join('\\n');\n}\n\n/**\n * Try indentation-flexible matching: ignore overall indentation level differences\n * Solves code block movement to different indentation levels\n * Returns null if multiple matches found to avoid ambiguity\n */\nfunction tryIndentationFlexibleMatch(\n content: string,\n oldStr: string,\n): string | null {\n const normalizedSearch = removeCommonIndentation(oldStr);\n const contentLines = content.split('\\n');\n const searchLines = oldStr.split('\\n');\n const matches: string[] = [];\n\n for (let i = 0; i <= contentLines.length - searchLines.length; i++) {\n const block = contentLines.slice(i, i + searchLines.length).join('\\n');\n if (removeCommonIndentation(block) === normalizedSearch) {\n matches.push(block);\n }\n }\n\n if (matches.length === 1) {\n return matches[0];\n }\n\n return null;\n}\n\n/**\n * Apply string replacement using multiple strategies to improve match success rate\n * Strategies are tried in priority order, using the first successful one\n *\n * Strategy chain (in priority order):\n * 1. Exact match\n * 2. Line-trimmed match (ignoring indentation)\n * 3. Block anchor match (using first/last lines + similarity)\n * 4. Whitespace-normalized match (handling extra spaces)\n * 5. Escape-normalized match (handling over-escaping)\n * 6. Indentation-flexible match (ignoring base indentation level)\n *\n * Note: If a strategy finds multiple matches and replace_all=false,\n * it will continue to the next more precise strategy (but current implementation\n * performs replacement directly, as subsequent strategies typically find the same\n * or more matches)\n */\nfunction applyStringReplace(\n content: string,\n oldStr: string,\n newStr: string,\n replaceAll = false,\n): { result: string; matchIndex: number } {\n const performReplace = (\n text: string,\n search: string,\n replace: string,\n matchIdx: number,\n ): { result: string; matchIndex: number } => {\n if (replaceAll) {\n const escapedSearch = search.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return {\n result: text.replace(new RegExp(escapedSearch, 'g'), () => replace),\n matchIndex: matchIdx,\n };\n }\n return {\n result: text.replace(search, () => replace),\n matchIndex: matchIdx,\n };\n };\n\n // Strategy 1: Exact match\n if (content.includes(oldStr)) {\n const matchIndex = content.indexOf(oldStr);\n if (newStr !== '') {\n return performReplace(content, oldStr, newStr, matchIndex);\n }\n\n const hasTrailingNewline =\n !oldStr.endsWith('\\n') && content.includes(`${oldStr}\\n`);\n\n return hasTrailingNewline\n ? performReplace(content, `${oldStr}\\n`, newStr, matchIndex)\n : performReplace(content, oldStr, newStr, matchIndex);\n }\n\n // Strategy 2: Line-trimmed match\n const lineTrimmedMatch = tryLineTrimmedMatch(content, oldStr);\n if (lineTrimmedMatch) {\n const matchIndex = content.indexOf(lineTrimmedMatch);\n return performReplace(content, lineTrimmedMatch, newStr, matchIndex);\n }\n\n // Strategy 3: Block anchor match (first/last lines + similarity)\n const blockAnchorMatch = tryBlockAnchorMatch(content, oldStr);\n if (blockAnchorMatch) {\n const matchIndex = content.indexOf(blockAnchorMatch);\n return performReplace(content, blockAnchorMatch, newStr, matchIndex);\n }\n\n // Strategy 4: Whitespace-normalized match\n const whitespaceMatch = tryWhitespaceNormalizedMatch(content, oldStr);\n if (whitespaceMatch) {\n const matchIndex = content.indexOf(whitespaceMatch);\n return performReplace(content, whitespaceMatch, newStr, matchIndex);\n }\n\n // Strategy 5: Escape-normalized match\n const escapeMatch = tryEscapeNormalizedMatch(content, oldStr);\n if (escapeMatch) {\n const matchIndex = content.indexOf(escapeMatch);\n return performReplace(content, escapeMatch, newStr, matchIndex);\n }\n\n // Strategy 6: Indentation-flexible match\n const indentMatch = tryIndentationFlexibleMatch(content, oldStr);\n if (indentMatch) {\n const matchIndex = content.indexOf(indentMatch);\n return performReplace(content, indentMatch, newStr, matchIndex);\n }\n\n // All strategies failed\n const truncatedOldStr =\n oldStr.length > 200 ? `${oldStr.substring(0, 200)}...` : oldStr;\n\n throw new Error(\n `The string to be replaced was not found in the file. Please ensure the 'old_string' matches the file content exactly, including indentation and whitespace.\\nTarget string (first 200 chars): ${truncatedOldStr}`,\n );\n}\n\nexport function applyEdits(\n cwd: string,\n filePath: string,\n edits: Edit[],\n): { patch: any; updatedFile: string; startLineNumber: number } {\n const fullFilePath = isAbsolute(filePath) ? filePath : resolve(cwd, filePath);\n\n let fileContents = '';\n try {\n fileContents = readFileSync(fullFilePath, 'utf-8');\n // Normalize line endings: CRLF → LF\n fileContents = fileContents.replace(/\\r\\n/g, '\\n');\n } catch (error: any) {\n if (\n error.code === 'ENOENT' &&\n edits.length === 1 &&\n edits[0].old_string === ''\n ) {\n fileContents = '';\n } else {\n throw error;\n }\n }\n\n let currentContent = fileContents;\n const newStringsHistory: string[] = [];\n let firstMatchLineNumber = 1;\n\n for (const edit of edits) {\n const { old_string, new_string, replace_all } = edit;\n\n if (old_string === undefined || old_string === null) {\n throw new Error(\n `old_string is required and cannot be undefined or null when editing file: ${filePath}`,\n );\n }\n\n const oldStrCheck = old_string.replace(/\\n+$/, '');\n for (const historyStr of newStringsHistory) {\n if (oldStrCheck !== '' && historyStr.includes(oldStrCheck)) {\n throw new Error(\n `Cannot edit file: old_string is a substring of a new_string from a previous edit.\\nOld string: ${old_string}`,\n );\n }\n }\n\n const previousContent = currentContent;\n\n if (old_string === '') {\n currentContent = new_string;\n firstMatchLineNumber = 1;\n } else {\n const { result, matchIndex } = applyStringReplace(\n currentContent,\n old_string,\n new_string,\n replace_all,\n );\n currentContent = result;\n if (firstMatchLineNumber === 1 && matchIndex >= 0) {\n const textBeforeMatch = previousContent.substring(0, matchIndex);\n firstMatchLineNumber = textBeforeMatch.split('\\n').length;\n }\n }\n\n if (currentContent === previousContent) {\n if (old_string === new_string && old_string !== '') {\n throw new Error(\n 'No changes to make: old_string and new_string are exactly the same.',\n );\n }\n throw new Error(\n `String not found in file. Failed to apply edit.\\nString: ${old_string}`,\n );\n }\n\n newStringsHistory.push(new_string);\n }\n\n if (currentContent === fileContents && edits.length > 0) {\n throw new Error(\n 'Original and edited file match exactly. Failed to apply edit.',\n );\n }\n\n const patch = Diff.structuredPatch(\n filePath,\n filePath,\n fileContents,\n currentContent,\n );\n\n return {\n patch,\n updatedFile: currentContent,\n startLineNumber: firstMatchLineNumber,\n };\n}\n","import TurndownService from 'turndown';\nimport { z } from 'zod';\nimport type { ModelInfo } from '../../core/model';\nimport { query } from '../../core/query';\nimport { createTool } from '../tool';\nimport { safeStringify } from '../../utils/safeStringify';\n\nconst CACHE_TTL_MS = 5 * 60 * 1000; // 5min\nconst urlCache = new Map();\nconst MAX_CONTENT_LENGTH = 15000; // 15k\n\nexport function createFetchTool(opts: {\n model: ModelInfo;\n fetch?: typeof globalThis.fetch;\n}) {\n return createTool({\n name: 'fetch',\n description: `\nFetch content from url.\nRemembers:\n- IMPORTANT: If an MCP-provided web fetch tool is available, prefer using that tool instead of this one, as it may have fewer restrictions. All MCP-provided tools start with \"mcp__\"\n `.trim(),\n parameters: z.object({\n url: z.string().describe('The url to fetch content from'),\n prompt: z.string().describe('The prompt to run on the fetched content'),\n }),\n getDescription: ({ params }) => {\n if (!params.url || typeof params.url !== 'string') {\n return 'No URL provided';\n }\n return params.url;\n },\n execute: async ({ url, prompt }) => {\n try {\n const startTime = Date.now();\n const key = `${url}-${prompt}`;\n const cached = urlCache.get(key);\n if (cached && cached.durationMs < CACHE_TTL_MS) {\n return {\n returnDisplay: `Successfully fetched content from ${url} (cached)`,\n llmContent: safeStringify({\n ...cached,\n cached: true,\n durationMs: Date.now() - startTime,\n }),\n };\n }\n\n try {\n new URL(url);\n } catch (e) {\n throw new Error('Invalid URL');\n }\n\n const fetchFn = opts.fetch ?? globalThis.fetch;\n const response = await fetchFn(url);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch ${url}: ${response.status} ${response.statusText}`,\n );\n }\n const rawText = await response.text();\n const contentType = response.headers.get('content-type') ?? '';\n const bytes = Buffer.byteLength(rawText, 'utf-8');\n\n let content;\n if (contentType.includes('text/html')) {\n content = new TurndownService().turndown(rawText);\n } else {\n content = rawText;\n }\n\n if (content.length > MAX_CONTENT_LENGTH) {\n content =\n content.substring(0, MAX_CONTENT_LENGTH) + '...[content truncated]';\n }\n\n const input = `\nWeb page content:\n---\n${content}\n---\n\n${prompt}\n\nProvide a concise response based only on the content above. In your response:\n - Enforce a strict 125-character maximum for quotes from any source document. Open Source Software is ok as long as we respect the license.\n - Use quotation marks for exact language from articles; any language outside of the quotation should never be word-for-word the same.\n - You are not a lawyer and never comment on the legality of your own prompts and responses.\n - Never produce or reproduce exact song lyrics.\n `;\n const result = await query({\n userPrompt: input,\n model: opts.model,\n // Some models require a system prompt, otherwise it will throw an error.\n systemPrompt: process.env.AI_ENGINE_FETCH_SYSTEM_PROMPT ?? '',\n });\n const llmResult = result.success\n ? result.data.text\n : `Failed to fetch content from ${url}`;\n\n const code = response.status;\n const codeText = response.statusText;\n const data = {\n result: llmResult!,\n code,\n codeText,\n url,\n bytes,\n contentType,\n durationMs: Date.now() - startTime,\n };\n urlCache.set(key, data);\n return {\n llmContent: safeStringify(data),\n returnDisplay: `Successfully fetched content from ${url}`,\n };\n } catch (e) {\n return {\n isError: true,\n llmContent: e instanceof Error ? e.message : 'Unknown error',\n };\n }\n },\n approval: {\n category: 'network',\n },\n });\n}\n","export function safeStringify(\n obj: any,\n fallbackMessage = '[Unable to serialize object]',\n): string {\n try {\n return JSON.stringify(obj, null, 2);\n } catch (error) {\n return fallbackMessage;\n }\n}\n","import { glob } from 'glob';\nimport { z } from 'zod';\nimport { TOOL_NAMES } from '../../core/constants';\nimport { createTool } from '../tool';\nimport { safeStringify } from '../../utils/safeStringify';\n\nconst LIMIT = 100;\n\nexport function createGlobTool(opts: { cwd: string }) {\n return createTool({\n name: TOOL_NAMES.GLOB,\n description: `\nGlob\n- Fast file pattern matching tool that works with any codebase size\n- Supports glob patterns like \"**/*.js\" or \"src/**/*.ts\"\n- Returns matching file paths sorted by modification time\n- Use this tool when you need to find files by name patterns\n`.trim(),\n parameters: z.object({\n pattern: z.string().describe('The glob pattern to match files against'),\n path: z.string().optional().describe('The directory to search in'),\n }),\n getDescription: ({ params }) => {\n if (!params.pattern || typeof params.pattern !== 'string') {\n return 'No pattern provided';\n }\n return params.pattern;\n },\n execute: async ({ pattern, path }) => {\n try {\n const start = Date.now();\n const paths = await glob([pattern], {\n cwd: path ?? opts.cwd,\n nocase: true,\n nodir: true,\n stat: true,\n withFileTypes: true,\n });\n const sortedPaths = paths.sort(\n (a, b) => (a.mtimeMs ?? 0) - (b.mtimeMs ?? 0),\n );\n const truncated = sortedPaths.length > LIMIT;\n const filenames = sortedPaths\n .slice(0, LIMIT)\n .map((path) => path.fullpath());\n const message = truncated\n ? `Found ${filenames.length} files in ${Date.now() - start}ms, truncating to ${LIMIT}.`\n : `Found ${filenames.length} files in ${Date.now() - start}ms.`;\n return {\n returnDisplay: message,\n llmContent: safeStringify({\n filenames,\n durationMs: Date.now() - start,\n numFiles: filenames.length,\n truncated,\n }),\n };\n } catch (e) {\n return {\n isError: true,\n llmContent: e instanceof Error ? e.message : 'Unknown error',\n };\n }\n },\n approval: {\n category: 'read',\n },\n });\n}\n","import fs from 'fs';\nimport path from 'pathe';\nimport { z } from 'zod';\nimport { countTokens } from 'gpt-tokenizer';\nimport { TOOL_NAMES } from '../../core/constants';\nimport { createTool } from '../tool';\nimport { ripGrep } from '../../utils/ripgrep';\nimport { safeStringify } from '../../utils/safeStringify';\n\nconst DEFAULT_LIMIT = 1000;\nconst MAX_CONTENT_LINES = 1000;\nconst MAX_LINE_LENGTH = 2000;\nconst MAX_CONTENT_LENGTH = 262144;\nconst MAX_TOKENS = 25000;\n\nconst OUTPUT_MODES = ['content', 'files_with_matches', 'count'] as const;\ntype OutputMode = (typeof OUTPUT_MODES)[number];\n\nconst EXCLUDED_DIRS = ['.git', '.svn', '.hg', '.bzr'];\n\nfunction buildRipgrepArgs(params: {\n pattern: string;\n include?: string;\n output_mode?: OutputMode;\n before_context?: number;\n after_context?: number;\n context?: number;\n line_numbers?: boolean;\n ignore_case?: boolean;\n type?: string;\n multiline?: boolean;\n}): string[] {\n const args: string[] = ['--hidden', '--max-columns', '500'];\n\n for (const dir of EXCLUDED_DIRS) {\n args.push('--glob', `!${dir}`);\n }\n\n if (params.multiline) {\n args.push('-U', '--multiline-dotall');\n }\n\n if (params.ignore_case) {\n args.push('-i');\n }\n\n const mode = params.output_mode ?? 'files_with_matches';\n\n if (mode === 'files_with_matches') {\n args.push('-l');\n } else if (mode === 'count') {\n args.push('-c');\n }\n\n if (mode === 'content') {\n const showLineNumbers = params.line_numbers ?? true;\n if (showLineNumbers) {\n args.push('-n');\n }\n\n if (params.context !== undefined) {\n args.push('-C', String(params.context));\n } else {\n if (params.before_context !== undefined) {\n args.push('-B', String(params.before_context));\n }\n if (params.after_context !== undefined) {\n args.push('-A', String(params.after_context));\n }\n }\n }\n\n if (params.pattern.startsWith('-')) {\n args.push('-e', params.pattern);\n } else {\n args.push(params.pattern);\n }\n\n if (params.type) {\n args.push('--type', params.type);\n }\n\n if (params.include) {\n const globs = params.include.split(',').map((g) => g.trim());\n for (const glob of globs) {\n if (glob) {\n args.push('--glob', glob);\n }\n }\n }\n\n return args;\n}\n\nfunction extractFilenamesFromContent(lines: string[]): string[] {\n const filenames = new Set<string>();\n for (const line of lines) {\n const match = line.match(/^(.+?):\\d+:/);\n if (match) {\n filenames.add(match[1]);\n }\n }\n return Array.from(filenames);\n}\n\nexport function createGrepTool(opts: { cwd: string }) {\n return createTool({\n name: TOOL_NAMES.GREP,\n description: `A powerful search tool built on ripgrep.\n\nUsage:\n- ALWAYS use ${TOOL_NAMES.GREP} for search tasks. NEVER invoke \\`grep\\` or \\`rg\\` as a ${TOOL_NAMES.BASH} command. The ${TOOL_NAMES.GREP} tool has been optimized for correct permissions and access.\n- Supports full regex syntax (e.g., \"log.*Error\", \"function\\\\s+\\\\w+\")\n- Filter files with include parameter (e.g., \"*.js\", \"**/*.tsx\") or type parameter (e.g., \"js\", \"py\", \"rust\")\n- Output modes: \"content\" shows matching lines, \"files_with_matches\" shows only file paths (default), \"count\" shows match counts\n- Use ${TOOL_NAMES.TASK} tool for open-ended searches requiring multiple rounds\n- Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping\n- Multiline matching: For cross-line patterns, use multiline: true`,\n parameters: z.object({\n pattern: z.string().describe('The pattern to search for'),\n search_path: z.string().optional().describe('The path to search in'),\n include: z\n .string()\n .optional()\n .describe('The file pattern to include in the search'),\n limit: z\n .number()\n .max(DEFAULT_LIMIT)\n .optional()\n .describe(\n `Maximum number of files to return (positive number, default: ${DEFAULT_LIMIT})`,\n ),\n output_mode: z\n .enum(OUTPUT_MODES)\n .optional()\n .describe(\n 'Output mode: \"content\" shows matching lines, \"files_with_matches\" shows only file paths (default), \"count\" shows match counts',\n ),\n before_context: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Number of lines to show before each match (rg -B)'),\n after_context: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Number of lines to show after each match (rg -A)'),\n context: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe(\n 'Number of lines to show before and after each match (rg -C)',\n ),\n line_numbers: z\n .boolean()\n .optional()\n .describe('Show line numbers (default: true for content mode)'),\n ignore_case: z\n .boolean()\n .optional()\n .describe('Case insensitive search (rg -i)'),\n type: z\n .string()\n .optional()\n .describe('File type filter (e.g., \"js\", \"py\", \"ts\", \"rust\", \"go\")'),\n multiline: z\n .boolean()\n .optional()\n .describe(\n 'Enable multiline mode (rg -U --multiline-dotall), allows . to match newlines',\n ),\n offset: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Skip the first N results'),\n }),\n getDescription: ({ params }) => {\n if (!params.pattern || typeof params.pattern !== 'string') {\n return 'No pattern provided';\n }\n return params.pattern;\n },\n execute: async ({\n pattern,\n search_path,\n include,\n limit,\n output_mode,\n before_context,\n after_context,\n context,\n line_numbers,\n ignore_case,\n type,\n multiline,\n offset,\n }) => {\n try {\n if (!pattern) {\n return {\n isError: true,\n llmContent: 'Missing required parameter: pattern',\n };\n }\n\n const start = Date.now();\n const mode = output_mode ?? 'files_with_matches';\n\n const args = buildRipgrepArgs({\n pattern,\n include,\n output_mode: mode,\n before_context,\n after_context,\n context,\n line_numbers,\n ignore_case,\n type,\n multiline,\n });\n\n const absolutePath = search_path\n ? path.isAbsolute(search_path)\n ? search_path\n : path.resolve(opts.cwd, search_path)\n : opts.cwd;\n\n const result = await ripGrep(args, absolutePath);\n\n if (!result.success && result.exitCode !== 1) {\n return {\n isError: true,\n llmContent: `Ripgrep error: ${result.stderr}`,\n };\n }\n\n const durationMs = Date.now() - start;\n const appliedOffset = offset ?? 0;\n const maxResults = limit ?? DEFAULT_LIMIT;\n\n if (mode === 'content') {\n const allLines = result.lines;\n const totalLinesBeforeTruncation = allLines.length;\n\n let processedLines = allLines.slice(\n appliedOffset,\n appliedOffset + maxResults,\n );\n\n let truncated = false;\n let truncationReason = '';\n\n if (processedLines.length > MAX_CONTENT_LINES) {\n processedLines = processedLines.slice(0, MAX_CONTENT_LINES);\n truncated = true;\n truncationReason = 'lines';\n }\n\n processedLines = processedLines.map((line) =>\n line.length > MAX_LINE_LENGTH\n ? `${line.substring(0, MAX_LINE_LENGTH)}...`\n : line,\n );\n\n let content = processedLines.join('\\n');\n while (\n content.length > MAX_CONTENT_LENGTH &&\n processedLines.length > 0\n ) {\n processedLines = processedLines.slice(\n 0,\n Math.floor(processedLines.length * 0.8),\n );\n content = processedLines.join('\\n');\n truncated = true;\n truncationReason = 'length';\n }\n\n let tokenCount = countTokens(content);\n while (tokenCount > MAX_TOKENS && processedLines.length > 0) {\n processedLines = processedLines.slice(\n 0,\n Math.floor(processedLines.length * 0.8),\n );\n content = processedLines.join('\\n');\n tokenCount = countTokens(content);\n truncated = true;\n truncationReason = 'tokens';\n }\n\n const filenames = extractFilenamesFromContent(processedLines);\n\n const returnDisplay = truncated\n ? `Found ${totalLinesBeforeTruncation} lines, showing ${processedLines.length} (truncated due to ${truncationReason}) in ${filenames.length} files (${durationMs}ms)`\n : `Found ${totalLinesBeforeTruncation} lines in ${filenames.length} files (${durationMs}ms)`;\n\n return {\n returnDisplay,\n llmContent: safeStringify({\n mode: 'content',\n numFiles: filenames.length,\n filenames,\n content,\n numLines: processedLines.length,\n appliedLimit: maxResults,\n appliedOffset,\n durationMs,\n truncated,\n ...(truncated && {\n totalLinesBeforeTruncation,\n hint: 'Results truncated. Use more specific pattern, add include filter, or use offset parameter.',\n }),\n }),\n };\n }\n\n if (mode === 'count') {\n let totalMatches = 0;\n const filenames: string[] = [];\n\n for (const line of result.lines) {\n const colonIndex = line.lastIndexOf(':');\n if (colonIndex > 0) {\n const filename = line.slice(0, colonIndex);\n const count = parseInt(line.slice(colonIndex + 1), 10);\n if (!isNaN(count)) {\n totalMatches += count;\n filenames.push(filename);\n }\n }\n }\n\n return {\n returnDisplay: `Found ${totalMatches} matches in ${filenames.length} files (${durationMs}ms)`,\n llmContent: safeStringify({\n mode: 'count',\n numFiles: filenames.length,\n filenames: filenames.slice(\n appliedOffset,\n appliedOffset + maxResults,\n ),\n numMatches: totalMatches,\n durationMs,\n }),\n };\n }\n\n const stats = await Promise.all(\n result.lines.map((f) => {\n try {\n return fs.statSync(f);\n } catch {\n return null;\n }\n }),\n );\n\n const allMatches = result.lines\n .map((f, i) => [f, stats[i]] as const)\n .filter(([, stat]) => stat !== null)\n .sort((a, b) => {\n if (process.env.NODE_ENV === 'test') {\n return a[0].localeCompare(b[0]);\n }\n const timeComparison = (b[1]?.mtimeMs ?? 0) - (a[1]?.mtimeMs ?? 0);\n if (timeComparison === 0) {\n return a[0].localeCompare(b[0]);\n }\n return timeComparison;\n })\n .map(([f]) => f);\n\n const totalFiles = allMatches.length;\n const matches = allMatches.slice(\n appliedOffset,\n appliedOffset + maxResults,\n );\n const truncated = totalFiles > matches.length + appliedOffset;\n\n const returnDisplay = truncated\n ? `Found ${totalFiles} files (showing ${matches.length} of ${totalFiles}) in ${durationMs}ms`\n : `Found ${totalFiles} files in ${durationMs}ms`;\n\n return {\n returnDisplay,\n llmContent: safeStringify({\n mode: 'files_with_matches',\n filenames: matches,\n durationMs,\n totalFiles,\n returnedFiles: matches.length,\n truncated,\n appliedLimit: maxResults,\n appliedOffset,\n }),\n };\n } catch (e) {\n return {\n isError: true,\n llmContent: e instanceof Error ? e.message : 'Unknown error',\n };\n }\n },\n approval: {\n category: 'read',\n },\n });\n}\n","import { execFile, spawn } from 'child_process';\nimport createDebug from 'debug';\nimport path from 'pathe';\nimport { findActualExecutable } from 'spawn-rx';\nimport { matchesAnyPattern, parseProductIgnorePatterns } from './ignore';\nimport { isLocal } from './isLocal';\n\nconst debug = createDebug('oricore:utils:ripgrep');\n\nexport interface RipGrepResult {\n success: boolean;\n lines: string[];\n exitCode: number | null;\n stderr: string;\n}\n\n/**\n * Get the root directory of the project.\n * Works in both ESM and CJS contexts.\n */\nconst getRootDir = () => {\n const isDev = isLocal() || process.env.NODE_ENV === 'test';\n\n // Try to use __dirname first (available in CJS and when tsup compiles for CJS)\n if (typeof __dirname !== 'undefined') {\n return isDev ? path.resolve(__dirname, '../../') : path.resolve(__dirname, '../');\n }\n\n // Fallback for ESM: use import.meta.url\n try {\n const url = import.meta.url;\n const __filename = url.startsWith('file://') ? new URL(url).pathname : url;\n const moduleDir = path.dirname(__filename);\n return isDev ? path.resolve(moduleDir, '../../') : path.resolve(moduleDir, '../');\n } catch {\n // Ultimate fallback: use process.cwd()\n return process.cwd();\n }\n};\n\nconst rootDir = getRootDir();\n\nexport function ripgrepPath() {\n const { cmd } = findActualExecutable('rg', []);\n if (cmd !== 'rg') {\n return cmd;\n } else {\n const rgRoot = path.resolve(rootDir, 'vendor', 'ripgrep');\n if (process.platform === 'win32') {\n return path.resolve(rgRoot, 'x64-win32', 'rg.exe');\n } else {\n return path.resolve(rgRoot, `${process.arch}-${process.platform}`, 'rg');\n }\n }\n}\n\nexport async function ripGrep(\n args: string[],\n target: string,\n): Promise<RipGrepResult> {\n const rg = ripgrepPath();\n return new Promise((resolve) => {\n execFile(\n rg,\n [...args, target],\n {\n maxBuffer: 10_000_000,\n timeout: 60_000,\n },\n (err, stdout, stderr) => {\n if (err) {\n const exitCode = 'code' in err ? (err.code as number) : null;\n if (exitCode === 1) {\n resolve({ success: true, lines: [], exitCode: 1, stderr: '' });\n } else {\n debug(`[Ripgrep] Error: ${err}`);\n resolve({\n success: false,\n lines: stdout.trim().split('\\n').filter(Boolean),\n exitCode,\n stderr: stderr || String(err),\n });\n }\n } else {\n resolve({\n success: true,\n lines: stdout.trim().split('\\n').filter(Boolean),\n exitCode: 0,\n stderr: '',\n });\n }\n },\n );\n });\n}\n\nexport interface SearchFilesResult {\n success: boolean;\n data: {\n paths: string[];\n truncated: boolean;\n };\n}\n\nexport async function searchFiles(\n cwd: string,\n query: string,\n maxResults: number = 100,\n): Promise<SearchFilesResult> {\n const productPatterns = parseProductIgnorePatterns(cwd, [\n 'oricore',\n 'takumi',\n 'kwaipilot',\n ]);\n\n const { sep, normalize, relative } = path;\n const rgPath = ripgrepPath();\n let globPatterns: string[];\n if (query.includes(sep) || query.includes('/')) {\n const normalizedQuery = normalize(query).replace(/\\\\/g, '/');\n globPatterns = [`**/${normalizedQuery}*`, `**/${normalizedQuery}*/**`];\n } else {\n globPatterns = [`**/*${query}*`, `**/*${query}*/**`];\n }\n const args = [\n '--files',\n '--hidden',\n ...globPatterns.flatMap((p) => ['--iglob', p]),\n '--iglob',\n '!**/.git/**',\n '--iglob',\n '!**/node_modules/**',\n cwd,\n ];\n\n return new Promise((resolve) => {\n const rg = spawn(rgPath, args, {\n cwd,\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n\n const matches: string[] = [];\n const lowerQuery = query.toLowerCase();\n let buffer = '';\n let killed = false;\n\n if (rg.stdout) {\n rg.stdout.on('data', (chunk: Buffer) => {\n if (killed) return;\n buffer += chunk.toString();\n if (buffer.length > 10 * 1024 * 1024) {\n killed = true;\n rg.kill();\n return;\n }\n const lines = buffer.split('\\n');\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n if (!line || killed) continue;\n\n if (matches.length >= maxResults) {\n killed = true;\n rg.kill();\n return;\n }\n\n const relativePath = relative(cwd, line);\n\n if (matchesAnyPattern(relativePath, productPatterns)) continue;\n\n matches.push(relativePath);\n }\n });\n }\n\n rg.on('close', () => {\n const sorted = matches.sort((a, b) => {\n const aLower = a.toLowerCase();\n const bLower = b.toLowerCase();\n const aIndex = aLower.indexOf(lowerQuery);\n const bIndex = bLower.indexOf(lowerQuery);\n if (aIndex !== bIndex) return aIndex - bIndex;\n return a.length - b.length;\n });\n\n resolve({\n success: true,\n data: {\n paths: sorted.slice(0, maxResults),\n truncated: matches.length >= maxResults,\n },\n });\n });\n\n rg.on('error', (err) => {\n debug(`[SearchFiles] Error: ${err}`);\n resolve({\n success: true,\n data: { paths: [], truncated: false },\n });\n });\n });\n}\n","// Determine whether running in local development environment\n// - Bun: Local development environment\nexport function isLocal(): boolean {\n // @ts-ignore - Bun is a global in Bun runtime\n return typeof Bun !== 'undefined';\n}\n","import path from 'pathe';\nimport { z } from 'zod';\nimport { TOOL_NAMES } from '../../core/constants';\nimport { createTool } from '../tool';\nimport {\n createFileTree,\n listDirectory,\n MAX_FILES,\n printTree,\n TRUNCATED_MESSAGE,\n} from '../../utils/list';\n\nexport function createLSTool(opts: { cwd: string }) {\n return createTool({\n name: TOOL_NAMES.LS,\n description: 'Lists files and directories in a given path.',\n parameters: z.object({\n dir_path: z.string().describe('The path to the directory to list.'),\n }),\n getDescription: ({ params }) => {\n if (!params.dir_path || typeof params.dir_path !== 'string') {\n return '.';\n }\n return path.relative(opts.cwd, params.dir_path);\n },\n execute: async (params) => {\n const { dir_path } = params;\n const fullFilePath = path.isAbsolute(dir_path)\n ? dir_path\n : path.resolve(opts.cwd, dir_path);\n const result = listDirectory(fullFilePath, opts.cwd).sort();\n const tree = createFileTree(result);\n const userTree = printTree(opts.cwd, tree);\n if (result.length < MAX_FILES) {\n return {\n returnDisplay: `Listed ${result.length} files/directories`,\n llmContent: userTree,\n };\n } else {\n const assistantData = `${TRUNCATED_MESSAGE}${userTree}`;\n return {\n returnDisplay: `Listed ${result.length} files/directories (truncated)`,\n llmContent: assistantData,\n };\n }\n },\n approval: {\n category: 'read',\n },\n });\n}\n","import fs from 'fs';\nimport { countTokens } from 'gpt-tokenizer';\nimport path from 'pathe';\nimport { z } from 'zod';\nimport { BINARY_EXTENSIONS, IMAGE_EXTENSIONS, TOOL_NAMES } from '../../core/constants';\nimport { createTool, type ToolResult } from '../tool';\nimport {\n MaxFileReadLengthExceededError,\n MaxFileReadTokenExceededError,\n} from '../../utils/error';\nimport { safeStringify } from '../../utils/safeStringify';\nimport {\n formatPDFResult,\n isPDFParsingAvailable,\n parsePDF,\n} from '../../utils/pdf-parser';\n\ntype ImageMediaType =\n | 'image/jpeg'\n | 'image/png'\n | 'image/gif'\n | 'image/webp'\n | 'image/bmp'\n | 'image/svg+xml'\n | 'image/tiff';\n\nconst MAX_IMAGE_SIZE = 3.75 * 1024 * 1024; // 3.75MB in bytes\n\nfunction getImageMimeType(ext: string): ImageMediaType {\n const mimeTypes: Record<string, ImageMediaType> = {\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.png': 'image/png',\n '.gif': 'image/gif',\n '.bmp': 'image/bmp',\n '.webp': 'image/webp',\n '.svg': 'image/svg+xml',\n '.tiff': 'image/tiff',\n '.tif': 'image/tiff',\n };\n return mimeTypes[ext] || 'image/jpeg';\n}\n\nfunction createImageResponse(buffer: Buffer, ext: string): ToolResult {\n const mimeType = getImageMimeType(ext);\n const base64 = buffer.toString('base64');\n const data = `data:${mimeType};base64,${base64}`;\n return {\n llmContent: [{ type: 'image', data, mimeType }],\n returnDisplay: 'Read image file successfully.',\n };\n}\n\nasync function processImage(\n filePath: string,\n cwd: string,\n): Promise<ToolResult> {\n try {\n const stats = fs.statSync(filePath);\n const ext = path.extname(filePath).toLowerCase();\n\n // Security: Validate file path to prevent traversal attacks\n const resolvedPath = path.resolve(filePath);\n const normalizedCwd = path.resolve(cwd);\n if (!resolvedPath.startsWith(normalizedCwd)) {\n throw new Error('Invalid file path: path traversal detected');\n }\n\n const buffer = fs.readFileSync(filePath);\n\n // If file is within size limit, return as-is\n if (stats.size <= MAX_IMAGE_SIZE) {\n return createImageResponse(buffer, ext);\n }\n\n // If file is too large, return error with helpful message\n throw new Error(\n `Image file is too large (${Math.round((stats.size / 1024 / 1024) * 100) / 100}MB). ` +\n `Maximum supported size is ${Math.round((MAX_IMAGE_SIZE / 1024 / 1024) * 100) / 100}MB. ` +\n `Please resize the image and try again.`,\n );\n } catch (error) {\n throw error;\n }\n}\n\nconst MAX_LINES_TO_READ = 2000;\nconst MAX_LINE_LENGTH = 2000;\nconst MAX_FILE_LENGTH = 262144;\nconst MAX_TOKENS = 25000;\n\nexport function createReadTool(opts: { cwd: string; productName: string }) {\n const productName = opts.productName.toLowerCase();\n return createTool({\n name: TOOL_NAMES.READ,\n description: `\n\nReads a file from the local filesystem. You can access any file directly by using this tool.\nAssume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- The file_path parameter must be an absolute path, not a relative path\n- By default, it reads up to ${MAX_LINES_TO_READ} lines starting from the beginning of the file\n- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters\n- Any lines longer than ${MAX_LINE_LENGTH} characters will be truncated\n- This tool allows ${productName} to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as ${productName} is a multimodal LLM.\n- This tool can only read files, not directories. To read a directory, use the ${TOOL_NAMES.LS} tool.\n- You can call multiple tools in a single response. It is always better to speculatively read multiple potentially useful files in parallel.\n\n `,\n parameters: z.object({\n file_path: z.string().describe('The absolute path to the file to read'),\n offset: z\n .number()\n .optional()\n .describe(\n 'The line number to start reading from. Only provide if the file is too large to read at once',\n ),\n limit: z\n .number()\n .optional()\n .describe(\n `The number of lines to read. Only provide if the file is too large to read at once`,\n ),\n }),\n getDescription: ({ params, cwd }) => {\n if (!params.file_path || typeof params.file_path !== 'string') {\n return 'No file path provided';\n }\n return path.relative(cwd, params.file_path);\n },\n execute: async ({ file_path, offset, limit }) => {\n try {\n // Validate parameters\n if (offset !== undefined && offset !== null && offset < 1) {\n throw new Error('Offset must be >= 1');\n }\n if (limit !== undefined && limit !== null && limit < 1) {\n throw new Error('Limit must be >= 1');\n }\n\n const ext = path.extname(file_path).toLowerCase();\n\n const fullFilePath = (() => {\n if (path.isAbsolute(file_path)) {\n return file_path;\n }\n const full = path.resolve(opts.cwd, file_path);\n if (fs.existsSync(full)) {\n return full;\n }\n if (file_path.startsWith('@')) {\n const full = path.resolve(opts.cwd, file_path.slice(1));\n if (fs.existsSync(full)) {\n return full;\n }\n }\n throw new Error(`File ${file_path} does not exist.`);\n })();\n\n // Handle PDF files\n if ('.pdf' === ext) {\n const pdfAvailable = await isPDFParsingAvailable();\n if (!pdfAvailable) {\n throw new Error(\n 'PDF parsing requires the \"pdf-parse\" package. Install it with: npm install pdf-parse',\n );\n }\n\n const stats = fs.statSync(fullFilePath);\n\n // Security: Validate file path to prevent traversal attacks\n const resolvedPath = path.resolve(fullFilePath);\n const normalizedCwd = path.resolve(opts.cwd);\n if (!resolvedPath.startsWith(normalizedCwd)) {\n throw new Error('Invalid file path: path traversal detected');\n }\n\n // Check file size (warn if > 5MB)\n const fileSizeMB = stats.size / (1024 * 1024);\n if (fileSizeMB > 5) {\n return {\n isError: true,\n llmContent: `PDF file is too large (${Math.round(fileSizeMB * 100) / 100}MB). Maximum supported size is 5MB for PDF files.`,\n };\n }\n\n try {\n const result = await parsePDF(fullFilePath, {\n maxPages: 100, // Limit to 100 pages\n maxCharsPerPage: 5000, // Limit per page\n includeMetadata: true,\n });\n\n // Check token count\n const tokenCount = countTokens(result.text);\n const MAX_PDF_TOKENS = 15000;\n if (tokenCount > MAX_PDF_TOKENS) {\n return {\n isError: true,\n llmContent: `PDF content is too large (${tokenCount} tokens). Maximum supported is ${MAX_PDF_TOKENS} tokens. Try extracting specific pages.`,\n };\n }\n\n return {\n returnDisplay: `Read PDF file (${result.pageCount} pages)`,\n llmContent: safeStringify({\n type: 'pdf',\n filePath: file_path,\n pageCount: result.pageCount,\n metadata: result.metadata,\n content: result.text,\n tokenCount,\n }),\n };\n } catch (error) {\n return {\n isError: true,\n llmContent: `Failed to parse PDF file: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n // Handle image files\n if (IMAGE_EXTENSIONS.has(ext)) {\n const result = await processImage(fullFilePath, opts.cwd);\n return result;\n }\n\n // Handle binary/restricted files\n if (BINARY_EXTENSIONS.has(ext)) {\n throw new Error(\n `Cannot read file \"${path.basename(file_path)}\": Extension \"${ext}\" is restricted as a binary/system file.`,\n );\n }\n\n // Handle empty files\n const stats = fs.statSync(fullFilePath);\n if (stats.size === 0) {\n return {\n returnDisplay: 'File is empty.',\n llmContent: safeStringify({\n type: 'text',\n filePath: file_path,\n content: '',\n totalLines: 0,\n offset: 1,\n limit: 0,\n actualLinesRead: 0,\n }),\n };\n }\n\n // Handle text files\n const {\n content,\n totalLines,\n startLine,\n actualLimit,\n selectedLines,\n endLine,\n } = readFileWithOffsetLimit(\n fullFilePath,\n offset ?? 1,\n limit ?? MAX_LINES_TO_READ,\n );\n\n if (content.length > MAX_FILE_LENGTH) {\n throw new MaxFileReadLengthExceededError(\n content.length,\n MAX_FILE_LENGTH,\n );\n }\n\n // token validation\n const tokenCount = countTokens(content);\n if (tokenCount > MAX_TOKENS) {\n throw new MaxFileReadTokenExceededError(tokenCount, MAX_TOKENS);\n }\n\n // Truncate long lines\n const truncatedLines = selectedLines.map((line) =>\n line.length > MAX_LINE_LENGTH\n ? `${line.substring(0, MAX_LINE_LENGTH)}...`\n : line,\n );\n\n const processedContent = truncatedLines.join('\\n');\n const actualLinesRead = selectedLines.length;\n\n return {\n returnDisplay:\n offset !== undefined || limit !== undefined\n ? `Read ${actualLinesRead} lines (from line ${startLine + 1} to ${endLine}).`\n : `Read ${actualLinesRead} lines.`,\n llmContent: safeStringify({\n type: 'text',\n filePath: file_path,\n content: processedContent,\n totalLines,\n offset: startLine + 1, // Convert back to 1-based\n limit: actualLimit,\n actualLinesRead,\n }),\n };\n } catch (e) {\n return {\n isError: true,\n llmContent: e instanceof Error ? e.message : 'Unknown error',\n };\n }\n },\n approval: {\n category: 'read',\n },\n });\n}\n\nfunction readFileWithOffsetLimit(\n filePath: string,\n offset: number = 1,\n limit: number = MAX_LINES_TO_READ,\n) {\n const fileContent = fs.readFileSync(filePath, { encoding: 'utf8' });\n if (fileContent === undefined || fileContent === null) {\n throw new Error(`Failed to read file: ${filePath}`);\n }\n const allLines = fileContent.split(/\\r?\\n/);\n const totalLines = allLines.length;\n\n // Apply offset and limit with defaults\n const actualOffset = offset ?? 1;\n const actualLimit = limit ?? MAX_LINES_TO_READ;\n const startLine = Math.max(0, actualOffset - 1); // Convert 1-based to 0-based\n const endLine = Math.min(totalLines, startLine + actualLimit);\n const selectedLines = allLines.slice(startLine, endLine);\n\n return {\n content: selectedLines.join('\\n'),\n lineCount: selectedLines.length,\n startLine,\n endLine,\n actualLimit,\n totalLines,\n selectedLines,\n };\n}\n","/**\n * PDF Parser Utility\n * Extracts text content from PDF files\n */\n\nimport fs from 'fs';\nimport path from 'pathe';\n\nexport interface ParseResult {\n text: string;\n pageCount: number;\n metadata?: {\n title?: string;\n author?: string;\n subject?: string;\n keywords?: string;\n creator?: string;\n producer?: string;\n creationDate?: string;\n modificationDate?: string;\n };\n}\n\nexport interface ParseOptions {\n /**\n * Maximum number of pages to parse (0 = all pages)\n * @default 0\n */\n maxPages?: number;\n\n /**\n * Maximum text length per page (0 = no limit)\n * @default 10000\n */\n maxCharsPerPage?: number;\n\n /**\n * Include metadata in the result\n * @default true\n */\n includeMetadata?: boolean;\n}\n\nconst DEFAULT_OPTIONS: ParseOptions = {\n maxPages: 0, // Parse all pages\n maxCharsPerPage: 10000,\n includeMetadata: true,\n};\n\n/**\n * Parse a PDF file and extract text content\n *\n * @param filePath - Absolute path to the PDF file\n * @param options - Parsing options\n * @returns Parsed PDF content\n */\nexport async function parsePDF(\n filePath: string,\n options: ParseOptions = {},\n): Promise<ParseResult> {\n const opts = { ...DEFAULT_OPTIONS, ...options };\n\n // Validate file exists\n if (!fs.existsSync(filePath)) {\n throw new Error(`PDF file not found: ${filePath}`);\n }\n\n // Get file stats\n const stats = fs.statSync(filePath);\n const fileSizeMB = stats.size / (1024 * 1024);\n\n // Check file size (warn if > 10MB)\n if (fileSizeMB > 10) {\n console.warn(\n `PDF file is large (${fileSizeMB.toFixed(2)}MB), parsing may take a while`,\n );\n }\n\n try {\n // Try to use pdf-parse if available\n const pdfParse = await import('pdf-parse');\n const dataBuffer = fs.readFileSync(filePath);\n\n const data = await pdfParse.default(dataBuffer, {\n // Only parse requested pages\n max: opts.maxPages || undefined,\n });\n\n // Truncate text per page if needed\n let text = data.text;\n if (opts.maxCharsPerPage && opts.maxCharsPerPage > 0) {\n // Split by pages (pdf-parse doesn't give page breaks, so we split by heuristics)\n // This is a simple approach - for better results, use a library that preserves page structure\n text = text\n .split(/\\f/) // Form feed character often used as page separator\n .map((pageText: string) => {\n if (pageText.length > opts.maxCharsPerPage!) {\n return pageText.substring(0, opts.maxCharsPerPage) + '... [truncated]';\n }\n return pageText;\n })\n .join('\\n\\n--- Page Break ---\\n\\n');\n }\n\n const result: ParseResult = {\n text: text.trim(),\n pageCount: data.numpages,\n };\n\n // Add metadata if requested and available\n if (opts.includeMetadata) {\n const metadata: ParseResult['metadata'] = {};\n\n if (data.info) {\n if (data.info.Title) metadata.title = String(data.info.Title);\n if (data.info.Author) metadata.author = String(data.info.Author);\n if (data.info.Subject) metadata.subject = String(data.info.Subject);\n if (data.info.Keywords) metadata.keywords = String(data.info.Keywords);\n if (data.info.Creator) metadata.creator = String(data.info.Creator);\n if (data.info.Producer) metadata.producer = String(data.info.Producer);\n if (data.info.CreationDate)\n metadata.creationDate = String(data.info.CreationDate);\n if (data.info.ModDate)\n metadata.modificationDate = String(data.info.ModDate);\n }\n\n if (Object.keys(metadata).length > 0) {\n result.metadata = metadata;\n }\n }\n\n return result;\n } catch (error: any) {\n if (error.code === 'MODULE_NOT_FOUND' || error.code === 'ERR_MODULE_NOT_FOUND') {\n // pdf-parse not available, provide helpful error\n throw new Error(\n 'PDF parsing requires the \"pdf-parse\" package. Install it with: npm install pdf-parse',\n );\n }\n\n throw new Error(\n `Failed to parse PDF file: ${error.message || String(error)}`,\n );\n }\n}\n\n/**\n * Check if PDF parsing is available (pdf-parse is installed)\n */\nexport async function isPDFParsingAvailable(): Promise<boolean> {\n try {\n await import('pdf-parse');\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Format PDF parse result for LLM consumption\n */\nexport function formatPDFResult(result: ParseResult): string {\n const sections: string[] = [];\n\n sections.push(`# PDF Document`);\n sections.push(`Pages: ${result.pageCount}`);\n\n if (result.metadata) {\n const meta: string[] = [];\n if (result.metadata.title) meta.push(`Title: ${result.metadata.title}`);\n if (result.metadata.author) meta.push(`Author: ${result.metadata.author}`);\n if (result.metadata.subject) meta.push(`Subject: ${result.metadata.subject}`);\n if (result.metadata.creationDate)\n meta.push(`Created: ${result.metadata.creationDate}`);\n\n if (meta.length > 0) {\n sections.push('\\n## Metadata');\n sections.push(meta.join('\\n'));\n }\n }\n\n sections.push('\\n## Content');\n sections.push(result.text);\n\n return sections.join('\\n');\n}\n","import path from 'pathe';\nimport { z } from 'zod';\nimport type { Context } from '../../core/context';\nimport type { SkillManager, SkillMetadata } from '../../skill/skill';\nimport { createTool, type Tool } from '../tool';\nimport { safeStringify } from '../../utils/safeStringify';\nimport { createTaskTool } from './task';\nimport { randomUUID } from '../../utils/randomUUID';\n\nfunction renderAvailableSkills(skills: SkillMetadata[]): string {\n return skills\n .filter((skill) => skill.modelInvocable !== false)\n .map(\n (skill) =>\n `<skill>\\n<name>${skill.name}</name>\\n<description>${skill.description}</description>\\n</skill>`,\n )\n .join('\\n');\n}\n\nfunction generateDescription(skillManager: SkillManager): string {\n const skills = skillManager.getSkills({ modelInvocable: true });\n return `Execute a skill within the main conversation\n<skills_instructions>\nWhen users ask you to perform tasks, check if any of the available skills below match the task. If a skill matches, use this tool to invoke it. Skills provide specialized knowledge and procedures for specific tasks.\n</skills_instructions>\n<available_skills>\n${renderAvailableSkills(skills)}\n</available_skills>`;\n}\n\nexport interface CreateSkillToolOpts {\n skillManager: SkillManager;\n context: Context;\n tools: Tool[];\n sessionId: string;\n signal?: AbortSignal;\n}\n\nexport function createSkillTool(opts: CreateSkillToolOpts) {\n const { skillManager, context, tools, sessionId, signal } = opts;\n\n return createTool({\n name: 'skill',\n description: generateDescription(skillManager),\n parameters: z.object({\n skill: z.string().describe('The skill name to execute'),\n args: z\n .string()\n .optional()\n .describe('Optional arguments to pass to the skill'),\n }),\n getDescription: ({ params }) => {\n return params.args\n ? `${params.skill} ${params.args}`\n : params.skill;\n },\n async execute({ skill, args }) {\n const trimmed = skill.trim();\n const skillName = trimmed.startsWith('/')\n ? trimmed.substring(1)\n : trimmed;\n const foundSkill = skillManager.getSkill(skillName);\n\n if (!foundSkill) {\n return {\n isError: true,\n llmContent: `Skill \"${skillName}\" not found`,\n };\n }\n\n // Check if skill can be invoked by model\n if (foundSkill.modelInvocable === false) {\n return {\n isError: true,\n llmContent: `Skill \"${skillName}\" cannot be invoked by the model`,\n };\n }\n\n const skillArgs = args || '';\n const body = await skillManager.readSkillBody(foundSkill, skillArgs);\n const baseDir = path.dirname(foundSkill.path);\n\n // If skill has context: 'fork', use task tool for isolated execution\n if (foundSkill.context === 'fork') {\n if (!context.agentManager) {\n return {\n isError: true,\n llmContent: `Skill \"${skillName}\" requires fork execution but agent manager is not available`,\n };\n }\n\n // Create filtered tools list based on allowedTools\n // Exclude 'skill' tool itself to prevent recursive invocation loops\n const allowedTools = foundSkill.allowedTools;\n const filteredTools = allowedTools\n ? tools.filter(\n (t) =>\n t.name !== 'skill' &&\n allowedTools.some(\n (allowed) =>\n allowed.toLowerCase() === t.name.toLowerCase(),\n ),\n )\n : tools.filter((t) => t.name !== 'skill');\n\n // Create task tool with filtered tools\n const taskTool = createTaskTool({\n context,\n tools: filteredTools,\n sessionId,\n signal,\n });\n\n // Execute skill as a task\n const agentType = foundSkill.agent || 'general-purpose';\n const prompt = `Base directory for this skill: ${baseDir}\\n\\n${body}`;\n\n // Generate a unique toolCallId for tracking\n const toolCallId = `skill-${skillName}-${randomUUID()}`;\n\n return taskTool.execute(\n {\n description: `Execute skill: ${skillName}`,\n prompt,\n subagent_type: agentType,\n },\n toolCallId,\n );\n }\n\n // Inline execution (default)\n const messages = [\n {\n type: 'text',\n text: `<command-message>${skillName} is running…</command-message>\\n<command-name>${skillName}</command-name>`,\n },\n {\n type: 'text',\n text: `Base directory for this skill: ${baseDir}\\n\\n${body}`,\n isMeta: true,\n },\n ];\n\n return {\n llmContent: safeStringify(messages),\n returnDisplay: `Loaded skill: ${foundSkill.name}`,\n };\n },\n approval: { category: 'read' },\n });\n}\n","import { z } from 'zod';\nimport { TOOL_NAMES } from '../../core/constants';\nimport type { Context } from '../../core/context';\nimport type { NormalizedMessage } from '../../core/message';\nimport {\n type ApprovalCategory,\n createTool,\n type Tool,\n type ToolApprovalResult,\n type ToolUse,\n} from '../tool';\nimport { randomUUID } from '../../utils/randomUUID';\n\nexport function createTaskTool(opts: {\n context: Context;\n tools: Tool[];\n sessionId: string;\n signal?: AbortSignal;\n}) {\n const { signal, sessionId } = opts;\n const { cwd, agentManager, messageBus } = opts.context;\n const agentDescriptions = agentManager?.getAgentDescriptions();\n\n return createTool({\n name: TOOL_NAMES.TASK,\n\n description: `Launch a new agent to handle complex, multi-step tasks autonomously.\nThe ${TOOL_NAMES.TASK} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.\nAvailable agent types and the tools they have access to:\n\n${agentDescriptions}\n\nWhen using the ${TOOL_NAMES.TASK} tool, you must specify a subagent_type parameter to select which agent type to use.\n\nWhen NOT to use the Agent tool:\n- If you want to read a specific file path, use the ${TOOL_NAMES.READ} or ${TOOL_NAMES.GLOB} tool instead of the Agent tool, to find the match more quickly\n- If you are searching for a specific class definition like \"class Foo\", use the ${TOOL_NAMES.GLOB} tool instead, to find the match more quickly\n- If you are searching for code within a specific file or set of 2-3 files, use the ${TOOL_NAMES.READ} tool instead of the Agent tool, to find the match more quickly\n- Other tasks that are not related to the agent descriptions above\n\nUsage notes:\n- Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\n- When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\n- Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\n- The agent's outputs should generally be trusted\n- Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent\n- If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.\n- If the user specifies that they want you to run agents \"in parallel\", you MUST send a single message with multiple Task tool use content blocks. For example, if you need to launch both a code-reviewer agent and a test-runner agent in parallel, send a single message with both tool calls.\n\nExample usage:\n\n<example_agent_descriptions>\n\"code-reviewer\": use this agent after you are done writing a signficant piece of code\n\"greeting-responder\": use this agent when to respond to user greetings with a friendly joke\n</example_agent_description>\n\n<example>\nuser: \"Please write a function that checks if a number is prime\"\nassistant: Sure let me write a function that checks if a number is prime\nassistant: First let me use the ${TOOL_NAMES.WRITE} tool to write a function that checks if a number is prime\nassistant: I'm going to use the ${TOOL_NAMES.WRITE} tool to write the following code:\n<code>\nfunction isPrime(n) {\n if (n <= 1) return false\n for (let i = 2; i * i <= n; i++) {\n if (n % i === 0) return false\n }\n return true\n}\n</code>\n<commentary>\nSince a signficant piece of code was written and the task was completed, now use the code-reviewer agent to review the code\n</commentary>\nassistant: Now let me use the code-reviewer agent to review the code\nassistant: Uses the ${TOOL_NAMES.TASK} tool to launch the with the code-reviewer agent\n</example>\n\n<example>\nuser: \"Hello\"\n<commentary>\nSince the user is greeting, use the greeting-responder agent to respond with a friendly joke\n</commentary>\nassistant: \"I'm going to use the ${TOOL_NAMES.TASK} tool to launch the with the greeting-responder agent\"\n</example>\n `,\n\n parameters: z.object({\n description: z\n .string()\n .describe('A short (3-5 word) description of task'),\n prompt: z.string().describe('The task for the agent to perform'),\n subagent_type: z\n .string()\n .describe('The type of specialized agent to use for this task'),\n resume: z\n .string()\n .optional()\n .describe(\n 'Optional agent ID to resume from. If provided, the agent will continue from the previous execution transcript.',\n ),\n }),\n\n execute: async (params, toolCallId?: string) => {\n const startTime = Date.now();\n const parentToolUseId = toolCallId;\n\n if (!toolCallId) {\n return {\n llmContent: 'Tool call ID is required',\n isError: true,\n };\n }\n\n if (!agentManager) {\n return {\n llmContent: 'Agent manager not found',\n isError: true,\n };\n }\n\n // Create onToolApprove callback to handle tool approval requests from agent\n const onToolApprove = async (opts: {\n toolUse: ToolUse;\n category?: ApprovalCategory;\n }): Promise<boolean | ToolApprovalResult> => {\n // If messageBus is not available, fallback to auto-approve\n if (!messageBus) {\n return true;\n }\n\n try {\n /**\n * Request tool approval from the UI layer via messageBus.\n *\n * Params sent to toolApproval handler:\n * @param toolUse - The tool invocation request containing name, params, and callId\n * @param category - Optional approval category (read/write/command/network/ask)\n * @param sessionId - The session ID that initiated this tool approval request\n * Used for session identification and UI routing\n *\n * Expected return from toolApproval handler:\n * @returns approved - Whether the tool use is approved\n * @returns params - Optional updated parameters for the tool\n * @returns denyReason - Optional reason for denial\n *\n * Handler registration example:\n * messageBus.registerHandler('toolApproval', async ({ toolUse, category, sessionId }) => {\n * // Handle approval logic, sessionId can be used for:\n * // - Logging and tracking which session requested approval\n * // - UI session-specific actions (resume, update state)\n * // - Multi-session management\n * return { approved: true/false, params?: {...}, denyReason?: '...' };\n * });\n */\n const result = await messageBus.request('toolApproval', {\n toolUse: opts.toolUse,\n category: opts.category,\n sessionId,\n });\n\n // Handle both boolean and ToolApprovalResult return types\n if (result.params || result.denyReason) {\n return {\n approved: result.approved,\n params: result.params,\n denyReason: result.denyReason,\n };\n }\n\n return result.approved;\n } catch (error) {\n console.error('[createTaskTool] onToolApprove error:', error);\n // On error, fallback to auto-approve\n return true;\n }\n };\n\n try {\n const result = await agentManager.executeTask(params, {\n cwd,\n signal,\n tools: opts.tools,\n parentSessionId: sessionId,\n onToolApprove,\n async onMessage(\n message: NormalizedMessage,\n agentId: string,\n model: string,\n ) {\n try {\n if (messageBus) {\n await messageBus.emitEvent('agent.progress', {\n sessionId,\n cwd,\n agentId,\n agentType: params.subagent_type,\n prompt: params.prompt,\n message,\n parentToolUseId,\n status: 'running',\n model,\n timestamp: Date.now(),\n });\n }\n } catch (error) {\n console.error(\n '[createTaskTool] Failed to emit progress event:',\n error,\n );\n }\n },\n // TODO: get forkContextMessages from context\n // forkContextMessages: [],\n });\n\n // Emit completion event to close the UI overlay\n if (messageBus) {\n await messageBus.emitEvent('agent.progress', {\n sessionId,\n cwd,\n agentId: result.agentId,\n agentType: params.subagent_type,\n prompt: params.prompt,\n message: {\n role: 'assistant',\n content:\n result.status === 'completed'\n ? 'Task completed'\n : 'Task failed',\n type: 'message',\n uuid: randomUUID(),\n timestamp: new Date().toISOString(),\n parentUuid: null,\n } as NormalizedMessage,\n parentToolUseId,\n status: result.status === 'completed' ? 'completed' : 'failed',\n model: result.model,\n timestamp: Date.now(),\n });\n }\n\n const duration = Date.now() - startTime;\n\n if (result.status === 'completed') {\n return {\n llmContent: `Sub-agent (${params.subagent_type}) completed successfully:\\n\\n${result.content}\\n\\n---\\nAgent ID: ${result.agentId}`,\n isError: false,\n returnDisplay: {\n type: 'agent_result',\n agentId: result.agentId,\n agentType: params.subagent_type,\n description: params.description,\n prompt: params.prompt,\n content: result.content,\n model: result.model,\n stats: {\n toolCalls: result.totalToolCalls,\n duration,\n tokens: {\n input: result.usage.inputTokens,\n output: result.usage.outputTokens,\n },\n },\n status: 'completed',\n },\n metadata: {\n agentId: result.agentId,\n agentType: params.subagent_type,\n },\n };\n }\n return {\n llmContent: `Sub-agent (${params.subagent_type}) failed:\\n\\n${result.content}\\n\\n---\\nAgent ID: ${result.agentId}`,\n isError: true,\n returnDisplay: {\n type: 'agent_result',\n agentId: result.agentId,\n agentType: params.subagent_type,\n description: params.description,\n prompt: params.prompt,\n content: result.content,\n model: result.model,\n stats: {\n toolCalls: 0,\n duration,\n tokens: {\n input: 0,\n output: 0,\n },\n },\n status: 'failed',\n },\n metadata: {\n agentId: result.agentId,\n agentType: params.subagent_type,\n },\n };\n } catch (error) {\n return {\n llmContent: `Failed to execute sub-agent: ${error instanceof Error ? error.message : String(error)}`,\n isError: true,\n };\n }\n },\n\n approval: { category: 'read' },\n });\n}\n","import fs from 'fs';\nimport { readFile, writeFile } from 'fs/promises';\nimport path from 'pathe';\nimport { z } from 'zod';\nimport { TOOL_NAMES } from '../../core/constants';\nimport { createTool } from '../tool';\n\nconst TODO_WRITE_PROMPT = `\nUse this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.\nIt also helps the user understand the progress of the task and overall progress of their requests.\n\n## When to Use This Tool\nUse this tool proactively in these scenarios:\n\n1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions\n2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations\n3. User explicitly requests todo list - When the user directly asks you to use the todo list\n4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)\n5. After receiving new instructions - Immediately capture user requirements as todos\n6. When you start working on a task - Mark it as in_progress BEFORE beginning work. Ideally you should only have one todo as in_progress at a time\n7. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation\n\n## When NOT to Use This Tool\n\nSkip using this tool when:\n1. There is only a single, straightforward task\n2. The task is trivial and tracking it provides no organizational benefit\n3. The task can be completed in less than 3 trivial steps\n4. The task is purely conversational or informational\n\nNOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.\n\n## Examples of When to Use the Todo List\n\n<example>\nUser: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!\nAssistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.\n*Creates todo list with the following items:*\n1. Create dark mode toggle component in Settings page\n2. Add dark mode state management (context/store)\n3. Implement CSS-in-JS styles for dark theme\n4. Update existing components to support theme switching\n5. Run tests and build process, addressing any failures or errors that occur\n*Begins working on the first task*\n\n<reasoning>\nThe assistant used the todo list because:\n1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes\n2. The user explicitly requested tests and build be run afterward\n3. The assistant inferred that tests and build need to pass by adding \"Ensure tests and build succeed\" as the final task\n</reasoning>\n</example>\n\n<example>\nUser: Help me rename the function getCwd to getCurrentWorkingDirectory across my project\nAssistant: Let me first search through your codebase to find all occurrences of 'getCwd'.\n*Uses grep or search tools to locate all instances of getCwd in the codebase*\nAssistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.\n*Creates todo list with specific items for each file that needs updating*\n\n<reasoning>\nThe assistant used the todo list because:\n1. First, the assistant searched to understand the scope of the task\n2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps\n3. The todo list helps ensure every instance is tracked and updated systematically\n4. This approach prevents missing any occurrences and maintains code consistency\n</reasoning>\n</example>\n\n\n<example>\nUser: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow.\nAssistant: I'll help implement these features. First, let's add all the features to the todo list.\n*Creates a todo list breaking down each feature into specific tasks based on the project architecture*\nAssistant: Let's start with user registration. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system.\n\n<reasoning>\nThe assistant used the todo list because:\n1. The user provided multiple complex features to implement in a comma separated list\n2. The todo list helps organize these large features into manageable tasks\n3. This approach allows for tracking progress across the entire implementation\n</reasoning>\n</example>\n\n<example>\nUser: Can you help optimize my React application? It's rendering slowly and has performance issues.</user>\nAssistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks.\n*Reviews component structure, render patterns, state management, and data fetching*\nAssistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts.\n*Creates todo list with items like: 1) Implement memoization for expensive calculations in ProductList, 2) Add virtualization for long lists in Dashboard, 3) Optimize image loading in Gallery component, 4) Fix state update loops in ShoppingCart, 5) Review bundle size and implement code splitting*\nLet's start by implementing memoization for the expensive calculations in your ProductList component.</assistant>\n\n<reasoning>\nThe assistant used the todo list because:\n1. First, the assistant examined the codebase to identify specific performance issues\n2. Based on this analysis, it identified multiple optimization opportunities\n3. Performance optimization is a non-trivial task requiring multiple steps\n4. The todo list helps methodically track improvements across different components\n5. This systematic approach ensures all performance bottlenecks are addressed\n</reasoning>\n</example>\n\n## Examples of When NOT to Use the Todo List\n\n<example>\nUser: How do I print 'Hello World' in Python?\nAssistant: In Python, you can print \"Hello World\" with this simple code:\n\npython\nprint(\"Hello World\")\n\nThis will output the text \"Hello World\" to the console when executed.</assistant>\n\n<reasoning>\nThe assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.\n</reasoning>\n</example>\n\n<example>\nUser: What does the git status command do?\nAssistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits.\n\n<reasoning>\nThe assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks.\n</reasoning>\n</example>\n\n<example>\nUser: Can you add a comment to the calculateTotal function to explain what it does?\nAssistant: Sure, let me add a comment to the calculateTotal function to explain what it does.\n* Uses the write tool to add a comment to the calculateTotal function *\n\n<reasoning>\nThe assistant did not use the todo list because this is a single, straightforward task confined to one location in the code. Adding a comment doesn't require tracking multiple steps or systematic organization.\n</reasoning>\n</example>\n\n<example>\nUser: Run npm install for me and tell me what happens.\nAssistant: I'll run the npm install command for you.\n\n*Executes: npm install*\n\nThe command completed successfully. Here's the output:\n[Output of npm install command]\n\nAll dependencies have been installed according to your package.json file.\n\n<reasoning>\nThe assistant did not use the todo list because this is a single command execution with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward task.\n</reasoning>\n</example>\n\n## Task States and Management\n\n1. **Task States**: Use these states to track progress:\n - pending: Task not yet started\n - in_progress: Currently working on (limit to ONE task at a time)\n - completed: Task finished successfully\n\n2. **Task Management**:\n - Update task status in real-time as you work\n - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)\n - Only have ONE task in_progress at any time\n - Complete current tasks before starting new ones\n - Remove tasks that are no longer relevant from the list entirely\n\n3. **Task Completion Requirements**:\n - ONLY mark a task as completed when you have FULLY accomplished it\n - If you encounter errors, blockers, or cannot finish, keep the task as in_progress\n - When blocked, create a new task describing what needs to be resolved\n - Never mark a task as completed if:\n - Tests are failing\n - Implementation is partial\n - You encountered unresolved errors\n - You couldn't find necessary files or dependencies\n\n4. **Task Breakdown**:\n - Create specific, actionable items\n - Break complex tasks into smaller, manageable steps\n - Use clear, descriptive task names\n\nWhen in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.\n`;\n\nconst TodoItemSchema = z.object({\n id: z.string(),\n content: z.string().min(1, 'Content cannot be empty'),\n status: z.enum(['pending', 'in_progress', 'completed']),\n priority: z.enum(['low', 'medium', 'high']),\n});\n\nconst TodoListSchema = z.array(TodoItemSchema);\n\ntype TodoList = z.infer<typeof TodoListSchema>;\n\nexport type TodoItem = z.infer<typeof TodoItemSchema>;\n\nasync function loadTodosFromFile(filePath: string) {\n if (!fs.existsSync(filePath)) return [];\n\n try {\n const fileContent = await readFile(filePath, { encoding: 'utf-8' });\n const parsedData = JSON.parse(fileContent);\n return TodoListSchema.parse(parsedData);\n } catch (error) {\n console.error(error instanceof Error ? error : new Error(String(error)));\n return [];\n }\n}\n\nasync function saveTodos(todos: TodoList, filePath: string) {\n await writeFile(filePath, JSON.stringify(todos, null, 2));\n}\n\nexport function createTodoTool(opts: { filePath: string }) {\n function ensureTodoDirectory() {\n const todoDir = path.dirname(opts.filePath);\n if (!fs.existsSync(todoDir)) {\n fs.mkdirSync(todoDir, { recursive: true });\n }\n return todoDir;\n }\n\n function getTodoFilePath() {\n ensureTodoDirectory();\n return opts.filePath;\n }\n\n async function readTodos() {\n return await loadTodosFromFile(getTodoFilePath());\n }\n\n const todoWriteTool = createTool({\n name: TOOL_NAMES.TODO_WRITE,\n description: TODO_WRITE_PROMPT,\n parameters: z.object({\n todos: TodoListSchema.describe('The updated todo list'),\n }),\n async execute({ todos }) {\n try {\n const oldTodos = await readTodos();\n const newTodos = todos;\n await saveTodos(newTodos, getTodoFilePath());\n\n return {\n llmContent:\n 'Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable',\n returnDisplay: { type: 'todo_write', oldTodos, newTodos },\n };\n } catch (error) {\n return {\n isError: true,\n llmContent:\n error instanceof Error\n ? `Failed to write todos: ${error.message}`\n : 'Unknown error',\n };\n }\n },\n approval: {\n category: 'read',\n },\n });\n\n return {\n todoWriteTool,\n };\n}\n","import fs from 'fs';\nimport path from 'pathe';\nimport { z } from 'zod';\nimport { TOOL_NAMES } from '../../core/constants';\nimport { createTool } from '../tool';\n\nexport function createWriteTool(opts: { cwd: string }) {\n return createTool({\n name: TOOL_NAMES.WRITE,\n description: `Writes a file to the local filesystem\n\nUsage:\n- This tool will overwrite the existing file if there is one at the provided path.\n- If this is an existing file, you MUST use the ${TOOL_NAMES.READ} tool first to read the file's contents. This tool will fail if you did not read the file first.\n- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.\n- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.\n- Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.`,\n parameters: z.object({\n file_path: z.string(),\n content: z.string(),\n }),\n getDescription: ({ params, cwd }) => {\n if (!params.file_path || typeof params.file_path !== 'string') {\n return 'No file path provided';\n }\n return path.relative(cwd, params.file_path);\n },\n execute: async ({ file_path, content }) => {\n try {\n const fullFilePath = path.isAbsolute(file_path)\n ? file_path\n : path.resolve(opts.cwd, file_path);\n const oldFileExists = fs.existsSync(fullFilePath);\n const oldContent = oldFileExists\n ? fs.readFileSync(fullFilePath, 'utf-8')\n : '';\n // TODO: backup old content\n // TODO: let user know if they want to write to a file that already exists\n const dir = path.dirname(fullFilePath);\n fs.mkdirSync(dir, { recursive: true });\n fs.writeFileSync(fullFilePath, format(content));\n return {\n llmContent: `File successfully written to ${file_path}`,\n returnDisplay: {\n type: 'diff_viewer',\n filePath: path.relative(opts.cwd, fullFilePath),\n absoluteFilePath: fullFilePath,\n originalContent: oldContent,\n newContent: { inputKey: 'content' },\n writeType: oldFileExists ? 'replace' : 'add',\n },\n };\n } catch (e) {\n return {\n isError: true,\n llmContent: e instanceof Error ? e.message : 'Unknown error',\n };\n }\n },\n approval: {\n category: 'write',\n },\n });\n}\n\nfunction format(content: string) {\n if (!content.endsWith('\\n')) {\n return content + '\\n';\n }\n return content;\n}\n","import type {\n ImagePart,\n NormalizedMessage,\n ReasoningPart,\n TextPart,\n ToolResultPart2,\n} from '../core/message';\n\nfunction formatToolResultContent(llmContent: unknown): string {\n if (typeof llmContent === 'string') {\n const truncatedText =\n llmContent.length > 200\n ? `${llmContent.substring(0, 200)}...`\n : llmContent;\n return `: ${truncatedText}`;\n }\n if (Array.isArray(llmContent)) {\n const textParts = llmContent\n .filter((part): part is TextPart => part.type === 'text')\n .map((part) => part.text)\n .join(' ');\n const truncatedText =\n textParts.length > 200 ? `${textParts.substring(0, 200)}...` : textParts;\n if (truncatedText) {\n return `: ${truncatedText}`;\n }\n }\n return '';\n}\n\n/**\n * Normalizes messages for compacting by filtering out tool-related content\n * while preserving the conversational flow and essential information.\n *\n * This function transforms tool calls and results into human-readable summaries\n * to make the conversation history suitable for compression without losing\n * important context about what operations were performed.\n *\n * For assistant messages:\n * - Removes tool_use parts\n * - Keeps text and reasoning parts\n * - If no text content exists, converts reasoning to text for readability\n * - If no content remains, uses a default placeholder\n *\n * For tool messages:\n * - Converts to user messages with tool execution summaries\n *\n * @param messages - Array of normalized messages to process\n * @returns Array of normalized messages with tool content converted to summaries\n */\nexport function normalizeMessagesForCompact(\n messages: NormalizedMessage[],\n): NormalizedMessage[] {\n return messages\n .map((message) => {\n if (message.role === 'assistant') {\n if (Array.isArray(message.content)) {\n const filteredContent = message.content.filter(\n (part): part is TextPart | ReasoningPart =>\n part.type === 'text' || part.type === 'reasoning',\n );\n\n if (filteredContent.length === 0) {\n return {\n ...message,\n content: [\n {\n type: 'text' as const,\n text: '[Assistant performed tool operations]',\n },\n ],\n };\n }\n\n // If there's no text content, convert reasoning to text for readability\n const hasTextPart = filteredContent.some(\n (part) => part.type === 'text',\n );\n if (!hasTextPart) {\n const reasoningTexts = filteredContent\n .filter(\n (part): part is ReasoningPart => part.type === 'reasoning',\n )\n .map((part) => part.text)\n .filter((text) => text.trim().length > 0);\n\n if (reasoningTexts.length > 0) {\n return {\n ...message,\n content: [\n {\n type: 'text' as const,\n text: reasoningTexts.join('\\n'),\n },\n ],\n };\n }\n\n // If even reasoning is empty, use default text\n return {\n ...message,\n content: [\n {\n type: 'text' as const,\n text: '[Assistant performed tool operations]',\n },\n ],\n };\n }\n\n return {\n ...message,\n content: filteredContent,\n };\n }\n return message;\n }\n\n if (message.role === 'tool') {\n if (Array.isArray(message.content)) {\n const toolSummaries = message.content.map((part: ToolResultPart2) => {\n if (part.type === 'tool-result') {\n const result = part.result;\n let summary = `Tool ${part.toolName} executed`;\n\n if (\n result &&\n typeof result === 'object' &&\n 'llmContent' in result\n ) {\n const contentSuffix = formatToolResultContent(\n result.llmContent,\n );\n summary += contentSuffix || ' successfully';\n } else {\n summary += ' successfully';\n }\n\n return summary;\n }\n return 'Tool operation completed';\n });\n\n return {\n ...message,\n role: 'user' as const,\n content: `[Tool Results Summary: ${toolSummaries.join('; ')}]`,\n };\n }\n\n return {\n ...message,\n role: 'user' as const,\n content: '[Tool operations completed]',\n };\n }\n\n // Filter out image parts from user messages in compact mode\n // Images consume too many tokens and are not needed for summarization\n if (message.role === 'user') {\n if (Array.isArray(message.content)) {\n const filteredContent = message.content.filter(\n (part): part is TextPart => part.type === 'text',\n );\n return {\n ...message,\n content: (filteredContent.length > 0\n ? filteredContent\n : message.content) as Array<TextPart | ImagePart>,\n };\n }\n return message;\n }\n\n return message;\n })\n .filter((message) => {\n if (typeof message.content === 'string') {\n return message.content.trim().length > 0;\n }\n if (Array.isArray(message.content)) {\n return message.content.length > 0;\n }\n return true;\n });\n}\n","/**\n * Checks if the given language is English or English-related.\n */\nexport function isEnglish(language: string): boolean {\n const normalized = language.toLowerCase().trim();\n return (\n normalized === 'english' ||\n normalized === 'en' ||\n normalized === 'en-us' ||\n normalized === 'en-gb' ||\n normalized === 'en-au' ||\n normalized === 'en-ca' ||\n normalized.startsWith('en-') ||\n normalized.startsWith('english')\n );\n}\n\n/**\n * Returns the language instruction string for prompts.\n * Returns empty string if the language is English.\n */\nexport function getLanguageInstruction(\n language: string,\n format: 'communicate' | 'respond' = 'communicate',\n): string {\n if (isEnglish(language)) {\n return '';\n }\n if (format === 'respond') {\n return `- Respond in ${language}.`;\n }\n return `**Language:** Please communicate in ${language}.`;\n}\n","import type { NormalizedMessage } from '../core/message';\nimport type { ModelInfo } from '../core/model';\nimport { query } from './query';\nimport { normalizeMessagesForCompact } from '../utils/messageNormalization';\nimport { getLanguageInstruction } from '../utils/language';\n\ntype CompactOptions = {\n messages: NormalizedMessage[];\n model: ModelInfo;\n language?: string;\n};\n\nexport const COMPACT_MESSAGE = `Chat history compacted successfully.`;\n\n/**\n * Build compact system prompt with optional language instruction.\n * When language is non-English, appends a language instruction to the prompt.\n */\nfunction buildCompactSystemPrompt(language?: string): string {\n if (!language) return COMPACT_SYSTEM_PROMPT;\n\n const languageInstruction = getLanguageInstruction(language, 'respond');\n if (!languageInstruction) return COMPACT_SYSTEM_PROMPT;\n\n return `${COMPACT_SYSTEM_PROMPT}\\n\\n${languageInstruction}`;\n}\n\nexport async function compact(opts: CompactOptions): Promise<string> {\n // why: The toolConfig field must be defined when using toolUse and toolResult content blocks\n const normalizedMessages = normalizeMessagesForCompact(opts.messages);\n const systemPrompt = buildCompactSystemPrompt(opts.language);\n\n const result = await query({\n messages: normalizedMessages,\n userPrompt: COMPACT_USER_PROMPT,\n systemPrompt,\n model: opts.model,\n });\n if (result.success) {\n const summary = result.data.text;\n if (!summary || summary.trim() === '') {\n throw new Error('Failed to compact: received empty summary from model');\n }\n return summary;\n }\n throw new Error(`Failed to compact: ${result.error.message}`);\n}\n\nconst COMPACT_USER_PROMPT = `\nProvide a detailed but concise summary of our conversation above. Focus on information that would be helpful for continuing the conversation, including what we did, what we're doing, which files we're working on, and what we're going to do next.\n`;\nconst COMPACT_SYSTEM_PROMPT = `\nYou are a helpful AI assistant tasked with summarizing conversations.\n\nWhen the conversation history grows too large, you will be invoked to distill the entire history into a concise, structured XML snapshot. This snapshot is CRITICAL, as it will become the agent's *only* memory of the past. The agent will resume its work based solely on this snapshot. All crucial details, plans, errors, and user directives MUST be preserved.\n\nFirst, you will think through the entire history. Review the user's overall goal, the agent's actions, tool outputs, file modifications, and any unresolved questions. Identify every piece of information that is essential for future actions.\n\nAfter your reasoning is complete, generate the final <context_summary> XML object. Be incredibly dense with information. Omit any irrelevant conversational filler.\n\nThe structure MUST be as follows:\n\n<context_summary>\n <conversation_overview>\n <!-- Single paragraph overview of the entire conversation\n <!-- Example: \"User requested implementation of a new authentication system using JWT,\n with specific requirements for token expiration and refresh mechanisms.\" -->\n </conversation_overview>\n\n <key_knowledge>\n <!-- Crucial facts, conventions, and constraints the agent must remember based on the conversation history and interaction with the user. Use bullet points. -->\n <!-- Example:\n - Build Command: \\`npm run build\\`\n - Testing: Tests are run with \\`npm test\\`. Test files must end in \\`.test.ts\\`.\n - API Endpoint: The primary API endpoint is \\`https://api.example.com/v2\\`.\n\n -->\n </key_knowledge>\n\n <file_system_state>\n <!-- List files that have been created, read, modified, or deleted. Note their status and critical learnings. -->\n <!-- Example:\n - CWD: \\`/home/user/project/src\\`\n - READ: \\`package.json\\` - Confirmed 'axios' is a dependency.\n - MODIFIED: \\`services/auth.ts\\` - Replaced 'jsonwebtoken' with 'jose'.\n - CREATED: \\`tests/new-feature.test.ts\\` - Initial test structure for the new feature.\n -->\n </file_system_state>\n\n <recent_actions>\n <!-- A summary of the last few significant agent actions and their outcomes. Focus on facts. -->\n <!-- Example:\n - Ran \\`grep 'old_function'\\` which returned 3 results in 2 files.\n - Ran \\`npm run test\\`, which failed due to a snapshot mismatch in \\`UserProfile.test.ts\\`.\n - Ran \\`ls -F static/\\` and discovered image assets are stored as \\`.webp\\`.\n -->\n </recent_actions>\n\n <current_plan>\n <!-- The agent's step-by-step plan. Mark completed steps. -->\n <!-- Example:\n 1. [DONE] Identify all files using the deprecated 'UserAPI'.\n 2. [IN PROGRESS] Refactor \\`src/components/UserProfile.tsx\\` to use the new 'ProfileAPI'.\n 3. [TODO] Refactor the remaining files.\n 4. [TODO] Update tests to reflect the API change.\n -->\n </current_plan>\n</context_summary>\n\nRemember: This summary will serve as the foundation for continuing the conversation and implementation. Ensure all critical information is preserved while maintaining clarity and conciseness.\n`;\n","import createDebug from 'debug';\nimport { countTokens } from './utils/tokenCounter';\nimport {\n COMPACTION_OUTPUT_TOKEN_MAX,\n COMPACTION_TRIGGER_RATIO,\n PRUNE_MINIMUM,\n PRUNE_PROTECTED_TOOLS,\n PRUNE_PROTECT_THRESHOLD,\n PRUNE_PROTECT_TURNS,\n} from './core/constants';\nimport type { NormalizedMessage, ToolResultPart2 } from './core/message';\n\nconst debug = createDebug('oricore:compression');\n\n// ============================================\n// Type Definitions\n// ============================================\n\nexport interface CompressionConfig {\n compaction: {\n auto: boolean; // Whether to enable auto compression\n outputTokenMax: number; // Reserved output tokens\n autoContinue: boolean; // Auto continue after compression\n triggerRatio: number; // Trigger compression when context usage exceeds this ratio (0-1)\n };\n pruning: {\n enabled: boolean; // Whether to enable pruning\n protectThreshold: number; // Protection threshold (tokens)\n minimumPrune: number; // Minimum prune amount\n protectedTools: string[]; // Protected tool list\n protectTurns: number; // Protected turns\n };\n}\n\ninterface ModelLimit {\n context: number;\n output: number;\n input?: number;\n}\n\ninterface TokenUsage {\n input: number;\n output: number;\n cacheRead?: number;\n}\n\nexport interface PruneResult {\n pruned: boolean;\n prunedCount: number;\n prunedTokens: number;\n}\n\n// ============================================\n// Utility Functions\n// ============================================\n\n/**\n * Check if compression is needed (Token overflow detection)\n *\n * Formula: currentInputTokens > context * triggerRatio\n * Triggers when usage exceeds the specified ratio of total context window\n * Example: triggerRatio=0.7 means trigger when using >70% (remaining <30%)\n */\nexport function isOverflow(\n tokens: TokenUsage,\n modelLimit: ModelLimit,\n config: CompressionConfig,\n): boolean {\n if (!config.compaction.auto) {\n return false;\n }\n\n const context = modelLimit.context;\n if (context === 0) {\n return false;\n }\n\n // Calculate current input token usage (input + cacheRead)\n const currentInputTokens = tokens.input + (tokens.cacheRead || 0);\n\n // Calculate compression threshold based on TOTAL context window\n // triggerRatio = 0.7 means: trigger when using >70% (remaining <30%)\n const compressionThreshold = context * config.compaction.triggerRatio;\n\n const overflow = currentInputTokens > compressionThreshold;\n\n debug(\n `[isOverflow] currentInputTokens=${currentInputTokens}, context=${context}, triggerRatio=${config.compaction.triggerRatio}, threshold=${compressionThreshold}, overflow=${overflow}`,\n );\n\n return overflow;\n}\n\n// ============================================\n// Compression Namespace\n// ============================================\n\nexport namespace Compression {\n export const DEFAULT_CONFIG: CompressionConfig = {\n compaction: {\n auto: true,\n outputTokenMax: COMPACTION_OUTPUT_TOKEN_MAX,\n autoContinue: true,\n triggerRatio: COMPACTION_TRIGGER_RATIO,\n },\n pruning: {\n enabled: true,\n protectThreshold: PRUNE_PROTECT_THRESHOLD,\n minimumPrune: PRUNE_MINIMUM,\n protectedTools: [...PRUNE_PROTECTED_TOOLS],\n protectTurns: PRUNE_PROTECT_TURNS,\n },\n };\n\n /**\n * Pruning: Prune historical tool outputs\n *\n * Rules:\n * 1. Traverse messages in reverse order (from newest to oldest)\n * 2. Skip recent N turns of conversation (default 2 turns)\n * 3. Accumulate token count of tool outputs\n * 4. When accumulated tokens > protectThreshold, subsequent tool outputs are marked for pruning\n * 5. Only execute if pruning amount > minimumPrune\n * 6. Stop traversing when encountering already pruned parts\n */\n export function prune(\n messages: NormalizedMessage[],\n config: CompressionConfig,\n ): PruneResult {\n if (!config.pruning.enabled) {\n return { pruned: false, prunedCount: 0, prunedTokens: 0 };\n }\n\n const { protectThreshold, minimumPrune, protectedTools, protectTurns } =\n config.pruning;\n\n let totalTokens = 0;\n let prunedTokens = 0;\n const toPrune: ToolResultPart2[] = [];\n let turns = 0;\n\n // Traverse messages in reverse order\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n\n // Count conversation turns (user messages count as one turn)\n if (msg.role === 'user') {\n turns++;\n }\n\n // Check if it's a tool message\n if (msg.role === 'tool' && Array.isArray(msg.content)) {\n // Protect recent N turns\n if (turns < protectTurns) {\n continue;\n }\n\n for (const part of msg.content as ToolResultPart2[]) {\n if (part.type !== 'tool-result') continue;\n\n // Skip protected tools\n if (protectedTools.includes(part.toolName)) {\n continue;\n }\n\n // Skip already pruned parts\n if (part.pruned) {\n // Stop traversing when encountering pruned parts\n break;\n }\n\n // Estimate token count\n const resultContent =\n typeof part.result?.llmContent === 'string'\n ? part.result.llmContent\n : JSON.stringify(part.result?.llmContent || '');\n const tokenEstimate = countTokens(resultContent);\n totalTokens += tokenEstimate;\n\n // Only parts exceeding protection threshold are marked for pruning\n if (totalTokens > protectThreshold) {\n prunedTokens += tokenEstimate;\n toPrune.push(part);\n }\n }\n }\n }\n\n // Only execute pruning if amount exceeds minimum\n if (prunedTokens > minimumPrune) {\n const prunedAt = Date.now();\n for (const part of toPrune) {\n part.pruned = true;\n part.prunedAt = prunedAt;\n // Clear original output content, keep metadata\n if (part.result) {\n part.result = {\n ...part.result,\n llmContent: `[Output pruned at ${new Date(prunedAt).toISOString()}]`,\n };\n }\n }\n\n debug(\n `[prune] Pruned ${toPrune.length} tool outputs, ~${prunedTokens} tokens`,\n );\n\n return { pruned: true, prunedCount: toPrune.length, prunedTokens };\n }\n\n return { pruned: false, prunedCount: 0, prunedTokens: 0 };\n }\n}\n","import { encode } from 'gpt-tokenizer';\n\n/**\n * Count tokens in a text string using gpt-tokenizer\n * Falls back to simple estimation if encoding fails\n *\n * @param text - The text to count tokens for\n * @returns The number of tokens\n */\nexport function countTokens(text: string): number {\n if (!text) return 0;\n try {\n return encode(text).length;\n } catch (error) {\n console.warn('Failed to encode text with gpt-tokenizer:', error);\n // Fallback to simple estimation if encoding fails\n return Math.ceil(text.length / 4);\n }\n}\n"],"mappings":";;;;;;AAIA,OAAOA,kBAAiB;;;ACJxB,OAAO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/B,wBAAY,IAAI,KAAK,QAAQ;AAAA,UAC/B;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,UAAM,WAAqB,CAAC;AAE5B,aAAS,KAAK,yBAAyB;AACvC,aAAS;AAAA,MACP,mCAAmC,YAAY;AAAA,IACjD;AACA,QAAI,iBAAiB;AACnB,YAAM,UACJ,OAAO,gBAAgB,YAAY,WAC/B,gBAAgB,UAChB,KAAK,UAAU,gBAAgB,OAAO;AAC5C,YAAM,UACJ,QAAQ,SAAS,MACb,QAAQ,UAAU,GAAG,GAAG,IAAI,QAC5B;AACN,eAAS,KAAK,iCAAiC,OAAO,GAAG;AAAA,IAC3D;AACA,aAAS,KAAK,0BAA0B;AAExC,QAAI,YAAY,OAAO,GAAG;AACxB,eAAS,KAAK;AAAA,iBAAoB;AAClC,eAAS,KAAK,sBAAsB,MAAM,KAAK,WAAW,EAAE,KAAK,IAAI,CAAC,EAAE;AACxE,eAAS,KAAK,mBAAmB;AAAA,IACnC;AAEA,aAAS,KAAK;AAAA,OAAU;AACxB,aAAS;AAAA,MACP;AAAA,IACF;AACA,aAAS;AAAA,MAAK;AAAA,IACd;AACA,aAAS,KAAK,SAAS;AAEvB,WAAO,SAAS,KAAK,IAAI;AAAA,EAC3B;AACF;","names":["createDebug","assert","createDebug","fs","fs","join","relative","sep","path","regex","path","relative","sep","fs","join","path","sep","fs","regex","selectedLines","content","createDebug","debug","debug","createDebug","resolve","startTime","message","key","assert","defu","fs","homedir","path","path","path","homedir","fs","defu","defu","defu","assert","path","z","z","z","createDebug","fs","os","path","z","os","os","resolve","debug","createDebug","fs","resolve","os","path","backgroundPIDs","result","z","fs","path","z","z","path","fs","z","z","z","z","path","fs","path","z","spawn","createDebug","path","debug","createDebug","path","resolve","MAX_CONTENT_LENGTH","glob","z","path","truncated","returnDisplay","fs","path","z","z","path","fs","countTokens","path","z","fs","fs","path","MAX_LINES_TO_READ","MAX_LINE_LENGTH","MAX_TOKENS","z","full","stats","tokenCount","countTokens","path","z","z","z","opts","z","path","fs","path","z","z","fs","path","fs","path","z","z","path","fs","path","assert","format","createDebug","countTokens","debug","createDebug","Compression","countTokens","debug","createDebug","part","summaryMessage"]}
|