@cognipeer/agent-sdk 0.8.10 → 0.8.12

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
@@ -2761,6 +2761,40 @@ declare function digestToolInputArguments(argumentsJson: string, options?: ToolI
2761
2761
  digestedPaths: string[];
2762
2762
  reclaimedChars: number;
2763
2763
  };
2764
+ /**
2765
+ * Parse tool arguments against the tool's schema.
2766
+ *
2767
+ * Two passes, and the order is the contract: the raw arguments are validated
2768
+ * FIRST, so a model that emits well-typed arguments is unaffected and the schema
2769
+ * stays a real constraint. Only when that fails are the arguments run through
2770
+ * `coerceToolArgs` and re-validated — repairing the type artifacts smaller and
2771
+ * grammar-constrained backends produce (a nested object sent as a JSON string, a
2772
+ * number sent as `"60"`, `""` standing in for an omitted optional) instead of
2773
+ * spending a turn telling the model something it did not get wrong.
2774
+ *
2775
+ * Coercion never fabricates a value, so a genuinely missing required argument
2776
+ * still fails — and it fails with the ORIGINAL issues plus the shape the tool
2777
+ * actually wants, because "expected object, received string" on its own does not
2778
+ * tell a weaker model which key to fix.
2779
+ */
2780
+ declare function validateToolArgs(tool: ToolInterface<any, any, any>, args: unknown): {
2781
+ ok: true;
2782
+ value: any;
2783
+ coerced?: boolean;
2784
+ } | {
2785
+ ok: false;
2786
+ message: string;
2787
+ };
2788
+
2789
+ /**
2790
+ * Re-type `value` so it satisfies `schema`, walking both together.
2791
+ *
2792
+ * Returns the original value untouched whenever nothing needs repairing or
2793
+ * nothing sensible can be done — this must never throw, because it runs on the
2794
+ * error path and a throw here would replace a useful validation message with a
2795
+ * crash.
2796
+ */
2797
+ declare function coerceToolArgs(schema: unknown, value: unknown): unknown;
2764
2798
 
2765
2799
  declare function fileSink(path?: string): TraceSinkConfig;
