@cognipeer/agent-sdk 0.8.11 → 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.cjs +173 -20
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +60 -1
- package/dist/index.d.ts +60 -1
- package/dist/index.mjs +171 -21
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
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
|
@@ -5299,7 +5299,10 @@ function shouldSignalSummarization(state, threshold) {
|
|
|
5299
5299
|
});
|
|
5300
5300
|
const tokenCount = countMessagesTokens(tokCountMessages);
|
|
5301
5301
|
if (tokenCount <= threshold) return "skip";
|
|
5302
|
-
if (state.ctx?.__summarizationExhausted)
|
|
5302
|
+
if (state.ctx?.__summarizationExhausted) {
|
|
5303
|
+
const exhaustedAt = state.ctx?.__summarizationExhaustedAtToolCount;
|
|
5304
|
+
if (typeof exhaustedAt !== "number" || (state.toolHistory || []).length <= exhaustedAt) return "skip";
|
|
5305
|
+
}
|
|
5303
5306
|
const hasFreshSummary = (state.messages || []).some(
|
|
5304
5307
|
(m) => m.role === "tool" && typeof m.content === "string" && (m.content === "SUMMARIZED" || m.content.startsWith("SUMMARIZED_TOOL_RESPONSE"))
|
|
5305
5308
|
);
|
|
@@ -6344,6 +6347,20 @@ function extractCanonicalFacts(messages) {
|
|
|
6344
6347
|
function isSummarizedToolPlaceholder(content) {
|
|
6345
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"));
|
|
6346
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
|
+
}
|
|
6347
6364
|
function findToolHistoryEntry(state, toolCallId, toolName) {
|
|
6348
6365
|
const entries = [
|
|
6349
6366
|
...state.toolHistory || [],
|
|
@@ -6438,6 +6455,10 @@ function createContextSummarizeNode(opts) {
|
|
|
6438
6455
|
if (compressableMessages.length === 0) {
|
|
6439
6456
|
return {};
|
|
6440
6457
|
}
|
|
6458
|
+
const protectedToolCallIds = collectLatestTurnToolCallIds(messages);
|
|
6459
|
+
if (compressableMessages.every((m) => m.tool_call_id && protectedToolCallIds.has(m.tool_call_id))) {
|
|
6460
|
+
return {};
|
|
6461
|
+
}
|
|
6441
6462
|
const tokenCountBefore = countMessagesTokens(messages);
|
|
6442
6463
|
const summaryPromptMaxTokens = config.summaryPromptMaxTokens;
|
|
6443
6464
|
const availableTokensForConversation = summaryPromptMaxTokens - 500;
|
|
@@ -6457,7 +6478,8 @@ function createContextSummarizeNode(opts) {
|
|
|
6457
6478
|
const historyEntry = findToolHistoryEntry(state, m.tool_call_id, m.name);
|
|
6458
6479
|
if (historyEntry) {
|
|
6459
6480
|
const original = historyEntry.rawOutput ?? historyEntry.output;
|
|
6460
|
-
|
|
6481
|
+
const recovered = typeof original === "string" ? original : JSON.stringify(original);
|
|
6482
|
+
if (typeof recovered === "string") content = recovered;
|
|
6461
6483
|
}
|
|
6462
6484
|
}
|
|
6463
6485
|
const maxContentLength = 2e3;
|
|
@@ -6596,22 +6618,6 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
|
|
|
6596
6618
|
});
|
|
6597
6619
|
}
|
|
6598
6620
|
});
|
|
6599
|
-
const protectedToolCallIds = /* @__PURE__ */ new Set();
|
|
6600
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
6601
|
-
const m = messages[i];
|
|
6602
|
-
if (m.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
|
|
6603
|
-
const thisToolCallIds = new Set(m.tool_calls.map((tc) => tc.id).filter(Boolean));
|
|
6604
|
-
const otherCompressable = compressableMessages.filter(
|
|
6605
|
-
(cm) => !thisToolCallIds.has(cm.tool_call_id)
|
|
6606
|
-
);
|
|
6607
|
-
if (otherCompressable.length > 0) {
|
|
6608
|
-
for (const tc of m.tool_calls) {
|
|
6609
|
-
if (tc.id) protectedToolCallIds.add(tc.id);
|
|
6610
|
-
}
|
|
6611
|
-
}
|
|
6612
|
-
break;
|
|
6613
|
-
}
|
|
6614
|
-
}
|
|
6615
6621
|
const retentionDeclarations = collectToolRetentionDeclarations(state.agent?.tools);
|
|
6616
6622
|
const digestableToolCallIds = /* @__PURE__ */ new Set();
|
|
6617
6623
|
for (const m of messages) {
|
|
@@ -7540,6 +7546,127 @@ function createSkillTools(deps) {
|
|
|
7540
7546
|
if (isSearchDisclosure(deps.policy)) tools.unshift(createSearchSkillsTool(deps));
|
|
7541
7547
|
return tools;
|
|
7542
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
|
+
}
|
|
7543
7670
|
|
|
7544
7671
|
// src/smart/subagents/types.ts
|
|
7545
7672
|
var DEFAULT_SUBAGENT_POLICY = {
|
|
@@ -8196,11 +8323,16 @@ function createSmartAgent(opts) {
|
|
|
8196
8323
|
if (!summarizer) return { state: currentState, rawMessages: currentRawMessages, compressed: false };
|
|
8197
8324
|
const delta = await summarizer(currentState);
|
|
8198
8325
|
if (!delta || Object.keys(delta).length === 0) {
|
|
8199
|
-
const ctx2 = {
|
|
8326
|
+
const ctx2 = {
|
|
8327
|
+
...currentState.ctx || {},
|
|
8328
|
+
__summarizationExhausted: true,
|
|
8329
|
+
__summarizationExhaustedAtToolCount: (currentState.toolHistory || []).length
|
|
8330
|
+
};
|
|
8200
8331
|
return { state: { ...currentState, ctx: ctx2 }, rawMessages: currentRawMessages, compressed: false };
|
|
8201
8332
|
}
|
|
8202
8333
|
const ctx = { ...currentState.ctx || {} };
|
|
8203
8334
|
delete ctx.__summarizationExhausted;
|
|
8335
|
+
delete ctx.__summarizationExhaustedAtToolCount;
|
|
8204
8336
|
const updated = await persistLatestSummary(syncPlanStateWith(ref, { ...currentState, ...delta, ctx }));
|
|
8205
8337
|
return { state: updated, rawMessages: [...updated.messages || currentRawMessages], compressed: true };
|
|
8206
8338
|
}
|
|
@@ -8241,7 +8373,25 @@ function createSmartAgent(opts) {
|
|
|
8241
8373
|
const disclosureBlock = [skillBlock, subagentBlock].filter(Boolean).join("\n\n") || void 0;
|
|
8242
8374
|
const alreadyHasSystem = Array.isArray(input.messages) && input.messages[0]?.role === "system";
|
|
8243
8375
|
const seedMessages = alreadyHasSystem ? [...input.messages || []] : [systemMessage2(disclosureBlock), ...input.messages || []];
|
|
8244
|
-
let
|
|
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);
|
|
8245
8395
|
let lastResult = null;
|
|
8246
8396
|
let rawMessages = [...seedMessages];
|
|
8247
8397
|
const effectiveMaxToolCalls = config?.limits?.maxToolCalls ?? resolved.limits.maxToolCalls ?? 10;
|
|
@@ -11502,6 +11652,6 @@ function createProvider(config) {
|
|
|
11502
11652
|
}
|
|
11503
11653
|
}
|
|
11504
11654
|
|
|
11505
|
-
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 };
|
|
11506
11656
|
//# sourceMappingURL=index.mjs.map
|
|
11507
11657
|
//# sourceMappingURL=index.mjs.map
|