@cognipeer/agent-sdk 0.8.12 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1775,6 +1775,15 @@ type InvokeConfig = RunnableConfig & {
1775
1775
  limits?: Partial<AgentLimits>;
1776
1776
  onStateChange?: (state: SmartState) => boolean;
1777
1777
  checkpointReason?: string;
1778
+ /**
1779
+ * Keys of `skills` to open deterministically at the start of this invoke,
1780
+ * before the first model call. Each one is opened through the real
1781
+ * `open_skill` tool and written into the transcript as an assistant tool call
1782
+ * plus its tool result, so the model starts the run with the skill's guidance
1783
+ * and tools already bound instead of having to discover them. Unknown or
1784
+ * unavailable keys are skipped. Ignored when the agent has no `skills`.
1785
+ */
1786
+ preopenedSkills?: string[];
1778
1787
  };
1779
1788
  type SnapshotRuntimeHint = {
1780
1789
  name?: string;
@@ -2108,6 +2117,56 @@ declare function parseSkillFrontmatter(md: string): SkillFrontmatter;
2108
2117
  */
2109
2118
  declare function loadSkillsFromDisk(opts: LoadSkillsOptions): Promise<Skill[]>;
2110
2119
 
2120
+ /**
2121
+ * Deterministic pre-opening of skills at the start of an invoke.
2122
+ *
2123
+ * Some skills must not depend on the model choosing to discover them — an
2124
+ * organization policy, or the integration a scheduled run is about. Those keys
2125
+ * are passed per-invoke (`InvokeConfig.preopenedSkills`) and opened here BEFORE
2126
+ * the first model call, by invoking the very same `open_skill` tool the model
2127
+ * would have called. The run then continues normally: the skill's tools are
2128
+ * bound in the registry and `bind_skill_tools` can still widen the surface.
2129
+ *
2130
+ * The opening is written into the transcript as a real tool exchange (one
2131
+ * assistant message carrying the tool calls, then one tool message per call),
2132
+ * because that is the shape the model is trained on and the shape the rest of
2133
+ * the runtime — summarization, retention, `get_tool_response` — already
2134
+ * understands. Tool call ids are derived from the skill key rather than random,
2135
+ * so the same preopen set produces a byte-identical prefix on every run and the
2136
+ * provider-side prompt cache keeps hitting.
2137
+ */
2138
+ declare const PREOPEN_TOOL_CALL_PREFIX = "preopen_skill_";
2139
+ type PreopenSkillsResult = {
2140
+ /** Synthetic transcript entries to append after the user message. */
2141
+ messages: BaseMessage[];
2142
+ /** Tool-history rows mirroring the synthetic calls. */
2143
+ toolHistory: NonNullable<AgentState["toolHistory"]>;
2144
+ /** Skill keys actually opened (available, resolved, not already open). */
2145
+ openedKeys: string[];
2146
+ /** Keys that were requested but could not be opened, with the reason. */
2147
+ skipped: Array<{
2148
+ skillKey: string;
2149
+ reason: string;
2150
+ }>;
2151
+ };
2152
+ /** Tool call ids must survive provider id charset rules; skill keys contain ':'. */
2153
+ declare function preopenToolCallId(skillKey: string): string;
2154
+ /**
2155
+ * Open the requested skills through the real `open_skill` tool and return the
2156
+ * transcript + tool-history entries that describe the exchange. Binding side
2157
+ * effects (registry mutation + `__onToolsChanged`) happen inside the tool, so
2158
+ * the caller only has to merge the returned messages/history into its state.
2159
+ */
2160
+ declare function preopenSkills(input: {
2161
+ skillKeys: string[];
2162
+ tools: ToolInterface[];
2163
+ /** Keys already open on the registry — a resumed run must not re-open them. */
2164
+ alreadyOpenedKeys?: string[];
2165
+ /** Existing transcript, used to keep the injection idempotent across resumes. */
2166
+ existingMessages?: BaseMessage[];
2167
+ onEvent?: (event: SmartAgentEvent) => void;
2168
+ }): Promise<PreopenSkillsResult>;
2169
+
2111
2170
  /**
2112
2171
  * Pure registry helpers for the sub-agent primitive. No I/O, no agent loop —
2113
2172
  * the deterministic core, fully unit-testable on its own.
@@ -3335,4 +3394,4 @@ declare function fromNativeProvider(provider: BaseProvider, options?: NativeMode
3335
3394
  */
3336
3395
  declare function createProvider(config: ProviderConfig): BaseProvider;
3337
3396
 
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 };
3397
+ 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, PREOPEN_TOOL_CALL_PREFIX, type PendingToolApproval, type PendingUserQuestion, type PlanEvent, type PlanStepRecord, type PlanningMode, type PreopenSkillsResult, 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, preopenSkills, preopenToolCallId, 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
@@ -1775,6 +1775,15 @@ type InvokeConfig = RunnableConfig & {
1775
1775
  limits?: Partial<AgentLimits>;
1776
1776
  onStateChange?: (state: SmartState) => boolean;
1777
1777
  checkpointReason?: string;
1778
+ /**
1779
+ * Keys of `skills` to open deterministically at the start of this invoke,
1780
+ * before the first model call. Each one is opened through the real
1781
+ * `open_skill` tool and written into the transcript as an assistant tool call
1782
+ * plus its tool result, so the model starts the run with the skill's guidance
1783
+ * and tools already bound instead of having to discover them. Unknown or
1784
+ * unavailable keys are skipped. Ignored when the agent has no `skills`.
1785
+ */
1786
+ preopenedSkills?: string[];
1778
1787
  };
