@dreb/agent-core 2.60.1 → 2.61.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/README.md +1 -1
- package/dist/agent-loop.d.ts.map +1 -1
- package/dist/agent-loop.js +3 -1
- package/dist/agent-loop.js.map +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -150,7 +150,7 @@ const agent = new Agent({
|
|
|
150
150
|
initialState: {
|
|
151
151
|
systemPrompt: string,
|
|
152
152
|
model: Model<any>,
|
|
153
|
-
thinkingLevel: "off" | "minimal" | "low" | "medium" | "high" | "xhigh",
|
|
153
|
+
thinkingLevel: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max",
|
|
154
154
|
tools: AgentTool<any>[],
|
|
155
155
|
messages: AgentMessage[],
|
|
156
156
|
},
|
package/dist/agent-loop.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-loop.d.ts","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAIN,WAAW,EAKX,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EACX,YAAY,EACZ,UAAU,EACV,eAAe,EACf,YAAY,EAIZ,QAAQ,EAER,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAQzE;;;GAGG;AACH,wBAAgB,SAAS,CACxB,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAiBzC;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAChC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAwBzC;AAED,wBAAsB,YAAY,CACjC,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,YAAY,EAAE,CAAC,CAoBzB;AAED,wBAAsB,oBAAoB,CACzC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,YAAY,EAAE,CAAC,CAqBzB","sourcesContent":["/**\n * Agent loop that works with AgentMessage throughout.\n * Transforms to Message[] only at the LLM call boundary.\n */\n\nimport {\n\ttype AssistantMessage,\n\ttype Context,\n\tDEFAULT_MAX_OUTPUT_TOKENS,\n\tEventStream,\n\tstreamSimple,\n\tsupportsXhigh,\n\ttype ToolResultMessage,\n\tvalidateToolArguments,\n} from \"@dreb/ai\";\nimport type {\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolCall,\n\tAgentToolResult,\n\tStreamFn,\n\tThinkingLevel,\n} from \"./types.js\";\n\nexport type AgentEventSink = (event: AgentEvent) => Promise<void> | void;\n\nfunction getEffectiveThinkingLevel(config: AgentLoopConfig): ThinkingLevel {\n\tconst requested = config.reasoning ?? \"off\";\n\tif (!config.model.reasoning) return \"off\";\n\treturn requested === \"xhigh\" && !supportsXhigh(config.model) ? \"high\" : requested;\n}\n\n/**\n * Start an agent loop with a new prompt message.\n * The prompt is added to the context and events are emitted for it.\n */\nexport function agentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tconst stream = createAgentStream();\n\n\tvoid runAgentLoop(\n\t\tprompts,\n\t\tcontext,\n\t\tconfig,\n\t\tasync (event) => {\n\t\t\tstream.push(event);\n\t\t},\n\t\tsignal,\n\t\tstreamFn,\n\t).then((messages) => {\n\t\tstream.end(messages);\n\t});\n\n\treturn stream;\n}\n\n/**\n * Continue an agent loop from the current context without adding a new message.\n * Used for retries - context already has user message or tool results.\n *\n * **Important:** The last message in context must convert to a `user` or `toolResult` message\n * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.\n * This cannot be validated here since `convertToLlm` is only called once per turn.\n */\nexport function agentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst stream = createAgentStream();\n\n\tvoid runAgentLoopContinue(\n\t\tcontext,\n\t\tconfig,\n\t\tasync (event) => {\n\t\t\tstream.push(event);\n\t\t},\n\t\tsignal,\n\t\tstreamFn,\n\t).then((messages) => {\n\t\tstream.end(messages);\n\t});\n\n\treturn stream;\n}\n\nexport async function runAgentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tconst newMessages: AgentMessage[] = [...prompts];\n\tconst currentContext: AgentContext = {\n\t\t...context,\n\t\tmessages: [...context.messages, ...prompts],\n\t};\n\n\tawait emit({\n\t\ttype: \"agent_start\",\n\t\tmodel: { provider: config.model.provider, id: config.model.id },\n\t\tthinkingLevel: getEffectiveThinkingLevel(config),\n\t});\n\tawait emit({ type: \"turn_start\" });\n\tfor (const prompt of prompts) {\n\t\tawait emit({ type: \"message_start\", message: prompt });\n\t\tawait emit({ type: \"message_end\", message: prompt });\n\t}\n\n\tawait runLoop(currentContext, newMessages, config, signal, emit, streamFn);\n\treturn newMessages;\n}\n\nexport async function runAgentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst newMessages: AgentMessage[] = [];\n\tconst currentContext: AgentContext = { ...context };\n\n\tawait emit({\n\t\ttype: \"agent_start\",\n\t\tmodel: { provider: config.model.provider, id: config.model.id },\n\t\tthinkingLevel: getEffectiveThinkingLevel(config),\n\t});\n\tawait emit({ type: \"turn_start\" });\n\n\tawait runLoop(currentContext, newMessages, config, signal, emit, streamFn);\n\treturn newMessages;\n}\n\nfunction createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {\n\treturn new EventStream<AgentEvent, AgentMessage[]>(\n\t\t(event: AgentEvent) => event.type === \"agent_end\",\n\t\t(event: AgentEvent) => (event.type === \"agent_end\" ? event.messages : []),\n\t);\n}\n\n/**\n * Main loop logic shared by agentLoop and agentLoopContinue.\n */\nasync function runLoop(\n\tcurrentContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n): Promise<void> {\n\tlet firstTurn = true;\n\tlet endTurnRequested = false;\n\tlet llmCallCount = 0;\n\t// Check for steering messages at start (user may have typed while waiting)\n\tlet pendingMessages: AgentMessage[] = (await config.getSteeringMessages?.()) || [];\n\n\t// Outer loop: continues when queued follow-up messages arrive after agent would stop\n\twhile (true) {\n\t\tlet hasMoreToolCalls = true;\n\t\tendTurnRequested = false;\n\n\t\t// Inner loop: process tool calls and steering messages\n\t\twhile (hasMoreToolCalls || pendingMessages.length > 0) {\n\t\t\t// Process pending messages first (inject into context so they're never lost).\n\t\t\t// This happens before turn_start and shouldContinue so messages are always\n\t\t\t// preserved regardless of whether the turn proceeds.\n\t\t\tif (pendingMessages.length > 0) {\n\t\t\t\tfor (const message of pendingMessages) {\n\t\t\t\t\tawait emit({ type: \"message_start\", message });\n\t\t\t\t\tawait emit({ type: \"message_end\", message });\n\t\t\t\t\tcurrentContext.messages.push(message);\n\t\t\t\t\tnewMessages.push(message);\n\t\t\t\t}\n\t\t\t\tpendingMessages = [];\n\t\t\t}\n\n\t\t\t// Check shouldContinue before starting a new turn (not the very first).\n\t\t\t// This runs before turn_start so we never emit an orphaned turn_start.\n\t\t\tif (llmCallCount > 0 && config.shouldContinue && !config.shouldContinue()) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (!firstTurn) {\n\t\t\t\tawait emit({ type: \"turn_start\" });\n\t\t\t} else {\n\t\t\t\tfirstTurn = false;\n\t\t\t}\n\n\t\t\t// Stream assistant response\n\t\t\tconst message = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);\n\t\t\tnewMessages.push(message);\n\t\t\tllmCallCount++;\n\n\t\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\t\tawait emit({ type: \"turn_end\", message, toolResults: [] });\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for tool calls\n\t\t\tconst toolCalls = message.content.filter((c) => c.type === \"toolCall\");\n\t\t\thasMoreToolCalls = toolCalls.length > 0;\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\tif (hasMoreToolCalls) {\n\t\t\t\tconst executionResult = await executeToolCalls(currentContext, message, config, signal, emit);\n\t\t\t\ttoolResults.push(...executionResult.results);\n\n\t\t\t\tfor (const result of toolResults) {\n\t\t\t\t\tcurrentContext.messages.push(result);\n\t\t\t\t\tnewMessages.push(result);\n\t\t\t\t}\n\n\t\t\t\tif (executionResult.endTurn) {\n\t\t\t\t\tendTurnRequested = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait emit({ type: \"turn_end\", message, toolResults });\n\n\t\t\t// If a tool requested endTurn, stop the loop (skip further LLM calls)\n\t\t\tif (endTurnRequested) {\n\t\t\t\thasMoreToolCalls = false;\n\t\t\t\tpendingMessages = [];\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tpendingMessages = (await config.getSteeringMessages?.()) || [];\n\t\t}\n\n\t\t// Agent would stop here. Drain any steering messages that arrived during\n\t\t// wind-down (e.g., background agent results delivered via steer() between\n\t\t// endTurn break and here). Then check for follow-up messages.\n\t\tconst leftoverSteering = (await config.getSteeringMessages?.()) || [];\n\t\tconst followUpMessages = (await config.getFollowUpMessages?.()) || [];\n\t\tconst allPending = [...leftoverSteering, ...followUpMessages];\n\t\tif (allPending.length > 0) {\n\t\t\t// Set as pending so inner loop processes them\n\t\t\tpendingMessages = allPending;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// No more messages, exit\n\t\tbreak;\n\t}\n\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\n/**\n * Check if an error is a stream-drop error (connection dropped before terminal event).\n * Only these errors trigger automatic retry — all other errors propagate as-is.\n */\nfunction isStreamDropError(error: unknown): boolean {\n\tconst msg = error instanceof Error ? error.message : typeof error === \"string\" ? error : \"\";\n\treturn (\n\t\tmsg.includes(\"Stream ended without\") ||\n\t\tmsg.includes(\"connection likely dropped\") ||\n\t\tmsg.includes(\"WebSocket stream closed before\")\n\t);\n}\n\n/**\n * Sleep for a duration, aborting early if the signal fires.\n */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tif (signal?.aborted) {\n\t\t\tresolve();\n\t\t\treturn;\n\t\t}\n\t\tconst timer = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Stream an assistant response from the LLM.\n * This is where AgentMessage[] gets transformed to Message[] for the LLM.\n */\nasync function streamAssistantResponse(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n): Promise<AssistantMessage> {\n\t// Apply context transform if configured (AgentMessage[] → AgentMessage[])\n\tlet messages = context.messages;\n\tif (config.transformContext) {\n\t\tmessages = await config.transformContext(messages, signal);\n\t}\n\n\t// Convert to LLM-compatible messages (AgentMessage[] → Message[])\n\tconst llmMessages = await config.convertToLlm(messages);\n\n\t// Build LLM context\n\tconst llmContext: Context = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\tmessages: llmMessages,\n\t\ttools: context.tools,\n\t};\n\n\tconst streamFunction = streamFn || streamSimple;\n\n\t// Resolve API key (important for expiring tokens)\n\tconst resolvedApiKey =\n\t\t(config.getApiKey ? await config.getApiKey(config.model.provider) : undefined) || config.apiKey;\n\n\tconst streamStart = performance.now();\n\tlet partialMessage: AssistantMessage | null = null;\n\tlet addedPartial = false;\n\n\tconst finalizeMessage = async (finalMessage: AssistantMessage): Promise<AssistantMessage> => {\n\t\tfinalMessage.durationMs = Math.max(0, performance.now() - streamStart);\n\t\tif (addedPartial) {\n\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t} else {\n\t\t\tcontext.messages.push(finalMessage);\n\t\t}\n\t\tif (!addedPartial) {\n\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t}\n\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\treturn finalMessage;\n\t};\n\n\tconst createErrorMessage = (error: unknown): AssistantMessage => ({\n\t\trole: \"assistant\",\n\t\tcontent: partialMessage?.content ?? [{ type: \"text\", text: \"\" }],\n\t\tapi: config.model.api,\n\t\tprovider: config.model.provider,\n\t\tmodel: config.model.id,\n\t\tusage: partialMessage?.usage ?? {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: signal?.aborted ? \"aborted\" : \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: partialMessage?.timestamp ?? Date.now(),\n\t});\n\n\tconst maxRetries = config.streamRetries ?? 3;\n\tconst retryBaseDelay = config.streamRetryBaseDelayMs ?? 1000;\n\tconst lengthRetries = config.lengthRetries ?? 2;\n\tconst lengthMultiplier = config.lengthRetryBudgetMultiplier ?? 2;\n\t// The maxTokens budget requested for the current attempt. Starts at the\n\t// caller-configured budget (may be undefined → provider default) and is\n\t// escalated on each length retry. Kept separate from stream-drop retries.\n\tlet requestMaxTokens = config.maxTokens;\n\tlet lengthAttempts = 0;\n\tconst clonePartialForDebug = (): AssistantMessage | undefined => {\n\t\tif (!partialMessage) return undefined;\n\t\treturn {\n\t\t\t...partialMessage,\n\t\t\tcontent: partialMessage.content.map((block) => ({ ...block })),\n\t\t\tusage: { ...partialMessage.usage, cost: { ...partialMessage.usage.cost } },\n\t\t};\n\t};\n\n\t// Discard the truncated partial message (if any) before re-issuing a request.\n\tconst discardPartial = () => {\n\t\tif (addedPartial) {\n\t\t\tcontext.messages.pop();\n\t\t\taddedPartial = false;\n\t\t}\n\t\tpartialMessage = null;\n\t};\n\n\t// Compute the escalated token budget for a length retry, never exceeding the\n\t// model's ceiling. `current` is the *effective* budget that produced the\n\t// truncated response (resolved from the provider default when no explicit\n\t// maxTokens was set), so the escalation always requests strictly more.\n\tconst escalateLengthBudget = (current: number): number => {\n\t\tconst ceiling = config.model.maxTokens;\n\t\treturn Math.min(Math.ceil(current * lengthMultiplier), ceiling);\n\t};\n\n\t// Build the truncation failure message after length retries are exhausted.\n\tconst createLengthExhaustedMessage = (attempts: number): AssistantMessage => {\n\t\tconst errorMessage = createErrorMessage(\n\t\t\tnew Error(\n\t\t\t\t`Response truncated at token limit after ${attempts} attempt${attempts === 1 ? \"\" : \"s\"} — output exceeded the model's maximum token budget`,\n\t\t\t),\n\t\t);\n\t\t// Force \"error\" so the runLoop error guard terminates the turn loudly.\n\t\terrorMessage.stopReason = signal?.aborted ? \"aborted\" : \"error\";\n\t\treturn errorMessage;\n\t};\n\n\t// stream-drop retries are counted separately from length retries. A length retry\n\t// is a fresh request, so it resets the stream-drop attempt counter.\n\tlet streamDropAttempt = 0;\n\twhile (true) {\n\t\tlet response: Awaited<ReturnType<StreamFn>>;\n\t\ttry {\n\t\t\tresponse = await streamFunction(config.model, llmContext, {\n\t\t\t\t...config,\n\t\t\t\tmaxTokens: requestMaxTokens,\n\t\t\t\tapiKey: resolvedApiKey,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (isStreamDropError(error) && streamDropAttempt < maxRetries && !signal?.aborted) {\n\t\t\t\tawait emit({\n\t\t\t\t\ttype: \"stream_retry\",\n\t\t\t\t\tattempt: streamDropAttempt + 1,\n\t\t\t\t\tmaxAttempts: maxRetries,\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\tdiscardedPartial: clonePartialForDebug(),\n\t\t\t\t});\n\t\t\t\tawait sleep(retryBaseDelay * 2 ** streamDropAttempt, signal);\n\t\t\t\tdiscardPartial();\n\t\t\t\tstreamDropAttempt++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst surfacedError = isStreamDropError(error)\n\t\t\t\t? new Error(\"Stream dropped repeatedly — connection likely unstable\")\n\t\t\t\t: error instanceof Error\n\t\t\t\t\t? error\n\t\t\t\t\t: new Error(String(error));\n\t\t\treturn finalizeMessage(createErrorMessage(surfacedError));\n\t\t}\n\n\t\tlet shouldRetry = false;\n\t\tlet retryError = \"\";\n\t\t// Set when the stream completes with a \"length\" result that warrants a budget escalation.\n\t\tlet lengthRetry: { previous: number; next: number } | null = null;\n\t\ttry {\n\t\t\tfor await (const event of response) {\n\t\t\t\tswitch (event.type) {\n\t\t\t\t\tcase \"start\":\n\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\tcontext.messages.push(partialMessage);\n\t\t\t\t\t\taddedPartial = true;\n\t\t\t\t\t\tawait emit({ type: \"message_start\", message: { ...partialMessage } });\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"text_start\":\n\t\t\t\t\tcase \"text_delta\":\n\t\t\t\t\tcase \"text_end\":\n\t\t\t\t\tcase \"thinking_start\":\n\t\t\t\t\tcase \"thinking_delta\":\n\t\t\t\t\tcase \"thinking_end\":\n\t\t\t\t\tcase \"toolcall_start\":\n\t\t\t\t\tcase \"toolcall_delta\":\n\t\t\t\t\tcase \"toolcall_end\":\n\t\t\t\t\t\tif (partialMessage) {\n\t\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\t\tcontext.messages[context.messages.length - 1] = partialMessage;\n\t\t\t\t\t\t\tawait emit({\n\t\t\t\t\t\t\t\ttype: \"message_update\",\n\t\t\t\t\t\t\t\tassistantMessageEvent: event,\n\t\t\t\t\t\t\t\tmessage: { ...partialMessage },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"done\":\n\t\t\t\t\tcase \"error\": {\n\t\t\t\t\t\tconst result = await response.result();\n\t\t\t\t\t\t// Check if this is a stream-drop error that should be retried\n\t\t\t\t\t\tconst isDrop = result.stopReason === \"error\" && isStreamDropError(result.errorMessage);\n\t\t\t\t\t\tif (isDrop && streamDropAttempt < maxRetries && !signal?.aborted) {\n\t\t\t\t\t\t\tshouldRetry = true;\n\t\t\t\t\t\t\tretryError =\n\t\t\t\t\t\t\t\tresult.errorMessage ?? \"Stream ended without terminal event — connection likely dropped\";\n\t\t\t\t\t\t} else if (isDrop) {\n\t\t\t\t\t\t\t// Final attempt exhausted — surface friendly message\n\t\t\t\t\t\t\treturn finalizeMessage(\n\t\t\t\t\t\t\t\tcreateErrorMessage(new Error(\"Stream dropped repeatedly — connection likely unstable\")),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else if (result.stopReason === \"length\") {\n\t\t\t\t\t\t\t// The model exhausted its output budget mid-response. Retry with a\n\t\t\t\t\t\t\t// larger budget if we have retries left, the budget can still grow,\n\t\t\t\t\t\t\t// and we have not been aborted. Otherwise, fail loudly below.\n\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t// When no explicit maxTokens was set, the request used the provider\n\t\t\t\t\t\t\t// default budget — Math.min(model.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS),\n\t\t\t\t\t\t\t// NOT the full model ceiling. Resolving the effective budget to the\n\t\t\t\t\t\t\t// real default lets escalation request strictly more, and lets the\n\t\t\t\t\t\t\t// ceiling guard correctly distinguish a default request (which can\n\t\t\t\t\t\t\t// still grow) from one already at the model ceiling.\n\t\t\t\t\t\t\tconst effectiveMaxTokens =\n\t\t\t\t\t\t\t\trequestMaxTokens ?? Math.min(config.model.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS);\n\t\t\t\t\t\t\tconst atCeiling = effectiveMaxTokens >= config.model.maxTokens;\n\t\t\t\t\t\t\tif (lengthAttempts < lengthRetries && !atCeiling && !signal?.aborted) {\n\t\t\t\t\t\t\t\tlengthRetry = {\n\t\t\t\t\t\t\t\t\tprevious: effectiveMaxTokens,\n\t\t\t\t\t\t\t\t\tnext: escalateLengthBudget(effectiveMaxTokens),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\treturn finalizeMessage(createLengthExhaustedMessage(lengthAttempts + 1));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn finalizeMessage(result);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (shouldRetry || lengthRetry) break;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (isStreamDropError(error) && streamDropAttempt < maxRetries && !signal?.aborted) {\n\t\t\t\tshouldRetry = true;\n\t\t\t\tretryError = error instanceof Error ? error.message : String(error);\n\t\t\t} else {\n\t\t\t\tconst surfacedError = isStreamDropError(error)\n\t\t\t\t\t? new Error(\"Stream dropped repeatedly — connection likely unstable\")\n\t\t\t\t\t: error instanceof Error\n\t\t\t\t\t\t? error\n\t\t\t\t\t\t: new Error(String(error));\n\t\t\t\treturn finalizeMessage(createErrorMessage(surfacedError));\n\t\t\t}\n\t\t}\n\n\t\tif (lengthRetry) {\n\t\t\tawait emit({\n\t\t\t\ttype: \"length_retry\",\n\t\t\t\tattempt: lengthAttempts + 1,\n\t\t\t\tmaxAttempts: lengthRetries,\n\t\t\t\tpreviousMaxTokens: lengthRetry.previous,\n\t\t\t\tnextMaxTokens: lengthRetry.next,\n\t\t\t\tdiscardedPartial: clonePartialForDebug(),\n\t\t\t});\n\t\t\tdiscardPartial();\n\t\t\trequestMaxTokens = lengthRetry.next;\n\t\t\tlengthAttempts++;\n\t\t\t// A length retry is a fresh request; reset the stream-drop counter.\n\t\t\tstreamDropAttempt = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (shouldRetry) {\n\t\t\tawait emit({\n\t\t\t\ttype: \"stream_retry\",\n\t\t\t\tattempt: streamDropAttempt + 1,\n\t\t\t\tmaxAttempts: maxRetries,\n\t\t\t\terror: retryError,\n\t\t\t\tdiscardedPartial: clonePartialForDebug(),\n\t\t\t});\n\t\t\tawait sleep(retryBaseDelay * 2 ** streamDropAttempt, signal);\n\t\t\tdiscardPartial();\n\t\t\tstreamDropAttempt++;\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn finalizeMessage(await response.result());\n\t}\n}\n\ninterface ToolExecutionResult {\n\tresults: ToolResultMessage[];\n\tendTurn: boolean;\n}\n\n/**\n * Execute tool calls from an assistant message.\n */\nasync function executeToolCalls(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolExecutionResult> {\n\tconst toolCalls = assistantMessage.content.filter((c) => c.type === \"toolCall\");\n\tif (config.toolExecution === \"sequential\") {\n\t\treturn executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit);\n\t}\n\treturn executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);\n}\n\nasync function executeToolCallsSequential(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolExecutionResult> {\n\tconst results: ToolResultMessage[] = [];\n\tlet endTurn = false;\n\n\tfor (const toolCall of toolCalls) {\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tif (preparation.result.endTurn) endTurn = true;\n\t\t\tresults.push(await emitToolCallOutcome(toolCall, preparation.result, preparation.isError, emit));\n\t\t} else {\n\t\t\tconst executed = await executePreparedToolCall(preparation, signal, emit);\n\t\t\tif (executed.result.endTurn) endTurn = true;\n\t\t\tresults.push(\n\t\t\t\tawait finalizeExecutedToolCall(\n\t\t\t\t\tcurrentContext,\n\t\t\t\t\tassistantMessage,\n\t\t\t\t\tpreparation,\n\t\t\t\t\texecuted,\n\t\t\t\t\tconfig,\n\t\t\t\t\tsignal,\n\t\t\t\t\temit,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\treturn { results, endTurn };\n}\n\nasync function executeToolCallsParallel(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolExecutionResult> {\n\tconst results: ToolResultMessage[] = [];\n\tconst runnableCalls: PreparedToolCall[] = [];\n\tlet endTurn = false;\n\n\tfor (const toolCall of toolCalls) {\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tif (preparation.result.endTurn) endTurn = true;\n\t\t\tresults.push(await emitToolCallOutcome(toolCall, preparation.result, preparation.isError, emit));\n\t\t} else {\n\t\t\trunnableCalls.push(preparation);\n\t\t}\n\t}\n\n\tconst runningCalls = runnableCalls.map((prepared) => ({\n\t\tprepared,\n\t\texecution: executePreparedToolCall(prepared, signal, emit),\n\t}));\n\n\tfor (const running of runningCalls) {\n\t\tconst executed = await running.execution;\n\t\tif (executed.result.endTurn) endTurn = true;\n\t\tresults.push(\n\t\t\tawait finalizeExecutedToolCall(\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\trunning.prepared,\n\t\t\t\texecuted,\n\t\t\t\tconfig,\n\t\t\t\tsignal,\n\t\t\t\temit,\n\t\t\t),\n\t\t);\n\t}\n\n\treturn { results, endTurn };\n}\n\ntype PreparedToolCall = {\n\tkind: \"prepared\";\n\ttoolCall: AgentToolCall;\n\ttool: AgentTool<any>;\n\targs: unknown;\n};\n\ntype ImmediateToolCallOutcome = {\n\tkind: \"immediate\";\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n};\n\ntype ExecutedToolCallOutcome = {\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n};\n\nasync function prepareToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCall: AgentToolCall,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<PreparedToolCall | ImmediateToolCallOutcome> {\n\tconst tool = currentContext.tools?.find((t) => t.name === toolCall.name);\n\tif (!tool) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(`Tool ${toolCall.name} not found`),\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\ttry {\n\t\tconst validatedArgs = validateToolArguments(tool, toolCall);\n\t\tif (config.beforeToolCall) {\n\t\t\tconst beforeResult = await config.beforeToolCall(\n\t\t\t\t{\n\t\t\t\t\tassistantMessage,\n\t\t\t\t\ttoolCall,\n\t\t\t\t\targs: validatedArgs,\n\t\t\t\t\tcontext: currentContext,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (beforeResult?.block) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"immediate\",\n\t\t\t\t\tresult: createErrorToolResult(beforeResult.reason || \"Tool execution was blocked\"),\n\t\t\t\t\tisError: true,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tkind: \"prepared\",\n\t\t\ttoolCall,\n\t\t\ttool,\n\t\t\targs: validatedArgs,\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t\t\tisError: true,\n\t\t};\n\t}\n}\n\nasync function executePreparedToolCall(\n\tprepared: PreparedToolCall,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallOutcome> {\n\tconst updateEvents: Promise<void>[] = [];\n\n\ttry {\n\t\tconst result = await prepared.tool.execute(\n\t\t\tprepared.toolCall.id,\n\t\t\tprepared.args as never,\n\t\t\tsignal,\n\t\t\t(partialResult) => {\n\t\t\t\tupdateEvents.push(\n\t\t\t\t\tPromise.resolve(\n\t\t\t\t\t\temit({\n\t\t\t\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\t\t\t\targs: prepared.toolCall.arguments,\n\t\t\t\t\t\t\tpartialResult,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t},\n\t\t);\n\t\tawait Promise.all(updateEvents);\n\t\treturn { result, isError: false };\n\t} catch (error) {\n\t\tawait Promise.all(updateEvents);\n\t\treturn {\n\t\t\tresult: createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t\t\tisError: true,\n\t\t};\n\t}\n}\n\nasync function finalizeExecutedToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tprepared: PreparedToolCall,\n\texecuted: ExecutedToolCallOutcome,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolResultMessage> {\n\tlet result = executed.result;\n\tlet isError = executed.isError;\n\n\tif (config.afterToolCall) {\n\t\tconst afterResult = await config.afterToolCall(\n\t\t\t{\n\t\t\t\tassistantMessage,\n\t\t\t\ttoolCall: prepared.toolCall,\n\t\t\t\targs: prepared.args,\n\t\t\t\tresult,\n\t\t\t\tisError,\n\t\t\t\tcontext: currentContext,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t\tif (afterResult) {\n\t\t\tresult = {\n\t\t\t\tcontent: afterResult.content ?? result.content,\n\t\t\t\tdetails: afterResult.details ?? result.details,\n\t\t\t};\n\t\t\tisError = afterResult.isError ?? isError;\n\t\t}\n\t}\n\n\treturn await emitToolCallOutcome(prepared.toolCall, result, isError, emit);\n}\n\nfunction createErrorToolResult(message: string): AgentToolResult<any> {\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\tdetails: {},\n\t};\n}\n\nasync function emitToolCallOutcome(\n\ttoolCall: AgentToolCall,\n\tresult: AgentToolResult<any>,\n\tisError: boolean,\n\temit: AgentEventSink,\n): Promise<ToolResultMessage> {\n\tawait emit({\n\t\ttype: \"tool_execution_end\",\n\t\ttoolCallId: toolCall.id,\n\t\ttoolName: toolCall.name,\n\t\tresult,\n\t\tisError,\n\t});\n\n\tconst toolResultMessage: ToolResultMessage = {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: toolCall.id,\n\t\ttoolName: toolCall.name,\n\t\tcontent: result.content,\n\t\tdetails: result.details,\n\t\tisError,\n\t\ttimestamp: Date.now(),\n\t};\n\n\tawait emit({ type: \"message_start\", message: toolResultMessage });\n\tawait emit({ type: \"message_end\", message: toolResultMessage });\n\treturn toolResultMessage;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent-loop.d.ts","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAIN,WAAW,EAMX,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EACX,YAAY,EACZ,UAAU,EACV,eAAe,EACf,YAAY,EAIZ,QAAQ,EAER,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AASzE;;;GAGG;AACH,wBAAgB,SAAS,CACxB,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAiBzC;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAChC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAwBzC;AAED,wBAAsB,YAAY,CACjC,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,YAAY,EAAE,CAAC,CAoBzB;AAED,wBAAsB,oBAAoB,CACzC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,QAAQ,GACjB,OAAO,CAAC,YAAY,EAAE,CAAC,CAqBzB","sourcesContent":["/**\n * Agent loop that works with AgentMessage throughout.\n * Transforms to Message[] only at the LLM call boundary.\n */\n\nimport {\n\ttype AssistantMessage,\n\ttype Context,\n\tDEFAULT_MAX_OUTPUT_TOKENS,\n\tEventStream,\n\tstreamSimple,\n\tsupportsMax,\n\tsupportsXhigh,\n\ttype ToolResultMessage,\n\tvalidateToolArguments,\n} from \"@dreb/ai\";\nimport type {\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolCall,\n\tAgentToolResult,\n\tStreamFn,\n\tThinkingLevel,\n} from \"./types.js\";\n\nexport type AgentEventSink = (event: AgentEvent) => Promise<void> | void;\n\nfunction getEffectiveThinkingLevel(config: AgentLoopConfig): ThinkingLevel {\n\tconst requested = config.reasoning ?? \"off\";\n\tif (!config.model.reasoning) return \"off\";\n\tif (requested === \"max\" && !supportsMax(config.model)) return supportsXhigh(config.model) ? \"xhigh\" : \"high\";\n\treturn requested === \"xhigh\" && !supportsXhigh(config.model) ? \"high\" : requested;\n}\n\n/**\n * Start an agent loop with a new prompt message.\n * The prompt is added to the context and events are emitted for it.\n */\nexport function agentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tconst stream = createAgentStream();\n\n\tvoid runAgentLoop(\n\t\tprompts,\n\t\tcontext,\n\t\tconfig,\n\t\tasync (event) => {\n\t\t\tstream.push(event);\n\t\t},\n\t\tsignal,\n\t\tstreamFn,\n\t).then((messages) => {\n\t\tstream.end(messages);\n\t});\n\n\treturn stream;\n}\n\n/**\n * Continue an agent loop from the current context without adding a new message.\n * Used for retries - context already has user message or tool results.\n *\n * **Important:** The last message in context must convert to a `user` or `toolResult` message\n * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.\n * This cannot be validated here since `convertToLlm` is only called once per turn.\n */\nexport function agentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst stream = createAgentStream();\n\n\tvoid runAgentLoopContinue(\n\t\tcontext,\n\t\tconfig,\n\t\tasync (event) => {\n\t\t\tstream.push(event);\n\t\t},\n\t\tsignal,\n\t\tstreamFn,\n\t).then((messages) => {\n\t\tstream.end(messages);\n\t});\n\n\treturn stream;\n}\n\nexport async function runAgentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tconst newMessages: AgentMessage[] = [...prompts];\n\tconst currentContext: AgentContext = {\n\t\t...context,\n\t\tmessages: [...context.messages, ...prompts],\n\t};\n\n\tawait emit({\n\t\ttype: \"agent_start\",\n\t\tmodel: { provider: config.model.provider, id: config.model.id },\n\t\tthinkingLevel: getEffectiveThinkingLevel(config),\n\t});\n\tawait emit({ type: \"turn_start\" });\n\tfor (const prompt of prompts) {\n\t\tawait emit({ type: \"message_start\", message: prompt });\n\t\tawait emit({ type: \"message_end\", message: prompt });\n\t}\n\n\tawait runLoop(currentContext, newMessages, config, signal, emit, streamFn);\n\treturn newMessages;\n}\n\nexport async function runAgentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst newMessages: AgentMessage[] = [];\n\tconst currentContext: AgentContext = { ...context };\n\n\tawait emit({\n\t\ttype: \"agent_start\",\n\t\tmodel: { provider: config.model.provider, id: config.model.id },\n\t\tthinkingLevel: getEffectiveThinkingLevel(config),\n\t});\n\tawait emit({ type: \"turn_start\" });\n\n\tawait runLoop(currentContext, newMessages, config, signal, emit, streamFn);\n\treturn newMessages;\n}\n\nfunction createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {\n\treturn new EventStream<AgentEvent, AgentMessage[]>(\n\t\t(event: AgentEvent) => event.type === \"agent_end\",\n\t\t(event: AgentEvent) => (event.type === \"agent_end\" ? event.messages : []),\n\t);\n}\n\n/**\n * Main loop logic shared by agentLoop and agentLoopContinue.\n */\nasync function runLoop(\n\tcurrentContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n): Promise<void> {\n\tlet firstTurn = true;\n\tlet endTurnRequested = false;\n\tlet llmCallCount = 0;\n\t// Check for steering messages at start (user may have typed while waiting)\n\tlet pendingMessages: AgentMessage[] = (await config.getSteeringMessages?.()) || [];\n\n\t// Outer loop: continues when queued follow-up messages arrive after agent would stop\n\twhile (true) {\n\t\tlet hasMoreToolCalls = true;\n\t\tendTurnRequested = false;\n\n\t\t// Inner loop: process tool calls and steering messages\n\t\twhile (hasMoreToolCalls || pendingMessages.length > 0) {\n\t\t\t// Process pending messages first (inject into context so they're never lost).\n\t\t\t// This happens before turn_start and shouldContinue so messages are always\n\t\t\t// preserved regardless of whether the turn proceeds.\n\t\t\tif (pendingMessages.length > 0) {\n\t\t\t\tfor (const message of pendingMessages) {\n\t\t\t\t\tawait emit({ type: \"message_start\", message });\n\t\t\t\t\tawait emit({ type: \"message_end\", message });\n\t\t\t\t\tcurrentContext.messages.push(message);\n\t\t\t\t\tnewMessages.push(message);\n\t\t\t\t}\n\t\t\t\tpendingMessages = [];\n\t\t\t}\n\n\t\t\t// Check shouldContinue before starting a new turn (not the very first).\n\t\t\t// This runs before turn_start so we never emit an orphaned turn_start.\n\t\t\tif (llmCallCount > 0 && config.shouldContinue && !config.shouldContinue()) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (!firstTurn) {\n\t\t\t\tawait emit({ type: \"turn_start\" });\n\t\t\t} else {\n\t\t\t\tfirstTurn = false;\n\t\t\t}\n\n\t\t\t// Stream assistant response\n\t\t\tconst message = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);\n\t\t\tnewMessages.push(message);\n\t\t\tllmCallCount++;\n\n\t\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\t\tawait emit({ type: \"turn_end\", message, toolResults: [] });\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for tool calls\n\t\t\tconst toolCalls = message.content.filter((c) => c.type === \"toolCall\");\n\t\t\thasMoreToolCalls = toolCalls.length > 0;\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\tif (hasMoreToolCalls) {\n\t\t\t\tconst executionResult = await executeToolCalls(currentContext, message, config, signal, emit);\n\t\t\t\ttoolResults.push(...executionResult.results);\n\n\t\t\t\tfor (const result of toolResults) {\n\t\t\t\t\tcurrentContext.messages.push(result);\n\t\t\t\t\tnewMessages.push(result);\n\t\t\t\t}\n\n\t\t\t\tif (executionResult.endTurn) {\n\t\t\t\t\tendTurnRequested = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait emit({ type: \"turn_end\", message, toolResults });\n\n\t\t\t// If a tool requested endTurn, stop the loop (skip further LLM calls)\n\t\t\tif (endTurnRequested) {\n\t\t\t\thasMoreToolCalls = false;\n\t\t\t\tpendingMessages = [];\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tpendingMessages = (await config.getSteeringMessages?.()) || [];\n\t\t}\n\n\t\t// Agent would stop here. Drain any steering messages that arrived during\n\t\t// wind-down (e.g., background agent results delivered via steer() between\n\t\t// endTurn break and here). Then check for follow-up messages.\n\t\tconst leftoverSteering = (await config.getSteeringMessages?.()) || [];\n\t\tconst followUpMessages = (await config.getFollowUpMessages?.()) || [];\n\t\tconst allPending = [...leftoverSteering, ...followUpMessages];\n\t\tif (allPending.length > 0) {\n\t\t\t// Set as pending so inner loop processes them\n\t\t\tpendingMessages = allPending;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// No more messages, exit\n\t\tbreak;\n\t}\n\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\n/**\n * Check if an error is a stream-drop error (connection dropped before terminal event).\n * Only these errors trigger automatic retry — all other errors propagate as-is.\n */\nfunction isStreamDropError(error: unknown): boolean {\n\tconst msg = error instanceof Error ? error.message : typeof error === \"string\" ? error : \"\";\n\treturn (\n\t\tmsg.includes(\"Stream ended without\") ||\n\t\tmsg.includes(\"connection likely dropped\") ||\n\t\tmsg.includes(\"WebSocket stream closed before\")\n\t);\n}\n\n/**\n * Sleep for a duration, aborting early if the signal fires.\n */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tif (signal?.aborted) {\n\t\t\tresolve();\n\t\t\treturn;\n\t\t}\n\t\tconst timer = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Stream an assistant response from the LLM.\n * This is where AgentMessage[] gets transformed to Message[] for the LLM.\n */\nasync function streamAssistantResponse(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n): Promise<AssistantMessage> {\n\t// Apply context transform if configured (AgentMessage[] → AgentMessage[])\n\tlet messages = context.messages;\n\tif (config.transformContext) {\n\t\tmessages = await config.transformContext(messages, signal);\n\t}\n\n\t// Convert to LLM-compatible messages (AgentMessage[] → Message[])\n\tconst llmMessages = await config.convertToLlm(messages);\n\n\t// Build LLM context\n\tconst llmContext: Context = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\tmessages: llmMessages,\n\t\ttools: context.tools,\n\t};\n\n\tconst streamFunction = streamFn || streamSimple;\n\n\t// Resolve API key (important for expiring tokens)\n\tconst resolvedApiKey =\n\t\t(config.getApiKey ? await config.getApiKey(config.model.provider) : undefined) || config.apiKey;\n\n\tconst streamStart = performance.now();\n\tlet partialMessage: AssistantMessage | null = null;\n\tlet addedPartial = false;\n\n\tconst finalizeMessage = async (finalMessage: AssistantMessage): Promise<AssistantMessage> => {\n\t\tfinalMessage.durationMs = Math.max(0, performance.now() - streamStart);\n\t\tif (addedPartial) {\n\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t} else {\n\t\t\tcontext.messages.push(finalMessage);\n\t\t}\n\t\tif (!addedPartial) {\n\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t}\n\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\treturn finalMessage;\n\t};\n\n\tconst createErrorMessage = (error: unknown): AssistantMessage => ({\n\t\trole: \"assistant\",\n\t\tcontent: partialMessage?.content ?? [{ type: \"text\", text: \"\" }],\n\t\tapi: config.model.api,\n\t\tprovider: config.model.provider,\n\t\tmodel: config.model.id,\n\t\tusage: partialMessage?.usage ?? {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: signal?.aborted ? \"aborted\" : \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: partialMessage?.timestamp ?? Date.now(),\n\t});\n\n\tconst maxRetries = config.streamRetries ?? 3;\n\tconst retryBaseDelay = config.streamRetryBaseDelayMs ?? 1000;\n\tconst lengthRetries = config.lengthRetries ?? 2;\n\tconst lengthMultiplier = config.lengthRetryBudgetMultiplier ?? 2;\n\t// The maxTokens budget requested for the current attempt. Starts at the\n\t// caller-configured budget (may be undefined → provider default) and is\n\t// escalated on each length retry. Kept separate from stream-drop retries.\n\tlet requestMaxTokens = config.maxTokens;\n\tlet lengthAttempts = 0;\n\tconst clonePartialForDebug = (): AssistantMessage | undefined => {\n\t\tif (!partialMessage) return undefined;\n\t\treturn {\n\t\t\t...partialMessage,\n\t\t\tcontent: partialMessage.content.map((block) => ({ ...block })),\n\t\t\tusage: { ...partialMessage.usage, cost: { ...partialMessage.usage.cost } },\n\t\t};\n\t};\n\n\t// Discard the truncated partial message (if any) before re-issuing a request.\n\tconst discardPartial = () => {\n\t\tif (addedPartial) {\n\t\t\tcontext.messages.pop();\n\t\t\taddedPartial = false;\n\t\t}\n\t\tpartialMessage = null;\n\t};\n\n\t// Compute the escalated token budget for a length retry, never exceeding the\n\t// model's ceiling. `current` is the *effective* budget that produced the\n\t// truncated response (resolved from the provider default when no explicit\n\t// maxTokens was set), so the escalation always requests strictly more.\n\tconst escalateLengthBudget = (current: number): number => {\n\t\tconst ceiling = config.model.maxTokens;\n\t\treturn Math.min(Math.ceil(current * lengthMultiplier), ceiling);\n\t};\n\n\t// Build the truncation failure message after length retries are exhausted.\n\tconst createLengthExhaustedMessage = (attempts: number): AssistantMessage => {\n\t\tconst errorMessage = createErrorMessage(\n\t\t\tnew Error(\n\t\t\t\t`Response truncated at token limit after ${attempts} attempt${attempts === 1 ? \"\" : \"s\"} — output exceeded the model's maximum token budget`,\n\t\t\t),\n\t\t);\n\t\t// Force \"error\" so the runLoop error guard terminates the turn loudly.\n\t\terrorMessage.stopReason = signal?.aborted ? \"aborted\" : \"error\";\n\t\treturn errorMessage;\n\t};\n\n\t// stream-drop retries are counted separately from length retries. A length retry\n\t// is a fresh request, so it resets the stream-drop attempt counter.\n\tlet streamDropAttempt = 0;\n\twhile (true) {\n\t\tlet response: Awaited<ReturnType<StreamFn>>;\n\t\ttry {\n\t\t\tresponse = await streamFunction(config.model, llmContext, {\n\t\t\t\t...config,\n\t\t\t\tmaxTokens: requestMaxTokens,\n\t\t\t\tapiKey: resolvedApiKey,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (isStreamDropError(error) && streamDropAttempt < maxRetries && !signal?.aborted) {\n\t\t\t\tawait emit({\n\t\t\t\t\ttype: \"stream_retry\",\n\t\t\t\t\tattempt: streamDropAttempt + 1,\n\t\t\t\t\tmaxAttempts: maxRetries,\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\tdiscardedPartial: clonePartialForDebug(),\n\t\t\t\t});\n\t\t\t\tawait sleep(retryBaseDelay * 2 ** streamDropAttempt, signal);\n\t\t\t\tdiscardPartial();\n\t\t\t\tstreamDropAttempt++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst surfacedError = isStreamDropError(error)\n\t\t\t\t? new Error(\"Stream dropped repeatedly — connection likely unstable\")\n\t\t\t\t: error instanceof Error\n\t\t\t\t\t? error\n\t\t\t\t\t: new Error(String(error));\n\t\t\treturn finalizeMessage(createErrorMessage(surfacedError));\n\t\t}\n\n\t\tlet shouldRetry = false;\n\t\tlet retryError = \"\";\n\t\t// Set when the stream completes with a \"length\" result that warrants a budget escalation.\n\t\tlet lengthRetry: { previous: number; next: number } | null = null;\n\t\ttry {\n\t\t\tfor await (const event of response) {\n\t\t\t\tswitch (event.type) {\n\t\t\t\t\tcase \"start\":\n\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\tcontext.messages.push(partialMessage);\n\t\t\t\t\t\taddedPartial = true;\n\t\t\t\t\t\tawait emit({ type: \"message_start\", message: { ...partialMessage } });\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"text_start\":\n\t\t\t\t\tcase \"text_delta\":\n\t\t\t\t\tcase \"text_end\":\n\t\t\t\t\tcase \"thinking_start\":\n\t\t\t\t\tcase \"thinking_delta\":\n\t\t\t\t\tcase \"thinking_end\":\n\t\t\t\t\tcase \"toolcall_start\":\n\t\t\t\t\tcase \"toolcall_delta\":\n\t\t\t\t\tcase \"toolcall_end\":\n\t\t\t\t\t\tif (partialMessage) {\n\t\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\t\tcontext.messages[context.messages.length - 1] = partialMessage;\n\t\t\t\t\t\t\tawait emit({\n\t\t\t\t\t\t\t\ttype: \"message_update\",\n\t\t\t\t\t\t\t\tassistantMessageEvent: event,\n\t\t\t\t\t\t\t\tmessage: { ...partialMessage },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"done\":\n\t\t\t\t\tcase \"error\": {\n\t\t\t\t\t\tconst result = await response.result();\n\t\t\t\t\t\t// Check if this is a stream-drop error that should be retried\n\t\t\t\t\t\tconst isDrop = result.stopReason === \"error\" && isStreamDropError(result.errorMessage);\n\t\t\t\t\t\tif (isDrop && streamDropAttempt < maxRetries && !signal?.aborted) {\n\t\t\t\t\t\t\tshouldRetry = true;\n\t\t\t\t\t\t\tretryError =\n\t\t\t\t\t\t\t\tresult.errorMessage ?? \"Stream ended without terminal event — connection likely dropped\";\n\t\t\t\t\t\t} else if (isDrop) {\n\t\t\t\t\t\t\t// Final attempt exhausted — surface friendly message\n\t\t\t\t\t\t\treturn finalizeMessage(\n\t\t\t\t\t\t\t\tcreateErrorMessage(new Error(\"Stream dropped repeatedly — connection likely unstable\")),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else if (result.stopReason === \"length\") {\n\t\t\t\t\t\t\t// The model exhausted its output budget mid-response. Retry with a\n\t\t\t\t\t\t\t// larger budget if we have retries left, the budget can still grow,\n\t\t\t\t\t\t\t// and we have not been aborted. Otherwise, fail loudly below.\n\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t// When no explicit maxTokens was set, the request used the provider\n\t\t\t\t\t\t\t// default budget — Math.min(model.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS),\n\t\t\t\t\t\t\t// NOT the full model ceiling. Resolving the effective budget to the\n\t\t\t\t\t\t\t// real default lets escalation request strictly more, and lets the\n\t\t\t\t\t\t\t// ceiling guard correctly distinguish a default request (which can\n\t\t\t\t\t\t\t// still grow) from one already at the model ceiling.\n\t\t\t\t\t\t\tconst effectiveMaxTokens =\n\t\t\t\t\t\t\t\trequestMaxTokens ?? Math.min(config.model.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS);\n\t\t\t\t\t\t\tconst atCeiling = effectiveMaxTokens >= config.model.maxTokens;\n\t\t\t\t\t\t\tif (lengthAttempts < lengthRetries && !atCeiling && !signal?.aborted) {\n\t\t\t\t\t\t\t\tlengthRetry = {\n\t\t\t\t\t\t\t\t\tprevious: effectiveMaxTokens,\n\t\t\t\t\t\t\t\t\tnext: escalateLengthBudget(effectiveMaxTokens),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\treturn finalizeMessage(createLengthExhaustedMessage(lengthAttempts + 1));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn finalizeMessage(result);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (shouldRetry || lengthRetry) break;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (isStreamDropError(error) && streamDropAttempt < maxRetries && !signal?.aborted) {\n\t\t\t\tshouldRetry = true;\n\t\t\t\tretryError = error instanceof Error ? error.message : String(error);\n\t\t\t} else {\n\t\t\t\tconst surfacedError = isStreamDropError(error)\n\t\t\t\t\t? new Error(\"Stream dropped repeatedly — connection likely unstable\")\n\t\t\t\t\t: error instanceof Error\n\t\t\t\t\t\t? error\n\t\t\t\t\t\t: new Error(String(error));\n\t\t\t\treturn finalizeMessage(createErrorMessage(surfacedError));\n\t\t\t}\n\t\t}\n\n\t\tif (lengthRetry) {\n\t\t\tawait emit({\n\t\t\t\ttype: \"length_retry\",\n\t\t\t\tattempt: lengthAttempts + 1,\n\t\t\t\tmaxAttempts: lengthRetries,\n\t\t\t\tpreviousMaxTokens: lengthRetry.previous,\n\t\t\t\tnextMaxTokens: lengthRetry.next,\n\t\t\t\tdiscardedPartial: clonePartialForDebug(),\n\t\t\t});\n\t\t\tdiscardPartial();\n\t\t\trequestMaxTokens = lengthRetry.next;\n\t\t\tlengthAttempts++;\n\t\t\t// A length retry is a fresh request; reset the stream-drop counter.\n\t\t\tstreamDropAttempt = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (shouldRetry) {\n\t\t\tawait emit({\n\t\t\t\ttype: \"stream_retry\",\n\t\t\t\tattempt: streamDropAttempt + 1,\n\t\t\t\tmaxAttempts: maxRetries,\n\t\t\t\terror: retryError,\n\t\t\t\tdiscardedPartial: clonePartialForDebug(),\n\t\t\t});\n\t\t\tawait sleep(retryBaseDelay * 2 ** streamDropAttempt, signal);\n\t\t\tdiscardPartial();\n\t\t\tstreamDropAttempt++;\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn finalizeMessage(await response.result());\n\t}\n}\n\ninterface ToolExecutionResult {\n\tresults: ToolResultMessage[];\n\tendTurn: boolean;\n}\n\n/**\n * Execute tool calls from an assistant message.\n */\nasync function executeToolCalls(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolExecutionResult> {\n\tconst toolCalls = assistantMessage.content.filter((c) => c.type === \"toolCall\");\n\tif (config.toolExecution === \"sequential\") {\n\t\treturn executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit);\n\t}\n\treturn executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);\n}\n\nasync function executeToolCallsSequential(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolExecutionResult> {\n\tconst results: ToolResultMessage[] = [];\n\tlet endTurn = false;\n\n\tfor (const toolCall of toolCalls) {\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tif (preparation.result.endTurn) endTurn = true;\n\t\t\tresults.push(await emitToolCallOutcome(toolCall, preparation.result, preparation.isError, emit));\n\t\t} else {\n\t\t\tconst executed = await executePreparedToolCall(preparation, signal, emit);\n\t\t\tif (executed.result.endTurn) endTurn = true;\n\t\t\tresults.push(\n\t\t\t\tawait finalizeExecutedToolCall(\n\t\t\t\t\tcurrentContext,\n\t\t\t\t\tassistantMessage,\n\t\t\t\t\tpreparation,\n\t\t\t\t\texecuted,\n\t\t\t\t\tconfig,\n\t\t\t\t\tsignal,\n\t\t\t\t\temit,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\treturn { results, endTurn };\n}\n\nasync function executeToolCallsParallel(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolExecutionResult> {\n\tconst results: ToolResultMessage[] = [];\n\tconst runnableCalls: PreparedToolCall[] = [];\n\tlet endTurn = false;\n\n\tfor (const toolCall of toolCalls) {\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tif (preparation.result.endTurn) endTurn = true;\n\t\t\tresults.push(await emitToolCallOutcome(toolCall, preparation.result, preparation.isError, emit));\n\t\t} else {\n\t\t\trunnableCalls.push(preparation);\n\t\t}\n\t}\n\n\tconst runningCalls = runnableCalls.map((prepared) => ({\n\t\tprepared,\n\t\texecution: executePreparedToolCall(prepared, signal, emit),\n\t}));\n\n\tfor (const running of runningCalls) {\n\t\tconst executed = await running.execution;\n\t\tif (executed.result.endTurn) endTurn = true;\n\t\tresults.push(\n\t\t\tawait finalizeExecutedToolCall(\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\trunning.prepared,\n\t\t\t\texecuted,\n\t\t\t\tconfig,\n\t\t\t\tsignal,\n\t\t\t\temit,\n\t\t\t),\n\t\t);\n\t}\n\n\treturn { results, endTurn };\n}\n\ntype PreparedToolCall = {\n\tkind: \"prepared\";\n\ttoolCall: AgentToolCall;\n\ttool: AgentTool<any>;\n\targs: unknown;\n};\n\ntype ImmediateToolCallOutcome = {\n\tkind: \"immediate\";\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n};\n\ntype ExecutedToolCallOutcome = {\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n};\n\nasync function prepareToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCall: AgentToolCall,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<PreparedToolCall | ImmediateToolCallOutcome> {\n\tconst tool = currentContext.tools?.find((t) => t.name === toolCall.name);\n\tif (!tool) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(`Tool ${toolCall.name} not found`),\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\ttry {\n\t\tconst validatedArgs = validateToolArguments(tool, toolCall);\n\t\tif (config.beforeToolCall) {\n\t\t\tconst beforeResult = await config.beforeToolCall(\n\t\t\t\t{\n\t\t\t\t\tassistantMessage,\n\t\t\t\t\ttoolCall,\n\t\t\t\t\targs: validatedArgs,\n\t\t\t\t\tcontext: currentContext,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (beforeResult?.block) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"immediate\",\n\t\t\t\t\tresult: createErrorToolResult(beforeResult.reason || \"Tool execution was blocked\"),\n\t\t\t\t\tisError: true,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tkind: \"prepared\",\n\t\t\ttoolCall,\n\t\t\ttool,\n\t\t\targs: validatedArgs,\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t\t\tisError: true,\n\t\t};\n\t}\n}\n\nasync function executePreparedToolCall(\n\tprepared: PreparedToolCall,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallOutcome> {\n\tconst updateEvents: Promise<void>[] = [];\n\n\ttry {\n\t\tconst result = await prepared.tool.execute(\n\t\t\tprepared.toolCall.id,\n\t\t\tprepared.args as never,\n\t\t\tsignal,\n\t\t\t(partialResult) => {\n\t\t\t\tupdateEvents.push(\n\t\t\t\t\tPromise.resolve(\n\t\t\t\t\t\temit({\n\t\t\t\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\t\t\t\targs: prepared.toolCall.arguments,\n\t\t\t\t\t\t\tpartialResult,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t},\n\t\t);\n\t\tawait Promise.all(updateEvents);\n\t\treturn { result, isError: false };\n\t} catch (error) {\n\t\tawait Promise.all(updateEvents);\n\t\treturn {\n\t\t\tresult: createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t\t\tisError: true,\n\t\t};\n\t}\n}\n\nasync function finalizeExecutedToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tprepared: PreparedToolCall,\n\texecuted: ExecutedToolCallOutcome,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolResultMessage> {\n\tlet result = executed.result;\n\tlet isError = executed.isError;\n\n\tif (config.afterToolCall) {\n\t\tconst afterResult = await config.afterToolCall(\n\t\t\t{\n\t\t\t\tassistantMessage,\n\t\t\t\ttoolCall: prepared.toolCall,\n\t\t\t\targs: prepared.args,\n\t\t\t\tresult,\n\t\t\t\tisError,\n\t\t\t\tcontext: currentContext,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t\tif (afterResult) {\n\t\t\tresult = {\n\t\t\t\tcontent: afterResult.content ?? result.content,\n\t\t\t\tdetails: afterResult.details ?? result.details,\n\t\t\t};\n\t\t\tisError = afterResult.isError ?? isError;\n\t\t}\n\t}\n\n\treturn await emitToolCallOutcome(prepared.toolCall, result, isError, emit);\n}\n\nfunction createErrorToolResult(message: string): AgentToolResult<any> {\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\tdetails: {},\n\t};\n}\n\nasync function emitToolCallOutcome(\n\ttoolCall: AgentToolCall,\n\tresult: AgentToolResult<any>,\n\tisError: boolean,\n\temit: AgentEventSink,\n): Promise<ToolResultMessage> {\n\tawait emit({\n\t\ttype: \"tool_execution_end\",\n\t\ttoolCallId: toolCall.id,\n\t\ttoolName: toolCall.name,\n\t\tresult,\n\t\tisError,\n\t});\n\n\tconst toolResultMessage: ToolResultMessage = {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: toolCall.id,\n\t\ttoolName: toolCall.name,\n\t\tcontent: result.content,\n\t\tdetails: result.details,\n\t\tisError,\n\t\ttimestamp: Date.now(),\n\t};\n\n\tawait emit({ type: \"message_start\", message: toolResultMessage });\n\tawait emit({ type: \"message_end\", message: toolResultMessage });\n\treturn toolResultMessage;\n}\n"]}
|
package/dist/agent-loop.js
CHANGED
|
@@ -2,11 +2,13 @@
|
|
|
2
2
|
* Agent loop that works with AgentMessage throughout.
|
|
3
3
|
* Transforms to Message[] only at the LLM call boundary.
|
|
4
4
|
*/
|
|
5
|
-
import { DEFAULT_MAX_OUTPUT_TOKENS, EventStream, streamSimple, supportsXhigh, validateToolArguments, } from "@dreb/ai";
|
|
5
|
+
import { DEFAULT_MAX_OUTPUT_TOKENS, EventStream, streamSimple, supportsMax, supportsXhigh, validateToolArguments, } from "@dreb/ai";
|
|
6
6
|
function getEffectiveThinkingLevel(config) {
|
|
7
7
|
const requested = config.reasoning ?? "off";
|
|
8
8
|
if (!config.model.reasoning)
|
|
9
9
|
return "off";
|
|
10
|
+
if (requested === "max" && !supportsMax(config.model))
|
|
11
|
+
return supportsXhigh(config.model) ? "xhigh" : "high";
|
|
10
12
|
return requested === "xhigh" && !supportsXhigh(config.model) ? "high" : requested;
|
|
11
13
|
}
|
|
12
14
|
/**
|
package/dist/agent-loop.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-loop.js","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAGN,yBAAyB,EACzB,WAAW,EACX,YAAY,EACZ,aAAa,EAEb,qBAAqB,GACrB,MAAM,UAAU,CAAC;AAelB,SAAS,yBAAyB,CAAC,MAAuB,EAAiB;IAC1E,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,IAAI,KAAK,CAAC;IAC5C,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,SAAS;QAAE,OAAO,KAAK,CAAC;IAC1C,OAAO,SAAS,KAAK,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;AAAA,CAClF;AAED;;;GAGG;AACH,MAAM,UAAU,SAAS,CACxB,OAAuB,EACvB,OAAqB,EACrB,MAAuB,EACvB,MAAoB,EACpB,QAAmB,EACuB;IAC1C,MAAM,MAAM,GAAG,iBAAiB,EAAE,CAAC;IAEnC,KAAK,YAAY,CAChB,OAAO,EACP,OAAO,EACP,MAAM,EACN,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC;QAChB,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAAA,CACnB,EACD,MAAM,EACN,QAAQ,CACR,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC;QACpB,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAAA,CACrB,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAAA,CACd;AAED;;;;;;;GAOG;AACH,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AmB,CAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;AAAA,CAC3E;AAED,SAAS,qBAAqB,CAAC,OAAe,EAAwB;IACrE,OAAO;QACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;QAC1C,OAAO,EAAE,EAAE;KACX,CAAC;AAAA,CACF;AAED,KAAK,UAAU,mBAAmB,CACjC,QAAuB,EACvB,MAA4B,EAC5B,OAAgB,EAChB,IAAoB,EACS;IAC7B,MAAM,IAAI,CAAC;QACV,IAAI,EAAE,oBAAoB;QAC1B,UAAU,EAAE,QAAQ,CAAC,EAAE;QACvB,QAAQ,EAAE,QAAQ,CAAC,IAAI;QACvB,MAAM;QACN,OAAO;KACP,CAAC,CAAC;IAEH,MAAM,iBAAiB,GAAsB;QAC5C,IAAI,EAAE,YAAY;QAClB,UAAU,EAAE,QAAQ,CAAC,EAAE;QACvB,QAAQ,EAAE,QAAQ,CAAC,IAAI;QACvB,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,OAAO;QACP,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;KACrB,CAAC;IAEF,MAAM,IAAI,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;IAClE,MAAM,IAAI,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;IAChE,OAAO,iBAAiB,CAAC;AAAA,CACzB","sourcesContent":["/**\n * Agent loop that works with AgentMessage throughout.\n * Transforms to Message[] only at the LLM call boundary.\n */\n\nimport {\n\ttype AssistantMessage,\n\ttype Context,\n\tDEFAULT_MAX_OUTPUT_TOKENS,\n\tEventStream,\n\tstreamSimple,\n\tsupportsXhigh,\n\ttype ToolResultMessage,\n\tvalidateToolArguments,\n} from \"@dreb/ai\";\nimport type {\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolCall,\n\tAgentToolResult,\n\tStreamFn,\n\tThinkingLevel,\n} from \"./types.js\";\n\nexport type AgentEventSink = (event: AgentEvent) => Promise<void> | void;\n\nfunction getEffectiveThinkingLevel(config: AgentLoopConfig): ThinkingLevel {\n\tconst requested = config.reasoning ?? \"off\";\n\tif (!config.model.reasoning) return \"off\";\n\treturn requested === \"xhigh\" && !supportsXhigh(config.model) ? \"high\" : requested;\n}\n\n/**\n * Start an agent loop with a new prompt message.\n * The prompt is added to the context and events are emitted for it.\n */\nexport function agentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tconst stream = createAgentStream();\n\n\tvoid runAgentLoop(\n\t\tprompts,\n\t\tcontext,\n\t\tconfig,\n\t\tasync (event) => {\n\t\t\tstream.push(event);\n\t\t},\n\t\tsignal,\n\t\tstreamFn,\n\t).then((messages) => {\n\t\tstream.end(messages);\n\t});\n\n\treturn stream;\n}\n\n/**\n * Continue an agent loop from the current context without adding a new message.\n * Used for retries - context already has user message or tool results.\n *\n * **Important:** The last message in context must convert to a `user` or `toolResult` message\n * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.\n * This cannot be validated here since `convertToLlm` is only called once per turn.\n */\nexport function agentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst stream = createAgentStream();\n\n\tvoid runAgentLoopContinue(\n\t\tcontext,\n\t\tconfig,\n\t\tasync (event) => {\n\t\t\tstream.push(event);\n\t\t},\n\t\tsignal,\n\t\tstreamFn,\n\t).then((messages) => {\n\t\tstream.end(messages);\n\t});\n\n\treturn stream;\n}\n\nexport async function runAgentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tconst newMessages: AgentMessage[] = [...prompts];\n\tconst currentContext: AgentContext = {\n\t\t...context,\n\t\tmessages: [...context.messages, ...prompts],\n\t};\n\n\tawait emit({\n\t\ttype: \"agent_start\",\n\t\tmodel: { provider: config.model.provider, id: config.model.id },\n\t\tthinkingLevel: getEffectiveThinkingLevel(config),\n\t});\n\tawait emit({ type: \"turn_start\" });\n\tfor (const prompt of prompts) {\n\t\tawait emit({ type: \"message_start\", message: prompt });\n\t\tawait emit({ type: \"message_end\", message: prompt });\n\t}\n\n\tawait runLoop(currentContext, newMessages, config, signal, emit, streamFn);\n\treturn newMessages;\n}\n\nexport async function runAgentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst newMessages: AgentMessage[] = [];\n\tconst currentContext: AgentContext = { ...context };\n\n\tawait emit({\n\t\ttype: \"agent_start\",\n\t\tmodel: { provider: config.model.provider, id: config.model.id },\n\t\tthinkingLevel: getEffectiveThinkingLevel(config),\n\t});\n\tawait emit({ type: \"turn_start\" });\n\n\tawait runLoop(currentContext, newMessages, config, signal, emit, streamFn);\n\treturn newMessages;\n}\n\nfunction createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {\n\treturn new EventStream<AgentEvent, AgentMessage[]>(\n\t\t(event: AgentEvent) => event.type === \"agent_end\",\n\t\t(event: AgentEvent) => (event.type === \"agent_end\" ? event.messages : []),\n\t);\n}\n\n/**\n * Main loop logic shared by agentLoop and agentLoopContinue.\n */\nasync function runLoop(\n\tcurrentContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n): Promise<void> {\n\tlet firstTurn = true;\n\tlet endTurnRequested = false;\n\tlet llmCallCount = 0;\n\t// Check for steering messages at start (user may have typed while waiting)\n\tlet pendingMessages: AgentMessage[] = (await config.getSteeringMessages?.()) || [];\n\n\t// Outer loop: continues when queued follow-up messages arrive after agent would stop\n\twhile (true) {\n\t\tlet hasMoreToolCalls = true;\n\t\tendTurnRequested = false;\n\n\t\t// Inner loop: process tool calls and steering messages\n\t\twhile (hasMoreToolCalls || pendingMessages.length > 0) {\n\t\t\t// Process pending messages first (inject into context so they're never lost).\n\t\t\t// This happens before turn_start and shouldContinue so messages are always\n\t\t\t// preserved regardless of whether the turn proceeds.\n\t\t\tif (pendingMessages.length > 0) {\n\t\t\t\tfor (const message of pendingMessages) {\n\t\t\t\t\tawait emit({ type: \"message_start\", message });\n\t\t\t\t\tawait emit({ type: \"message_end\", message });\n\t\t\t\t\tcurrentContext.messages.push(message);\n\t\t\t\t\tnewMessages.push(message);\n\t\t\t\t}\n\t\t\t\tpendingMessages = [];\n\t\t\t}\n\n\t\t\t// Check shouldContinue before starting a new turn (not the very first).\n\t\t\t// This runs before turn_start so we never emit an orphaned turn_start.\n\t\t\tif (llmCallCount > 0 && config.shouldContinue && !config.shouldContinue()) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (!firstTurn) {\n\t\t\t\tawait emit({ type: \"turn_start\" });\n\t\t\t} else {\n\t\t\t\tfirstTurn = false;\n\t\t\t}\n\n\t\t\t// Stream assistant response\n\t\t\tconst message = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);\n\t\t\tnewMessages.push(message);\n\t\t\tllmCallCount++;\n\n\t\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\t\tawait emit({ type: \"turn_end\", message, toolResults: [] });\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for tool calls\n\t\t\tconst toolCalls = message.content.filter((c) => c.type === \"toolCall\");\n\t\t\thasMoreToolCalls = toolCalls.length > 0;\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\tif (hasMoreToolCalls) {\n\t\t\t\tconst executionResult = await executeToolCalls(currentContext, message, config, signal, emit);\n\t\t\t\ttoolResults.push(...executionResult.results);\n\n\t\t\t\tfor (const result of toolResults) {\n\t\t\t\t\tcurrentContext.messages.push(result);\n\t\t\t\t\tnewMessages.push(result);\n\t\t\t\t}\n\n\t\t\t\tif (executionResult.endTurn) {\n\t\t\t\t\tendTurnRequested = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait emit({ type: \"turn_end\", message, toolResults });\n\n\t\t\t// If a tool requested endTurn, stop the loop (skip further LLM calls)\n\t\t\tif (endTurnRequested) {\n\t\t\t\thasMoreToolCalls = false;\n\t\t\t\tpendingMessages = [];\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tpendingMessages = (await config.getSteeringMessages?.()) || [];\n\t\t}\n\n\t\t// Agent would stop here. Drain any steering messages that arrived during\n\t\t// wind-down (e.g., background agent results delivered via steer() between\n\t\t// endTurn break and here). Then check for follow-up messages.\n\t\tconst leftoverSteering = (await config.getSteeringMessages?.()) || [];\n\t\tconst followUpMessages = (await config.getFollowUpMessages?.()) || [];\n\t\tconst allPending = [...leftoverSteering, ...followUpMessages];\n\t\tif (allPending.length > 0) {\n\t\t\t// Set as pending so inner loop processes them\n\t\t\tpendingMessages = allPending;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// No more messages, exit\n\t\tbreak;\n\t}\n\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\n/**\n * Check if an error is a stream-drop error (connection dropped before terminal event).\n * Only these errors trigger automatic retry — all other errors propagate as-is.\n */\nfunction isStreamDropError(error: unknown): boolean {\n\tconst msg = error instanceof Error ? error.message : typeof error === \"string\" ? error : \"\";\n\treturn (\n\t\tmsg.includes(\"Stream ended without\") ||\n\t\tmsg.includes(\"connection likely dropped\") ||\n\t\tmsg.includes(\"WebSocket stream closed before\")\n\t);\n}\n\n/**\n * Sleep for a duration, aborting early if the signal fires.\n */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tif (signal?.aborted) {\n\t\t\tresolve();\n\t\t\treturn;\n\t\t}\n\t\tconst timer = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Stream an assistant response from the LLM.\n * This is where AgentMessage[] gets transformed to Message[] for the LLM.\n */\nasync function streamAssistantResponse(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n): Promise<AssistantMessage> {\n\t// Apply context transform if configured (AgentMessage[] → AgentMessage[])\n\tlet messages = context.messages;\n\tif (config.transformContext) {\n\t\tmessages = await config.transformContext(messages, signal);\n\t}\n\n\t// Convert to LLM-compatible messages (AgentMessage[] → Message[])\n\tconst llmMessages = await config.convertToLlm(messages);\n\n\t// Build LLM context\n\tconst llmContext: Context = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\tmessages: llmMessages,\n\t\ttools: context.tools,\n\t};\n\n\tconst streamFunction = streamFn || streamSimple;\n\n\t// Resolve API key (important for expiring tokens)\n\tconst resolvedApiKey =\n\t\t(config.getApiKey ? await config.getApiKey(config.model.provider) : undefined) || config.apiKey;\n\n\tconst streamStart = performance.now();\n\tlet partialMessage: AssistantMessage | null = null;\n\tlet addedPartial = false;\n\n\tconst finalizeMessage = async (finalMessage: AssistantMessage): Promise<AssistantMessage> => {\n\t\tfinalMessage.durationMs = Math.max(0, performance.now() - streamStart);\n\t\tif (addedPartial) {\n\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t} else {\n\t\t\tcontext.messages.push(finalMessage);\n\t\t}\n\t\tif (!addedPartial) {\n\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t}\n\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\treturn finalMessage;\n\t};\n\n\tconst createErrorMessage = (error: unknown): AssistantMessage => ({\n\t\trole: \"assistant\",\n\t\tcontent: partialMessage?.content ?? [{ type: \"text\", text: \"\" }],\n\t\tapi: config.model.api,\n\t\tprovider: config.model.provider,\n\t\tmodel: config.model.id,\n\t\tusage: partialMessage?.usage ?? {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: signal?.aborted ? \"aborted\" : \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: partialMessage?.timestamp ?? Date.now(),\n\t});\n\n\tconst maxRetries = config.streamRetries ?? 3;\n\tconst retryBaseDelay = config.streamRetryBaseDelayMs ?? 1000;\n\tconst lengthRetries = config.lengthRetries ?? 2;\n\tconst lengthMultiplier = config.lengthRetryBudgetMultiplier ?? 2;\n\t// The maxTokens budget requested for the current attempt. Starts at the\n\t// caller-configured budget (may be undefined → provider default) and is\n\t// escalated on each length retry. Kept separate from stream-drop retries.\n\tlet requestMaxTokens = config.maxTokens;\n\tlet lengthAttempts = 0;\n\tconst clonePartialForDebug = (): AssistantMessage | undefined => {\n\t\tif (!partialMessage) return undefined;\n\t\treturn {\n\t\t\t...partialMessage,\n\t\t\tcontent: partialMessage.content.map((block) => ({ ...block })),\n\t\t\tusage: { ...partialMessage.usage, cost: { ...partialMessage.usage.cost } },\n\t\t};\n\t};\n\n\t// Discard the truncated partial message (if any) before re-issuing a request.\n\tconst discardPartial = () => {\n\t\tif (addedPartial) {\n\t\t\tcontext.messages.pop();\n\t\t\taddedPartial = false;\n\t\t}\n\t\tpartialMessage = null;\n\t};\n\n\t// Compute the escalated token budget for a length retry, never exceeding the\n\t// model's ceiling. `current` is the *effective* budget that produced the\n\t// truncated response (resolved from the provider default when no explicit\n\t// maxTokens was set), so the escalation always requests strictly more.\n\tconst escalateLengthBudget = (current: number): number => {\n\t\tconst ceiling = config.model.maxTokens;\n\t\treturn Math.min(Math.ceil(current * lengthMultiplier), ceiling);\n\t};\n\n\t// Build the truncation failure message after length retries are exhausted.\n\tconst createLengthExhaustedMessage = (attempts: number): AssistantMessage => {\n\t\tconst errorMessage = createErrorMessage(\n\t\t\tnew Error(\n\t\t\t\t`Response truncated at token limit after ${attempts} attempt${attempts === 1 ? \"\" : \"s\"} — output exceeded the model's maximum token budget`,\n\t\t\t),\n\t\t);\n\t\t// Force \"error\" so the runLoop error guard terminates the turn loudly.\n\t\terrorMessage.stopReason = signal?.aborted ? \"aborted\" : \"error\";\n\t\treturn errorMessage;\n\t};\n\n\t// stream-drop retries are counted separately from length retries. A length retry\n\t// is a fresh request, so it resets the stream-drop attempt counter.\n\tlet streamDropAttempt = 0;\n\twhile (true) {\n\t\tlet response: Awaited<ReturnType<StreamFn>>;\n\t\ttry {\n\t\t\tresponse = await streamFunction(config.model, llmContext, {\n\t\t\t\t...config,\n\t\t\t\tmaxTokens: requestMaxTokens,\n\t\t\t\tapiKey: resolvedApiKey,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (isStreamDropError(error) && streamDropAttempt < maxRetries && !signal?.aborted) {\n\t\t\t\tawait emit({\n\t\t\t\t\ttype: \"stream_retry\",\n\t\t\t\t\tattempt: streamDropAttempt + 1,\n\t\t\t\t\tmaxAttempts: maxRetries,\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\tdiscardedPartial: clonePartialForDebug(),\n\t\t\t\t});\n\t\t\t\tawait sleep(retryBaseDelay * 2 ** streamDropAttempt, signal);\n\t\t\t\tdiscardPartial();\n\t\t\t\tstreamDropAttempt++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst surfacedError = isStreamDropError(error)\n\t\t\t\t? new Error(\"Stream dropped repeatedly — connection likely unstable\")\n\t\t\t\t: error instanceof Error\n\t\t\t\t\t? error\n\t\t\t\t\t: new Error(String(error));\n\t\t\treturn finalizeMessage(createErrorMessage(surfacedError));\n\t\t}\n\n\t\tlet shouldRetry = false;\n\t\tlet retryError = \"\";\n\t\t// Set when the stream completes with a \"length\" result that warrants a budget escalation.\n\t\tlet lengthRetry: { previous: number; next: number } | null = null;\n\t\ttry {\n\t\t\tfor await (const event of response) {\n\t\t\t\tswitch (event.type) {\n\t\t\t\t\tcase \"start\":\n\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\tcontext.messages.push(partialMessage);\n\t\t\t\t\t\taddedPartial = true;\n\t\t\t\t\t\tawait emit({ type: \"message_start\", message: { ...partialMessage } });\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"text_start\":\n\t\t\t\t\tcase \"text_delta\":\n\t\t\t\t\tcase \"text_end\":\n\t\t\t\t\tcase \"thinking_start\":\n\t\t\t\t\tcase \"thinking_delta\":\n\t\t\t\t\tcase \"thinking_end\":\n\t\t\t\t\tcase \"toolcall_start\":\n\t\t\t\t\tcase \"toolcall_delta\":\n\t\t\t\t\tcase \"toolcall_end\":\n\t\t\t\t\t\tif (partialMessage) {\n\t\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\t\tcontext.messages[context.messages.length - 1] = partialMessage;\n\t\t\t\t\t\t\tawait emit({\n\t\t\t\t\t\t\t\ttype: \"message_update\",\n\t\t\t\t\t\t\t\tassistantMessageEvent: event,\n\t\t\t\t\t\t\t\tmessage: { ...partialMessage },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"done\":\n\t\t\t\t\tcase \"error\": {\n\t\t\t\t\t\tconst result = await response.result();\n\t\t\t\t\t\t// Check if this is a stream-drop error that should be retried\n\t\t\t\t\t\tconst isDrop = result.stopReason === \"error\" && isStreamDropError(result.errorMessage);\n\t\t\t\t\t\tif (isDrop && streamDropAttempt < maxRetries && !signal?.aborted) {\n\t\t\t\t\t\t\tshouldRetry = true;\n\t\t\t\t\t\t\tretryError =\n\t\t\t\t\t\t\t\tresult.errorMessage ?? \"Stream ended without terminal event — connection likely dropped\";\n\t\t\t\t\t\t} else if (isDrop) {\n\t\t\t\t\t\t\t// Final attempt exhausted — surface friendly message\n\t\t\t\t\t\t\treturn finalizeMessage(\n\t\t\t\t\t\t\t\tcreateErrorMessage(new Error(\"Stream dropped repeatedly — connection likely unstable\")),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else if (result.stopReason === \"length\") {\n\t\t\t\t\t\t\t// The model exhausted its output budget mid-response. Retry with a\n\t\t\t\t\t\t\t// larger budget if we have retries left, the budget can still grow,\n\t\t\t\t\t\t\t// and we have not been aborted. Otherwise, fail loudly below.\n\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t// When no explicit maxTokens was set, the request used the provider\n\t\t\t\t\t\t\t// default budget — Math.min(model.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS),\n\t\t\t\t\t\t\t// NOT the full model ceiling. Resolving the effective budget to the\n\t\t\t\t\t\t\t// real default lets escalation request strictly more, and lets the\n\t\t\t\t\t\t\t// ceiling guard correctly distinguish a default request (which can\n\t\t\t\t\t\t\t// still grow) from one already at the model ceiling.\n\t\t\t\t\t\t\tconst effectiveMaxTokens =\n\t\t\t\t\t\t\t\trequestMaxTokens ?? Math.min(config.model.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS);\n\t\t\t\t\t\t\tconst atCeiling = effectiveMaxTokens >= config.model.maxTokens;\n\t\t\t\t\t\t\tif (lengthAttempts < lengthRetries && !atCeiling && !signal?.aborted) {\n\t\t\t\t\t\t\t\tlengthRetry = {\n\t\t\t\t\t\t\t\t\tprevious: effectiveMaxTokens,\n\t\t\t\t\t\t\t\t\tnext: escalateLengthBudget(effectiveMaxTokens),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\treturn finalizeMessage(createLengthExhaustedMessage(lengthAttempts + 1));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn finalizeMessage(result);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (shouldRetry || lengthRetry) break;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (isStreamDropError(error) && streamDropAttempt < maxRetries && !signal?.aborted) {\n\t\t\t\tshouldRetry = true;\n\t\t\t\tretryError = error instanceof Error ? error.message : String(error);\n\t\t\t} else {\n\t\t\t\tconst surfacedError = isStreamDropError(error)\n\t\t\t\t\t? new Error(\"Stream dropped repeatedly — connection likely unstable\")\n\t\t\t\t\t: error instanceof Error\n\t\t\t\t\t\t? error\n\t\t\t\t\t\t: new Error(String(error));\n\t\t\t\treturn finalizeMessage(createErrorMessage(surfacedError));\n\t\t\t}\n\t\t}\n\n\t\tif (lengthRetry) {\n\t\t\tawait emit({\n\t\t\t\ttype: \"length_retry\",\n\t\t\t\tattempt: lengthAttempts + 1,\n\t\t\t\tmaxAttempts: lengthRetries,\n\t\t\t\tpreviousMaxTokens: lengthRetry.previous,\n\t\t\t\tnextMaxTokens: lengthRetry.next,\n\t\t\t\tdiscardedPartial: clonePartialForDebug(),\n\t\t\t});\n\t\t\tdiscardPartial();\n\t\t\trequestMaxTokens = lengthRetry.next;\n\t\t\tlengthAttempts++;\n\t\t\t// A length retry is a fresh request; reset the stream-drop counter.\n\t\t\tstreamDropAttempt = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (shouldRetry) {\n\t\t\tawait emit({\n\t\t\t\ttype: \"stream_retry\",\n\t\t\t\tattempt: streamDropAttempt + 1,\n\t\t\t\tmaxAttempts: maxRetries,\n\t\t\t\terror: retryError,\n\t\t\t\tdiscardedPartial: clonePartialForDebug(),\n\t\t\t});\n\t\t\tawait sleep(retryBaseDelay * 2 ** streamDropAttempt, signal);\n\t\t\tdiscardPartial();\n\t\t\tstreamDropAttempt++;\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn finalizeMessage(await response.result());\n\t}\n}\n\ninterface ToolExecutionResult {\n\tresults: ToolResultMessage[];\n\tendTurn: boolean;\n}\n\n/**\n * Execute tool calls from an assistant message.\n */\nasync function executeToolCalls(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolExecutionResult> {\n\tconst toolCalls = assistantMessage.content.filter((c) => c.type === \"toolCall\");\n\tif (config.toolExecution === \"sequential\") {\n\t\treturn executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit);\n\t}\n\treturn executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);\n}\n\nasync function executeToolCallsSequential(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolExecutionResult> {\n\tconst results: ToolResultMessage[] = [];\n\tlet endTurn = false;\n\n\tfor (const toolCall of toolCalls) {\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tif (preparation.result.endTurn) endTurn = true;\n\t\t\tresults.push(await emitToolCallOutcome(toolCall, preparation.result, preparation.isError, emit));\n\t\t} else {\n\t\t\tconst executed = await executePreparedToolCall(preparation, signal, emit);\n\t\t\tif (executed.result.endTurn) endTurn = true;\n\t\t\tresults.push(\n\t\t\t\tawait finalizeExecutedToolCall(\n\t\t\t\t\tcurrentContext,\n\t\t\t\t\tassistantMessage,\n\t\t\t\t\tpreparation,\n\t\t\t\t\texecuted,\n\t\t\t\t\tconfig,\n\t\t\t\t\tsignal,\n\t\t\t\t\temit,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\treturn { results, endTurn };\n}\n\nasync function executeToolCallsParallel(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolExecutionResult> {\n\tconst results: ToolResultMessage[] = [];\n\tconst runnableCalls: PreparedToolCall[] = [];\n\tlet endTurn = false;\n\n\tfor (const toolCall of toolCalls) {\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tif (preparation.result.endTurn) endTurn = true;\n\t\t\tresults.push(await emitToolCallOutcome(toolCall, preparation.result, preparation.isError, emit));\n\t\t} else {\n\t\t\trunnableCalls.push(preparation);\n\t\t}\n\t}\n\n\tconst runningCalls = runnableCalls.map((prepared) => ({\n\t\tprepared,\n\t\texecution: executePreparedToolCall(prepared, signal, emit),\n\t}));\n\n\tfor (const running of runningCalls) {\n\t\tconst executed = await running.execution;\n\t\tif (executed.result.endTurn) endTurn = true;\n\t\tresults.push(\n\t\t\tawait finalizeExecutedToolCall(\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\trunning.prepared,\n\t\t\t\texecuted,\n\t\t\t\tconfig,\n\t\t\t\tsignal,\n\t\t\t\temit,\n\t\t\t),\n\t\t);\n\t}\n\n\treturn { results, endTurn };\n}\n\ntype PreparedToolCall = {\n\tkind: \"prepared\";\n\ttoolCall: AgentToolCall;\n\ttool: AgentTool<any>;\n\targs: unknown;\n};\n\ntype ImmediateToolCallOutcome = {\n\tkind: \"immediate\";\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n};\n\ntype ExecutedToolCallOutcome = {\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n};\n\nasync function prepareToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCall: AgentToolCall,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<PreparedToolCall | ImmediateToolCallOutcome> {\n\tconst tool = currentContext.tools?.find((t) => t.name === toolCall.name);\n\tif (!tool) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(`Tool ${toolCall.name} not found`),\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\ttry {\n\t\tconst validatedArgs = validateToolArguments(tool, toolCall);\n\t\tif (config.beforeToolCall) {\n\t\t\tconst beforeResult = await config.beforeToolCall(\n\t\t\t\t{\n\t\t\t\t\tassistantMessage,\n\t\t\t\t\ttoolCall,\n\t\t\t\t\targs: validatedArgs,\n\t\t\t\t\tcontext: currentContext,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (beforeResult?.block) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"immediate\",\n\t\t\t\t\tresult: createErrorToolResult(beforeResult.reason || \"Tool execution was blocked\"),\n\t\t\t\t\tisError: true,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tkind: \"prepared\",\n\t\t\ttoolCall,\n\t\t\ttool,\n\t\t\targs: validatedArgs,\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t\t\tisError: true,\n\t\t};\n\t}\n}\n\nasync function executePreparedToolCall(\n\tprepared: PreparedToolCall,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallOutcome> {\n\tconst updateEvents: Promise<void>[] = [];\n\n\ttry {\n\t\tconst result = await prepared.tool.execute(\n\t\t\tprepared.toolCall.id,\n\t\t\tprepared.args as never,\n\t\t\tsignal,\n\t\t\t(partialResult) => {\n\t\t\t\tupdateEvents.push(\n\t\t\t\t\tPromise.resolve(\n\t\t\t\t\t\temit({\n\t\t\t\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\t\t\t\targs: prepared.toolCall.arguments,\n\t\t\t\t\t\t\tpartialResult,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t},\n\t\t);\n\t\tawait Promise.all(updateEvents);\n\t\treturn { result, isError: false };\n\t} catch (error) {\n\t\tawait Promise.all(updateEvents);\n\t\treturn {\n\t\t\tresult: createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t\t\tisError: true,\n\t\t};\n\t}\n}\n\nasync function finalizeExecutedToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tprepared: PreparedToolCall,\n\texecuted: ExecutedToolCallOutcome,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolResultMessage> {\n\tlet result = executed.result;\n\tlet isError = executed.isError;\n\n\tif (config.afterToolCall) {\n\t\tconst afterResult = await config.afterToolCall(\n\t\t\t{\n\t\t\t\tassistantMessage,\n\t\t\t\ttoolCall: prepared.toolCall,\n\t\t\t\targs: prepared.args,\n\t\t\t\tresult,\n\t\t\t\tisError,\n\t\t\t\tcontext: currentContext,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t\tif (afterResult) {\n\t\t\tresult = {\n\t\t\t\tcontent: afterResult.content ?? result.content,\n\t\t\t\tdetails: afterResult.details ?? result.details,\n\t\t\t};\n\t\t\tisError = afterResult.isError ?? isError;\n\t\t}\n\t}\n\n\treturn await emitToolCallOutcome(prepared.toolCall, result, isError, emit);\n}\n\nfunction createErrorToolResult(message: string): AgentToolResult<any> {\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\tdetails: {},\n\t};\n}\n\nasync function emitToolCallOutcome(\n\ttoolCall: AgentToolCall,\n\tresult: AgentToolResult<any>,\n\tisError: boolean,\n\temit: AgentEventSink,\n): Promise<ToolResultMessage> {\n\tawait emit({\n\t\ttype: \"tool_execution_end\",\n\t\ttoolCallId: toolCall.id,\n\t\ttoolName: toolCall.name,\n\t\tresult,\n\t\tisError,\n\t});\n\n\tconst toolResultMessage: ToolResultMessage = {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: toolCall.id,\n\t\ttoolName: toolCall.name,\n\t\tcontent: result.content,\n\t\tdetails: result.details,\n\t\tisError,\n\t\ttimestamp: Date.now(),\n\t};\n\n\tawait emit({ type: \"message_start\", message: toolResultMessage });\n\tawait emit({ type: \"message_end\", message: toolResultMessage });\n\treturn toolResultMessage;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent-loop.js","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAGN,yBAAyB,EACzB,WAAW,EACX,YAAY,EACZ,WAAW,EACX,aAAa,EAEb,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AE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;QAC1C,OAAO,EAAE,EAAE;KACX,CAAC;AAAA,CACF;AAED,KAAK,UAAU,mBAAmB,CACjC,QAAuB,EACvB,MAA4B,EAC5B,OAAgB,EAChB,IAAoB,EACS;IAC7B,MAAM,IAAI,CAAC;QACV,IAAI,EAAE,oBAAoB;QAC1B,UAAU,EAAE,QAAQ,CAAC,EAAE;QACvB,QAAQ,EAAE,QAAQ,CAAC,IAAI;QACvB,MAAM;QACN,OAAO;KACP,CAAC,CAAC;IAEH,MAAM,iBAAiB,GAAsB;QAC5C,IAAI,EAAE,YAAY;QAClB,UAAU,EAAE,QAAQ,CAAC,EAAE;QACvB,QAAQ,EAAE,QAAQ,CAAC,IAAI;QACvB,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,OAAO;QACP,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;KACrB,CAAC;IAEF,MAAM,IAAI,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;IAClE,MAAM,IAAI,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;IAChE,OAAO,iBAAiB,CAAC;AAAA,CACzB","sourcesContent":["/**\n * Agent loop that works with AgentMessage throughout.\n * Transforms to Message[] only at the LLM call boundary.\n */\n\nimport {\n\ttype AssistantMessage,\n\ttype Context,\n\tDEFAULT_MAX_OUTPUT_TOKENS,\n\tEventStream,\n\tstreamSimple,\n\tsupportsMax,\n\tsupportsXhigh,\n\ttype ToolResultMessage,\n\tvalidateToolArguments,\n} from \"@dreb/ai\";\nimport type {\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolCall,\n\tAgentToolResult,\n\tStreamFn,\n\tThinkingLevel,\n} from \"./types.js\";\n\nexport type AgentEventSink = (event: AgentEvent) => Promise<void> | void;\n\nfunction getEffectiveThinkingLevel(config: AgentLoopConfig): ThinkingLevel {\n\tconst requested = config.reasoning ?? \"off\";\n\tif (!config.model.reasoning) return \"off\";\n\tif (requested === \"max\" && !supportsMax(config.model)) return supportsXhigh(config.model) ? \"xhigh\" : \"high\";\n\treturn requested === \"xhigh\" && !supportsXhigh(config.model) ? \"high\" : requested;\n}\n\n/**\n * Start an agent loop with a new prompt message.\n * The prompt is added to the context and events are emitted for it.\n */\nexport function agentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tconst stream = createAgentStream();\n\n\tvoid runAgentLoop(\n\t\tprompts,\n\t\tcontext,\n\t\tconfig,\n\t\tasync (event) => {\n\t\t\tstream.push(event);\n\t\t},\n\t\tsignal,\n\t\tstreamFn,\n\t).then((messages) => {\n\t\tstream.end(messages);\n\t});\n\n\treturn stream;\n}\n\n/**\n * Continue an agent loop from the current context without adding a new message.\n * Used for retries - context already has user message or tool results.\n *\n * **Important:** The last message in context must convert to a `user` or `toolResult` message\n * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.\n * This cannot be validated here since `convertToLlm` is only called once per turn.\n */\nexport function agentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): EventStream<AgentEvent, AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst stream = createAgentStream();\n\n\tvoid runAgentLoopContinue(\n\t\tcontext,\n\t\tconfig,\n\t\tasync (event) => {\n\t\t\tstream.push(event);\n\t\t},\n\t\tsignal,\n\t\tstreamFn,\n\t).then((messages) => {\n\t\tstream.end(messages);\n\t});\n\n\treturn stream;\n}\n\nexport async function runAgentLoop(\n\tprompts: AgentMessage[],\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tconst newMessages: AgentMessage[] = [...prompts];\n\tconst currentContext: AgentContext = {\n\t\t...context,\n\t\tmessages: [...context.messages, ...prompts],\n\t};\n\n\tawait emit({\n\t\ttype: \"agent_start\",\n\t\tmodel: { provider: config.model.provider, id: config.model.id },\n\t\tthinkingLevel: getEffectiveThinkingLevel(config),\n\t});\n\tawait emit({ type: \"turn_start\" });\n\tfor (const prompt of prompts) {\n\t\tawait emit({ type: \"message_start\", message: prompt });\n\t\tawait emit({ type: \"message_end\", message: prompt });\n\t}\n\n\tawait runLoop(currentContext, newMessages, config, signal, emit, streamFn);\n\treturn newMessages;\n}\n\nexport async function runAgentLoopContinue(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\temit: AgentEventSink,\n\tsignal?: AbortSignal,\n\tstreamFn?: StreamFn,\n): Promise<AgentMessage[]> {\n\tif (context.messages.length === 0) {\n\t\tthrow new Error(\"Cannot continue: no messages in context\");\n\t}\n\n\tif (context.messages[context.messages.length - 1].role === \"assistant\") {\n\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t}\n\n\tconst newMessages: AgentMessage[] = [];\n\tconst currentContext: AgentContext = { ...context };\n\n\tawait emit({\n\t\ttype: \"agent_start\",\n\t\tmodel: { provider: config.model.provider, id: config.model.id },\n\t\tthinkingLevel: getEffectiveThinkingLevel(config),\n\t});\n\tawait emit({ type: \"turn_start\" });\n\n\tawait runLoop(currentContext, newMessages, config, signal, emit, streamFn);\n\treturn newMessages;\n}\n\nfunction createAgentStream(): EventStream<AgentEvent, AgentMessage[]> {\n\treturn new EventStream<AgentEvent, AgentMessage[]>(\n\t\t(event: AgentEvent) => event.type === \"agent_end\",\n\t\t(event: AgentEvent) => (event.type === \"agent_end\" ? event.messages : []),\n\t);\n}\n\n/**\n * Main loop logic shared by agentLoop and agentLoopContinue.\n */\nasync function runLoop(\n\tcurrentContext: AgentContext,\n\tnewMessages: AgentMessage[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n): Promise<void> {\n\tlet firstTurn = true;\n\tlet endTurnRequested = false;\n\tlet llmCallCount = 0;\n\t// Check for steering messages at start (user may have typed while waiting)\n\tlet pendingMessages: AgentMessage[] = (await config.getSteeringMessages?.()) || [];\n\n\t// Outer loop: continues when queued follow-up messages arrive after agent would stop\n\twhile (true) {\n\t\tlet hasMoreToolCalls = true;\n\t\tendTurnRequested = false;\n\n\t\t// Inner loop: process tool calls and steering messages\n\t\twhile (hasMoreToolCalls || pendingMessages.length > 0) {\n\t\t\t// Process pending messages first (inject into context so they're never lost).\n\t\t\t// This happens before turn_start and shouldContinue so messages are always\n\t\t\t// preserved regardless of whether the turn proceeds.\n\t\t\tif (pendingMessages.length > 0) {\n\t\t\t\tfor (const message of pendingMessages) {\n\t\t\t\t\tawait emit({ type: \"message_start\", message });\n\t\t\t\t\tawait emit({ type: \"message_end\", message });\n\t\t\t\t\tcurrentContext.messages.push(message);\n\t\t\t\t\tnewMessages.push(message);\n\t\t\t\t}\n\t\t\t\tpendingMessages = [];\n\t\t\t}\n\n\t\t\t// Check shouldContinue before starting a new turn (not the very first).\n\t\t\t// This runs before turn_start so we never emit an orphaned turn_start.\n\t\t\tif (llmCallCount > 0 && config.shouldContinue && !config.shouldContinue()) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (!firstTurn) {\n\t\t\t\tawait emit({ type: \"turn_start\" });\n\t\t\t} else {\n\t\t\t\tfirstTurn = false;\n\t\t\t}\n\n\t\t\t// Stream assistant response\n\t\t\tconst message = await streamAssistantResponse(currentContext, config, signal, emit, streamFn);\n\t\t\tnewMessages.push(message);\n\t\t\tllmCallCount++;\n\n\t\t\tif (message.stopReason === \"error\" || message.stopReason === \"aborted\") {\n\t\t\t\tawait emit({ type: \"turn_end\", message, toolResults: [] });\n\t\t\t\tawait emit({ type: \"agent_end\", messages: newMessages });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Check for tool calls\n\t\t\tconst toolCalls = message.content.filter((c) => c.type === \"toolCall\");\n\t\t\thasMoreToolCalls = toolCalls.length > 0;\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\tif (hasMoreToolCalls) {\n\t\t\t\tconst executionResult = await executeToolCalls(currentContext, message, config, signal, emit);\n\t\t\t\ttoolResults.push(...executionResult.results);\n\n\t\t\t\tfor (const result of toolResults) {\n\t\t\t\t\tcurrentContext.messages.push(result);\n\t\t\t\t\tnewMessages.push(result);\n\t\t\t\t}\n\n\t\t\t\tif (executionResult.endTurn) {\n\t\t\t\t\tendTurnRequested = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait emit({ type: \"turn_end\", message, toolResults });\n\n\t\t\t// If a tool requested endTurn, stop the loop (skip further LLM calls)\n\t\t\tif (endTurnRequested) {\n\t\t\t\thasMoreToolCalls = false;\n\t\t\t\tpendingMessages = [];\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tpendingMessages = (await config.getSteeringMessages?.()) || [];\n\t\t}\n\n\t\t// Agent would stop here. Drain any steering messages that arrived during\n\t\t// wind-down (e.g., background agent results delivered via steer() between\n\t\t// endTurn break and here). Then check for follow-up messages.\n\t\tconst leftoverSteering = (await config.getSteeringMessages?.()) || [];\n\t\tconst followUpMessages = (await config.getFollowUpMessages?.()) || [];\n\t\tconst allPending = [...leftoverSteering, ...followUpMessages];\n\t\tif (allPending.length > 0) {\n\t\t\t// Set as pending so inner loop processes them\n\t\t\tpendingMessages = allPending;\n\t\t\tcontinue;\n\t\t}\n\n\t\t// No more messages, exit\n\t\tbreak;\n\t}\n\n\tawait emit({ type: \"agent_end\", messages: newMessages });\n}\n\n/**\n * Check if an error is a stream-drop error (connection dropped before terminal event).\n * Only these errors trigger automatic retry — all other errors propagate as-is.\n */\nfunction isStreamDropError(error: unknown): boolean {\n\tconst msg = error instanceof Error ? error.message : typeof error === \"string\" ? error : \"\";\n\treturn (\n\t\tmsg.includes(\"Stream ended without\") ||\n\t\tmsg.includes(\"connection likely dropped\") ||\n\t\tmsg.includes(\"WebSocket stream closed before\")\n\t);\n}\n\n/**\n * Sleep for a duration, aborting early if the signal fires.\n */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tif (signal?.aborted) {\n\t\t\tresolve();\n\t\t\treturn;\n\t\t}\n\t\tconst timer = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\n\t\t\t\"abort\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t});\n}\n\n/**\n * Stream an assistant response from the LLM.\n * This is where AgentMessage[] gets transformed to Message[] for the LLM.\n */\nasync function streamAssistantResponse(\n\tcontext: AgentContext,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n\tstreamFn?: StreamFn,\n): Promise<AssistantMessage> {\n\t// Apply context transform if configured (AgentMessage[] → AgentMessage[])\n\tlet messages = context.messages;\n\tif (config.transformContext) {\n\t\tmessages = await config.transformContext(messages, signal);\n\t}\n\n\t// Convert to LLM-compatible messages (AgentMessage[] → Message[])\n\tconst llmMessages = await config.convertToLlm(messages);\n\n\t// Build LLM context\n\tconst llmContext: Context = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\tmessages: llmMessages,\n\t\ttools: context.tools,\n\t};\n\n\tconst streamFunction = streamFn || streamSimple;\n\n\t// Resolve API key (important for expiring tokens)\n\tconst resolvedApiKey =\n\t\t(config.getApiKey ? await config.getApiKey(config.model.provider) : undefined) || config.apiKey;\n\n\tconst streamStart = performance.now();\n\tlet partialMessage: AssistantMessage | null = null;\n\tlet addedPartial = false;\n\n\tconst finalizeMessage = async (finalMessage: AssistantMessage): Promise<AssistantMessage> => {\n\t\tfinalMessage.durationMs = Math.max(0, performance.now() - streamStart);\n\t\tif (addedPartial) {\n\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t} else {\n\t\t\tcontext.messages.push(finalMessage);\n\t\t}\n\t\tif (!addedPartial) {\n\t\t\tawait emit({ type: \"message_start\", message: { ...finalMessage } });\n\t\t}\n\t\tawait emit({ type: \"message_end\", message: finalMessage });\n\t\treturn finalMessage;\n\t};\n\n\tconst createErrorMessage = (error: unknown): AssistantMessage => ({\n\t\trole: \"assistant\",\n\t\tcontent: partialMessage?.content ?? [{ type: \"text\", text: \"\" }],\n\t\tapi: config.model.api,\n\t\tprovider: config.model.provider,\n\t\tmodel: config.model.id,\n\t\tusage: partialMessage?.usage ?? {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: signal?.aborted ? \"aborted\" : \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: partialMessage?.timestamp ?? Date.now(),\n\t});\n\n\tconst maxRetries = config.streamRetries ?? 3;\n\tconst retryBaseDelay = config.streamRetryBaseDelayMs ?? 1000;\n\tconst lengthRetries = config.lengthRetries ?? 2;\n\tconst lengthMultiplier = config.lengthRetryBudgetMultiplier ?? 2;\n\t// The maxTokens budget requested for the current attempt. Starts at the\n\t// caller-configured budget (may be undefined → provider default) and is\n\t// escalated on each length retry. Kept separate from stream-drop retries.\n\tlet requestMaxTokens = config.maxTokens;\n\tlet lengthAttempts = 0;\n\tconst clonePartialForDebug = (): AssistantMessage | undefined => {\n\t\tif (!partialMessage) return undefined;\n\t\treturn {\n\t\t\t...partialMessage,\n\t\t\tcontent: partialMessage.content.map((block) => ({ ...block })),\n\t\t\tusage: { ...partialMessage.usage, cost: { ...partialMessage.usage.cost } },\n\t\t};\n\t};\n\n\t// Discard the truncated partial message (if any) before re-issuing a request.\n\tconst discardPartial = () => {\n\t\tif (addedPartial) {\n\t\t\tcontext.messages.pop();\n\t\t\taddedPartial = false;\n\t\t}\n\t\tpartialMessage = null;\n\t};\n\n\t// Compute the escalated token budget for a length retry, never exceeding the\n\t// model's ceiling. `current` is the *effective* budget that produced the\n\t// truncated response (resolved from the provider default when no explicit\n\t// maxTokens was set), so the escalation always requests strictly more.\n\tconst escalateLengthBudget = (current: number): number => {\n\t\tconst ceiling = config.model.maxTokens;\n\t\treturn Math.min(Math.ceil(current * lengthMultiplier), ceiling);\n\t};\n\n\t// Build the truncation failure message after length retries are exhausted.\n\tconst createLengthExhaustedMessage = (attempts: number): AssistantMessage => {\n\t\tconst errorMessage = createErrorMessage(\n\t\t\tnew Error(\n\t\t\t\t`Response truncated at token limit after ${attempts} attempt${attempts === 1 ? \"\" : \"s\"} — output exceeded the model's maximum token budget`,\n\t\t\t),\n\t\t);\n\t\t// Force \"error\" so the runLoop error guard terminates the turn loudly.\n\t\terrorMessage.stopReason = signal?.aborted ? \"aborted\" : \"error\";\n\t\treturn errorMessage;\n\t};\n\n\t// stream-drop retries are counted separately from length retries. A length retry\n\t// is a fresh request, so it resets the stream-drop attempt counter.\n\tlet streamDropAttempt = 0;\n\twhile (true) {\n\t\tlet response: Awaited<ReturnType<StreamFn>>;\n\t\ttry {\n\t\t\tresponse = await streamFunction(config.model, llmContext, {\n\t\t\t\t...config,\n\t\t\t\tmaxTokens: requestMaxTokens,\n\t\t\t\tapiKey: resolvedApiKey,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (isStreamDropError(error) && streamDropAttempt < maxRetries && !signal?.aborted) {\n\t\t\t\tawait emit({\n\t\t\t\t\ttype: \"stream_retry\",\n\t\t\t\t\tattempt: streamDropAttempt + 1,\n\t\t\t\t\tmaxAttempts: maxRetries,\n\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\tdiscardedPartial: clonePartialForDebug(),\n\t\t\t\t});\n\t\t\t\tawait sleep(retryBaseDelay * 2 ** streamDropAttempt, signal);\n\t\t\t\tdiscardPartial();\n\t\t\t\tstreamDropAttempt++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst surfacedError = isStreamDropError(error)\n\t\t\t\t? new Error(\"Stream dropped repeatedly — connection likely unstable\")\n\t\t\t\t: error instanceof Error\n\t\t\t\t\t? error\n\t\t\t\t\t: new Error(String(error));\n\t\t\treturn finalizeMessage(createErrorMessage(surfacedError));\n\t\t}\n\n\t\tlet shouldRetry = false;\n\t\tlet retryError = \"\";\n\t\t// Set when the stream completes with a \"length\" result that warrants a budget escalation.\n\t\tlet lengthRetry: { previous: number; next: number } | null = null;\n\t\ttry {\n\t\t\tfor await (const event of response) {\n\t\t\t\tswitch (event.type) {\n\t\t\t\t\tcase \"start\":\n\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\tcontext.messages.push(partialMessage);\n\t\t\t\t\t\taddedPartial = true;\n\t\t\t\t\t\tawait emit({ type: \"message_start\", message: { ...partialMessage } });\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"text_start\":\n\t\t\t\t\tcase \"text_delta\":\n\t\t\t\t\tcase \"text_end\":\n\t\t\t\t\tcase \"thinking_start\":\n\t\t\t\t\tcase \"thinking_delta\":\n\t\t\t\t\tcase \"thinking_end\":\n\t\t\t\t\tcase \"toolcall_start\":\n\t\t\t\t\tcase \"toolcall_delta\":\n\t\t\t\t\tcase \"toolcall_end\":\n\t\t\t\t\t\tif (partialMessage) {\n\t\t\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\t\t\tcontext.messages[context.messages.length - 1] = partialMessage;\n\t\t\t\t\t\t\tawait emit({\n\t\t\t\t\t\t\t\ttype: \"message_update\",\n\t\t\t\t\t\t\t\tassistantMessageEvent: event,\n\t\t\t\t\t\t\t\tmessage: { ...partialMessage },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \"done\":\n\t\t\t\t\tcase \"error\": {\n\t\t\t\t\t\tconst result = await response.result();\n\t\t\t\t\t\t// Check if this is a stream-drop error that should be retried\n\t\t\t\t\t\tconst isDrop = result.stopReason === \"error\" && isStreamDropError(result.errorMessage);\n\t\t\t\t\t\tif (isDrop && streamDropAttempt < maxRetries && !signal?.aborted) {\n\t\t\t\t\t\t\tshouldRetry = true;\n\t\t\t\t\t\t\tretryError =\n\t\t\t\t\t\t\t\tresult.errorMessage ?? \"Stream ended without terminal event — connection likely dropped\";\n\t\t\t\t\t\t} else if (isDrop) {\n\t\t\t\t\t\t\t// Final attempt exhausted — surface friendly message\n\t\t\t\t\t\t\treturn finalizeMessage(\n\t\t\t\t\t\t\t\tcreateErrorMessage(new Error(\"Stream dropped repeatedly — connection likely unstable\")),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else if (result.stopReason === \"length\") {\n\t\t\t\t\t\t\t// The model exhausted its output budget mid-response. Retry with a\n\t\t\t\t\t\t\t// larger budget if we have retries left, the budget can still grow,\n\t\t\t\t\t\t\t// and we have not been aborted. Otherwise, fail loudly below.\n\t\t\t\t\t\t\t//\n\t\t\t\t\t\t\t// When no explicit maxTokens was set, the request used the provider\n\t\t\t\t\t\t\t// default budget — Math.min(model.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS),\n\t\t\t\t\t\t\t// NOT the full model ceiling. Resolving the effective budget to the\n\t\t\t\t\t\t\t// real default lets escalation request strictly more, and lets the\n\t\t\t\t\t\t\t// ceiling guard correctly distinguish a default request (which can\n\t\t\t\t\t\t\t// still grow) from one already at the model ceiling.\n\t\t\t\t\t\t\tconst effectiveMaxTokens =\n\t\t\t\t\t\t\t\trequestMaxTokens ?? Math.min(config.model.maxTokens, DEFAULT_MAX_OUTPUT_TOKENS);\n\t\t\t\t\t\t\tconst atCeiling = effectiveMaxTokens >= config.model.maxTokens;\n\t\t\t\t\t\t\tif (lengthAttempts < lengthRetries && !atCeiling && !signal?.aborted) {\n\t\t\t\t\t\t\t\tlengthRetry = {\n\t\t\t\t\t\t\t\t\tprevious: effectiveMaxTokens,\n\t\t\t\t\t\t\t\t\tnext: escalateLengthBudget(effectiveMaxTokens),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\treturn finalizeMessage(createLengthExhaustedMessage(lengthAttempts + 1));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn finalizeMessage(result);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (shouldRetry || lengthRetry) break;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (isStreamDropError(error) && streamDropAttempt < maxRetries && !signal?.aborted) {\n\t\t\t\tshouldRetry = true;\n\t\t\t\tretryError = error instanceof Error ? error.message : String(error);\n\t\t\t} else {\n\t\t\t\tconst surfacedError = isStreamDropError(error)\n\t\t\t\t\t? new Error(\"Stream dropped repeatedly — connection likely unstable\")\n\t\t\t\t\t: error instanceof Error\n\t\t\t\t\t\t? error\n\t\t\t\t\t\t: new Error(String(error));\n\t\t\t\treturn finalizeMessage(createErrorMessage(surfacedError));\n\t\t\t}\n\t\t}\n\n\t\tif (lengthRetry) {\n\t\t\tawait emit({\n\t\t\t\ttype: \"length_retry\",\n\t\t\t\tattempt: lengthAttempts + 1,\n\t\t\t\tmaxAttempts: lengthRetries,\n\t\t\t\tpreviousMaxTokens: lengthRetry.previous,\n\t\t\t\tnextMaxTokens: lengthRetry.next,\n\t\t\t\tdiscardedPartial: clonePartialForDebug(),\n\t\t\t});\n\t\t\tdiscardPartial();\n\t\t\trequestMaxTokens = lengthRetry.next;\n\t\t\tlengthAttempts++;\n\t\t\t// A length retry is a fresh request; reset the stream-drop counter.\n\t\t\tstreamDropAttempt = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (shouldRetry) {\n\t\t\tawait emit({\n\t\t\t\ttype: \"stream_retry\",\n\t\t\t\tattempt: streamDropAttempt + 1,\n\t\t\t\tmaxAttempts: maxRetries,\n\t\t\t\terror: retryError,\n\t\t\t\tdiscardedPartial: clonePartialForDebug(),\n\t\t\t});\n\t\t\tawait sleep(retryBaseDelay * 2 ** streamDropAttempt, signal);\n\t\t\tdiscardPartial();\n\t\t\tstreamDropAttempt++;\n\t\t\tcontinue;\n\t\t}\n\n\t\treturn finalizeMessage(await response.result());\n\t}\n}\n\ninterface ToolExecutionResult {\n\tresults: ToolResultMessage[];\n\tendTurn: boolean;\n}\n\n/**\n * Execute tool calls from an assistant message.\n */\nasync function executeToolCalls(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolExecutionResult> {\n\tconst toolCalls = assistantMessage.content.filter((c) => c.type === \"toolCall\");\n\tif (config.toolExecution === \"sequential\") {\n\t\treturn executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit);\n\t}\n\treturn executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);\n}\n\nasync function executeToolCallsSequential(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolExecutionResult> {\n\tconst results: ToolResultMessage[] = [];\n\tlet endTurn = false;\n\n\tfor (const toolCall of toolCalls) {\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tif (preparation.result.endTurn) endTurn = true;\n\t\t\tresults.push(await emitToolCallOutcome(toolCall, preparation.result, preparation.isError, emit));\n\t\t} else {\n\t\t\tconst executed = await executePreparedToolCall(preparation, signal, emit);\n\t\t\tif (executed.result.endTurn) endTurn = true;\n\t\t\tresults.push(\n\t\t\t\tawait finalizeExecutedToolCall(\n\t\t\t\t\tcurrentContext,\n\t\t\t\t\tassistantMessage,\n\t\t\t\t\tpreparation,\n\t\t\t\t\texecuted,\n\t\t\t\t\tconfig,\n\t\t\t\t\tsignal,\n\t\t\t\t\temit,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\treturn { results, endTurn };\n}\n\nasync function executeToolCallsParallel(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCalls: AgentToolCall[],\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolExecutionResult> {\n\tconst results: ToolResultMessage[] = [];\n\tconst runnableCalls: PreparedToolCall[] = [];\n\tlet endTurn = false;\n\n\tfor (const toolCall of toolCalls) {\n\t\tawait emit({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tconst preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);\n\t\tif (preparation.kind === \"immediate\") {\n\t\t\tif (preparation.result.endTurn) endTurn = true;\n\t\t\tresults.push(await emitToolCallOutcome(toolCall, preparation.result, preparation.isError, emit));\n\t\t} else {\n\t\t\trunnableCalls.push(preparation);\n\t\t}\n\t}\n\n\tconst runningCalls = runnableCalls.map((prepared) => ({\n\t\tprepared,\n\t\texecution: executePreparedToolCall(prepared, signal, emit),\n\t}));\n\n\tfor (const running of runningCalls) {\n\t\tconst executed = await running.execution;\n\t\tif (executed.result.endTurn) endTurn = true;\n\t\tresults.push(\n\t\t\tawait finalizeExecutedToolCall(\n\t\t\t\tcurrentContext,\n\t\t\t\tassistantMessage,\n\t\t\t\trunning.prepared,\n\t\t\t\texecuted,\n\t\t\t\tconfig,\n\t\t\t\tsignal,\n\t\t\t\temit,\n\t\t\t),\n\t\t);\n\t}\n\n\treturn { results, endTurn };\n}\n\ntype PreparedToolCall = {\n\tkind: \"prepared\";\n\ttoolCall: AgentToolCall;\n\ttool: AgentTool<any>;\n\targs: unknown;\n};\n\ntype ImmediateToolCallOutcome = {\n\tkind: \"immediate\";\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n};\n\ntype ExecutedToolCallOutcome = {\n\tresult: AgentToolResult<any>;\n\tisError: boolean;\n};\n\nasync function prepareToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\ttoolCall: AgentToolCall,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<PreparedToolCall | ImmediateToolCallOutcome> {\n\tconst tool = currentContext.tools?.find((t) => t.name === toolCall.name);\n\tif (!tool) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(`Tool ${toolCall.name} not found`),\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\ttry {\n\t\tconst validatedArgs = validateToolArguments(tool, toolCall);\n\t\tif (config.beforeToolCall) {\n\t\t\tconst beforeResult = await config.beforeToolCall(\n\t\t\t\t{\n\t\t\t\t\tassistantMessage,\n\t\t\t\t\ttoolCall,\n\t\t\t\t\targs: validatedArgs,\n\t\t\t\t\tcontext: currentContext,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\tif (beforeResult?.block) {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"immediate\",\n\t\t\t\t\tresult: createErrorToolResult(beforeResult.reason || \"Tool execution was blocked\"),\n\t\t\t\t\tisError: true,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tkind: \"prepared\",\n\t\t\ttoolCall,\n\t\t\ttool,\n\t\t\targs: validatedArgs,\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tkind: \"immediate\",\n\t\t\tresult: createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t\t\tisError: true,\n\t\t};\n\t}\n}\n\nasync function executePreparedToolCall(\n\tprepared: PreparedToolCall,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ExecutedToolCallOutcome> {\n\tconst updateEvents: Promise<void>[] = [];\n\n\ttry {\n\t\tconst result = await prepared.tool.execute(\n\t\t\tprepared.toolCall.id,\n\t\t\tprepared.args as never,\n\t\t\tsignal,\n\t\t\t(partialResult) => {\n\t\t\t\tupdateEvents.push(\n\t\t\t\t\tPromise.resolve(\n\t\t\t\t\t\temit({\n\t\t\t\t\t\t\ttype: \"tool_execution_update\",\n\t\t\t\t\t\t\ttoolCallId: prepared.toolCall.id,\n\t\t\t\t\t\t\ttoolName: prepared.toolCall.name,\n\t\t\t\t\t\t\targs: prepared.toolCall.arguments,\n\t\t\t\t\t\t\tpartialResult,\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t},\n\t\t);\n\t\tawait Promise.all(updateEvents);\n\t\treturn { result, isError: false };\n\t} catch (error) {\n\t\tawait Promise.all(updateEvents);\n\t\treturn {\n\t\t\tresult: createErrorToolResult(error instanceof Error ? error.message : String(error)),\n\t\t\tisError: true,\n\t\t};\n\t}\n}\n\nasync function finalizeExecutedToolCall(\n\tcurrentContext: AgentContext,\n\tassistantMessage: AssistantMessage,\n\tprepared: PreparedToolCall,\n\texecuted: ExecutedToolCallOutcome,\n\tconfig: AgentLoopConfig,\n\tsignal: AbortSignal | undefined,\n\temit: AgentEventSink,\n): Promise<ToolResultMessage> {\n\tlet result = executed.result;\n\tlet isError = executed.isError;\n\n\tif (config.afterToolCall) {\n\t\tconst afterResult = await config.afterToolCall(\n\t\t\t{\n\t\t\t\tassistantMessage,\n\t\t\t\ttoolCall: prepared.toolCall,\n\t\t\t\targs: prepared.args,\n\t\t\t\tresult,\n\t\t\t\tisError,\n\t\t\t\tcontext: currentContext,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t\tif (afterResult) {\n\t\t\tresult = {\n\t\t\t\tcontent: afterResult.content ?? result.content,\n\t\t\t\tdetails: afterResult.details ?? result.details,\n\t\t\t};\n\t\t\tisError = afterResult.isError ?? isError;\n\t\t}\n\t}\n\n\treturn await emitToolCallOutcome(prepared.toolCall, result, isError, emit);\n}\n\nfunction createErrorToolResult(message: string): AgentToolResult<any> {\n\treturn {\n\t\tcontent: [{ type: \"text\", text: message }],\n\t\tdetails: {},\n\t};\n}\n\nasync function emitToolCallOutcome(\n\ttoolCall: AgentToolCall,\n\tresult: AgentToolResult<any>,\n\tisError: boolean,\n\temit: AgentEventSink,\n): Promise<ToolResultMessage> {\n\tawait emit({\n\t\ttype: \"tool_execution_end\",\n\t\ttoolCallId: toolCall.id,\n\t\ttoolName: toolCall.name,\n\t\tresult,\n\t\tisError,\n\t});\n\n\tconst toolResultMessage: ToolResultMessage = {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: toolCall.id,\n\t\ttoolName: toolCall.name,\n\t\tcontent: result.content,\n\t\tdetails: result.details,\n\t\tisError,\n\t\ttimestamp: Date.now(),\n\t};\n\n\tawait emit({ type: \"message_start\", message: toolResultMessage });\n\tawait emit({ type: \"message_end\", message: toolResultMessage });\n\treturn toolResultMessage;\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -230,7 +230,7 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
|
|
|
230
230
|
* Thinking/reasoning level for models that support it.
|
|
231
231
|
* Note: "xhigh" is only supported by OpenAI reasoning models that explicitly advertise extended reasoning (for example GPT-5.2+ and Codex GPT-5.3+).
|
|
232
232
|
*/
|
|
233
|
-
export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
|
|
233
|
+
export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
|
234
234
|
/**
|
|
235
235
|
* Extensible interface for custom app messages.
|
|
236
236
|
* Apps can extend via declaration merging:
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,gBAAgB,EAChB,qBAAqB,EACrB,YAAY,EACZ,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,YAAY,EACZ,WAAW,EACX,IAAI,EACJ,iBAAiB,EACjB,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAEzD;;;;;;;;GAQG;AACH,MAAM,MAAM,QAAQ,GAAG,CACtB,GAAG,IAAI,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,KACpC,UAAU,CAAC,OAAO,YAAY,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC;AAEhF;;;;;;GAMG;AACH,MAAM,MAAM,iBAAiB,GAAG,YAAY,GAAG,UAAU,CAAC;AAE1D,wEAAwE;AACxE,MAAM,MAAM,aAAa,GAAG,OAAO,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,EAAE;IAAE,IAAI,EAAE,UAAU,CAAA;CAAE,CAAC,CAAC;AAE/F;;;;;GAKG;AACH,MAAM,WAAW,oBAAoB;IACpC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;;;;GAUG;AACH,MAAM,WAAW,mBAAmB;IACnC,OAAO,CAAC,EAAE,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,CAAC;IACzC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,OAAO,CAAC,EAAE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AAW,EAAE,MAAM,CAAC;IACpB,2DAA2D;IAC3D,iBAAiB,EAAE,MAAM,CAAC;IAC1B,6DAA6D;IAC7D,aAAa,EAAE,MAAM,CAAC;IACtB,4FAA4F;IAC5F,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;CACnC,CAAC","sourcesContent":["import type {\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tstreamSimple,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n} from \"@dreb/ai\";\nimport type { Static, TSchema } from \"@sinclair/typebox\";\n\n/**\n * Stream function used by the agent loop.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\t...args: Parameters<typeof streamSimple>\n) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then allowed tools execute concurrently.\n * Final tool results are still emitted in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/** A single tool call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content` or `details`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n}\n\n/** Context passed to `beforeToolCall`. */\nexport interface BeforeToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** Current agent context at the time the tool call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** The executed tool result before any `afterToolCall` overrides are applied. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed tool result is currently treated as an error. */\n\tisError: boolean;\n\t/** Current agent context at the time the tool call is finalized. */\n\tcontext: AgentContext;\n}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools concurrently\n\t *\n\t * Default: \"parallel\"\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Called before each LLM call in the inner loop. If it returns false,\n\t * the loop exits cleanly as if no more tool calls were pending.\n\t *\n\t * Use this to enforce turn limits or other dynamic stopping conditions.\n\t * The callback is NOT called before the very first LLM call of a run —\n\t * only before subsequent calls triggered by tool results or steering.\n\t */\n\tshouldContinue?: () => boolean;\n\n\t/**\n\t * Maximum number of times to retry when a stream drops mid-response.\n\t * Retries only trigger on detected stream-drop errors (connection dropped before\n\t * the provider sent its terminal completion event). Other errors are not retried.\n\t *\n\t * Default: 3\n\t */\n\tstreamRetries?: number;\n\n\t/**\n\t * Base delay in milliseconds for exponential backoff between stream retries.\n\t * Actual delay is `baseDelay * 2^attempt` (e.g., 1000, 2000, 4000).\n\t *\n\t * Default: 1000\n\t */\n\tstreamRetryBaseDelayMs?: number;\n\n\t/**\n\t * Maximum number of times to retry when a turn ends with stopReason \"length\"\n\t * (the model exhausted its output token budget mid-response). Each retry\n\t * discards the truncated partial and re-issues the request with an escalated\n\t * `maxTokens` budget. This is SEPARATE from `streamRetries`.\n\t *\n\t * Default: 2\n\t */\n\tlengthRetries?: number;\n\n\t/**\n\t * Factor by which to multiply `maxTokens` on each length retry, clamped to the\n\t * model's output ceiling (`model.maxTokens`). Each retry requests a strictly\n\t * larger budget than the previous attempt.\n\t *\n\t * Default: 2\n\t */\n\tlengthRetryBudgetMultiplier?: number;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before final tool events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" is only supported by OpenAI reasoning models that explicitly advertise extended reasoning (for example GPT-5.2+ and Codex GPT-5.3+).\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@dreb/agent-core\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {\n\t// Empty by default - apps extend via declaration merging\n}\n\n/**\n * AgentMessage: Union of LLM messages + custom messages.\n * This abstraction allows apps to add custom message types while maintaining\n * type safety and compatibility with the base LLM messages.\n */\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Agent state containing all configuration and conversation data.\n */\nexport interface AgentState {\n\tsystemPrompt: string;\n\tmodel: Model<any>;\n\tthinkingLevel: ThinkingLevel;\n\ttools: AgentTool<any>[];\n\tmessages: AgentMessage[]; // Can include attachments + custom message types\n\tisStreaming: boolean;\n\tstreamMessage: AgentMessage | null;\n\tpendingToolCalls: Set<string>;\n\terror?: string;\n}\n\nexport interface AgentToolResult<T> {\n\t// Content blocks supporting text and images\n\tcontent: (TextContent | ImageContent)[];\n\t// Details to be displayed in a UI or logged\n\tdetails: T;\n\t/**\n\t * When true, the agent loop will stop after processing all tool results\n\t * from the current assistant message. No further LLM call is made.\n\t *\n\t * Use this when a tool's result means the agent should yield control\n\t * (e.g., after launching background agents that will deliver results later).\n\t */\n\tendTurn?: boolean;\n}\n\n// Callback for streaming tool execution updates\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n// AgentTool extends Tool but adds the execute function\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t// A human-readable label for the tool to be displayed in UI\n\tlabel: string;\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n}\n\n// AgentContext is like Context but uses AgentTool\nexport interface AgentContext {\n\tsystemPrompt: string;\n\tmessages: AgentMessage[];\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n * These events provide fine-grained lifecycle information for messages, turns, and tool executions.\n */\nexport type AgentEvent =\n\t// Agent lifecycle\n\t| {\n\t\t\ttype: \"agent_start\";\n\t\t\tmodel?: { provider: string; id: string };\n\t\t\t/** Effective thinking level sent to the provider for this run. */\n\t\t\tthinkingLevel?: ThinkingLevel;\n\t }\n\t| { type: \"agent_end\"; messages: AgentMessage[] }\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t| { type: \"turn_start\" }\n\t| { type: \"turn_end\"; message: AgentMessage; toolResults: ToolResultMessage[] }\n\t// Message lifecycle - emitted for user, assistant, and toolResult messages\n\t| { type: \"message_start\"; message: AgentMessage }\n\t// Only emitted for assistant messages during streaming\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t// Tool execution lifecycle\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| { type: \"tool_execution_end\"; toolCallId: string; toolName: string; result: any; isError: boolean }\n\t// Stream reliability\n\t| {\n\t\t\ttype: \"stream_retry\";\n\t\t\tattempt: number;\n\t\t\tmaxAttempts: number;\n\t\t\terror: string;\n\t\t\t/** Partial assistant message discarded before retry, for debugging/instrumentation only. */\n\t\t\tdiscardedPartial?: AssistantMessage;\n\t }\n\t// Emitted when a turn ends with stopReason \"length\" and is retried with a larger token budget.\n\t| {\n\t\t\ttype: \"length_retry\";\n\t\t\tattempt: number;\n\t\t\tmaxAttempts: number;\n\t\t\t/** The maxTokens budget used for the truncated attempt. */\n\t\t\tpreviousMaxTokens: number;\n\t\t\t/** The escalated maxTokens budget the retry will request. */\n\t\t\tnextMaxTokens: number;\n\t\t\t/** Partial assistant message discarded before retry, for debugging/instrumentation only. */\n\t\t\tdiscardedPartial?: AssistantMessage;\n\t };\n"]}
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,gBAAgB,EAChB,qBAAqB,EACrB,YAAY,EACZ,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,YAAY,EACZ,WAAW,EACX,IAAI,EACJ,iBAAiB,EACjB,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAEzD;;;;;;;;GAQG;AACH,MAAM,MAAM,QAAQ,GAAG,CACtB,GAAG,IAAI,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,KACpC,UAAU,CAAC,OAAO,YAAY,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC,CAAC;AAEhF;;;;;;GAMG;AACH,MAAM,MAAM,iBAAiB,GAAG,YAAY,GAAG,UAAU,CAAC;AAE1D,wEAAwE;AACxE,MAAM,MAAM,aAAa,GAAG,OAAO,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,EAAE;IAAE,IAAI,EAAE,UAAU,CAAA;CAAE,CAAC,CAAC;AAE/F;;;;;GAKG;AACH,MAAM,WAAW,oBAAoB;IACpC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,MAAM,CAAC,EAAE,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AM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,4FAA4F;IAC5F,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;CACnC,GAED;IACA,IAAI,EAAE,cAAc,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,2DAA2D;IAC3D,iBAAiB,EAAE,MAAM,CAAC;IAC1B,6DAA6D;IAC7D,aAAa,EAAE,MAAM,CAAC;IACtB,4FAA4F;IAC5F,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;CACnC,CAAC","sourcesContent":["import type {\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tstreamSimple,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n} from \"@dreb/ai\";\nimport type { Static, TSchema } from \"@sinclair/typebox\";\n\n/**\n * Stream function used by the agent loop.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\t...args: Parameters<typeof streamSimple>\n) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then allowed tools execute concurrently.\n * Final tool results are still emitted in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/** A single tool call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content` or `details`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n}\n\n/** Context passed to `beforeToolCall`. */\nexport interface BeforeToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** Current agent context at the time the tool call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** The executed tool result before any `afterToolCall` overrides are applied. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed tool result is currently treated as an error. */\n\tisError: boolean;\n\t/** Current agent context at the time the tool call is finalized. */\n\tcontext: AgentContext;\n}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools concurrently\n\t *\n\t * Default: \"parallel\"\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Called before each LLM call in the inner loop. If it returns false,\n\t * the loop exits cleanly as if no more tool calls were pending.\n\t *\n\t * Use this to enforce turn limits or other dynamic stopping conditions.\n\t * The callback is NOT called before the very first LLM call of a run —\n\t * only before subsequent calls triggered by tool results or steering.\n\t */\n\tshouldContinue?: () => boolean;\n\n\t/**\n\t * Maximum number of times to retry when a stream drops mid-response.\n\t * Retries only trigger on detected stream-drop errors (connection dropped before\n\t * the provider sent its terminal completion event). Other errors are not retried.\n\t *\n\t * Default: 3\n\t */\n\tstreamRetries?: number;\n\n\t/**\n\t * Base delay in milliseconds for exponential backoff between stream retries.\n\t * Actual delay is `baseDelay * 2^attempt` (e.g., 1000, 2000, 4000).\n\t *\n\t * Default: 1000\n\t */\n\tstreamRetryBaseDelayMs?: number;\n\n\t/**\n\t * Maximum number of times to retry when a turn ends with stopReason \"length\"\n\t * (the model exhausted its output token budget mid-response). Each retry\n\t * discards the truncated partial and re-issues the request with an escalated\n\t * `maxTokens` budget. This is SEPARATE from `streamRetries`.\n\t *\n\t * Default: 2\n\t */\n\tlengthRetries?: number;\n\n\t/**\n\t * Factor by which to multiply `maxTokens` on each length retry, clamped to the\n\t * model's output ceiling (`model.maxTokens`). Each retry requests a strictly\n\t * larger budget than the previous attempt.\n\t *\n\t * Default: 2\n\t */\n\tlengthRetryBudgetMultiplier?: number;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before final tool events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" is only supported by OpenAI reasoning models that explicitly advertise extended reasoning (for example GPT-5.2+ and Codex GPT-5.3+).\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@dreb/agent-core\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {\n\t// Empty by default - apps extend via declaration merging\n}\n\n/**\n * AgentMessage: Union of LLM messages + custom messages.\n * This abstraction allows apps to add custom message types while maintaining\n * type safety and compatibility with the base LLM messages.\n */\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Agent state containing all configuration and conversation data.\n */\nexport interface AgentState {\n\tsystemPrompt: string;\n\tmodel: Model<any>;\n\tthinkingLevel: ThinkingLevel;\n\ttools: AgentTool<any>[];\n\tmessages: AgentMessage[]; // Can include attachments + custom message types\n\tisStreaming: boolean;\n\tstreamMessage: AgentMessage | null;\n\tpendingToolCalls: Set<string>;\n\terror?: string;\n}\n\nexport interface AgentToolResult<T> {\n\t// Content blocks supporting text and images\n\tcontent: (TextContent | ImageContent)[];\n\t// Details to be displayed in a UI or logged\n\tdetails: T;\n\t/**\n\t * When true, the agent loop will stop after processing all tool results\n\t * from the current assistant message. No further LLM call is made.\n\t *\n\t * Use this when a tool's result means the agent should yield control\n\t * (e.g., after launching background agents that will deliver results later).\n\t */\n\tendTurn?: boolean;\n}\n\n// Callback for streaming tool execution updates\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n// AgentTool extends Tool but adds the execute function\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t// A human-readable label for the tool to be displayed in UI\n\tlabel: string;\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n}\n\n// AgentContext is like Context but uses AgentTool\nexport interface AgentContext {\n\tsystemPrompt: string;\n\tmessages: AgentMessage[];\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n * These events provide fine-grained lifecycle information for messages, turns, and tool executions.\n */\nexport type AgentEvent =\n\t// Agent lifecycle\n\t| {\n\t\t\ttype: \"agent_start\";\n\t\t\tmodel?: { provider: string; id: string };\n\t\t\t/** Effective thinking level sent to the provider for this run. */\n\t\t\tthinkingLevel?: ThinkingLevel;\n\t }\n\t| { type: \"agent_end\"; messages: AgentMessage[] }\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t| { type: \"turn_start\" }\n\t| { type: \"turn_end\"; message: AgentMessage; toolResults: ToolResultMessage[] }\n\t// Message lifecycle - emitted for user, assistant, and toolResult messages\n\t| { type: \"message_start\"; message: AgentMessage }\n\t// Only emitted for assistant messages during streaming\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t// Tool execution lifecycle\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| { type: \"tool_execution_end\"; toolCallId: string; toolName: string; result: any; isError: boolean }\n\t// Stream reliability\n\t| {\n\t\t\ttype: \"stream_retry\";\n\t\t\tattempt: number;\n\t\t\tmaxAttempts: number;\n\t\t\terror: string;\n\t\t\t/** Partial assistant message discarded before retry, for debugging/instrumentation only. */\n\t\t\tdiscardedPartial?: AssistantMessage;\n\t }\n\t// Emitted when a turn ends with stopReason \"length\" and is retried with a larger token budget.\n\t| {\n\t\t\ttype: \"length_retry\";\n\t\t\tattempt: number;\n\t\t\tmaxAttempts: number;\n\t\t\t/** The maxTokens budget used for the truncated attempt. */\n\t\t\tpreviousMaxTokens: number;\n\t\t\t/** The escalated maxTokens budget the retry will request. */\n\t\t\tnextMaxTokens: number;\n\t\t\t/** Partial assistant message discarded before retry, for debugging/instrumentation only. */\n\t\t\tdiscardedPartial?: AssistantMessage;\n\t };\n"]}
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tstreamSimple,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n} from \"@dreb/ai\";\nimport type { Static, TSchema } from \"@sinclair/typebox\";\n\n/**\n * Stream function used by the agent loop.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\t...args: Parameters<typeof streamSimple>\n) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then allowed tools execute concurrently.\n * Final tool results are still emitted in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/** A single tool call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content` or `details`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n}\n\n/** Context passed to `beforeToolCall`. */\nexport interface BeforeToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** Current agent context at the time the tool call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** The executed tool result before any `afterToolCall` overrides are applied. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed tool result is currently treated as an error. */\n\tisError: boolean;\n\t/** Current agent context at the time the tool call is finalized. */\n\tcontext: AgentContext;\n}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools concurrently\n\t *\n\t * Default: \"parallel\"\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Called before each LLM call in the inner loop. If it returns false,\n\t * the loop exits cleanly as if no more tool calls were pending.\n\t *\n\t * Use this to enforce turn limits or other dynamic stopping conditions.\n\t * The callback is NOT called before the very first LLM call of a run —\n\t * only before subsequent calls triggered by tool results or steering.\n\t */\n\tshouldContinue?: () => boolean;\n\n\t/**\n\t * Maximum number of times to retry when a stream drops mid-response.\n\t * Retries only trigger on detected stream-drop errors (connection dropped before\n\t * the provider sent its terminal completion event). Other errors are not retried.\n\t *\n\t * Default: 3\n\t */\n\tstreamRetries?: number;\n\n\t/**\n\t * Base delay in milliseconds for exponential backoff between stream retries.\n\t * Actual delay is `baseDelay * 2^attempt` (e.g., 1000, 2000, 4000).\n\t *\n\t * Default: 1000\n\t */\n\tstreamRetryBaseDelayMs?: number;\n\n\t/**\n\t * Maximum number of times to retry when a turn ends with stopReason \"length\"\n\t * (the model exhausted its output token budget mid-response). Each retry\n\t * discards the truncated partial and re-issues the request with an escalated\n\t * `maxTokens` budget. This is SEPARATE from `streamRetries`.\n\t *\n\t * Default: 2\n\t */\n\tlengthRetries?: number;\n\n\t/**\n\t * Factor by which to multiply `maxTokens` on each length retry, clamped to the\n\t * model's output ceiling (`model.maxTokens`). Each retry requests a strictly\n\t * larger budget than the previous attempt.\n\t *\n\t * Default: 2\n\t */\n\tlengthRetryBudgetMultiplier?: number;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before final tool events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" is only supported by OpenAI reasoning models that explicitly advertise extended reasoning (for example GPT-5.2+ and Codex GPT-5.3+).\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@dreb/agent-core\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {\n\t// Empty by default - apps extend via declaration merging\n}\n\n/**\n * AgentMessage: Union of LLM messages + custom messages.\n * This abstraction allows apps to add custom message types while maintaining\n * type safety and compatibility with the base LLM messages.\n */\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Agent state containing all configuration and conversation data.\n */\nexport interface AgentState {\n\tsystemPrompt: string;\n\tmodel: Model<any>;\n\tthinkingLevel: ThinkingLevel;\n\ttools: AgentTool<any>[];\n\tmessages: AgentMessage[]; // Can include attachments + custom message types\n\tisStreaming: boolean;\n\tstreamMessage: AgentMessage | null;\n\tpendingToolCalls: Set<string>;\n\terror?: string;\n}\n\nexport interface AgentToolResult<T> {\n\t// Content blocks supporting text and images\n\tcontent: (TextContent | ImageContent)[];\n\t// Details to be displayed in a UI or logged\n\tdetails: T;\n\t/**\n\t * When true, the agent loop will stop after processing all tool results\n\t * from the current assistant message. No further LLM call is made.\n\t *\n\t * Use this when a tool's result means the agent should yield control\n\t * (e.g., after launching background agents that will deliver results later).\n\t */\n\tendTurn?: boolean;\n}\n\n// Callback for streaming tool execution updates\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n// AgentTool extends Tool but adds the execute function\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t// A human-readable label for the tool to be displayed in UI\n\tlabel: string;\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n}\n\n// AgentContext is like Context but uses AgentTool\nexport interface AgentContext {\n\tsystemPrompt: string;\n\tmessages: AgentMessage[];\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n * These events provide fine-grained lifecycle information for messages, turns, and tool executions.\n */\nexport type AgentEvent =\n\t// Agent lifecycle\n\t| {\n\t\t\ttype: \"agent_start\";\n\t\t\tmodel?: { provider: string; id: string };\n\t\t\t/** Effective thinking level sent to the provider for this run. */\n\t\t\tthinkingLevel?: ThinkingLevel;\n\t }\n\t| { type: \"agent_end\"; messages: AgentMessage[] }\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t| { type: \"turn_start\" }\n\t| { type: \"turn_end\"; message: AgentMessage; toolResults: ToolResultMessage[] }\n\t// Message lifecycle - emitted for user, assistant, and toolResult messages\n\t| { type: \"message_start\"; message: AgentMessage }\n\t// Only emitted for assistant messages during streaming\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t// Tool execution lifecycle\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| { type: \"tool_execution_end\"; toolCallId: string; toolName: string; result: any; isError: boolean }\n\t// Stream reliability\n\t| {\n\t\t\ttype: \"stream_retry\";\n\t\t\tattempt: number;\n\t\t\tmaxAttempts: number;\n\t\t\terror: string;\n\t\t\t/** Partial assistant message discarded before retry, for debugging/instrumentation only. */\n\t\t\tdiscardedPartial?: AssistantMessage;\n\t }\n\t// Emitted when a turn ends with stopReason \"length\" and is retried with a larger token budget.\n\t| {\n\t\t\ttype: \"length_retry\";\n\t\t\tattempt: number;\n\t\t\tmaxAttempts: number;\n\t\t\t/** The maxTokens budget used for the truncated attempt. */\n\t\t\tpreviousMaxTokens: number;\n\t\t\t/** The escalated maxTokens budget the retry will request. */\n\t\t\tnextMaxTokens: number;\n\t\t\t/** Partial assistant message discarded before retry, for debugging/instrumentation only. */\n\t\t\tdiscardedPartial?: AssistantMessage;\n\t };\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tImageContent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tstreamSimple,\n\tTextContent,\n\tTool,\n\tToolResultMessage,\n} from \"@dreb/ai\";\nimport type { Static, TSchema } from \"@sinclair/typebox\";\n\n/**\n * Stream function used by the agent loop.\n *\n * Contract:\n * - Must not throw or return a rejected promise for request/model/runtime failures.\n * - Must return an AssistantMessageEventStream.\n * - Failures must be encoded in the returned stream via protocol events and a\n * final AssistantMessage with stopReason \"error\" or \"aborted\" and errorMessage.\n */\nexport type StreamFn = (\n\t...args: Parameters<typeof streamSimple>\n) => ReturnType<typeof streamSimple> | Promise<ReturnType<typeof streamSimple>>;\n\n/**\n * Configuration for how tool calls from a single assistant message are executed.\n *\n * - \"sequential\": each tool call is prepared, executed, and finalized before the next one starts.\n * - \"parallel\": tool calls are prepared sequentially, then allowed tools execute concurrently.\n * Final tool results are still emitted in assistant source order.\n */\nexport type ToolExecutionMode = \"sequential\" | \"parallel\";\n\n/** A single tool call content block emitted by an assistant message. */\nexport type AgentToolCall = Extract<AssistantMessage[\"content\"][number], { type: \"toolCall\" }>;\n\n/**\n * Result returned from `beforeToolCall`.\n *\n * Returning `{ block: true }` prevents the tool from executing. The loop emits an error tool result instead.\n * `reason` becomes the text shown in that error result. If omitted, a default blocked message is used.\n */\nexport interface BeforeToolCallResult {\n\tblock?: boolean;\n\treason?: string;\n}\n\n/**\n * Partial override returned from `afterToolCall`.\n *\n * Merge semantics are field-by-field:\n * - `content`: if provided, replaces the tool result content array in full\n * - `details`: if provided, replaces the tool result details value in full\n * - `isError`: if provided, replaces the tool result error flag\n *\n * Omitted fields keep the original executed tool result values.\n * There is no deep merge for `content` or `details`.\n */\nexport interface AfterToolCallResult {\n\tcontent?: (TextContent | ImageContent)[];\n\tdetails?: unknown;\n\tisError?: boolean;\n}\n\n/** Context passed to `beforeToolCall`. */\nexport interface BeforeToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** Current agent context at the time the tool call is prepared. */\n\tcontext: AgentContext;\n}\n\n/** Context passed to `afterToolCall`. */\nexport interface AfterToolCallContext {\n\t/** The assistant message that requested the tool call. */\n\tassistantMessage: AssistantMessage;\n\t/** The raw tool call block from `assistantMessage.content`. */\n\ttoolCall: AgentToolCall;\n\t/** Validated tool arguments for the target tool schema. */\n\targs: unknown;\n\t/** The executed tool result before any `afterToolCall` overrides are applied. */\n\tresult: AgentToolResult<any>;\n\t/** Whether the executed tool result is currently treated as an error. */\n\tisError: boolean;\n\t/** Current agent context at the time the tool call is finalized. */\n\tcontext: AgentContext;\n}\n\nexport interface AgentLoopConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\n\n\t/**\n\t * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.\n\t *\n\t * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage\n\t * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,\n\t * status messages) should be filtered out.\n\t *\n\t * Contract: must not throw or reject. Return a safe fallback value instead.\n\t * Throwing interrupts the low-level agent loop without producing a normal event sequence.\n\t *\n\t * @example\n\t * ```typescript\n\t * convertToLlm: (messages) => messages.flatMap(m => {\n\t * if (m.role === \"custom\") {\n\t * // Convert custom message to user message\n\t * return [{ role: \"user\", content: m.content, timestamp: m.timestamp }];\n\t * }\n\t * if (m.role === \"notification\") {\n\t * // Filter out UI-only messages\n\t * return [];\n\t * }\n\t * // Pass through standard LLM messages\n\t * return [m];\n\t * })\n\t * ```\n\t */\n\tconvertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\n\t/**\n\t * Optional transform applied to the context before `convertToLlm`.\n\t *\n\t * Use this for operations that work at the AgentMessage level:\n\t * - Context window management (pruning old messages)\n\t * - Injecting context from external sources\n\t *\n\t * Contract: must not throw or reject. Return the original messages or another\n\t * safe fallback value instead.\n\t *\n\t * @example\n\t * ```typescript\n\t * transformContext: async (messages) => {\n\t * if (estimateTokens(messages) > MAX_TOKENS) {\n\t * return pruneOldMessages(messages);\n\t * }\n\t * return messages;\n\t * }\n\t * ```\n\t */\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\n\t/**\n\t * Resolves an API key dynamically for each LLM call.\n\t *\n\t * Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may expire\n\t * during long-running tool execution phases.\n\t *\n\t * Contract: must not throw or reject. Return undefined when no key is available.\n\t */\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\n\t/**\n\t * Returns steering messages to inject into the conversation mid-run.\n\t *\n\t * Called after the current assistant turn finishes executing its tool calls.\n\t * If messages are returned, they are added to the context before the next LLM call.\n\t * Tool calls from the current assistant message are not skipped.\n\t *\n\t * Use this for \"steering\" the agent while it's working.\n\t *\n\t * Contract: must not throw or reject. Return [] when no steering messages are available.\n\t */\n\tgetSteeringMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Returns follow-up messages to process after the agent would otherwise stop.\n\t *\n\t * Called when the agent has no more tool calls and no steering messages.\n\t * If messages are returned, they're added to the context and the agent\n\t * continues with another turn.\n\t *\n\t * Use this for follow-up messages that should wait until the agent finishes.\n\t *\n\t * Contract: must not throw or reject. Return [] when no follow-up messages are available.\n\t */\n\tgetFollowUpMessages?: () => Promise<AgentMessage[]>;\n\n\t/**\n\t * Tool execution mode.\n\t * - \"sequential\": execute tool calls one by one\n\t * - \"parallel\": preflight tool calls sequentially, then execute allowed tools concurrently\n\t *\n\t * Default: \"parallel\"\n\t */\n\ttoolExecution?: ToolExecutionMode;\n\n\t/**\n\t * Called before each LLM call in the inner loop. If it returns false,\n\t * the loop exits cleanly as if no more tool calls were pending.\n\t *\n\t * Use this to enforce turn limits or other dynamic stopping conditions.\n\t * The callback is NOT called before the very first LLM call of a run —\n\t * only before subsequent calls triggered by tool results or steering.\n\t */\n\tshouldContinue?: () => boolean;\n\n\t/**\n\t * Maximum number of times to retry when a stream drops mid-response.\n\t * Retries only trigger on detected stream-drop errors (connection dropped before\n\t * the provider sent its terminal completion event). Other errors are not retried.\n\t *\n\t * Default: 3\n\t */\n\tstreamRetries?: number;\n\n\t/**\n\t * Base delay in milliseconds for exponential backoff between stream retries.\n\t * Actual delay is `baseDelay * 2^attempt` (e.g., 1000, 2000, 4000).\n\t *\n\t * Default: 1000\n\t */\n\tstreamRetryBaseDelayMs?: number;\n\n\t/**\n\t * Maximum number of times to retry when a turn ends with stopReason \"length\"\n\t * (the model exhausted its output token budget mid-response). Each retry\n\t * discards the truncated partial and re-issues the request with an escalated\n\t * `maxTokens` budget. This is SEPARATE from `streamRetries`.\n\t *\n\t * Default: 2\n\t */\n\tlengthRetries?: number;\n\n\t/**\n\t * Factor by which to multiply `maxTokens` on each length retry, clamped to the\n\t * model's output ceiling (`model.maxTokens`). Each retry requests a strictly\n\t * larger budget than the previous attempt.\n\t *\n\t * Default: 2\n\t */\n\tlengthRetryBudgetMultiplier?: number;\n\n\t/**\n\t * Called before a tool is executed, after arguments have been validated.\n\t *\n\t * Return `{ block: true }` to prevent execution. The loop emits an error tool result instead.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\n\t/**\n\t * Called after a tool finishes executing, before final tool events are emitted.\n\t *\n\t * Return an `AfterToolCallResult` to override parts of the executed tool result:\n\t * - `content` replaces the full content array\n\t * - `details` replaces the full details payload\n\t * - `isError` replaces the error flag\n\t *\n\t * Any omitted fields keep their original values. No deep merge is performed.\n\t * The hook receives the agent abort signal and is responsible for honoring it.\n\t */\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n}\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" is only supported by OpenAI reasoning models that explicitly advertise extended reasoning (for example GPT-5.2+ and Codex GPT-5.3+).\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/**\n * Extensible interface for custom app messages.\n * Apps can extend via declaration merging:\n *\n * @example\n * ```typescript\n * declare module \"@dreb/agent-core\" {\n * interface CustomAgentMessages {\n * artifact: ArtifactMessage;\n * notification: NotificationMessage;\n * }\n * }\n * ```\n */\nexport interface CustomAgentMessages {\n\t// Empty by default - apps extend via declaration merging\n}\n\n/**\n * AgentMessage: Union of LLM messages + custom messages.\n * This abstraction allows apps to add custom message types while maintaining\n * type safety and compatibility with the base LLM messages.\n */\nexport type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];\n\n/**\n * Agent state containing all configuration and conversation data.\n */\nexport interface AgentState {\n\tsystemPrompt: string;\n\tmodel: Model<any>;\n\tthinkingLevel: ThinkingLevel;\n\ttools: AgentTool<any>[];\n\tmessages: AgentMessage[]; // Can include attachments + custom message types\n\tisStreaming: boolean;\n\tstreamMessage: AgentMessage | null;\n\tpendingToolCalls: Set<string>;\n\terror?: string;\n}\n\nexport interface AgentToolResult<T> {\n\t// Content blocks supporting text and images\n\tcontent: (TextContent | ImageContent)[];\n\t// Details to be displayed in a UI or logged\n\tdetails: T;\n\t/**\n\t * When true, the agent loop will stop after processing all tool results\n\t * from the current assistant message. No further LLM call is made.\n\t *\n\t * Use this when a tool's result means the agent should yield control\n\t * (e.g., after launching background agents that will deliver results later).\n\t */\n\tendTurn?: boolean;\n}\n\n// Callback for streaming tool execution updates\nexport type AgentToolUpdateCallback<T = any> = (partialResult: AgentToolResult<T>) => void;\n\n// AgentTool extends Tool but adds the execute function\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t// A human-readable label for the tool to be displayed in UI\n\tlabel: string;\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t\tonUpdate?: AgentToolUpdateCallback<TDetails>,\n\t) => Promise<AgentToolResult<TDetails>>;\n}\n\n// AgentContext is like Context but uses AgentTool\nexport interface AgentContext {\n\tsystemPrompt: string;\n\tmessages: AgentMessage[];\n\ttools?: AgentTool<any>[];\n}\n\n/**\n * Events emitted by the Agent for UI updates.\n * These events provide fine-grained lifecycle information for messages, turns, and tool executions.\n */\nexport type AgentEvent =\n\t// Agent lifecycle\n\t| {\n\t\t\ttype: \"agent_start\";\n\t\t\tmodel?: { provider: string; id: string };\n\t\t\t/** Effective thinking level sent to the provider for this run. */\n\t\t\tthinkingLevel?: ThinkingLevel;\n\t }\n\t| { type: \"agent_end\"; messages: AgentMessage[] }\n\t// Turn lifecycle - a turn is one assistant response + any tool calls/results\n\t| { type: \"turn_start\" }\n\t| { type: \"turn_end\"; message: AgentMessage; toolResults: ToolResultMessage[] }\n\t// Message lifecycle - emitted for user, assistant, and toolResult messages\n\t| { type: \"message_start\"; message: AgentMessage }\n\t// Only emitted for assistant messages during streaming\n\t| { type: \"message_update\"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }\n\t| { type: \"message_end\"; message: AgentMessage }\n\t// Tool execution lifecycle\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t| { type: \"tool_execution_update\"; toolCallId: string; toolName: string; args: any; partialResult: any }\n\t| { type: \"tool_execution_end\"; toolCallId: string; toolName: string; result: any; isError: boolean }\n\t// Stream reliability\n\t| {\n\t\t\ttype: \"stream_retry\";\n\t\t\tattempt: number;\n\t\t\tmaxAttempts: number;\n\t\t\terror: string;\n\t\t\t/** Partial assistant message discarded before retry, for debugging/instrumentation only. */\n\t\t\tdiscardedPartial?: AssistantMessage;\n\t }\n\t// Emitted when a turn ends with stopReason \"length\" and is retried with a larger token budget.\n\t| {\n\t\t\ttype: \"length_retry\";\n\t\t\tattempt: number;\n\t\t\tmaxAttempts: number;\n\t\t\t/** The maxTokens budget used for the truncated attempt. */\n\t\t\tpreviousMaxTokens: number;\n\t\t\t/** The escalated maxTokens budget the retry will request. */\n\t\t\tnextMaxTokens: number;\n\t\t\t/** Partial assistant message discarded before retry, for debugging/instrumentation only. */\n\t\t\tdiscardedPartial?: AssistantMessage;\n\t };\n"]}
|