agentix-cli 0.6.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +337 -116
- package/dist/agent-QYQVGKLM.js +2 -0
- package/dist/chunk-34UAFPK4.js +10 -0
- package/dist/chunk-34UAFPK4.js.map +1 -0
- package/dist/{chunk-X7UN6JAA.js → chunk-6MKAXEE5.js} +2 -2
- package/dist/chunk-BAIQJHQF.js +64 -0
- package/dist/chunk-BAIQJHQF.js.map +1 -0
- package/dist/chunk-BHDLKX3G.js +6 -0
- package/dist/chunk-BHDLKX3G.js.map +1 -0
- package/dist/chunk-CJ45Y2IR.js +12 -0
- package/dist/chunk-CJ45Y2IR.js.map +1 -0
- package/dist/chunk-DSYKYZMT.js +2 -0
- package/dist/chunk-DSYKYZMT.js.map +1 -0
- package/dist/chunk-IVVVYXPH.js +136 -0
- package/dist/chunk-IVVVYXPH.js.map +1 -0
- package/dist/{chunk-MGMZNJCE.js → chunk-KXZMYLHQ.js} +27 -27
- package/dist/chunk-KXZMYLHQ.js.map +1 -0
- package/dist/chunk-SBUX74OU.js +108 -0
- package/dist/chunk-SBUX74OU.js.map +1 -0
- package/dist/chunk-X32247GM.js +2 -0
- package/dist/chunk-X32247GM.js.map +1 -0
- package/dist/chunk-ZRYBSI5G.js +23 -0
- package/dist/chunk-ZRYBSI5G.js.map +1 -0
- package/dist/cli.js +289 -9
- package/dist/cli.js.map +1 -1
- package/dist/compaction-E3MQRLTL.js +28 -0
- package/dist/compaction-E3MQRLTL.js.map +1 -0
- package/dist/config-MSWKC466.js +2 -0
- package/dist/debug-N3B5NVJU.js +2 -0
- package/dist/heal-OTGT5HHJ.js +2 -0
- package/dist/heal-OTGT5HHJ.js.map +1 -0
- package/dist/index.d.ts +707 -164
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/memory-extract-RGPUPMKU.js +2 -0
- package/dist/memory-extract-RGPUPMKU.js.map +1 -0
- package/dist/{providers-AVYG63KK.js → providers-G3WZ4RVJ.js} +2 -2
- package/dist/providers-G3WZ4RVJ.js.map +1 -0
- package/dist/registry-FP6FUOXF.js +2 -0
- package/dist/registry-FP6FUOXF.js.map +1 -0
- package/dist/subagent-WV7QKQ3L.js +3 -0
- package/dist/subagent-WV7QKQ3L.js.map +1 -0
- package/dist/usage-dashboard-2TJQBFSH.js +404 -0
- package/dist/usage-dashboard-2TJQBFSH.js.map +1 -0
- package/package.json +4 -1
- package/dist/agent-K2YOEOJ5.js +0 -2
- package/dist/chunk-F73GPYCO.js +0 -106
- package/dist/chunk-F73GPYCO.js.map +0 -1
- package/dist/chunk-MGMZNJCE.js.map +0 -1
- package/dist/chunk-WT2UJMBC.js +0 -68
- package/dist/chunk-WT2UJMBC.js.map +0 -1
- package/dist/chunk-Z4GC5D6D.js +0 -12
- package/dist/chunk-Z4GC5D6D.js.map +0 -1
- package/dist/heal-UV5A6B5T.js +0 -2
- /package/dist/{agent-K2YOEOJ5.js.map → agent-QYQVGKLM.js.map} +0 -0
- /package/dist/{chunk-X7UN6JAA.js.map → chunk-6MKAXEE5.js.map} +0 -0
- /package/dist/{heal-UV5A6B5T.js.map → config-MSWKC466.js.map} +0 -0
- /package/dist/{providers-AVYG63KK.js.map → debug-N3B5NVJU.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent/tools/definitions.ts","../src/agent/providers/claude.ts","../src/agent/providers/claude-code.ts","../src/agent/providers/index.ts"],"sourcesContent":["// --- Agent tool definitions in Anthropic tool_use format ---\n\nexport interface ToolDefinition {\n name: string\n description: string\n input_schema: Record<string, unknown>\n permission?: \"file-read\" | \"file-write\" | \"command\" | \"none\"\n}\n\nconst TOOL_DEFINITIONS: ToolDefinition[] = [\n {\n name: \"create_files\",\n description:\n \"Create one or more files as output. Use this when you need to generate code, documents, configs, or any file-based output.\",\n input_schema: {\n type: \"object\",\n properties: {\n files: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description:\n \"Relative file path from project root (e.g., src/components/Button.tsx)\",\n },\n content: {\n type: \"string\",\n description: \"The full content of the file\",\n },\n language: {\n type: \"string\",\n description: \"Programming language or file type\",\n },\n description: {\n type: \"string\",\n description: \"Brief description of what this file does\",\n },\n },\n required: [\"path\", \"content\"],\n },\n },\n summary: {\n type: \"string\",\n description: \"Brief summary of all generated files\",\n },\n },\n required: [\"files\"],\n },\n permission: \"file-write\",\n },\n {\n name: \"ask_user\",\n description:\n \"Ask the user a clarifying question when you need more information to proceed. Use this when the request is ambiguous or you need to confirm important decisions.\",\n input_schema: {\n type: \"object\",\n properties: {\n question: {\n type: \"string\",\n description: \"The question to ask the user\",\n },\n options: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Optional list of choices for the user\",\n },\n },\n required: [\"question\"],\n },\n permission: \"none\",\n },\n {\n name: \"read_file\",\n description:\n \"Read the contents of a file. Use this to inspect existing code, understand patterns, check implementations, or gather context before generating code.\",\n input_schema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description: \"Relative file path from project root\",\n },\n max_lines: {\n type: \"number\",\n description:\n \"Maximum number of lines to read. Defaults to 500. Use for large files.\",\n },\n },\n required: [\"path\"],\n },\n permission: \"file-read\",\n },\n {\n name: \"search_files\",\n description:\n \"Search for files matching a pattern and optionally search their content with a regex. Use this to find relevant code, understand project structure, or locate specific patterns.\",\n input_schema: {\n type: \"object\",\n properties: {\n pattern: {\n type: \"string\",\n description:\n \"Glob pattern to match files (e.g., 'src/**/*.ts', '*.json')\",\n },\n content_regex: {\n type: \"string\",\n description:\n \"Optional regex to search within matched files. Returns matching lines.\",\n },\n max_results: {\n type: \"number\",\n description: \"Maximum number of results to return. Default: 50.\",\n },\n },\n required: [\"pattern\"],\n },\n permission: \"none\",\n },\n {\n name: \"list_directory\",\n description:\n \"List files and directories at a given path. Use this to explore project structure.\",\n input_schema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description:\n \"Relative directory path from project root. Defaults to '.' (root).\",\n },\n recursive: {\n type: \"boolean\",\n description: \"List recursively. Default: false.\",\n },\n max_depth: {\n type: \"number\",\n description: \"Maximum depth for recursive listing. Default: 3.\",\n },\n },\n },\n permission: \"none\",\n },\n {\n name: \"run_command\",\n description:\n \"Execute a shell command. Use this to run build tools, test commands, linters, or inspect the environment. Commands run in the project root directory.\",\n input_schema: {\n type: \"object\",\n properties: {\n command: {\n type: \"string\",\n description: \"The shell command to execute\",\n },\n timeout: {\n type: \"number\",\n description:\n \"Timeout in milliseconds. Default: 30000 (30 seconds).\",\n },\n },\n required: [\"command\"],\n },\n permission: \"command\",\n },\n {\n name: \"edit_file\",\n description:\n \"Apply search-and-replace edits to an existing file. Use this for targeted modifications to existing code rather than rewriting entire files.\",\n input_schema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description: \"Relative file path from project root\",\n },\n edits: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n old_text: {\n type: \"string\",\n description: \"The exact text to find in the file\",\n },\n new_text: {\n type: \"string\",\n description: \"The replacement text\",\n },\n },\n required: [\"old_text\", \"new_text\"],\n },\n description: \"List of search/replace pairs to apply in order\",\n },\n },\n required: [\"path\", \"edits\"],\n },\n permission: \"file-write\",\n },\n]\n\n/**\n * Get all tool definitions in Anthropic API format (for generateRaw()).\n * Optionally filter by enabled tool names.\n */\nexport function getAnthropicTools(enabledTools?: string[]): Array<{\n name: string\n description: string\n input_schema: Record<string, unknown>\n}> {\n const defs = enabledTools\n ? TOOL_DEFINITIONS.filter((t) => enabledTools.includes(t.name))\n : TOOL_DEFINITIONS\n\n return defs.map(({ name, description, input_schema }) => ({\n name,\n description,\n input_schema,\n }))\n}\n\n/**\n * Get the legacy tools (create_files + ask_user) for backward compatibility.\n */\nexport function getLegacyTools(): Array<{\n name: string\n description: string\n input_schema: Record<string, unknown>\n}> {\n return getAnthropicTools([\"create_files\", \"ask_user\"])\n}\n\n/**\n * Format tool descriptions for inclusion in a system prompt.\n * Used when the `claude` CLI binary handles its own tools —\n * we describe our additional tools as text so the binary's built-in\n * capabilities (read, write, bash) handle them natively.\n */\nexport function formatToolsForSystemPrompt(): string {\n const agenticTools = TOOL_DEFINITIONS.filter(\n (t) => t.name !== \"create_files\" && t.name !== \"ask_user\"\n )\n\n if (agenticTools.length === 0) return \"\"\n\n const lines = [\n \"# Available Capabilities\",\n \"In addition to generating files, you have the following capabilities:\",\n \"\",\n ]\n\n for (const tool of agenticTools) {\n lines.push(`## ${tool.name}`)\n lines.push(tool.description)\n lines.push(\"\")\n }\n\n return lines.join(\"\\n\")\n}\n\nexport const ALL_TOOL_NAMES = TOOL_DEFINITIONS.map((t) => t.name)\n","import type {\n AgentProvider,\n GenerationMessage,\n GenerationResult,\n GeneratedFile,\n ProviderOptions,\n StreamEvent,\n AnthropicMessage,\n RawGenerationResult,\n ContentBlock,\n} from \"./types\"\nimport { resolveToken } from \"@/utils/auth-store\"\nimport { getLegacyTools } from \"../tools/definitions\"\n\n// --- Claude provider (default) using Anthropic SDK ---\n\nconst DEFAULT_MODEL = \"claude-sonnet-4-20250514\"\nconst DEFAULT_MAX_TOKENS = 8192\n\ninterface AnthropicResponse {\n id: string\n content: Array<{\n type: \"text\" | \"tool_use\" | \"tool_result\"\n text?: string\n id?: string\n name?: string\n input?: Record<string, unknown>\n tool_use_id?: string\n content?: string\n }>\n model: string\n stop_reason: string\n usage: { input_tokens: number; output_tokens: number }\n}\n\nexport class ClaudeProvider implements AgentProvider {\n name = \"claude\"\n private apiKey: string\n private authType: \"api-key\" | \"oauth\" = \"api-key\"\n\n constructor(apiKey?: string) {\n this.apiKey = apiKey || process.env.ANTHROPIC_API_KEY || \"\"\n if (!this.apiKey) {\n // Fallback to auth store\n const resolved = resolveToken()\n if (resolved) {\n this.apiKey = resolved.token\n this.authType = resolved.authType\n }\n }\n if (!this.apiKey) {\n throw new Error(\n \"Anthropic API key required. Run `agentx model` to configure, set ANTHROPIC_API_KEY, or pass --api-key.\"\n )\n }\n }\n\n async generate(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): Promise<GenerationResult> {\n const model = options?.model || DEFAULT_MODEL\n const maxTokens = options?.maxTokens || DEFAULT_MAX_TOKENS\n\n // Extract system message\n const systemMsg = messages.find((m) => m.role === \"system\")\n const conversationMsgs = messages\n .filter((m) => m.role !== \"system\")\n .map((m) => ({\n role: m.role as \"user\" | \"assistant\",\n content: m.content,\n }))\n\n const body: Record<string, unknown> = {\n model,\n max_tokens: maxTokens,\n messages: conversationMsgs,\n tools: getLegacyTools(),\n }\n\n if (systemMsg) {\n body.system = systemMsg.content\n }\n\n if (options?.temperature !== undefined) {\n body.temperature = options.temperature\n }\n\n const response = await this.callApi(body)\n\n return this.parseResponse(response)\n }\n\n async generateRaw(\n messages: AnthropicMessage[],\n systemPrompt: string,\n tools: Array<{ name: string; description: string; input_schema: Record<string, unknown> }>,\n options?: ProviderOptions\n ): Promise<RawGenerationResult> {\n const model = options?.model || DEFAULT_MODEL\n const maxTokens = options?.maxTokens || DEFAULT_MAX_TOKENS\n\n const body: Record<string, unknown> = {\n model,\n max_tokens: maxTokens,\n system: systemPrompt,\n messages,\n tools,\n }\n\n if (options?.temperature !== undefined) {\n body.temperature = options.temperature\n }\n\n const response = await this.callApi(body)\n\n // Map response content blocks to our ContentBlock type\n const content: ContentBlock[] = response.content.map((block) => {\n if (block.type === \"text\") {\n return { type: \"text\" as const, text: block.text || \"\" }\n }\n if (block.type === \"tool_use\") {\n return {\n type: \"tool_use\" as const,\n id: block.id || \"\",\n name: block.name || \"\",\n input: block.input || {},\n }\n }\n return { type: \"text\" as const, text: \"\" }\n })\n\n return {\n content,\n stop_reason: response.stop_reason as RawGenerationResult[\"stop_reason\"],\n usage: response.usage,\n }\n }\n\n async *stream(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): AsyncIterable<StreamEvent> {\n const model = options?.model || DEFAULT_MODEL\n const maxTokens = options?.maxTokens || DEFAULT_MAX_TOKENS\n\n const systemMsg = messages.find((m) => m.role === \"system\")\n const conversationMsgs = messages\n .filter((m) => m.role !== \"system\")\n .map((m) => ({\n role: m.role as \"user\" | \"assistant\",\n content: m.content,\n }))\n\n const body: Record<string, unknown> = {\n model,\n max_tokens: maxTokens,\n messages: conversationMsgs,\n stream: true,\n tools: getLegacyTools(),\n }\n\n if (systemMsg) {\n body.system = systemMsg.content\n }\n\n const headers = this.buildHeaders()\n\n const res = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n })\n\n if (!res.ok) {\n const errorText = await res.text()\n yield { type: \"error\", error: `Anthropic API error (${res.status}): ${errorText}` }\n return\n }\n\n const reader = res.body?.getReader()\n if (!reader) {\n yield { type: \"error\", error: \"No response body\" }\n return\n }\n\n const decoder = new TextDecoder()\n let buffer = \"\"\n const files: GeneratedFile[] = []\n let content = \"\"\n let followUp: string | undefined\n let tokensUsed = 0\n let activeTool: { name: string; id: string; json: string } | null = null\n\n const inferFollowUpFromText = (text: string): string | undefined => {\n const cleaned = (text || \"\").trim()\n if (!cleaned) return undefined\n if (cleaned.includes(\"```\")) return undefined\n\n const lines = cleaned.replace(/\\r\\n/g, \"\\n\").split(\"\\n\")\n const tail = lines.slice(Math.max(0, lines.length - 20))\n const tailText = tail.join(\"\\n\")\n\n const looksLikePlanApproval =\n /\\b(plan|proposal)\\b/i.test(tailText) &&\n /(ready for your review|review (the )?plan|requesting plan approval|awaiting approval|waiting for (your )?approval|approve (the )?plan|approval to proceed)/i.test(\n tailText\n )\n\n if (looksLikePlanApproval) {\n return (\n \"The provider is requesting plan approval.\\n\" +\n \"Reply with:\\n\" +\n \"- approve\\n\" +\n \"- revise: <what to change>\\n\" +\n \"- cancel\"\n )\n }\n\n const isIntro = (l: string) =>\n /^(question|clarification|clarify|i need|need more|before i proceed|to proceed|please (confirm|clarify)|which|what|where|when|how|do you)/i.test(\n l.trim()\n )\n\n let startIdx = -1\n for (let i = tail.length - 1; i >= 0; i--) {\n const l = tail[i].trim()\n if (!l) continue\n if (isIntro(l) || l.includes(\"?\")) {\n startIdx = i\n break\n }\n }\n if (startIdx === -1) return undefined\n\n const out: string[] = []\n for (let i = startIdx; i < tail.length && out.length < 8; i++) {\n const l = tail[i]\n const t = l.trim()\n if (out.length > 0 && !t) break\n if (\n out.length > 0 &&\n !/^(options?:|[-*]\\s|\\d+[\\).]\\s)/i.test(t) &&\n !t.includes(\"?\")\n ) {\n break\n }\n out.push(l.trimEnd())\n }\n\n const candidate = out.join(\"\\n\").trim()\n if (candidate.length < 5) return undefined\n if (candidate.length > 800) return candidate.slice(0, 800).trimEnd()\n return candidate\n }\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split(\"\\n\")\n buffer = lines.pop() || \"\"\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue\n const data = line.slice(6).trim()\n if (data === \"[DONE]\") continue\n\n try {\n const event = JSON.parse(data)\n\n if (event.type === \"content_block_start\") {\n if (event.content_block?.type === \"tool_use\") {\n // Finalize any previous tool block if the stream didn't send a stop.\n if (activeTool) {\n yield { type: \"tool_use_end\", name: activeTool.name }\n try {\n const input = JSON.parse(activeTool.json || \"{}\") as any\n if (activeTool.name === \"create_files\" && input) {\n if (Array.isArray(input.files)) {\n files.push(...(input.files as GeneratedFile[]))\n }\n if (typeof input.summary === \"string\" && input.summary.trim()) {\n content += `\\n${input.summary}`\n }\n }\n if (activeTool.name === \"ask_user\" && input) {\n if (typeof input.question === \"string\" && input.question.trim()) {\n followUp = input.question\n if (Array.isArray(input.options) && input.options.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n } catch {\n // Ignore invalid tool JSON\n } finally {\n activeTool = null\n }\n }\n\n activeTool = {\n name: event.content_block.name,\n id: event.content_block.id,\n json: \"\",\n }\n yield {\n type: \"tool_use_start\",\n name: event.content_block.name,\n id: event.content_block.id,\n }\n }\n }\n\n if (event.type === \"content_block_delta\") {\n if (event.delta?.type === \"text_delta\") {\n content += event.delta.text\n yield { type: \"text_delta\", text: event.delta.text }\n }\n if (event.delta?.type === \"input_json_delta\") {\n if (activeTool) activeTool.json += event.delta.partial_json || \"\"\n yield { type: \"tool_use_delta\", json: event.delta.partial_json }\n }\n }\n\n if (event.type === \"content_block_stop\") {\n // Tool use blocks are complete\n if (activeTool) {\n // Manually inline finalize to avoid generator gymnastics.\n yield { type: \"tool_use_end\", name: activeTool.name }\n try {\n const input = JSON.parse(activeTool.json || \"{}\") as any\n if (activeTool.name === \"create_files\" && input) {\n if (Array.isArray(input.files)) {\n files.push(...(input.files as GeneratedFile[]))\n }\n if (typeof input.summary === \"string\" && input.summary.trim()) {\n content += `\\n${input.summary}`\n }\n }\n if (activeTool.name === \"ask_user\" && input) {\n if (typeof input.question === \"string\" && input.question.trim()) {\n followUp = input.question\n if (Array.isArray(input.options) && input.options.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n } catch {\n // Ignore invalid tool JSON\n } finally {\n activeTool = null\n }\n }\n }\n\n if (event.type === \"message_delta\") {\n if (event.usage) {\n tokensUsed = (event.usage.input_tokens || 0) + (event.usage.output_tokens || 0)\n }\n }\n\n if (event.type === \"message_stop\") {\n // Message complete\n }\n } catch {\n // Skip unparseable lines\n }\n }\n }\n } finally {\n reader.releaseLock()\n }\n\n // Flush any trailing tool input.\n if (activeTool) {\n yield { type: \"tool_use_end\", name: activeTool.name }\n try {\n const input = JSON.parse(activeTool.json || \"{}\") as any\n if (activeTool.name === \"create_files\" && input) {\n if (Array.isArray(input.files)) {\n files.push(...(input.files as GeneratedFile[]))\n }\n if (typeof input.summary === \"string\" && input.summary.trim()) {\n content += `\\n${input.summary}`\n }\n }\n if (activeTool.name === \"ask_user\" && input) {\n if (typeof input.question === \"string\" && input.question.trim()) {\n followUp = input.question\n if (Array.isArray(input.options) && input.options.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n } catch {\n // Ignore\n }\n activeTool = null\n }\n\n if (!followUp && files.length === 0) {\n followUp = inferFollowUpFromText(content)\n }\n\n yield {\n type: \"done\",\n result: { content, files, followUp, tokensUsed },\n }\n }\n\n private buildHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"anthropic-version\": \"2023-06-01\",\n }\n\n if (this.authType === \"oauth\") {\n headers[\"Authorization\"] = `Bearer ${this.apiKey}`\n headers[\"anthropic-beta\"] = \"claude-code-20250219,oauth-2025-04-20\"\n headers[\"user-agent\"] = \"claude-cli/2.1.2 (external, cli)\"\n headers[\"x-app\"] = \"cli\"\n headers[\"anthropic-dangerous-direct-browser-access\"] = \"true\"\n } else {\n headers[\"x-api-key\"] = this.apiKey\n }\n\n return headers\n }\n\n private async callApi(body: Record<string, unknown>): Promise<AnthropicResponse> {\n const headers = this.buildHeaders()\n\n const res = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n })\n\n if (!res.ok) {\n const errorText = await res.text()\n throw new Error(`Anthropic API error (${res.status}): ${errorText}`)\n }\n\n return (await res.json()) as AnthropicResponse\n }\n\n private parseResponse(response: AnthropicResponse): GenerationResult {\n const files: GeneratedFile[] = []\n let content = \"\"\n let followUp: string | undefined\n\n for (const block of response.content) {\n if (block.type === \"text\") {\n content += block.text || \"\"\n }\n\n if (block.type === \"tool_use\") {\n if (block.name === \"create_files\" && block.input) {\n const input = block.input as {\n files: GeneratedFile[]\n summary?: string\n }\n files.push(...(input.files || []))\n if (input.summary) {\n content += `\\n${input.summary}`\n }\n }\n\n if (block.name === \"ask_user\" && block.input) {\n const input = block.input as { question: string; options?: string[] }\n followUp = input.question\n if (input.options?.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n }\n\n return {\n content,\n files,\n followUp,\n tokensUsed: response.usage.input_tokens + response.usage.output_tokens,\n }\n }\n}\n","import type {\n AgentProvider,\n GenerationMessage,\n GenerationResult,\n GeneratedFile,\n ProviderOptions,\n StreamEvent,\n AnthropicMessage,\n RawGenerationResult,\n ContentBlock,\n} from \"./types\"\nimport { resolveToken, loadAuthConfig } from \"@/utils/auth-store\"\nimport { execa } from \"execa\"\nimport { getLegacyTools } from \"../tools/definitions\"\n\n// --- Claude Code provider: uses Claude CLI (subscription) or direct API (API key) ---\n\nconst DEFAULT_MODEL = \"claude-sonnet-4-20250514\"\nconst DEFAULT_MAX_TOKENS = 8192\n\n// Model ID → claude CLI alias\nconst CLI_MODEL_ALIASES: Record<string, string> = {\n \"claude-sonnet-4-20250514\": \"sonnet\",\n \"claude-opus-4-20250514\": \"opus\",\n \"claude-haiku-4-20250514\": \"haiku\",\n}\n\ntype AuthCredential = { type: \"oauth\"; token: string } | { type: \"api-key\"; token: string }\n\ninterface AnthropicResponse {\n id: string\n content: Array<{\n type: \"text\" | \"tool_use\" | \"tool_result\"\n text?: string\n id?: string\n name?: string\n input?: Record<string, unknown>\n }>\n model: string\n stop_reason: string\n usage: { input_tokens: number; output_tokens: number }\n}\n\nexport class ClaudeCodeProvider implements AgentProvider {\n name = \"claude-code\"\n private credential: AuthCredential\n\n constructor() {\n // Stored config takes priority — if user ran `agentx model` and chose OAuth,\n // we use that regardless of ANTHROPIC_API_KEY env var (same as OpenClaw's clearEnv).\n const stored = loadAuthConfig()\n if (stored) {\n this.credential = { type: stored.authType, token: stored.token }\n return\n }\n\n const resolved = resolveToken()\n if (!resolved) {\n throw new Error(\n \"No Claude credentials found.\\n\" +\n \"Options:\\n\" +\n \" 1. Run `agentx model` to configure credentials\\n\" +\n \" 2. Set ANTHROPIC_API_KEY environment variable\\n\" +\n \" 3. Set ANTHROPIC_OAUTH_TOKEN environment variable\"\n )\n }\n this.credential = { type: resolved.authType, token: resolved.token }\n }\n\n async generate(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): Promise<GenerationResult> {\n // OAuth tokens → use claude CLI (subscription billing)\n // API keys → call API directly\n if (this.credential.type === \"oauth\") {\n return this.generateViaCli(messages, options)\n }\n return this.generateViaApi(messages, options)\n }\n\n /**\n * generateRaw() for the agentic tool_result loop.\n * Only available for API key auth — the CLI binary has its own agent loop.\n */\n async generateRaw(\n messages: AnthropicMessage[],\n systemPrompt: string,\n tools: Array<{ name: string; description: string; input_schema: Record<string, unknown> }>,\n options?: ProviderOptions\n ): Promise<RawGenerationResult> {\n // OAuth path: not supported — the claude CLI has its own built-in tools\n if (this.credential.type === \"oauth\") {\n throw new Error(\"generateRaw() not available for OAuth/CLI mode\")\n }\n\n const model = options?.model || DEFAULT_MODEL\n const maxTokens = options?.maxTokens || DEFAULT_MAX_TOKENS\n\n const body: Record<string, unknown> = {\n model,\n max_tokens: maxTokens,\n system: systemPrompt,\n messages,\n tools,\n }\n\n if (options?.temperature !== undefined) {\n body.temperature = options.temperature\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"anthropic-version\": \"2023-06-01\",\n \"x-api-key\": this.credential.token,\n }\n\n const res = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n })\n\n if (!res.ok) {\n const errorText = await res.text()\n throw new Error(`Anthropic API error (${res.status}): ${errorText}`)\n }\n\n const response = (await res.json()) as AnthropicResponse\n\n const content: ContentBlock[] = response.content.map((block) => {\n if (block.type === \"text\") {\n return { type: \"text\" as const, text: block.text || \"\" }\n }\n if (block.type === \"tool_use\") {\n return {\n type: \"tool_use\" as const,\n id: block.id || \"\",\n name: block.name || \"\",\n input: block.input || {},\n }\n }\n return { type: \"text\" as const, text: \"\" }\n })\n\n return {\n content,\n stop_reason: response.stop_reason as RawGenerationResult[\"stop_reason\"],\n usage: response.usage,\n }\n }\n\n /**\n * Returns true if this provider can use the agentic tool loop.\n * Only available for API key auth (CLI mode falls back to legacy loop).\n */\n get supportsAgenticLoop(): boolean {\n return this.credential.type === \"api-key\"\n }\n\n /**\n * Generate via the `claude` CLI binary.\n * This is how subscription billing works — the CLI handles auth internally.\n */\n private async generateViaCli(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): Promise<GenerationResult> {\n const model = options?.model || loadAuthConfig()?.model || DEFAULT_MODEL\n const cliModel = CLI_MODEL_ALIASES[model] || model\n\n const systemMsg = messages.find((m) => m.role === \"system\")\n const userMsgs = messages.filter((m) => m.role === \"user\")\n const prompt = userMsgs.map((m) => m.content).join(\"\\n\\n\")\n\n const args = [\n \"-p\",\n \"--output-format\", \"json\",\n \"--model\", cliModel,\n \"--dangerously-skip-permissions\",\n ]\n\n if (systemMsg) {\n args.push(\"--append-system-prompt\", systemMsg.content)\n }\n\n // Prompt goes as the last positional argument\n args.push(prompt)\n\n // Clear ANTHROPIC_API_KEY to force CLI to use subscription auth\n const env = { ...process.env }\n delete env.ANTHROPIC_API_KEY\n delete env.ANTHROPIC_API_KEY_OLD\n\n const result = await execa(\"claude\", args, {\n env,\n extendEnv: false,\n reject: false,\n timeout: 300_000,\n stdin: \"ignore\",\n })\n\n if (result.exitCode !== 0) {\n const err = result.stderr || result.stdout || \"Claude CLI failed\"\n throw new Error(`Claude CLI error: ${err}`)\n }\n\n // Claude CLI may return success exit code but with is_error in JSON\n const output = result.stdout.trim()\n try {\n const json = JSON.parse(output)\n if (json.is_error && json.result) {\n throw new Error(json.result)\n }\n } catch (e: any) {\n if (e.message && !e.message.includes(\"JSON\")) throw e\n // Not JSON — that's fine, parseCliOutput will handle it\n }\n\n return this.parseCliOutput(output)\n }\n\n /**\n * Generate via direct Anthropic API call (for API key auth).\n */\n private async generateViaApi(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): Promise<GenerationResult> {\n const model = options?.model || DEFAULT_MODEL\n const maxTokens = options?.maxTokens || DEFAULT_MAX_TOKENS\n\n const systemMsg = messages.find((m) => m.role === \"system\")\n const conversationMsgs = messages\n .filter((m) => m.role !== \"system\")\n .map((m) => ({\n role: m.role as \"user\" | \"assistant\",\n content: m.content,\n }))\n\n const body: Record<string, unknown> = {\n model,\n max_tokens: maxTokens,\n messages: conversationMsgs,\n tools: getLegacyTools(),\n }\n\n if (systemMsg) {\n body.system = systemMsg.content\n }\n\n if (options?.temperature !== undefined) {\n body.temperature = options.temperature\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"anthropic-version\": \"2023-06-01\",\n \"x-api-key\": this.credential.token,\n }\n\n const res = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n })\n\n if (!res.ok) {\n const errorText = await res.text()\n throw new Error(`Anthropic API error (${res.status}): ${errorText}`)\n }\n\n const response = (await res.json()) as AnthropicResponse\n return this.parseApiResponse(response)\n }\n\n /**\n * Stream responses. For OAuth, uses CLI with --output-format stream-json.\n * For API keys, uses SSE streaming.\n */\n async *stream(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): AsyncIterable<StreamEvent> {\n if (this.credential.type === \"oauth\") {\n // CLI streaming via --output-format stream-json\n yield* this.streamViaCli(messages, options)\n } else {\n // API streaming via SSE (same as ClaudeProvider.stream)\n yield* this.streamViaApi(messages, options)\n }\n }\n\n private async *streamViaCli(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): AsyncIterable<StreamEvent> {\n const model = options?.model || loadAuthConfig()?.model || DEFAULT_MODEL\n const cliModel = CLI_MODEL_ALIASES[model] || model\n\n const systemMsg = messages.find((m) => m.role === \"system\")\n const userMsgs = messages.filter((m) => m.role === \"user\")\n const prompt = userMsgs.map((m) => m.content).join(\"\\n\\n\")\n\n const args = [\n \"-p\",\n \"--output-format\", \"stream-json\",\n \"--model\", cliModel,\n \"--dangerously-skip-permissions\",\n ]\n\n if (systemMsg) {\n args.push(\"--append-system-prompt\", systemMsg.content)\n }\n\n args.push(prompt)\n\n const env = { ...process.env }\n delete env.ANTHROPIC_API_KEY\n delete env.ANTHROPIC_API_KEY_OLD\n\n const child = execa(\"claude\", args, {\n env,\n extendEnv: false,\n reject: false,\n timeout: 300_000,\n stdin: \"ignore\",\n })\n\n let fullContent = \"\"\n let stderr = \"\"\n let fatalError: string | undefined\n\n if (child.stderr) {\n child.stderr.on(\"data\", (chunk: any) => {\n stderr += Buffer.isBuffer(chunk) ? chunk.toString(\"utf8\") : String(chunk)\n })\n }\n\n if (child.stdout) {\n const decoder = new TextDecoder()\n const readable = child.stdout as unknown as AsyncIterable<Uint8Array>\n\n for await (const chunk of readable) {\n const text = typeof chunk === \"string\" ? chunk : decoder.decode(chunk, { stream: true })\n // Stream JSON format: each line is a JSON object\n const lines = text.split(\"\\n\").filter(Boolean)\n for (const line of lines) {\n try {\n const event = JSON.parse(line)\n // Some claude stream-json builds emit error events.\n if (event.type === \"error\") {\n fatalError = String(event.error || event.message || \"Claude CLI error\")\n continue\n }\n if (event.is_error && (event.result || event.message)) {\n fatalError = String(event.result || event.message)\n continue\n }\n if (event.type === \"assistant\" && event.message) {\n fullContent += event.message\n yield { type: \"text_delta\", text: event.message }\n } else if (event.type === \"result\") {\n fullContent = event.result || fullContent\n }\n } catch {\n // Not JSON, treat as raw text\n fullContent += line\n yield { type: \"text_delta\", text: line }\n }\n }\n }\n }\n\n const res = await child\n if (res.exitCode !== 0 && !fatalError) {\n fatalError = (stderr || res.stderr || res.stdout || \"Claude CLI failed\").toString().trim()\n }\n\n if (fatalError) {\n yield { type: \"error\", error: `Claude CLI error: ${fatalError}` }\n return\n }\n\n const files = this.extractFilesFromText(fullContent)\n const followUp =\n files.length === 0 ? this.inferFollowUpFromText(fullContent) : undefined\n yield {\n type: \"done\",\n result: { content: fullContent, files, followUp, tokensUsed: 0 },\n }\n }\n\n private async *streamViaApi(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): AsyncIterable<StreamEvent> {\n const model = options?.model || DEFAULT_MODEL\n const maxTokens = options?.maxTokens || DEFAULT_MAX_TOKENS\n\n const systemMsg = messages.find((m) => m.role === \"system\")\n const conversationMsgs = messages\n .filter((m) => m.role !== \"system\")\n .map((m) => ({ role: m.role as \"user\" | \"assistant\", content: m.content }))\n\n const body: Record<string, unknown> = {\n model,\n max_tokens: maxTokens,\n messages: conversationMsgs,\n tools: getLegacyTools(),\n stream: true,\n }\n\n if (systemMsg) body.system = systemMsg.content\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"anthropic-version\": \"2023-06-01\",\n \"x-api-key\": this.credential.token,\n }\n\n const res = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n })\n\n if (!res.ok) {\n const errorText = await res.text()\n yield { type: \"error\", error: `Anthropic API error (${res.status}): ${errorText}` }\n return\n }\n\n const reader = res.body?.getReader()\n if (!reader) {\n yield { type: \"error\", error: \"No response body\" }\n return\n }\n\n const decoder = new TextDecoder()\n let buffer = \"\"\n let content = \"\"\n let tokensUsed = 0\n const files: GeneratedFile[] = []\n let followUp: string | undefined\n let activeTool: { name: string; id: string; json: string } | null = null\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split(\"\\n\")\n buffer = lines.pop() || \"\"\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue\n const data = line.slice(6).trim()\n if (data === \"[DONE]\") continue\n\n try {\n const event = JSON.parse(data)\n if (event.type === \"content_block_start\") {\n if (event.content_block?.type === \"tool_use\") {\n // Finalize any previous tool block if the stream didn't send a stop.\n if (activeTool) {\n yield { type: \"tool_use_end\", name: activeTool.name }\n try {\n const input = JSON.parse(activeTool.json || \"{}\") as any\n if (activeTool.name === \"create_files\" && input) {\n if (Array.isArray(input.files)) {\n files.push(...(input.files as GeneratedFile[]))\n }\n if (typeof input.summary === \"string\" && input.summary.trim()) {\n content += `\\n${input.summary}`\n }\n }\n if (activeTool.name === \"ask_user\" && input) {\n if (typeof input.question === \"string\" && input.question.trim()) {\n followUp = input.question\n if (Array.isArray(input.options) && input.options.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n } catch {\n // Ignore invalid tool JSON\n } finally {\n activeTool = null\n }\n }\n\n activeTool = {\n name: event.content_block.name,\n id: event.content_block.id,\n json: \"\",\n }\n yield { type: \"tool_use_start\", name: activeTool.name, id: activeTool.id }\n }\n }\n\n if (event.type === \"content_block_delta\" && event.delta?.type === \"text_delta\") {\n content += event.delta.text\n yield { type: \"text_delta\", text: event.delta.text }\n }\n if (event.type === \"content_block_delta\" && event.delta?.type === \"input_json_delta\") {\n if (activeTool) activeTool.json += event.delta.partial_json || \"\"\n yield { type: \"tool_use_delta\", json: event.delta.partial_json }\n }\n if (event.type === \"content_block_stop\") {\n if (activeTool) {\n yield { type: \"tool_use_end\", name: activeTool.name }\n try {\n const input = JSON.parse(activeTool.json || \"{}\") as any\n if (activeTool.name === \"create_files\" && input) {\n if (Array.isArray(input.files)) {\n files.push(...(input.files as GeneratedFile[]))\n }\n if (typeof input.summary === \"string\" && input.summary.trim()) {\n content += `\\n${input.summary}`\n }\n }\n if (activeTool.name === \"ask_user\" && input) {\n if (typeof input.question === \"string\" && input.question.trim()) {\n followUp = input.question\n if (Array.isArray(input.options) && input.options.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n } catch {\n // Ignore invalid tool JSON\n } finally {\n activeTool = null\n }\n }\n }\n if (event.type === \"message_delta\" && event.usage) {\n tokensUsed = (event.usage.input_tokens || 0) + (event.usage.output_tokens || 0)\n }\n } catch {\n // Skip\n }\n }\n }\n } finally {\n reader.releaseLock()\n }\n\n // Flush any trailing tool input.\n if (activeTool) {\n yield { type: \"tool_use_end\", name: activeTool.name }\n try {\n const input = JSON.parse(activeTool.json || \"{}\") as any\n if (activeTool.name === \"create_files\" && input) {\n if (Array.isArray(input.files)) {\n files.push(...(input.files as GeneratedFile[]))\n }\n if (typeof input.summary === \"string\" && input.summary.trim()) {\n content += `\\n${input.summary}`\n }\n }\n if (activeTool.name === \"ask_user\" && input) {\n if (typeof input.question === \"string\" && input.question.trim()) {\n followUp = input.question\n if (Array.isArray(input.options) && input.options.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n } catch {\n // Ignore\n }\n activeTool = null\n }\n\n // If the model didn't use tools (or we couldn't parse them), fall back to fenced-code extraction.\n if (files.length === 0) {\n files.push(...this.extractFilesFromText(content))\n }\n if (!followUp && files.length === 0) {\n followUp = this.inferFollowUpFromText(content)\n }\n yield {\n type: \"done\",\n result: { content, files, followUp, tokensUsed },\n }\n }\n\n /**\n * Parse JSON output from the `claude` CLI.\n */\n private parseCliOutput(stdout: string): GenerationResult {\n let parsed: any\n try {\n parsed = JSON.parse(stdout)\n } catch {\n // CLI returned plain text\n const inferred = this.inferFollowUpFromText(stdout.trim())\n return {\n content: stdout.trim(),\n files: [],\n followUp: inferred,\n tokensUsed: 0,\n }\n }\n\n // Claude CLI JSON format: { result: \"...\", session_id: \"...\", ... }\n const text = parsed.result || parsed.text || parsed.content || \"\"\n\n // Extract files from the text if it contains code blocks with file paths\n const files = this.extractFilesFromText(text)\n const followUp = files.length === 0 ? this.inferFollowUpFromText(text) : undefined\n\n return {\n content: text,\n files,\n followUp,\n tokensUsed: parsed.usage\n ? (parsed.usage.input_tokens || 0) + (parsed.usage.output_tokens || 0)\n : 0,\n }\n }\n\n /**\n * Extract file blocks from CLI text output.\n * Looks for patterns like: ```path/to/file.ts ... ```\n */\n private extractFilesFromText(text: string): GeneratedFile[] {\n const files: GeneratedFile[] = []\n // Match fenced code blocks with a file path hint on the opening line\n const pattern = /```[\\w]*\\s*([\\w/._-]+\\.\\w+)\\n([\\s\\S]*?)```/g\n let match: RegExpExecArray | null\n while ((match = pattern.exec(text)) !== null) {\n const filePath = match[1]\n const content = match[2]\n if (filePath && content) {\n files.push({ path: filePath, content: content.trimEnd() })\n }\n }\n return files\n }\n\n /**\n * Claude CLI (OAuth/subscription) doesn't always emit structured ask_user tool blocks.\n * When it's obviously asking for clarification, infer a follow-up question from the tail.\n */\n private inferFollowUpFromText(text: string): string | undefined {\n const cleaned = (text || \"\").trim()\n if (!cleaned) return undefined\n\n // If it looks like it produced file blocks, don't treat it as a follow-up.\n if (cleaned.includes(\"```\")) return undefined\n\n const lines = cleaned.replace(/\\r\\n/g, \"\\n\").split(\"\\n\")\n const tail = lines.slice(Math.max(0, lines.length - 20))\n\n const tailText = tail.join(\"\\n\")\n const looksLikePlanApproval =\n /\\b(plan|proposal)\\b/i.test(tailText) &&\n /(ready for your review|review (the )?plan|requesting plan approval|awaiting approval|waiting for (your )?approval|approve (the )?plan|approval to proceed)/i.test(\n tailText\n )\n\n if (looksLikePlanApproval) {\n return (\n \"The provider is requesting plan approval.\\n\" +\n \"Reply with:\\n\" +\n \"- approve\\n\" +\n \"- revise: <what to change>\\n\" +\n \"- cancel\"\n )\n }\n\n const isIntro = (l: string) =>\n /^(question|clarification|clarify|i need|need more|before i proceed|to proceed|please (confirm|clarify)|which|what|where|when|how|do you)/i.test(\n l.trim()\n )\n\n // Find the last strong candidate line.\n let startIdx = -1\n for (let i = tail.length - 1; i >= 0; i--) {\n const l = tail[i].trim()\n if (!l) continue\n if (isIntro(l) || l.includes(\"?\")) {\n startIdx = i\n break\n }\n }\n if (startIdx === -1) return undefined\n\n // Collect the question + a small option/list block that follows it.\n const out: string[] = []\n for (let i = startIdx; i < tail.length && out.length < 8; i++) {\n const l = tail[i]\n const t = l.trim()\n if (out.length > 0 && !t) break\n\n if (\n out.length > 0 &&\n !/^(options?:|[-*]\\s|\\d+[\\).]\\s)/i.test(t) &&\n !t.includes(\"?\")\n ) {\n break\n }\n\n out.push(l.trimEnd())\n }\n\n const candidate = out.join(\"\\n\").trim()\n if (candidate.length < 5) return undefined\n if (candidate.length > 800) return candidate.slice(0, 800).trimEnd()\n return candidate\n }\n\n /**\n * Parse Anthropic API response (tool-use format).\n */\n private parseApiResponse(response: AnthropicResponse): GenerationResult {\n const files: GeneratedFile[] = []\n let content = \"\"\n let followUp: string | undefined\n\n for (const block of response.content) {\n if (block.type === \"text\") {\n content += block.text || \"\"\n }\n\n if (block.type === \"tool_use\") {\n if (block.name === \"create_files\" && block.input) {\n const input = block.input as {\n files: GeneratedFile[]\n summary?: string\n }\n files.push(...(input.files || []))\n if (input.summary) {\n content += `\\n${input.summary}`\n }\n }\n\n if (block.name === \"ask_user\" && block.input) {\n const input = block.input as { question: string; options?: string[] }\n followUp = input.question\n if (input.options?.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n }\n\n return {\n content,\n files,\n followUp,\n tokensUsed: response.usage.input_tokens + response.usage.output_tokens,\n }\n }\n}\n","import type { AgentProvider } from \"./types\"\nimport { ClaudeProvider } from \"./claude\"\nimport { ClaudeCodeProvider } from \"./claude-code\"\nimport { loadAuthConfig } from \"@/utils/auth-store\"\n\nexport type ProviderName = \"claude-code\" | \"claude\" | \"openai\" | \"ollama\" | \"custom\"\n\nexport function createProvider(\n name: ProviderName = \"claude-code\",\n apiKey?: string\n): AgentProvider {\n // Auto-detect provider from stored config when using the default\n let resolvedName = name\n if (name === \"claude-code\" && !apiKey) {\n const stored = loadAuthConfig()\n if (stored) {\n resolvedName = stored.provider\n }\n }\n\n switch (resolvedName) {\n case \"claude-code\":\n return new ClaudeCodeProvider()\n case \"claude\":\n return new ClaudeProvider(apiKey)\n case \"openai\":\n throw new Error(\n \"OpenAI provider coming soon. Set provider to 'claude-code' or contribute at github.com/anis-marrouchi/agentx\"\n )\n case \"ollama\":\n throw new Error(\n \"Ollama provider coming soon. Set provider to 'claude-code' or contribute at github.com/anis-marrouchi/agentx\"\n )\n default:\n throw new Error(`Unknown provider: ${resolvedName}. Supported: claude-code, claude`)\n }\n}\n\nexport { ClaudeProvider } from \"./claude\"\nexport { ClaudeCodeProvider } from \"./claude-code\"\nexport type {\n AgentProvider,\n GenerationMessage,\n GenerationResult,\n GeneratedFile,\n ProviderOptions,\n StreamEvent,\n AnthropicMessage,\n ContentBlock,\n RawGenerationResult,\n} from \"./types\"\n"],"mappings":"+CASA,IAAMA,EAAqC,CACzC,CACE,KAAM,eACN,YACE,6HACF,aAAc,CACZ,KAAM,SACN,WAAY,CACV,MAAO,CACL,KAAM,QACN,MAAO,CACL,KAAM,SACN,WAAY,CACV,KAAM,CACJ,KAAM,SACN,YACE,wEACJ,EACA,QAAS,CACP,KAAM,SACN,YAAa,8BACf,EACA,SAAU,CACR,KAAM,SACN,YAAa,mCACf,EACA,YAAa,CACX,KAAM,SACN,YAAa,0CACf,CACF,EACA,SAAU,CAAC,OAAQ,SAAS,CAC9B,CACF,EACA,QAAS,CACP,KAAM,SACN,YAAa,sCACf,CACF,EACA,SAAU,CAAC,OAAO,CACpB,EACA,WAAY,YACd,EACA,CACE,KAAM,WACN,YACE,mKACF,aAAc,CACZ,KAAM,SACN,WAAY,CACV,SAAU,CACR,KAAM,SACN,YAAa,8BACf,EACA,QAAS,CACP,KAAM,QACN,MAAO,CAAE,KAAM,QAAS,EACxB,YAAa,uCACf,CACF,EACA,SAAU,CAAC,UAAU,CACvB,EACA,WAAY,MACd,EACA,CACE,KAAM,YACN,YACE,wJACF,aAAc,CACZ,KAAM,SACN,WAAY,CACV,KAAM,CACJ,KAAM,SACN,YAAa,sCACf,EACA,UAAW,CACT,KAAM,SACN,YACE,wEACJ,CACF,EACA,SAAU,CAAC,MAAM,CACnB,EACA,WAAY,WACd,EACA,CACE,KAAM,eACN,YACE,mLACF,aAAc,CACZ,KAAM,SACN,WAAY,CACV,QAAS,CACP,KAAM,SACN,YACE,6DACJ,EACA,cAAe,CACb,KAAM,SACN,YACE,wEACJ,EACA,YAAa,CACX,KAAM,SACN,YAAa,mDACf,CACF,EACA,SAAU,CAAC,SAAS,CACtB,EACA,WAAY,MACd,EACA,CACE,KAAM,iBACN,YACE,qFACF,aAAc,CACZ,KAAM,SACN,WAAY,CACV,KAAM,CACJ,KAAM,SACN,YACE,oEACJ,EACA,UAAW,CACT,KAAM,UACN,YAAa,mCACf,EACA,UAAW,CACT,KAAM,SACN,YAAa,kDACf,CACF,CACF,EACA,WAAY,MACd,EACA,CACE,KAAM,cACN,YACE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AKM,EAAM,WAI1B,GAAInC,EAAM,OAAS,YAAcA,EAAM,MAAO,CAC5C,IAAMmC,EAAQnC,EAAM,MACpB0B,EAAWS,EAAM,SACbA,EAAM,SAAS,SACjBT,GAAY;AAAA,WAAcS,EAAM,QAAQ,KAAK,IAAI,MAMzD,MAAO,CACL,QAAAN,EACA,MAAAJ,EACA,SAAAC,EACA,WAAY3B,EAAS,MAAM,aAAeA,EAAS,MAAM,aAC3D,CACF,CACF,EC/uBO,SAASsD,GACdC,EAAqB,cACrBC,EACe,CAEf,IAAIC,EAAeF,EACnB,GAAIA,IAAS,eAAiB,CAACC,EAAQ,CACrC,IAAME,EAASC,EAAe,EAC1BD,IACFD,EAAeC,EAAO,UAI1B,OAAQD,EAAc,CACpB,IAAK,cACH,OAAO,IAAIG,EACb,IAAK,SACH,OAAO,IAAIC,EAAeL,CAAM,EAClC,IAAK,SACH,MAAM,IAAI,MACR,8GACF,EACF,IAAK,SACH,MAAM,IAAI,MACR,8GACF,EACF,QACE,MAAM,IAAI,MAAM,qBAAqBC,mCAA8C,CACvF,CACF","names":["TOOL_DEFINITIONS","getAnthropicTools","enabledTools","t","name","description","input_schema","getLegacyTools","formatToolsForSystemPrompt","agenticTools","lines","tool","ALL_TOOL_NAMES","DEFAULT_MODEL","DEFAULT_MAX_TOKENS","ClaudeProvider","apiKey","resolved","resolveToken","messages","options","model","maxTokens","systemMsg","m","conversationMsgs","body","getLegacyTools","response","systemPrompt","tools","block","headers","res","errorText","reader","decoder","buffer","files","content","followUp","tokensUsed","activeTool","inferFollowUpFromText","text","cleaned","lines","tail","tailText","isIntro","l","startIdx","i","out","t","candidate","done","value","line","data","event","input","execa","DEFAULT_MODEL","DEFAULT_MAX_TOKENS","CLI_MODEL_ALIASES","ClaudeCodeProvider","stored","loadAuthConfig","resolved","resolveToken","messages","options","systemPrompt","tools","model","maxTokens","body","headers","res","errorText","response","block","cliModel","systemMsg","m","prompt","args","env","result","execa","err","output","json","e","conversationMsgs","getLegacyTools","child","fullContent","stderr","fatalError","chunk","decoder","readable","lines","line","event","files","followUp","reader","buffer","content","tokensUsed","activeTool","done","value","data","input","stdout","parsed","inferred","text","pattern","match","filePath","cleaned","tail","tailText","isIntro","l","startIdx","i","out","t","candidate","createProvider","name","apiKey","resolvedName","stored","loadAuthConfig","ClaudeCodeProvider","ClaudeProvider"]}
|
package/dist/chunk-WT2UJMBC.js
DELETED
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
import{i as be,j as ke}from"./chunk-Z4GC5D6D.js";import{b as H}from"./chunk-4YCH6IZV.js";var B=class{baseUrl;token;constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.token=t}async getAgentCard(){let e=await fetch(`${this.baseUrl}/.well-known/agent-card.json`,{headers:this.headers()});if(!e.ok)throw new Error(`Failed to fetch agent card: ${e.status}`);return e.json()}async sendTask(e,t){let n=await this.rpc("tasks/send",{id:`task-${Date.now().toString(36)}`,message:{role:"user",parts:[{type:"text",text:e}]},metadata:t});if(n.error)throw new Error(`A2A error: ${n.error.message}`);return n.result}async*sendTaskStream(e,t){let n=JSON.stringify({jsonrpc:"2.0",id:1,method:"tasks/sendSubscribe",params:{id:`task-${Date.now().toString(36)}`,message:{role:"user",parts:[{type:"text",text:e}]},metadata:t}}),s=await fetch(this.baseUrl,{method:"POST",headers:{...this.headers(),"Content-Type":"application/json",Accept:"text/event-stream"},body:n});if(!s.ok||!s.body)throw new Error(`A2A stream error: ${s.status}`);let r=s.body.getReader(),i=new TextDecoder,a="";for(;;){let{done:o,value:g}=await r.read();if(o)break;a+=i.decode(g,{stream:!0});let l=a.split(`
|
|
2
|
-
`);a=l.pop()||"";for(let d of l)if(d.startsWith("data: "))try{let f=JSON.parse(d.slice(6));yield{state:f.state,message:f.message?.parts?.[0]?.text,final:f.final}}catch{}}}async getTask(e){let t=await this.rpc("tasks/get",{id:e});if(t.error)throw new Error(`A2A error: ${t.error.message}`);return t.result}async cancelTask(e){let t=await this.rpc("tasks/cancel",{id:e});if(t.error)throw new Error(`A2A error: ${t.error.message}`);return t.result}async rpc(e,t){let n=await fetch(this.baseUrl,{method:"POST",headers:{...this.headers(),"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:e,params:t})});if(!n.ok)throw new Error(`A2A HTTP error: ${n.status}`);return n.json()}headers(){let e={};return this.token&&(e.Authorization=`Bearer ${this.token}`),e}};var U=class{peers=new Map;healthTimer;config;log;constructor(e,t=console.error.bind(console,"[mesh]")){this.config=e,this.log=t;for(let n of e.mesh.peers)this.peers.set(n.name,{peer:n,client:new B(n.url,n.token),healthy:!1,agents:[]})}async start(){this.log(`Mesh starting with ${this.peers.size} peer(s)`),await this.discoverAll();let e=this.config.mesh.healthCheck.interval*1e3;this.healthTimer=setInterval(()=>this.discoverAll(),e)}async stop(){this.healthTimer&&clearInterval(this.healthTimer)}async discoverAll(){let e=await Promise.allSettled(Array.from(this.peers.entries()).map(([n,s])=>this.discoverPeer(n,s))),t=Array.from(this.peers.values()).filter(n=>n.healthy).length;this.log(`Discovery complete: ${t}/${this.peers.size} peers healthy`)}async discoverPeer(e,t){let n=this.config.mesh.healthCheck.timeout*1e3;try{let s=new AbortController,r=setTimeout(()=>s.abort(),n),i=await t.client.getAgentCard();clearTimeout(r),t.healthy=!0,t.lastCheck=new Date,t.agentCard=i,t.agents=i.skills||[],this.log(`Peer "${e}" healthy: ${i.name} (${t.agents.length} skills)`)}catch(s){t.healthy=!1,t.lastCheck=new Date,this.log(`Peer "${e}" unreachable: ${s.message}`)}}async sendTask(e,t,n){let s=this.peers.get(e);if(!s)throw new Error(`Unknown peer: ${e}`);if(!s.healthy)throw new Error(`Peer "${e}" is not healthy`);let r=n||s.agents[0]?.id;if(!r)throw new Error(`Peer "${e}" has no agents`);let i=`${s.peer.url}/task`,a={"Content-Type":"application/json"};s.peer.token&&(a.Authorization=`Bearer ${s.peer.token}`);let o=await fetch(i,{method:"POST",headers:a,body:JSON.stringify({agent:r,message:t})});if(!o.ok)throw new Error(`Peer "${e}" /task error: ${o.status}`);let g=await o.json();if(g.error)throw new Error(`Peer "${e}" agent error: ${g.error}`);return g.content||"No response"}findPeerWithSkill(e){for(let t of this.peers.values())if(t.healthy&&t.agents.some(n=>n.id===e))return t}directory(){return Array.from(this.peers.entries()).map(([e,t])=>({peer:e,peerUrl:t.peer.url,healthy:t.healthy,skills:t.agents,lastCheck:t.lastCheck}))}};import{z as h}from"zod";import{readFileSync as ve,existsSync as G}from"fs";import{resolve as J}from"path";function Ge(c){let e=J(c,".env");if(!G(e))return;let t=ve(e,"utf-8");for(let n of t.split(`
|
|
3
|
-
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r===-1)continue;let i=s.slice(0,r).trim(),a=s.slice(r+1).trim();process.env[i]||(process.env[i]=a)}}var Je=h.object({apiKey:h.string().optional(),defaultModel:h.string().optional(),baseUrl:h.string().optional()}),Fe=h.object({name:h.string(),workspace:h.string(),tier:h.enum(["claude-code","sdk","orchestrator"]).default("claude-code"),provider:h.string().optional(),model:h.string().optional(),systemPrompt:h.string().optional(),mentions:h.array(h.string()).default([]),maxConcurrent:h.number().default(1),permissionMode:h.string().default("default")}),Ke=h.object({token:h.string(),agentBinding:h.string()}),ze=h.object({telegram:h.object({enabled:h.boolean().default(!1),accounts:h.record(h.string(),Ke).default({}),policy:h.object({dm:h.enum(["pair","block"]).default("pair"),group:h.enum(["mention-required","all"]).default("mention-required")}).default({})}).default({}),whatsapp:h.object({enabled:h.boolean().default(!1),sessionDir:h.string().default(".agentx/whatsapp-sessions"),defaultAgent:h.string().optional(),allowFrom:h.array(h.string()).optional(),routes:h.array(h.object({contact:h.string().optional(),group:h.string().optional(),agent:h.string()})).default([])}).default({}),discord:h.object({enabled:h.boolean().default(!1),token:h.string().optional(),agentBinding:h.string().optional()}).default({}),gitlab:h.object({enabled:h.boolean().default(!1),webhookPort:h.number().default(18810),webhookSecret:h.string().optional(),host:h.string().default("https://gitlab.com"),token:h.string().optional(),routes:h.array(h.object({project:h.string(),agent:h.string()})).default([]),agentMappings:h.array(h.object({agentId:h.string(),gitlabUsernames:h.array(h.string()).default([]),keywords:h.array(h.string()).default([])})).default([])}).default({})}),qe=h.object({enabled:h.boolean().default(!0),schedule:h.string(),timezone:h.string().default("UTC"),agent:h.string(),prompt:h.string(),timeout:h.number().default(600),model:h.string().optional(),onError:h.enum(["log","notify","disable"]).default("log")}),Ve=h.object({url:h.string(),name:h.string(),token:h.string().optional()}),Xe=h.object({enabled:h.boolean().default(!1),peers:h.array(Ve).default([]),discovery:h.enum(["static","mdns"]).default("static"),healthCheck:h.object({interval:h.number().default(60),timeout:h.number().default(10)}).default({})}),Qe=h.object({node:h.object({id:h.string(),name:h.string(),bind:h.string().default("127.0.0.1:18800")}),providers:h.record(h.string(),Je).default({}),agents:h.record(h.string(),Fe).default({}),channels:ze.default({}),crons:h.record(h.string(),qe).default({}),mesh:Xe.default({})});function he(c){if(typeof c=="string")return c.replace(/\$\{(\w+)\}/g,(e,t)=>process.env[t]||"");if(Array.isArray(c))return c.map(he);if(c!==null&&typeof c=="object"){let e={};for(let[t,n]of Object.entries(c))e[t]=he(n);return e}return c}function $e(c){let e=c?[c]:[J(process.cwd(),"agentx.json"),J(process.cwd(),".agentx/config.json")];Ge(process.cwd());let t,n;for(let a of e)if(G(a)){t=ve(a,"utf-8"),n=a;break}if(!t||!n)throw new Error(`No config found. Create agentx.json or .agentx/config.json
|
|
4
|
-
Searched: ${e.join(", ")}`);let s;try{s=JSON.parse(t)}catch(a){throw new Error(`Invalid JSON in ${n}: ${a.message}`)}let r=he(s),i=Qe.safeParse(r);if(!i.success){let a=i.error.issues.map(o=>` ${o.path.join(".")}: ${o.message}`).join(`
|
|
5
|
-
`);throw new Error(`Config validation failed (${n}):
|
|
6
|
-
${a}`)}return i.data}function xe(c){let e=[];for(let[t,n]of Object.entries(c.agents)){if(!G(n.workspace)){e.push(`Agent "${t}": workspace not found at ${n.workspace}`);continue}if(n.tier==="claude-code"){let i=J(n.workspace,".claude");G(i)||e.push(`Agent "${t}": no .claude/ directory in workspace ${n.workspace}. Claude Code native features (hooks, MCP, skills) won't be available.`)}let s=n.provider||"claude",r=c.providers[s];n.tier!=="claude-code"&&(!r||!r.apiKey)&&e.push(`Agent "${t}": provider "${s}" has no API key configured. Set providers.${s}.apiKey in config or use tier "claude-code" for subscription.`)}for(let[t,n]of Object.entries(c.crons))c.agents[n.agent]||e.push(`Cron "${t}": references unknown agent "${n.agent}"`);if(c.channels.telegram.enabled)for(let[t,n]of Object.entries(c.channels.telegram.accounts))c.agents[n.agentBinding]||e.push(`Telegram account "${t}": references unknown agent "${n.agentBinding}"`);return e}import{execa as Ye}from"execa";import{execFile as Ze}from"child_process";function Ae(c,e,t){let n=[];if(c.systemPrompt&&n.push(c.systemPrompt),e.context){let s=e.context,r=["","[Environment]"],i=s.channel==="gitlab"||s.channel?.startsWith("webhook:"),a=s.channel==="telegram";if(s.channel&&r.push(`Channel: ${s.channel}`),s.group&&r.push(`Group: ${s.group}`),s.sender&&r.push(`Message from: ${s.sender}`),s.myHandle&&r.push(`Your handle on this channel: ${s.myHandle}`),i&&(r.push(""),r.push("[IMPORTANT: You are responding to a GitLab comment/event]"),r.push("- Reply with a focused, actionable GitLab comment"),r.push("- Use markdown (GitLab flavored) for formatting"),r.push("- Do NOT mention Telegram handles (@noqta_*) \u2014 they don't work on GitLab"),r.push("- Do NOT try to delegate to other agents \u2014 reply directly"),r.push("- Reference issues with #IID and MRs with !IID")),a&&s.peers?.length){r.push(""),r.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let o of s.peers){let g=o.handle?` (mention: ${o.handle})`:"",l=o.role?` \u2014 ${o.role}`:"";r.push(`\u2022 ${o.name}${g}${l}`)}r.push(""),r.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}n.push(r.join(`
|
|
7
|
-
`))}return e.context?.replyToText&&(n.push(""),n.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(n.push(""),n.push(`[Attached file: ${e.context.mediaPath}]`),n.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?n.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?n.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?n.push("A video file is attached. Describe what you can determine about it."):n.push("Please read this file and respond based on its content.")),t&&(n.push(""),n.push(t)),n.push(""),n.push(e.message),n.join(`
|
|
8
|
-
`)}function Se(c,e,t,n){let s=["-p",e,"--output-format",t?"stream-json":"json"];return t&&s.push("--verbose"),n&&s.push("--resume",n),c.model&&s.push("--model",c.model),c.permissionMode==="bypassPermissions"&&s.push("--dangerously-skip-permissions"),s}function et(c){try{let e=JSON.parse(c);return{text:e.result||e.content||"",sessionId:e.session_id}}catch{return{text:c}}}async function tt(c,e,t,n){let s=Date.now(),r=Ae(c,e,n?void 0:t),i=Se(c,r,!1,n);try{let{stdout:a,stderr:o,exitCode:g}=await new Promise((d,f)=>{let p=Ze("claude",i,{cwd:c.workspace,timeout:6e5,maxBuffer:10485760,env:{...process.env,HOME:process.env.HOME||"/home/"+(process.env.USER||"clawd")}},(y,u,m)=>{d({stdout:u||"",stderr:m||"",exitCode:y?y.code??1:0})})});if(!a&&g!==0)return{content:"",error:(o?.trim()||`Claude Code exited with code ${g}`).slice(0,300),duration:Date.now()-s};let l=et(a);return{content:l.text,duration:Date.now()-s,claudeSessionId:l.sessionId}}catch(a){return console.error(`[runtime] execFile threw: ${a.message}`),{content:"",error:a.message||"Claude Code failed",duration:Date.now()-s}}}async function nt(c,e,t,n,s){let r=Date.now(),i=Ae(c,e,s?void 0:n),a=Se(c,i,!0,s),o="";try{let g=Ye("claude",a,{cwd:c.workspace,timeout:6e5,reject:!1,env:process.env,buffer:!1});if(g.stdout){let d="";g.stdout.on("data",f=>{d+=f.toString();let p=d.split(`
|
|
9
|
-
`);d=p.pop()||"";for(let y of p)if(y.trim())try{let u=JSON.parse(y);if(u.type==="assistant"&&u.message?.content){for(let m of u.message.content)if(m.type==="text"&&m.text){let b=m.text.slice(o.length);b&&(o=m.text,t(b,o))}}if(u.type==="content_block_delta"&&u.delta?.text&&(o+=u.delta.text,t(u.delta.text,o)),u.type==="result"&&u.result){let m=(typeof u.result=="string",u.result);if(typeof m=="string"&&m.length>o.length){let b=m.slice(o.length);o=m,b&&t(b,o)}}}catch{y.trim()&&!y.startsWith("{")&&(o+=y+`
|
|
10
|
-
`,t(y+`
|
|
11
|
-
`,o))}})}let l=await g;return!o&&l.stdout&&(o=typeof l.stdout=="string"?l.stdout:""),l.exitCode!==0&&!o?{content:"",error:(typeof l.stderr=="string"?l.stderr:"")||`Claude Code exited with code ${l.exitCode}`,duration:Date.now()-r}:{content:o,duration:Date.now()-r}}catch(g){return{content:o||"",error:g.message,duration:Date.now()-r}}}async function st(c,e,t){let n=Date.now();try{let s=await import("@anthropic-ai/claude-agent-sdk"),{query:r}=s,i=c.systemPrompt?`${c.systemPrompt}
|
|
12
|
-
|
|
13
|
-
${e.message}`:e.message,a="",o=r({prompt:i,options:{model:c.model,cwd:c.workspace,permissionMode:"bypassPermissions"}});for await(let g of o)g.type==="result"&&g.subtype==="success"&&(a=g.result||"");return{content:a,duration:Date.now()-n}}catch(s){return{content:"",error:`SDK error: ${s.message}`,duration:Date.now()-n}}}async function rt(c,e,t){let n=Date.now();try{let{generate:s}=await import("./agent-K2YOEOJ5.js"),r=c.provider||"claude-code",i=await s({task:e.message,cwd:c.workspace,provider:r,model:c.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1});return{content:i.content||"Done.",tokensUsed:i.tokensUsed,duration:Date.now()-n}}catch(s){return{content:"",error:`Orchestrator error: ${s.message}`,duration:Date.now()-n}}}async function Te(c,e,t,n,s,r){switch(c.tier){case"claude-code":return n?nt(c,e,n,s,r):tt(c,e,s,r);case"sdk":{let i=c.provider||"claude",a=t[i]?.apiKey;return a?st(c,e,a):{content:"",error:`No API key for provider "${i}". Configure providers.${i}.apiKey`}}case"orchestrator":{let i=c.provider||"claude-code",a=t[i]?.apiKey;return rt(c,e,a)}default:return{content:"",error:`Unknown tier: ${c.tier}`}}}import{readFileSync as Ce,writeFileSync as F,existsSync as K,mkdirSync as de,readdirSync as ue,statSync as it}from"fs";import{resolve as C,join as ot,relative as z,dirname as at}from"path";var R=class{baseDir;rawDir;log;constructor(e=C(process.cwd(),".agentx/wiki"),t=console.error.bind(console,"[wiki]")){this.baseDir=e,this.rawDir=C(e,"raw/entries"),this.log=t,de(this.rawDir,{recursive:!0}),de(C(e,"raw"),{recursive:!0})}canRead(e,t){return!!(e.access==="public"||e.owner===t||e.access==="shared"&&e.sharedWith?.includes(t))}canWrite(e,t){return e.owner===t}addEntry(e){let t=`${e.date}_${e.id}.md`,n=C(this.rawDir,t),s=["---",`id: ${e.id}`,`date: ${e.date}`,`agent: ${e.agentId}`,`source: ${e.source}`];if(e.sourceContext&&s.push(`context: ${e.sourceContext}`),e.meta)for(let[r,i]of Object.entries(e.meta))s.push(`${r}: ${JSON.stringify(i)}`);return s.push("---","",e.content),F(n,s.join(`
|
|
14
|
-
`)),t}listEntries(e){if(!K(this.rawDir))return[];let t=ue(this.rawDir).filter(s=>s.endsWith(".md")).sort(),n=[];for(let s of t){let r=Ce(C(this.rawDir,s),"utf-8"),i=this.parseEntry(r,s);i&&(e?.agentId&&i.agentId!==e.agentId||e?.after&&i.date<e.after||e?.before&&i.date>e.before||n.push(i))}return n}parseEntry(e,t){let n=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!n)return null;let s=n[1],r=n[2].trim(),i=a=>s.match(new RegExp(`^${a}:\\s*(.+)$`,"m"))?.[1]?.trim()||"";return{id:i("id")||t.replace(".md",""),date:i("date"),agentId:i("agent"),source:i("source"),sourceContext:i("context")||void 0,content:r}}writeArticle(e,t,n,s){let r=this.readArticle(e);if(r&&!this.canWrite(r.meta,s))return this.log(`Permission denied: "${s}" cannot write "${e}" (owner: ${r.meta.owner})`),!1;let i=C(this.baseDir,e);de(at(i),{recursive:!0});let a=["---",`title: "${t.title}"`,`type: ${t.type}`,`owner: ${t.owner}`,`access: ${t.access}`];return t.sharedWith?.length&&a.push(`shared_with: [${t.sharedWith.map(o=>`"${o}"`).join(", ")}]`),a.push(`created: ${t.created}`,`last_updated: ${t.lastUpdated}`,`related: [${t.related.map(o=>`"${o}"`).join(", ")}]`,`sources: [${t.sources.map(o=>`"${o}"`).join(", ")}]`),t.tags?.length&&a.push(`tags: [${t.tags.map(o=>`"${o}"`).join(", ")}]`),a.push("---","",n),F(i,a.join(`
|
|
15
|
-
`)),!0}readArticle(e){let t=C(this.baseDir,e);if(!K(t))return null;let n=Ce(t,"utf-8");return this.parseArticle(n,e)}readArticleAs(e,t){let n=this.readArticle(e);return!n||!this.canRead(n.meta,t)?null:n}parseArticle(e,t){let n=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!n)return null;let s=n[1],r=n[2].trim(),i=o=>s.match(new RegExp(`^${o}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",a=o=>{let g=s.match(new RegExp(`^${o}:\\s*\\[(.*)\\]$`,"m"));return g?g[1].split(",").map(l=>l.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[]};return{meta:{title:i("title"),type:i("type"),owner:i("owner"),access:i("access")||"public",sharedWith:a("shared_with"),created:i("created"),lastUpdated:i("last_updated"),related:a("related"),sources:a("sources"),tags:a("tags")},content:r,path:t}}listArticles(e){let t=[];return this.walkDir(this.baseDir,n=>{if(!n.endsWith(".md"))return;let s=z(this.baseDir,n);if(s.startsWith("raw/")||s.startsWith("_"))return;let r=this.readArticle(s);r&&this.canRead(r.meta,e)&&t.push(r)}),t}search(e,t,n=10){let s=e.toLowerCase(),r=[];return this.walkDir(this.baseDir,i=>{if(!i.endsWith(".md"))return;let a=z(this.baseDir,i);if(a.startsWith("raw/")||a.startsWith("_"))return;let o=this.readArticle(a);if(!o||!this.canRead(o.meta,t))return;let g=0,l=o.meta.title.toLowerCase(),d=o.content.toLowerCase();l.includes(s)&&(g+=10),o.meta.tags?.some(p=>p.toLowerCase().includes(s))&&(g+=5);let f=(d.match(new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"))||[]).length;g+=Math.min(f,5),g>0&&r.push({article:o,score:g})}),r.sort((i,a)=>a.score-i.score).slice(0,n).map(i=>i.article)}findRelevant(e,t,n=3){let s=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","can","shall","to","of","in","for","on","with","at","by","from","as","into","about","through","and","but","or","not","no","if","then","so","what","how","when","where","who","which","that","this","it","i","you","we","they","he","she","me","my","your","our","their","please","just","also","very","much","some","any","all"]),r=e.toLowerCase().replace(/[^a-z0-9\s@_-]/g," ").split(/\s+/).filter(a=>a.length>2&&!s.has(a));if(r.length===0)return[];let i=new Map;for(let a of r){let o=this.search(a,t,5);for(let g of o){let l=i.get(g.path);l?l.score+=1:i.set(g.path,{article:g,score:1})}}return Array.from(i.values()).sort((a,o)=>o.score-a.score).slice(0,n).map(a=>a.article)}buildContext(e,t=4e3){if(e.length===0)return"";let n=["[Wiki Knowledge]"],s=0;for(let r of e){let i=`
|
|
16
|
-
## ${r.meta.title} (${r.meta.type})`,a=r.content.length>600?r.content.slice(0,600)+"...":r.content,o=i+`
|
|
17
|
-
`+a;if(s+o.length>t)break;n.push(o),s+=o.length}return n.push(`
|
|
18
|
-
[End Wiki Knowledge]`),n.join(`
|
|
19
|
-
`)}rebuildIndex(){let e=[],t=new Map;this.walkDir(this.baseDir,i=>{if(!i.endsWith(".md"))return;let a=z(this.baseDir,i);if(a.startsWith("raw/")||a.startsWith("_"))return;let o=this.readArticle(a);if(!o)return;let g=o.content.match(/\[\[([^\]]+)\]\]/g)||[];for(let d of g){let f=d.replace(/\[\[|\]\]/g,"");t.set(f,(t.get(f)||0)+1)}let l=[o.meta.title.toLowerCase()];o.meta.tags&&l.push(...o.meta.tags.map(d=>d.toLowerCase())),e.push({path:a,title:o.meta.title,type:o.meta.type,owner:o.meta.owner,access:o.meta.access,sharedWith:o.meta.sharedWith,aliases:l,backlinks:t.get(o.meta.title)||0})});let n={articles:e,lastRebuilt:new Date().toISOString()};F(C(this.baseDir,"_index.json"),JSON.stringify(n,null,2));let s=["# Wiki Index","",`Last rebuilt: ${n.lastRebuilt}`,""],r=new Map;for(let i of e){let a=r.get(i.type)||[];a.push(i),r.set(i.type,a)}for(let[i,a]of Array.from(r.entries()).sort()){s.push(`## ${i}`,"");for(let o of a.sort((g,l)=>g.title.localeCompare(l.title))){let g=o.access==="private"?" (private)":o.access==="shared"?" (shared)":"";s.push(`- [${o.title}](${o.path})${g} \u2014 owner: ${o.owner}`)}s.push("")}return F(C(this.baseDir,"WIKI.md"),s.join(`
|
|
20
|
-
`)),this.log(`Index rebuilt: ${e.length} articles`),n}stats(){let e=0,t={},n={},s={};this.walkDir(this.baseDir,i=>{if(!i.endsWith(".md"))return;let a=z(this.baseDir,i);if(a.startsWith("raw/")||a.startsWith("_")||a==="WIKI.md")return;let o=this.readArticle(a);o&&(e++,t[o.meta.type]=(t[o.meta.type]||0)+1,n[o.meta.access]=(n[o.meta.access]||0)+1,s[o.meta.owner]=(s[o.meta.owner]||0)+1)});let r=K(this.rawDir)?ue(this.rawDir).filter(i=>i.endsWith(".md")).length:0;return{totalArticles:e,totalEntries:r,articlesByType:t,articlesByAccess:n,articlesByOwner:s}}walkDir(e,t){if(K(e))for(let n of ue(e)){let s=ot(e,n);it(s).isDirectory()?this.walkDir(s,t):t(s)}}};import{readFileSync as ct,writeFileSync as lt,mkdirSync as gt,existsSync as Me}from"fs";import{resolve as Ie}from"path";var ht=12e3,Pe=30,q=class{sessionsDir;cache=new Map;constructor(e=process.cwd()){this.sessionsDir=Ie(e,".agentx/sessions"),Me(this.sessionsDir)||gt(this.sessionsDir,{recursive:!0})}sessionKey(e,t,n){let s=new Date().toISOString().slice(0,10);return`${e}:${t}:${n}:${s}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return Ie(this.sessionsDir,`${t}.json`)}getSession(e,t,n){let s=this.sessionKey(e,t,n);if(this.cache.has(s))return this.cache.get(s);let r=this.sessionFile(s);if(Me(r))try{let o=JSON.parse(ct(r,"utf-8"));return this.cache.set(s,o),o}catch{}let i=new Date().toISOString().slice(0,10),a={id:s,agentId:e,channel:t,chatId:n,day:i,messages:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return this.cache.set(s,a),this.save(a),a}addUserMessage(e,t,n,s,r){let i=this.getSession(e,t,n);i.messages.push({role:"user",name:s,content:r,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i)}addAgentMessage(e,t,n,s){let r=this.getSession(e,t,n);r.messages.push({role:"agent",name:e,content:s,timestamp:new Date().toISOString()}),this.trim(r),r.updatedAt=new Date().toISOString(),this.save(r)}getClaudeSessionId(e,t,n){return this.getSession(e,t,n).claudeSessionId}setClaudeSessionId(e,t,n,s){let r=this.getSession(e,t,n);r.claudeSessionId=s,r.updatedAt=new Date().toISOString(),this.save(r)}buildHistoryContext(e,t,n){let s=this.getSession(e,t,n);if(s.messages.length===0)return"";let r=[`[Conversation history for today (${s.day})]`];for(let i of s.messages){let a=i.timestamp.slice(11,16);i.role==="user"?r.push(`[${a}] ${i.name||"User"}: ${i.content}`):r.push(`[${a}] ${i.name||"Agent"}: ${i.content}`)}return r.push("[End of history \u2014 respond to the latest message above]"),r.push(""),r.join(`
|
|
21
|
-
`)}trim(e){e.messages.length>Pe&&(e.messages=e.messages.slice(-Pe));let t=e.messages.reduce((n,s)=>n+s.content.length,0);for(;t>ht&&e.messages.length>2;){let n=e.messages.shift();t-=n.content.length}}save(e){try{let t=this.sessionFile(e.id);lt(t,JSON.stringify(e,null,2))}catch{}}};var V=class{windows=new Map;maxPerMinute;maxPerHour;constructor(e=10,t=100){this.maxPerMinute=e,this.maxPerHour=t}check(e){let t=Date.now(),n=this.windows.get(e)||[],s=t-36e5,r=n.filter(o=>o>s),i=t-6e4,a=r.filter(o=>o>i).length;return a>=this.maxPerMinute?{allowed:!1,reason:`Rate limit: ${a}/${this.maxPerMinute} per minute`}:r.length>=this.maxPerHour?{allowed:!1,reason:`Rate limit: ${r.length}/${this.maxPerHour} per hour`}:(r.push(t),this.windows.set(e,r),{allowed:!0})}usage(e){let t=Date.now(),n=this.windows.get(e)||[];return{lastMinute:n.filter(s=>s>t-6e4).length,lastHour:n.filter(s=>s>t-36e5).length}}};import{readFileSync as De,writeFileSync as dt,existsSync as Re,mkdirSync as ut}from"fs";import{resolve as _e}from"path";var X=class{dir;cache=null;constructor(e=_e(process.cwd(),".agentx/usage")){this.dir=e,ut(this.dir,{recursive:!0})}record(e,t,n,s,r){let i=this.today(),a=i.agents[e]||{tasks:0,estimatedTokens:0,totalDuration:0,errors:0};a.tasks++,a.totalDuration+=s,a.estimatedTokens+=Math.ceil((t+n)/4),r&&a.errors++,i.agents[e]=a,this.save(i)}today(){let e=new Date().toISOString().slice(0,10);if(this.cache?.date===e)return this.cache;let t=this.filePath(e);if(Re(t))try{return this.cache=JSON.parse(De(t,"utf-8")),this.cache}catch{}return this.cache={date:e,agents:{}},this.cache}getDate(e){let t=this.filePath(e);if(!Re(t))return null;try{return JSON.parse(De(t,"utf-8"))}catch{return null}}summary(e=7){let t=0,n=0,s=0,r={};for(let i=0;i<e;i++){let a=new Date(Date.now()-i*864e5).toISOString().slice(0,10),o=this.getDate(a);if(o)for(let[g,l]of Object.entries(o.agents)){t+=l.tasks,n+=l.estimatedTokens,s+=l.errors;let d=r[g]||{tasks:0,tokens:0,avgDuration:0,totalDuration:0};d.tasks+=l.tasks,d.tokens+=l.estimatedTokens,d.totalDuration+=l.totalDuration,d.avgDuration=d.totalDuration/d.tasks,r[g]=d}}return{totalTasks:t,totalTokens:n,totalErrors:s,byAgent:r}}filePath(e){return _e(this.dir,`${e}.json`)}save(e){try{dt(this.filePath(e.date),JSON.stringify(e,null,2))}catch{}}};var pt={totalBudget:4e3,layerBudgets:{channel:200,scope:200,identity:300,peers:400,intent:200,artifacts:500,history:1200,wiki:1e3}},je=4;function Le(c,e=pt){let t=mt(c,e);t.sort((i,a)=>i.priority-a.priority);let n=[],s=0,r=e.totalBudget*je;for(let i of t){if(!i.content)continue;let a=i.maxTokens*je,o=i.content.length>a?i.content.slice(0,a)+"...":i.content;if(s+o.length>r){let g=r-s;g>100&&n.push(o.slice(0,g)+"...");break}n.push(o),s+=o.length}return n.join(`
|
|
22
|
-
|
|
23
|
-
`)}function mt(c,e){let t=(a,o)=>e.layerBudgets?.[a]??o,n=[];n.push(ft(c,t("channel",200))),n.push(yt(c,t("scope",200))),c.systemPrompt&&n.push({name:"identity",priority:3,maxTokens:t("identity",300),content:c.systemPrompt.split(`
|
|
24
|
-
`)[0],tags:["identity",c.agentId]}),c.peers?.length&&kt(c.channel)&&n.push(wt(c,t("peers",400)));let s=bt(c.message);s.length&&n.push({name:"intent",priority:5,maxTokens:t("intent",200),content:`[Intent: ${s.join(", ")}]`,tags:s});let r=[];c.replyToText&&r.push(`[Replying to]: ${c.replyToText.slice(0,300)}`),c.mediaPath&&(r.push(`[Attached file: ${c.mediaPath}]`),r.push(`[File type: ${c.mediaType||"unknown"}]`),c.mediaType?.startsWith("image/")?r.push("Please view this image and respond to it."):c.mediaType?.startsWith("audio/")&&r.push("Please transcribe this audio and respond.")),c.issueMR&&r.push(`[${c.issueMR.type} #${c.issueMR.iid}: ${c.issueMR.title}]`),r.length&&n.push({name:"artifacts",priority:6,maxTokens:t("artifacts",500),content:r.join(`
|
|
25
|
-
`),tags:["artifacts",...c.mediaType?["media"]:[]]});let i=c.groupHistory||c.sessionHistory;return i&&n.push({name:"history",priority:7,maxTokens:t("history",1200),content:i,tags:["history","conversation"]}),c.wikiContext&&n.push({name:"wiki",priority:8,maxTokens:t("wiki",1e3),content:c.wikiContext,tags:["wiki","knowledge"]}),n}function ft(c,e){let t=[`Channel: ${c.channel}`],n=[],s=[c.channel];switch(c.channel){case"telegram":c.agentHandle&&t.push(`Your handle: ${c.agentHandle}`),t.push(`From: ${c.sender}`),n.push("Format responses using Telegram-compatible markdown"),n.push("Keep responses concise for mobile reading");break;case"whatsapp":t.push(`From: ${c.sender}`),n.push("Keep responses concise \u2014 WhatsApp is mobile-first"),n.push("No rich formatting \u2014 plain text only");break;case"gitlab":t.push(`From: ${c.sender}`),n.push("Reply as a GitLab comment with GitLab-flavored markdown"),n.push("Do NOT mention Telegram handles (@noqta_*)"),n.push("Do NOT delegate to other agents"),n.push("Reference issues with #IID and merge requests with !IID"),n.push("Be specific and actionable \u2014 this is a code review context"),s.push("code-review");break;case"discord":t.push(`From: ${c.sender}`),n.push("Use Discord markdown for formatting");break;default:c.channel.startsWith("webhook:")&&(n.push("This is an automated event \u2014 respond with actionable steps"),s.push("webhook","automated"))}return n.length&&(t.push(""),t.push("[Rules]"),t.push(...n.map(r=>`- ${r}`))),{name:"channel",priority:1,maxTokens:e,content:t.join(`
|
|
26
|
-
`),tags:s,rules:n}}function yt(c,e){let t=[],n=[];return c.channelScope==="group"&&c.groupName?(t.push(`Group: ${c.groupName}`),n.push("group",c.groupName)):c.channelScope==="project"&&c.projectPath?(t.push(`Project: ${c.projectPath}`),n.push("project",c.projectPath)):c.channelScope==="personal"&&(t.push("Direct message"),n.push("dm")),{name:"scope",priority:2,maxTokens:e,content:t.join(`
|
|
27
|
-
`),tags:n}}function wt(c,e){let t=["[Team \u2014 mention to delegate]"];for(let n of c.peers||[]){let s=n.handle?` (${n.handle})`:"",r=n.role?` \u2014 ${n.role}`:"";t.push(`\u2022 ${n.name}${s}${r}`)}return t.push("Mention their handle to involve them."),{name:"peers",priority:4,maxTokens:e,content:t.join(`
|
|
28
|
-
`),tags:["peers","team"]}}function bt(c){let e=[],t=c.toLowerCase();return/deploy|push|release|ship/.test(t)&&e.push("deployment"),/review|check|look at|approve/.test(t)&&e.push("review"),/fix|bug|broken|error|issue/.test(t)&&e.push("bugfix"),/create|add|build|implement/.test(t)&&e.push("feature"),/test|spec|coverage/.test(t)&&e.push("testing"),/refactor|clean|improve/.test(t)&&e.push("refactor"),/docs|document|readme/.test(t)&&e.push("docs"),/security|vuln|auth|token/.test(t)&&e.push("security"),/perf|slow|optim|fast/.test(t)&&e.push("performance"),/status|update|progress|standup/.test(t)&&e.push("status"),/help|how|what|explain/.test(t)&&e.push("question"),/gitlab|merge|mr|issue|pipeline/.test(t)&&e.push("gitlab"),/seo|analytics|content|marketing/.test(t)&&e.push("marketing"),/infra|server|docker|k8s|devops/.test(t)&&e.push("devops"),e}function kt(c){return c==="telegram"}var Q=class{agents=new Map;config;providers={};sessions;wiki;rateLimiter;tokenTracker;log;constructor(e,t=console.error.bind(console,"[agents]")){this.log=t,this.config=e,this.providers=e.providers,this.sessions=new q,this.wiki=new R,this.rateLimiter=new V,this.tokenTracker=new X;for(let[n,s]of Object.entries(e.agents))this.agents.set(n,{id:n,def:s,activeTasks:0,totalTasks:0,errors:0})}getAgent(e){return this.agents.get(e)?.def}findByMention(e){let t=e.toLowerCase(),n,s=0;for(let[r,i]of this.agents)for(let a of i.def.mentions){let o=a.toLowerCase();t.includes(o)&&o.length>s&&(n=r,s=o.length)}return n}findAllMentioned(e){let t=e.toLowerCase(),n=[];for(let[s,r]of this.agents)for(let i of r.def.mentions)if(t.includes(i.toLowerCase())){n.push(s);break}return n}buildPeerList(e,t){let n=[];for(let[s,r]of this.agents)s!==e&&n.push({name:r.def.name,handle:this.getChannelHandle(s,t),role:r.def.systemPrompt?.split(`
|
|
29
|
-
`)[0]?.slice(0,80)});return n}getChannelHandle(e,t){let n=this.agents.get(e)?.def;if(n)return t==="telegram"?n.mentions.find(s=>s.startsWith("@")):n.mentions[0]}async execute(e,t){let n=this.agents.get(e.agentId);if(!n)return{content:"",error:`Unknown agent: ${e.agentId}`};if(n.activeTasks>=n.def.maxConcurrent)return{content:"",error:`Agent "${e.agentId}" is busy (${n.activeTasks}/${n.def.maxConcurrent} tasks)`};let s=this.rateLimiter.check(e.agentId);if(!s.allowed)return this.log(`[${e.agentId}] ${s.reason}`),{content:"",error:s.reason};n.activeTasks++,n.totalTasks++,n.lastActive=new Date,this.log(`[${e.agentId}] executing task (${n.activeTasks}/${n.def.maxConcurrent})`);let r=e.context?.channel||"api",i=e.context?.group||e.context?.sender||"default",a=e.context?.sender||"User";this.sessions.addUserMessage(e.agentId,r,i,a,e.message);let o=this.wiki.findRelevant(e.message,e.agentId,3),g=this.wiki.buildContext(o),l=n.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,r,i):void 0,d=l?void 0:this.sessions.buildHistoryContext(e.agentId,r,i),f=this.buildPeerList(e.agentId,r),p={channel:r,channelScope:e.context?.group?"group":r==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:n.def.name,agentHandle:this.getChannelHandle(e.agentId,r),systemPrompt:n.def.systemPrompt,sender:a,peers:f,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,groupHistory:(e.context?.group,void 0),sessionHistory:d,wikiContext:g,message:e.message},y=Le(p);try{let u=await Te(n.def,e,this.providers,t,y,l);if(u.error)n.errors++,this.log(`[${e.agentId}] error: ${u.error}`);else{if(this.sessions.addAgentMessage(e.agentId,r,i,u.content),u.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,r,i,u.claudeSessionId),u.content.length>50)try{let m=`${e.agentId}-${Date.now().toString(36)}`;this.wiki.addEntry({id:m,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:r,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
30
|
-
|
|
31
|
-
Agent: ${u.content}`})}catch{}this.tokenTracker.record(e.agentId,e.message.length,u.content.length,u.duration||0),this.log(`[${e.agentId}] completed in ${u.duration}ms`+(u.tokensUsed?` (${u.tokensUsed} tokens)`:""))}return u}catch(u){return n.errors++,this.log(`[${e.agentId}] unexpected error: ${u.message}`),{content:"",error:u.message}}finally{n.activeTasks--}}list(){return Array.from(this.agents.values()).map(e=>({id:e.id,name:e.def.name,tier:e.def.tier,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive}))}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}};import{readFileSync as vt,writeFileSync as $t,existsSync as xt,mkdirSync as At}from"fs";import{resolve as Ee}from"path";var St=30,Tt=6e3,Y=class{dir;cache=new Map;constructor(e=Ee(process.cwd(),".agentx/groups")){this.dir=e,At(this.dir,{recursive:!0})}add(e,t,n){let s=this.load(e);for(s.push({sender:t,text:n.slice(0,500),timestamp:Date.now()});s.length>St;)s.shift();this.cache.set(e,s),this.save(e,s)}buildContext(e){let t=this.load(e);if(t.length<=1)return"";let n=["[Recent group conversation]"],s=0;for(let r=t.length-2;r>=0;r--){let i=t[r],o=`[${new Date(i.timestamp).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1})}] ${i.sender}: ${i.text}`;if(s+o.length>Tt)break;n.splice(1,0,o),s+=o.length}return n.length<=1?"":(n.push("[End of conversation \u2014 respond to the latest message]"),n.join(`
|
|
32
|
-
`))}getEntries(e){return[...this.load(e)]}filePath(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Ee(this.dir,`${t}.json`)}load(e){if(this.cache.has(e))return this.cache.get(e);let t=this.filePath(e);if(!xt(t))return this.cache.set(e,[]),[];try{let n=JSON.parse(vt(t,"utf-8")),s=Array.isArray(n)?n:[];return this.cache.set(e,s),s}catch{return this.cache.set(e,[]),[]}}save(e,t){try{$t(this.filePath(e),JSON.stringify(t))}catch{}}};var Ct=1500,Mt=4e3,pe=class{registry;config;channels=new Map;hooks;mesh;groupLog;log;constructor(e,t,n,s=console.error.bind(console,"[router]")){this.registry=e,this.config=t,this.hooks=n,this.log=s,this.groupLog=new Y}setMesh(e){this.mesh=e}addChannel(e){this.channels.set(e.name,e),e.onMessage(t=>this.handleMessage(e,t))}async startAll(){for(let[e,t]of this.channels)this.log(`Starting channel: ${e}`),await t.start()}async stopAll(){for(let[e,t]of this.channels)this.log(`Stopping channel: ${e}`),await t.stop()}async handleMessage(e,t){if(this.hooks?.has("pre:channel-message")){let w=await this.hooks.execute("pre:channel-message",{event:"pre:channel-message",channel:t.channel,sender:t.sender.name,text:t.text,group:t.group?.name});if(w.blocked){this.log(`Message blocked by hook: ${w.message}`);return}w.modified?.text&&(t={...t,text:w.modified.text})}if(t.group){let w=t.group.id;this.groupLog.add(w,t.sender.name,t.text)}let n=this.resolveAgent(t);if(!n)return;if(t.group&&t.channel==="telegram"){let w=this.getAccountForAgent(n);if(w&&w!==t.accountId)return}let s=t.group?.id||t.sender.id,i=this.registry.getAgent(n)?.name||n,a=this.getAccountForAgent(n)||t.accountId;this.log(`Routing [${t.channel}/${t.sender.name}] -> "${i}": ${t.text.slice(0,80)}`),this.adapterReact(e,s,t.id,"\u{1F440}",a);let o=this.startTypingLoop(e,s,a),g=typeof e.editMessage=="function",l,d=0,f=g?async(w,k)=>{let x=Date.now();if(!(x-d<Ct))if(l)try{await this.adapterEdit(e,s,l,k,void 0,a),d=x}catch{}else{let v=k.length>20?k:`_${i} is writing..._
|
|
33
|
-
|
|
34
|
-
${k}`;try{l=await this.adapterSend(e,{channel:t.channel,chatId:s,text:v,replyTo:t.id,accountId:a}),d=x}catch{}}}:void 0,p=t.group?this.groupLog.buildContext(s):"",y=p?`${p}
|
|
35
|
-
|
|
36
|
-
${t.sender.name}: ${t.text}`:t.text,u=await this.registry.execute({message:y,agentId:n,context:{channel:t.channel,sender:t.sender.name,group:t.group?.name,mediaPath:t.media?.path,mediaType:t.media?.type,replyToText:t.replyToText}},f);if(clearInterval(o),u.error){this.log(`Agent error: ${u.error}`);let w=`Error: ${u.error}`;l?await this.adapterEdit(e,s,l,w,"plain",a):await this.adapterSend(e,{channel:t.channel,chatId:s,text:w,replyTo:t.id,parseMode:"plain",accountId:a});return}let m=u.content;if(this.hooks?.has("post:channel-message")){let w=await this.hooks.execute("post:channel-message",{event:"post:channel-message",channel:t.channel,sender:t.sender.name,response:m,agentId:n});if(w.blocked){this.log(`Response blocked by hook: ${w.message}`);return}w.modified?.response&&(m=w.modified.response)}let b;m&&(l?(await this.adapterEdit(e,s,l,m,void 0,a),b=l):b=await this.adapterSend(e,{channel:t.channel,chatId:s,text:m,replyTo:t.id,accountId:a})),t.group&&m&&this.groupLog.add(s,i,m),m&&b&&t.channel==="telegram"&&this.handleBotToBotChain(e,t,n,m,b,0).catch(w=>{this.log(`Bot-to-bot error: ${w.message}`)})}async handleBotToBotChain(e,t,n,s,r,i,a=new Set){if(i>=pe.MAX_BOT_CHAIN_DEPTH){this.log(`Bot-to-bot: max depth (${i}) reached, stopping`);return}a.add(n);for(let[o,g]of Object.entries(this.config.agents)){if(o===n)continue;if(a.has(o)){this.log(`Bot-to-bot: "${o}" already participated, stopping chain`);continue}if(!g.mentions.some(y=>s.toLowerCase().includes(y.toLowerCase())))continue;this.log(`Bot-to-bot [${i+1}]: "${n}" -> "${o}"`);let d=t.group?.id||t.sender.id,f=this.getAccountForAgent(o),p=this.getAccountForAgent(n);try{this.adapterReact(e,d,r,"\u{1F440}",f);let y=this.startTypingLoop(e,d,f),u=i===0?`[Original from ${t.sender.name}]: ${t.text}
|
|
37
|
-
|
|
38
|
-
[${n} said]: ${s}`:s,m=await this.registry.execute({message:u,agentId:o,context:{channel:t.channel,sender:`agent:${n}`,group:t.group?.name}});if(clearInterval(y),m.content&&!m.error){let b=await this.adapterSend(e,{channel:t.channel,chatId:d,text:m.content,accountId:f});b&&m.content&&await this.handleBotToBotChain(e,t,o,m.content,b,i+1,a)}else m.error&&this.log(`Bot-to-bot "${o}" error: ${m.error}`)}catch(y){this.log(`Bot-to-bot "${o}" failed: ${y.message}`)}break}}async adapterSend(e,t){return e.name==="telegram"&&t.accountId?e.send({...t,parseMode:t.parseMode,accountId:t.accountId}):e.send(t)||""}async adapterEdit(e,t,n,s,r,i){return e.name==="telegram"&&i?e.editMessage(t,n,s,r,i):e.editMessage?.(t,n,s,r)??!1}adapterReact(e,t,n,s,r){e.name==="telegram"&&r?e.react(t,n,s,r):e.react?.(t,n,s)}startTypingLoop(e,t,n){let s=()=>{e.name==="telegram"&&n?e.sendTyping(t,n):e.sendTyping?.(t)};return s(),setInterval(s,Mt)}async handleViaMesh(e,t){if(!this.mesh)return!1;let n=t.text.toLowerCase(),s=this.mesh.directory();for(let r of s)if(r.healthy){for(let i of r.skills)if(n.includes(i.id.toLowerCase())||n.includes(i.name.toLowerCase())){this.log(`Mesh routing [${t.channel}/${t.sender.name}] -> peer "${r.peer}" agent "${i.id}"`);let a=t.group?.id||t.sender.id,o=t.accountId;this.adapterReact(e,a,t.id,"\u{1F440}",o);let g=this.startTypingLoop(e,a,o);try{let l=await this.mesh.sendTask(r.peer,t.text,i.id);if(clearInterval(g),l){let d=`**${i.name}** _(${r.peer})_:
|
|
39
|
-
|
|
40
|
-
`;await this.adapterSend(e,{channel:t.channel,chatId:a,text:d+l,replyTo:t.id,accountId:o})}return!0}catch(l){return clearInterval(g),this.log(`Mesh routing error: ${l.message}`),await this.adapterSend(e,{channel:t.channel,chatId:a,text:`Error from ${r.peer}/${i.name}: ${l.message}`,replyTo:t.id,parseMode:"plain",accountId:o}),!0}}}return!1}getAccountForAgent(e){for(let[t,n]of Object.entries(this.config.channels.telegram.accounts))if(n.agentBinding===e)return t}resolveAgent(e){if(e.resolvedAgent)return e.resolvedAgent;if(!e.group)return e.channel==="telegram"?this.config.channels.telegram.accounts[e.accountId]?.agentBinding:e.channel==="whatsapp"?this.config.channels.whatsapp.defaultAgent:void 0;if(e.channel==="telegram"&&this.config.channels.telegram.policy.group==="mention-required"){let s=this.registry.findByMention(e.text);return s||void 0}let t=this.registry.findByMention(e.text);return t||(e.channel==="telegram"?this.config.channels.telegram.accounts[e.accountId]?.agentBinding:this.config.channels.whatsapp.defaultAgent)}},_=pe;H(_,"MAX_BOT_CHAIN_DEPTH",3);function Z(c){return c.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function me(c){let e=c.split(`
|
|
41
|
-
`),t=[],n=!1,s="",r=[],i=!1,a=[],o=!1;for(let l=0;l<e.length;l++){let d=e[l];if(d.trimStart().startsWith("```"))if(n){n=!1;let u=Z(r.join(`
|
|
42
|
-
`)),m=s?`// ${s}
|
|
43
|
-
`:"";t.push(`<pre><code>${m}${u}</code></pre>`),s="";continue}else{n=!0,s=d.trimStart().slice(3).trim(),r=[];continue}if(n){r.push(d);continue}if(i&&!d.trimStart().startsWith(">")&&(t.push("</blockquote>"),i=!1),o&&!d.trim().startsWith("|")&&(o=!1,a=[]),d.trimStart().startsWith("> ")){let u=d.replace(/^>\s*/,"");i||(t.push("<blockquote>"),i=!0),t.push(M(u));continue}let f=d.match(/^(#{1,6})\s+(.+)$/);if(f){t.push(""),t.push(`<b>${M(f[2])}</b>`);continue}if(/^[-*_]{3,}\s*$/.test(d.trim())){t.push("\u2014\u2014\u2014");continue}if(d.trim().startsWith("|")&&d.trim().endsWith("|")){let u=d.split("|").slice(1,-1).map(m=>m.trim());if(/^\|[\s\-:|]+\|$/.test(d.trim())){o=!0;continue}if(!o){a=u,o=!0;continue}if(a.length>0&&u.length>0)if(u.length>=2){let m=[];for(let b=0;b<u.length;b++)if(b===0)m.push(`<b>${M(u[b])}</b>`);else{let w=a[b]?`${M(a[b])}: `:"";m.push(`${w}${M(u[b])}`)}t.push(`\u2022 ${m.join(" \u2014 ")}`)}else t.push(`\u2022 ${M(u[0])}`);continue}let p=d.match(/^(\s*)[-*+]\s+(.+)$/);if(p){let u=p[1].length>0?" ":"";t.push(`${u}\u2022 ${M(p[2])}`);continue}let y=d.match(/^(\s*)\d+[.)]\s+(.+)$/);if(y){let u=y[1].length>0?" ":"",m=d.match(/^(\s*)(\d+)/)?.[2]||"1";t.push(`${u}${m}. ${M(y[2])}`);continue}if(!d.trim()){t.push("");continue}t.push(M(d))}n&&t.push(`<pre><code>${Z(r.join(`
|
|
44
|
-
`))}</code></pre>`),i&&t.push("</blockquote>");let g=t.join(`
|
|
45
|
-
`).trim();return g=Pt(g),g}function M(c){let e=Z(c);return e=e.replace(/`([^`]+)`/g,"<code>$1</code>"),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(t,n,s)=>`<a href="${Z(s)}">${n}</a>`),e=e.replace(/\*\*\*(.+?)\*\*\*/g,"<b><i>$1</i></b>"),e=e.replace(/\*\*(.+?)\*\*/g,"<b>$1</b>"),e=e.replace(/(?<!\*)\*([^*]+?)\*(?!\*)/g,"<i>$1</i>"),e=e.replace(/~~(.+?)~~/g,"<s>$1</s>"),e=e.replace(/\|\|(.+?)\|\|/g,"<tg-spoiler>$1</tg-spoiler>"),e}var It=/(?<=\w)\.(ts|js|py|rs|go|rb|cs|sh|md|yml|yaml|toml|json|env|css|html|xml|sql|tf|hcl)(?=[\s,;:)\]}<]|$)/gi;function Pt(c){let e=c.split(/(<\/?(?:code|pre|a)[^>]*>)/gi),t=!1;return e.map(n=>/<(?:code|pre|a)\b/i.test(n)?(t=!0,n):/<\/(?:code|pre|a)>/i.test(n)?(t=!1,n):t?n:n.replace(It,"<code>.$1</code>")).join("")}var ee=class{name="telegram";accounts;offsets=new Map;handler;polling=!1;log;constructor(e,t=console.error.bind(console,"[telegram]")){this.accounts=new Map(Object.entries(e)),this.log=t}onMessage(e){this.handler=e}async start(){this.polling=!0;let e=Array.from(this.accounts.entries());this.log(`${e.length} Telegram account(s) to start`);for(let t=0;t<e.length;t++){let[n,s]=e[t];this.log(`Starting polling for account "${n}" (${t+1}/${e.length})`);try{let r=await this.apiCall(s.token,"getMe");this.log(`Bot @${r.result?.username} ready (account: ${n})`),this.pollLoop(n,s)}catch(r){this.log(`Failed to verify bot for account "${n}": ${r.message}`)}t<e.length-1&&await new Promise(r=>setTimeout(r,300))}this.log(`All ${e.length} Telegram account(s) started`)}async stop(){this.polling=!1}getTokenForAccount(e){return this.accounts.get(e)?.token}getDefaultToken(){let[,e]=Array.from(this.accounts.entries())[0];return e?.token}resolveToken(e,t){if(t){let n=this.getTokenForAccount(t);if(n)return n}return this.chatAccountMap.get(e)?this.getTokenForAccount(this.chatAccountMap.get(e)):this.getDefaultToken()}chatAccountMap=new Map;async send(e){let t=this.resolveToken(e.chatId,e.accountId);if(!t)return this.log("No telegram token found for sending"),"";let n=4096,s=e.text.length>n?e.text.slice(0,n-3)+"...":e.text,r=e.parseMode==="markdown"||e.parseMode===void 0?me(s):s,i={chat_id:e.chatId,text:r,parse_mode:"HTML"};e.replyTo&&(i.reply_to_message_id=parseInt(e.replyTo,10)),e.parseMode==="html"?(i.parse_mode="HTML",i.text=s):e.parseMode==="plain"&&(delete i.parse_mode,i.text=s);try{let a=await this.apiCall(t,"sendMessage",i);return String(a.result?.message_id||"")}catch(a){if(i.parse_mode){delete i.parse_mode,i.text=s;let o=await this.apiCall(t,"sendMessage",i);return String(o.result?.message_id||"")}throw a}}async editMessage(e,t,n,s,r){let i=this.resolveToken(e,r);if(!i)return!1;let a=4096,o=n.length>a?n.slice(0,a-3)+"...":n,g=s!=="html"&&s!=="plain"?me(o):o,l={chat_id:e,message_id:parseInt(t,10),text:g,parse_mode:"HTML"};s==="html"?(l.parse_mode="HTML",l.text=o):s==="plain"&&(delete l.parse_mode,l.text=o);try{return await this.apiCall(i,"editMessageText",l),!0}catch(d){if(d.message?.includes("message is not modified"))return!0;if(l.parse_mode){delete l.parse_mode,l.text=o;try{return await this.apiCall(i,"editMessageText",l),!0}catch{return!1}}return!1}}async react(e,t,n="\u{1F440}",s){let r=this.resolveToken(e,s);if(r)try{await this.apiCall(r,"setMessageReaction",{chat_id:e,message_id:parseInt(t,10),reaction:[{type:"emoji",emoji:n}]})}catch{}}async sendTyping(e,t){let n=this.resolveToken(e,t);if(n)try{await this.apiCall(n,"sendChatAction",{chat_id:e,action:"typing"})}catch{}}async pollLoop(e,t){let n=0;for(;this.polling;)try{let s=this.offsets.get(e)||0,i=(await this.apiCall(t.token,"getUpdates",{offset:s||void 0,timeout:30,allowed_updates:["message"]})).result||[];for(let a of i)if(this.offsets.set(e,a.update_id+1),a.message&&this.handler){let o=a.message,g=o.text||o.caption||"",l,d=o.photo&&o.photo.length>0,f=!!o.voice,p=!!o.audio,y=!!o.video,u=!!o.document;if(d||f||p||y||u){let w,k="application/octet-stream";if(d?(w=o.photo[o.photo.length-1].file_id,k="image/jpeg",g||(g="[Photo attached \u2014 please describe what you see]")):f?(w=o.voice.file_id,k=o.voice.mime_type||"audio/ogg",g||(g="[Voice message \u2014 please transcribe and respond]")):p?(w=o.audio.file_id,k=o.audio.mime_type||"audio/mpeg",g||(g=`[Audio: ${o.audio.title||"audio file"}]`)):y?(w=o.video.file_id,k=o.video.mime_type||"video/mp4",g||(g="[Video attached]")):u&&(w=o.document.file_id,k=o.document.mime_type||"application/octet-stream",g||(g=`[Document: ${o.document.file_name||"file"}]`)),w)try{let v=(await this.apiCall(t.token,"getFile",{file_id:w})).result?.file_path;if(v){let I=`https://api.telegram.org/file/bot${t.token}/${v}`,O=await fetch(I);if(O.ok){let we=Buffer.from(await O.arrayBuffer()),S=k.split("/")[1]?.split(";")[0]||"bin",{mkdirSync:oe,writeFileSync:P}=await import("fs"),{randomUUID:W}=await import("crypto"),{resolve:N,join:ae}=await import("path"),$=N(process.cwd(),".agentx/media/telegram");oe($,{recursive:!0});let T=o.document?.file_name||`${W()}.${S}`,A=ae($,T);P(A,we),l={path:A,type:k,fileName:T}}}}catch(x){this.log(`Media download failed: ${x.message}`)}}if(!g)continue;let b={id:String(o.message_id),channel:"telegram",accountId:e,sender:{id:String(o.from.id),name:[o.from.first_name,o.from.last_name].filter(Boolean).join(" "),username:o.from.username},group:o.chat.type!=="private"?{id:String(o.chat.id),name:o.chat.title||""}:void 0,text:g,media:l,replyTo:o.reply_to_message?String(o.reply_to_message.message_id):void 0,replyToText:o.reply_to_message?o.reply_to_message.text||o.reply_to_message.caption||`[message from ${o.reply_to_message.from?.first_name||"unknown"}]`:void 0,timestamp:new Date(o.date*1e3),raw:a};this.chatAccountMap.set(String(o.chat.id),e),this.handler(b).catch(w=>{this.log(`Error handling message: ${w.message}`)})}n=0}catch(s){n++;let r=Math.min(5e3*Math.pow(2,n-1),6e4);this.log(`Poll error (${e}): ${s.message} [retry in ${r/1e3}s, errors: ${n}]`),await new Promise(i=>setTimeout(i,r))}}async apiCall(e,t,n){let s=`https://api.telegram.org/bot${e}/${t}`,r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:n?JSON.stringify(n):void 0});if(!r.ok){let i=await r.text();throw new Error(`Telegram API error: ${r.status} ${i}`)}return r.json()}};import{mkdirSync as Oe,writeFileSync as Dt}from"fs";import{resolve as We,join as Rt}from"path";import{randomUUID as _t}from"crypto";var te=class{name="whatsapp";sessionDir;defaultAgent;allowFrom;routes;handler;sock=null;sentMessageIds=new Set;log;constructor(e,t=console.error.bind(console,"[whatsapp]")){this.sessionDir=We(e.sessionDir),this.defaultAgent=e.defaultAgent,this.allowFrom=e.allowFrom,this.routes=e.routes||[],this.log=t}resolveAgent(e,t,n){for(let s of this.routes){if(s.contact){let r=s.contact.replace(/\+/g,"");if(e.includes(r)||r.includes(e))return s.agent}if(s.group&&(t||n)){let r=s.group.toLowerCase();if(t?.toLowerCase().includes(r)||n?.toLowerCase().includes(r))return s.agent}}return this.defaultAgent}onMessage(e){this.handler=e}async start(){let e,t,n,s;try{s=await import("@whiskeysockets/baileys"),e=s.default||s.makeWASocket,t=s.useMultiFileAuthState,n=s.DisconnectReason}catch{this.log("WhatsApp requires @whiskeysockets/baileys. Install with:"),this.log(" npm install @whiskeysockets/baileys");return}Oe(this.sessionDir,{recursive:!0});let{state:r,saveCreds:i}=await t(this.sessionDir),a;try{let{version:g}=await s.fetchLatestBaileysVersion();a=g,this.log(`WhatsApp Web version: ${g.join(".")}`)}catch{this.log("Could not fetch WA version, using default")}let o={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:(...g)=>this.log("WA error:",...g),child:()=>o};this.sock=e({auth:{creds:r.creds,keys:s.makeCacheableSignalKeyStore?s.makeCacheableSignalKeyStore(r.keys,o):r.keys},...a?{version:a}:{},logger:o,printQRInTerminal:!1,browser:["agentx","server","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1}),this.sock.ev.on("creds.update",i),this.sock.ev.on("messaging-history.set",g=>{this.log(`WA history sync: ${g.messages?.length||0} messages, ${g.isLatest?"latest":"partial"}`)}),this.sock.ev.on("connection.update",async g=>{let{connection:l,lastDisconnect:d,qr:f}=g;if(f){this.log("Scan QR code with WhatsApp to connect:");try{let{default:p}=await import("qrcode-terminal");p.generate(f,{small:!0})}catch{this.log(`QR: ${f}`),this.log("Install qrcode-terminal for visual QR: npm install qrcode-terminal")}}if(l==="close"){let p=d?.error?.output?.statusCode;this.log(`WhatsApp connection closed (status: ${p})`),p===515?(this.log("Stream error, reconnecting in 5s..."),setTimeout(()=>this.start(),5e3)):p===n?.loggedOut||p===401?this.log("Logged out. Delete session dir and restart to re-scan QR."):p!==void 0&&(this.log("Reconnecting in 3s..."),setTimeout(()=>this.start(),3e3))}l==="open"&&this.log("WhatsApp connected")}),this.sock.ev.on("messages.upsert",async g=>{if(this.log(`WA messages.upsert: ${g.messages?.length||0} messages, type: ${g.type}`),!!this.handler)for(let l of g.messages||[]){let d=(l.key.remoteJid||"").replace(/@.*/,"").slice(-6),f=!!(l.message?.conversation||l.message?.extendedTextMessage?.text);if(this.log(`WA msg: from=${d} fromMe=${l.key.fromMe} hasText=${f} type=${Object.keys(l.message||{}).join(",")}`),l.key.remoteJid==="status@broadcast")continue;if(l.key.id&&this.sentMessageIds.has(l.key.id)){this.sentMessageIds.delete(l.key.id);continue}if(l.key.fromMe){let $=this.sock?.user,T=l.key.remoteJid||"",A=$?.id?.replace(/:.*/,"")||"",ce=$?.lid?.replace(/:.*/,"")||"",D=T.replace(/:.*/,"").replace(/@.*/,"");if(!(D===A||D===ce))continue}let p=l.message?.conversation||l.message?.extendedTextMessage?.text||l.message?.imageMessage?.caption||l.message?.videoMessage?.caption||"",y=l.message||{},u=!!y.imageMessage,m=!!y.audioMessage,b=!!y.videoMessage,w=!!y.documentMessage,k=!!y.stickerMessage,x=u||m||b||w||k;if(x&&!p&&(u?p="[Image attached \u2014 please describe what you see]":m?p="[Voice message attached \u2014 please transcribe and respond]":b?p="[Video attached]":w?p=`[Document: ${y.documentMessage?.fileName||"file"}]`:k&&(p="[Sticker]")),!p)continue;let v=l.key.remoteJid||"",I=v.endsWith("@g.us"),O=v.replace(/@.*$/,""),S=(I?l.key.participant||"":v).replace(/@.*$/,"");if(this.allowFrom?.length&&!l.key.fromMe&&!this.allowFrom.some(T=>{let A=T.replace(/\+/g,"");return S.includes(A)||O.includes(A)}))continue;let oe=l.key.fromMe?"me":l.pushName||S,P;if(I&&this.sock)try{P=(await this.sock.groupMetadata(v)).subject}catch{}let W=this.resolveAgent(S,P,I?v:void 0);if(!W){this.log(`No route for ${I?`group ${P||v}`:S}, skipping`);continue}let N;if(x&&this.sock)try{let T=await(await import("@whiskeysockets/baileys")).downloadMediaMessage(l,"buffer",{},{reuploadRequest:this.sock.updateMediaMessage,logger:this.sock.logger});if(T){let A=y.imageMessage?.mimetype||y.audioMessage?.mimetype||"audio/ogg",ce=A.split("/")[1]?.split(";")[0]||"bin",D=We(this.sessionDir,"../media/inbound");Oe(D,{recursive:!0});let le=y.documentMessage?.fileName||`${_t()}.${ce}`,ge=Rt(D,le);Dt(ge,T),N={path:ge,type:A,fileName:le},this.log(`WA media saved: ${A} -> ${ge}`)}}catch($){this.log(`WA media download failed: ${$.message}`)}let ae={id:l.key.id||String(Date.now()),channel:"whatsapp",accountId:"default",sender:{id:l.key.fromMe?(this.sock?.user?.id?.replace(/:.*/,"")||S)+"@s.whatsapp.net":S,name:oe,username:S},group:I?{id:v,name:P||v}:void 0,text:p,media:N,replyTo:l.message?.extendedTextMessage?.contextInfo?.stanzaId,timestamp:new Date((l.messageTimestamp||0)*1e3),raw:l,resolvedAgent:W};this.handler(ae).catch($=>{this.log(`Error handling message: ${$.message}`)})}})}async stop(){this.sock&&(this.sock.end(),this.sock=null)}async send(e){if(!this.sock)return this.log("WhatsApp not connected"),"";let t=e.chatId.includes("@")?e.chatId:`${e.chatId}@s.whatsapp.net`;try{let s=(await this.sock.sendMessage(t,{text:e.text}))?.key?.id||"";return s&&this.sentMessageIds.add(s),s}catch(n){return this.log(`Send error: ${n.message}`),""}}async editMessage(e,t,n){if(!this.sock)return!1;let s=e.includes("@")?e:`${e}@s.whatsapp.net`;try{return await this.sock.sendMessage(s,{text:n,edit:{remoteJid:s,id:t,fromMe:!0}}),!0}catch{return!1}}async sendTyping(e){if(!this.sock)return;let t=e.includes("@")?e:`${e}@s.whatsapp.net`;try{await this.sock.sendPresenceUpdate("composing",t)}catch{}}async react(e,t,n="\u{1F440}"){if(!this.sock)return;let s=e.includes("@")?e:`${e}@s.whatsapp.net`;try{await this.sock.sendMessage(s,{react:{text:n,key:{remoteJid:s,id:t}}})}catch{}}};import{writeFileSync as jt,mkdirSync as Ne,existsSync as He}from"fs";import{resolve as fe}from"path";function j(c,e,t){let n=[];for(let s of c.split(","))if(s==="*")for(let r=e;r<=t;r++)n.push(r);else if(s.includes("/")){let[r,i]=s.split("/"),a=parseInt(i,10),o=r==="*"?e:parseInt(r,10);for(let g=o;g<=t;g+=a)n.push(g)}else if(s.includes("-")){let[r,i]=s.split("-").map(Number);for(let a=r;a<=i;a++)n.push(a)}else n.push(parseInt(s,10));return[...new Set(n)].sort((s,r)=>s-r)}function Lt(c,e,t){let n=c.trim().split(/\s+/);if(n.length!==5)throw new Error(`Invalid cron: ${c}`);let s=j(n[0],0,59),r=j(n[1],0,23),i=j(n[2],1,31),a=j(n[3],1,12),o=j(n[4],0,6),g=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),l=new Date(e.getTime()+6e4);l.setSeconds(0,0);let d=new Date(l.getTime()+366*24*60*60*1e3);for(;l<d;){let f=g.formatToParts(l),p=k=>parseInt(f.find(x=>x.type===k)?.value||"0",10),y=p("minute"),u=p("hour"),m=p("day"),b=p("month"),w=l.getDay();if(s.includes(y)&&r.includes(u)&&i.includes(m)&&a.includes(b)&&o.includes(w))return l;l.setTime(l.getTime()+6e4)}throw new Error(`No next run found for cron "${c}" within 1 year`)}var ne=class{jobs=new Map;timers=new Map;registry;hooks;runsDir;running=!1;log;constructor(e,t,n,s=console.error.bind(console,"[cron]")){this.registry=t,this.hooks=n,this.log=s,this.runsDir=fe(process.cwd(),".agentx/cron/runs");for(let[r,i]of Object.entries(e.crons))this.jobs.set(r,{id:r,enabled:i.enabled,schedule:i.schedule,timezone:i.timezone,agent:i.agent,prompt:i.prompt,timeout:i.timeout,model:i.model,onError:i.onError,consecutiveErrors:0,totalRuns:0})}async start(){this.running=!0,He(this.runsDir)||Ne(this.runsDir,{recursive:!0});for(let[e,t]of this.jobs){if(!t.enabled){this.log(`Job "${e}" is disabled, skipping`);continue}this.scheduleNext(e)}this.log(`${this.jobs.size} cron job(s) loaded, ${Array.from(this.jobs.values()).filter(e=>e.enabled).length} enabled`)}async stop(){this.running=!1;for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}scheduleNext(e){let t=this.jobs.get(e);if(!(!t||!t.enabled||!this.running))try{let n=Lt(t.schedule,new Date,t.timezone);t.nextRun=n;let s=n.getTime()-Date.now();this.log(`Job "${e}" next run: ${n.toISOString()} (in ${Math.round(s/1e3)}s)`);let r=setTimeout(()=>this.executeJob(e),s);this.timers.set(e,r)}catch(n){this.log(`Failed to schedule "${e}": ${n.message}`)}}async executeJob(e){let t=this.jobs.get(e);if(!t||!this.running)return;if(this.hooks?.has("pre:cron-run")){let s=await this.hooks.execute("pre:cron-run",{event:"pre:cron-run",jobId:e,agent:t.agent,prompt:t.prompt});if(s.blocked){this.log(`Job "${e}" blocked by hook: ${s.message}`),this.scheduleNext(e);return}}this.log(`Executing job "${e}" -> agent "${t.agent}"`);let n=new Date;t.lastRun=n,t.totalRuns++;try{let s=await this.registry.execute({message:t.prompt,agentId:t.agent,context:{channel:"cron"}}),r={jobId:e,startedAt:n,completedAt:new Date,success:!s.error,response:s.content,error:s.error,duration:s.duration||Date.now()-n.getTime()};s.error?(t.consecutiveErrors++,this.log(`Job "${e}" failed (${t.consecutiveErrors} consecutive): ${s.error}`),t.onError==="disable"&&t.consecutiveErrors>=3&&(t.enabled=!1,this.log(`Job "${e}" disabled after ${t.consecutiveErrors} consecutive errors`))):(t.consecutiveErrors=0,this.log(`Job "${e}" completed in ${r.duration}ms`)),this.logRun(r),this.hooks?.has("post:cron-run")&&await this.hooks.execute("post:cron-run",{event:"post:cron-run",jobId:e,success:r.success,duration:r.duration,error:r.error?new Error(r.error):void 0})}catch(s){t.consecutiveErrors++,this.log(`Job "${e}" threw: ${s.message}`)}this.scheduleNext(e)}logRun(e){try{let t=fe(this.runsDir,e.jobId);He(t)||Ne(t,{recursive:!0});let n=`${e.startedAt.toISOString().replace(/[:.]/g,"-")}.json`;jt(fe(t,n),JSON.stringify(e,null,2))}catch{}}list(){return Array.from(this.jobs.values())}};import{createServer as Ot}from"http";import{writeFileSync as Wt,existsSync as Nt,unlinkSync as Ht,mkdirSync as Bt}from"fs";import{resolve as Be,dirname as Ut}from"path";var se=class{name="discord";token;agentBinding;handler;client=null;log;constructor(e,t=console.error.bind(console,"[discord]")){this.token=e.token,this.agentBinding=e.agentBinding,this.log=t}onMessage(e){this.handler=e}async start(){let e;try{e=await import("discord.js")}catch{this.log("Discord requires discord.js. Install with:"),this.log(" npm install discord.js");return}let{Client:t,GatewayIntentBits:n}=e;this.client=new t({intents:[n.Guilds,n.GuildMessages,n.MessageContent,n.DirectMessages]}),this.client.on("ready",()=>{this.log(`Discord connected as ${this.client.user?.tag}`)}),this.client.on("messageCreate",async s=>{if(!this.handler||s.author.bot)return;let r=s.mentions.users.has(this.client.user?.id),i=!s.guild;if(!r&&!i)return;let a=s.content;if(this.client.user&&(a=a.replace(new RegExp(`<@!?${this.client.user.id}>`,"g"),"").trim()),!a)return;let o={id:s.id,channel:"discord",accountId:"default",sender:{id:s.author.id,name:s.author.displayName||s.author.username,username:s.author.username},group:s.guild?{id:s.channelId,name:s.channel?.name||s.channelId}:void 0,text:a,replyTo:s.reference?.messageId,timestamp:s.createdAt,raw:s};this.handler(o).catch(g=>{this.log(`Error handling message: ${g.message}`)})});try{await this.client.login(this.token)}catch(s){this.log(`Discord login failed: ${s.message}`)}}async stop(){this.client&&(this.client.destroy(),this.client=null)}async send(e){if(!this.client)return"";try{let t=await this.client.channels.fetch(e.chatId);return t?.isTextBased()?(await t.send({content:e.text,...e.replyTo?{reply:{messageReference:e.replyTo}}:{}})).id:""}catch(t){return this.log(`Send error: ${t.message}`),""}}async editMessage(e,t,n){if(!this.client)return!1;try{let s=await this.client.channels.fetch(e);return s?.isTextBased()?(await(await s.messages.fetch(t)).edit(n),!0):!1}catch{return!1}}async sendTyping(e){if(this.client)try{let t=await this.client.channels.fetch(e);t?.isTextBased()&&await t.sendTyping()}catch{}}async react(e,t,n="\u{1F440}"){if(this.client)try{let s=await this.client.channels.fetch(e);if(!s?.isTextBased())return;await(await s.messages.fetch(t)).react(n)}catch{}}};import{createServer as Et}from"http";var re=class{name="gitlab";config;handler;server;botUsername;sentNoteIds=new Set;log;constructor(e,t=console.error.bind(console,"[gitlab]")){this.config=e,this.log=t}onMessage(e){this.handler=e}async start(){try{let t=await(await fetch(`${this.config.host}/api/v4/user`,{headers:{"PRIVATE-TOKEN":this.config.token}})).json();this.botUsername=t.username,this.log(`Bot user: ${this.botUsername}`)}catch(e){this.log(`Could not resolve bot user: ${e.message}`)}this.server=Et(async(e,t)=>{e.method==="POST"?await this.handleWebhook(e,t):(t.writeHead(200,{"Content-Type":"text/plain"}),t.end("GitLab webhook endpoint. POST events here."))}),this.server.listen(this.config.webhookPort,()=>{this.log(`GitLab webhook listening on :${this.config.webhookPort}`)})}async stop(){this.server&&this.server.close()}async send(e){let t=e.chatId.split(":");if(t.length<3)return this.log(`Invalid chatId for GitLab reply: ${e.chatId}`),"";let n=t.pop(),s=t.pop(),r=t.join(":"),i=encodeURIComponent(r),a;switch(s){case"issue":a=`${this.config.host}/api/v4/projects/${i}/issues/${n}/notes`;break;case"merge_request":a=`${this.config.host}/api/v4/projects/${i}/merge_requests/${n}/notes`;break;default:return this.log(`Unsupported noteable type: ${s}`),""}try{let o=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json","PRIVATE-TOKEN":this.config.token},body:JSON.stringify({body:e.text})});if(!o.ok){let d=await o.text();return this.log(`GitLab API error: ${o.status} ${d}`),""}let g=await o.json(),l=String(g.id||"");return l&&this.sentNoteIds.add(l),l}catch(o){return this.log(`GitLab send error: ${o.message}`),""}}async handleWebhook(e,t){if(this.config.webhookSecret&&e.headers["x-gitlab-token"]!==this.config.webhookSecret){t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid token"}));return}let s=await this.readBody(e),r=s.object_kind||s.event_type||"unknown";switch(this.log(`Event: ${r} from ${s.project?.path_with_namespace||"unknown"}`),r){case"note":await this.handleNote(s,t);break;case"issue":await this.handleIssue(s,t);break;case"merge_request":await this.handleMR(s,t);break;case"pipeline":await this.handlePipeline(s,t);break;default:this.log(`Unhandled event: ${r}`),t.writeHead(200),t.end("ok")}}async handleNote(e,t){if(!this.handler){t.writeHead(200),t.end("ok");return}let n=e.object_attributes.note,s=e.project.path_with_namespace,r=e.user,i=String(e.object_attributes.id);if(this.botUsername&&r.username===this.botUsername){this.log(`Skipping own comment from ${this.botUsername}`),t.writeHead(200),t.end("ok");return}if(this.sentNoteIds.has(i)){this.sentNoteIds.delete(i),t.writeHead(200),t.end("ok");return}let a="",o="",g="";e.issue?(a="issue",o=String(e.issue.iid),g=e.issue.title):e.merge_request&&(a="merge_request",o=String(e.merge_request.iid),g=e.merge_request.title);let l=this.resolveAgentFromMention(n)||this.resolveAgent(s),d=`${s}:${a}:${o}`,f={id:String(e.object_attributes.id),channel:"gitlab",accountId:"default",sender:{id:d,name:r.name,username:r.username},text:`[GitLab ${a} #${o}: ${g}]
|
|
46
|
-
${r.name} commented:
|
|
47
|
-
${n}`,timestamp:new Date,raw:e,resolvedAgent:l};this.handler(f).catch(p=>{this.log(`Error handling note: ${p.message}`)}),t.writeHead(200),t.end("ok")}async handleIssue(e,t){if(!this.handler){t.writeHead(200),t.end("ok");return}let n=e.object_attributes,s=e.project.path_with_namespace,r=this.resolveAgent(s),i={id:`issue-${n.iid}-${n.action}`,channel:"gitlab",accountId:"default",sender:{id:`${s}:issue:${n.iid}`,name:e.user.name,username:e.user.username},text:`[GitLab Issue #${n.iid} ${n.action}]: ${n.title}
|
|
48
|
-
${n.description?.slice(0,500)||""}
|
|
49
|
-
URL: ${n.url}`,timestamp:new Date,raw:e,resolvedAgent:r};this.handler(i).catch(a=>this.log(`Error handling issue: ${a.message}`)),t.writeHead(200),t.end("ok")}async handleMR(e,t){if(!this.handler){t.writeHead(200),t.end("ok");return}let n=e.object_attributes,s=e.project.path_with_namespace,r=this.resolveAgent(s),i={id:`mr-${n.iid}-${n.action}`,channel:"gitlab",accountId:"default",sender:{id:`${s}:merge_request:${n.iid}`,name:e.user.name,username:e.user.username},text:`[GitLab MR !${n.iid} ${n.action}]: ${n.title}
|
|
50
|
-
Branch: ${n.source_branch} -> ${n.target_branch}
|
|
51
|
-
${n.description?.slice(0,500)||""}
|
|
52
|
-
URL: ${n.url}`,timestamp:new Date,raw:e,resolvedAgent:r};this.handler(i).catch(a=>this.log(`Error handling MR: ${a.message}`)),t.writeHead(200),t.end("ok")}async handlePipeline(e,t){if(!this.handler){t.writeHead(200),t.end("ok");return}if(e.object_attributes.status!=="failed"){t.writeHead(200),t.end("ok");return}let n=e.object_attributes,s=e.project.path_with_namespace,r=this.resolveAgent(s),i={id:`pipeline-${n.id}`,channel:"gitlab",accountId:"default",sender:{id:`${s}:pipeline:${n.id}`,name:e.user.name,username:e.user.username},text:`[GitLab Pipeline FAILED] Project: ${s}
|
|
53
|
-
Ref: ${n.ref}
|
|
54
|
-
Duration: ${n.duration}s
|
|
55
|
-
Please investigate the failure.`,timestamp:new Date,raw:e,resolvedAgent:r};this.handler(i).catch(a=>this.log(`Error handling pipeline: ${a.message}`)),t.writeHead(200),t.end("ok")}resolveAgentFromMention(e){if(!this.config.agentMappings?.length)return;let t=e.toLowerCase(),n=e.match(/@(\w+)/g)?.map(s=>s.slice(1).toLowerCase())||[];for(let s of this.config.agentMappings){for(let r of s.gitlabUsernames)if(n.includes(r.toLowerCase()))return this.log(`Mention @${r} -> agent ${s.agentId}`),s.agentId;for(let r of s.keywords)if(t.includes(r.toLowerCase()))return this.log(`Keyword "${r}" -> agent ${s.agentId}`),s.agentId}}resolveAgent(e){for(let t of this.config.routes)if(t.project===e||t.project==="*")return t.agent}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{try{t(n?JSON.parse(n):{})}catch{t({raw:n})}}),e.on("error",()=>t({}))})}};var E=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new E(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(E.levelOrder[e]<E.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},r=e==="error"?"ERROR":e==="warn"?"WARN":"",i=`[${this.module}]`,a=r?`${i} ${r}: ${t}`:`${i} ${t}`;console.error(a)}},L=E;H(L,"levelOrder",{debug:0,info:1,warn:2,error:3});var ie=class{registry;config;log;constructor(e,t={},n=console.error.bind(console,"[webhook]")){this.registry=e,this.config=t,this.log=n}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),r=s[0],i=s[1];if(!r){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let a=await this.readBody(e),o=i||this.detectSource(e.headers),g=this.buildSummary(o,a,e.headers);this.log(`Webhook [${o}] -> ${r}: ${g.slice(0,100)}`);try{let l=await this.registry.execute({message:g,agentId:r,context:{channel:`webhook:${o}`,sender:`webhook:${o}`}});this.sendJson(t,l.error?500:200,{ok:!l.error,agent:r,source:o,response:l.content?.slice(0,500),error:l.error,duration:l.duration})}catch(l){this.sendJson(t,500,{error:l.message})}}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let i=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",o=t.user?.name||t.user_username||"";if(s.push(`Event: ${i}`),a&&s.push(`Project: ${a}`),o&&s.push(`User: ${o}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let l of t.commits.slice(0,3))s.push(` - ${l.message?.split(`
|
|
56
|
-
`)[0]||"no message"} (${l.author?.name||""})`)}let g=t.object_attributes;if(g?.title&&(s.push(`Title: ${g.title}`),s.push(`State: ${g.state||""}`),s.push(`Action: ${g.action||""}`),g.source_branch&&s.push(`Branch: ${g.source_branch} -> ${g.target_branch}`),g.url&&s.push(`URL: ${g.url}`)),g?.iid&&!g?.source_branch&&(s.push(`Issue #${g.iid}: ${g.title||""}`),g.description&&s.push(`Description: ${g.description.slice(0,200)}`)),t.object_kind==="pipeline"){let l=t.object_attributes;s.push(`Pipeline: ${l?.status||""} (${l?.ref||""})`),s.push(`Duration: ${l?.duration||0}s`)}break}case"github":{let i=n["x-github-event"]||"event",a=t.repository?.full_name||"",o=t.sender?.login||"";if(s.push(`Event: ${i}`),a&&s.push(`Repository: ${a}`),o&&s.push(`Sender: ${o}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits))for(let d of t.commits.slice(0,3))s.push(` - ${d.message?.split(`
|
|
57
|
-
`)[0]||""} (${d.author?.name||""})`);let g=t.pull_request;g&&(s.push(`PR #${g.number}: ${g.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${g.head?.ref} -> ${g.base?.ref}`));let l=t.issue;l&&(s.push(`Issue #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let i=t.type||"event",a=t.data?.object||{};s.push(`Event: ${i}`),a.amount&&s.push(`Amount: ${(a.amount/100).toFixed(2)} ${a.currency?.toUpperCase()||""}`),a.customer_email&&s.push(`Customer: ${a.customer_email}`),a.description&&s.push(`Description: ${a.description}`),a.status&&s.push(`Status: ${a.status}`);break}case"sentry":{let i=n["sentry-hook-resource"]||"event";s.push(`Resource: ${i}`);let a=t.data||t;a.error?.title&&s.push(`Error: ${a.error.title}`),a.error?.culprit&&s.push(`Culprit: ${a.error.culprit}`),a.error?.metadata?.value&&s.push(`Message: ${a.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(i=>i.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let r=JSON.stringify(t).slice(0,500);s.push(`Body: ${r}`)}return s.join(`
|
|
58
|
-
`)}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{try{t(n?JSON.parse(n):{})}catch{t({raw:n})}}),e.on("error",()=>t({}))})}sendJson(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}};var Ue=class{config;registry;router;cron;mesh;hooks;httpServer;webhooks;log;constructor(e){let t=new L("agentx");this.log=t.asConsoleLog(),this.log("Loading configuration..."),this.config=$e(e);let n=xe(this.config);for(let s of n)this.log(` \u26A0 ${s}`);this.hooks=new be,ke(process.cwd(),this.hooks),this.registry=new Q(this.config,this.log),this.router=new _(this.registry,this.config,this.hooks,this.log),this.webhooks=new ie(this.registry,{},this.log),this.cron=new ne(this.config,this.registry,this.hooks,this.log),this.config.mesh.enabled&&(this.mesh=new U(this.config,this.log),this.router.setMesh(this.mesh))}async start(){this.log(""),this.log(" \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),this.log(" \u2502 agentx daemon \u2502"),this.log(" \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),this.log(""),this.log(` Node: ${this.config.node.name} (${this.config.node.id})`),this.log(` Bind: ${this.config.node.bind}`),this.log(""),await this.startChannels(),await this.cron.start(),this.mesh&&await this.mesh.start(),await this.startHttpApi(),this.log(""),this.log(" Agents:");for(let r of this.registry.list())this.log(` ${r.id} (${r.tier}) \u2192 ${r.workspace}`);let e=this.cron.list();if(e.length){this.log(""),this.log(" Cron Jobs:");for(let r of e){let i=r.enabled?"enabled":"disabled";this.log(` ${r.id} [${i}] \u2192 ${r.agent} (${r.schedule})`)}}if(this.mesh){this.log(""),this.log(" Mesh Peers:");for(let r of this.mesh.directory()){let i=r.healthy?"\u2713":"\u2717";this.log(` ${i} ${r.peer} (${r.peerUrl})`)}}this.log(""),this.log(" Ready."),this.log("");let t=Be(process.cwd(),".agentx/daemon.pid");Bt(Ut(t),{recursive:!0}),Wt(t,String(process.pid)),this.log(` PID: ${process.pid} (${t})`),process.on("uncaughtException",r=>{this.log(`UNCAUGHT EXCEPTION: ${r.message}`),this.log(r.stack||"")}),process.on("unhandledRejection",r=>{this.log(`UNHANDLED REJECTION: ${r}`)});let n=!1,s=async r=>{n||(n=!0,this.log(`
|
|
59
|
-
Received ${r}, shutting down gracefully...`),await this.stop())};process.on("SIGINT",()=>s("SIGINT")),process.on("SIGTERM",()=>s("SIGTERM"))}async stop(){let e=Date.now();try{this.log(" Stopping channels..."),await Promise.race([this.router.stopAll(),new Promise(t=>setTimeout(t,5e3))])}catch(t){this.log(` Channel stop error: ${t.message}`)}try{this.log(" Stopping crons..."),await this.cron.stop()}catch{}try{this.mesh&&(this.log(" Stopping mesh..."),await this.mesh.stop())}catch{}this.httpServer&&this.httpServer.close();try{let t=Be(process.cwd(),".agentx/daemon.pid");Nt(t)&&Ht(t)}catch{}this.log(` Shutdown complete (${Date.now()-e}ms)`),process.exit(0)}async startChannels(){if(this.config.channels.telegram.enabled){let e=this.config.channels.telegram.accounts;if(Object.keys(e).length>0){let t=new ee(e,this.log);this.router.addChannel(t),this.log(" Telegram: enabled")}}if(this.config.channels.whatsapp.enabled){let e=new te({sessionDir:this.config.channels.whatsapp.sessionDir,defaultAgent:this.config.channels.whatsapp.defaultAgent,allowFrom:this.config.channels.whatsapp.allowFrom,routes:this.config.channels.whatsapp.routes},this.log);this.router.addChannel(e),this.log(` WhatsApp: enabled (${this.config.channels.whatsapp.routes.length} routes)`)}if(this.config.channels.discord?.enabled&&this.config.channels.discord.token){let e=new se({token:this.config.channels.discord.token,agentBinding:this.config.channels.discord.agentBinding},this.log);this.router.addChannel(e),this.log(" Discord: enabled")}if(this.config.channels.gitlab?.enabled&&this.config.channels.gitlab.token){let e=new re({webhookPort:this.config.channels.gitlab.webhookPort,webhookSecret:this.config.channels.gitlab.webhookSecret,host:this.config.channels.gitlab.host,token:this.config.channels.gitlab.token,routes:this.config.channels.gitlab.routes,agentMappings:this.config.channels.gitlab.agentMappings},this.log);this.router.addChannel(e),this.log(` GitLab: enabled (${this.config.channels.gitlab.routes.length} project routes, webhook :${this.config.channels.gitlab.webhookPort})`)}await this.router.startAll()}async startHttpApi(){let[e,t]=this.config.node.bind.split(":"),n=parseInt(t||"18800",10);this.httpServer=Ot(async(s,r)=>{if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),s.method==="OPTIONS"){r.writeHead(204),r.end();return}await this.handleHttp(s,r)}),this.httpServer.on("error",s=>{s.code==="EADDRINUSE"?(this.log(` ERROR: Port ${n} is already in use. Retrying in 5s...`),setTimeout(()=>{this.httpServer?.close(),this.httpServer?.listen(n,e||"0.0.0.0")},5e3)):this.log(` HTTP error: ${s.message}`)}),this.httpServer.listen(n,e||"0.0.0.0",()=>{this.log(` HTTP API: http://${e||"0.0.0.0"}:${n}`)})}async handleHttp(e,t){let s=new URL(e.url||"/",`http://${e.headers.host||"localhost"}`).pathname;try{if(e.method==="POST"&&s.startsWith("/webhook/")){await this.webhooks.handle(e,t,s);return}if(e.method==="POST"&&(s==="/v1/chat/completions"||s.match(/^\/llm\/[^/]+\/v1\/chat\/completions$/))){await this.handleOpenAICompat(e,t,s);return}switch(`${e.method} ${s}`){case"GET /health":this.json(t,200,{status:"ok",node:this.config.node,uptime:process.uptime(),agents:this.registry.list(),crons:this.cron.list().map(r=>({id:r.id,enabled:r.enabled,nextRun:r.nextRun})),mesh:this.mesh?.directory()||[],usage:this.registry.getTodayUsage()});break;case"GET /usage":this.json(t,200,this.registry.getUsage(7));break;case"GET /agents":this.json(t,200,this.registry.list());break;case"GET /crons":this.json(t,200,this.cron.list());break;case"GET /mesh":this.json(t,200,this.mesh?.directory()||[]);break;case"POST /task":{let r=await ye(e);if(!r.agent||!r.message){this.json(t,400,{error:"Missing: agent, message"});return}let i=await this.registry.execute({agentId:r.agent,message:r.message,context:r.context});this.json(t,i.error?500:200,i);break}case"POST /mesh/task":{let r=await ye(e);if(!r.peer||!r.message){this.json(t,400,{error:"Missing: peer, message"});return}if(!this.mesh){this.json(t,400,{error:"Mesh not enabled"});return}let i=await this.mesh.sendTask(r.peer,r.message);this.json(t,200,{response:i});break}case"GET /.well-known/agent-card.json":this.json(t,200,{name:this.config.node.name,description:`AgentX daemon node "${this.config.node.name}"`,url:`http://${this.config.node.bind}`,version:"1.0.0",capabilities:{streaming:!1,pushNotifications:!1,stateTransitionHistory:!1},skills:this.registry.list().map(r=>({id:r.id,name:r.name,description:`Agent "${r.name}" (${r.tier})`,tags:[r.tier]})),defaultInputModes:["text"],defaultOutputModes:["text"]});break;default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /mesh","POST /task { agent, message, context? }","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","GET /.well-known/agent-card.json"]})}}catch(r){this.json(t,500,{error:r.message})}}async handleOpenAICompat(e,t,n){let s=await ye(e),i=n.match(/^\/llm\/([^/]+)\//)?.[1]||s.model||"atlas",a=s.messages||[],o=[...a].reverse().find(f=>f.role==="user");if(!o?.content){this.json(t,400,{error:{message:"No user message found",type:"invalid_request_error"}});return}let g=a.slice(0,-1).map(f=>`${f.role==="user"?"User":"Assistant"}: ${f.content.slice(0,200)}`),l=g.length>0?`[Conversation]
|
|
60
|
-
${g.slice(-10).join(`
|
|
61
|
-
`)}
|
|
62
|
-
|
|
63
|
-
`:"";if(s.stream===!0){t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});let f=`chatcmpl-${Date.now().toString(36)}`,p=await this.registry.execute({agentId:i,message:l+o.content,context:{channel:"api",sender:"openai-compat"}}),y=p.error||p.content||"",u={id:f,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:i,choices:[{index:0,delta:{role:"assistant",content:y},finish_reason:"stop"}]};t.write(`data: ${JSON.stringify(u)}
|
|
64
|
-
|
|
65
|
-
`),t.write(`data: [DONE]
|
|
66
|
-
|
|
67
|
-
`),t.end()}else{let f=await this.registry.execute({agentId:i,message:l+o.content,context:{channel:"api",sender:"openai-compat"}}),p=f.error||f.content||"",y=Math.ceil(p.length/4);this.json(t,200,{id:`chatcmpl-${Date.now().toString(36)}`,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:i,choices:[{index:0,message:{role:"assistant",content:p},finish_reason:"stop"}],usage:{prompt_tokens:Math.ceil(o.content.length/4),completion_tokens:y,total_tokens:Math.ceil(o.content.length/4)+y}})}}json(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}};async function ye(c){return new Promise((e,t)=>{let n="";c.on("data",s=>n+=s.toString()),c.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),c.on("error",t)})}import Gt from"path";import Jt from"fs-extra";function gs(){let c=Gt.join("package.json");return Jt.readJSONSync(c)}export{B as a,U as b,Qe as c,$e as d,xe as e,tt as f,st as g,rt as h,Te as i,R as j,Q as k,_ as l,ee as m,te as n,ne as o,Ue as p,gs as q};
|
|
68
|
-
//# sourceMappingURL=chunk-WT2UJMBC.js.map
|