1779
1788
  type SnapshotRuntimeHint = {
1780
1789
  name?: string;
@@ -2108,6 +2117,56 @@ declare function parseSkillFrontmatter(md: string): SkillFrontmatter;
2108
2117
  */
2109
2118
  declare function loadSkillsFromDisk(opts: LoadSkillsOptions): Promise<Skill[]>;
2110
2119
 
2120
+ /**
2121
+ * Deterministic pre-opening of skills at the start of an invoke.
2122
+ *
2123
+ * Some skills must not depend on the model choosing to discover them — an
2124
+ * organization policy, or the integration a scheduled run is about. Those keys
2125
+ * are passed per-invoke (`InvokeConfig.preopenedSkills`) and opened here BEFORE
2126
+ * the first model call, by invoking the very same `open_skill` tool the model
2127
+ * would have called. The run then continues normally: the skill's tools are
2128
+ * bound in the registry and `bind_skill_tools` can still widen the surface.
2129
+ *
2130
+ * The opening is written into the transcript as a real tool exchange (one
2131
+ * assistant message carrying the tool calls, then one tool message per call),
2132
+ * because that is the shape the model is trained on and the shape the rest of
2133
+ * the runtime — summarization, retention, `get_tool_response` — already
2134
+ * understands. Tool call ids are derived from the skill key rather than random,
2135
+ * so the same preopen set produces a byte-identical prefix on every run and the
2136
+ * provider-side prompt cache keeps hitting.
2137
+ */
2138
+ declare const PREOPEN_TOOL_CALL_PREFIX = "preopen_skill_";
2139
+ type PreopenSkillsResult = {
2140
+ /** Synthetic transcript entries to append after the user message. */
2141
+ messages: BaseMessage[];
2142
+ /** Tool-history rows mirroring the synthetic calls. */
2143
+ toolHistory: NonNullable<AgentState["toolHistory"]>;
2144
+ /** Skill keys actually opened (available, resolved, not already open). */
2145
+ openedKeys: string[];
2146
+ /** Keys that were requested but could not be opened, with the reason. */
2147
+ skipped: Array<{
2148
+ skillKey: string;
2149
+ reason: string;
2150
+ }>;
2151
+ };
2152
+ /** Tool call ids must survive provider id charset rules; skill keys contain ':'. */
2153
+ declare function preopenToolCallId(skillKey: string): string;
2154
+ /**
2155
+ * Open the requested skills through the real `open_skill` tool and return the
2156
+ * transcript + tool-history entries that describe the exchange. Binding side
2157
+ * effects (registry mutation + `__onToolsChanged`) happen inside the tool, so
2158
+ * the caller only has to merge the returned messages/history into its state.
2159
+ */
2160
+ declare function preopenSkills(input: {
2161
+ skillKeys: string[];
2162
+ tools: ToolInterface[];
2163
+ /** Keys already open on the registry — a resumed run must not re-open them. */
2164
+ alreadyOpenedKeys?: string[];
2165
+ /** Existing transcript, used to keep the injection idempotent across resumes. */
2166
+ existingMessages?: BaseMessage[];
2167
+ onEvent?: (event: SmartAgentEvent) => void;
2168
+ }): Promise<PreopenSkillsResult>;
2169
+
2111
2170
  /**
2112
2171
  * Pure registry helpers for the sub-agent primitive. No I/O, no agent loop —
2113
2172
  * the deterministic core, fully unit-testable on its own.
@@ -3335,4 +3394,4 @@ declare function fromNativeProvider(provider: BaseProvider, options?: NativeMode
3335
3394
  */
3336
3395
  declare function createProvider(config: ProviderConfig): BaseProvider;
3337
3396
 
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 };
3397
+ 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, PREOPEN_TOOL_CALL_PREFIX, type PendingToolApproval, type PendingUserQuestion, type PlanEvent, type PlanStepRecord, type PlanningMode, type PreopenSkillsResult, 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, preopenSkills, preopenToolCallId, 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
@@ -7546,6 +7546,127 @@ function createSkillTools(deps) {
7546
7546
  if (isSearchDisclosure(deps.policy)) tools.unshift(createSearchSkillsTool(deps));
7547
7547
  return tools;
7548
7548
  }