2766
2800
  type CustomSinkArg = ((event: TraceEventRecord) => void | Promise<void>) | {
@@ -3301,4 +3335,4 @@ declare function fromNativeProvider(provider: BaseProvider, options?: NativeMode
3301
3335
  */
3302
3336
  declare function createProvider(config: ProviderConfig): BaseProvider;
3303
3337
 
3304
- export { type AIMessage, ASK_USER_TOOL_NAME, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, AnthropicProvider, type AnthropicProviderConfig, type AudioContent, AzureProvider, type AzureProviderConfig, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, BaseProvider, BedrockProvider, type BedrockProviderConfig, type BuildChildConfig, type BuiltInRuntimeProfile, CCRStore, CONTEXT_PILOT_JSON_MARKER_KEY, CONTROL_PLANE_TOOL_NAMES, type CancellationTokenLike, type CancelledEvent, type ChatCompletionChunk, type ChatCompletionRequest, type ChatCompletionResponse, type ChildContextPolicy, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type CompressToolOutputParams, type ContextPilotCCRConfig, type ContextPilotCacheAlignmentConfig, type ContextPilotCompressionConfig, type ContextPilotCompressionStats, type ContextPilotCompressorKind, type ContextPilotConfig, type ContextPilotDedupConfig, type ContextPilotDiffCompressionConfig, type ContextPilotJsonCompressionConfig, type ContextPilotLogCompressionConfig, type ContextPilotResult, type ContextPilotRuntime, type ContextPilotSearchCompressionConfig, type ContextPilotTextCompressionConfig, type ContextPolicy, type ContextToolsStateRef, type ConversationGuardrail, type CustomRuleCallback, type CustomRuleOptions, DEFAULT_MAX_TOOL_INPUT_FIELD_CHARS, DEFAULT_PROFILE_CONFIGS, DEFAULT_SKILL_POLICY, DEFAULT_SUBAGENT_POLICY, DEFAULT_SUBAGENT_TOOL_NAMES, DEFAULT_TOOL_INPUT_DIGEST_HEAD_CHARS, DELEGATION_TOOL_NAMES, DedupTracker, type DelegationEventStamp, type DelegationMode, type EvalCase, type EvalCaseResult, type EvalFamily, type EvalHarnessMetrics, type EvalHarnessParams, type EvalHarnessResult, type EvalProfileDescriptor, type EvalProfileTarget, type FileContent, type FinalAnswerEvent, type FinishReason, type GuardrailContext, type GuardrailDisposition, type GuardrailEvent, type GuardrailIncident, type GuardrailOutcome, GuardrailPhase, type GuardrailRule, type HandoffDescriptor, type HandoffEvent, type HumanInTheLoopAskUserConfig, type HumanInTheLoopOptions, type HumanInTheLoopRuntimeConfig, type ImageContent, InMemoryMemoryStore, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, type LoadSkillsOptions, type MemoryFact, type MemoryProviderKind, type MemoryReadPolicy, type MemoryScope, type MemoryStore, type MemoryWritePolicy, type Message, type MetadataEvent, type ModelCapabilities, NativeJsonSchemaStrategy, type NativeModelOptions, type NativeReasoningConfig, OpenAICompatibleProvider, type OpenAICompatibleProviderConfig, OpenAIProvider, type OpenAIProviderConfig, type PendingToolApproval, type PendingUserQuestion, type PlanEvent, type PlanStepRecord, type PlanningMode, type ProfileConfig, type ProgressEvent, type ProgressUpdate, type PromptHooks, type ProviderConfig, ProviderError, type ToolCall as ProviderToolCall, type ToolDefinition as ProviderToolDefinition, type ProviderType, type ReasoningConfig, type ReasoningLevel, type ReflectionCadence, type ReflectionConfig, type ReflectionEvent, type ReflectionHookContext, type ReflectionRecord, type RegexGuardrailOptions, type RegexRuleOptions, type ReplanPolicy, type ResolvedContextPilotConfig, type ResolvedSmartAgentConfig, type ResolvedTraceConfig, type ResolvedTraceSink, type RestoreSnapshotOptions, type RuntimeProfile, SMALL_TIER_SKILL_POLICY, type SerializableSmartState, type Skill, type SkillDisclosure, type SkillExecutionContext, type SkillFrontmatter, type SkillFs, type SkillModelTier, type SkillPolicy, type SkillRegistryRef, type SkillToolDeps, type SkillToolHeader, type SmartAgentBudgetConfig, type SmartAgentContextConfig, type SmartAgentCustomProfileConfig, type SmartAgentDelegationConfig, type SmartAgentEvent, type SmartAgentInstance, type SmartAgentLimits, type SmartAgentMemoryConfig, type SmartAgentOptions, type SmartAgentPlanningConfig, type SmartAgentSummarizationConfig, type SmartAgentToolResponseConfig, type SmartAgentTracingConfig, type SmartModel, type SmartState, type SmartToolFn, type SnapshotOptions, type SnapshotRuntimeHint, type StreamChunk, type StreamEvent, type StructuredOutputError, type StructuredOutputFieldError, StructuredOutputManager, type StructuredOutputManagerConfig, type StructuredOutputResult, type StructuredOutputStrategy, type StructuredSummary, type SubagentDef, type SubagentEvent, type SubagentMode, type SubagentPendingRecord, type SubagentPolicy, type SubagentRegistryRef, type SubagentResult, type SubagentToolDeps, type SubagentToolNames, type SummarizationEvent, type SummarizationMode, type SummaryFactItem, type SummaryIntegrityCheck, TOOL_INPUT_DIGEST_KEY, type TextContent, type TokenCounter, type TokenUsage, type ToolApprovalEvent, type ToolApprovalResolution, type ToolApprovalStatus, ToolBasedStrategy, type ToolCachePolicy, type ToolCallEvent, type ToolInputDigestOptions, type ToolInputDigestResult, type ToolInputRetentionPolicy, type ToolInterface, type ToolResponseClassification, type ToolResponseRetentionPolicy, type ToolRetentionDeclarations, type ToolRetentionSpec, type ToolRetryPolicy, type TraceDataSection, type TraceErrorRecord, type TraceEventRecord, type TraceMessageSection, type TraceMetadataSection, type TraceSessionConfigSnapshot, type TraceSessionFile, type TraceSessionStatus, type TraceSessionSummary, type TraceSinkCognipeerConfig, type TraceSinkConfig, type TraceSinkCustomConfig, type TraceSinkFileConfig, type TraceSinkHttpConfig, type TraceSinkOtlpConfig, type TraceSinkSnapshot, type TraceSummarySection, type TraceToolCallSection, type TraceToolDetails, type TraceToolResponseSection, type TraceToolResultSection, type TracingConfig, type TracingMode, type UnifiedMessage, type UserQuestionAnswer, type UserQuestionAnswerSet, type UserQuestionEvent, type UserQuestionItem, type UserQuestionOption, type UserQuestionResolution, type UserQuestionStatus, VertexProvider, type VertexProviderConfig, type VolatileContentFinding, type VolatileContentPattern, agentVerdictRule, appendBoundTools, buildSkillHeaderBlock, buildSubagentCatalogBlock, buildSystemPrompt, canOpenSkill, canSpawn, captureSnapshot, codePresenceRule, cognipeerSink, collectToolRetentionDeclarations, composeToolSets, compressDiffOutput, compressJsonOutput, compressLogOutput, compressSearchOutput, compressTextOutput, compressToolOutput, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createAskUserQuestionTool, createBindSkillToolsTool, createCodeGuardrail, createContextPilotRuntime, createContextSummarizeNode, createContextTools, createDelegateTool, createGetToolResponseTool, createGuardrail, createJsonGuardrail, createManageTodoTool, createOpenSkillTool, createParallelTool, createProvider, createRegexGuardrail, createResolverNode, createSearchSkillsTool, createSkillRegistryRef, createSkillTools, createSmartAgent, createSpawnTool, createSubagentRegistryRef, createSubagentTools, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, dedupeToolsByName, defaultTokenCounter, detectTextFormat, detectVolatileContent, digestToolInputArguments, digestToolInputValue, emptyUsage, evaluateGuardrails, extractLatestUserQuery, fileSink, findSubagent, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getModelCapabilities, getNestedValue, getResolvedSmartConfig, getTokenCounter, hasToolResponseRecoveryReference, httpSink, isSmartModel, jsonSchemaRule, loadSkillsFromDisk, normalizeSmartAgentOptions, otlpSink, parseSkillFrontmatter, readMemoryFacts, regexRule, resolveAvailableSkills, resolveAvailableSubagents, resolveInputRetention, resolveMemoryStore, resolveReasoning, resolveStrategy, resolveSubagentTools, resolveSummarizationRetention, resolveToolApprovalState, resolveUserQuestionState, restoreSnapshot, runSmartAgentEvalHarness, scoreItemsByRelevance, searchSkills, seedChildMessages, selectTopIndicesInOrder, setTokenCounter, startStreamingSession, summarizeObject, tokenize, traceSessionToOtlp, validateReasoningConfig, withTools, withinDepth, writeSummaryFactsToMemory };
3338
+ export { type AIMessage, ASK_USER_TOOL_NAME, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, AnthropicProvider, type AnthropicProviderConfig, type AudioContent, AzureProvider, type AzureProviderConfig, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, BaseProvider, BedrockProvider, type BedrockProviderConfig, type BuildChildConfig, type BuiltInRuntimeProfile, CCRStore, CONTEXT_PILOT_JSON_MARKER_KEY, CONTROL_PLANE_TOOL_NAMES, type CancellationTokenLike, type CancelledEvent, type ChatCompletionChunk, type ChatCompletionRequest, type ChatCompletionResponse, type ChildContextPolicy, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type CompressToolOutputParams, type ContextPilotCCRConfig, type ContextPilotCacheAlignmentConfig, type ContextPilotCompressionConfig, type ContextPilotCompressionStats, type ContextPilotCompressorKind, type ContextPilotConfig, type ContextPilotDedupConfig, type ContextPilotDiffCompressionConfig, type ContextPilotJsonCompressionConfig, type ContextPilotLogCompressionConfig, type ContextPilotResult, type ContextPilotRuntime, type ContextPilotSearchCompressionConfig, type ContextPilotTextCompressionConfig, type ContextPolicy, type ContextToolsStateRef, type ConversationGuardrail, type CustomRuleCallback, type CustomRuleOptions, DEFAULT_MAX_TOOL_INPUT_FIELD_CHARS, DEFAULT_PROFILE_CONFIGS, DEFAULT_SKILL_POLICY, DEFAULT_SUBAGENT_POLICY, DEFAULT_SUBAGENT_TOOL_NAMES, DEFAULT_TOOL_INPUT_DIGEST_HEAD_CHARS, DELEGATION_TOOL_NAMES, DedupTracker, type DelegationEventStamp, type DelegationMode, type EvalCase, type EvalCaseResult, type EvalFamily, type EvalHarnessMetrics, type EvalHarnessParams, type EvalHarnessResult, type EvalProfileDescriptor, type EvalProfileTarget, type FileContent, type FinalAnswerEvent, type FinishReason, type GuardrailContext, type GuardrailDisposition, type GuardrailEvent, type GuardrailIncident, type GuardrailOutcome, GuardrailPhase, type GuardrailRule, type HandoffDescriptor, type HandoffEvent, type HumanInTheLoopAskUserConfig, type HumanInTheLoopOptions, type HumanInTheLoopRuntimeConfig, type ImageContent, InMemoryMemoryStore, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, type LoadSkillsOptions, type MemoryFact, type MemoryProviderKind, type MemoryReadPolicy, type MemoryScope, type MemoryStore, type MemoryWritePolicy, type Message, type MetadataEvent, type ModelCapabilities, NativeJsonSchemaStrategy, type NativeModelOptions, type NativeReasoningConfig, OpenAICompatibleProvider, type OpenAICompatibleProviderConfig, OpenAIProvider, type OpenAIProviderConfig, type PendingToolApproval, type PendingUserQuestion, type PlanEvent, type PlanStepRecord, type PlanningMode, type ProfileConfig, type ProgressEvent, type ProgressUpdate, type PromptHooks, type ProviderConfig, ProviderError, type ToolCall as ProviderToolCall, type ToolDefinition as ProviderToolDefinition, type ProviderType, type ReasoningConfig, type ReasoningLevel, type ReflectionCadence, type ReflectionConfig, type ReflectionEvent, type ReflectionHookContext, type ReflectionRecord, type RegexGuardrailOptions, type RegexRuleOptions, type ReplanPolicy, type ResolvedContextPilotConfig, type ResolvedSmartAgentConfig, type ResolvedTraceConfig, type ResolvedTraceSink, type RestoreSnapshotOptions, type RuntimeProfile, SMALL_TIER_SKILL_POLICY, type SerializableSmartState, type Skill, type SkillDisclosure, type SkillExecutionContext, type SkillFrontmatter, type SkillFs, type SkillModelTier, type SkillPolicy, type SkillRegistryRef, type SkillToolDeps, type SkillToolHeader, type SmartAgentBudgetConfig, type SmartAgentContextConfig, type SmartAgentCustomProfileConfig, type SmartAgentDelegationConfig, type SmartAgentEvent, type SmartAgentInstance, type SmartAgentLimits, type SmartAgentMemoryConfig, type SmartAgentOptions, type SmartAgentPlanningConfig, type SmartAgentSummarizationConfig, type SmartAgentToolResponseConfig, type SmartAgentTracingConfig, type SmartModel, type SmartState, type SmartToolFn, type SnapshotOptions, type SnapshotRuntimeHint, type StreamChunk, type StreamEvent, type StructuredOutputError, type StructuredOutputFieldError, StructuredOutputManager, type StructuredOutputManagerConfig, type StructuredOutputResult, type StructuredOutputStrategy, type StructuredSummary, type SubagentDef, type SubagentEvent, type SubagentMode, type SubagentPendingRecord, type SubagentPolicy, type SubagentRegistryRef, type SubagentResult, type SubagentToolDeps, type SubagentToolNames, type SummarizationEvent, type SummarizationMode, type SummaryFactItem, type SummaryIntegrityCheck, TOOL_INPUT_DIGEST_KEY, type TextContent, type TokenCounter, type TokenUsage, type ToolApprovalEvent, type ToolApprovalResolution, type ToolApprovalStatus, ToolBasedStrategy, type ToolCachePolicy, type ToolCallEvent, type ToolInputDigestOptions, type ToolInputDigestResult, type ToolInputRetentionPolicy, type ToolInterface, type ToolResponseClassification, type ToolResponseRetentionPolicy, type ToolRetentionDeclarations, type ToolRetentionSpec, type ToolRetryPolicy, type TraceDataSection, type TraceErrorRecord, type TraceEventRecord, type TraceMessageSection, type TraceMetadataSection, type TraceSessionConfigSnapshot, type TraceSessionFile, type TraceSessionStatus, type TraceSessionSummary, type TraceSinkCognipeerConfig, type TraceSinkConfig, type TraceSinkCustomConfig, type TraceSinkFileConfig, type TraceSinkHttpConfig, type TraceSinkOtlpConfig, type TraceSinkSnapshot, type TraceSummarySection, type TraceToolCallSection, type TraceToolDetails, type TraceToolResponseSection, type TraceToolResultSection, type TracingConfig, type TracingMode, type UnifiedMessage, type UserQuestionAnswer, type UserQuestionAnswerSet, type UserQuestionEvent, type UserQuestionItem, type UserQuestionOption, type UserQuestionResolution, type UserQuestionStatus, VertexProvider, type VertexProviderConfig, type VolatileContentFinding, type VolatileContentPattern, agentVerdictRule, appendBoundTools, buildSkillHeaderBlock, buildSubagentCatalogBlock, buildSystemPrompt, canOpenSkill, canSpawn, captureSnapshot, codePresenceRule, coerceToolArgs, cognipeerSink, collectToolRetentionDeclarations, composeToolSets, compressDiffOutput, compressJsonOutput, compressLogOutput, compressSearchOutput, compressTextOutput, compressToolOutput, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createAskUserQuestionTool, createBindSkillToolsTool, createCodeGuardrail, createContextPilotRuntime, createContextSummarizeNode, createContextTools, createDelegateTool, createGetToolResponseTool, createGuardrail, createJsonGuardrail, createManageTodoTool, createOpenSkillTool, createParallelTool, createProvider, createRegexGuardrail, createResolverNode, createSearchSkillsTool, createSkillRegistryRef, createSkillTools, createSmartAgent, createSpawnTool, createSubagentRegistryRef, createSubagentTools, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, dedupeToolsByName, defaultTokenCounter, detectTextFormat, detectVolatileContent, digestToolInputArguments, digestToolInputValue, emptyUsage, evaluateGuardrails, extractLatestUserQuery, fileSink, findSubagent, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getModelCapabilities, getNestedValue, getResolvedSmartConfig, getTokenCounter, hasToolResponseRecoveryReference, httpSink, isSmartModel, jsonSchemaRule, loadSkillsFromDisk, normalizeSmartAgentOptions, otlpSink, parseSkillFrontmatter, readMemoryFacts, regexRule, resolveAvailableSkills, resolveAvailableSubagents, resolveInputRetention, resolveMemoryStore, resolveReasoning, resolveStrategy, resolveSubagentTools, resolveSummarizationRetention, resolveToolApprovalState, resolveUserQuestionState, restoreSnapshot, runSmartAgentEvalHarness, scoreItemsByRelevance, searchSkills, seedChildMessages, selectTopIndicesInOrder, setTokenCounter, startStreamingSession, summarizeObject, tokenize, traceSessionToOtlp, validateReasoningConfig, validateToolArgs, withTools, withinDepth, writeSummaryFactsToMemory };
package/dist/index.d.ts CHANGED
@@ -2761,6 +2761,40 @@ declare function digestToolInputArguments(argumentsJson: string, options?: ToolI
2761
2761
  digestedPaths: string[];
2762
2762
  reclaimedChars: number;
2763
2763
  };
2764
+ /**
2765
+ * Parse tool arguments against the tool's schema.
2766
+ *
2767
+ * Two passes, and the order is the contract: the raw arguments are validated
2768
+ * FIRST, so a model that emits well-typed arguments is unaffected and the schema
2769
+ * stays a real constraint. Only when that fails are the arguments run through
2770
+ * `coerceToolArgs` and re-validated — repairing the type artifacts smaller and
2771
+ * grammar-constrained backends produce (a nested object sent as a JSON string, a
2772
+ * number sent as `"60"`, `""` standing in for an omitted optional) instead of
2773
+ * spending a turn telling the model something it did not get wrong.
2774
+ *
2775
+ * Coercion never fabricates a value, so a genuinely missing required argument
2776
+ * still fails — and it fails with the ORIGINAL issues plus the shape the tool
2777
+ * actually wants, because "expected object, received string" on its own does not
2778
+ * tell a weaker model which key to fix.
2779
+ */
2780
+ declare function validateToolArgs(tool: ToolInterface<any, any, any>, args: unknown): {
2781
+ ok: true;
2782
+ value: any;
2783
+ coerced?: boolean;
2784
+ } | {
2785
+ ok: false;
2786
+ message: string;
2787
+ };
2788
+
2789
+ /**
2790
+ * Re-type `value` so it satisfies `schema`, walking both together.
2791
+ *
2792
+ * Returns the original value untouched whenever nothing needs repairing or
2793
+ * nothing sensible can be done — this must never throw, because it runs on the
2794
+ * error path and a throw here would replace a useful validation message with a
2795
+ * crash.
2796
+ */
2797
+ declare function coerceToolArgs(schema: unknown, value: unknown): unknown;
2764
2798
 
2765
2799
  declare function fileSink(path?: string): TraceSinkConfig;
2766
2800
  type CustomSinkArg = ((event: TraceEventRecord) => void | Promise<void>) | {
@@ -3301,4 +3335,4 @@ declare function fromNativeProvider(provider: BaseProvider, options?: NativeMode
3301
3335
  */
3302
3336
  declare function createProvider(config: ProviderConfig): BaseProvider;
3303
3337
 
3304
- export { type AIMessage, ASK_USER_TOOL_NAME, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, AnthropicProvider, type AnthropicProviderConfig, type AudioContent, AzureProvider, type AzureProviderConfig, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, BaseProvider, BedrockProvider, type BedrockProviderConfig, type BuildChildConfig, type BuiltInRuntimeProfile, CCRStore, CONTEXT_PILOT_JSON_MARKER_KEY, CONTROL_PLANE_TOOL_NAMES, type CancellationTokenLike, type CancelledEvent, type ChatCompletionChunk, type ChatCompletionRequest, type ChatCompletionResponse, type ChildContextPolicy, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type CompressToolOutputParams, type ContextPilotCCRConfig, type ContextPilotCacheAlignmentConfig, type ContextPilotCompressionConfig, type ContextPilotCompressionStats, type ContextPilotCompressorKind, type ContextPilotConfig, type ContextPilotDedupConfig, type ContextPilotDiffCompressionConfig, type ContextPilotJsonCompressionConfig, type ContextPilotLogCompressionConfig, type ContextPilotResult, type ContextPilotRuntime, type ContextPilotSearchCompressionConfig, type ContextPilotTextCompressionConfig, type ContextPolicy, type ContextToolsStateRef, type ConversationGuardrail, type CustomRuleCallback, type CustomRuleOptions, DEFAULT_MAX_TOOL_INPUT_FIELD_CHARS, DEFAULT_PROFILE_CONFIGS, DEFAULT_SKILL_POLICY, DEFAULT_SUBAGENT_POLICY, DEFAULT_SUBAGENT_TOOL_NAMES, DEFAULT_TOOL_INPUT_DIGEST_HEAD_CHARS, DELEGATION_TOOL_NAMES, DedupTracker, type DelegationEventStamp, type DelegationMode, type EvalCase, type EvalCaseResult, type EvalFamily, type EvalHarnessMetrics, type EvalHarnessParams, type EvalHarnessResult, type EvalProfileDescriptor, type EvalProfileTarget, type FileContent, type FinalAnswerEvent, type FinishReason, type GuardrailContext, type GuardrailDisposition, type GuardrailEvent, type GuardrailIncident, type GuardrailOutcome, GuardrailPhase, type GuardrailRule, type HandoffDescriptor, type HandoffEvent, type HumanInTheLoopAskUserConfig, type HumanInTheLoopOptions, type HumanInTheLoopRuntimeConfig, type ImageContent, InMemoryMemoryStore, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, type LoadSkillsOptions, type MemoryFact, type MemoryProviderKind, type MemoryReadPolicy, type MemoryScope, type MemoryStore, type MemoryWritePolicy, type Message, type MetadataEvent, type ModelCapabilities, NativeJsonSchemaStrategy, type NativeModelOptions, type NativeReasoningConfig, OpenAICompatibleProvider, type OpenAICompatibleProviderConfig, OpenAIProvider, type OpenAIProviderConfig, type PendingToolApproval, type PendingUserQuestion, type PlanEvent, type PlanStepRecord, type PlanningMode, type ProfileConfig, type ProgressEvent, type ProgressUpdate, type PromptHooks, type ProviderConfig, ProviderError, type ToolCall as ProviderToolCall, type ToolDefinition as ProviderToolDefinition, type ProviderType, type ReasoningConfig, type ReasoningLevel, type ReflectionCadence, type ReflectionConfig, type ReflectionEvent, type ReflectionHookContext, type ReflectionRecord, type RegexGuardrailOptions, type RegexRuleOptions, type ReplanPolicy, type ResolvedContextPilotConfig, type ResolvedSmartAgentConfig, type ResolvedTraceConfig, type ResolvedTraceSink, type RestoreSnapshotOptions, type RuntimeProfile, SMALL_TIER_SKILL_POLICY, type SerializableSmartState, type Skill, type SkillDisclosure, type SkillExecutionContext, type SkillFrontmatter, type SkillFs, type SkillModelTier, type SkillPolicy, type SkillRegistryRef, type SkillToolDeps, type SkillToolHeader, type SmartAgentBudgetConfig, type SmartAgentContextConfig, type SmartAgentCustomProfileConfig, type SmartAgentDelegationConfig, type SmartAgentEvent, type SmartAgentInstance, type SmartAgentLimits, type SmartAgentMemoryConfig, type SmartAgentOptions, type SmartAgentPlanningConfig, type SmartAgentSummarizationConfig, type SmartAgentToolResponseConfig, type SmartAgentTracingConfig, type SmartModel, type SmartState, type SmartToolFn, type SnapshotOptions, type SnapshotRuntimeHint, type StreamChunk, type StreamEvent, type StructuredOutputError, type StructuredOutputFieldError, StructuredOutputManager, type StructuredOutputManagerConfig, type StructuredOutputResult, type StructuredOutputStrategy, type StructuredSummary, type SubagentDef, type SubagentEvent, type SubagentMode, type SubagentPendingRecord, type SubagentPolicy, type SubagentRegistryRef, type SubagentResult, type SubagentToolDeps, type SubagentToolNames, type SummarizationEvent, type SummarizationMode, type SummaryFactItem, type SummaryIntegrityCheck, TOOL_INPUT_DIGEST_KEY, type TextContent, type TokenCounter, type TokenUsage, type ToolApprovalEvent, type ToolApprovalResolution, type ToolApprovalStatus, ToolBasedStrategy, type ToolCachePolicy, type ToolCallEvent, type ToolInputDigestOptions, type ToolInputDigestResult, type ToolInputRetentionPolicy, type ToolInterface, type ToolResponseClassification, type ToolResponseRetentionPolicy, type ToolRetentionDeclarations, type ToolRetentionSpec, type ToolRetryPolicy, type TraceDataSection, type TraceErrorRecord, type TraceEventRecord, type TraceMessageSection, type TraceMetadataSection, type TraceSessionConfigSnapshot, type TraceSessionFile, type TraceSessionStatus, type TraceSessionSummary, type TraceSinkCognipeerConfig, type TraceSinkConfig, type TraceSinkCustomConfig, type TraceSinkFileConfig, type TraceSinkHttpConfig, type TraceSinkOtlpConfig, type TraceSinkSnapshot, type TraceSummarySection, type TraceToolCallSection, type TraceToolDetails, type TraceToolResponseSection, type TraceToolResultSection, type TracingConfig, type TracingMode, type UnifiedMessage, type UserQuestionAnswer, type UserQuestionAnswerSet, type UserQuestionEvent, type UserQuestionItem, type UserQuestionOption, type UserQuestionResolution, type UserQuestionStatus, VertexProvider, type VertexProviderConfig, type VolatileContentFinding, type VolatileContentPattern, agentVerdictRule, appendBoundTools, buildSkillHeaderBlock, buildSubagentCatalogBlock, buildSystemPrompt, canOpenSkill, canSpawn, captureSnapshot, codePresenceRule, cognipeerSink, collectToolRetentionDeclarations, composeToolSets, compressDiffOutput, compressJsonOutput, compressLogOutput, compressSearchOutput, compressTextOutput, compressToolOutput, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createAskUserQuestionTool, createBindSkillToolsTool, createCodeGuardrail, createContextPilotRuntime, createContextSummarizeNode, createContextTools, createDelegateTool, createGetToolResponseTool, createGuardrail, createJsonGuardrail, createManageTodoTool, createOpenSkillTool, createParallelTool, createProvider, createRegexGuardrail, createResolverNode, createSearchSkillsTool, createSkillRegistryRef, createSkillTools, createSmartAgent, createSpawnTool, createSubagentRegistryRef, createSubagentTools, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, dedupeToolsByName, defaultTokenCounter, detectTextFormat, detectVolatileContent, digestToolInputArguments, digestToolInputValue, emptyUsage, evaluateGuardrails, extractLatestUserQuery, fileSink, findSubagent, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getModelCapabilities, getNestedValue, getResolvedSmartConfig, getTokenCounter, hasToolResponseRecoveryReference, httpSink, isSmartModel, jsonSchemaRule, loadSkillsFromDisk, normalizeSmartAgentOptions, otlpSink, parseSkillFrontmatter, readMemoryFacts, regexRule, resolveAvailableSkills, resolveAvailableSubagents, resolveInputRetention, resolveMemoryStore, resolveReasoning, resolveStrategy, resolveSubagentTools, resolveSummarizationRetention, resolveToolApprovalState, resolveUserQuestionState, restoreSnapshot, runSmartAgentEvalHarness, scoreItemsByRelevance, searchSkills, seedChildMessages, selectTopIndicesInOrder, setTokenCounter, startStreamingSession, summarizeObject, tokenize, traceSessionToOtlp, validateReasoningConfig, withTools, withinDepth, writeSummaryFactsToMemory };
3338
+ export { type AIMessage, ASK_USER_TOOL_NAME, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, AnthropicProvider, type AnthropicProviderConfig, type AudioContent, AzureProvider, type AzureProviderConfig, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, BaseProvider, BedrockProvider, type BedrockProviderConfig, type BuildChildConfig, type BuiltInRuntimeProfile, CCRStore, CONTEXT_PILOT_JSON_MARKER_KEY, CONTROL_PLANE_TOOL_NAMES, type CancellationTokenLike, type CancelledEvent, type ChatCompletionChunk, type ChatCompletionRequest, type ChatCompletionResponse, type ChildContextPolicy, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type CompressToolOutputParams, type ContextPilotCCRConfig, type ContextPilotCacheAlignmentConfig, type ContextPilotCompressionConfig, type ContextPilotCompressionStats, type ContextPilotCompressorKind, type ContextPilotConfig, type ContextPilotDedupConfig, type ContextPilotDiffCompressionConfig, type ContextPilotJsonCompressionConfig, type ContextPilotLogCompressionConfig, type ContextPilotResult, type ContextPilotRuntime, type ContextPilotSearchCompressionConfig, type ContextPilotTextCompressionConfig, type ContextPolicy, type ContextToolsStateRef, type ConversationGuardrail, type CustomRuleCallback, type CustomRuleOptions, DEFAULT_MAX_TOOL_INPUT_FIELD_CHARS, DEFAULT_PROFILE_CONFIGS, DEFAULT_SKILL_POLICY, DEFAULT_SUBAGENT_POLICY, DEFAULT_SUBAGENT_TOOL_NAMES, DEFAULT_TOOL_INPUT_DIGEST_HEAD_CHARS, DELEGATION_TOOL_NAMES, DedupTracker, type DelegationEventStamp, type DelegationMode, type EvalCase, type EvalCaseResult, type EvalFamily, type EvalHarnessMetrics, type EvalHarnessParams, type EvalHarnessResult, type EvalProfileDescriptor, type EvalProfileTarget, type FileContent, type FinalAnswerEvent, type FinishReason, type GuardrailContext, type GuardrailDisposition, type GuardrailEvent, type GuardrailIncident, type GuardrailOutcome, GuardrailPhase, type GuardrailRule, type HandoffDescriptor, type HandoffEvent, type HumanInTheLoopAskUserConfig, type HumanInTheLoopOptions, type HumanInTheLoopRuntimeConfig, type ImageContent, InMemoryMemoryStore, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, type LoadSkillsOptions, type MemoryFact, type MemoryProviderKind, type MemoryReadPolicy, type MemoryScope, type MemoryStore, type MemoryWritePolicy, type Message, type MetadataEvent, type ModelCapabilities, NativeJsonSchemaStrategy, type NativeModelOptions, type NativeReasoningConfig, OpenAICompatibleProvider, type OpenAICompatibleProviderConfig, OpenAIProvider, type OpenAIProviderConfig, type PendingToolApproval, type PendingUserQuestion, type PlanEvent, type PlanStepRecord, type PlanningMode, type ProfileConfig, type ProgressEvent, type ProgressUpdate, type PromptHooks, type ProviderConfig, ProviderError, type ToolCall as ProviderToolCall, type ToolDefinition as ProviderToolDefinition, type ProviderType, type ReasoningConfig, type ReasoningLevel, type ReflectionCadence, type ReflectionConfig, type ReflectionEvent, type ReflectionHookContext, type ReflectionRecord, type RegexGuardrailOptions, type RegexRuleOptions, type ReplanPolicy, type ResolvedContextPilotConfig, type ResolvedSmartAgentConfig, type ResolvedTraceConfig, type ResolvedTraceSink, type RestoreSnapshotOptions, type RuntimeProfile, SMALL_TIER_SKILL_POLICY, type SerializableSmartState, type Skill, type SkillDisclosure, type SkillExecutionContext, type SkillFrontmatter, type SkillFs, type SkillModelTier, type SkillPolicy, type SkillRegistryRef, type SkillToolDeps, type SkillToolHeader, type SmartAgentBudgetConfig, type SmartAgentContextConfig, type SmartAgentCustomProfileConfig, type SmartAgentDelegationConfig, type SmartAgentEvent, type SmartAgentInstance, type SmartAgentLimits, type SmartAgentMemoryConfig, type SmartAgentOptions, type SmartAgentPlanningConfig, type SmartAgentSummarizationConfig, type SmartAgentToolResponseConfig, type SmartAgentTracingConfig, type SmartModel, type SmartState, type SmartToolFn, type SnapshotOptions, type SnapshotRuntimeHint, type StreamChunk, type StreamEvent, type StructuredOutputError, type StructuredOutputFieldError, StructuredOutputManager, type StructuredOutputManagerConfig, type StructuredOutputResult, type StructuredOutputStrategy, type StructuredSummary, type SubagentDef, type SubagentEvent, type SubagentMode, type SubagentPendingRecord, type SubagentPolicy, type SubagentRegistryRef, type SubagentResult, type SubagentToolDeps, type SubagentToolNames, type SummarizationEvent, type SummarizationMode, type SummaryFactItem, type SummaryIntegrityCheck, TOOL_INPUT_DIGEST_KEY, type TextContent, type TokenCounter, type TokenUsage, type ToolApprovalEvent, type ToolApprovalResolution, type ToolApprovalStatus, ToolBasedStrategy, type ToolCachePolicy, type ToolCallEvent, type ToolInputDigestOptions, type ToolInputDigestResult, type ToolInputRetentionPolicy, type ToolInterface, type ToolResponseClassification, type ToolResponseRetentionPolicy, type ToolRetentionDeclarations, type ToolRetentionSpec, type ToolRetryPolicy, type TraceDataSection, type TraceErrorRecord, type TraceEventRecord, type TraceMessageSection, type TraceMetadataSection, type TraceSessionConfigSnapshot, type TraceSessionFile, type TraceSessionStatus, type TraceSessionSummary, type TraceSinkCognipeerConfig, type TraceSinkConfig, type TraceSinkCustomConfig, type TraceSinkFileConfig, type TraceSinkHttpConfig, type TraceSinkOtlpConfig, type TraceSinkSnapshot, type TraceSummarySection, type TraceToolCallSection, type TraceToolDetails, type TraceToolResponseSection, type TraceToolResultSection, type TracingConfig, type TracingMode, type UnifiedMessage, type UserQuestionAnswer, type UserQuestionAnswerSet, type UserQuestionEvent, type UserQuestionItem, type UserQuestionOption, type UserQuestionResolution, type UserQuestionStatus, VertexProvider, type VertexProviderConfig, type VolatileContentFinding, type VolatileContentPattern, agentVerdictRule, appendBoundTools, buildSkillHeaderBlock, buildSubagentCatalogBlock, buildSystemPrompt, canOpenSkill, canSpawn, captureSnapshot, codePresenceRule, coerceToolArgs, cognipeerSink, collectToolRetentionDeclarations, composeToolSets, compressDiffOutput, compressJsonOutput, compressLogOutput, compressSearchOutput, compressTextOutput, compressToolOutput, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createAskUserQuestionTool, createBindSkillToolsTool, createCodeGuardrail, createContextPilotRuntime, createContextSummarizeNode, createContextTools, createDelegateTool, createGetToolResponseTool, createGuardrail, createJsonGuardrail, createManageTodoTool, createOpenSkillTool, createParallelTool, createProvider, createRegexGuardrail, createResolverNode, createSearchSkillsTool, createSkillRegistryRef, createSkillTools, createSmartAgent, createSpawnTool, createSubagentRegistryRef, createSubagentTools, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, dedupeToolsByName, defaultTokenCounter, detectTextFormat, detectVolatileContent, digestToolInputArguments, digestToolInputValue, emptyUsage, evaluateGuardrails, extractLatestUserQuery, fileSink, findSubagent, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getModelCapabilities, getNestedValue, getResolvedSmartConfig, getTokenCounter, hasToolResponseRecoveryReference, httpSink, isSmartModel, jsonSchemaRule, loadSkillsFromDisk, normalizeSmartAgentOptions, otlpSink, parseSkillFrontmatter, readMemoryFacts, regexRule, resolveAvailableSkills, resolveAvailableSubagents, resolveInputRetention, resolveMemoryStore, resolveReasoning, resolveStrategy, resolveSubagentTools, resolveSummarizationRetention, resolveToolApprovalState, resolveUserQuestionState, restoreSnapshot, runSmartAgentEvalHarness, scoreItemsByRelevance, searchSkills, seedChildMessages, selectTopIndicesInOrder, setTokenCounter, startStreamingSession, summarizeObject, tokenize, traceSessionToOtlp, validateReasoningConfig, validateToolArgs, withTools, withinDepth, writeSummaryFactsToMemory };
package/dist/index.mjs CHANGED
@@ -2014,6 +2014,177 @@ function extractMessageText2(message) {
2014
2014
  return "";
2015
2015
  }
2016
2016
 
2017
+ // src/smart/toolArgCoercion.ts
2018
+ var PLACEHOLDER_TEXT = /* @__PURE__ */ new Set(["", "null", "undefined", "none", "nil", "n/a", "na"]);
2019
+ var ENVELOPE_KEYS = ["input", "args", "arguments", "params", "parameters", "payload"];
2020
+ function defOf(schema) {
2021
+ const def = schema?._def;
2022
+ return def && typeof def === "object" ? def : null;
2023
+ }
2024
+ function isPlaceholder(value) {
2025
+ return typeof value === "string" && PLACEHOLDER_TEXT.has(value.trim().toLowerCase());
2026
+ }
2027
+ function parseJsonish(value) {
2028
+ const text = value.trim();
2029
+ if (!text.startsWith("{") && !text.startsWith("[")) return { ok: false };
2030
+ try {
2031
+ return { ok: true, value: JSON.parse(text) };
2032
+ } catch {
2033
+ return { ok: false };
2034
+ }
2035
+ }
2036
+ function safeParses(schema, value) {
2037
+ try {
2038
+ return schema.safeParse(value).success === true;
2039
+ } catch {
2040
+ return false;
2041
+ }
2042
+ }
2043
+ function coerceToolArgs(schema, value) {
2044
+ try {
2045
+ return coerceNode(schema, value, 0);
2046
+ } catch {
2047
+ return value;
2048
+ }
2049
+ }
2050
+ function coerceNode(schema, value, depth) {
2051
+ if (depth > 12) return value;
2052
+ const def = defOf(schema);
2053
+ if (!def) return value;
2054
+ switch (def.typeName) {
2055
+ case "ZodOptional":
2056
+ case "ZodNullable": {
2057
+ if (value === void 0 || value === null) return value;
2058
+ if (isPlaceholder(value)) return void 0;
2059
+ return coerceNode(def.innerType, value, depth + 1);
2060
+ }
2061
+ case "ZodDefault":
2062
+ case "ZodCatch":
2063
+ case "ZodReadonly":
2064
+ case "ZodBranded":
2065
+ return coerceNode(def.innerType, value, depth + 1);
2066
+ case "ZodEffects":
2067
+ return coerceNode(def.schema, value, depth + 1);
2068
+ case "ZodPipeline":
2069
+ return coerceNode(def.in, value, depth + 1);
2070
+ case "ZodLazy":
2071
+ return coerceNode(def.getter(), value, depth + 1);
2072
+ case "ZodObject":
2073
+ return coerceObject(def, value, depth);
2074
+ case "ZodRecord": {
2075
+ const unwrapped = unwrapJsonString(value);
2076
+ if (!unwrapped || typeof unwrapped !== "object" || Array.isArray(unwrapped)) return unwrapped ?? value;
2077
+ const out = {};
2078
+ for (const [key, entry] of Object.entries(unwrapped)) {
2079
+ out[key] = def.valueType ? coerceNode(def.valueType, entry, depth + 1) : entry;
2080
+ }
2081
+ return out;
2082
+ }
2083
+ case "ZodArray": {
2084
+ const unwrapped = unwrapJsonString(value);
2085
+ const items = Array.isArray(unwrapped) ? unwrapped : unwrapped === void 0 || unwrapped === null ? unwrapped : [unwrapped];
2086
+ if (!Array.isArray(items)) return items;
2087
+ return items.map((item) => coerceNode(def.type, item, depth + 1));
2088
+ }
2089
+ case "ZodTuple": {
2090
+ const unwrapped = unwrapJsonString(value);
2091
+ if (!Array.isArray(unwrapped)) return unwrapped ?? value;
2092
+ const items = def.items ?? [];
2093
+ return unwrapped.map((item, index) => items[index] ? coerceNode(items[index], item, depth + 1) : item);
2094
+ }
2095
+ case "ZodNumber": {
2096
+ if (typeof value === "number") return value;
2097
+ if (typeof value === "string" && value.trim() !== "") {
2098
+ const parsed = Number(value.trim());
2099
+ if (Number.isFinite(parsed)) return parsed;
2100
+ }
2101
+ if (typeof value === "boolean") return value ? 1 : 0;
2102
+ return value;
2103
+ }
2104
+ case "ZodBoolean": {
2105
+ if (typeof value === "boolean") return value;
2106
+ if (typeof value === "string") {
2107
+ const text = value.trim().toLowerCase();
2108
+ if (text === "true" || text === "yes" || text === "1") return true;
2109
+ if (text === "false" || text === "no" || text === "0") return false;
2110
+ }
2111
+ if (value === 1) return true;
2112
+ if (value === 0) return false;
2113
+ return value;
2114
+ }
2115
+ case "ZodString": {
2116
+ if (typeof value === "string") return value;
2117
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
2118
+ if (value && typeof value === "object") {
2119
+ try {
2120
+ return JSON.stringify(value);
2121
+ } catch {
2122
+ return value;
2123
+ }
2124
+ }
2125
+ return value;
2126
+ }
2127
+ case "ZodEnum": {
2128
+ if (typeof value !== "string") return value;
2129
+ const values = def.values ?? [];
2130
+ if (values.includes(value)) return value;
2131
+ const match = values.find((option) => option.toLowerCase() === value.trim().toLowerCase());
2132
+ return match ?? value;
2133
+ }
2134
+ case "ZodNativeEnum": {
2135
+ if (typeof value !== "string") return value;
2136
+ const values = Object.values(def.values ?? {}).filter((option) => typeof option === "string");
2137
+ if (values.includes(value)) return value;
2138
+ return values.find((option) => option.toLowerCase() === value.trim().toLowerCase()) ?? value;
2139
+ }
2140
+ case "ZodUnion":
2141
+ case "ZodDiscriminatedUnion": {
2142
+ const options = def.options ? Array.isArray(def.options) ? def.options : Array.from(def.options.values()) : [];
2143
+ for (const option of options) {
2144
+ const candidate = coerceNode(option, value, depth + 1);
2145
+ if (safeParses(option, candidate)) return candidate;
2146
+ }
2147
+ return value;
2148
+ }
2149
+ default:
2150
+ return value;
2151
+ }
2152
+ }
2153
+ function unwrapJsonString(value) {
2154
+ if (typeof value !== "string") return value;
2155
+ if (isPlaceholder(value)) return void 0;
2156
+ const parsed = parseJsonish(value);
2157
+ return parsed.ok ? parsed.value : value;
2158
+ }
2159
+ function coerceObject(def, value, depth) {
2160
+ const unwrapped = unwrapJsonString(value);
2161
+ if (!unwrapped || typeof unwrapped !== "object" || Array.isArray(unwrapped)) return unwrapped ?? value;
2162
+ const shape = typeof def.shape === "function" ? def.shape() : def.shape ?? {};
2163
+ const shapeKeys = Object.keys(shape);
2164
+ let source = unwrapped;
2165
+ if (depth === 0 && shapeKeys.length > 0) {
2166
+ const keys = Object.keys(source);
2167
+ if (keys.length === 1 && !shapeKeys.includes(keys[0]) && ENVELOPE_KEYS.includes(keys[0].toLowerCase())) {
2168
+ const inner = unwrapJsonString(source[keys[0]]);
2169
+ if (inner && typeof inner === "object" && !Array.isArray(inner)) {
2170
+ source = inner;
2171
+ }
2172
+ }
2173
+ }
2174
+ const out = {};
2175
+ for (const [key, entry] of Object.entries(source)) {
2176
+ const field = shape[key];
2177
+ if (!field) {
2178
+ out[key] = entry;
2179
+ continue;
2180
+ }
2181
+ const coerced = coerceNode(field, entry, depth + 1);
2182
+ if (coerced === void 0) continue;
2183
+ out[key] = coerced;
2184
+ }
2185
+ return out;
2186
+ }
2187
+
2017
2188
  // src/smart/toolResponses.ts
2018
2189
  var CONTROL_PLANE_TOOL_NAMES = [
2019
2190
  "response",
@@ -2216,17 +2387,60 @@ Use get_tool_response with executionId "${refId}" only if you must recover the o
2216
2387
  }
2217
2388
  function validateToolArgs(tool, args) {
2218
2389
  const schema = tool.schema;
2219
- if (!schema || typeof schema.parse !== "function") {
2390
+ if (!schema || typeof schema.safeParse !== "function") {
2220
2391
  return { ok: true, value: args };
2221
2392
  }
2222
- try {
2223
- return { ok: true, value: schema.parse(args) };
2224
- } catch (error) {
2225
- if (error instanceof ZodError) {
2226
- const message = error.issues.map((issue) => `${issue.path.join(".") || "root"}: ${issue.message}`).join("; ");
2227
- return { ok: false, message };
2228
- }
2229
- return { ok: false, message: error instanceof Error ? error.message : String(error) };
2393
+ const direct = schema.safeParse(args);
2394
+ if (direct.success) {
2395
+ return { ok: true, value: direct.data };
2396
+ }
2397
+ const repaired = schema.safeParse(coerceToolArgs(schema, args));
2398
+ if (repaired.success) {
2399
+ return { ok: true, value: repaired.data, coerced: true };
2400
+ }
2401
+ const error = direct.error;
2402
+ if (error instanceof ZodError) {
2403
+ const issues = error.issues.map((issue) => `${issue.path.join(".") || "root"}: ${issue.message}`).join("; ");
2404
+ const expected = describeExpectedArgs(schema);
2405
+ return { ok: false, message: expected ? `${issues}. Expected arguments: ${expected}` : issues };
2406
+ }
2407
+ return { ok: false, message: error instanceof Error ? error.message : String(error) };
2408
+ }
2409
+ function describeExpectedArgs(schema) {
2410
+ const shape = typeof schema?._def?.shape === "function" ? schema._def.shape() : schema?._def?.shape;
2411
+ if (!shape || typeof shape !== "object") return null;
2412
+ const parts = Object.entries(shape).map(([key, field]) => {
2413
+ const { typeName, optional } = describeField(field);
2414
+ return `${key}${optional ? "?" : ""}: ${typeName}`;
2415
+ });
2416
+ return parts.length > 0 ? parts.join(", ") : null;
2417
+ }
2418
+ function describeField(field, depth = 0) {
2419
+ const def = field?._def;
2420
+ if (!def || depth > 6) return { typeName: "value", optional: false };
2421
+ switch (def.typeName) {
2422
+ case "ZodOptional":
2423
+ case "ZodNullable":
2424
+ case "ZodDefault":
2425
+ return { typeName: describeField(def.innerType, depth + 1).typeName, optional: true };
2426
+ case "ZodEffects":
2427
+ return { ...describeField(def.schema, depth + 1), optional: describeField(def.schema, depth + 1).optional };
2428
+ case "ZodObject":
2429
+ return { typeName: "object", optional: false };
2430
+ case "ZodArray":
2431
+ return { typeName: `array of ${describeField(def.type, depth + 1).typeName}`, optional: false };
2432
+ case "ZodRecord":
2433
+ return { typeName: "object", optional: false };
2434
+ case "ZodString":
2435
+ return { typeName: "string", optional: false };
2436
+ case "ZodNumber":
2437
+ return { typeName: "number", optional: false };
2438
+ case "ZodBoolean":
2439
+ return { typeName: "boolean", optional: false };
2440
+ case "ZodEnum":
2441
+ return { typeName: `one of ${(def.values ?? []).join("|")}`, optional: false };
2442
+ default:
2443
+ return { typeName: "value", optional: false };
2230
2444
  }
2231
2445
  }
2232
2446
 
@@ -5085,7 +5299,10 @@ function shouldSignalSummarization(state, threshold) {
5085
5299
  });
5086
5300
  const tokenCount = countMessagesTokens(tokCountMessages);
5087
5301
  if (tokenCount <= threshold) return "skip";
5088
- if (state.ctx?.__summarizationExhausted) return "skip";
5302
+ if (state.ctx?.__summarizationExhausted) {
5303
+ const exhaustedAt = state.ctx?.__summarizationExhaustedAtToolCount;
5304
+ if (typeof exhaustedAt !== "number" || (state.toolHistory || []).length <= exhaustedAt) return "skip";
5305
+ }
5089
5306
  const hasFreshSummary = (state.messages || []).some(
5090
5307
  (m) => m.role === "tool" && typeof m.content === "string" && (m.content === "SUMMARIZED" || m.content.startsWith("SUMMARIZED_TOOL_RESPONSE"))
5091
5308
  );
@@ -6130,6 +6347,20 @@ function extractCanonicalFacts(messages) {
6130
6347
  function isSummarizedToolPlaceholder(content) {
6131
6348
  return typeof content === "string" && (content === "SUMMARIZED" || content.startsWith("SUMMARIZED_TOOL_RESPONSE") || content.startsWith("ARCHIVED_TOOL_RESPONSE") || content.startsWith("STRUCTURED_TOOL_RESPONSE") || content.startsWith("DROPPED_TOOL_RESPONSE"));
6132
6349
  }
6350
+ function collectLatestTurnToolCallIds(messages) {
6351
+ const ids = /* @__PURE__ */ new Set();
6352
+ for (let i = messages.length - 1; i >= 0; i--) {
6353
+ const m = messages[i];
6354
+ if (isSyntheticSummaryMessage(m)) continue;
6355
+ if (m.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
6356
+ for (const tc of m.tool_calls) {
6357
+ if (tc.id) ids.add(tc.id);
6358
+ }
6359
+ break;
6360
+ }
6361
+ }
6362
+ return ids;
6363
+ }
6133
6364
  function findToolHistoryEntry(state, toolCallId, toolName) {
6134
6365
  const entries = [
6135
6366
  ...state.toolHistory || [],
@@ -6224,6 +6455,10 @@ function createContextSummarizeNode(opts) {
6224
6455
  if (compressableMessages.length === 0) {
6225
6456
  return {};
6226
6457
  }
6458
+ const protectedToolCallIds = collectLatestTurnToolCallIds(messages);
6459
+ if (compressableMessages.every((m) => m.tool_call_id && protectedToolCallIds.has(m.tool_call_id))) {
6460
+ return {};
6461
+ }
6227
6462
  const tokenCountBefore = countMessagesTokens(messages);
6228
6463
  const summaryPromptMaxTokens = config.summaryPromptMaxTokens;
6229
6464
  const availableTokensForConversation = summaryPromptMaxTokens - 500;
@@ -6243,7 +6478,8 @@ function createContextSummarizeNode(opts) {
6243
6478
  const historyEntry = findToolHistoryEntry(state, m.tool_call_id, m.name);
6244
6479
  if (historyEntry) {
6245
6480
  const original = historyEntry.rawOutput ?? historyEntry.output;
6246
- content = typeof original === "string" ? original : JSON.stringify(original);
6481
+ const recovered = typeof original === "string" ? original : JSON.stringify(original);
6482
+ if (typeof recovered === "string") content = recovered;
6247
6483
  }
6248
6484
  }
6249
6485
  const maxContentLength = 2e3;
@@ -6382,22 +6618,6 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
6382
6618
  });
6383
6619
  }
6384
6620
  });
6385
- const protectedToolCallIds = /* @__PURE__ */ new Set();
6386
- for (let i = messages.length - 1; i >= 0; i--) {
6387
- const m = messages[i];
6388
- if (m.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
6389
- const thisToolCallIds = new Set(m.tool_calls.map((tc) => tc.id).filter(Boolean));
6390
- const otherCompressable = compressableMessages.filter(
6391
- (cm) => !thisToolCallIds.has(cm.tool_call_id)
6392
- );
6393
- if (otherCompressable.length > 0) {
6394
- for (const tc of m.tool_calls) {
6395
- if (tc.id) protectedToolCallIds.add(tc.id);
6396
- }
6397
- }
6398
- break;
6399
- }
6400
- }
6401
6621
  const retentionDeclarations = collectToolRetentionDeclarations(state.agent?.tools);
6402
6622
  const digestableToolCallIds = /* @__PURE__ */ new Set();
6403
6623
  for (const m of messages) {
@@ -7982,11 +8202,16 @@ function createSmartAgent(opts) {
7982
8202
  if (!summarizer) return { state: currentState, rawMessages: currentRawMessages, compressed: false };
7983
8203
  const delta = await summarizer(currentState);
7984
8204
  if (!delta || Object.keys(delta).length === 0) {
7985
- const ctx2 = { ...currentState.ctx || {}, __summarizationExhausted: true };
8205
+ const ctx2 = {
8206
+ ...currentState.ctx || {},
8207
+ __summarizationExhausted: true,
8208
+ __summarizationExhaustedAtToolCount: (currentState.toolHistory || []).length
8209
+ };
7986
8210
  return { state: { ...currentState, ctx: ctx2 }, rawMessages: currentRawMessages, compressed: false };
7987
8211
  }
7988
8212
  const ctx = { ...currentState.ctx || {} };
7989
8213
  delete ctx.__summarizationExhausted;
8214
+ delete ctx.__summarizationExhaustedAtToolCount;
7990
8215
  const updated = await persistLatestSummary(syncPlanStateWith(ref, { ...currentState, ...delta, ctx }));
7991
8216
  return { state: updated, rawMessages: [...updated.messages || currentRawMessages], compressed: true };
7992
8217
  }
@@ -11049,6 +11274,43 @@ function convertToJsonSchema(schema, strict = false) {
11049
11274
  }
11050
11275
  return converted;
11051
11276
  }
11277
+ function simplifyOptionalNullableUnions(schema, required = null) {
11278
+ if (!schema || typeof schema !== "object") return schema;
11279
+ const clone2 = { ...schema };
11280
+ if (clone2.properties && typeof clone2.properties === "object") {
11281
+ const requiredKeys = new Set(Array.isArray(clone2.required) ? clone2.required : []);
11282
+ const properties = {};
11283
+ for (const [key, value] of Object.entries(clone2.properties)) {
11284
+ const child = simplifyOptionalNullableUnions(value, requiredKeys);
11285
+ properties[key] = requiredKeys.has(key) ? child : dropNullBranch(child);
11286
+ }
11287
+ clone2.properties = properties;
11288
+ }
11289
+ if (clone2.items) clone2.items = simplifyOptionalNullableUnions(clone2.items, required);
11290
+ for (const key of ["anyOf", "oneOf", "allOf"]) {
11291
+ if (Array.isArray(clone2[key])) {
11292
+ clone2[key] = clone2[key].map((entry) => simplifyOptionalNullableUnions(entry, required));
11293
+ }
11294
+ }
11295
+ return clone2;
11296
+ }
11297
+ function dropNullBranch(schema) {
11298
+ if (!schema || typeof schema !== "object") return schema;
11299
+ if (Array.isArray(schema.type) && schema.type.includes("null") && schema.type.length === 2) {
11300
+ return { ...schema, type: schema.type.find((entry) => entry !== "null") };
11301
+ }
11302
+ if (Array.isArray(schema.anyOf)) {
11303
+ const branches = schema.anyOf.filter((entry) => entry?.type !== "null");
11304
+ if (branches.length === 1 && branches.length !== schema.anyOf.length) {
11305
+ const { anyOf, ...rest } = schema;
11306
+ return { ...branches[0], ...rest };
11307
+ }
11308
+ if (branches.length !== schema.anyOf.length && branches.length > 1) {
11309
+ return { ...schema, anyOf: branches };
11310
+ }
11311
+ }
11312
+ return schema;
11313
+ }
11052
11314
  function normalizeStrictSchema(schema) {
11053
11315
  if (!schema || typeof schema !== "object") return schema;
11054
11316
  const clone2 = { ...schema };
@@ -11113,6 +11375,8 @@ function toToolDefinition(tool, strict) {
11113
11375
  parameters = convertToJsonSchema(rawSchema, useStrict);
11114
11376
  if (useStrict) {
11115
11377
  parameters = normalizeStrictSchema(parameters);
11378
+ } else {
11379
+ parameters = simplifyOptionalNullableUnions(parameters);
11116
11380
  }
11117
11381
  return { name, description, parameters, ...useStrict ? { strict: true } : {} };
11118
11382
  }
@@ -11249,6 +11513,6 @@ function createProvider(config) {
11249
11513
  }
11250
11514
  }
11251
11515
 
11252
- export { ASK_USER_TOOL_NAME, AnthropicProvider, AzureProvider, BaseProvider, BedrockProvider, CCRStore, CONTEXT_PILOT_JSON_MARKER_KEY, CONTROL_PLANE_TOOL_NAMES, DEFAULT_MAX_TOOL_INPUT_FIELD_CHARS, DEFAULT_PROFILE_CONFIGS, DEFAULT_SKILL_POLICY, DEFAULT_SUBAGENT_POLICY, DEFAULT_SUBAGENT_TOOL_NAMES, DEFAULT_TOOL_INPUT_DIGEST_HEAD_CHARS, DELEGATION_TOOL_NAMES, DedupTracker, GuardrailPhase, InMemoryMemoryStore, NativeJsonSchemaStrategy, OpenAICompatibleProvider, OpenAIProvider, ProviderError, SMALL_TIER_SKILL_POLICY, StructuredOutputManager, TOOL_INPUT_DIGEST_KEY, ToolBasedStrategy, VertexProvider, agentVerdictRule, appendBoundTools, buildSkillHeaderBlock, buildSubagentCatalogBlock, buildSystemPrompt, canOpenSkill, canSpawn, captureSnapshot, codePresenceRule, cognipeerSink, collectToolRetentionDeclarations, composeToolSets, compressDiffOutput, compressJsonOutput, compressLogOutput, compressSearchOutput, compressTextOutput, compressToolOutput, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createAskUserQuestionTool, createBindSkillToolsTool, createCodeGuardrail, createContextPilotRuntime, createContextSummarizeNode, createContextTools, createDelegateTool, createGetToolResponseTool, createGuardrail, createJsonGuardrail, createManageTodoTool, createOpenSkillTool, createParallelTool, createProvider, createRegexGuardrail, createResolverNode, createSearchSkillsTool, createSkillRegistryRef, createSkillTools, createSmartAgent, createSpawnTool, createSubagentRegistryRef, createSubagentTools, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, dedupeToolsByName, defaultTokenCounter, detectTextFormat, detectVolatileContent, digestToolInputArguments, digestToolInputValue, emptyUsage, evaluateGuardrails, extractLatestUserQuery, fileSink, findSubagent, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getModelCapabilities, getNestedValue, getResolvedSmartConfig, getTokenCounter, hasToolResponseRecoveryReference, httpSink, isSmartModel, jsonSchemaRule, loadSkillsFromDisk, normalizeSmartAgentOptions, otlpSink, parseSkillFrontmatter, readMemoryFacts, regexRule, resolveAvailableSkills, resolveAvailableSubagents, resolveInputRetention, resolveMemoryStore, resolveReasoning, resolveStrategy, resolveSubagentTools, resolveSummarizationRetention, resolveToolApprovalState, resolveUserQuestionState, restoreSnapshot, runSmartAgentEvalHarness, scoreItemsByRelevance, searchSkills, seedChildMessages, selectTopIndicesInOrder, setTokenCounter, startStreamingSession, summarizeObject, tokenize, traceSessionToOtlp, validateReasoningConfig, withTools, withinDepth, writeSummaryFactsToMemory };
11516
+ export { ASK_USER_TOOL_NAME, AnthropicProvider, AzureProvider, BaseProvider, BedrockProvider, CCRStore, CONTEXT_PILOT_JSON_MARKER_KEY, CONTROL_PLANE_TOOL_NAMES, DEFAULT_MAX_TOOL_INPUT_FIELD_CHARS, DEFAULT_PROFILE_CONFIGS, DEFAULT_SKILL_POLICY, DEFAULT_SUBAGENT_POLICY, DEFAULT_SUBAGENT_TOOL_NAMES, DEFAULT_TOOL_INPUT_DIGEST_HEAD_CHARS, DELEGATION_TOOL_NAMES, DedupTracker, GuardrailPhase, InMemoryMemoryStore, NativeJsonSchemaStrategy, OpenAICompatibleProvider, OpenAIProvider, ProviderError, SMALL_TIER_SKILL_POLICY, StructuredOutputManager, TOOL_INPUT_DIGEST_KEY, ToolBasedStrategy, VertexProvider, agentVerdictRule, appendBoundTools, buildSkillHeaderBlock, buildSubagentCatalogBlock, buildSystemPrompt, canOpenSkill, canSpawn, captureSnapshot, codePresenceRule, coerceToolArgs, cognipeerSink, collectToolRetentionDeclarations, composeToolSets, compressDiffOutput, compressJsonOutput, compressLogOutput, compressSearchOutput, compressTextOutput, compressToolOutput, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createAskUserQuestionTool, createBindSkillToolsTool, createCodeGuardrail, createContextPilotRuntime, createContextSummarizeNode, createContextTools, createDelegateTool, createGetToolResponseTool, createGuardrail, createJsonGuardrail, createManageTodoTool, createOpenSkillTool, createParallelTool, createProvider, createRegexGuardrail, createResolverNode, createSearchSkillsTool, createSkillRegistryRef, createSkillTools, createSmartAgent, createSpawnTool, createSubagentRegistryRef, createSubagentTools, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, dedupeToolsByName, defaultTokenCounter, detectTextFormat, detectVolatileContent, digestToolInputArguments, digestToolInputValue, emptyUsage, evaluateGuardrails, extractLatestUserQuery, fileSink, findSubagent, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getModelCapabilities, getNestedValue, getResolvedSmartConfig, getTokenCounter, hasToolResponseRecoveryReference, httpSink, isSmartModel, jsonSchemaRule, loadSkillsFromDisk, normalizeSmartAgentOptions, otlpSink, parseSkillFrontmatter, readMemoryFacts, regexRule, resolveAvailableSkills, resolveAvailableSubagents, resolveInputRetention, resolveMemoryStore, resolveReasoning, resolveStrategy, resolveSubagentTools, resolveSummarizationRetention, resolveToolApprovalState, resolveUserQuestionState, restoreSnapshot, runSmartAgentEvalHarness, scoreItemsByRelevance, searchSkills, seedChildMessages, selectTopIndicesInOrder, setTokenCounter, startStreamingSession, summarizeObject, tokenize, traceSessionToOtlp, validateReasoningConfig, validateToolArgs, withTools, withinDepth, writeSummaryFactsToMemory };
11253
11517
  //# sourceMappingURL=index.mjs.map
11254
11518
  //# sourceMappingURL=index.mjs.map