@agentloop/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../src/content.ts","../src/message.ts","../src/schema.ts","../src/model.ts","../src/tool.ts","../src/policy.ts","../src/observer.ts","../src/channel.ts","../src/emit.ts","../src/pipeline.ts","../src/execute.ts","../src/loop.ts","../src/agent.ts"],"sourcesContent":["/** Plain text content. */\nexport interface TextPart {\n /** Part discriminator. */\n type: \"text\";\n /** The text content. */\n text: string;\n /** Provider-specific signature for reasoning verification. */\n signature?: string;\n /** Arbitrary key-value pairs for provider or application use. */\n metadata?: Record<string, unknown>;\n}\n\n/** Structured JSON content. */\nexport interface JsonPart {\n /** Part discriminator. */\n type: \"json\";\n /** The JSON payload. */\n json: Record<string, unknown>;\n /** Arbitrary key-value pairs for provider or application use. */\n metadata?: Record<string, unknown>;\n}\n\n/** Inline binary data (images, audio, video, documents, etc.). */\nexport interface BlobPart {\n /** Part discriminator. */\n type: \"blob\";\n /** Raw binary content or a base64-encoded string. */\n data: string | Uint8Array;\n /** MIME type of the binary data (e.g. `\"image/png\"`, `\"audio/wav\"`). */\n mediaType: string;\n /** Arbitrary key-value pairs for provider or application use. */\n metadata?: Record<string, unknown>;\n}\n\n/** Reference to an external resource. */\nexport interface URLPart {\n /** Part discriminator. */\n type: \"url\";\n /** The resource URL. */\n url: string;\n /** Optional MIME type hint for the referenced resource. */\n mediaType?: string;\n /** Arbitrary key-value pairs for provider or application use. */\n metadata?: Record<string, unknown>;\n}\n\n/** Model reasoning trace. */\nexport interface ThinkingPart {\n /** Part discriminator. */\n type: \"thinking\";\n /** The model's internal reasoning text. */\n thinking: string;\n /** Provider-specific signature for thinking verification. */\n signature?: string;\n /** Whether the thinking content was redacted by the provider. */\n redacted: boolean;\n}\n\n/** A request from the model to invoke a tool. */\nexport interface ToolCallPart {\n /** Part discriminator. */\n type: \"tool_call\";\n /** Unique identifier for this tool call, used to match results. */\n id: string;\n /** The name of the tool to invoke. */\n name: string;\n /** The arguments to pass to the tool. */\n arguments: Record<string, unknown>;\n /** Provider-specific signature for tool call verification. */\n signature?: string;\n}\n\n/** The result of a tool invocation. */\nexport interface ToolResultPart {\n /** Part discriminator. */\n type: \"tool_result\";\n /** Identifier matching the originating {@link ToolCallPart.id}. */\n id: string;\n /** The name of the tool that was invoked. */\n name: string;\n /** The content returned by the tool. */\n output: Content[];\n /** Whether the tool invocation failed. */\n isError?: boolean;\n}\n\n/** Renderable content: text, structured data, or binary/external media. */\nexport type Content = TextPart | JsonPart | BlobPart | URLPart;\n\n/** Content that can appear in a system message. */\nexport type SystemContent = TextPart;\n\n/** Content that can appear in a user message. */\nexport type UserContent = TextPart | JsonPart | BlobPart | URLPart;\n\n/** Content that can appear in an assistant message. */\nexport type AssistantContent = TextPart | ThinkingPart | ToolCallPart;\n\n/** Content that can appear in a tool message. */\nexport type ToolContent = ToolResultPart;\n\n/** Create a {@link TextPart}. */\nexport function text(value: string): TextPart {\n return { type: \"text\", text: value };\n}\n\n/** Create a {@link JsonPart}. */\nexport function json(value: Record<string, unknown>): JsonPart {\n return { type: \"json\", json: value };\n}\n\n/** Create a {@link BlobPart}. */\nexport function blob(data: string | Uint8Array, mediaType: string): BlobPart {\n return { type: \"blob\", data, mediaType };\n}\n\n/** Create a {@link URLPart}. */\nexport function url(value: string, mediaType?: string): URLPart {\n return { type: \"url\", url: value, ...(mediaType != null && { mediaType }) };\n}\n","import type { AssistantContent, SystemContent, ToolContent, UserContent } from \"./content.ts\";\nimport { text } from \"./content.ts\";\n\n/** A system instruction that guides model behavior. */\nexport interface SystemMessage {\n /** Message discriminator. */\n role: \"system\";\n /** The system instruction content. */\n content: SystemContent[];\n /** Arbitrary key-value pairs for provider or application use. */\n metadata?: Record<string, unknown>;\n}\n\n/** A message from the user. */\nexport interface UserMessage {\n /** Message discriminator. */\n role: \"user\";\n /** User-provided content (text, media, structured data, etc.). */\n content: UserContent[];\n /** Arbitrary key-value pairs for provider or application use. */\n metadata?: Record<string, unknown>;\n}\n\n/** A response from the model. */\nexport interface AssistantMessage {\n /** Message discriminator. */\n role: \"assistant\";\n /** Model-generated content (text, thinking, tool calls). */\n content: AssistantContent[];\n /** Arbitrary key-value pairs for provider or application use. */\n metadata?: Record<string, unknown>;\n}\n\n/** The result of one or more tool invocations. */\nexport interface ToolMessage {\n /** Message discriminator. */\n role: \"tool\";\n /** Tool results to return to the model. */\n content: ToolContent[];\n /** Arbitrary key-value pairs for provider or application use. */\n metadata?: Record<string, unknown>;\n}\n\n/** A message in a conversation. */\nexport type Message = SystemMessage | UserMessage | AssistantMessage | ToolMessage;\n\n/** Create a {@link SystemMessage}. Accepts a string or content array. */\nexport function system(content: string | SystemContent[]): SystemMessage {\n return { role: \"system\", content: typeof content === \"string\" ? [text(content)] : content };\n}\n\n/** Create a {@link UserMessage}. Accepts a string or content array. */\nexport function user(content: string | UserContent[]): UserMessage {\n return { role: \"user\", content: typeof content === \"string\" ? [text(content)] : content };\n}\n\n/** Create an {@link AssistantMessage}. Accepts a string or content array. */\nexport function assistant(content: string | AssistantContent[]): AssistantMessage {\n return { role: \"assistant\", content: typeof content === \"string\" ? [text(content)] : content };\n}\n\n/** Flexible input type for agent invocations. A plain string is treated as a user message. */\nexport type Prompt = string | Message | Message[];\n\n/** Normalize a {@link Prompt} into a {@link Message} array. */\nexport function normalizePrompt(prompt: Prompt): Message[] {\n if (typeof prompt === \"string\") {\n return [user(prompt)];\n }\n if (Array.isArray(prompt)) {\n return prompt;\n }\n return [prompt];\n}\n","/**\n * Minimal schema interface for argument validation and type inference.\n *\n * Any validator with a compatible `safeParse` method works — Zod, Valibot,\n * ArkType, or a hand-rolled validator. No adapter needed.\n *\n * **Provider requirement:** When used in tool definitions, providers need to\n * extract a JSON Schema representation to send to the model API. Providers\n * use the [Standard Schema](https://github.com/standard-schema/standard-schema)\n * interface (`~standard.jsonSchema.input()`) for this conversion.\n *\n * Schemas from Standard Schema-compliant libraries (Zod v4+, Valibot v1+,\n * ArkType) work automatically with all providers. Hand-rolled schemas with\n * only `safeParse` will validate arguments correctly but will throw at\n * runtime when used with a provider that requires JSON Schema extraction.\n */\nexport interface Schema<T = unknown> {\n safeParse(value: unknown): { success: true; data: T } | { success: false; error: unknown };\n}\n\n/** Extract the output type from a {@link Schema}. */\nexport type Infer<S extends Schema> = S extends Schema<infer T> ? T : never;\n\n/**\n * Extract a JSON Schema object from a\n * [Standard Schema v1](https://github.com/standard-schema/standard-schema)\n * compatible validator.\n *\n * Throws if the schema does not expose `~standard.jsonSchema.input()`.\n */\nexport function schemaToJsonSchema(schema: unknown): Record<string, unknown> {\n const ss = (schema as Record<string, unknown>)?.[\"~standard\"] as\n | { jsonSchema?: { input?: () => Record<string, unknown> } }\n | undefined;\n if (ss?.jsonSchema?.input) {\n return ss.jsonSchema.input() as Record<string, unknown>;\n }\n throw new Error(\n \"Cannot convert schema to JSON Schema. Provide a Standard Schema v1-compatible validator.\",\n );\n}\n","import type { Message } from \"./message.ts\";\nimport type { Schema } from \"./schema.ts\";\nimport type { ToolDefinition } from \"./tool.ts\";\n\n/** Normalized reason the model stopped generating. */\nexport type FinishReason =\n /** The model finished generating naturally. */\n | \"stop\"\n /** The model requested a tool invocation. */\n | \"tool_call\"\n /** The generation hit the maximum token limit. */\n | \"length\"\n /** The model stopped at a configured stop sequence. */\n | \"stop_sequence\"\n /** The generation was cancelled by the client. */\n | \"cancelled\"\n /** The model refused to generate (content policy). */\n | \"refused\"\n /** An error occurred during generation. */\n | \"error\"\n /** The provider returned an unrecognized finish reason. */\n | \"unknown\";\n\n/** Token usage statistics for a model call. */\nexport interface Usage {\n /** Number of tokens in the input/prompt. */\n inputTokens: number;\n /** Number of tokens in the generated output. */\n outputTokens: number;\n /** Total tokens (input + output). */\n totalTokens: number;\n /** Tokens read from cache (e.g. Anthropic prompt caching, Google cached content). */\n cacheReadTokens?: number;\n /** Tokens written to cache (e.g. Anthropic cache creation). */\n cacheWriteTokens?: number;\n}\n\n/** Individual chunks yielded by a model during streaming. */\nexport type StreamPart =\n /** The model began producing text. */\n | { type: \"text_start\" }\n /** A chunk of text output. */\n | { type: \"text_delta\"; text: string }\n /** The model finished producing text. */\n | { type: \"text_end\" }\n /** The model began a reasoning trace. */\n | { type: \"thinking_start\"; redacted?: boolean }\n /** A chunk of reasoning output. */\n | { type: \"thinking_delta\"; thinking: string }\n /** The model finished a reasoning trace. */\n | { type: \"thinking_end\"; signature?: string }\n /** A new tool call has started. */\n | { type: \"tool_call_start\"; id: string; name: string; signature?: string }\n /** A chunk of tool call arguments (partial JSON). */\n | { type: \"tool_call_delta\"; id: string; args: string }\n /** A tool call is complete. */\n | { type: \"tool_call_end\"; id: string }\n /** The model finished generating. */\n | { type: \"finish\"; finishReason: FinishReason; usage: Usage }\n /** An error occurred during streaming. */\n | { type: \"error\"; error: Error };\n\n/** Configuration knobs for a model call. */\nexport interface ModelConfig {\n /** Maximum tokens to generate. */\n maxTokens?: number;\n /** Sampling temperature. */\n temperature?: number;\n /** Top-p (nucleus) sampling. */\n topP?: number;\n /** Top-k sampling. */\n topK?: number;\n /** Stop sequences. */\n stopSequences?: string[];\n}\n\n/** A configured model instance returned by a {@link Provider}. */\nexport interface Model {\n /** The model identifier (e.g. \"claude-sonnet-4-20250514\"). */\n name: string;\n /** Stream a response as incremental parts. */\n stream(options: {\n /** The conversation messages. */\n messages: Message[];\n /** Tool definitions available to the model. */\n tools?: ToolDefinition[];\n /** Per-call config overrides. */\n config?: ModelConfig;\n /** Schema for structured output. */\n output?: Schema;\n /** Signal for cooperative cancellation. */\n signal?: AbortSignal;\n }): AsyncIterable<StreamPart>;\n}\n\n/** Configuration for a provider connection. */\nexport interface ProviderConfig {\n /** API key for authentication. */\n apiKey?: string;\n /** Base URL for the API. */\n baseUrl?: string;\n /** Request timeout in milliseconds. */\n timeout?: number;\n /** Maximum number of retries on transient failures. */\n maxRetries?: number;\n /** Additional headers to include in requests. */\n headers?: Record<string, string>;\n}\n\n/** Factory for creating {@link Model} instances. */\nexport interface Provider {\n /** Create a model instance with optional default config. */\n model(name: string, config?: ModelConfig): Model;\n}\n\n/** Create an empty {@link Usage}. */\nexport function emptyUsage(): Usage {\n return { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n}\n\n/** Add two {@link Usage} objects together. */\nexport function addUsage(a: Usage, b: Usage): Usage {\n return {\n inputTokens: a.inputTokens + b.inputTokens,\n outputTokens: a.outputTokens + b.outputTokens,\n totalTokens: a.totalTokens + b.totalTokens,\n cacheReadTokens: (a.cacheReadTokens ?? 0) + (b.cacheReadTokens ?? 0) || undefined,\n cacheWriteTokens: (a.cacheWriteTokens ?? 0) + (b.cacheWriteTokens ?? 0) || undefined,\n };\n}\n","import type { Content } from \"./content.ts\";\nimport { json, text } from \"./content.ts\";\nimport type { RunContext, ToolContext } from \"./context.ts\";\nimport type { AfterToolRunAction, BeforeToolRunAction } from \"./policy.ts\";\nimport type { Schema } from \"./schema.ts\";\n\n/** Flexible return type for tool execution. Strings and objects are auto-wrapped. */\nexport type ToolReturn = string | Record<string, unknown> | Content[];\n\n/** Declarative tool metadata shared between {@link Tool} and the model API. */\nexport interface ToolDefinition<T = unknown> {\n /** The tool name exposed to the model. */\n name: string;\n /** Description of what the tool does, sent to the model. */\n description: string;\n /** Schema for argument validation and JSON Schema extraction. */\n schema: Schema<T>;\n /** Maximum execution time in milliseconds before the tool is aborted. */\n timeout?: number;\n}\n\n/** A tool the model can invoke. */\nexport interface Tool<T = unknown> extends ToolDefinition<T> {\n /** Called before execution. Can skip, stop, or modify arguments. */\n before?(\n args: T,\n ctx: RunContext,\n ): void | BeforeToolRunAction | Promise<void | BeforeToolRunAction>;\n /** Execute the tool with validated arguments. */\n execute(args: T, ctx: ToolContext): ToolReturn | Promise<ToolReturn>;\n /** Called after execution. Can rewrite output, retry, or stop the run. */\n after?(\n args: T,\n output: Content[],\n ctx: RunContext,\n ): void | AfterToolRunAction | Promise<void | AfterToolRunAction>;\n}\n\n/** Create a type-safe {@link Tool}. Schema infers the argument type. */\nexport function defineTool<T>(config: Tool<T>): Tool<T> {\n return config;\n}\n\n/** Normalize a {@link ToolReturn} into a {@link Content} array. */\nexport function normalizeToolReturn(value: ToolReturn): Content[] {\n if (typeof value === \"string\") {\n return [text(value)];\n }\n if (Array.isArray(value)) {\n return value;\n }\n return [json(value)];\n}\n","import type { Content } from \"./content.ts\";\nimport type { RunContext } from \"./context.ts\";\nimport type { AssistantMessage, Message } from \"./message.ts\";\nimport type { FinishReason, Model, ModelConfig, Usage } from \"./model.ts\";\nimport type { Tool } from \"./tool.ts\";\n\n/** Action returned from {@link Policy.beforeStep}. */\nexport type BeforeStepAction =\n /** Halt the run. */\n { action: \"stop\"; reason?: string };\n\n/** Action returned from {@link Policy.afterResponse}. */\nexport type AfterResponseAction =\n /** Halt the run. Tools never execute. */\n | { action: \"stop\"; reason?: string }\n /** Replace the model's response with a substitute message. */\n | { action: \"replace\"; message: AssistantMessage; reason?: string }\n /** Roll back the response and try again with optional guidance. */\n | { action: \"retry\"; messages?: Message[]; reason?: string };\n\n/** Action returned from {@link Policy.beforeToolRun} and {@link Tool.before}. */\nexport type BeforeToolRunAction =\n /** Skip this tool call without executing it. */\n | { action: \"skip\"; output?: Content[]; reason?: string }\n /** Halt the entire run. */\n | { action: \"stop\"; output?: Content[]; reason?: string };\n\n/** Action returned from {@link Policy.afterToolRun} and {@link Tool.after}. */\nexport type AfterToolRunAction =\n /** Replace the tool's output. */\n | { action: \"rewrite\"; output: Content[]; reason?: string }\n /** Re-execute the tool, optionally with different arguments. */\n | { action: \"retry\"; arguments?: Record<string, unknown>; reason?: string }\n /** Halt the entire run. */\n | { action: \"stop\"; reason?: string };\n\n/** Action returned from {@link Policy.afterStep}. */\nexport type AfterStepAction =\n /** Halt the run. */\n | { action: \"stop\"; reason?: string }\n /** Roll back the entire step and try again with optional guidance. */\n | { action: \"retry\"; messages?: Message[]; reason?: string }\n /** Inject messages into the transcript and force another model call. */\n | { action: \"inject\"; messages: Message[] };\n\n/**\n * A mutable plan for the upcoming model call.\n *\n * The loop creates a shallow copy of the transcript for {@link StepPlan.messages},\n * so policies can safely add, remove, or reorder messages without affecting the\n * canonical transcript.\n */\nexport interface StepPlan extends Partial<ModelConfig> {\n /** The model to use for this step. Policies can swap this to route different steps to different models. */\n model: Model;\n /** System instructions for the model. Converted to a system message before calling the model. */\n instructions?: string;\n /** A draft copy of the transcript. Safe to mutate without affecting the canonical transcript. */\n messages: Message[];\n /** Tools available for this step. Policies can add or remove tools. */\n tools: Tool[];\n}\n\n/** Information about the model's response, before tool execution. */\nexport interface ResponseInfo {\n /** The assistant message. */\n readonly message: AssistantMessage;\n /** The full transcript including the new message. */\n readonly messages: readonly Message[];\n /** Token usage for this response. */\n readonly usage: Usage;\n /** Aggregated token usage across all steps so far. */\n readonly totalUsage: Usage;\n /** Why the model stopped generating. */\n readonly finishReason: FinishReason;\n /** Parsed structured output, if an output schema was provided. */\n readonly object?: unknown;\n}\n\n/** Information about a tool call before execution. */\nexport interface ToolCallInfo {\n /** The tool call ID. */\n readonly id: string;\n /** The tool name. */\n readonly name: string;\n /** Parsed arguments. Mutable for sanitization by policies. */\n arguments: Record<string, unknown>;\n}\n\n/** Information about a tool call after execution. */\nexport interface ToolResultInfo {\n /** The tool call ID. */\n readonly id: string;\n /** The tool name. */\n readonly name: string;\n /** The arguments that were passed to the tool. */\n readonly arguments: Record<string, unknown>;\n /** The output content produced by the tool. */\n readonly output: readonly Content[];\n /** Whether the tool produced an error. */\n readonly isError: boolean;\n}\n\n/** Information about a completed step. */\nexport interface StepInfo {\n /** Messages produced during this step. */\n readonly messages: readonly Message[];\n /** The full transcript. */\n readonly transcript: readonly Message[];\n /** Token usage for this step. */\n readonly usage: Usage;\n /** Aggregated token usage across all steps so far. */\n readonly totalUsage: Usage;\n /** Why the model stopped in this step. */\n readonly finishReason: FinishReason;\n /** Parsed structured output, if an output schema was provided. */\n readonly object?: unknown;\n}\n\n/**\n * Controls agent loop behavior at key decision points.\n *\n * Implement any combination of hooks — unimplemented hooks default to\n * continue with no side effects.\n *\n * Policies are evaluated in pipeline order: the first policy to return\n * a non-continue result short-circuits, and later policies are skipped.\n * If a hook returns an error, it is treated as a stop directive.\n */\nexport interface Policy {\n /** A human-readable name for this policy, used in error attribution and events. */\n name: string;\n /** Called before each model call. Can mutate the step plan or stop the run. */\n beforeStep?(\n ctx: RunContext,\n plan: StepPlan,\n ): void | BeforeStepAction | Promise<void | BeforeStepAction>;\n /** Called after the model responds, before tool execution. */\n afterResponse?(\n ctx: RunContext,\n info: ResponseInfo,\n ): void | AfterResponseAction | Promise<void | AfterResponseAction>;\n /** Called before each individual tool execution. */\n beforeToolRun?(\n ctx: RunContext,\n call: ToolCallInfo,\n ): void | BeforeToolRunAction | Promise<void | BeforeToolRunAction>;\n /** Called after each individual tool execution. */\n afterToolRun?(\n ctx: RunContext,\n result: ToolResultInfo,\n ): void | AfterToolRunAction | Promise<void | AfterToolRunAction>;\n /** Called after the complete step (model response + tool execution). */\n afterStep?(\n ctx: RunContext,\n info: StepInfo,\n ): void | AfterStepAction | Promise<void | AfterStepAction>;\n}\n\n/** Create a {@link Policy}. */\nexport function definePolicy(config: Policy): Policy {\n return config;\n}\n","import type { Content, ToolCallPart } from \"./content.ts\";\nimport type { AssistantMessage, Message, Prompt } from \"./message.ts\";\nimport type { FinishReason, Usage } from \"./model.ts\";\n\n/** Common fields present on every observer event. */\nexport interface BaseEvent {\n /** Event discriminator. */\n readonly type: string;\n /** Unique identifier for the current run. */\n readonly runId: string;\n /** The current step number (zero-indexed). */\n readonly step: number;\n /** The name of the active agent, if applicable. */\n readonly agent?: string;\n /** Unix timestamp (ms) when the event was created. */\n readonly timestamp: number;\n}\n\n/** Fired when a run begins. */\nexport interface RunStartEvent extends BaseEvent {\n readonly type: \"runStart\";\n /** The model being used for the run. */\n readonly model: string;\n /** System instructions, if provided. */\n readonly instructions?: string;\n /** The input prompt. */\n readonly prompt?: Prompt;\n /** Names of the tools available to the model. */\n readonly tools: string[];\n}\n\n/** Fired when a run completes (successfully or with an error). */\nexport interface RunFinishEvent extends BaseEvent {\n readonly type: \"runFinish\";\n /** Convenience extraction of the final text output. */\n readonly text: string;\n /** The final assistant message. */\n readonly response: AssistantMessage;\n /** The full conversation transcript. */\n readonly transcript: readonly Message[];\n /** Parsed structured output, if an output schema was provided. */\n readonly object?: unknown;\n /** Total number of steps executed. */\n readonly steps: number;\n /** Aggregated token usage for the entire run. */\n readonly usage: Usage;\n /** Why the run ended. */\n readonly finishReason: FinishReason;\n /** The name of the policy that stopped the run, if applicable. */\n readonly stoppedBy?: string;\n /** The error, if the run ended due to a failure. */\n readonly error?: Error;\n /** Wall-clock duration of the run in milliseconds. */\n readonly duration: number;\n}\n\n/** Fired when a step begins (one model call + tool execution cycle). */\nexport interface StepStartEvent extends BaseEvent {\n readonly type: \"stepStart\";\n /** The model being used for this step (may differ from run start if swapped by a policy). */\n readonly model: string;\n}\n\n/** Fired when a step is retried. */\nexport interface StepRetryEvent extends BaseEvent {\n readonly type: \"stepRetry\";\n /** Why the step is being retried. */\n readonly reason?: string;\n /** How many times this step has been retried so far. */\n readonly retries: number;\n}\n\n/** Fired when a step completes (model response + all tool executions). */\nexport interface StepFinishEvent extends BaseEvent {\n readonly type: \"stepFinish\";\n /** Messages produced during this step. */\n readonly messages: readonly Message[];\n /** Parsed structured output, if an output schema was provided. */\n readonly object?: unknown;\n /** Token usage for this step. */\n readonly usage: Usage;\n /** Aggregated token usage across all steps so far. */\n readonly totalUsage: Usage;\n /** Why the model stopped generating in this step. */\n readonly finishReason: FinishReason;\n /** Wall-clock duration of the step in milliseconds. */\n readonly duration: number;\n}\n\n/** Fired after the model responds, before tool execution. */\nexport interface ResponseFinishEvent extends BaseEvent {\n readonly type: \"responseFinish\";\n /** The assistant message. */\n readonly message: AssistantMessage;\n /** Token usage for this response. */\n readonly usage: Usage;\n /** Aggregated token usage across all steps so far. */\n readonly totalUsage: Usage;\n /** Why the model stopped generating. */\n readonly finishReason: FinishReason;\n /** The error, if the response failed. */\n readonly error?: Error;\n /** Wall-clock duration of the model call in milliseconds. */\n readonly duration: number;\n}\n\n/** Fired when the model begins producing text output. */\nexport interface TextStartEvent extends BaseEvent {\n readonly type: \"textStart\";\n}\n\n/** Fired for each chunk of text output. */\nexport interface TextDeltaEvent extends BaseEvent {\n readonly type: \"textDelta\";\n /** The text chunk. */\n readonly text: string;\n}\n\n/** Fired when the model finishes producing text output. */\nexport interface TextStopEvent extends BaseEvent {\n readonly type: \"textStop\";\n}\n\n/** Fired when the model begins a reasoning trace. */\nexport interface ThinkingStartEvent extends BaseEvent {\n readonly type: \"thinkingStart\";\n /** Whether the thinking content is redacted by the provider. */\n readonly redacted?: boolean;\n}\n\n/** Fired for each chunk of reasoning output. */\nexport interface ThinkingDeltaEvent extends BaseEvent {\n readonly type: \"thinkingDelta\";\n /** The reasoning text chunk. */\n readonly text: string;\n}\n\n/** Fired when the model finishes a reasoning trace. */\nexport interface ThinkingStopEvent extends BaseEvent {\n readonly type: \"thinkingStop\";\n}\n\n/** Fired when the model begins producing a tool call. */\nexport interface ToolCallStartEvent extends BaseEvent {\n readonly type: \"toolCallStart\";\n /** The tool call ID, matching {@link ToolCallPart.id}. */\n readonly id: string;\n /** The tool name. */\n readonly name: string;\n}\n\n/** Fired for each chunk of tool call arguments. */\nexport interface ToolCallDeltaEvent extends BaseEvent {\n readonly type: \"toolCallDelta\";\n /** The tool call ID, matching {@link ToolCallPart.id}. */\n readonly id: string;\n /** The tool name. */\n readonly name: string;\n /** Partial JSON arguments received so far. */\n readonly partialArguments: string;\n}\n\n/** Fired when the model finishes producing a tool call. */\nexport interface ToolCallStopEvent extends BaseEvent {\n readonly type: \"toolCallStop\";\n /** The tool call ID, matching {@link ToolCallPart.id}. */\n readonly id: string;\n /** The tool name. */\n readonly name: string;\n /** The fully parsed tool call arguments, matching {@link ToolCallPart.arguments}. */\n readonly arguments: Record<string, unknown>;\n}\n\n/** Fired when a tool begins executing. */\nexport interface ToolRunStartEvent extends BaseEvent {\n readonly type: \"toolRunStart\";\n /** The tool call ID, matching {@link ToolCallPart.id}. */\n readonly id: string;\n /** The tool name. */\n readonly name: string;\n /** The arguments passed to the tool. */\n readonly arguments: Record<string, unknown>;\n}\n\n/** Fired when a tool emits a progress update via {@link ToolContext.update}. */\nexport interface ToolRunUpdateEvent extends BaseEvent {\n readonly type: \"toolRunUpdate\";\n /** The tool call ID, matching {@link ToolCallPart.id}. */\n readonly id: string;\n /** The tool name. */\n readonly name: string;\n /** The progress data emitted by the tool. */\n readonly data: Record<string, unknown>;\n}\n\n/** Fired when a tool finishes executing. */\nexport interface ToolRunEndEvent extends BaseEvent {\n readonly type: \"toolRunEnd\";\n /** The tool call ID, matching {@link ToolCallPart.id}. */\n readonly id: string;\n /** The tool name. */\n readonly name: string;\n /** The content returned by the tool. */\n readonly output: readonly Content[];\n /** The error, if the tool failed. */\n readonly error?: Error;\n /** Wall-clock duration of the tool execution in milliseconds. */\n readonly duration: number;\n}\n\n/** Fired when a tool call is skipped by a policy or the tool's own before hook. */\nexport interface ToolSkipEvent extends BaseEvent {\n readonly type: \"toolSkip\";\n /** The tool call ID, matching {@link ToolCallPart.id}. */\n readonly id: string;\n /** The tool name. */\n readonly name: string;\n /** The arguments the model passed to the tool. */\n readonly arguments: Record<string, unknown>;\n /** Whether the tool was skipped or the entire run was stopped. */\n readonly action: \"skip\" | \"stop\";\n /** What triggered the skip. */\n readonly source: \"policy\" | \"tool\";\n /** Human-readable reason for the skip. */\n readonly reason?: string;\n}\n\n/** Fired when the run is aborted via the abort signal. */\nexport interface AbortEvent extends BaseEvent {\n readonly type: \"abort\";\n /** Human-readable reason for the abort. */\n readonly reason?: string;\n}\n\n/** Fired when an error occurs during the run. */\nexport interface ErrorEvent extends BaseEvent {\n readonly type: \"error\";\n /** The error that occurred. */\n readonly error: Error;\n /** Where the error originated. */\n readonly source: \"provider\" | \"tool\" | \"policy\" | \"validation\" | \"observer\";\n /** The tool call that caused the error, if applicable. */\n readonly toolCall?: ToolCallPart;\n /** The name of the policy that caused the error, if applicable. */\n readonly policy?: string;\n /** The name of the observer that caused the error, if applicable. */\n readonly observer?: string;\n}\n\n/** Discriminated union of all observer events. */\nexport type ObserverEvent =\n | RunStartEvent\n | RunFinishEvent\n | StepStartEvent\n | StepRetryEvent\n | StepFinishEvent\n | ResponseFinishEvent\n | TextStartEvent\n | TextDeltaEvent\n | TextStopEvent\n | ThinkingStartEvent\n | ThinkingDeltaEvent\n | ThinkingStopEvent\n | ToolCallStartEvent\n | ToolCallDeltaEvent\n | ToolCallStopEvent\n | ToolRunStartEvent\n | ToolRunUpdateEvent\n | ToolRunEndEvent\n | ToolSkipEvent\n | AbortEvent\n | ErrorEvent;\n\n/** Auto-generated typed handler for each event (e.g. `onTextDelta`, `onRunFinish`). */\ntype EventHandlers = {\n [E in ObserverEvent as `on${Capitalize<E[\"type\"]>}`]?: (event: E) => void | Promise<void>;\n};\n\n/**\n * Watches the agent loop and reacts to events.\n *\n * Implement individual `on*` handlers for specific events,\n * or a catch-all {@link Observer.handler} for everything.\n */\nexport interface Observer extends EventHandlers {\n /** A human-readable name for this observer. */\n name: string;\n /** Catch-all handler invoked for every event. */\n handler?(event: ObserverEvent): void | Promise<void>;\n}\n\n/** Create an {@link Observer}. */\nexport function defineObserver(config: Observer): Observer {\n return config;\n}\n","/**\n * A push-pull async channel that decouples a producer from a consumer.\n *\n * The producer pushes values without blocking; the consumer pulls via\n * {@link EventChannel.stream | async iteration}. The channel is unbounded —\n * pushed values buffer in memory until consumed.\n *\n * Used internally by the agent loop to deliver observer events to the\n * {@link AgentStream} consumer without blocking the loop.\n */\nexport interface EventChannel<T, TResult> {\n /** Push a value into the channel. No-op after {@link close} or {@link fail}. */\n push(value: T): void;\n\n /** Signal successful completion with a final result. */\n close(result: TResult): void;\n\n /** Signal failure. Rejects the {@link result} promise. */\n fail(error: Error): void;\n\n /** Async iterable consumer side. Yields buffered values, then ends when the channel closes. */\n readonly stream: AsyncIterable<T>;\n\n /** Resolves on {@link close}, rejects on {@link fail}. */\n readonly result: Promise<TResult>;\n}\n\n/** Create an {@link EventChannel}. */\nexport function createEventChannel<T, TResult>(): EventChannel<T, TResult> {\n const buffer: T[] = [];\n let closed = false;\n let waiter: ((item: IteratorResult<T>) => void) | null = null;\n\n let resolveResult!: (value: TResult) => void;\n let rejectResult!: (error: Error) => void;\n const result = new Promise<TResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n function releaseWaiter(): void {\n if (waiter !== null) {\n const resolve = waiter;\n waiter = null;\n resolve({ value: undefined, done: true });\n }\n }\n\n function push(value: T): void {\n if (closed) return;\n if (waiter !== null) {\n const resolve = waiter;\n waiter = null;\n resolve({ value, done: false });\n } else {\n buffer.push(value);\n }\n }\n\n function close(value: TResult): void {\n if (closed) return;\n closed = true;\n resolveResult(value);\n releaseWaiter();\n }\n\n function fail(error: Error): void {\n if (closed) return;\n closed = true;\n rejectResult(error);\n releaseWaiter();\n }\n\n const stream: AsyncIterable<T> = {\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n next(): Promise<IteratorResult<T>> {\n if (buffer.length > 0) {\n return Promise.resolve({ value: buffer.shift()!, done: false });\n }\n if (closed) {\n return Promise.resolve({ value: undefined, done: true });\n }\n return new Promise((resolve) => {\n waiter = resolve;\n });\n },\n return(): Promise<IteratorResult<T>> {\n releaseWaiter();\n return Promise.resolve({ value: undefined, done: true });\n },\n };\n },\n };\n\n return { push, close, fail, stream, result };\n}\n","import type { ErrorEvent, Observer, ObserverEvent } from \"./observer.ts\";\n\n/** Callback that delivers an event to observers and an optional external consumer. */\nexport type EmitFn = (event: ObserverEvent) => void;\n\n/**\n * Create an {@link EmitFn} that delivers events to observers and optionally\n * pushes them into an external consumer (e.g. an {@link EventChannel}).\n *\n * Observer handlers are invoked synchronously; async rejections are caught.\n * No observer can block or crash the agent loop.\n */\nexport function createEmitFn(observers: Observer[], push?: (event: ObserverEvent) => void): EmitFn {\n return (event) => {\n if (push !== undefined) push(event);\n notifyObservers(observers, event, push);\n };\n}\n\n/** Dispatch an event to all observers, reporting observer failures to the others. */\nfunction notifyObservers(\n observers: Observer[],\n event: ObserverEvent,\n push: ((event: ObserverEvent) => void) | undefined,\n): void {\n const isObserverError = event.type === \"error\" && event.source === \"observer\";\n\n for (const observer of observers) {\n invokeObserver(observer, event, (err) => {\n if (isObserverError) return;\n\n const errorEvent: ErrorEvent = {\n type: \"error\",\n runId: event.runId,\n step: event.step,\n agent: event.agent,\n timestamp: Date.now(),\n error: err instanceof Error ? err : new Error(String(err)),\n source: \"observer\",\n observer: observer.name,\n };\n\n if (push !== undefined) push(errorEvent);\n\n for (const other of observers) {\n if (other !== observer) {\n invokeObserver(other, errorEvent, () => {});\n }\n }\n });\n }\n}\n\n/** Call an observer's typed handler and catch-all handler, independently. */\nfunction invokeObserver(\n observer: Observer,\n event: ObserverEvent,\n onError: (err: unknown) => void,\n): void {\n const key = `on${event.type.charAt(0).toUpperCase()}${event.type.slice(1)}`;\n const typed = (observer as unknown as Record<string, unknown>)[key];\n if (typeof typed === \"function\") {\n try {\n const fn = typed as (this: Observer, event: ObserverEvent) => void | Promise<void>;\n const result = fn.call(observer, event);\n if (result != null) Promise.resolve(result).catch(onError);\n } catch (err) {\n onError(err);\n }\n }\n\n if (observer.handler !== undefined) {\n try {\n const result = observer.handler(event);\n if (result != null) Promise.resolve(result).catch(onError);\n } catch (err) {\n onError(err);\n }\n }\n}\n","/* eslint-disable no-await-in-loop */\nimport type { Policy } from \"./policy.ts\";\n\n/**\n * The result of evaluating a policy pipeline.\n *\n * Contains the winning action, the name of the policy that produced it,\n * and — if the policy threw instead of returning — the original error.\n */\nexport interface PolicyResult<TAction> {\n /** The action returned by the winning policy, or a synthetic stop on error. */\n action: TAction;\n /** Name of the policy that produced this result. */\n policy: string;\n /** The error, if the policy threw instead of returning an action. */\n error?: Error;\n}\n\n/**\n * Evaluate policies in pipeline order.\n *\n * The first policy to return a non-void action wins and short-circuits the\n * remaining policies. If a policy throws, the error is caught and treated as\n * a `{ action: \"stop\" }` directive — the error is preserved on the result\n * so the caller can emit an appropriate {@link ErrorEvent}.\n */\nexport async function runPolicies<TAction>(\n policies: Policy[],\n invoke: (policy: Policy) => void | TAction | Promise<void | TAction>,\n): Promise<PolicyResult<TAction> | undefined> {\n for (const policy of policies) {\n try {\n const result = await invoke(policy);\n if (result != null) {\n return { action: result, policy: policy.name };\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n return {\n action: { action: \"stop\", reason: error.message } as TAction,\n policy: policy.name,\n error,\n };\n }\n }\n return undefined;\n}\n","/* eslint-disable no-await-in-loop */\nimport type { Content, ToolCallPart, ToolResultPart } from \"./content.ts\";\nimport { text } from \"./content.ts\";\nimport type { RunContext, ToolContext } from \"./context.ts\";\nimport type { EmitFn } from \"./emit.ts\";\nimport type {\n ErrorEvent,\n ToolRunEndEvent,\n ToolRunStartEvent,\n ToolRunUpdateEvent,\n ToolSkipEvent,\n} from \"./observer.ts\";\nimport type {\n AfterToolRunAction,\n BeforeToolRunAction,\n Policy,\n ToolCallInfo,\n ToolResultInfo,\n} from \"./policy.ts\";\nimport type { Tool } from \"./tool.ts\";\nimport { normalizeToolReturn } from \"./tool.ts\";\nimport { runPolicies } from \"./pipeline.ts\";\n\n/** Internal result from executing a single tool call. */\ninterface ToolExecResult {\n output: Content[];\n isError: boolean;\n stopRun?: string;\n}\n\n/**\n * Execute all tool calls from a model response in parallel.\n *\n * Returns assembled {@link ToolResultPart} entries (one per call, preserving\n * call order) and an optional `stopRun` policy name if any tool or policy\n * signaled a stop.\n */\nexport async function executeToolCalls(\n calls: ToolCallPart[],\n toolMap: Map<string, Tool>,\n policies: Policy[],\n ctx: RunContext,\n emit: EmitFn,\n): Promise<{ results: ToolResultPart[]; stopRun?: string }> {\n const promises = calls.map((call) => {\n const tool = toolMap.get(call.name);\n if (tool === undefined) {\n emit({\n type: \"error\",\n ...base(ctx),\n error: new Error(`Tool \"${call.name}\" is not available`),\n source: \"tool\",\n toolCall: call,\n } satisfies ErrorEvent);\n return Promise.resolve<ToolExecResult>({\n output: [\n text(\n `Tool \"${call.name}\" is not available. Available tools: ${[...toolMap.keys()].join(\", \")}`,\n ),\n ],\n isError: true,\n });\n }\n return executeTool(call, tool, policies, ctx, emit);\n });\n\n const settled = await Promise.all(promises);\n\n let stopRun: string | undefined;\n const results: ToolResultPart[] = [];\n\n for (let i = 0; i < calls.length; i++) {\n const call = calls[i]!;\n const exec = settled[i]!;\n\n results.push({\n type: \"tool_result\",\n id: call.id,\n name: call.name,\n output: exec.output,\n isError: exec.isError ? true : undefined,\n });\n\n if (exec.stopRun !== undefined && stopRun === undefined) {\n stopRun = exec.stopRun;\n }\n }\n\n return { results, stopRun };\n}\n\nasync function executeTool(\n call: ToolCallPart,\n tool: Tool,\n policies: Policy[],\n ctx: RunContext,\n emit: EmitFn,\n): Promise<ToolExecResult> {\n const callInfo: ToolCallInfo = {\n id: call.id,\n name: call.name,\n arguments: { ...call.arguments },\n };\n\n const beforePol = await runPolicies<BeforeToolRunAction>(policies, (p) =>\n p.beforeToolRun?.(ctx, callInfo),\n );\n\n if (beforePol != null) {\n if (beforePol.error) {\n emitError(emit, ctx, beforePol.error, \"policy\", call, beforePol.policy);\n }\n emitSkip(emit, ctx, call, beforePol.action.action, \"policy\", beforePol.action.reason);\n return {\n output: beforePol.action.output ?? [],\n isError: false,\n stopRun: beforePol.action.action === \"stop\" ? beforePol.policy : undefined,\n };\n }\n\n const parsed = tool.schema.safeParse(callInfo.arguments);\n if (!parsed.success) {\n const msg = `Invalid arguments for tool \"${tool.name}\": ${String(parsed.error)}`;\n emitError(emit, ctx, new Error(msg), \"validation\", call);\n return { output: [text(msg)], isError: true };\n }\n\n try {\n const beforeAction = await tool.before?.(parsed.data, ctx);\n if (beforeAction != null) {\n emitSkip(emit, ctx, call, beforeAction.action, \"tool\", beforeAction.reason);\n return {\n output: beforeAction.output ?? [],\n isError: false,\n stopRun: beforeAction.action === \"stop\" ? tool.name : undefined,\n };\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n emitError(emit, ctx, error, \"tool\", call);\n return {\n output: [text(`Error in \"${tool.name}\" before hook: ${error.message}`)],\n isError: true,\n };\n }\n\n const execStart = Date.now();\n\n emit({\n type: \"toolRunStart\",\n ...base(ctx),\n id: call.id,\n name: call.name,\n arguments: callInfo.arguments,\n } satisfies ToolRunStartEvent);\n\n let output: Content[] = [];\n let error: Error | undefined;\n let stopRun: string | undefined;\n let currentArgs: unknown = parsed.data;\n for (;;) {\n const toolSignal =\n tool.timeout !== undefined\n ? AbortSignal.any([ctx.signal, AbortSignal.timeout(tool.timeout)])\n : ctx.signal;\n\n const toolCtx: ToolContext = {\n ...ctx,\n signal: toolSignal,\n id: call.id,\n update(data) {\n emit({\n type: \"toolRunUpdate\",\n ...base(ctx),\n id: call.id,\n name: call.name,\n data,\n } satisfies ToolRunUpdateEvent);\n },\n };\n\n try {\n const raw = await raceAbort((async () => tool.execute(currentArgs, toolCtx))(), toolSignal);\n output = normalizeToolReturn(raw);\n error = undefined;\n } catch (err) {\n error = err instanceof Error ? err : new Error(String(err));\n output = [text(`Error in tool \"${tool.name}\": ${error.message}`)];\n emitError(emit, ctx, error, \"tool\", call);\n }\n\n let shouldRetry = false;\n\n if (tool.after !== undefined) {\n try {\n const action = await tool.after(currentArgs, output, ctx);\n if (action != null) {\n const r = applyAfterAction(action, tool, currentArgs);\n if (r.output !== undefined) {\n output = r.output;\n error = undefined;\n }\n if (r.retry) {\n currentArgs = r.nextArgs;\n stopRun = undefined;\n shouldRetry = true;\n }\n if (r.stop) {\n stopRun = tool.name;\n }\n if (r.validationError) {\n error = r.validationError;\n output = [text(error.message)];\n break;\n }\n }\n } catch (err) {\n emitError(emit, ctx, err instanceof Error ? err : new Error(String(err)), \"tool\", call);\n }\n }\n\n if (shouldRetry) continue;\n\n const resultInfo: ToolResultInfo = {\n id: call.id,\n name: call.name,\n arguments: callInfo.arguments,\n output,\n isError: error !== undefined,\n };\n\n const afterPol = await runPolicies<AfterToolRunAction>(policies, (p) =>\n p.afterToolRun?.(ctx, resultInfo),\n );\n\n if (afterPol != null) {\n if (afterPol.error) {\n emitError(emit, ctx, afterPol.error, \"policy\", call, afterPol.policy);\n }\n const r = applyAfterAction(afterPol.action, tool, currentArgs);\n if (r.output !== undefined) {\n output = r.output;\n error = undefined;\n }\n if (r.retry) {\n currentArgs = r.nextArgs;\n stopRun = undefined;\n continue;\n }\n if (r.stop) {\n stopRun = afterPol.policy;\n }\n if (r.validationError) {\n error = r.validationError;\n output = [text(error.message)];\n break;\n }\n }\n\n break;\n }\n\n emit({\n type: \"toolRunEnd\",\n ...base(ctx),\n id: call.id,\n name: call.name,\n output,\n error,\n duration: Date.now() - execStart,\n } satisfies ToolRunEndEvent);\n\n return { output, isError: error !== undefined, stopRun };\n}\n\n/** Shared result of interpreting an {@link AfterToolRunAction}. */\ninterface AfterActionResult {\n output?: Content[];\n retry: boolean;\n nextArgs: unknown;\n stop: boolean;\n validationError?: Error;\n}\n\n/**\n * Interpret an {@link AfterToolRunAction} from either `tool.after` or\n * `policy.afterToolRun`. Handles rewrite, retry (with optional re-validation),\n * and stop uniformly so the two call sites stay DRY.\n */\nfunction applyAfterAction(\n action: AfterToolRunAction,\n tool: Tool,\n currentArgs: unknown,\n): AfterActionResult {\n switch (action.action) {\n case \"rewrite\":\n return { output: action.output, retry: false, nextArgs: currentArgs, stop: false };\n\n case \"retry\": {\n if (action.arguments !== undefined) {\n const reparsed = tool.schema.safeParse(action.arguments);\n if (!reparsed.success) {\n return {\n retry: false,\n nextArgs: currentArgs,\n stop: false,\n validationError: new Error(\n `Invalid retry arguments for \"${tool.name}\": ${String(reparsed.error)}`,\n ),\n };\n }\n return { retry: true, nextArgs: reparsed.data, stop: false };\n }\n return { retry: true, nextArgs: currentArgs, stop: false };\n }\n\n case \"stop\":\n return { retry: false, nextArgs: currentArgs, stop: true };\n }\n}\n\n/** Create the base fields shared by all observer events. */\nfunction base(ctx: RunContext) {\n return { runId: ctx.runId, step: ctx.step, agent: ctx.agent, timestamp: Date.now() };\n}\n\n/** Emit an {@link ErrorEvent}. */\nfunction emitError(\n emit: EmitFn,\n ctx: RunContext,\n error: Error,\n source: ErrorEvent[\"source\"],\n toolCall?: ToolCallPart,\n policy?: string,\n): void {\n emit({ type: \"error\", ...base(ctx), error, source, toolCall, policy } satisfies ErrorEvent);\n}\n\n/** Emit a {@link ToolSkipEvent}. */\nfunction emitSkip(\n emit: EmitFn,\n ctx: RunContext,\n call: ToolCallPart,\n action: \"skip\" | \"stop\",\n source: \"policy\" | \"tool\",\n reason?: string,\n): void {\n emit({\n type: \"toolSkip\",\n ...base(ctx),\n id: call.id,\n name: call.name,\n arguments: call.arguments,\n action,\n source,\n reason,\n } satisfies ToolSkipEvent);\n}\n\n/**\n * Race a promise against an {@link AbortSignal}, with proper listener cleanup.\n *\n * If the signal is already aborted, rejects immediately. Otherwise, whichever\n * settles first wins, and the abort listener is removed to prevent leaks.\n */\nfunction raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(signal.reason ?? new Error(\"Aborted\"));\n }\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason ?? new Error(\"Aborted\"));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (v) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(e);\n },\n );\n });\n}\n","/* eslint-disable no-await-in-loop */\nimport type { AssistantContent, ToolCallPart } from \"./content.ts\";\nimport type { RunContext } from \"./context.ts\";\nimport type { EmitFn } from \"./emit.ts\";\nimport type { AssistantMessage, Message, Prompt } from \"./message.ts\";\nimport { normalizePrompt, system } from \"./message.ts\";\nimport type { FinishReason, ModelConfig, StreamPart, Usage } from \"./model.ts\";\nimport { addUsage, emptyUsage } from \"./model.ts\";\nimport type {\n AbortEvent,\n ErrorEvent,\n ResponseFinishEvent,\n RunFinishEvent,\n RunStartEvent,\n StepFinishEvent,\n StepRetryEvent,\n StepStartEvent,\n TextDeltaEvent,\n TextStartEvent,\n TextStopEvent,\n ThinkingDeltaEvent,\n ThinkingStartEvent,\n ThinkingStopEvent,\n ToolCallDeltaEvent,\n ToolCallStartEvent,\n ToolCallStopEvent,\n} from \"./observer.ts\";\nimport type {\n AfterResponseAction,\n AfterStepAction,\n BeforeStepAction,\n Policy,\n ResponseInfo,\n StepInfo,\n StepPlan,\n} from \"./policy.ts\";\nimport type { Schema } from \"./schema.ts\";\nimport type { Tool, ToolDefinition } from \"./tool.ts\";\nimport type { AgentConfig, AgentResult, RunOptions } from \"./agent.ts\";\nimport { executeToolCalls } from \"./execute.ts\";\nimport { runPolicies } from \"./pipeline.ts\";\n\n/** Base fields for every observer event, derived from run state. */\ninterface BaseFields {\n readonly runId: string;\n readonly step: number;\n readonly agent: string | undefined;\n readonly timestamp: number;\n}\n\n/** Create base observer event fields from current run state. */\nfunction baseFields(runId: string, step: number, agent: string | undefined): BaseFields {\n return { runId, step, agent, timestamp: Date.now() };\n}\n\n/** Ensure system instructions appear as the first message in a plan's message list. */\nfunction prepareMessages(plan: StepPlan): Message[] {\n const messages = plan.messages;\n if (plan.instructions !== undefined) {\n if (messages.length > 0 && messages[0]!.role === \"system\") {\n messages[0] = system(plan.instructions);\n } else {\n messages.unshift(system(plan.instructions));\n }\n }\n return messages;\n}\n\n/** Extract {@link ToolDefinition} metadata from tools (strips execute/hooks). */\nfunction deriveToolDefs(tools: Tool[]): ToolDefinition[] {\n return tools.map((t) => ({\n name: t.name,\n description: t.description,\n schema: t.schema,\n ...(t.timeout !== undefined && { timeout: t.timeout }),\n }));\n}\n\n/** Extract the {@link ModelConfig} subset from a {@link StepPlan}. */\nfunction extractModelConfig(plan: StepPlan): ModelConfig {\n const config: ModelConfig = {};\n if (plan.maxTokens !== undefined) config.maxTokens = plan.maxTokens;\n if (plan.temperature !== undefined) config.temperature = plan.temperature;\n if (plan.topP !== undefined) config.topP = plan.topP;\n if (plan.topK !== undefined) config.topK = plan.topK;\n if (plan.stopSequences !== undefined) config.stopSequences = plan.stopSequences;\n return config;\n}\n\n/** Extract all {@link ToolCallPart} entries from an assistant message. */\nfunction extractToolCalls(message: AssistantMessage): ToolCallPart[] {\n const calls: ToolCallPart[] = [];\n for (const part of message.content) {\n if (part.type === \"tool_call\") calls.push(part);\n }\n return calls;\n}\n\n/** Join all text content parts from an assistant message. */\nfunction extractText(message: AssistantMessage): string {\n let result = \"\";\n for (const part of message.content) {\n if (part.type === \"text\") {\n if (result) result += \"\\n\";\n result += part.text;\n }\n }\n return result;\n}\n\n/**\n * Parse structured output from the last text part of a response.\n *\n * Returns the validated object on success, `null` on failure. Emits an\n * {@link ErrorEvent} with `source: \"validation\"` on parse or validation failure.\n */\nfunction parseStructuredOutput(\n message: AssistantMessage,\n schema: Schema,\n emit: EmitFn,\n base: BaseFields,\n): unknown | null {\n let lastText: string | undefined;\n for (const part of message.content) {\n if (part.type === \"text\") lastText = part.text;\n }\n if (lastText === undefined) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(lastText);\n } catch {\n emit({\n type: \"error\",\n ...base,\n error: new Error(\"Structured output is not valid JSON\"),\n source: \"validation\",\n } satisfies ErrorEvent);\n return null;\n }\n\n const result = schema.safeParse(parsed);\n if (result.success) return result.data;\n\n emit({\n type: \"error\",\n ...base,\n error: new Error(`Structured output validation failed: ${String(result.error)}`),\n source: \"validation\",\n } satisfies ErrorEvent);\n return null;\n}\n\n/** Result of consuming a model stream. */\ninterface StreamResult {\n message: AssistantMessage;\n usage: Usage;\n finishReason: FinishReason;\n}\n\n/**\n * Consume a model's {@link StreamPart} iterable, assembling the final\n * {@link AssistantMessage} while emitting observer events for each part.\n *\n * Single pass, single piece of state. Throws on stream errors — the caller\n * catches and converts to an error result.\n */\nasync function consumeStream(\n stream: AsyncIterable<StreamPart>,\n emit: EmitFn,\n base: () => BaseFields,\n): Promise<StreamResult> {\n const content: AssistantContent[] = [];\n const toolCalls = new Map<\n string,\n { id: string; name: string; args: string; signature?: string }\n >();\n\n let textBuffer = \"\";\n let thinkingBuffer = \"\";\n let thinkingSignature: string | undefined;\n let thinkingRedacted = false;\n let usage: Usage = emptyUsage();\n let finishReason: FinishReason = \"unknown\";\n\n function flushText(): void {\n if (textBuffer) {\n content.push({ type: \"text\", text: textBuffer });\n textBuffer = \"\";\n }\n }\n\n function flushThinking(): void {\n if (thinkingBuffer || thinkingRedacted) {\n content.push({\n type: \"thinking\",\n thinking: thinkingBuffer,\n signature: thinkingSignature,\n redacted: thinkingRedacted,\n });\n thinkingBuffer = \"\";\n thinkingSignature = undefined;\n thinkingRedacted = false;\n }\n }\n\n for await (const part of stream) {\n switch (part.type) {\n case \"text_start\":\n flushText();\n flushThinking();\n textBuffer = \"\";\n emit({ type: \"textStart\", ...base() } satisfies TextStartEvent);\n break;\n\n case \"text_delta\":\n textBuffer += part.text;\n emit({ type: \"textDelta\", ...base(), text: part.text } satisfies TextDeltaEvent);\n break;\n\n case \"text_end\":\n flushText();\n emit({ type: \"textStop\", ...base() } satisfies TextStopEvent);\n break;\n\n case \"thinking_start\":\n flushText();\n flushThinking();\n thinkingBuffer = \"\";\n thinkingSignature = undefined;\n thinkingRedacted = part.redacted ?? false;\n emit({\n type: \"thinkingStart\",\n ...base(),\n redacted: part.redacted,\n } satisfies ThinkingStartEvent);\n break;\n\n case \"thinking_delta\":\n thinkingBuffer += part.thinking;\n emit({\n type: \"thinkingDelta\",\n ...base(),\n text: part.thinking,\n } satisfies ThinkingDeltaEvent);\n break;\n\n case \"thinking_end\":\n thinkingSignature = part.signature;\n flushThinking();\n emit({ type: \"thinkingStop\", ...base() } satisfies ThinkingStopEvent);\n break;\n\n case \"tool_call_start\":\n flushText();\n flushThinking();\n toolCalls.set(part.id, {\n id: part.id,\n name: part.name,\n args: \"\",\n signature: part.signature,\n });\n emit({\n type: \"toolCallStart\",\n ...base(),\n id: part.id,\n name: part.name,\n } satisfies ToolCallStartEvent);\n break;\n\n case \"tool_call_delta\": {\n const tc = toolCalls.get(part.id);\n if (tc !== undefined) {\n tc.args += part.args;\n emit({\n type: \"toolCallDelta\",\n ...base(),\n id: part.id,\n name: tc.name,\n partialArguments: tc.args,\n } satisfies ToolCallDeltaEvent);\n }\n break;\n }\n\n case \"tool_call_end\": {\n const tc = toolCalls.get(part.id);\n if (tc !== undefined) {\n let args: Record<string, unknown>;\n try {\n args = JSON.parse(tc.args || \"{}\") as Record<string, unknown>;\n } catch (e) {\n throw new Error(`Invalid JSON in tool call arguments for ${tc.name} (${tc.id})`, {\n cause: e,\n });\n }\n content.push({\n type: \"tool_call\",\n id: tc.id,\n name: tc.name,\n arguments: args,\n ...(tc.signature !== undefined && { signature: tc.signature }),\n });\n toolCalls.delete(tc.id);\n emit({\n type: \"toolCallStop\",\n ...base(),\n id: tc.id,\n name: tc.name,\n arguments: args,\n } satisfies ToolCallStopEvent);\n }\n break;\n }\n\n case \"finish\":\n usage = part.usage;\n finishReason = part.finishReason;\n break;\n\n case \"error\":\n throw part.error;\n }\n }\n\n flushThinking();\n flushText();\n\n return { message: { role: \"assistant\", content }, usage, finishReason };\n}\n\n/**\n * Execute an agent run to completion.\n *\n * This function never throws. All errors are caught and reflected in the\n * returned {@link AgentResult}. The caller provides an {@link EmitFn} that\n * receives every observer event as it occurs.\n */\nexport async function executeRun(\n config: AgentConfig,\n prompt: Prompt | undefined,\n options: RunOptions,\n emit: EmitFn,\n): Promise<AgentResult> {\n const runStart = Date.now();\n const runId = crypto.randomUUID();\n const policies: Policy[] = [...(config.policies ?? []), ...(options.policies ?? [])];\n const tools: Tool[] = config.tools ?? [];\n\n const transcript: Message[] = [\n ...(options.transcript ?? []),\n ...(prompt !== undefined ? normalizePrompt(prompt) : []),\n ];\n\n const modelConfig: ModelConfig = {};\n if (options.maxTokens !== undefined) modelConfig.maxTokens = options.maxTokens;\n if (options.temperature !== undefined) modelConfig.temperature = options.temperature;\n if (options.topP !== undefined) modelConfig.topP = options.topP;\n if (options.topK !== undefined) modelConfig.topK = options.topK;\n if (options.stopSequences !== undefined) modelConfig.stopSequences = options.stopSequences;\n\n const signal = options.signal ?? new AbortController().signal;\n const state: Record<string, unknown> = options.state ?? {};\n let totalUsage: Usage = emptyUsage();\n let step = 0;\n let retries = 0;\n let finishReason: FinishReason = \"unknown\";\n let stoppedBy: string | undefined;\n let runError: Error | undefined;\n let parsedObject: unknown;\n let lastResponse: AssistantMessage = { role: \"assistant\", content: [] };\n\n /** Snapshot the current {@link RunContext}. */\n function ctx(): RunContext {\n return { runId, step, agent: config.name, state, retries, signal };\n }\n\n /** Create {@link BaseFields} from current run state. */\n function base(): BaseFields {\n return baseFields(runId, step, config.name);\n }\n\n try {\n emit({\n type: \"runStart\",\n ...base(),\n model: config.model.name,\n instructions: config.instructions,\n prompt: prompt ?? undefined,\n tools: tools.map((t) => t.name),\n } satisfies RunStartEvent);\n\n for (;;) {\n if (signal.aborted) {\n finishReason = \"cancelled\";\n emit({\n type: \"abort\",\n ...base(),\n reason: String(signal.reason ?? \"Aborted\"),\n } satisfies AbortEvent);\n break;\n }\n\n const plan: StepPlan = {\n model: config.model,\n instructions: config.instructions,\n messages: [...transcript],\n tools: [...tools],\n ...modelConfig,\n };\n\n const beforeStep = await runPolicies<BeforeStepAction>(policies, (p) =>\n p.beforeStep?.(ctx(), plan),\n );\n\n if (beforeStep != null) {\n if (beforeStep.error) {\n emit({\n type: \"error\",\n ...base(),\n error: beforeStep.error,\n source: \"policy\",\n policy: beforeStep.policy,\n } satisfies ErrorEvent);\n }\n finishReason = \"stop\";\n stoppedBy = beforeStep.policy;\n break;\n }\n\n const toolMap = new Map(plan.tools.map((t) => [t.name, t]));\n const stepStart = Date.now();\n\n emit({\n type: \"stepStart\",\n ...base(),\n model: plan.model.name,\n } satisfies StepStartEvent);\n\n const callMessages = prepareMessages(plan);\n const toolDefs = deriveToolDefs(plan.tools);\n\n let message: AssistantMessage;\n let stepUsage: Usage;\n let stepFinishReason: FinishReason;\n\n try {\n const result = await consumeStream(\n plan.model.stream({\n messages: callMessages,\n tools: toolDefs.length > 0 ? toolDefs : undefined,\n config: extractModelConfig(plan),\n output: options.output,\n signal,\n }),\n emit,\n base,\n );\n message = result.message;\n stepUsage = result.usage;\n stepFinishReason = result.finishReason;\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n emit({\n type: \"error\",\n ...base(),\n error,\n source: \"provider\",\n } satisfies ErrorEvent);\n message = { role: \"assistant\", content: [] };\n stepUsage = emptyUsage();\n stepFinishReason = \"error\";\n runError = error;\n }\n\n const responseEnd = Date.now();\n totalUsage = addUsage(totalUsage, stepUsage);\n finishReason = stepFinishReason;\n lastResponse = message;\n\n parsedObject =\n options.output !== undefined\n ? parseStructuredOutput(message, options.output, emit, base())\n : undefined;\n\n emit({\n type: \"responseFinish\",\n ...base(),\n message,\n usage: stepUsage,\n totalUsage,\n finishReason: stepFinishReason,\n error: runError,\n duration: responseEnd - stepStart,\n } satisfies ResponseFinishEvent);\n\n if (runError !== undefined) break;\n\n transcript.push(message);\n\n const responseInfo: ResponseInfo = {\n message,\n messages: transcript,\n usage: stepUsage,\n totalUsage,\n finishReason: stepFinishReason,\n object: parsedObject,\n };\n\n const afterResponse = await runPolicies<AfterResponseAction>(policies, (p) =>\n p.afterResponse?.(ctx(), responseInfo),\n );\n\n if (afterResponse != null) {\n if (afterResponse.error) {\n emit({\n type: \"error\",\n ...base(),\n error: afterResponse.error,\n source: \"policy\",\n policy: afterResponse.policy,\n } satisfies ErrorEvent);\n }\n\n const a = afterResponse.action;\n\n if (a.action === \"stop\") {\n finishReason = \"stop\";\n stoppedBy = afterResponse.policy;\n break;\n }\n\n if (a.action === \"replace\") {\n transcript[transcript.length - 1] = a.message;\n lastResponse = a.message;\n message = a.message;\n }\n\n if (a.action === \"retry\") {\n transcript.pop();\n if (a.messages) transcript.push(...a.messages);\n retries++;\n emit({\n type: \"stepRetry\",\n ...base(),\n reason: a.reason,\n retries,\n } satisfies StepRetryEvent);\n continue;\n }\n }\n\n const toolCalls = extractToolCalls(message);\n\n if (toolCalls.length > 0) {\n const { results, stopRun } = await executeToolCalls(\n toolCalls,\n toolMap,\n policies,\n ctx(),\n emit,\n );\n\n transcript.push({ role: \"tool\", content: results });\n\n if (stopRun !== undefined) {\n stoppedBy = stopRun;\n finishReason = \"stop\";\n break;\n }\n }\n\n const stepMessages: Message[] = [message];\n if (toolCalls.length > 0) {\n stepMessages.push(transcript[transcript.length - 1]!);\n }\n\n const stepInfo: StepInfo = {\n messages: stepMessages,\n transcript,\n usage: stepUsage,\n totalUsage,\n finishReason: stepFinishReason,\n object: parsedObject,\n };\n\n const afterStep = await runPolicies<AfterStepAction>(policies, (p) =>\n p.afterStep?.(ctx(), stepInfo),\n );\n\n let injected = false;\n\n if (afterStep != null) {\n if (afterStep.error) {\n emit({\n type: \"error\",\n ...base(),\n error: afterStep.error,\n source: \"policy\",\n policy: afterStep.policy,\n } satisfies ErrorEvent);\n }\n\n const a = afterStep.action;\n\n if (a.action === \"stop\") {\n finishReason = \"stop\";\n stoppedBy = afterStep.policy;\n emit({\n type: \"stepFinish\",\n ...base(),\n messages: stepMessages,\n object: parsedObject,\n usage: stepUsage,\n totalUsage,\n finishReason,\n duration: Date.now() - stepStart,\n } satisfies StepFinishEvent);\n break;\n }\n\n if (a.action === \"retry\") {\n transcript.splice(transcript.length - stepMessages.length, stepMessages.length);\n if (a.messages) transcript.push(...a.messages);\n retries++;\n emit({\n type: \"stepRetry\",\n ...base(),\n reason: a.reason,\n retries,\n } satisfies StepRetryEvent);\n continue;\n }\n\n if (a.action === \"inject\") {\n transcript.push(...a.messages);\n injected = true;\n }\n }\n\n emit({\n type: \"stepFinish\",\n ...base(),\n messages: stepMessages,\n object: parsedObject,\n usage: stepUsage,\n totalUsage,\n finishReason: stepFinishReason,\n duration: Date.now() - stepStart,\n } satisfies StepFinishEvent);\n\n if (toolCalls.length === 0 && !injected) {\n break;\n }\n\n step++;\n retries = 0;\n }\n } catch (err) {\n runError = err instanceof Error ? err : new Error(String(err));\n finishReason = \"error\";\n emit({\n type: \"error\",\n ...base(),\n error: runError,\n source: \"provider\",\n } satisfies ErrorEvent);\n }\n\n const result: AgentResult = {\n text: extractText(lastResponse),\n response: lastResponse,\n transcript,\n steps: step + 1,\n usage: totalUsage,\n finishReason,\n stoppedBy,\n error: runError,\n duration: Date.now() - runStart,\n object: parsedObject as AgentResult[\"object\"],\n };\n\n emit({\n type: \"runFinish\",\n ...base(),\n text: result.text,\n response: result.response,\n transcript: result.transcript,\n object: result.object,\n steps: result.steps,\n usage: result.usage,\n finishReason: result.finishReason,\n stoppedBy: result.stoppedBy,\n error: result.error,\n duration: result.duration,\n } satisfies RunFinishEvent);\n\n return result;\n}\n","import type { AssistantMessage, Message, Prompt } from \"./message.ts\";\nimport type { FinishReason, Model, ModelConfig, Usage } from \"./model.ts\";\nimport type { Observer, ObserverEvent } from \"./observer.ts\";\nimport type { Policy } from \"./policy.ts\";\nimport type { Schema } from \"./schema.ts\";\nimport type { Tool, ToolReturn } from \"./tool.ts\";\nimport { createEventChannel } from \"./channel.ts\";\nimport { createEmitFn } from \"./emit.ts\";\nimport { executeRun } from \"./loop.ts\";\n\n/** Configuration for creating an agent. */\nexport interface AgentConfig {\n /** Human-readable name for this agent, used in events and error attribution. */\n name?: string;\n /** The model instance to use. */\n model: Model;\n /** System instructions that guide model behavior. */\n instructions?: string;\n /** Tools available to the agent. */\n tools?: Tool[];\n /** Observers that watch the agent loop. */\n observers?: Observer[];\n /** Policies that govern the agent loop. */\n policies?: Policy[];\n}\n\n/** Per-run overrides passed to {@link Agent.run} or {@link Agent.stream}. */\nexport interface RunOptions extends Partial<ModelConfig> {\n /** Existing transcript to continue from. */\n transcript?: Message[];\n /** Additional observers merged with the agent's observers. */\n observers?: Observer[];\n /** Additional policies merged with the agent's policies. */\n policies?: Policy[];\n /** Schema for structured output. */\n output?: Schema;\n /** Initial state for the run context. */\n state?: Record<string, unknown>;\n /** Signal for cooperative cancellation. */\n signal?: AbortSignal;\n}\n\n/** The result of an agent run. */\nexport interface AgentResult<TOutput = unknown> {\n /** Convenience extraction of the final text output. */\n readonly text: string;\n /** The final assistant message. */\n readonly response: AssistantMessage;\n /** The full conversation transcript. */\n readonly transcript: readonly Message[];\n /** Total number of steps executed. */\n readonly steps: number;\n /** Aggregated token usage for the entire run. */\n readonly usage: Usage;\n /** Why the run ended. */\n readonly finishReason: FinishReason;\n /** The name of the policy that stopped the run, if applicable. */\n readonly stoppedBy?: string;\n /** The error, if the run ended due to a failure. */\n readonly error?: Error;\n /** Wall-clock duration of the run in milliseconds. */\n readonly duration: number;\n /** Parsed structured output, if an output schema was provided. */\n readonly object?: TOutput | null;\n}\n\n/** An async iterable of observer events with access to the final result. */\nexport interface AgentStream<TOutput = unknown> extends AsyncIterable<ObserverEvent> {\n /** Resolves to the final result when the run completes. */\n readonly result: Promise<AgentResult<TOutput>>;\n}\n\n/** Configuration for converting an agent into a {@link Tool} via {@link Agent.asTool}. */\nexport interface AsToolConfig<TArgs> {\n /** The tool name exposed to the parent agent. */\n name: string;\n /** Description of what this sub-agent does. */\n description: string;\n /** Schema for the tool's arguments. */\n schema: Schema<TArgs>;\n /** Build the prompt from the parsed arguments. */\n prompt(args: TArgs): Prompt;\n /** Transform the agent result into tool output. Defaults to returning the text. */\n output?(result: AgentResult): ToolReturn;\n}\n\n/** An agent that runs a model loop with tools, policies, and observers. */\nexport interface Agent {\n /** Run the agent to completion and return the result. */\n run<T>(\n prompt: Prompt | undefined,\n options: RunOptions & { output: Schema<T> },\n ): Promise<AgentResult<T>>;\n run(prompt?: Prompt, options?: RunOptions): Promise<AgentResult>;\n\n /** Run the agent and stream observer events as they occur. */\n stream<T>(\n prompt: Prompt | undefined,\n options: RunOptions & { output: Schema<T> },\n ): AgentStream<T>;\n stream(prompt?: Prompt, options?: RunOptions): AgentStream;\n\n /** Convert this agent into a tool for use by another agent. */\n asTool<TArgs>(config: AsToolConfig<TArgs>): Tool;\n}\n\n/** Create an {@link Agent} from the given configuration. */\nexport function defineAgent(config: AgentConfig): Agent {\n const agent: Agent = {\n run(prompt?: Prompt, options?: RunOptions): Promise<AgentResult> {\n const opts = options ?? {};\n const observers = [...(config.observers ?? []), ...(opts.observers ?? [])];\n const emit = createEmitFn(observers);\n return executeRun(config, prompt, opts, emit);\n },\n\n stream(prompt?: Prompt, options?: RunOptions): AgentStream {\n const opts = options ?? {};\n const observers = [...(config.observers ?? []), ...(opts.observers ?? [])];\n const channel = createEventChannel<ObserverEvent, AgentResult>();\n const emit = createEmitFn(observers, channel.push);\n\n executeRun(config, prompt, opts, emit).then(\n (result) => channel.close(result),\n (err) => channel.fail(err instanceof Error ? err : new Error(String(err))),\n );\n\n return {\n result: channel.result,\n [Symbol.asyncIterator]() {\n return channel.stream[Symbol.asyncIterator]();\n },\n };\n },\n\n asTool<TArgs>(toolConfig: AsToolConfig<TArgs>): Tool {\n return {\n name: toolConfig.name,\n description: toolConfig.description,\n schema: toolConfig.schema,\n async execute(args: TArgs, ctx) {\n const result = await agent.run(toolConfig.prompt(args), { signal: ctx.signal });\n if (toolConfig.output) return toolConfig.output(result);\n return result.text;\n },\n };\n },\n };\n\n return agent;\n}\n"],"mappings":";;;AAsGA,SAAgB,KAAK,OAAyB;AAC5C,QAAO;EAAE,MAAM;EAAQ,MAAM;EAAO;;;AAItC,SAAgB,KAAK,OAA0C;AAC7D,QAAO;EAAE,MAAM;EAAQ,MAAM;EAAO;;;AAItC,SAAgB,KAAK,MAA2B,WAA6B;AAC3E,QAAO;EAAE,MAAM;EAAQ;EAAM;EAAW;;;AAI1C,SAAgB,IAAI,OAAe,WAA6B;AAC9D,QAAO;EAAE,MAAM;EAAO,KAAK;EAAO,GAAI,aAAa,QAAQ,EAAE,WAAW;EAAG;;;;;ACvE7E,SAAgB,OAAO,SAAkD;AACvE,QAAO;EAAE,MAAM;EAAU,SAAS,OAAO,Y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