@axlsdk/axl 0.19.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -3066,6 +3066,10 @@ type ToolHooks<TInput = unknown, TOutput = unknown> = {
3066
3066
  /** Transform output after the handler runs. Receives handler result and workflow context. */
3067
3067
  after?(output: TOutput, ctx: WorkflowContext): TOutput | Promise<TOutput>;
3068
3068
  };
3069
+ /** JSON-compatible content that a tool may explicitly expose to the model. */
3070
+ type ToolModelOutput = string | number | boolean | null | readonly ToolModelOutput[] | {
3071
+ readonly [key: string]: ToolModelOutput | undefined;
3072
+ };
3069
3073
  /** Tool configuration */
3070
3074
  type ToolConfig<TInput extends z.ZodType, TOutput = unknown> = {
3071
3075
  name: string;
@@ -3080,6 +3084,8 @@ type ToolConfig<TInput extends z.ZodType, TOutput = unknown> = {
3080
3084
  requireApproval?: boolean;
3081
3085
  /** Lifecycle hooks: before/after the handler. */
3082
3086
  hooks?: ToolHooks<z.infer<TInput>, TOutput>;
3087
+ /** Select the subset of a successful result that is sent back to the model. */
3088
+ toModelOutput?(this: void, output: Readonly<TOutput>): ToolModelOutput;
3083
3089
  };
3084
3090
  /** A defined tool instance */
3085
3091
  type Tool<TInput extends z.ZodType = z.ZodType, TOutput = unknown> = {
@@ -3090,6 +3096,8 @@ type Tool<TInput extends z.ZodType = z.ZodType, TOutput = unknown> = {
3090
3096
  readonly retry: RetryPolicy;
3091
3097
  readonly requireApproval: boolean;
3092
3098
  readonly hooks?: ToolHooks<z.infer<TInput>, TOutput>;
3099
+ /** Select the subset of a successful result that is sent back to the model. */
3100
+ toModelOutput?(this: void, output: Readonly<TOutput>): ToolModelOutput;
3093
3101
  /** Run the tool directly from workflow code */
3094
3102
  run(ctx: WorkflowContext, input: z.infer<TInput>): Promise<TOutput>;
3095
3103
  /** Execute the handler (internal use — includes retry logic) */
@@ -4356,6 +4364,12 @@ declare class AxlError extends Error {
4356
4364
  readonly code: string;
4357
4365
  constructor(code: string, message: string);
4358
4366
  }
4367
+ /** Thrown when a tool's model-facing output cannot be projected safely. */
4368
+ declare class ToolModelOutputError extends AxlError {
4369
+ readonly toolName: string;
4370
+ readonly cause: unknown;
4371
+ constructor(toolName: string, cause: unknown);
4372
+ }
4359
4373
  /** Thrown when schema validation fails after all retries exhausted */
4360
4374
  declare class VerifyError extends AxlError {
4361
4375
  readonly lastOutput: unknown;
@@ -5244,4 +5258,4 @@ declare class NoopSpanManager implements SpanManager {
5244
5258
  */
5245
5259
  declare function createSpanManager(config?: TelemetryConfig): Promise<SpanManager>;
5246
5260
 
5247
- export { AXL_EVENT_TYPES, AZURE_PROFILE, type Agent, type AgentCallEndData, type AgentCallInfo, type AgentCallParams, type AgentCallStartData, type AgentConfig, AnthropicProvider, type AnyWorkflow, type ApiKeySource, type AskOptions, type AskScoped, type AuthHeader, type AwaitHumanData, type AwaitHumanOptions, type AwaitHumanResolvedData, type AxlConfig, AxlError, type AxlEvent, type AxlEventBase, AxlEventBus, type AxlEventOf, type AxlEventType, AxlRuntime, AxlStream, BEDROCK_PROFILE, BUILTIN_PROFILES, BudgetExceededError, type BudgetOptions, type BudgetResult, CONFIG_CANDIDATES, COST_BEARING_LEAF_TYPES, type CallbackMeta, type CapabilityFlags, type ChatMessage, type ChatOptions, type CheckpointEventData, type CoalescedPartialObject, type CreateContextOptions, DEEPSEEK_PROFILE, type DelegateData, type DelegateOptions, type Effort, type EmbedResult, type EmbedUsage, type Embedder, type EvalExecuteWorkflow, type EvalHistoryEntry, type EventStreamOptions, EventStreamOverflowError, type ExecuteOptions, type ExecutionInfo, type ExecutionState, GROQ_PROFILE, GeminiProvider, type GuardrailBlockHandler, type GuardrailData, GuardrailError, type GuardrailResult, type GuardrailsConfig, type HandoffDescriptor, type HandoffRecord, type HandoffReturnData, type HandoffStartData, type HumanDecision, InMemoryVectorStore, type InputGuardrail, LLAMACPP_PROFILE, LMSTUDIO_PROFILE, MISTRAL_PROFILE, type MapOptions, MaxTurnsError, McpManager, type McpServer, type McpServerConfig, type McpToolDefinition, type McpToolResult, type MemoryConfig, type MemoryEventData, MemoryManager, MemoryStore, NoConsensus, NoopSpanManager, OLLAMA_PROFILE, OPENAI_PRICING, OPENAI_PROFILE, OPENROUTER_PROFILE, type OpenAICompatibleOptions, OpenAICompatibleProvider, OpenAIEmbedder, OpenAIProvider, OpenAIResponsesProvider, type OutputGuardrail, type OutputValidator, type PendingDecision, type PerModel, type PricingSource, type PricingTable, type Provider, type ProviderAdapter, ProviderError, type ProviderProfile, ProviderRegistry, type ProviderResponse, QuorumNotMet, REDACTED, REDACTION_RULES, type RaceOptions, type RateLimitConfig, RateLimiter, type ReasoningCapture, type ReasoningEmit, type ReasoningProfile, type ReasoningRoundTrip, type RecallOptions, type RecallResult, RedisStore, type RememberOptions, type RememberResult, type ResolvedThinkingOptions, type Result, type RetryPolicy, SGLANG_PROFILE, SQLiteStore, type SchemaCheckData, type SchemaDiagnosticData, type SchemaPromptOption, Session, type SessionOptions, type SpanHandle, type SpanManager, type SpawnOptions, SqliteVectorStore, type StateStore, type StreamChunk, type StringDeltaData, type StringStreamEvent, type StringStreamFilter, type TelemetryConfig, ThinkTagScanner, TimeoutError, type Tool, type ToolApprovalData, type ToolCallData, type ToolCallMessage, type ToolCallStartData, type ToolChoice, type ToolConfig, ToolDenied, type ToolDeniedData, type ToolHooks, VLLM_PROFILE, type ValidateData, type ValidateResult, ValidationError, type VectorEntry, type VectorResult, type VectorStore, type VerifyData, VerifyError, type VerifyOptions, type VerifyRetry, type VoteOptions, type Workflow, type WorkflowConfig, WorkflowContext, type WorkflowContextInit, type WorkflowEndData, type WorkflowStartData, XAI_PROFILE, agent, createSpanManager, defineConfig, estimateOpenAICost, eventCostContribution, expandGlob, extractJson, extractThinkTags, findConfig, hasPositiveTokens, importModule, isCostBearingLeaf, isRetryableStatus, isRootLevel, isUnpricedLeaf, isUsableCost, needsTsxLoader, openaiReasoningEmit, parsePartialJson, pickDefault, pickExport, priceFromTable, reasoningEffortEmit, reasoningObjectEmit, redactEvent, registerConditions, resolveApiKey, resolvePerModel, resolveRuntime, resolveThinkingOptions, stringStreamFromEvents, tool, workflow, zodToJsonSchema };
5261
+ export { AXL_EVENT_TYPES, AZURE_PROFILE, type Agent, type AgentCallEndData, type AgentCallInfo, type AgentCallParams, type AgentCallStartData, type AgentConfig, AnthropicProvider, type AnyWorkflow, type ApiKeySource, type AskOptions, type AskScoped, type AuthHeader, type AwaitHumanData, type AwaitHumanOptions, type AwaitHumanResolvedData, type AxlConfig, AxlError, type AxlEvent, type AxlEventBase, AxlEventBus, type AxlEventOf, type AxlEventType, AxlRuntime, AxlStream, BEDROCK_PROFILE, BUILTIN_PROFILES, BudgetExceededError, type BudgetOptions, type BudgetResult, CONFIG_CANDIDATES, COST_BEARING_LEAF_TYPES, type CallbackMeta, type CapabilityFlags, type ChatMessage, type ChatOptions, type CheckpointEventData, type CoalescedPartialObject, type CreateContextOptions, DEEPSEEK_PROFILE, type DelegateData, type DelegateOptions, type Effort, type EmbedResult, type EmbedUsage, type Embedder, type EvalExecuteWorkflow, type EvalHistoryEntry, type EventStreamOptions, EventStreamOverflowError, type ExecuteOptions, type ExecutionInfo, type ExecutionState, GROQ_PROFILE, GeminiProvider, type GuardrailBlockHandler, type GuardrailData, GuardrailError, type GuardrailResult, type GuardrailsConfig, type HandoffDescriptor, type HandoffRecord, type HandoffReturnData, type HandoffStartData, type HumanDecision, InMemoryVectorStore, type InputGuardrail, LLAMACPP_PROFILE, LMSTUDIO_PROFILE, MISTRAL_PROFILE, type MapOptions, MaxTurnsError, McpManager, type McpServer, type McpServerConfig, type McpToolDefinition, type McpToolResult, type MemoryConfig, type MemoryEventData, MemoryManager, MemoryStore, NoConsensus, NoopSpanManager, OLLAMA_PROFILE, OPENAI_PRICING, OPENAI_PROFILE, OPENROUTER_PROFILE, type OpenAICompatibleOptions, OpenAICompatibleProvider, OpenAIEmbedder, OpenAIProvider, OpenAIResponsesProvider, type OutputGuardrail, type OutputValidator, type PendingDecision, type PerModel, type PricingSource, type PricingTable, type Provider, type ProviderAdapter, ProviderError, type ProviderProfile, ProviderRegistry, type ProviderResponse, QuorumNotMet, REDACTED, REDACTION_RULES, type RaceOptions, type RateLimitConfig, RateLimiter, type ReasoningCapture, type ReasoningEmit, type ReasoningProfile, type ReasoningRoundTrip, type RecallOptions, type RecallResult, RedisStore, type RememberOptions, type RememberResult, type ResolvedThinkingOptions, type Result, type RetryPolicy, SGLANG_PROFILE, SQLiteStore, type SchemaCheckData, type SchemaDiagnosticData, type SchemaPromptOption, Session, type SessionOptions, type SpanHandle, type SpanManager, type SpawnOptions, SqliteVectorStore, type StateStore, type StreamChunk, type StringDeltaData, type StringStreamEvent, type StringStreamFilter, type TelemetryConfig, ThinkTagScanner, TimeoutError, type Tool, type ToolApprovalData, type ToolCallData, type ToolCallMessage, type ToolCallStartData, type ToolChoice, type ToolConfig, ToolDenied, type ToolDeniedData, type ToolHooks, type ToolModelOutput, ToolModelOutputError, VLLM_PROFILE, type ValidateData, type ValidateResult, ValidationError, type VectorEntry, type VectorResult, type VectorStore, type VerifyData, VerifyError, type VerifyOptions, type VerifyRetry, type VoteOptions, type Workflow, type WorkflowConfig, WorkflowContext, type WorkflowContextInit, type WorkflowEndData, type WorkflowStartData, XAI_PROFILE, agent, createSpanManager, defineConfig, estimateOpenAICost, eventCostContribution, expandGlob, extractJson, extractThinkTags, findConfig, hasPositiveTokens, importModule, isCostBearingLeaf, isRetryableStatus, isRootLevel, isUnpricedLeaf, isUsableCost, needsTsxLoader, openaiReasoningEmit, parsePartialJson, pickDefault, pickExport, priceFromTable, reasoningEffortEmit, reasoningObjectEmit, redactEvent, registerConditions, resolveApiKey, resolvePerModel, resolveRuntime, resolveThinkingOptions, stringStreamFromEvents, tool, workflow, zodToJsonSchema };
package/dist/index.d.ts CHANGED
@@ -3066,6 +3066,10 @@ type ToolHooks<TInput = unknown, TOutput = unknown> = {
3066
3066
  /** Transform output after the handler runs. Receives handler result and workflow context. */
3067
3067
  after?(output: TOutput, ctx: WorkflowContext): TOutput | Promise<TOutput>;
3068
3068
  };
3069
+ /** JSON-compatible content that a tool may explicitly expose to the model. */
3070
+ type ToolModelOutput = string | number | boolean | null | readonly ToolModelOutput[] | {
3071
+ readonly [key: string]: ToolModelOutput | undefined;
3072
+ };
3069
3073
  /** Tool configuration */
3070
3074
  type ToolConfig<TInput extends z.ZodType, TOutput = unknown> = {
3071
3075
  name: string;
@@ -3080,6 +3084,8 @@ type ToolConfig<TInput extends z.ZodType, TOutput = unknown> = {
3080
3084
  requireApproval?: boolean;
3081
3085
  /** Lifecycle hooks: before/after the handler. */
3082
3086
  hooks?: ToolHooks<z.infer<TInput>, TOutput>;
3087
+ /** Select the subset of a successful result that is sent back to the model. */
3088
+ toModelOutput?(this: void, output: Readonly<TOutput>): ToolModelOutput;
3083
3089
  };
3084
3090
  /** A defined tool instance */
3085
3091
  type Tool<TInput extends z.ZodType = z.ZodType, TOutput = unknown> = {
@@ -3090,6 +3096,8 @@ type Tool<TInput extends z.ZodType = z.ZodType, TOutput = unknown> = {
3090
3096
  readonly retry: RetryPolicy;
3091
3097
  readonly requireApproval: boolean;
3092
3098
  readonly hooks?: ToolHooks<z.infer<TInput>, TOutput>;
3099
+ /** Select the subset of a successful result that is sent back to the model. */
3100
+ toModelOutput?(this: void, output: Readonly<TOutput>): ToolModelOutput;
3093
3101
  /** Run the tool directly from workflow code */
3094
3102
  run(ctx: WorkflowContext, input: z.infer<TInput>): Promise<TOutput>;
3095
3103
  /** Execute the handler (internal use — includes retry logic) */
@@ -4356,6 +4364,12 @@ declare class AxlError extends Error {
4356
4364
  readonly code: string;
4357
4365
  constructor(code: string, message: string);
4358
4366
  }
4367
+ /** Thrown when a tool's model-facing output cannot be projected safely. */
4368
+ declare class ToolModelOutputError extends AxlError {
4369
+ readonly toolName: string;
4370
+ readonly cause: unknown;
4371
+ constructor(toolName: string, cause: unknown);
4372
+ }
4359
4373
  /** Thrown when schema validation fails after all retries exhausted */
4360
4374
  declare class VerifyError extends AxlError {
4361
4375
  readonly lastOutput: unknown;
@@ -5244,4 +5258,4 @@ declare class NoopSpanManager implements SpanManager {
5244
5258
  */
5245
5259
  declare function createSpanManager(config?: TelemetryConfig): Promise<SpanManager>;
5246
5260
 
5247
- export { AXL_EVENT_TYPES, AZURE_PROFILE, type Agent, type AgentCallEndData, type AgentCallInfo, type AgentCallParams, type AgentCallStartData, type AgentConfig, AnthropicProvider, type AnyWorkflow, type ApiKeySource, type AskOptions, type AskScoped, type AuthHeader, type AwaitHumanData, type AwaitHumanOptions, type AwaitHumanResolvedData, type AxlConfig, AxlError, type AxlEvent, type AxlEventBase, AxlEventBus, type AxlEventOf, type AxlEventType, AxlRuntime, AxlStream, BEDROCK_PROFILE, BUILTIN_PROFILES, BudgetExceededError, type BudgetOptions, type BudgetResult, CONFIG_CANDIDATES, COST_BEARING_LEAF_TYPES, type CallbackMeta, type CapabilityFlags, type ChatMessage, type ChatOptions, type CheckpointEventData, type CoalescedPartialObject, type CreateContextOptions, DEEPSEEK_PROFILE, type DelegateData, type DelegateOptions, type Effort, type EmbedResult, type EmbedUsage, type Embedder, type EvalExecuteWorkflow, type EvalHistoryEntry, type EventStreamOptions, EventStreamOverflowError, type ExecuteOptions, type ExecutionInfo, type ExecutionState, GROQ_PROFILE, GeminiProvider, type GuardrailBlockHandler, type GuardrailData, GuardrailError, type GuardrailResult, type GuardrailsConfig, type HandoffDescriptor, type HandoffRecord, type HandoffReturnData, type HandoffStartData, type HumanDecision, InMemoryVectorStore, type InputGuardrail, LLAMACPP_PROFILE, LMSTUDIO_PROFILE, MISTRAL_PROFILE, type MapOptions, MaxTurnsError, McpManager, type McpServer, type McpServerConfig, type McpToolDefinition, type McpToolResult, type MemoryConfig, type MemoryEventData, MemoryManager, MemoryStore, NoConsensus, NoopSpanManager, OLLAMA_PROFILE, OPENAI_PRICING, OPENAI_PROFILE, OPENROUTER_PROFILE, type OpenAICompatibleOptions, OpenAICompatibleProvider, OpenAIEmbedder, OpenAIProvider, OpenAIResponsesProvider, type OutputGuardrail, type OutputValidator, type PendingDecision, type PerModel, type PricingSource, type PricingTable, type Provider, type ProviderAdapter, ProviderError, type ProviderProfile, ProviderRegistry, type ProviderResponse, QuorumNotMet, REDACTED, REDACTION_RULES, type RaceOptions, type RateLimitConfig, RateLimiter, type ReasoningCapture, type ReasoningEmit, type ReasoningProfile, type ReasoningRoundTrip, type RecallOptions, type RecallResult, RedisStore, type RememberOptions, type RememberResult, type ResolvedThinkingOptions, type Result, type RetryPolicy, SGLANG_PROFILE, SQLiteStore, type SchemaCheckData, type SchemaDiagnosticData, type SchemaPromptOption, Session, type SessionOptions, type SpanHandle, type SpanManager, type SpawnOptions, SqliteVectorStore, type StateStore, type StreamChunk, type StringDeltaData, type StringStreamEvent, type StringStreamFilter, type TelemetryConfig, ThinkTagScanner, TimeoutError, type Tool, type ToolApprovalData, type ToolCallData, type ToolCallMessage, type ToolCallStartData, type ToolChoice, type ToolConfig, ToolDenied, type ToolDeniedData, type ToolHooks, VLLM_PROFILE, type ValidateData, type ValidateResult, ValidationError, type VectorEntry, type VectorResult, type VectorStore, type VerifyData, VerifyError, type VerifyOptions, type VerifyRetry, type VoteOptions, type Workflow, type WorkflowConfig, WorkflowContext, type WorkflowContextInit, type WorkflowEndData, type WorkflowStartData, XAI_PROFILE, agent, createSpanManager, defineConfig, estimateOpenAICost, eventCostContribution, expandGlob, extractJson, extractThinkTags, findConfig, hasPositiveTokens, importModule, isCostBearingLeaf, isRetryableStatus, isRootLevel, isUnpricedLeaf, isUsableCost, needsTsxLoader, openaiReasoningEmit, parsePartialJson, pickDefault, pickExport, priceFromTable, reasoningEffortEmit, reasoningObjectEmit, redactEvent, registerConditions, resolveApiKey, resolvePerModel, resolveRuntime, resolveThinkingOptions, stringStreamFromEvents, tool, workflow, zodToJsonSchema };
5261
+ export { AXL_EVENT_TYPES, AZURE_PROFILE, type Agent, type AgentCallEndData, type AgentCallInfo, type AgentCallParams, type AgentCallStartData, type AgentConfig, AnthropicProvider, type AnyWorkflow, type ApiKeySource, type AskOptions, type AskScoped, type AuthHeader, type AwaitHumanData, type AwaitHumanOptions, type AwaitHumanResolvedData, type AxlConfig, AxlError, type AxlEvent, type AxlEventBase, AxlEventBus, type AxlEventOf, type AxlEventType, AxlRuntime, AxlStream, BEDROCK_PROFILE, BUILTIN_PROFILES, BudgetExceededError, type BudgetOptions, type BudgetResult, CONFIG_CANDIDATES, COST_BEARING_LEAF_TYPES, type CallbackMeta, type CapabilityFlags, type ChatMessage, type ChatOptions, type CheckpointEventData, type CoalescedPartialObject, type CreateContextOptions, DEEPSEEK_PROFILE, type DelegateData, type DelegateOptions, type Effort, type EmbedResult, type EmbedUsage, type Embedder, type EvalExecuteWorkflow, type EvalHistoryEntry, type EventStreamOptions, EventStreamOverflowError, type ExecuteOptions, type ExecutionInfo, type ExecutionState, GROQ_PROFILE, GeminiProvider, type GuardrailBlockHandler, type GuardrailData, GuardrailError, type GuardrailResult, type GuardrailsConfig, type HandoffDescriptor, type HandoffRecord, type HandoffReturnData, type HandoffStartData, type HumanDecision, InMemoryVectorStore, type InputGuardrail, LLAMACPP_PROFILE, LMSTUDIO_PROFILE, MISTRAL_PROFILE, type MapOptions, MaxTurnsError, McpManager, type McpServer, type McpServerConfig, type McpToolDefinition, type McpToolResult, type MemoryConfig, type MemoryEventData, MemoryManager, MemoryStore, NoConsensus, NoopSpanManager, OLLAMA_PROFILE, OPENAI_PRICING, OPENAI_PROFILE, OPENROUTER_PROFILE, type OpenAICompatibleOptions, OpenAICompatibleProvider, OpenAIEmbedder, OpenAIProvider, OpenAIResponsesProvider, type OutputGuardrail, type OutputValidator, type PendingDecision, type PerModel, type PricingSource, type PricingTable, type Provider, type ProviderAdapter, ProviderError, type ProviderProfile, ProviderRegistry, type ProviderResponse, QuorumNotMet, REDACTED, REDACTION_RULES, type RaceOptions, type RateLimitConfig, RateLimiter, type ReasoningCapture, type ReasoningEmit, type ReasoningProfile, type ReasoningRoundTrip, type RecallOptions, type RecallResult, RedisStore, type RememberOptions, type RememberResult, type ResolvedThinkingOptions, type Result, type RetryPolicy, SGLANG_PROFILE, SQLiteStore, type SchemaCheckData, type SchemaDiagnosticData, type SchemaPromptOption, Session, type SessionOptions, type SpanHandle, type SpanManager, type SpawnOptions, SqliteVectorStore, type StateStore, type StreamChunk, type StringDeltaData, type StringStreamEvent, type StringStreamFilter, type TelemetryConfig, ThinkTagScanner, TimeoutError, type Tool, type ToolApprovalData, type ToolCallData, type ToolCallMessage, type ToolCallStartData, type ToolChoice, type ToolConfig, ToolDenied, type ToolDeniedData, type ToolHooks, type ToolModelOutput, ToolModelOutputError, VLLM_PROFILE, type ValidateData, type ValidateResult, ValidationError, type VectorEntry, type VectorResult, type VectorStore, type VerifyData, VerifyError, type VerifyOptions, type VerifyRetry, type VoteOptions, type Workflow, type WorkflowConfig, WorkflowContext, type WorkflowContextInit, type WorkflowEndData, type WorkflowStartData, XAI_PROFILE, agent, createSpanManager, defineConfig, estimateOpenAICost, eventCostContribution, expandGlob, extractJson, extractThinkTags, findConfig, hasPositiveTokens, importModule, isCostBearingLeaf, isRetryableStatus, isRootLevel, isUnpricedLeaf, isUsableCost, needsTsxLoader, openaiReasoningEmit, parsePartialJson, pickDefault, pickExport, priceFromTable, reasoningEffortEmit, reasoningObjectEmit, redactEvent, registerConditions, resolveApiKey, resolvePerModel, resolveRuntime, resolveThinkingOptions, stringStreamFromEvents, tool, workflow, zodToJsonSchema };
package/dist/index.js CHANGED
@@ -73,6 +73,7 @@ function tool(config) {
73
73
  retry: retryPolicy,
74
74
  requireApproval: config.requireApproval ?? false,
75
75
  hooks: config.hooks,
76
+ ...config.toModelOutput !== void 0 ? { toModelOutput: config.toModelOutput } : {},
76
77
  async run(ctx, input) {
77
78
  const startTime = Date.now();
78
79
  try {
@@ -134,6 +135,17 @@ var AxlError = class extends Error {
134
135
  this.code = code;
135
136
  }
136
137
  };
138
+ var ToolModelOutputError = class extends AxlError {
139
+ toolName;
140
+ cause;
141
+ constructor(toolName, cause) {
142
+ super("TOOL_MODEL_OUTPUT_ERROR", `Failed to prepare model output for tool "${toolName}"`);
143
+ this.name = "ToolModelOutputError";
144
+ this.toolName = toolName;
145
+ this.cause = cause;
146
+ Object.defineProperty(this, "cause", { enumerable: false });
147
+ }
148
+ };
137
149
  var VerifyError = class extends AxlError {
138
150
  lastOutput;
139
151
  zodError;
@@ -2154,6 +2166,15 @@ function sanitizeSchemaForGemini(schema) {
2154
2166
  }
2155
2167
  return out;
2156
2168
  }
2169
+ function parseGeminiFunctionResponse(content) {
2170
+ let parsed;
2171
+ try {
2172
+ parsed = JSON.parse(content);
2173
+ } catch {
2174
+ return { result: content };
2175
+ }
2176
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : { result: parsed };
2177
+ }
2157
2178
  var GEMINI_PRICING = {
2158
2179
  "gemini-2.5-pro": [125e-8, 1e-5],
2159
2180
  "gemini-2.5-flash": [3e-7, 25e-7],
@@ -2489,15 +2510,9 @@ var GeminiProvider = class {
2489
2510
  }
2490
2511
  } else if (msg.role === "tool") {
2491
2512
  const functionName = toolCallIdToName.get(msg.tool_call_id) ?? "unknown";
2492
- let responseData;
2493
- try {
2494
- responseData = JSON.parse(msg.content);
2495
- } catch {
2496
- responseData = { result: msg.content };
2497
- }
2498
2513
  const functionResponse = {
2499
2514
  name: functionName,
2500
- response: responseData
2515
+ response: parseGeminiFunctionResponse(msg.content)
2501
2516
  };
2502
2517
  if (msg.tool_call_id && geminiNativeIds.has(msg.tool_call_id)) {
2503
2518
  functionResponse.id = msg.tool_call_id;
@@ -4727,8 +4742,191 @@ function resolveConfig(config) {
4727
4742
  return resolved;
4728
4743
  }
4729
4744
 
4745
+ // src/tool-model-output.ts
4746
+ import { types as nodeTypes } from "util";
4747
+ function invalid(path, reason) {
4748
+ return new Error(`Invalid tool model output at ${path}: ${reason}`);
4749
+ }
4750
+ function propertyPath(parent, key) {
4751
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)) return `${parent}.${key}`;
4752
+ let escaped = "";
4753
+ for (const character of key) {
4754
+ const code = character.charCodeAt(0);
4755
+ if (character === "\\" || character === '"') escaped += `\\${character}`;
4756
+ else if (code <= 31 || code === 8232 || code === 8233) {
4757
+ escaped += `\\u${code.toString(16).padStart(4, "0")}`;
4758
+ } else escaped += character;
4759
+ }
4760
+ return `${parent}["${escaped}"]`;
4761
+ }
4762
+ function normalize(value, path, stack) {
4763
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
4764
+ if (typeof value === "number") {
4765
+ if (!Number.isFinite(value)) throw invalid(path, "number must be finite");
4766
+ return value;
4767
+ }
4768
+ if (value === void 0) throw invalid(path, "undefined is only allowed on object properties");
4769
+ if (typeof value === "bigint" || typeof value === "function" || typeof value === "symbol") {
4770
+ throw invalid(path, `unsupported ${typeof value}`);
4771
+ }
4772
+ if (typeof value !== "object") throw invalid(path, `unsupported ${typeof value}`);
4773
+ let prototype;
4774
+ let descriptors;
4775
+ try {
4776
+ prototype = Object.getPrototypeOf(value);
4777
+ descriptors = Object.getOwnPropertyDescriptors(value);
4778
+ Object.setPrototypeOf(descriptors, null);
4779
+ } catch (cause) {
4780
+ throw invalid(
4781
+ path,
4782
+ `object inspection failed (${cause instanceof Error ? cause.name : "error"})`
4783
+ );
4784
+ }
4785
+ if (stack.has(value)) throw invalid(path, "cyclic reference");
4786
+ for (const key of Reflect.ownKeys(descriptors)) {
4787
+ const descriptor = descriptors[key];
4788
+ if (descriptor && !("value" in descriptor)) {
4789
+ throw invalid(
4790
+ typeof key === "string" ? propertyPath(path, key) : `${path}[symbol]`,
4791
+ "accessor properties are not supported"
4792
+ );
4793
+ }
4794
+ if (typeof key === "symbol" && descriptor?.enumerable) {
4795
+ throw invalid(`${path}[symbol]`, "enumerable symbol keys are not supported");
4796
+ }
4797
+ }
4798
+ if (typeof descriptors.toJSON?.value === "function") {
4799
+ throw invalid(propertyPath(path, "toJSON"), "custom toJSON is not supported");
4800
+ }
4801
+ const array = Array.isArray(value);
4802
+ if (array && prototype !== Array.prototype && prototype !== null) {
4803
+ throw invalid(path, "array subclasses are not supported");
4804
+ }
4805
+ const inheritedToJSON = prototype === Array.prototype || prototype === Object.prototype ? Object.getOwnPropertyDescriptor(prototype, "toJSON") : void 0;
4806
+ if (typeof inheritedToJSON?.value === "function") {
4807
+ throw invalid(propertyPath(path, "toJSON"), "inherited custom toJSON is not supported");
4808
+ }
4809
+ const inheritedThen = prototype === Array.prototype || prototype === Object.prototype ? Object.getOwnPropertyDescriptor(prototype, "then") : void 0;
4810
+ if (typeof descriptors.then?.value === "function" || inheritedThen !== void 0 && (!("value" in inheritedThen) || typeof inheritedThen.value === "function")) {
4811
+ throw invalid(path, "thenable output is not supported");
4812
+ }
4813
+ stack.add(value);
4814
+ try {
4815
+ if (array) {
4816
+ const normalized2 = [];
4817
+ const length = descriptors.length?.value;
4818
+ if (!Number.isSafeInteger(length) || length < 0) {
4819
+ throw invalid(propertyPath(path, "length"), "array length is invalid");
4820
+ }
4821
+ for (let index = 0; index < length; index++) {
4822
+ const descriptor = descriptors[String(index)];
4823
+ if (!descriptor || !("value" in descriptor)) {
4824
+ throw invalid(`${path}[${index}]`, "arrays must be dense data properties");
4825
+ }
4826
+ if (descriptor.value === void 0) {
4827
+ throw invalid(`${path}[${index}]`, "array values cannot be undefined");
4828
+ }
4829
+ normalized2.push(normalize(descriptor.value, `${path}[${index}]`, stack));
4830
+ }
4831
+ for (const key of Object.keys(descriptors)) {
4832
+ const descriptor = descriptors[key];
4833
+ if (!descriptor?.enumerable) continue;
4834
+ const index = Number(key);
4835
+ if (!Number.isInteger(index) || index < 0 || index >= length || String(index) !== key) {
4836
+ throw invalid(propertyPath(path, key), "non-index array properties are not supported");
4837
+ }
4838
+ }
4839
+ Object.setPrototypeOf(normalized2, null);
4840
+ return normalized2;
4841
+ }
4842
+ if (prototype !== Object.prototype && prototype !== null) {
4843
+ throw invalid(path, "only plain objects and null-prototype records are supported");
4844
+ }
4845
+ const normalized = /* @__PURE__ */ Object.create(null);
4846
+ for (const key of Object.keys(descriptors)) {
4847
+ const descriptor = descriptors[key];
4848
+ if (!descriptor?.enumerable) continue;
4849
+ if (!("value" in descriptor)) {
4850
+ throw invalid(propertyPath(path, key), "accessor properties are not supported");
4851
+ }
4852
+ if (descriptor.value === void 0) continue;
4853
+ normalized[key] = normalize(descriptor.value, propertyPath(path, key), stack);
4854
+ }
4855
+ return normalized;
4856
+ } finally {
4857
+ stack.delete(value);
4858
+ }
4859
+ }
4860
+ function serializeToolModelOutput(toolName, output) {
4861
+ try {
4862
+ if (nodeTypes.isPromise(output)) {
4863
+ void Promise.prototype.then.call(output, void 0, () => void 0);
4864
+ }
4865
+ if (typeof output === "string") return output;
4866
+ return JSON.stringify(normalize(output, "$", /* @__PURE__ */ new WeakSet()));
4867
+ } catch (cause) {
4868
+ throw new ToolModelOutputError(toolName, cause);
4869
+ }
4870
+ }
4871
+
4730
4872
  // src/context.ts
4731
4873
  var signalStorage = new AsyncLocalStorage();
4874
+ function isErrorShaped(value) {
4875
+ return value !== null && typeof value === "object" && "error" in value;
4876
+ }
4877
+ function isErrorShapedSafely(value) {
4878
+ try {
4879
+ return isErrorShaped(value);
4880
+ } catch {
4881
+ return false;
4882
+ }
4883
+ }
4884
+ function recordToolSpanResult(span, value, suppressInspectionErrors) {
4885
+ let isError = false;
4886
+ let errorMessage;
4887
+ const inspect = () => {
4888
+ if (isErrorShaped(value)) {
4889
+ isError = true;
4890
+ errorMessage = value.error;
4891
+ } else {
4892
+ isError = false;
4893
+ }
4894
+ };
4895
+ if (suppressInspectionErrors) {
4896
+ try {
4897
+ inspect();
4898
+ } catch {
4899
+ isError = false;
4900
+ errorMessage = void 0;
4901
+ }
4902
+ } else {
4903
+ inspect();
4904
+ }
4905
+ span.setAttribute("axl.tool.success", !isError);
4906
+ if (isError) span.setStatus("error", errorMessage);
4907
+ }
4908
+ function prepareToolModelOutput(toolName, project) {
4909
+ let output;
4910
+ try {
4911
+ output = project();
4912
+ } catch (cause) {
4913
+ throw new ToolModelOutputError(toolName, cause);
4914
+ }
4915
+ return serializeToolModelOutput(toolName, output);
4916
+ }
4917
+ function finalizeToolResult(options) {
4918
+ const { toolName, configuredTool, outcome, legacyContent, emitEnd, beforeProjection } = options;
4919
+ const projectionEligible = configuredTool !== void 0 && !configuredTool.sensitive && outcome.kind === "returned" && configuredTool.toModelOutput !== void 0;
4920
+ if (projectionEligible) {
4921
+ emitEnd();
4922
+ beforeProjection();
4923
+ const project = configuredTool.toModelOutput;
4924
+ return prepareToolModelOutput(toolName, () => project(outcome.value));
4925
+ }
4926
+ const content = legacyContent();
4927
+ emitEnd();
4928
+ return content;
4929
+ }
4732
4930
  var askStorage = new AsyncLocalStorage();
4733
4931
  var inlineSchemaCache = /* @__PURE__ */ new WeakMap();
4734
4932
  function zodToJsonSchema(schema) {
@@ -5423,6 +5621,7 @@ ${appendedSchemaText}`;
5423
5621
  let lastStartAttempt = 1;
5424
5622
  let lastStartMaxAttempts = 1;
5425
5623
  while (turns < maxTurns) {
5624
+ this.currentSignal?.throwIfAborted();
5426
5625
  if (Date.now() - startTime > timeoutMs) {
5427
5626
  throw new TimeoutError("ctx.ask()", timeoutMs);
5428
5627
  }
@@ -5524,6 +5723,7 @@ ${appendedSchemaText}`;
5524
5723
  this.onAgentStart?.({ agent: agent2._name, model: modelUri }, callbackMeta);
5525
5724
  let response;
5526
5725
  try {
5726
+ this.currentSignal?.throwIfAborted();
5527
5727
  if (this._streamingEnabled) {
5528
5728
  let content2 = "";
5529
5729
  const toolCalls = [];
@@ -5825,6 +6025,8 @@ ${appendedSchemaText}`;
5825
6025
  return await handoffFn();
5826
6026
  }
5827
6027
  }
6028
+ const tool2 = agent2._config.tools?.find((candidate) => candidate.name === toolName);
6029
+ const isMcpTool = !tool2 && this.mcpManager?.isMcpTool(toolName);
5828
6030
  const toolOverride = this.toolOverrides?.get(toolName);
5829
6031
  if (toolOverride) {
5830
6032
  let toolArgs2;
@@ -5849,38 +6051,47 @@ ${appendedSchemaText}`;
5849
6051
  callbackMeta
5850
6052
  );
5851
6053
  const toolStart2 = Date.now();
6054
+ const suppressErrorShapeInspection2 = tool2?.sensitive === true || tool2?.toModelOutput !== void 0;
5852
6055
  const executeOverride = async () => {
5853
- let toolResult3;
5854
6056
  try {
5855
- toolResult3 = await toolOverride(toolArgs2);
6057
+ return { kind: "returned", value: await toolOverride(toolArgs2) };
5856
6058
  } catch (err) {
5857
- toolResult3 = { error: err instanceof Error ? err.message : String(err) };
6059
+ return {
6060
+ kind: "thrown",
6061
+ value: { error: err instanceof Error ? err.message : String(err) }
6062
+ };
5858
6063
  }
5859
- return toolResult3;
5860
6064
  };
5861
- const toolResult2 = this.spanManager ? await this.spanManager.withSpanAsync(
6065
+ const outcome = this.spanManager ? await this.spanManager.withSpanAsync(
5862
6066
  "axl.tool.call",
5863
6067
  {
5864
6068
  "axl.tool.name": toolName,
5865
6069
  "axl.agent.name": agent2._name
5866
6070
  },
5867
6071
  async (span) => {
5868
- const r = await executeOverride();
6072
+ const result = await executeOverride();
5869
6073
  span.setAttribute("axl.tool.duration", Date.now() - toolStart2);
5870
- const isError = r && typeof r === "object" && "error" in r;
5871
- span.setAttribute("axl.tool.success", !isError);
5872
- if (isError)
5873
- span.setStatus("error", r.error);
5874
- return r;
6074
+ recordToolSpanResult(span, result.value, suppressErrorShapeInspection2);
6075
+ return result;
5875
6076
  }
5876
6077
  ) : await executeOverride();
5877
- const resultContent2 = JSON.stringify(toolResult2);
5878
- this.emitEvent({
5879
- type: "tool_call_end",
5880
- agent: agent2._name,
5881
- tool: toolName,
5882
- duration: Date.now() - toolStart2,
5883
- data: { args: toolArgs2, result: toolResult2, callId: toolCall.id }
6078
+ const toolResult2 = outcome.value;
6079
+ const resultContent2 = finalizeToolResult({
6080
+ toolName,
6081
+ configuredTool: tool2,
6082
+ outcome,
6083
+ legacyContent: () => tool2?.sensitive ? "[REDACTED - sensitive tool output]" : JSON.stringify(toolResult2),
6084
+ emitEnd: () => {
6085
+ const toolDuration2 = Date.now() - toolStart2;
6086
+ this.emitEvent({
6087
+ type: "tool_call_end",
6088
+ agent: agent2._name,
6089
+ tool: toolName,
6090
+ duration: toolDuration2,
6091
+ data: { args: toolArgs2, result: toolResult2, callId: toolCall.id }
6092
+ });
6093
+ },
6094
+ beforeProjection: () => this.currentSignal?.throwIfAborted()
5884
6095
  });
5885
6096
  currentMessages.push({
5886
6097
  role: "tool",
@@ -5889,8 +6100,6 @@ ${appendedSchemaText}`;
5889
6100
  });
5890
6101
  continue;
5891
6102
  }
5892
- const tool2 = agent2._config.tools?.find((t) => t.name === toolName);
5893
- const isMcpTool = !tool2 && this.mcpManager?.isMcpTool(toolName);
5894
6103
  if (!tool2 && !isMcpTool) {
5895
6104
  this.emitEvent({ type: "tool_denied", agent: agent2._name, tool: toolName });
5896
6105
  currentMessages.push({
@@ -5919,6 +6128,7 @@ ${appendedSchemaText}`;
5919
6128
  });
5920
6129
  this.onToolCall?.({ name: toolName, args: toolArgs, callId: toolCall.id }, callbackMeta);
5921
6130
  const toolStart = Date.now();
6131
+ const suppressErrorShapeInspection = tool2?.sensitive === true || tool2?.toModelOutput !== void 0;
5922
6132
  if (tool2 && tool2.requireApproval) {
5923
6133
  const approvalFn = async () => {
5924
6134
  const decision = await this.awaitHuman({
@@ -5980,12 +6190,12 @@ ${appendedSchemaText}`;
5980
6190
  }
5981
6191
  }
5982
6192
  const executeTool = async () => {
5983
- let toolResult2;
6193
+ let outcome;
5984
6194
  let resultContent2;
5985
6195
  if (isMcpTool && this.mcpManager) {
5986
6196
  try {
5987
6197
  const mcpResult = await this.mcpManager.callTool(toolName, toolArgs);
5988
- toolResult2 = mcpResult;
6198
+ outcome = { kind: "returned", value: mcpResult };
5989
6199
  resultContent2 = mcpResult.content.map(
5990
6200
  (c) => c.type === "text" ? c.text : `[${c.type}]`
5991
6201
  ).join("\n");
@@ -5993,34 +6203,50 @@ ${appendedSchemaText}`;
5993
6203
  resultContent2 = `Error: ${resultContent2}`;
5994
6204
  }
5995
6205
  } catch (err) {
5996
- toolResult2 = { error: err instanceof Error ? err.message : String(err) };
5997
- resultContent2 = JSON.stringify(toolResult2);
6206
+ outcome = {
6207
+ kind: "thrown",
6208
+ value: { error: err instanceof Error ? err.message : String(err) }
6209
+ };
6210
+ resultContent2 = JSON.stringify(outcome.value);
5998
6211
  }
5999
6212
  } else if (tool2) {
6000
6213
  const childCtx = this.createChildContext();
6001
6214
  try {
6002
- toolResult2 = await tool2._execute(toolArgs, childCtx);
6215
+ outcome = { kind: "returned", value: await tool2._execute(toolArgs, childCtx) };
6003
6216
  } catch (err) {
6004
- toolResult2 = { error: err instanceof Error ? err.message : String(err) };
6217
+ outcome = {
6218
+ kind: "thrown",
6219
+ value: { error: err instanceof Error ? err.message : String(err) }
6220
+ };
6005
6221
  }
6006
- if (tool2.hooks?.after && !(toolResult2 && typeof toolResult2 === "object" && "error" in toolResult2)) {
6222
+ if (outcome.kind === "returned" && tool2.hooks?.after && !(suppressErrorShapeInspection ? isErrorShapedSafely(outcome.value) : isErrorShaped(outcome.value))) {
6007
6223
  try {
6008
- toolResult2 = await tool2.hooks.after(toolResult2, this);
6224
+ outcome = {
6225
+ kind: "returned",
6226
+ value: await tool2.hooks.after(outcome.value, this)
6227
+ };
6009
6228
  } catch (err) {
6010
- toolResult2 = {
6011
- error: `After hook error: ${err instanceof Error ? err.message : String(err)}`
6229
+ outcome = {
6230
+ kind: "thrown",
6231
+ value: {
6232
+ error: `After hook error: ${err instanceof Error ? err.message : String(err)}`
6233
+ }
6012
6234
  };
6013
6235
  }
6014
6236
  }
6015
- resultContent2 = tool2.sensitive ? "[REDACTED - sensitive tool output]" : JSON.stringify(toolResult2);
6237
+ if (tool2.sensitive) {
6238
+ resultContent2 = "[REDACTED - sensitive tool output]";
6239
+ } else if (outcome.kind === "thrown" || tool2.toModelOutput === void 0) {
6240
+ resultContent2 = JSON.stringify(outcome.value);
6241
+ }
6016
6242
  } else {
6017
- toolResult2 = void 0;
6243
+ outcome = { kind: "returned", value: void 0 };
6018
6244
  resultContent2 = "Tool execution error";
6019
6245
  }
6020
- return { toolResult: toolResult2, resultContent: resultContent2 };
6246
+ return { outcome, resultContent: resultContent2 };
6021
6247
  };
6022
6248
  const traceName = isMcpTool && this.mcpManager ? this.mcpManager.getQualifiedName(toolName) ?? toolName : toolName;
6023
- const { toolResult, resultContent } = this.spanManager ? await this.spanManager.withSpanAsync(
6249
+ const execution = this.spanManager ? await this.spanManager.withSpanAsync(
6024
6250
  "axl.tool.call",
6025
6251
  {
6026
6252
  "axl.tool.name": traceName,
@@ -6029,22 +6255,27 @@ ${appendedSchemaText}`;
6029
6255
  async (span) => {
6030
6256
  const r = await executeTool();
6031
6257
  span.setAttribute("axl.tool.duration", Date.now() - toolStart);
6032
- const isError = r.toolResult && typeof r.toolResult === "object" && "error" in r.toolResult;
6033
- span.setAttribute("axl.tool.success", !isError);
6034
- if (isError)
6035
- span.setStatus(
6036
- "error",
6037
- r.toolResult.error
6038
- );
6258
+ recordToolSpanResult(span, r.outcome.value, suppressErrorShapeInspection);
6039
6259
  return r;
6040
6260
  }
6041
6261
  ) : await executeTool();
6042
- this.emitEvent({
6043
- type: "tool_call_end",
6044
- agent: agent2._name,
6045
- tool: traceName,
6046
- duration: Date.now() - toolStart,
6047
- data: { args: toolArgs, result: toolResult, callId: toolCall.id }
6262
+ const toolResult = execution.outcome.value;
6263
+ const toolDuration = Date.now() - toolStart;
6264
+ const resultContent = finalizeToolResult({
6265
+ toolName,
6266
+ configuredTool: tool2,
6267
+ outcome: execution.outcome,
6268
+ legacyContent: () => execution.resultContent,
6269
+ emitEnd: () => {
6270
+ this.emitEvent({
6271
+ type: "tool_call_end",
6272
+ agent: agent2._name,
6273
+ tool: traceName,
6274
+ duration: toolDuration,
6275
+ data: { args: toolArgs, result: toolResult, callId: toolCall.id }
6276
+ });
6277
+ },
6278
+ beforeProjection: () => this.currentSignal?.throwIfAborted()
6048
6279
  });
6049
6280
  currentMessages.push({
6050
6281
  role: "tool",
@@ -11908,6 +12139,7 @@ export {
11908
12139
  ThinkTagScanner,
11909
12140
  TimeoutError,
11910
12141
  ToolDenied,
12142
+ ToolModelOutputError,
11911
12143
  VLLM_PROFILE,
11912
12144
  ValidationError,
11913
12145
  VerifyError,