@kernlang/agon 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +47 -0
- package/dist/{chunk-ESSX7EFA.js → chunk-5QMVQPHY.js} +6 -2
- package/dist/{chunk-ESSX7EFA.js.map → chunk-5QMVQPHY.js.map} +1 -1
- package/dist/{chunk-GCXVT7RP.js → chunk-7PMMOQZ7.js} +3 -3
- package/dist/{chunk-GCXVT7RP.js.map → chunk-7PMMOQZ7.js.map} +1 -1
- package/dist/{chunk-4HY7J7LY.js → chunk-HVJTVOXT.js} +13 -11
- package/dist/chunk-HVJTVOXT.js.map +1 -0
- package/dist/{chunk-5J4XXR3J.js → chunk-LVW723TJ.js} +3 -3
- package/dist/{chunk-5J4XXR3J.js.map → chunk-LVW723TJ.js.map} +1 -1
- package/dist/{chunk-YNZ4UHZI.js → chunk-RSS3RL6Z.js} +3 -3
- package/dist/{chunk-YNZ4UHZI.js.map → chunk-RSS3RL6Z.js.map} +1 -1
- package/dist/{dispatch-CJVPYWJJ.js → dispatch-6LQSMMGI.js} +2 -2
- package/dist/{forge-OWSOM4TQ.js → forge-JWR2Z76K.js} +5 -5
- package/dist/index.js +49 -29
- package/dist/index.js.map +1 -1
- package/dist/{plan-mode-MWL3DAHY.js → plan-mode-KBJY2FJN.js} +5 -5
- package/dist/{src-HKGB6OYR.js → src-U2AWRNRL.js} +3 -3
- package/package.json +40 -4
- package/dist/chunk-4HY7J7LY.js.map +0 -1
- /package/dist/{dispatch-CJVPYWJJ.js.map → dispatch-6LQSMMGI.js.map} +0 -0
- /package/dist/{forge-OWSOM4TQ.js.map → forge-JWR2Z76K.js.map} +0 -0
- /package/dist/{plan-mode-MWL3DAHY.js.map → plan-mode-KBJY2FJN.js.map} +0 -0
- /package/dist/{src-HKGB6OYR.js.map → src-U2AWRNRL.js.map} +0 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nicolas Cukas
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# @kernlang/agon
|
|
2
|
+
|
|
3
|
+
**The competitive multi-AI orchestration CLI.** Any AI can join. They compete. You ship.
|
|
4
|
+
|
|
5
|
+
Agon pits the world's best AI engines against each other on the same software task — they compete in isolated git worktrees, the best test-passing solution is applied automatically, and Glicko-2 ratings track each model's performance over time.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install -g @kernlang/agon
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
That's it — one command pulls the engine substrate (`@kernlang/agon-engines`) and the semantic sidecars (`@kernlang/agon-dedup`) automatically. Then run `agon` in any git repository.
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
agon # start the interactive REPL
|
|
17
|
+
agon doctor # verify engines, worktrees, and Python sidecars resolve
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
**Requires Node ≥ 22.** Optional: Python 3.10+ unlocks semantic features (history search, tree-sitter fitness, dedup, task classifier) — Agon runs without it via substring/regex fallbacks.
|
|
21
|
+
|
|
22
|
+
## Modes
|
|
23
|
+
|
|
24
|
+
Pick by the **shape** of the problem:
|
|
25
|
+
|
|
26
|
+
| You need… | Use |
|
|
27
|
+
|-----------|-----|
|
|
28
|
+
| Ideas / "what am I missing?" | `agon brainstorm` |
|
|
29
|
+
| One refined output from many opinions | `agon synthesis` |
|
|
30
|
+
| A decision with real tradeoffs settled | `agon tribunal` |
|
|
31
|
+
| The whole panel on a high-stakes call | `agon council` |
|
|
32
|
+
| Open exploration, no decision yet | `agon campfire` |
|
|
33
|
+
| A problem decomposed before you act | `agon think` |
|
|
34
|
+
| Your own decision pressure-tested | `agon nero` |
|
|
35
|
+
| Code built competitively against a test | `agon forge` |
|
|
36
|
+
| A narrow target optimized to a discriminating oracle | `agon goal` |
|
|
37
|
+
| A whole feature built unattended → human merge gate | `agon conquer` |
|
|
38
|
+
|
|
39
|
+
Run `agon <mode> --help` for options, or just `agon` to drive everything from the interactive REPL.
|
|
40
|
+
|
|
41
|
+
## Engines
|
|
42
|
+
|
|
43
|
+
Agon orchestrates any installed CLI/API engine (Claude, Codex, Gemini, and more). Configure them via `agon engine` and `agon provider`. See the [full documentation](https://github.com/KERNlang/agon#readme).
|
|
44
|
+
|
|
45
|
+
## License
|
|
46
|
+
|
|
47
|
+
MIT © KERNlang
|
|
@@ -419,7 +419,11 @@ async function* apiStreamDispatchWithHistory(config, messages, timeout, signal,
|
|
|
419
419
|
}
|
|
420
420
|
case "error": {
|
|
421
421
|
clearTimeout(timer);
|
|
422
|
-
|
|
422
|
+
const errStr = String(part.error);
|
|
423
|
+
const routingShaped = stdout.length === 0 && /\b404\b|not found|no such (?:route|endpoint)/i.test(errStr);
|
|
424
|
+
const hint = routingShaped ? formatMismatchHint(config) : null;
|
|
425
|
+
return { exitCode: 1, stdout, stderr: hint ? `Stream error: ${errStr}
|
|
426
|
+
${hint}` : `Stream error: ${errStr}`, durationMs: Date.now() - startTime, timedOut: false };
|
|
423
427
|
}
|
|
424
428
|
}
|
|
425
429
|
}
|
|
@@ -470,4 +474,4 @@ export {
|
|
|
470
474
|
_formatHintEmitted,
|
|
471
475
|
apiStreamDispatchWithHistory
|
|
472
476
|
};
|
|
473
|
-
//# sourceMappingURL=chunk-
|
|
477
|
+
//# sourceMappingURL=chunk-5QMVQPHY.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../core/src/generated/api/dispatch.ts"],"sourcesContent":["// @generated by kern v3.5.6 — DO NOT EDIT. Source: src/kern/api/dispatch.kern\n\n// @kern-source: dispatch:283\n// @kern-source: dispatch:315\n\nimport { streamText, generateText, jsonSchema } from 'ai';\n\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\n\nimport { createAnthropic } from '@ai-sdk/anthropic';\n\nimport type { DispatchResult } from '../models/types.js';\n\n// @kern-source: dispatch:6\nexport interface ApiConfig {\n baseUrl: string;\n apiKeyEnv: string;\n model: string;\n maxTokens?: number;\n format?: 'openai'|'anthropic';\n firstChunkTimeoutMs?: number;\n idleTimeoutMs?: number;\n}\n\n// @kern-source: dispatch:16\nexport const _modelCache: Map<string,{model:any, apiKey:string}> = new Map<string,{model:any, apiKey:string}>();\n\n/**\n * Create AI SDK model instance from ApiConfig — routes to openai-compatible or anthropic provider. Cached by baseUrl+model+format; invalidated if API key changes.\n */\n// @kern-source: dispatch:18\nexport function buildModel(config: ApiConfig): any {\n const apiKey = process.env[config.apiKeyEnv];\n if (!apiKey) return null;\n\n const cacheKey = `${config.baseUrl}|${config.model}|${config.format ?? 'openai'}`;\n const cached = _modelCache.get(cacheKey);\n if (cached && cached.apiKey === apiKey) return cached.model;\n\n const base = config.baseUrl.replace(/\\/$/, '');\n\n let model: any;\n if (config.format === 'anthropic') {\n // createAnthropic baseURL should include /v1 — it appends /messages\n const baseURL = base.endsWith('/v1') ? base : base + '/v1';\n const provider = createAnthropic({ apiKey, baseURL });\n model = provider(config.model);\n } else {\n // OpenAI-compatible: baseURL is used as prefix, SDK appends /chat/completions\n const provider = createOpenAICompatible({\n name: 'agon-api',\n apiKey,\n baseURL: base,\n });\n model = provider.chatModel(config.model);\n }\n\n _modelCache.set(cacheKey, { model, apiKey });\n return model;\n}\n\n/**\n * Convert OpenAI-format tool definitions to AI SDK tool format.\n */\n// @kern-source: dispatch:50\nexport function convertToolsForSdk(tools: Array<{type:string,function:{name:string,description:string,parameters:Record<string,unknown>}}>): Record<string,any> {\n const result: Record<string, any> = {};\n for (const t of tools) {\n result[t.function.name] = {\n description: t.function.description,\n inputSchema: jsonSchema(t.function.parameters as any),\n // No execute — tool execution is handled by the caller (persistent-session)\n };\n }\n return result;\n}\n\n/**\n * Normalize tool call IDs per provider: Anthropic requires [a-zA-Z0-9_], Mistral max 9 chars.\n */\n// @kern-source: dispatch:64\nfunction normalizeToolCallId(id: string, format?: string): string {\n if (!id) {\n return `call_${Date.now()}`;\n }\n if (format === 'anthropic') {\n // Claude: alphanumeric + underscore only\n return id.replace(/[^a-zA-Z0-9_]/g, '_');\n }\n // Mistral: max 9 chars, alphanumeric only\n if (format === 'mistral') {\n return id.replace(/[^a-zA-Z0-9]/g, '').slice(0, 9) || `c${Date.now() % 100000000}`;\n }\n return id;\n}\n\n/**\n * Convert Agon message history (OpenAI wire format) to AI SDK CoreMessage format. Handles per-provider normalization.\n */\n// @kern-source: dispatch:77\nexport function convertMessagesForSdk(messages: Array<{role:string,content:any,tool_calls?:any[],tool_call_id?:string}>, format?: string): any[] {\n // Build original→normalized ID mapping, and record only immediately\n // following tool results for each assistant message. The AI SDK requires\n // every assistant tool-call part to be paired by the contiguous tool-result\n // block that follows it. If an interrupted stream left a dangling or\n // non-contiguous assistant tool_call in history, replay it as plain context\n // instead of letting the SDK throw MissingToolResultsError.\n const idMap = new Map<string, string>();\n for (const msg of messages) {\n if (msg.tool_calls) {\n for (const tc of msg.tool_calls) {\n if (tc.id && tc.function?.name) {\n const normalizedId = normalizeToolCallId(tc.id, format);\n idMap.set(tc.id, normalizedId);\n }\n }\n }\n }\n const contiguousResultIdsByAssistantIndex = new Map<number, Set<string>>();\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i] as any;\n if (msg?.role !== 'assistant' || !Array.isArray(msg.tool_calls) || msg.tool_calls.length === 0) continue;\n const resultIds = new Set<string>();\n for (let j = i + 1; j < messages.length; j++) {\n const candidate = messages[j] as any;\n if (candidate?.role !== 'tool') break;\n const originalId = typeof candidate.tool_call_id === 'string' ? candidate.tool_call_id : '';\n if (!originalId) continue;\n resultIds.add(idMap.get(originalId) ?? normalizeToolCallId(originalId, format));\n }\n contiguousResultIdsByAssistantIndex.set(i, resultIds);\n }\n\n const systemParts: string[] = [];\n for (const msg of messages) {\n if (msg.role !== 'system') continue;\n const content = typeof msg.content === 'string' ? msg.content : String(msg.content ?? '');\n if (content.trim()) systemParts.push(content);\n }\n\n const result: any[] = [];\n const activeToolNamesById = new Map<string, string>();\n if (systemParts.length > 0) {\n result.push({ role: 'system', content: systemParts.join('\\n\\n') });\n }\n const pushMessage = (message: any) => {\n const last = result[result.length - 1];\n if (\n message?.role === 'user'\n && last?.role === 'user'\n && typeof message.content === 'string'\n && typeof last.content === 'string'\n ) {\n last.content = `${last.content}\\n\\n${message.content}`;\n return;\n }\n result.push(message);\n };\n\n for (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {\n const msg = messages[messageIndex];\n if (msg.role === 'system') {\n continue;\n } else if (msg.role === 'user') {\n pushMessage({ role: 'user', content: typeof msg.content === 'string' ? msg.content : String(msg.content ?? '') });\n } else if (msg.role === 'assistant') {\n const parts: any[] = [];\n if (msg.content && typeof msg.content === 'string') {\n parts.push({ type: 'text', text: msg.content });\n }\n if (msg.tool_calls) {\n const droppedToolCalls: string[] = [];\n const contiguousResultIds = contiguousResultIdsByAssistantIndex.get(messageIndex) ?? new Set<string>();\n for (const tc of msg.tool_calls) {\n let args: Record<string, unknown> = {};\n try {\n args = typeof tc.function?.arguments === 'string'\n ? JSON.parse(tc.function.arguments)\n : tc.function?.arguments ?? {};\n } catch { args = {}; /* malformed tool_calls JSON — use empty args */ }\n const normalizedId = idMap.get(tc.id) ?? normalizeToolCallId(tc.id ?? `call_${Date.now()}`, format);\n const toolName = tc.function?.name ?? 'unknown';\n if (!contiguousResultIds.has(normalizedId)) {\n droppedToolCalls.push(toolName);\n continue;\n }\n activeToolNamesById.set(normalizedId, toolName);\n parts.push({\n type: 'tool-call',\n toolCallId: normalizedId,\n toolName,\n input: args,\n });\n }\n if (droppedToolCalls.length > 0) {\n parts.push({\n type: 'text',\n text: `[Recovered incomplete tool call${droppedToolCalls.length > 1 ? 's' : ''} omitted from native tool channel: ${droppedToolCalls.join(', ')}]`,\n });\n }\n }\n if (parts.length > 0) {\n pushMessage({ role: 'assistant', content: parts });\n } else {\n pushMessage({ role: 'assistant', content: '' });\n }\n } else if (msg.role === 'tool') {\n const originalId = typeof (msg as any).tool_call_id === 'string' ? (msg as any).tool_call_id : '';\n const toolCallId = originalId ? (idMap.get(originalId) ?? normalizeToolCallId(originalId, format)) : '';\n const toolName = toolCallId ? activeToolNamesById.get(toolCallId) : undefined;\n const outputValue = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content);\n if (!toolCallId || !toolName) {\n pushMessage({\n role: 'user',\n content: `[Recovered orphan tool result omitted from native tool channel]\\n${outputValue}`,\n });\n } else {\n pushMessage({\n role: 'tool',\n content: [{\n type: 'tool-result',\n toolCallId,\n toolName,\n output: {\n type: 'text' as const,\n value: outputValue,\n },\n }],\n });\n activeToolNamesById.delete(toolCallId);\n }\n }\n }\n\n // Mistral quirk: needs a dummy assistant message after consecutive tool results\n if (format === 'mistral') {\n for (let i = 1; i < result.length; i++) {\n if (result[i].role === 'tool' && result[i - 1].role === 'tool') {\n result.splice(i, 0, { role: 'assistant', content: '' });\n i++;\n }\n }\n }\n\n return result;\n}\n\n// @kern-source: dispatch:226\nexport async function apiDispatch(config: ApiConfig, prompt: string, timeout: number, signal?: AbortSignal, systemPrompt?: string): Promise<DispatchResult> {\n const model = buildModel(config);\n if (!model) {\n return {\n exitCode: 1,\n stdout: '',\n stderr: `Missing API key: set ${config.apiKeyEnv} environment variable`,\n durationMs: 0,\n timedOut: false,\n };\n }\n\n const startTime = Date.now();\n const messages: Array<{role: 'system'|'user', content: string}> = [];\n if (systemPrompt) messages.push({ role: 'system', content: systemPrompt });\n messages.push({ role: 'user', content: prompt });\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout * 1000);\n if (signal) {\n if (signal.aborted) { clearTimeout(timer); return { exitCode: 130, stdout: '', stderr: 'Aborted', durationMs: 0, timedOut: false }; }\n signal.addEventListener('abort', () => controller.abort(), { once: true });\n }\n\n try {\n const result = await generateText({\n model,\n messages,\n maxOutputTokens: config.maxTokens ?? 4096,\n abortSignal: controller.signal,\n maxRetries: 5,\n });\n clearTimeout(timer);\n const text = result.text || '';\n const usage = result.usage ? {\n promptTokens: result.usage.inputTokens ?? 0,\n completionTokens: result.usage.outputTokens ?? 0,\n totalTokens: (result.usage.inputTokens ?? 0) + (result.usage.outputTokens ?? 0),\n source: 'sdk' as const,\n } : undefined;\n return { exitCode: 0, stdout: text, stderr: '', durationMs: Date.now() - startTime, timedOut: false, usage };\n } catch (err) {\n clearTimeout(timer);\n const durationMs = Date.now() - startTime;\n if (err instanceof Error && err.name === 'AbortError') {\n return { exitCode: signal?.aborted ? 130 : 124, stdout: '', stderr: 'Request timed out', durationMs, timedOut: !signal?.aborted };\n }\n const isRateLimited = err instanceof Error && (\n err.message.includes('429') || err.message.includes('rate') || err.name === 'AI_RetryError' || err.name === 'RetryError'\n );\n const exitCode = isRateLimited ? 2 : 1;\n const prefix = isRateLimited ? 'API rate limited (retries exhausted)' : 'API request failed';\n return { exitCode, stdout: '', stderr: `${prefix}: ${err instanceof Error ? err.message : String(err)}`, durationMs, timedOut: false };\n }\n}\n\nexport async function* apiStreamDispatch(config: ApiConfig, prompt: string, timeout: number, signal?: AbortSignal, systemPrompt?: string): AsyncGenerator<string, DispatchResult, void> {\n const messages: Array<{role:string, content:string}> = [];\n if (systemPrompt) {\n messages.push({ role: 'system', content: systemPrompt });\n }\n messages.push({ role: 'user', content: prompt });\n return yield * apiStreamDispatchWithHistory(config, messages, timeout, signal);\n}\n\n// @kern-source: dispatch:297\nexport const _formatHintEmitted: Set<string> = new Set<string>();\n\n/**\n * Detect a common misconfiguration: format='anthropic' on a non-Anthropic base URL. Moonshot/Kimi/Groq/Together/DeepInfra etc. claim Anthropic compatibility loosely but actually serve OpenAI-shaped /chat/completions. Returns a one-line hint the first time we hit it for a given host, then null on subsequent calls for that host.\n */\n// @kern-source: dispatch:299\nfunction formatMismatchHint(config: ApiConfig): string|null {\n if (config.format !== 'anthropic') {\n return null;\n }\n try {\n const host = new URL(config.baseUrl).host.toLowerCase();\n if (host === 'api.anthropic.com' || host.endsWith('.anthropic.com')) {\n return null;\n }\n if (_formatHintEmitted.has(host)) {\n return null;\n }\n _formatHintEmitted.add(host);\n return `tip: format='anthropic' on '${host}' — many OpenAI-compat providers (Moonshot/Kimi, Groq, Together, DeepInfra) claim Anthropic but serve OpenAI /chat/completions. Try format='openai' (or remove the field) in the engine config.`;\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Streaming dispatch with full message history + optional native function calling. Uses Vercel AI SDK for robust SSE handling and provider abstraction.\n */\nexport async function* apiStreamDispatchWithHistory(config: ApiConfig, messages: Array<{role:string,content:any,tool_calls?:any[],tool_call_id?:string}>, timeout: number, signal?: AbortSignal, tools?: Array<{type:string,function:{name:string,description:string,parameters:Record<string,unknown>}}>): AsyncGenerator<string, DispatchResult, void> {\n const model = buildModel(config);\n if (!model) {\n return { exitCode: 1, stdout: '', stderr: `Missing API key: set ${config.apiKeyEnv}`, durationMs: 0, timedOut: false };\n }\n\n const startTime = Date.now();\n\n // Convert messages to AI SDK CoreMessage format\n // Detect provider format for per-provider normalization\n const providerFormat = config.format === 'anthropic' ? 'anthropic'\n : config.baseUrl?.includes('mistral') ? 'mistral'\n : undefined;\n const coreMessages = convertMessagesForSdk(messages, providerFormat);\n\n // Set up timeout + external abort\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout * 1000);\n if (signal) {\n if (signal.aborted) { clearTimeout(timer); return { exitCode: 130, stdout: '', stderr: 'Aborted', durationMs: 0, timedOut: false }; }\n signal.addEventListener('abort', () => controller.abort(), { once: true });\n }\n\n let stdout = '';\n // Capture structured parts at stream time — compaction folds over these\n // instead of doing fragile regex extraction on flat text\n const capturedParts: Array<{kind:'text',text:string}|{kind:'reasoning',text:string}|{kind:'tool_call',toolName:string,toolCallId:string,args:Record<string,unknown>}> = [];\n let currentTextBuf = '';\n let currentReasoningBuf = '';\n\n try {\n const streamOpts: any = {\n model,\n messages: coreMessages,\n maxOutputTokens: config.maxTokens ?? 4096,\n abortSignal: controller.signal,\n maxRetries: 5,\n };\n\n if (tools && tools.length > 0) {\n streamOpts.tools = convertToolsForSdk(tools);\n }\n\n // Apply Anthropic cache control: mark system + last 2 messages as ephemeral\n // This saves input tokens on multi-turn conversations\n if (config.format === 'anthropic' && coreMessages.length > 0) {\n // Cache system prompt (stable across turns)\n for (const msg of coreMessages) {\n if ((msg as any).role === 'system') {\n (msg as any).experimental_providerMetadata = {\n anthropic: { cacheControl: { type: 'ephemeral' } },\n };\n break;\n }\n }\n // Cache last 2 user/assistant messages (recent context)\n let cached = 0;\n for (let i = coreMessages.length - 1; i >= 0 && cached < 2; i--) {\n const role = (coreMessages[i] as any).role;\n if (role === 'user' || role === 'assistant') {\n (coreMessages[i] as any).experimental_providerMetadata = {\n anthropic: { cacheControl: { type: 'ephemeral' } },\n };\n cached++;\n }\n }\n }\n\n const result = streamText(streamOpts);\n\n // Two-tier idle timeout: longer patience before first chunk (queuing/cold start),\n // tighter watchdog once streaming starts. Per-engine config overrides defaults.\n // IDLE_TIMEOUT was 15s, which killed API engines during silent reasoning or\n // tool-call phases — a real failure mode observed in agon forge where gemini,\n // kimi-for-coding, and zai-coding produced zero diff because their stream\n // went quiet for >15s while internally working. 90s gives coding engines\n // room to think without breaking the safety net for genuinely hung streams.\n const FIRST_CHUNK_TIMEOUT = config.firstChunkTimeoutMs ?? 60_000; // 60s default\n const IDLE_TIMEOUT = config.idleTimeoutMs ?? 90_000; // 90s default\n const iterator = result.fullStream[Symbol.asyncIterator]();\n let iterDone = false;\n let gotFirstChunk = false;\n\n while (!iterDone) {\n const timeoutMs = gotFirstChunk ? IDLE_TIMEOUT : FIRST_CHUNK_TIMEOUT;\n const next = iterator.next();\n const idle = new Promise<never>((_, reject) => {\n const t = setTimeout(() => reject(new Error('IDLE_TIMEOUT')), timeoutMs);\n next.then(() => clearTimeout(t), () => clearTimeout(t));\n });\n\n let iterResult: IteratorResult<any>;\n try {\n iterResult = await Promise.race([next, idle]);\n } catch (err: any) {\n if (err?.message === 'IDLE_TIMEOUT') {\n const phase = gotFirstChunk ? 'inter-chunk' : 'first-chunk';\n console.warn(`[agon] api-dispatch: ${phase} idle timeout (${timeoutMs / 1000}s) — breaking stream`);\n // First-chunk timeout on a non-Anthropic host using Anthropic format is almost\n // always a config mismatch — surface the hint via stderr so the session UI picks it up.\n if (!gotFirstChunk) {\n const hint = formatMismatchHint(config);\n if (hint) {\n clearTimeout(timer);\n controller.abort();\n return { exitCode: 1, stdout, stderr: `API first-chunk timeout (${timeoutMs / 1000}s). ${hint}`, durationMs: Date.now() - startTime, timedOut: true };\n }\n }\n controller.abort();\n break;\n }\n throw err;\n }\n\n if (iterResult.done) { iterDone = true; break; }\n const part = iterResult.value;\n\n // Any productive event switches to tighter inter-chunk timeout\n if (!gotFirstChunk && (part.type === 'text-delta' || part.type === 'reasoning-delta' || part.type === 'tool-call')) {\n gotFirstChunk = true;\n }\n\n switch (part.type) {\n case 'text-delta': {\n const text = (part as any).text;\n stdout += text;\n currentTextBuf += text;\n yield text;\n break;\n }\n case 'reasoning-delta': {\n const text = (part as any).delta ?? '';\n if (text) {\n currentReasoningBuf += text;\n }\n break;\n }\n case 'tool-call': {\n // Flush accumulated text/reasoning buffers as parts\n if (currentTextBuf) {\n capturedParts.push({ kind: 'text', text: currentTextBuf });\n currentTextBuf = '';\n }\n if (currentReasoningBuf) {\n capturedParts.push({ kind: 'reasoning', text: currentReasoningBuf });\n currentReasoningBuf = '';\n }\n // Capture tool call as structured part\n const toolName = (part as any).toolName ?? 'unknown';\n const toolCallId = (part as any).toolCallId ?? `call_${Date.now()}`;\n const toolInput = (part as any).input ?? {};\n capturedParts.push({ kind: 'tool_call', toolName, toolCallId, args: toolInput });\n\n // Emit as <tool> marker matching Agon's parseToolCalls regex\n const marker = `\\n<tool name=\"${toolName}\">${JSON.stringify(toolInput)}</tool>\\n`;\n stdout += marker;\n yield marker;\n break;\n }\n case 'error': {\n clearTimeout(timer);\n return { exitCode: 1, stdout, stderr: `Stream error: ${String((part as any).error)}`, durationMs: Date.now() - startTime, timedOut: false };\n }\n }\n }\n\n // Flush final text/reasoning buffers\n if (currentTextBuf) capturedParts.push({ kind: 'text', text: currentTextBuf });\n if (currentReasoningBuf) capturedParts.push({ kind: 'reasoning', text: currentReasoningBuf });\n\n clearTimeout(timer);\n\n let usage: DispatchResult['usage'] = undefined;\n try {\n const finalUsage = await (result as any).usage;\n if (finalUsage) {\n usage = {\n promptTokens: finalUsage.inputTokens ?? 0,\n completionTokens: finalUsage.outputTokens ?? 0,\n totalTokens: (finalUsage.inputTokens ?? 0) + (finalUsage.outputTokens ?? 0),\n source: 'sdk' as const,\n };\n }\n } catch { /* usage tokens optional — extraction failure is non-critical */ }\n return { exitCode: 0, stdout, stderr: '', durationMs: Date.now() - startTime, timedOut: false, usage, parts: capturedParts };\n } catch (err) {\n clearTimeout(timer);\n const durationMs = Date.now() - startTime;\n if (err instanceof Error && err.name === 'AbortError') {\n return { exitCode: signal?.aborted ? 130 : 124, stdout, stderr: 'Request timed out', durationMs, timedOut: !signal?.aborted };\n }\n const isRateLimited = err instanceof Error && (\n err.message.includes('429') || err.message.includes('rate') || err.name === 'AI_RetryError' || err.name === 'RetryError'\n );\n const exitCode = isRateLimited ? 2 : 1;\n const prefix = isRateLimited ? 'API rate limited (retries exhausted)' : 'API stream failed';\n const baseMsg = `${prefix}: ${err instanceof Error ? err.message : String(err)}`;\n // Anthropic-format on non-Anthropic host is a common misconfig — append a hint\n // so the user sees it in the error toast instead of silently falling back every turn.\n const hint = stdout.length === 0 && !isRateLimited ? formatMismatchHint(config) : null;\n return { exitCode, stdout, stderr: hint ? `${baseMsg}\\n${hint}` : baseMsg, durationMs, timedOut: false };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAS,YAAY,cAAc,kBAAkB;AAErD,SAAS,8BAA8B;AAEvC,SAAS,uBAAuB;AAgBzB,IAAM,cAAsD,oBAAI,IAAuC;AAMvG,SAAS,WAAW,QAAwB;AACjD,QAAM,SAAS,QAAQ,IAAI,OAAO,SAAS;AAC3C,MAAI,CAAC,OAAQ,QAAO;AAEpB,QAAM,WAAW,GAAG,OAAO,OAAO,IAAI,OAAO,KAAK,IAAI,OAAO,UAAU,QAAQ;AAC/E,QAAM,SAAS,YAAY,IAAI,QAAQ;AACvC,MAAI,UAAU,OAAO,WAAW,OAAQ,QAAO,OAAO;AAEtD,QAAM,OAAO,OAAO,QAAQ,QAAQ,OAAO,EAAE;AAE7C,MAAI;AACJ,MAAI,OAAO,WAAW,aAAa;AAEjC,UAAM,UAAU,KAAK,SAAS,KAAK,IAAI,OAAO,OAAO;AACrD,UAAM,WAAW,gBAAgB,EAAE,QAAQ,QAAQ,CAAC;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C;AAG9E,UAAM,OAAO,OAAO,WAAW,KAAK,CAAC,gBAAgB,mBAAmB,MAAM,IAAI;AAClF,WAAO,EAAE,UAAU,QAAQ,QAAQ,OAAO,GAAG,OAAO;AAAA,EAAK,IAAI,KAAK,SAAS,YAAY,UAAU,MAAM;AAAA,EACzG;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../core/src/generated/api/dispatch.ts"],"sourcesContent":["// @generated by kern v3.5.7 — DO NOT EDIT. Source: src/kern/api/dispatch.kern\n\n// @kern-source: dispatch:283\n// @kern-source: dispatch:315\n\nimport { streamText, generateText, jsonSchema } from 'ai';\n\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\n\nimport { createAnthropic } from '@ai-sdk/anthropic';\n\nimport type { DispatchResult } from '../models/types.js';\n\n// @kern-source: dispatch:6\nexport interface ApiConfig {\n baseUrl: string;\n apiKeyEnv: string;\n model: string;\n maxTokens?: number;\n format?: 'openai'|'anthropic';\n firstChunkTimeoutMs?: number;\n idleTimeoutMs?: number;\n}\n\n// @kern-source: dispatch:16\nexport const _modelCache: Map<string,{model:any, apiKey:string}> = new Map<string,{model:any, apiKey:string}>();\n\n/**\n * Create AI SDK model instance from ApiConfig — routes to openai-compatible or anthropic provider. Cached by baseUrl+model+format; invalidated if API key changes.\n */\n// @kern-source: dispatch:18\nexport function buildModel(config: ApiConfig): any {\n const apiKey = process.env[config.apiKeyEnv];\n if (!apiKey) return null;\n\n const cacheKey = `${config.baseUrl}|${config.model}|${config.format ?? 'openai'}`;\n const cached = _modelCache.get(cacheKey);\n if (cached && cached.apiKey === apiKey) return cached.model;\n\n const base = config.baseUrl.replace(/\\/$/, '');\n\n let model: any;\n if (config.format === 'anthropic') {\n // createAnthropic baseURL should include /v1 — it appends /messages\n const baseURL = base.endsWith('/v1') ? base : base + '/v1';\n const provider = createAnthropic({ apiKey, baseURL });\n model = provider(config.model);\n } else {\n // OpenAI-compatible: baseURL is used as prefix, SDK appends /chat/completions\n const provider = createOpenAICompatible({\n name: 'agon-api',\n apiKey,\n baseURL: base,\n });\n model = provider.chatModel(config.model);\n }\n\n _modelCache.set(cacheKey, { model, apiKey });\n return model;\n}\n\n/**\n * Convert OpenAI-format tool definitions to AI SDK tool format.\n */\n// @kern-source: dispatch:50\nexport function convertToolsForSdk(tools: Array<{type:string,function:{name:string,description:string,parameters:Record<string,unknown>}}>): Record<string,any> {\n const result: Record<string, any> = {};\n for (const t of tools) {\n result[t.function.name] = {\n description: t.function.description,\n inputSchema: jsonSchema(t.function.parameters as any),\n // No execute — tool execution is handled by the caller (persistent-session)\n };\n }\n return result;\n}\n\n/**\n * Normalize tool call IDs per provider: Anthropic requires [a-zA-Z0-9_], Mistral max 9 chars.\n */\n// @kern-source: dispatch:64\nfunction normalizeToolCallId(id: string, format?: string): string {\n if (!id) {\n return `call_${Date.now()}`;\n }\n if (format === 'anthropic') {\n // Claude: alphanumeric + underscore only\n return id.replace(/[^a-zA-Z0-9_]/g, '_');\n }\n // Mistral: max 9 chars, alphanumeric only\n if (format === 'mistral') {\n return id.replace(/[^a-zA-Z0-9]/g, '').slice(0, 9) || `c${Date.now() % 100000000}`;\n }\n return id;\n}\n\n/**\n * Convert Agon message history (OpenAI wire format) to AI SDK CoreMessage format. Handles per-provider normalization.\n */\n// @kern-source: dispatch:77\nexport function convertMessagesForSdk(messages: Array<{role:string,content:any,tool_calls?:any[],tool_call_id?:string}>, format?: string): any[] {\n // Build original→normalized ID mapping, and record only immediately\n // following tool results for each assistant message. The AI SDK requires\n // every assistant tool-call part to be paired by the contiguous tool-result\n // block that follows it. If an interrupted stream left a dangling or\n // non-contiguous assistant tool_call in history, replay it as plain context\n // instead of letting the SDK throw MissingToolResultsError.\n const idMap = new Map<string, string>();\n for (const msg of messages) {\n if (msg.tool_calls) {\n for (const tc of msg.tool_calls) {\n if (tc.id && tc.function?.name) {\n const normalizedId = normalizeToolCallId(tc.id, format);\n idMap.set(tc.id, normalizedId);\n }\n }\n }\n }\n const contiguousResultIdsByAssistantIndex = new Map<number, Set<string>>();\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i] as any;\n if (msg?.role !== 'assistant' || !Array.isArray(msg.tool_calls) || msg.tool_calls.length === 0) continue;\n const resultIds = new Set<string>();\n for (let j = i + 1; j < messages.length; j++) {\n const candidate = messages[j] as any;\n if (candidate?.role !== 'tool') break;\n const originalId = typeof candidate.tool_call_id === 'string' ? candidate.tool_call_id : '';\n if (!originalId) continue;\n resultIds.add(idMap.get(originalId) ?? normalizeToolCallId(originalId, format));\n }\n contiguousResultIdsByAssistantIndex.set(i, resultIds);\n }\n\n const systemParts: string[] = [];\n for (const msg of messages) {\n if (msg.role !== 'system') continue;\n const content = typeof msg.content === 'string' ? msg.content : String(msg.content ?? '');\n if (content.trim()) systemParts.push(content);\n }\n\n const result: any[] = [];\n const activeToolNamesById = new Map<string, string>();\n if (systemParts.length > 0) {\n result.push({ role: 'system', content: systemParts.join('\\n\\n') });\n }\n const pushMessage = (message: any) => {\n const last = result[result.length - 1];\n if (\n message?.role === 'user'\n && last?.role === 'user'\n && typeof message.content === 'string'\n && typeof last.content === 'string'\n ) {\n last.content = `${last.content}\\n\\n${message.content}`;\n return;\n }\n result.push(message);\n };\n\n for (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {\n const msg = messages[messageIndex];\n if (msg.role === 'system') {\n continue;\n } else if (msg.role === 'user') {\n pushMessage({ role: 'user', content: typeof msg.content === 'string' ? msg.content : String(msg.content ?? '') });\n } else if (msg.role === 'assistant') {\n const parts: any[] = [];\n if (msg.content && typeof msg.content === 'string') {\n parts.push({ type: 'text', text: msg.content });\n }\n if (msg.tool_calls) {\n const droppedToolCalls: string[] = [];\n const contiguousResultIds = contiguousResultIdsByAssistantIndex.get(messageIndex) ?? new Set<string>();\n for (const tc of msg.tool_calls) {\n let args: Record<string, unknown> = {};\n try {\n args = typeof tc.function?.arguments === 'string'\n ? JSON.parse(tc.function.arguments)\n : tc.function?.arguments ?? {};\n } catch { args = {}; /* malformed tool_calls JSON — use empty args */ }\n const normalizedId = idMap.get(tc.id) ?? normalizeToolCallId(tc.id ?? `call_${Date.now()}`, format);\n const toolName = tc.function?.name ?? 'unknown';\n if (!contiguousResultIds.has(normalizedId)) {\n droppedToolCalls.push(toolName);\n continue;\n }\n activeToolNamesById.set(normalizedId, toolName);\n parts.push({\n type: 'tool-call',\n toolCallId: normalizedId,\n toolName,\n input: args,\n });\n }\n if (droppedToolCalls.length > 0) {\n parts.push({\n type: 'text',\n text: `[Recovered incomplete tool call${droppedToolCalls.length > 1 ? 's' : ''} omitted from native tool channel: ${droppedToolCalls.join(', ')}]`,\n });\n }\n }\n if (parts.length > 0) {\n pushMessage({ role: 'assistant', content: parts });\n } else {\n pushMessage({ role: 'assistant', content: '' });\n }\n } else if (msg.role === 'tool') {\n const originalId = typeof (msg as any).tool_call_id === 'string' ? (msg as any).tool_call_id : '';\n const toolCallId = originalId ? (idMap.get(originalId) ?? normalizeToolCallId(originalId, format)) : '';\n const toolName = toolCallId ? activeToolNamesById.get(toolCallId) : undefined;\n const outputValue = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content);\n if (!toolCallId || !toolName) {\n pushMessage({\n role: 'user',\n content: `[Recovered orphan tool result omitted from native tool channel]\\n${outputValue}`,\n });\n } else {\n pushMessage({\n role: 'tool',\n content: [{\n type: 'tool-result',\n toolCallId,\n toolName,\n output: {\n type: 'text' as const,\n value: outputValue,\n },\n }],\n });\n activeToolNamesById.delete(toolCallId);\n }\n }\n }\n\n // Mistral quirk: needs a dummy assistant message after consecutive tool results\n if (format === 'mistral') {\n for (let i = 1; i < result.length; i++) {\n if (result[i].role === 'tool' && result[i - 1].role === 'tool') {\n result.splice(i, 0, { role: 'assistant', content: '' });\n i++;\n }\n }\n }\n\n return result;\n}\n\n// @kern-source: dispatch:226\nexport async function apiDispatch(config: ApiConfig, prompt: string, timeout: number, signal?: AbortSignal, systemPrompt?: string): Promise<DispatchResult> {\n const model = buildModel(config);\n if (!model) {\n return {\n exitCode: 1,\n stdout: '',\n stderr: `Missing API key: set ${config.apiKeyEnv} environment variable`,\n durationMs: 0,\n timedOut: false,\n };\n }\n\n const startTime = Date.now();\n const messages: Array<{role: 'system'|'user', content: string}> = [];\n if (systemPrompt) messages.push({ role: 'system', content: systemPrompt });\n messages.push({ role: 'user', content: prompt });\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout * 1000);\n if (signal) {\n if (signal.aborted) { clearTimeout(timer); return { exitCode: 130, stdout: '', stderr: 'Aborted', durationMs: 0, timedOut: false }; }\n signal.addEventListener('abort', () => controller.abort(), { once: true });\n }\n\n try {\n const result = await generateText({\n model,\n messages,\n maxOutputTokens: config.maxTokens ?? 4096,\n abortSignal: controller.signal,\n maxRetries: 5,\n });\n clearTimeout(timer);\n const text = result.text || '';\n const usage = result.usage ? {\n promptTokens: result.usage.inputTokens ?? 0,\n completionTokens: result.usage.outputTokens ?? 0,\n totalTokens: (result.usage.inputTokens ?? 0) + (result.usage.outputTokens ?? 0),\n source: 'sdk' as const,\n } : undefined;\n return { exitCode: 0, stdout: text, stderr: '', durationMs: Date.now() - startTime, timedOut: false, usage };\n } catch (err) {\n clearTimeout(timer);\n const durationMs = Date.now() - startTime;\n if (err instanceof Error && err.name === 'AbortError') {\n return { exitCode: signal?.aborted ? 130 : 124, stdout: '', stderr: 'Request timed out', durationMs, timedOut: !signal?.aborted };\n }\n const isRateLimited = err instanceof Error && (\n err.message.includes('429') || err.message.includes('rate') || err.name === 'AI_RetryError' || err.name === 'RetryError'\n );\n const exitCode = isRateLimited ? 2 : 1;\n const prefix = isRateLimited ? 'API rate limited (retries exhausted)' : 'API request failed';\n return { exitCode, stdout: '', stderr: `${prefix}: ${err instanceof Error ? err.message : String(err)}`, durationMs, timedOut: false };\n }\n}\n\nexport async function* apiStreamDispatch(config: ApiConfig, prompt: string, timeout: number, signal?: AbortSignal, systemPrompt?: string): AsyncGenerator<string, DispatchResult, void> {\n const messages: Array<{role:string, content:string}> = [];\n if (systemPrompt) {\n messages.push({ role: 'system', content: systemPrompt });\n }\n messages.push({ role: 'user', content: prompt });\n return yield * apiStreamDispatchWithHistory(config, messages, timeout, signal);\n}\n\n// @kern-source: dispatch:297\nexport const _formatHintEmitted: Set<string> = new Set<string>();\n\n/**\n * Detect a common misconfiguration: format='anthropic' on a non-Anthropic base URL. Moonshot/Kimi/Groq/Together/DeepInfra etc. claim Anthropic compatibility loosely but actually serve OpenAI-shaped /chat/completions. Returns a one-line hint the first time we hit it for a given host, then null on subsequent calls for that host.\n */\n// @kern-source: dispatch:299\nfunction formatMismatchHint(config: ApiConfig): string|null {\n if (config.format !== 'anthropic') {\n return null;\n }\n try {\n const host = new URL(config.baseUrl).host.toLowerCase();\n if (host === 'api.anthropic.com' || host.endsWith('.anthropic.com')) {\n return null;\n }\n if (_formatHintEmitted.has(host)) {\n return null;\n }\n _formatHintEmitted.add(host);\n return `tip: format='anthropic' on '${host}' — many OpenAI-compat providers (Moonshot/Kimi, Groq, Together, DeepInfra) claim Anthropic but serve OpenAI /chat/completions. Try format='openai' (or remove the field) in the engine config.`;\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Streaming dispatch with full message history + optional native function calling. Uses Vercel AI SDK for robust SSE handling and provider abstraction.\n */\nexport async function* apiStreamDispatchWithHistory(config: ApiConfig, messages: Array<{role:string,content:any,tool_calls?:any[],tool_call_id?:string}>, timeout: number, signal?: AbortSignal, tools?: Array<{type:string,function:{name:string,description:string,parameters:Record<string,unknown>}}>): AsyncGenerator<string, DispatchResult, void> {\n const model = buildModel(config);\n if (!model) {\n return { exitCode: 1, stdout: '', stderr: `Missing API key: set ${config.apiKeyEnv}`, durationMs: 0, timedOut: false };\n }\n\n const startTime = Date.now();\n\n // Convert messages to AI SDK CoreMessage format\n // Detect provider format for per-provider normalization\n const providerFormat = config.format === 'anthropic' ? 'anthropic'\n : config.baseUrl?.includes('mistral') ? 'mistral'\n : undefined;\n const coreMessages = convertMessagesForSdk(messages, providerFormat);\n\n // Set up timeout + external abort\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout * 1000);\n if (signal) {\n if (signal.aborted) { clearTimeout(timer); return { exitCode: 130, stdout: '', stderr: 'Aborted', durationMs: 0, timedOut: false }; }\n signal.addEventListener('abort', () => controller.abort(), { once: true });\n }\n\n let stdout = '';\n // Capture structured parts at stream time — compaction folds over these\n // instead of doing fragile regex extraction on flat text\n const capturedParts: Array<{kind:'text',text:string}|{kind:'reasoning',text:string}|{kind:'tool_call',toolName:string,toolCallId:string,args:Record<string,unknown>}> = [];\n let currentTextBuf = '';\n let currentReasoningBuf = '';\n\n try {\n const streamOpts: any = {\n model,\n messages: coreMessages,\n maxOutputTokens: config.maxTokens ?? 4096,\n abortSignal: controller.signal,\n maxRetries: 5,\n };\n\n if (tools && tools.length > 0) {\n streamOpts.tools = convertToolsForSdk(tools);\n }\n\n // Apply Anthropic cache control: mark system + last 2 messages as ephemeral\n // This saves input tokens on multi-turn conversations\n if (config.format === 'anthropic' && coreMessages.length > 0) {\n // Cache system prompt (stable across turns)\n for (const msg of coreMessages) {\n if ((msg as any).role === 'system') {\n (msg as any).experimental_providerMetadata = {\n anthropic: { cacheControl: { type: 'ephemeral' } },\n };\n break;\n }\n }\n // Cache last 2 user/assistant messages (recent context)\n let cached = 0;\n for (let i = coreMessages.length - 1; i >= 0 && cached < 2; i--) {\n const role = (coreMessages[i] as any).role;\n if (role === 'user' || role === 'assistant') {\n (coreMessages[i] as any).experimental_providerMetadata = {\n anthropic: { cacheControl: { type: 'ephemeral' } },\n };\n cached++;\n }\n }\n }\n\n const result = streamText(streamOpts);\n\n // Two-tier idle timeout: longer patience before first chunk (queuing/cold start),\n // tighter watchdog once streaming starts. Per-engine config overrides defaults.\n // IDLE_TIMEOUT was 15s, which killed API engines during silent reasoning or\n // tool-call phases — a real failure mode observed in agon forge where gemini,\n // kimi-for-coding, and zai-coding produced zero diff because their stream\n // went quiet for >15s while internally working. 90s gives coding engines\n // room to think without breaking the safety net for genuinely hung streams.\n const FIRST_CHUNK_TIMEOUT = config.firstChunkTimeoutMs ?? 60_000; // 60s default\n const IDLE_TIMEOUT = config.idleTimeoutMs ?? 90_000; // 90s default\n const iterator = result.fullStream[Symbol.asyncIterator]();\n let iterDone = false;\n let gotFirstChunk = false;\n\n while (!iterDone) {\n const timeoutMs = gotFirstChunk ? IDLE_TIMEOUT : FIRST_CHUNK_TIMEOUT;\n const next = iterator.next();\n const idle = new Promise<never>((_, reject) => {\n const t = setTimeout(() => reject(new Error('IDLE_TIMEOUT')), timeoutMs);\n next.then(() => clearTimeout(t), () => clearTimeout(t));\n });\n\n let iterResult: IteratorResult<any>;\n try {\n iterResult = await Promise.race([next, idle]);\n } catch (err: any) {\n if (err?.message === 'IDLE_TIMEOUT') {\n const phase = gotFirstChunk ? 'inter-chunk' : 'first-chunk';\n console.warn(`[agon] api-dispatch: ${phase} idle timeout (${timeoutMs / 1000}s) — breaking stream`);\n // First-chunk timeout on a non-Anthropic host using Anthropic format is almost\n // always a config mismatch — surface the hint via stderr so the session UI picks it up.\n if (!gotFirstChunk) {\n const hint = formatMismatchHint(config);\n if (hint) {\n clearTimeout(timer);\n controller.abort();\n return { exitCode: 1, stdout, stderr: `API first-chunk timeout (${timeoutMs / 1000}s). ${hint}`, durationMs: Date.now() - startTime, timedOut: true };\n }\n }\n controller.abort();\n break;\n }\n throw err;\n }\n\n if (iterResult.done) { iterDone = true; break; }\n const part = iterResult.value;\n\n // Any productive event switches to tighter inter-chunk timeout\n if (!gotFirstChunk && (part.type === 'text-delta' || part.type === 'reasoning-delta' || part.type === 'tool-call')) {\n gotFirstChunk = true;\n }\n\n switch (part.type) {\n case 'text-delta': {\n const text = (part as any).text;\n stdout += text;\n currentTextBuf += text;\n yield text;\n break;\n }\n case 'reasoning-delta': {\n const text = (part as any).delta ?? '';\n if (text) {\n currentReasoningBuf += text;\n }\n break;\n }\n case 'tool-call': {\n // Flush accumulated text/reasoning buffers as parts\n if (currentTextBuf) {\n capturedParts.push({ kind: 'text', text: currentTextBuf });\n currentTextBuf = '';\n }\n if (currentReasoningBuf) {\n capturedParts.push({ kind: 'reasoning', text: currentReasoningBuf });\n currentReasoningBuf = '';\n }\n // Capture tool call as structured part\n const toolName = (part as any).toolName ?? 'unknown';\n const toolCallId = (part as any).toolCallId ?? `call_${Date.now()}`;\n const toolInput = (part as any).input ?? {};\n capturedParts.push({ kind: 'tool_call', toolName, toolCallId, args: toolInput });\n\n // Emit as <tool> marker matching Agon's parseToolCalls regex\n const marker = `\\n<tool name=\"${toolName}\">${JSON.stringify(toolInput)}</tool>\\n`;\n stdout += marker;\n yield marker;\n break;\n }\n case 'error': {\n clearTimeout(timer);\n const errStr = String((part as any).error);\n // A 404/not-found before any output is almost always a wrong baseUrl\n // path or a wire-format mismatch (e.g. format='anthropic' on a host\n // whose Anthropic endpoint isn't at /v1/messages — MiniMax, etc.).\n // Surface the actionable hint inline so the user sees the fix rather\n // than a bare 404. (Same hint the idle-timeout + catch paths use.)\n // NOTE: deliberately narrower than brain.kern's deterministic-retry\n // classifier (which also matches 401/403/auth). The format hint says\n // \"try format='openai'\", which is right for a wrong-path/format 404\n // but MISLEADING on a genuine auth 401 — those already get brain.kern's\n // \"check /engines\" hint instead. Do NOT broaden this to auth codes.\n const routingShaped = stdout.length === 0 && /\\b404\\b|not found|no such (?:route|endpoint)/i.test(errStr);\n const hint = routingShaped ? formatMismatchHint(config) : null;\n return { exitCode: 1, stdout, stderr: hint ? `Stream error: ${errStr}\\n${hint}` : `Stream error: ${errStr}`, durationMs: Date.now() - startTime, timedOut: false };\n }\n }\n }\n\n // Flush final text/reasoning buffers\n if (currentTextBuf) capturedParts.push({ kind: 'text', text: currentTextBuf });\n if (currentReasoningBuf) capturedParts.push({ kind: 'reasoning', text: currentReasoningBuf });\n\n clearTimeout(timer);\n\n let usage: DispatchResult['usage'] = undefined;\n try {\n const finalUsage = await (result as any).usage;\n if (finalUsage) {\n usage = {\n promptTokens: finalUsage.inputTokens ?? 0,\n completionTokens: finalUsage.outputTokens ?? 0,\n totalTokens: (finalUsage.inputTokens ?? 0) + (finalUsage.outputTokens ?? 0),\n source: 'sdk' as const,\n };\n }\n } catch { /* usage tokens optional — extraction failure is non-critical */ }\n return { exitCode: 0, stdout, stderr: '', durationMs: Date.now() - startTime, timedOut: false, usage, parts: capturedParts };\n } catch (err) {\n clearTimeout(timer);\n const durationMs = Date.now() - startTime;\n if (err instanceof Error && err.name === 'AbortError') {\n return { exitCode: signal?.aborted ? 130 : 124, stdout, stderr: 'Request timed out', durationMs, timedOut: !signal?.aborted };\n }\n const isRateLimited = err instanceof Error && (\n err.message.includes('429') || err.message.includes('rate') || err.name === 'AI_RetryError' || err.name === 'RetryError'\n );\n const exitCode = isRateLimited ? 2 : 1;\n const prefix = isRateLimited ? 'API rate limited (retries exhausted)' : 'API stream failed';\n const baseMsg = `${prefix}: ${err instanceof Error ? err.message : String(err)}`;\n // Anthropic-format on non-Anthropic host is a common misconfig — append a hint\n // so the user sees it in the error toast instead of silently falling back every turn.\n const hint = stdout.length === 0 && !isRateLimited ? formatMismatchHint(config) : null;\n return { exitCode, stdout, stderr: hint ? `${baseMsg}\\n${hint}` : baseMsg, durationMs, timedOut: false };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAS,YAAY,cAAc,kBAAkB;AAErD,SAAS,8BAA8B;AAEvC,SAAS,uBAAuB;AAgBzB,IAAM,cAAsD,oBAAI,IAAuC;AAMvG,SAAS,WAAW,QAAwB;AACjD,QAAM,SAAS,QAAQ,IAAI,OAAO,SAAS;AAC3C,MAAI,CAAC,OAAQ,QAAO;AAEpB,QAAM,WAAW,GAAG,OAAO,OAAO,IAAI,OAAO,KAAK,IAAI,OAAO,UAAU,QAAQ;AAC/E,QAAM,SAAS,YAAY,IAAI,QAAQ;AACvC,MAAI,UAAU,OAAO,WAAW,OAAQ,QAAO,OAAO;AAEtD,QAAM,OAAO,OAAO,QAAQ,QAAQ,OAAO,EAAE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qBAAqB,YAAY,UAAU,CAAC,QAAQ,QAAQ;AAAA,IAC9H;AACA,UAAM,gBAAgB,eAAe,UACnC,IAAI,QAAQ,SAAS,KAAK,KAAK,IAAI,QAAQ,SAAS,MAAM,KAAK,IAAI,SAAS,mBAAmB,IAAI,SAAS;AAE9G,UAAM,WAAW,gBAAgB,IAAI;AACrC,UAAM,SAAS,gBAAgB,yCAAyC;AACxE,UAAM,UAAU,GAAG,MAAM,KAAK,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAG9E,UAAM,OAAO,OAAO,WAAW,KAAK,CAAC,gBAAgB,mBAAmB,MAAM,IAAI;AAClF,WAAO,EAAE,UAAU,QAAQ,QAAQ,OAAO,GAAG,OAAO;AAAA,EAAK,IAAI,KAAK,SAAS,YAAY,UAAU,MAAM;AAAA,EACzG;AACF;","names":[]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
__require,
|
|
6
6
|
__toCommonJS,
|
|
7
7
|
apiStreamDispatchWithHistory
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-5QMVQPHY.js";
|
|
9
9
|
|
|
10
10
|
// ../core/src/generated/signals/glicko.ts
|
|
11
11
|
var glicko_exports = {};
|
|
@@ -23878,7 +23878,7 @@ ${newSummary.decisions.map((d) => ` - ${d}`).join("\n")}` : "",
|
|
|
23878
23878
|
const tier3CompactionEnabled = process.env.AGON_DISABLE_TIER3_COMPACTION !== "1";
|
|
23879
23879
|
if (tier3CompactionEnabled && afterTier2 > CONTEXT_LIMIT - COMPACTION_BUFFER && config2.engine.api) {
|
|
23880
23880
|
try {
|
|
23881
|
-
const { apiDispatch: apiDispatch2 } = await import("./dispatch-
|
|
23881
|
+
const { apiDispatch: apiDispatch2 } = await import("./dispatch-6LQSMMGI.js");
|
|
23882
23882
|
const compactionPrompt = `Summarize this conversation context into a concise briefing. Preserve: the user's goal, key discoveries, files read/modified, important decisions, and current progress. Drop: verbose tool outputs, repeated attempts, and pleasantries.
|
|
23883
23883
|
|
|
23884
23884
|
CONTEXT TO SUMMARIZE:
|
|
@@ -29106,4 +29106,4 @@ export {
|
|
|
29106
29106
|
predictTeamRating,
|
|
29107
29107
|
updateTeamElo
|
|
29108
29108
|
};
|
|
29109
|
-
//# sourceMappingURL=chunk-
|
|
29109
|
+
//# sourceMappingURL=chunk-7PMMOQZ7.js.map
|