7549
+ var PREOPEN_TOOL_CALL_PREFIX = "preopen_skill_";
7550
+ var OPEN_SKILL_TOOL_NAME = "open_skill";
7551
+ function preopenToolCallId(skillKey) {
7552
+ return `${PREOPEN_TOOL_CALL_PREFIX}${skillKey.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
7553
+ }
7554
+ function messagesContainCallId(messages, callId) {
7555
+ if (!Array.isArray(messages)) return false;
7556
+ return messages.some((message) => {
7557
+ const calls = message?.tool_calls;
7558
+ return Array.isArray(calls) && calls.some((call) => call?.id === callId);
7559
+ });
7560
+ }
7561
+ function serializeToolContent(result) {
7562
+ if (typeof result === "string") return result;
7563
+ try {
7564
+ return JSON.stringify(result);
7565
+ } catch {
7566
+ return String(result);
7567
+ }
7568
+ }
7569
+ async function preopenSkills(input) {
7570
+ const empty = { messages: [], toolHistory: [], openedKeys: [], skipped: [] };
7571
+ const requested = [...new Set(
7572
+ (input.skillKeys ?? []).map((key) => String(key ?? "").trim()).filter(Boolean)
7573
+ )];
7574
+ if (requested.length === 0) return empty;
7575
+ const openSkillTool = input.tools.find((tool) => tool?.name === OPEN_SKILL_TOOL_NAME);
7576
+ if (!openSkillTool) {
7577
+ return { ...empty, skipped: requested.map((skillKey) => ({ skillKey, reason: "open_skill tool is not wired" })) };
7578
+ }
7579
+ const alreadyOpen = new Set(input.alreadyOpenedKeys ?? []);
7580
+ const toolCalls = [];
7581
+ const toolMessages = [];
7582
+ const toolHistory = [];
7583
+ const openedKeys = [];
7584
+ const skipped = [];
7585
+ for (const skillKey of requested) {
7586
+ const toolCallId = preopenToolCallId(skillKey);
7587
+ if (alreadyOpen.has(skillKey) || messagesContainCallId(input.existingMessages, toolCallId)) {
7588
+ skipped.push({ skillKey, reason: "already open" });
7589
+ continue;
7590
+ }
7591
+ const args = { skillKey };
7592
+ input.onEvent?.({ type: "tool_call", phase: "start", name: OPEN_SKILL_TOOL_NAME, id: toolCallId, args });
7593
+ const start = Date.now();
7594
+ let result;
7595
+ try {
7596
+ result = await openSkillTool.invoke(args);
7597
+ } catch (error) {
7598
+ const message = error instanceof Error ? error.message : "open_skill failed";
7599
+ input.onEvent?.({
7600
+ type: "tool_call",
7601
+ phase: "error",
7602
+ name: OPEN_SKILL_TOOL_NAME,
7603
+ id: toolCallId,
7604
+ args,
7605
+ error: { message },
7606
+ durationMs: Date.now() - start
7607
+ });
7608
+ skipped.push({ skillKey, reason: message });
7609
+ continue;
7610
+ }
7611
+ const durationMs = Date.now() - start;
7612
+ if (result && typeof result === "object" && typeof result.error === "string") {
7613
+ input.onEvent?.({
7614
+ type: "tool_call",
7615
+ phase: "skipped",
7616
+ name: OPEN_SKILL_TOOL_NAME,
7617
+ id: toolCallId,
7618
+ args,
7619
+ error: { message: result.error },
7620
+ durationMs
7621
+ });
7622
+ skipped.push({ skillKey, reason: result.error });
7623
+ continue;
7624
+ }
7625
+ if (result && typeof result === "object") delete result.__runtimeToolsDelta;
7626
+ toolCalls.push({
7627
+ id: toolCallId,
7628
+ type: "function",
7629
+ function: { name: OPEN_SKILL_TOOL_NAME, arguments: JSON.stringify(args) }
7630
+ });
7631
+ toolMessages.push({
7632
+ role: "tool",
7633
+ name: OPEN_SKILL_TOOL_NAME,
7634
+ tool_call_id: toolCallId,
7635
+ content: serializeToolContent(result)
7636
+ });
7637
+ toolHistory.push({
7638
+ executionId: nanoid(),
7639
+ toolName: OPEN_SKILL_TOOL_NAME,
7640
+ args,
7641
+ output: result,
7642
+ rawOutput: result,
7643
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
7644
+ tool_call_id: toolCallId,
7645
+ summarized: false,
7646
+ retentionPolicy: "keep_full",
7647
+ status: "success"
7648
+ });
7649
+ openedKeys.push(skillKey);
7650
+ input.onEvent?.({
7651
+ type: "tool_call",
7652
+ phase: "success",
7653
+ name: OPEN_SKILL_TOOL_NAME,
7654
+ id: toolCallId,
7655
+ args,
7656
+ result,
7657
+ durationMs
7658
+ });
7659
+ }
7660
+ if (toolCalls.length === 0) {
7661
+ return { ...empty, skipped };
7662
+ }
7663
+ const assistantMessage = {
7664
+ role: "assistant",
7665
+ content: `Opening the ${openedKeys.join(", ")} skill${openedKeys.length > 1 ? "s" : ""} required for this task.`,
7666
+ tool_calls: toolCalls
7667
+ };
7668
+ return { messages: [assistantMessage, ...toolMessages], toolHistory, openedKeys, skipped };
7669
+ }
7549
7670
 
7550
7671
  // src/smart/subagents/types.ts
7551
7672
  var DEFAULT_SUBAGENT_POLICY = {
@@ -8252,7 +8373,25 @@ function createSmartAgent(opts) {
8252
8373
  const disclosureBlock = [skillBlock, subagentBlock].filter(Boolean).join("\n\n") || void 0;
8253
8374
  const alreadyHasSystem = Array.isArray(input.messages) && input.messages[0]?.role === "system";
8254
8375
  const seedMessages = alreadyHasSystem ? [...input.messages || []] : [systemMessage2(disclosureBlock), ...input.messages || []];
8255
- let state = syncRuntimeTools(await syncMemory({ ...input, messages: seedMessages }), seedMessages, toolSet);
8376
+ let seedToolHistory = input.toolHistory;
8377
+ if (skillsEnabled && toolSet.skillRegistryRef) {
8378
+ const preopenKeys = config?.preopenedSkills ?? [];
8379
+ if (preopenKeys.length > 0) {
8380
+ const preopened = await preopenSkills({
8381
+ skillKeys: preopenKeys,
8382
+ tools: toolSet.toolsWithoutRecovery,
8383
+ alreadyOpenedKeys: toolSet.skillRegistryRef.openedSkillKeys,
8384
+ existingMessages: seedMessages,
8385
+ onEvent: config?.onEvent ?? opts.onEvent
8386
+ });
8387
+ if (preopened.messages.length > 0) {
8388
+ seedMessages.push(...preopened.messages);
8389
+ seedToolHistory = [...seedToolHistory ?? [], ...preopened.toolHistory];
8390
+ stateRef.toolHistory = seedToolHistory;
8391
+ }
8392
+ }
8393
+ }
8394
+ let state = syncRuntimeTools(await syncMemory({ ...input, messages: seedMessages, toolHistory: seedToolHistory }), seedMessages, toolSet);
8256
8395
  let lastResult = null;
8257
8396
  let rawMessages = [...seedMessages];
8258
8397
  const effectiveMaxToolCalls = config?.limits?.maxToolCalls ?? resolved.limits.maxToolCalls ?? 10;
@@ -11513,6 +11652,6 @@ function createProvider(config) {
11513
11652
  }
11514
11653
  }
11515
11654
 
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 };
11655
+ 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, PREOPEN_TOOL_CALL_PREFIX, 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, preopenSkills, preopenToolCallId, 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 };
11517
11656
  //# sourceMappingURL=index.mjs.map
11518
11657
  //# sourceMappingURL=index.mjs.map