@cognipeer/agent-sdk 0.7.1 → 0.7.2

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
@@ -107,6 +107,71 @@ declare function withTools(model: SmartModel, tools: any[], options?: {
107
107
  }): BaseChatModel;
108
108
  declare function fromLangchainModel(lcModel: any): BaseChatModel;
109
109
 
110
+ /**
111
+ * Skill primitive — progressive capability disclosure for the smart agent.
112
+ *
113
+ * A Skill is a lazy, self-contained capability bundle. The model always sees a
114
+ * cheap one-line `header`; it calls `open_skill(key)` to load the skill's prompt
115
+ * and (for small skills) bind its tools, or `bind_skill_tools(key, names)` to
116
+ * bind a chosen subset of a fat skill. This keeps the number of bound tools per
117
+ * step small — the property small models need — and replaces an up-front
118
+ * tool-selector pass with on-demand disclosure.
119
+ */
120
+ type SkillToolHeader = {
121
+ name: string;
122
+ description?: string;
123
+ };
124
+ type SkillModelTier = "small" | "large";
125
+ type Skill = {
126
+ /** Stable key, e.g. "mcp:atlassian" | "integration:google" | "builtin:drawio". */
127
+ key: string;
128
+ title: string;
129
+ /** One-line "what + when to use" the model always sees in the catalog. */
130
+ header: string;
131
+ /** Injected (as the open_skill result) only after the skill is opened. */
132
+ prompt: string | (() => Promise<string> | string);
133
+ /** When true, opening this skill should trigger sandbox bootstrap. */
134
+ needsSandbox?: boolean;
135
+ /** Gate: a "large"-only skill is hidden from a small-tier model. */
136
+ minModelTier?: SkillModelTier;
137
+ /** Whether the skill is usable in the current workspace (integration connected, etc.). */
138
+ isAvailable?: () => boolean | Promise<boolean>;
139
+ /** Cheap list of the skill's tool headers (names + one-liners). */
140
+ listToolIndex: () => Promise<SkillToolHeader[]> | SkillToolHeader[];
141
+ /** Bind concrete tools. With no names, bind the whole (small) skill. */
142
+ bindTools: (names?: string[]) => Promise<ToolInterface[]> | ToolInterface[];
143
+ /** Optional embedding/heuristic ranking of tool headers for a fat skill. */
144
+ rankToolHeaders?: (query: string, headers: SkillToolHeader[]) => Promise<SkillToolHeader[]> | SkillToolHeader[];
145
+ /** Deterministic floor: tools to bind when a weak model gives no usable query. */
146
+ defaultBindNames?: string[];
147
+ };
148
+ type SkillPolicy = {
149
+ /** Max distinct skills open at once (small tier should be 1). */
150
+ maxOpenSkills: number;
151
+ /** Max tools bound from a single skill in one bind call. */
152
+ maxBoundToolsPerSkill: number;
153
+ /** Overall cap on skill-bound tools across the whole run. */
154
+ maxBoundToolsTotal: number;
155
+ /** Current model tier; gates `minModelTier`. */
156
+ modelTier?: SkillModelTier;
157
+ };
158
+ declare const DEFAULT_SKILL_POLICY: SkillPolicy;
159
+ declare const SMALL_TIER_SKILL_POLICY: SkillPolicy;
160
+ /**
161
+ * Mutable per-invoke registry. The skill tools mutate this ref (append-only) and
162
+ * call `__onToolsChanged` so the runtime can rebuild its tool sets. Mirrors the
163
+ * stateRef pattern used by createAskUserQuestionTool.
164
+ */
165
+ type SkillRegistryRef = {
166
+ /** Append-only: skills the model has opened this run. */
167
+ openedSkillKeys: string[];
168
+ /** Append-only, deduped by tool name: tools bound from opened skills. */
169
+ boundSkillTools: ToolInterface[];
170
+ /** Rebuild hook wired by createSmartAgent; rebuilds both recovery variants. */
171
+ __onToolsChanged?: () => void;
172
+ };
173
+ declare function createSkillRegistryRef(): SkillRegistryRef;
174
+
110
175
  type ImageURL = {
111
176
  url: string;
112
177
  detail?: 'auto' | 'low' | 'high';
@@ -577,6 +642,15 @@ type SmartAgentOptions = {
577
642
  costEstimator?: AgentOptions["costEstimator"];
578
643
  /** See AgentOptions.humanInTheLoop. */
579
644
  humanInTheLoop?: HumanInTheLoopOptions;
645
+ /**
646
+ * Progressive capability disclosure. When provided, the agent exposes cheap
647
+ * skill headers in its system prompt and binds a skill's tools on demand via
648
+ * the built-in open_skill / bind_skill_tools tools. Keeps the bound-tool count
649
+ * per step small. An empty array is a no-op.
650
+ */
651
+ skills?: Skill[];
652
+ /** Caps/tiering for skill disclosure. Defaults to DEFAULT_SKILL_POLICY. */
653
+ skillPolicy?: SkillPolicy;
580
654
  };
581
655
  type AgentRuntimeConfig = {
582
656
  name?: string;
@@ -1449,6 +1523,58 @@ declare function createSmartAgent<TOutput = unknown>(opts: SmartAgentOptions & {
1449
1523
  outputSchema?: ZodSchema<TOutput>;
1450
1524
  }): SmartAgentInstance<TOutput>;
1451
1525
 
1526
+ /**
1527
+ * Pure registry helpers for the skill primitive. No I/O, no agent loop — these
1528
+ * are the deterministic core, fully unit-testable on their own.
1529
+ */
1530
+ /**
1531
+ * Rebuild BOTH runtime tool-set variants with fresh array references.
1532
+ *
1533
+ * This is the heart of mid-run skill binding. `syncRuntimeTools` swaps between
1534
+ * two PRE-COMPUTED arrays and short-circuits on `currentRuntime.tools ===
1535
+ * nextTools`. So to make newly-bound skill tools take effect we must hand back
1536
+ * NEW array references (breaking the `===` short-circuit) AND include the skill
1537
+ * tools in the recovery variant too (otherwise a recovery-swap iteration would
1538
+ * silently drop them).
1539
+ */
1540
+ declare function composeToolSets(input: {
1541
+ base: ToolInterface[];
1542
+ boundSkillTools: ToolInterface[];
1543
+ recoveryTool?: ToolInterface;
1544
+ }): {
1545
+ toolsWithoutRecovery: ToolInterface[];
1546
+ toolsWithRecovery: ToolInterface[];
1547
+ };
1548
+ /**
1549
+ * Append tools to the registry, append-only and deduped by name, honoring the
1550
+ * overall total cap. Returns the tools actually added (may be fewer than asked).
1551
+ */
1552
+ declare function appendBoundTools(ref: SkillRegistryRef, newTools: ToolInterface[], policy: Pick<SkillPolicy, "maxBoundToolsTotal">): ToolInterface[];
1553
+ /** Precedence guard: may the model open another (not-yet-open) skill? */
1554
+ declare function canOpenSkill(ref: SkillRegistryRef, policy: SkillPolicy): {
1555
+ ok: true;
1556
+ } | {
1557
+ ok: false;
1558
+ reason: string;
1559
+ };
1560
+ /** Filter the catalog to skills usable now: available + tier-gated. */
1561
+ declare function resolveAvailableSkills(skills: Skill[], opts?: {
1562
+ modelTier?: SkillPolicy["modelTier"];
1563
+ }): Promise<Skill[]>;
1564
+ /** The cheap header block the model always sees in its system prompt. */
1565
+ declare function buildSkillHeaderBlock(skills: Skill[]): string;
1566
+ declare function dedupeToolsByName(tools: ToolInterface[]): ToolInterface[];
1567
+
1568
+ type SkillToolDeps = {
1569
+ registryRef: SkillRegistryRef;
1570
+ skills: Skill[];
1571
+ policy: SkillPolicy;
1572
+ };
1573
+ declare function createOpenSkillTool(deps: SkillToolDeps): ToolInterface;
1574
+ declare function createBindSkillToolsTool(deps: SkillToolDeps): ToolInterface;
1575
+ /** Both skill tools for an invoke, sharing one registry ref. */
1576
+ declare function createSkillTools(deps: SkillToolDeps): ToolInterface[];
1577
+
1452
1578
  type EvalHarnessParams = {
1453
1579
  profiles: EvalProfileTarget[];
1454
1580
  cases: EvalCase[];
@@ -2228,4 +2354,4 @@ declare function fromNativeProvider(provider: BaseProvider, options?: NativeMode
2228
2354
  */
2229
2355
  declare function createProvider(config: ProviderConfig): BaseProvider;
2230
2356
 
2231
- export { type AIMessage, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, AnthropicProvider, type AnthropicProviderConfig, AzureProvider, type AzureProviderConfig, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, BaseProvider, BedrockProvider, type BedrockProviderConfig, type BuiltInRuntimeProfile, type CancellationTokenLike, type CancelledEvent, type ChatCompletionChunk, type ChatCompletionRequest, type ChatCompletionResponse, type ChildContextPolicy, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type ContextPolicy, type ContextToolsStateRef, type ConversationGuardrail, type CustomRuleCallback, type CustomRuleOptions, DEFAULT_PROFILE_CONFIGS, type DelegationMode, type EvalCase, type EvalCaseResult, type EvalFamily, type EvalHarnessMetrics, type EvalHarnessParams, type EvalHarnessResult, type EvalProfileDescriptor, type EvalProfileTarget, 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, InMemoryMemoryStore, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, 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 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 ResolvedSmartAgentConfig, type ResolvedTraceConfig, type ResolvedTraceSink, type RestoreSnapshotOptions, type RuntimeProfile, type SerializableSmartState, 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 SummarizationEvent, type SummarizationMode, type SummaryFactItem, type SummaryIntegrityCheck, type TokenCounter, type TokenUsage, type ToolApprovalEvent, type ToolApprovalResolution, type ToolApprovalStatus, ToolBasedStrategy, type ToolCachePolicy, type ToolCallEvent, type ToolInterface, type ToolResponseClassification, type ToolResponseRetentionPolicy, 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, agentVerdictRule, buildSystemPrompt, captureSnapshot, codePresenceRule, cognipeerSink, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createAskUserQuestionTool, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGetToolResponseTool, createGuardrail, createJsonGuardrail, createManageTodoTool, createProvider, createRegexGuardrail, createResolverNode, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, defaultTokenCounter, emptyUsage, evaluateGuardrails, fileSink, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getModelCapabilities, getNestedValue, getResolvedSmartConfig, getTokenCounter, hasToolResponseRecoveryReference, httpSink, isSmartModel, jsonSchemaRule, normalizeSmartAgentOptions, otlpSink, readMemoryFacts, regexRule, resolveMemoryStore, resolveReasoning, resolveStrategy, resolveToolApprovalState, resolveUserQuestionState, restoreSnapshot, runSmartAgentEvalHarness, setTokenCounter, startStreamingSession, traceSessionToOtlp, validateReasoningConfig, withTools, writeSummaryFactsToMemory };
2357
+ export { type AIMessage, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, AnthropicProvider, type AnthropicProviderConfig, AzureProvider, type AzureProviderConfig, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, BaseProvider, BedrockProvider, type BedrockProviderConfig, type BuiltInRuntimeProfile, type CancellationTokenLike, type CancelledEvent, type ChatCompletionChunk, type ChatCompletionRequest, type ChatCompletionResponse, type ChildContextPolicy, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type ContextPolicy, type ContextToolsStateRef, type ConversationGuardrail, type CustomRuleCallback, type CustomRuleOptions, DEFAULT_PROFILE_CONFIGS, DEFAULT_SKILL_POLICY, type DelegationMode, type EvalCase, type EvalCaseResult, type EvalFamily, type EvalHarnessMetrics, type EvalHarnessParams, type EvalHarnessResult, type EvalProfileDescriptor, type EvalProfileTarget, 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, InMemoryMemoryStore, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, 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 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 ResolvedSmartAgentConfig, type ResolvedTraceConfig, type ResolvedTraceSink, type RestoreSnapshotOptions, type RuntimeProfile, SMALL_TIER_SKILL_POLICY, type SerializableSmartState, type Skill, 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 SummarizationEvent, type SummarizationMode, type SummaryFactItem, type SummaryIntegrityCheck, type TokenCounter, type TokenUsage, type ToolApprovalEvent, type ToolApprovalResolution, type ToolApprovalStatus, ToolBasedStrategy, type ToolCachePolicy, type ToolCallEvent, type ToolInterface, type ToolResponseClassification, type ToolResponseRetentionPolicy, 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, agentVerdictRule, appendBoundTools, buildSkillHeaderBlock, buildSystemPrompt, canOpenSkill, captureSnapshot, codePresenceRule, cognipeerSink, composeToolSets, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createAskUserQuestionTool, createBindSkillToolsTool, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGetToolResponseTool, createGuardrail, createJsonGuardrail, createManageTodoTool, createOpenSkillTool, createProvider, createRegexGuardrail, createResolverNode, createSkillRegistryRef, createSkillTools, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, dedupeToolsByName, defaultTokenCounter, emptyUsage, evaluateGuardrails, fileSink, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getModelCapabilities, getNestedValue, getResolvedSmartConfig, getTokenCounter, hasToolResponseRecoveryReference, httpSink, isSmartModel, jsonSchemaRule, normalizeSmartAgentOptions, otlpSink, readMemoryFacts, regexRule, resolveAvailableSkills, resolveMemoryStore, resolveReasoning, resolveStrategy, resolveToolApprovalState, resolveUserQuestionState, restoreSnapshot, runSmartAgentEvalHarness, setTokenCounter, startStreamingSession, traceSessionToOtlp, validateReasoningConfig, withTools, writeSummaryFactsToMemory };
package/dist/index.d.ts CHANGED
@@ -107,6 +107,71 @@ declare function withTools(model: SmartModel, tools: any[], options?: {
107
107
  }): BaseChatModel;
108
108
  declare function fromLangchainModel(lcModel: any): BaseChatModel;
109
109
 
110
+ /**
111
+ * Skill primitive — progressive capability disclosure for the smart agent.
112
+ *
113
+ * A Skill is a lazy, self-contained capability bundle. The model always sees a
114
+ * cheap one-line `header`; it calls `open_skill(key)` to load the skill's prompt
115
+ * and (for small skills) bind its tools, or `bind_skill_tools(key, names)` to
116
+ * bind a chosen subset of a fat skill. This keeps the number of bound tools per
117
+ * step small — the property small models need — and replaces an up-front
118
+ * tool-selector pass with on-demand disclosure.
119
+ */
120
+ type SkillToolHeader = {
121
+ name: string;
122
+ description?: string;
123
+ };
124
+ type SkillModelTier = "small" | "large";
125
+ type Skill = {
126
+ /** Stable key, e.g. "mcp:atlassian" | "integration:google" | "builtin:drawio". */
127
+ key: string;
128
+ title: string;
129
+ /** One-line "what + when to use" the model always sees in the catalog. */
130
+ header: string;
131
+ /** Injected (as the open_skill result) only after the skill is opened. */
132
+ prompt: string | (() => Promise<string> | string);
133
+ /** When true, opening this skill should trigger sandbox bootstrap. */
134
+ needsSandbox?: boolean;
135
+ /** Gate: a "large"-only skill is hidden from a small-tier model. */
136
+ minModelTier?: SkillModelTier;
137
+ /** Whether the skill is usable in the current workspace (integration connected, etc.). */
138
+ isAvailable?: () => boolean | Promise<boolean>;
139
+ /** Cheap list of the skill's tool headers (names + one-liners). */
140
+ listToolIndex: () => Promise<SkillToolHeader[]> | SkillToolHeader[];
141
+ /** Bind concrete tools. With no names, bind the whole (small) skill. */
142
+ bindTools: (names?: string[]) => Promise<ToolInterface[]> | ToolInterface[];
143
+ /** Optional embedding/heuristic ranking of tool headers for a fat skill. */
144
+ rankToolHeaders?: (query: string, headers: SkillToolHeader[]) => Promise<SkillToolHeader[]> | SkillToolHeader[];
145
+ /** Deterministic floor: tools to bind when a weak model gives no usable query. */
146
+ defaultBindNames?: string[];
147
+ };
148
+ type SkillPolicy = {
149
+ /** Max distinct skills open at once (small tier should be 1). */
150
+ maxOpenSkills: number;
151
+ /** Max tools bound from a single skill in one bind call. */
152
+ maxBoundToolsPerSkill: number;
153
+ /** Overall cap on skill-bound tools across the whole run. */
154
+ maxBoundToolsTotal: number;
155
+ /** Current model tier; gates `minModelTier`. */
156
+ modelTier?: SkillModelTier;
157
+ };
158
+ declare const DEFAULT_SKILL_POLICY: SkillPolicy;
159
+ declare const SMALL_TIER_SKILL_POLICY: SkillPolicy;
160
+ /**
161
+ * Mutable per-invoke registry. The skill tools mutate this ref (append-only) and
162
+ * call `__onToolsChanged` so the runtime can rebuild its tool sets. Mirrors the
163
+ * stateRef pattern used by createAskUserQuestionTool.
164
+ */
165
+ type SkillRegistryRef = {
166
+ /** Append-only: skills the model has opened this run. */
167
+ openedSkillKeys: string[];
168
+ /** Append-only, deduped by tool name: tools bound from opened skills. */
169
+ boundSkillTools: ToolInterface[];
170
+ /** Rebuild hook wired by createSmartAgent; rebuilds both recovery variants. */
171
+ __onToolsChanged?: () => void;
172
+ };
173
+ declare function createSkillRegistryRef(): SkillRegistryRef;
174
+
110
175
  type ImageURL = {
111
176
  url: string;
112
177
  detail?: 'auto' | 'low' | 'high';
@@ -577,6 +642,15 @@ type SmartAgentOptions = {
577
642
  costEstimator?: AgentOptions["costEstimator"];
578
643
  /** See AgentOptions.humanInTheLoop. */
579
644
  humanInTheLoop?: HumanInTheLoopOptions;
645
+ /**
646
+ * Progressive capability disclosure. When provided, the agent exposes cheap
647
+ * skill headers in its system prompt and binds a skill's tools on demand via
648
+ * the built-in open_skill / bind_skill_tools tools. Keeps the bound-tool count
649
+ * per step small. An empty array is a no-op.
650
+ */
651
+ skills?: Skill[];
652
+ /** Caps/tiering for skill disclosure. Defaults to DEFAULT_SKILL_POLICY. */
653
+ skillPolicy?: SkillPolicy;
580
654
  };
581
655
  type AgentRuntimeConfig = {
582
656
  name?: string;
@@ -1449,6 +1523,58 @@ declare function createSmartAgent<TOutput = unknown>(opts: SmartAgentOptions & {
1449
1523
  outputSchema?: ZodSchema<TOutput>;
1450
1524
  }): SmartAgentInstance<TOutput>;
1451
1525
 
1526
+ /**
1527
+ * Pure registry helpers for the skill primitive. No I/O, no agent loop — these
1528
+ * are the deterministic core, fully unit-testable on their own.
1529
+ */
1530
+ /**
1531
+ * Rebuild BOTH runtime tool-set variants with fresh array references.
1532
+ *
1533
+ * This is the heart of mid-run skill binding. `syncRuntimeTools` swaps between
1534
+ * two PRE-COMPUTED arrays and short-circuits on `currentRuntime.tools ===
1535
+ * nextTools`. So to make newly-bound skill tools take effect we must hand back
1536
+ * NEW array references (breaking the `===` short-circuit) AND include the skill
1537
+ * tools in the recovery variant too (otherwise a recovery-swap iteration would
1538
+ * silently drop them).
1539
+ */
1540
+ declare function composeToolSets(input: {
1541
+ base: ToolInterface[];
1542
+ boundSkillTools: ToolInterface[];
1543
+ recoveryTool?: ToolInterface;
1544
+ }): {
1545
+ toolsWithoutRecovery: ToolInterface[];
1546
+ toolsWithRecovery: ToolInterface[];
1547
+ };
1548
+ /**
1549
+ * Append tools to the registry, append-only and deduped by name, honoring the
1550
+ * overall total cap. Returns the tools actually added (may be fewer than asked).
1551
+ */
1552
+ declare function appendBoundTools(ref: SkillRegistryRef, newTools: ToolInterface[], policy: Pick<SkillPolicy, "maxBoundToolsTotal">): ToolInterface[];
1553
+ /** Precedence guard: may the model open another (not-yet-open) skill? */
1554
+ declare function canOpenSkill(ref: SkillRegistryRef, policy: SkillPolicy): {
1555
+ ok: true;
1556
+ } | {
1557
+ ok: false;
1558
+ reason: string;
1559
+ };
1560
+ /** Filter the catalog to skills usable now: available + tier-gated. */
1561
+ declare function resolveAvailableSkills(skills: Skill[], opts?: {
1562
+ modelTier?: SkillPolicy["modelTier"];
1563
+ }): Promise<Skill[]>;
1564
+ /** The cheap header block the model always sees in its system prompt. */
1565
+ declare function buildSkillHeaderBlock(skills: Skill[]): string;
1566
+ declare function dedupeToolsByName(tools: ToolInterface[]): ToolInterface[];
1567
+
1568
+ type SkillToolDeps = {
1569
+ registryRef: SkillRegistryRef;
1570
+ skills: Skill[];
1571
+ policy: SkillPolicy;
1572
+ };
1573
+ declare function createOpenSkillTool(deps: SkillToolDeps): ToolInterface;
1574
+ declare function createBindSkillToolsTool(deps: SkillToolDeps): ToolInterface;
1575
+ /** Both skill tools for an invoke, sharing one registry ref. */
1576
+ declare function createSkillTools(deps: SkillToolDeps): ToolInterface[];
1577
+
1452
1578
  type EvalHarnessParams = {
1453
1579
  profiles: EvalProfileTarget[];
1454
1580
  cases: EvalCase[];
@@ -2228,4 +2354,4 @@ declare function fromNativeProvider(provider: BaseProvider, options?: NativeMode
2228
2354
  */
2229
2355
  declare function createProvider(config: ProviderConfig): BaseProvider;
2230
2356
 
2231
- export { type AIMessage, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, AnthropicProvider, type AnthropicProviderConfig, AzureProvider, type AzureProviderConfig, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, BaseProvider, BedrockProvider, type BedrockProviderConfig, type BuiltInRuntimeProfile, type CancellationTokenLike, type CancelledEvent, type ChatCompletionChunk, type ChatCompletionRequest, type ChatCompletionResponse, type ChildContextPolicy, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type ContextPolicy, type ContextToolsStateRef, type ConversationGuardrail, type CustomRuleCallback, type CustomRuleOptions, DEFAULT_PROFILE_CONFIGS, type DelegationMode, type EvalCase, type EvalCaseResult, type EvalFamily, type EvalHarnessMetrics, type EvalHarnessParams, type EvalHarnessResult, type EvalProfileDescriptor, type EvalProfileTarget, 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, InMemoryMemoryStore, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, 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 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 ResolvedSmartAgentConfig, type ResolvedTraceConfig, type ResolvedTraceSink, type RestoreSnapshotOptions, type RuntimeProfile, type SerializableSmartState, 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 SummarizationEvent, type SummarizationMode, type SummaryFactItem, type SummaryIntegrityCheck, type TokenCounter, type TokenUsage, type ToolApprovalEvent, type ToolApprovalResolution, type ToolApprovalStatus, ToolBasedStrategy, type ToolCachePolicy, type ToolCallEvent, type ToolInterface, type ToolResponseClassification, type ToolResponseRetentionPolicy, 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, agentVerdictRule, buildSystemPrompt, captureSnapshot, codePresenceRule, cognipeerSink, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createAskUserQuestionTool, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGetToolResponseTool, createGuardrail, createJsonGuardrail, createManageTodoTool, createProvider, createRegexGuardrail, createResolverNode, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, defaultTokenCounter, emptyUsage, evaluateGuardrails, fileSink, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getModelCapabilities, getNestedValue, getResolvedSmartConfig, getTokenCounter, hasToolResponseRecoveryReference, httpSink, isSmartModel, jsonSchemaRule, normalizeSmartAgentOptions, otlpSink, readMemoryFacts, regexRule, resolveMemoryStore, resolveReasoning, resolveStrategy, resolveToolApprovalState, resolveUserQuestionState, restoreSnapshot, runSmartAgentEvalHarness, setTokenCounter, startStreamingSession, traceSessionToOtlp, validateReasoningConfig, withTools, writeSummaryFactsToMemory };
2357
+ export { type AIMessage, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, AnthropicProvider, type AnthropicProviderConfig, AzureProvider, type AzureProviderConfig, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, BaseProvider, BedrockProvider, type BedrockProviderConfig, type BuiltInRuntimeProfile, type CancellationTokenLike, type CancelledEvent, type ChatCompletionChunk, type ChatCompletionRequest, type ChatCompletionResponse, type ChildContextPolicy, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type ContextPolicy, type ContextToolsStateRef, type ConversationGuardrail, type CustomRuleCallback, type CustomRuleOptions, DEFAULT_PROFILE_CONFIGS, DEFAULT_SKILL_POLICY, type DelegationMode, type EvalCase, type EvalCaseResult, type EvalFamily, type EvalHarnessMetrics, type EvalHarnessParams, type EvalHarnessResult, type EvalProfileDescriptor, type EvalProfileTarget, 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, InMemoryMemoryStore, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, 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 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 ResolvedSmartAgentConfig, type ResolvedTraceConfig, type ResolvedTraceSink, type RestoreSnapshotOptions, type RuntimeProfile, SMALL_TIER_SKILL_POLICY, type SerializableSmartState, type Skill, 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 SummarizationEvent, type SummarizationMode, type SummaryFactItem, type SummaryIntegrityCheck, type TokenCounter, type TokenUsage, type ToolApprovalEvent, type ToolApprovalResolution, type ToolApprovalStatus, ToolBasedStrategy, type ToolCachePolicy, type ToolCallEvent, type ToolInterface, type ToolResponseClassification, type ToolResponseRetentionPolicy, 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, agentVerdictRule, appendBoundTools, buildSkillHeaderBlock, buildSystemPrompt, canOpenSkill, captureSnapshot, codePresenceRule, cognipeerSink, composeToolSets, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createAskUserQuestionTool, createBindSkillToolsTool, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGetToolResponseTool, createGuardrail, createJsonGuardrail, createManageTodoTool, createOpenSkillTool, createProvider, createRegexGuardrail, createResolverNode, createSkillRegistryRef, createSkillTools, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, dedupeToolsByName, defaultTokenCounter, emptyUsage, evaluateGuardrails, fileSink, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getModelCapabilities, getNestedValue, getResolvedSmartConfig, getTokenCounter, hasToolResponseRecoveryReference, httpSink, isSmartModel, jsonSchemaRule, normalizeSmartAgentOptions, otlpSink, readMemoryFacts, regexRule, resolveAvailableSkills, resolveMemoryStore, resolveReasoning, resolveStrategy, resolveToolApprovalState, resolveUserQuestionState, restoreSnapshot, runSmartAgentEvalHarness, setTokenCounter, startStreamingSession, traceSessionToOtlp, validateReasoningConfig, withTools, writeSummaryFactsToMemory };
package/dist/index.mjs CHANGED
@@ -3026,6 +3026,17 @@ function createToolsNode(initialTools, opts) {
3026
3026
  }
3027
3027
  const durationMs = Date.now() - start;
3028
3028
  const executionId = nanoid();
3029
+ if (output && typeof output === "object" && Array.isArray(output.__runtimeToolsDelta)) {
3030
+ const delta = output.__runtimeToolsDelta;
3031
+ delete output.__runtimeToolsDelta;
3032
+ const currentRuntime = state.agent || runtime;
3033
+ const currentTools = currentRuntime?.tools ?? [];
3034
+ const present = new Set(currentTools.map((tool2) => tool2?.name));
3035
+ const additions = delta.filter((tool2) => tool2 && tool2.name && !present.has(tool2.name));
3036
+ if (additions.length > 0 && currentRuntime) {
3037
+ state.agent = { ...currentRuntime, tools: [...currentTools, ...additions] };
3038
+ }
3039
+ }
3029
3040
  if (output && typeof output === "object" && output.__handoff && output.__handoff.runtime) {
3030
3041
  toolHistory.push({ executionId, toolName, args, output: "handoff:ok", rawOutput: output, timestamp: (/* @__PURE__ */ new Date()).toISOString(), tool_call_id: tc.id, status: "handoff" });
3031
3042
  push({ role: "tool", content: "ok", tool_call_id: tc.id || `${tc.name}_${toolCount}`, name: tc.name });
@@ -6183,6 +6194,190 @@ async function writeSummaryFactsToMemory(store, config, summary, sourceTurn) {
6183
6194
  return store.get(config.memory.scope, { limit: config.context.lastTurnsToKeep + summary.stable_facts.length });
6184
6195
  }
6185
6196
 
6197
+ // src/smart/skills/types.ts
6198
+ var DEFAULT_SKILL_POLICY = {
6199
+ maxOpenSkills: 4,
6200
+ maxBoundToolsPerSkill: 12,
6201
+ maxBoundToolsTotal: 40
6202
+ };
6203
+ var SMALL_TIER_SKILL_POLICY = {
6204
+ maxOpenSkills: 1,
6205
+ maxBoundToolsPerSkill: 6,
6206
+ maxBoundToolsTotal: 18,
6207
+ modelTier: "small"
6208
+ };
6209
+ function createSkillRegistryRef() {
6210
+ return { openedSkillKeys: [], boundSkillTools: [] };
6211
+ }
6212
+
6213
+ // src/smart/skills/registry.ts
6214
+ function composeToolSets(input) {
6215
+ const without = [...input.base, ...input.boundSkillTools];
6216
+ const withRec = input.recoveryTool ? [...without, input.recoveryTool] : [...without];
6217
+ return { toolsWithoutRecovery: without, toolsWithRecovery: withRec };
6218
+ }
6219
+ function appendBoundTools(ref, newTools, policy) {
6220
+ const present = new Set(ref.boundSkillTools.map((tool) => tool.name));
6221
+ const added = [];
6222
+ for (const tool of newTools) {
6223
+ if (ref.boundSkillTools.length >= policy.maxBoundToolsTotal) break;
6224
+ if (present.has(tool.name)) continue;
6225
+ present.add(tool.name);
6226
+ ref.boundSkillTools.push(tool);
6227
+ added.push(tool);
6228
+ }
6229
+ return added;
6230
+ }
6231
+ function canOpenSkill(ref, policy) {
6232
+ if (ref.openedSkillKeys.length >= policy.maxOpenSkills) {
6233
+ return { ok: false, reason: `max ${policy.maxOpenSkills} skill(s) already open` };
6234
+ }
6235
+ if (ref.boundSkillTools.length >= policy.maxBoundToolsTotal) {
6236
+ return { ok: false, reason: "skill tool budget exhausted" };
6237
+ }
6238
+ return { ok: true };
6239
+ }
6240
+ async function resolveAvailableSkills(skills, opts = {}) {
6241
+ const out = [];
6242
+ for (const skill of skills) {
6243
+ if (skill.minModelTier === "large" && opts.modelTier === "small") continue;
6244
+ const available = skill.isAvailable ? await skill.isAvailable() : true;
6245
+ if (available) out.push(skill);
6246
+ }
6247
+ return out;
6248
+ }
6249
+ function buildSkillHeaderBlock(skills) {
6250
+ if (skills.length === 0) return "";
6251
+ const lines = skills.map((skill) => `- ${skill.key}: ${skill.header}`);
6252
+ return [
6253
+ "<available_skills>",
6254
+ "Open a skill with open_skill(skillKey) to load its tools on demand. Only open what the task needs; close nothing \u2014 opened skills stay available for the rest of the run.",
6255
+ ...lines,
6256
+ "</available_skills>"
6257
+ ].join("\n");
6258
+ }
6259
+ function dedupeToolsByName(tools) {
6260
+ const seen = /* @__PURE__ */ new Set();
6261
+ const out = [];
6262
+ for (const tool of tools) {
6263
+ if (seen.has(tool.name)) continue;
6264
+ seen.add(tool.name);
6265
+ out.push(tool);
6266
+ }
6267
+ return out;
6268
+ }
6269
+
6270
+ // src/smart/skills/skillTools.ts
6271
+ var MAX_RETURNED_INDEX = 40;
6272
+ var OPEN_SKILL_DESCRIPTION = "Load a capability on demand. Pass a skillKey from <available_skills>. A small skill binds all its tools immediately; a large one returns a tool index \u2014 then call bind_skill_tools with only the tools you need. Open only what the task needs.";
6273
+ var BIND_SKILL_TOOLS_DESCRIPTION = "After open_skill on a large skill, bind a chosen subset of its tools by name. Pick the few tools the task actually needs.";
6274
+ function findSkill(deps, key) {
6275
+ return deps.skills.find((skill) => skill.key === key);
6276
+ }
6277
+ function createOpenSkillTool(deps) {
6278
+ const tool = createTool({
6279
+ name: "open_skill",
6280
+ description: OPEN_SKILL_DESCRIPTION,
6281
+ schema: z.object({
6282
+ skillKey: z.string().min(1).describe("A key from <available_skills>."),
6283
+ query: z.string().optional().describe("What you need from the skill \u2014 used to rank a large skill's tools.")
6284
+ }).strict(),
6285
+ func: async ({ skillKey, query }) => {
6286
+ const { registryRef: ref, policy } = tool._deps;
6287
+ const skill = findSkill(tool._deps, skillKey);
6288
+ if (!skill) {
6289
+ return { error: `Unknown skill: ${skillKey}. Choose a key listed in <available_skills>.` };
6290
+ }
6291
+ if (skill.isAvailable && !await skill.isAvailable()) {
6292
+ return { error: `Skill ${skillKey} is not available in this workspace.` };
6293
+ }
6294
+ const alreadyOpen = ref.openedSkillKeys.includes(skillKey);
6295
+ if (!alreadyOpen) {
6296
+ const guard = canOpenSkill(ref, policy);
6297
+ if (!guard.ok) {
6298
+ return {
6299
+ error: `Cannot open ${skillKey}: ${guard.reason}. Work with the skills already open.`
6300
+ };
6301
+ }
6302
+ ref.openedSkillKeys.push(skillKey);
6303
+ }
6304
+ const prompt = typeof skill.prompt === "function" ? await skill.prompt() : skill.prompt;
6305
+ const index = await skill.listToolIndex();
6306
+ if (index.length <= policy.maxBoundToolsPerSkill) {
6307
+ const bound = await skill.bindTools();
6308
+ const added = appendBoundTools(ref, bound, policy);
6309
+ if (added.length > 0) ref.__onToolsChanged?.();
6310
+ return {
6311
+ skillKey,
6312
+ prompt,
6313
+ needsSandbox: Boolean(skill.needsSandbox),
6314
+ boundTools: added.map((t) => t.name),
6315
+ // Inject the bound tools into the live runtime for this loop.
6316
+ __runtimeToolsDelta: added
6317
+ };
6318
+ }
6319
+ let defaultBound = [];
6320
+ let defaultAdded = [];
6321
+ if ((!query || query.trim().length < 3) && skill.defaultBindNames?.length) {
6322
+ const bound = await skill.bindTools(skill.defaultBindNames.slice(0, policy.maxBoundToolsPerSkill));
6323
+ defaultAdded = appendBoundTools(ref, bound, policy);
6324
+ if (defaultAdded.length > 0) ref.__onToolsChanged?.();
6325
+ defaultBound = defaultAdded.map((t) => t.name);
6326
+ }
6327
+ const headers = query && query.trim().length >= 3 && skill.rankToolHeaders ? await skill.rankToolHeaders(query, index) : index;
6328
+ return {
6329
+ skillKey,
6330
+ prompt,
6331
+ needsSandbox: Boolean(skill.needsSandbox),
6332
+ boundTools: defaultBound,
6333
+ toolIndex: headers.slice(0, MAX_RETURNED_INDEX).map((h) => ({ name: h.name, description: h.description })),
6334
+ hint: "Call bind_skill_tools(skillKey, toolNames) with only the tools you need.",
6335
+ ...defaultAdded.length > 0 ? { __runtimeToolsDelta: defaultAdded } : {}
6336
+ };
6337
+ }
6338
+ });
6339
+ tool._deps = deps;
6340
+ tool.__source = "smart-skills";
6341
+ return tool;
6342
+ }
6343
+ function createBindSkillToolsTool(deps) {
6344
+ const tool = createTool({
6345
+ name: "bind_skill_tools",
6346
+ description: BIND_SKILL_TOOLS_DESCRIPTION,
6347
+ schema: z.object({
6348
+ skillKey: z.string().min(1),
6349
+ toolNames: z.array(z.string().min(1)).min(1).describe("Tool names from the skill's index.")
6350
+ }).strict(),
6351
+ func: async ({ skillKey, toolNames }) => {
6352
+ const { registryRef: ref, policy } = tool._deps;
6353
+ const skill = findSkill(tool._deps, skillKey);
6354
+ if (!skill) {
6355
+ return { error: `Unknown skill: ${skillKey}.` };
6356
+ }
6357
+ if (!ref.openedSkillKeys.includes(skillKey)) {
6358
+ return { error: `Call open_skill("${skillKey}") before binding its tools.` };
6359
+ }
6360
+ const capped = toolNames.slice(0, policy.maxBoundToolsPerSkill);
6361
+ const bound = await skill.bindTools(capped);
6362
+ const added = appendBoundTools(ref, bound, policy);
6363
+ if (added.length > 0) ref.__onToolsChanged?.();
6364
+ return {
6365
+ skillKey,
6366
+ boundTools: added.map((t) => t.name),
6367
+ requested: capped.length,
6368
+ truncated: toolNames.length > capped.length,
6369
+ ...added.length > 0 ? { __runtimeToolsDelta: added } : {}
6370
+ };
6371
+ }
6372
+ });
6373
+ tool._deps = deps;
6374
+ tool.__source = "smart-skills";
6375
+ return tool;
6376
+ }
6377
+ function createSkillTools(deps) {
6378
+ return [createOpenSkillTool(deps), createBindSkillToolsTool(deps)];
6379
+ }
6380
+
6186
6381
  // src/smart/index.ts
6187
6382
  function createSmartAgent(opts) {
6188
6383
  const resolved = normalizeSmartAgentOptions(opts);
@@ -6217,6 +6412,9 @@ function createSmartAgent(opts) {
6217
6412
  if (askUserConfig) {
6218
6413
  factoryToolsWithoutRecovery.push(createAskUserQuestionTool(factoryStateRef, askUserConfig));
6219
6414
  }
6415
+ const skills = opts.skills ?? [];
6416
+ const skillPolicy = opts.skillPolicy ?? DEFAULT_SKILL_POLICY;
6417
+ const skillsEnabled = skills.length > 0;
6220
6418
  const soManagerFactory = opts.outputSchema ? new StructuredOutputManager(opts.outputSchema, resolveStrategy(opts.model)) : void 0;
6221
6419
  const modelCapabilities = opts.outputSchema ? getModelCapabilities(opts.model) : void 0;
6222
6420
  const responseFinalizeTool = soManagerFactory && modelCapabilities?.structuredOutput !== "native" ? soManagerFactory.getResponseTool() : void 0;
@@ -6224,12 +6422,31 @@ function createSmartAgent(opts) {
6224
6422
  const ref = { toolHistory: void 0, toolHistoryArchived: void 0, todoList: void 0, planVersion: 0, adherenceScore: 0 };
6225
6423
  const ctxTools = createContextTools(ref, { planningEnabled, includeGetToolResponse: false });
6226
6424
  const recoveryTool = createGetToolResponseTool(ref);
6227
- const base2 = [...userTools, ...ctxTools];
6228
- if (responseFinalizeTool) base2.push(responseFinalizeTool);
6229
- if (askUserConfig) base2.push(createAskUserQuestionTool(ref, askUserConfig));
6230
- const without = base2;
6231
- const withRec = [...without, recoveryTool];
6232
- return { stateRef: ref, toolsWithoutRecovery: without, toolsWithRecovery: withRec };
6425
+ const coreBase = [...userTools, ...ctxTools];
6426
+ if (responseFinalizeTool) coreBase.push(responseFinalizeTool);
6427
+ if (askUserConfig) coreBase.push(createAskUserQuestionTool(ref, askUserConfig));
6428
+ if (!skillsEnabled) {
6429
+ const without = coreBase;
6430
+ const withRec = [...without, recoveryTool];
6431
+ return { stateRef: ref, toolsWithoutRecovery: without, toolsWithRecovery: withRec };
6432
+ }
6433
+ const toolSet = { stateRef: ref, toolsWithoutRecovery: [], toolsWithRecovery: [] };
6434
+ const skillRegistryRef = createSkillRegistryRef();
6435
+ const skillMetaTools = createSkillTools({ registryRef: skillRegistryRef, skills, policy: skillPolicy });
6436
+ const baseWithMeta = [...coreBase, ...skillMetaTools];
6437
+ const rebuild = () => {
6438
+ const composed = composeToolSets({
6439
+ base: baseWithMeta,
6440
+ boundSkillTools: skillRegistryRef.boundSkillTools,
6441
+ recoveryTool
6442
+ });
6443
+ toolSet.toolsWithoutRecovery = composed.toolsWithoutRecovery;
6444
+ toolSet.toolsWithRecovery = composed.toolsWithRecovery;
6445
+ };
6446
+ skillRegistryRef.__onToolsChanged = rebuild;
6447
+ toolSet.skillRegistryRef = skillRegistryRef;
6448
+ rebuild();
6449
+ return toolSet;
6233
6450
  };
6234
6451
  const base = createAgent({ ...runtimeOpts, tools: factoryToolsWithoutRecovery });
6235
6452
  base.__runtime.runtimeProfile = resolved.runtimeProfile;
@@ -6280,9 +6497,9 @@ function createSmartAgent(opts) {
6280
6497
  planVersion: ref.planVersion || state.planVersion || 1
6281
6498
  };
6282
6499
  }
6283
- function systemMessage2() {
6500
+ function systemMessage2(extraBlock) {
6284
6501
  const sys = buildSystemPrompt(
6285
- [opts.systemPrompt, runtimeHint, structuredOutputHint].filter(Boolean).join("\n"),
6502
+ [opts.systemPrompt, runtimeHint, structuredOutputHint, extraBlock].filter(Boolean).join("\n"),
6286
6503
  planningEnabled,
6287
6504
  opts.name || "Agent",
6288
6505
  opts.todoListPrompt
@@ -6332,8 +6549,10 @@ function createSmartAgent(opts) {
6332
6549
  stateRef.planVersion = input.planVersion || input.plan?.version || 0;
6333
6550
  stateRef.adherenceScore = input.plan?.adherenceScore || 0;
6334
6551
  const syncPlanFromRef = (state2) => syncPlanStateWith(stateRef, state2);
6552
+ const availableSkills = skillsEnabled ? await resolveAvailableSkills(skills, { modelTier: skillPolicy.modelTier }) : [];
6553
+ const skillBlock = availableSkills.length > 0 ? buildSkillHeaderBlock(availableSkills) : void 0;
6335
6554
  const alreadyHasSystem = Array.isArray(input.messages) && input.messages[0]?.role === "system";
6336
- const seedMessages = alreadyHasSystem ? [...input.messages || []] : [systemMessage2(), ...input.messages || []];
6555
+ const seedMessages = alreadyHasSystem ? [...input.messages || []] : [systemMessage2(skillBlock), ...input.messages || []];
6337
6556
  let state = syncRuntimeTools(await syncMemory({ ...input, messages: seedMessages }), seedMessages, toolSet);
6338
6557
  let lastResult = null;
6339
6558
  let rawMessages = [...seedMessages];
@@ -9114,6 +9333,6 @@ function createProvider(config) {
9114
9333
  }
9115
9334
  }
9116
9335
 
9117
- export { AnthropicProvider, AzureProvider, BaseProvider, BedrockProvider, DEFAULT_PROFILE_CONFIGS, GuardrailPhase, InMemoryMemoryStore, NativeJsonSchemaStrategy, OpenAICompatibleProvider, OpenAIProvider, ProviderError, StructuredOutputManager, ToolBasedStrategy, VertexProvider, agentVerdictRule, buildSystemPrompt, captureSnapshot, codePresenceRule, cognipeerSink, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createAskUserQuestionTool, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGetToolResponseTool, createGuardrail, createJsonGuardrail, createManageTodoTool, createProvider, createRegexGuardrail, createResolverNode, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, defaultTokenCounter, emptyUsage, evaluateGuardrails, fileSink, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getModelCapabilities, getNestedValue, getResolvedSmartConfig, getTokenCounter, hasToolResponseRecoveryReference, httpSink, isSmartModel, jsonSchemaRule, normalizeSmartAgentOptions, otlpSink, readMemoryFacts, regexRule, resolveMemoryStore, resolveReasoning, resolveStrategy, resolveToolApprovalState, resolveUserQuestionState, restoreSnapshot, runSmartAgentEvalHarness, setTokenCounter, startStreamingSession, traceSessionToOtlp, validateReasoningConfig, withTools, writeSummaryFactsToMemory };
9336
+ export { AnthropicProvider, AzureProvider, BaseProvider, BedrockProvider, DEFAULT_PROFILE_CONFIGS, DEFAULT_SKILL_POLICY, GuardrailPhase, InMemoryMemoryStore, NativeJsonSchemaStrategy, OpenAICompatibleProvider, OpenAIProvider, ProviderError, SMALL_TIER_SKILL_POLICY, StructuredOutputManager, ToolBasedStrategy, VertexProvider, agentVerdictRule, appendBoundTools, buildSkillHeaderBlock, buildSystemPrompt, canOpenSkill, captureSnapshot, codePresenceRule, cognipeerSink, composeToolSets, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createAskUserQuestionTool, createBindSkillToolsTool, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGetToolResponseTool, createGuardrail, createJsonGuardrail, createManageTodoTool, createOpenSkillTool, createProvider, createRegexGuardrail, createResolverNode, createSkillRegistryRef, createSkillTools, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, dedupeToolsByName, defaultTokenCounter, emptyUsage, evaluateGuardrails, fileSink, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getModelCapabilities, getNestedValue, getResolvedSmartConfig, getTokenCounter, hasToolResponseRecoveryReference, httpSink, isSmartModel, jsonSchemaRule, normalizeSmartAgentOptions, otlpSink, readMemoryFacts, regexRule, resolveAvailableSkills, resolveMemoryStore, resolveReasoning, resolveStrategy, resolveToolApprovalState, resolveUserQuestionState, restoreSnapshot, runSmartAgentEvalHarness, setTokenCounter, startStreamingSession, traceSessionToOtlp, validateReasoningConfig, withTools, writeSummaryFactsToMemory };
9118
9337
  //# sourceMappingURL=index.mjs.map
9119
9338
  //# sourceMappingURL=index.mjs.map