@cognipeer/agent-sdk 0.4.7 → 0.4.9

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
@@ -315,14 +315,6 @@ type SmartAgentToolResponseConfig = {
315
315
  retryOnSchemaError?: boolean;
316
316
  fallbackPolicy?: ToolResponseRetentionPolicy;
317
317
  };
318
- type SmartAgentWatchdogConfig = {
319
- enabled?: boolean;
320
- tokenDriftThreshold?: number;
321
- overToolingSpikeThreshold?: number;
322
- contextRotThreshold?: number;
323
- autoCompaction?: boolean;
324
- autoReplanOnFailure?: boolean;
325
- };
326
318
  type SmartAgentCustomProfileConfig = {
327
319
  extends?: BuiltInRuntimeProfile;
328
320
  limits?: AgentLimits;
@@ -332,7 +324,6 @@ type SmartAgentCustomProfileConfig = {
332
324
  memory?: SmartAgentMemoryConfig;
333
325
  delegation?: SmartAgentDelegationConfig;
334
326
  toolResponses?: SmartAgentToolResponseConfig;
335
- watchdog?: SmartAgentWatchdogConfig;
336
327
  };
337
328
  type ProfileConfig = {
338
329
  limits: Required<AgentLimits>;
@@ -346,7 +337,6 @@ type ProfileConfig = {
346
337
  };
347
338
  delegation: Required<SmartAgentDelegationConfig>;
348
339
  toolResponses: Required<SmartAgentToolResponseConfig>;
349
- watchdog: Required<SmartAgentWatchdogConfig>;
350
340
  };
351
341
  type ResolvedSmartAgentConfig = ProfileConfig & {
352
342
  runtimeProfile: RuntimeProfile;
@@ -368,7 +358,6 @@ type SmartAgentOptions = {
368
358
  planning?: SmartAgentPlanningConfig;
369
359
  delegation?: SmartAgentDelegationConfig;
370
360
  toolResponses?: SmartAgentToolResponseConfig;
371
- watchdog?: SmartAgentWatchdogConfig;
372
361
  systemPrompt?: string;
373
362
  todoListPrompt?: string;
374
363
  /** @deprecated Use planning.mode="todo" */
@@ -673,13 +662,6 @@ type SmartState = AgentState & {
673
662
  adherenceScore?: number;
674
663
  } | null;
675
664
  planVersion?: number;
676
- watchdog?: {
677
- tokenDrift?: number;
678
- contextRotScore?: number;
679
- overToolingRate?: number;
680
- compactions?: number;
681
- lastAction?: string;
682
- };
683
665
  };
684
666
  type ToolCallEvent = {
685
667
  type: "tool_call";
@@ -866,6 +848,9 @@ type CancellationTokenLike = {
866
848
  dispose(): void;
867
849
  } | void;
868
850
  };
851
+ type AbortSignalLike = {
852
+ readonly aborted: boolean;
853
+ };
869
854
  type ProgressUpdate = {
870
855
  stage?: string;
871
856
  message?: string;
@@ -881,7 +866,7 @@ type InvokeConfig = RunnableConfig & {
881
866
  onProgress?: (progress: ProgressUpdate) => void;
882
867
  onStream?: (chunk: StreamChunk) => void;
883
868
  stream?: boolean;
884
- cancellationToken?: CancellationTokenLike | AbortSignal;
869
+ cancellationToken?: CancellationTokenLike | AbortSignalLike;
885
870
  timeoutMs?: number;
886
871
  limits?: Partial<AgentLimits>;
887
872
  onStateChange?: (state: SmartState) => boolean;
@@ -1228,4 +1213,4 @@ declare function generateSpanId(): string;
1228
1213
  */
1229
1214
  declare function startStreamingSession(session: TraceSessionRuntime | undefined, agentRuntime?: AgentRuntimeConfig): Promise<void>;
1230
1215
 
1231
- export { type AIMessage, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, type BuiltInRuntimeProfile, type CancellationTokenLike, type CancelledEvent, type ChildContextPolicy, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type ContextPolicy, 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 GuardrailContext, type GuardrailDisposition, type GuardrailEvent, type GuardrailIncident, type GuardrailOutcome, GuardrailPhase, type GuardrailRule, type HandoffDescriptor, type HandoffEvent, InMemoryMemoryStore, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, type MemoryFact, type MemoryProviderKind, type MemoryReadPolicy, type MemoryScope, type MemoryStore, type MemoryWritePolicy, type Message, type MetadataEvent, type PendingToolApproval, type PlanEvent, type PlanStepRecord, type PlanningMode, type ProfileConfig, type ProgressEvent, type ProgressUpdate, 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 SmartAgentWatchdogConfig, type SmartModel, type SmartState, type SmartToolFn, type SnapshotOptions, type SnapshotRuntimeHint, type StreamChunk, type StreamEvent, type StructuredSummary, type SummarizationEvent, type SummarizationMode, type SummaryFactItem, type SummaryIntegrityCheck, type TokenLimits, type ToolApprovalEvent, type ToolApprovalResolution, type ToolApprovalStatus, type ToolCallEvent, type ToolInterface, type ToolResponseClassification, type ToolResponseRetentionPolicy, 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 TraceToolResultSection, type TracingConfig, type TracingMode, agentVerdictRule, applyTokenLimits, buildSystemPrompt, captureSnapshot, codePresenceRule, cognipeerSink, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGuardrail, createJsonGuardrail, createRegexGuardrail, createResolverNode, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, evaluateGuardrails, fileSink, fromLangchainModel, fromLangchainTools, generateSpanId, generateTraceId, getResolvedSmartConfig, httpSink, isSmartModel, jsonSchemaRule, normalizeSmartAgentOptions, otlpSink, readMemoryFacts, regexRule, renderMemoryFacts, resolveMemoryStore, resolveToolApprovalState, restoreSnapshot, runSmartAgentEvalHarness, startStreamingSession, traceSessionToOtlp, withTools, writeSummaryFactsToMemory };
1216
+ export { type AIMessage, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, type BuiltInRuntimeProfile, type CancellationTokenLike, type CancelledEvent, type ChildContextPolicy, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type ContextPolicy, 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 GuardrailContext, type GuardrailDisposition, type GuardrailEvent, type GuardrailIncident, type GuardrailOutcome, GuardrailPhase, type GuardrailRule, type HandoffDescriptor, type HandoffEvent, InMemoryMemoryStore, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, type MemoryFact, type MemoryProviderKind, type MemoryReadPolicy, type MemoryScope, type MemoryStore, type MemoryWritePolicy, type Message, type MetadataEvent, type PendingToolApproval, type PlanEvent, type PlanStepRecord, type PlanningMode, type ProfileConfig, type ProgressEvent, type ProgressUpdate, 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 StructuredSummary, type SummarizationEvent, type SummarizationMode, type SummaryFactItem, type SummaryIntegrityCheck, type TokenLimits, type ToolApprovalEvent, type ToolApprovalResolution, type ToolApprovalStatus, type ToolCallEvent, type ToolInterface, type ToolResponseClassification, type ToolResponseRetentionPolicy, 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 TraceToolResultSection, type TracingConfig, type TracingMode, agentVerdictRule, applyTokenLimits, buildSystemPrompt, captureSnapshot, codePresenceRule, cognipeerSink, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGuardrail, createJsonGuardrail, createRegexGuardrail, createResolverNode, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, evaluateGuardrails, fileSink, fromLangchainModel, fromLangchainTools, generateSpanId, generateTraceId, getResolvedSmartConfig, httpSink, isSmartModel, jsonSchemaRule, normalizeSmartAgentOptions, otlpSink, readMemoryFacts, regexRule, renderMemoryFacts, resolveMemoryStore, resolveToolApprovalState, restoreSnapshot, runSmartAgentEvalHarness, startStreamingSession, traceSessionToOtlp, withTools, writeSummaryFactsToMemory };
package/dist/index.d.ts CHANGED
@@ -315,14 +315,6 @@ type SmartAgentToolResponseConfig = {
315
315
  retryOnSchemaError?: boolean;
316
316
  fallbackPolicy?: ToolResponseRetentionPolicy;
317
317
  };
318
- type SmartAgentWatchdogConfig = {
319
- enabled?: boolean;
320
- tokenDriftThreshold?: number;
321
- overToolingSpikeThreshold?: number;
322
- contextRotThreshold?: number;
323
- autoCompaction?: boolean;
324
- autoReplanOnFailure?: boolean;
325
- };
326
318
  type SmartAgentCustomProfileConfig = {
327
319
  extends?: BuiltInRuntimeProfile;
328
320
  limits?: AgentLimits;
@@ -332,7 +324,6 @@ type SmartAgentCustomProfileConfig = {
332
324
  memory?: SmartAgentMemoryConfig;
333
325
  delegation?: SmartAgentDelegationConfig;
334
326
  toolResponses?: SmartAgentToolResponseConfig;
335
- watchdog?: SmartAgentWatchdogConfig;
336
327
  };
337
328
  type ProfileConfig = {
338
329
  limits: Required<AgentLimits>;
@@ -346,7 +337,6 @@ type ProfileConfig = {
346
337
  };
347
338
  delegation: Required<SmartAgentDelegationConfig>;
348
339
  toolResponses: Required<SmartAgentToolResponseConfig>;
349
- watchdog: Required<SmartAgentWatchdogConfig>;
350
340
  };
351
341
  type ResolvedSmartAgentConfig = ProfileConfig & {
352
342
  runtimeProfile: RuntimeProfile;
@@ -368,7 +358,6 @@ type SmartAgentOptions = {
368
358
  planning?: SmartAgentPlanningConfig;
369
359
  delegation?: SmartAgentDelegationConfig;
370
360
  toolResponses?: SmartAgentToolResponseConfig;
371
- watchdog?: SmartAgentWatchdogConfig;
372
361
  systemPrompt?: string;
373
362
  todoListPrompt?: string;
374
363
  /** @deprecated Use planning.mode="todo" */
@@ -673,13 +662,6 @@ type SmartState = AgentState & {
673
662
  adherenceScore?: number;
674
663
  } | null;
675
664
  planVersion?: number;
676
- watchdog?: {
677
- tokenDrift?: number;
678
- contextRotScore?: number;
679
- overToolingRate?: number;
680
- compactions?: number;
681
- lastAction?: string;
682
- };
683
665
  };
684
666
  type ToolCallEvent = {
685
667
  type: "tool_call";
@@ -866,6 +848,9 @@ type CancellationTokenLike = {
866
848
  dispose(): void;
867
849
  } | void;
868
850
  };
851
+ type AbortSignalLike = {
852
+ readonly aborted: boolean;
853
+ };
869
854
  type ProgressUpdate = {
870
855
  stage?: string;
871
856
  message?: string;
@@ -881,7 +866,7 @@ type InvokeConfig = RunnableConfig & {
881
866
  onProgress?: (progress: ProgressUpdate) => void;
882
867
  onStream?: (chunk: StreamChunk) => void;
883
868
  stream?: boolean;
884
- cancellationToken?: CancellationTokenLike | AbortSignal;
869
+ cancellationToken?: CancellationTokenLike | AbortSignalLike;
885
870
  timeoutMs?: number;
886
871
  limits?: Partial<AgentLimits>;
887
872
  onStateChange?: (state: SmartState) => boolean;
@@ -1228,4 +1213,4 @@ declare function generateSpanId(): string;
1228
1213
  */
1229
1214
  declare function startStreamingSession(session: TraceSessionRuntime | undefined, agentRuntime?: AgentRuntimeConfig): Promise<void>;
1230
1215
 
1231
- export { type AIMessage, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, type BuiltInRuntimeProfile, type CancellationTokenLike, type CancelledEvent, type ChildContextPolicy, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type ContextPolicy, 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 GuardrailContext, type GuardrailDisposition, type GuardrailEvent, type GuardrailIncident, type GuardrailOutcome, GuardrailPhase, type GuardrailRule, type HandoffDescriptor, type HandoffEvent, InMemoryMemoryStore, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, type MemoryFact, type MemoryProviderKind, type MemoryReadPolicy, type MemoryScope, type MemoryStore, type MemoryWritePolicy, type Message, type MetadataEvent, type PendingToolApproval, type PlanEvent, type PlanStepRecord, type PlanningMode, type ProfileConfig, type ProgressEvent, type ProgressUpdate, 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 SmartAgentWatchdogConfig, type SmartModel, type SmartState, type SmartToolFn, type SnapshotOptions, type SnapshotRuntimeHint, type StreamChunk, type StreamEvent, type StructuredSummary, type SummarizationEvent, type SummarizationMode, type SummaryFactItem, type SummaryIntegrityCheck, type TokenLimits, type ToolApprovalEvent, type ToolApprovalResolution, type ToolApprovalStatus, type ToolCallEvent, type ToolInterface, type ToolResponseClassification, type ToolResponseRetentionPolicy, 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 TraceToolResultSection, type TracingConfig, type TracingMode, agentVerdictRule, applyTokenLimits, buildSystemPrompt, captureSnapshot, codePresenceRule, cognipeerSink, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGuardrail, createJsonGuardrail, createRegexGuardrail, createResolverNode, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, evaluateGuardrails, fileSink, fromLangchainModel, fromLangchainTools, generateSpanId, generateTraceId, getResolvedSmartConfig, httpSink, isSmartModel, jsonSchemaRule, normalizeSmartAgentOptions, otlpSink, readMemoryFacts, regexRule, renderMemoryFacts, resolveMemoryStore, resolveToolApprovalState, restoreSnapshot, runSmartAgentEvalHarness, startStreamingSession, traceSessionToOtlp, withTools, writeSummaryFactsToMemory };
1216
+ export { type AIMessage, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, type BuiltInRuntimeProfile, type CancellationTokenLike, type CancelledEvent, type ChildContextPolicy, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type ContextPolicy, 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 GuardrailContext, type GuardrailDisposition, type GuardrailEvent, type GuardrailIncident, type GuardrailOutcome, GuardrailPhase, type GuardrailRule, type HandoffDescriptor, type HandoffEvent, InMemoryMemoryStore, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, type MemoryFact, type MemoryProviderKind, type MemoryReadPolicy, type MemoryScope, type MemoryStore, type MemoryWritePolicy, type Message, type MetadataEvent, type PendingToolApproval, type PlanEvent, type PlanStepRecord, type PlanningMode, type ProfileConfig, type ProgressEvent, type ProgressUpdate, 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 StructuredSummary, type SummarizationEvent, type SummarizationMode, type SummaryFactItem, type SummaryIntegrityCheck, type TokenLimits, type ToolApprovalEvent, type ToolApprovalResolution, type ToolApprovalStatus, type ToolCallEvent, type ToolInterface, type ToolResponseClassification, type ToolResponseRetentionPolicy, 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 TraceToolResultSection, type TracingConfig, type TracingMode, agentVerdictRule, applyTokenLimits, buildSystemPrompt, captureSnapshot, codePresenceRule, cognipeerSink, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGuardrail, createJsonGuardrail, createRegexGuardrail, createResolverNode, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, evaluateGuardrails, fileSink, fromLangchainModel, fromLangchainTools, generateSpanId, generateTraceId, getResolvedSmartConfig, httpSink, isSmartModel, jsonSchemaRule, normalizeSmartAgentOptions, otlpSink, readMemoryFacts, regexRule, renderMemoryFacts, resolveMemoryStore, resolveToolApprovalState, restoreSnapshot, runSmartAgentEvalHarness, startStreamingSession, traceSessionToOtlp, withTools, writeSummaryFactsToMemory };
package/dist/index.mjs CHANGED
@@ -1783,14 +1783,6 @@ var DEFAULT_PROFILE_CONFIGS = {
1783
1783
  schemaValidation: "strict",
1784
1784
  retryOnSchemaError: true,
1785
1785
  fallbackPolicy: "keep_structured"
1786
- },
1787
- watchdog: {
1788
- enabled: true,
1789
- tokenDriftThreshold: 1200,
1790
- overToolingSpikeThreshold: 0.7,
1791
- contextRotThreshold: 0.65,
1792
- autoCompaction: true,
1793
- autoReplanOnFailure: true
1794
1786
  }
1795
1787
  },
1796
1788
  balanced: {
@@ -1848,14 +1840,6 @@ var DEFAULT_PROFILE_CONFIGS = {
1848
1840
  schemaValidation: "strict",
1849
1841
  retryOnSchemaError: true,
1850
1842
  fallbackPolicy: "keep_structured"
1851
- },
1852
- watchdog: {
1853
- enabled: true,
1854
- tokenDriftThreshold: 1800,
1855
- overToolingSpikeThreshold: 0.6,
1856
- contextRotThreshold: 0.55,
1857
- autoCompaction: true,
1858
- autoReplanOnFailure: true
1859
1843
  }
1860
1844
  },
1861
1845
  deep: {
@@ -1913,14 +1897,6 @@ var DEFAULT_PROFILE_CONFIGS = {
1913
1897
  schemaValidation: "strict",
1914
1898
  retryOnSchemaError: true,
1915
1899
  fallbackPolicy: "keep_structured"
1916
- },
1917
- watchdog: {
1918
- enabled: true,
1919
- tokenDriftThreshold: 2200,
1920
- overToolingSpikeThreshold: 0.55,
1921
- contextRotThreshold: 0.5,
1922
- autoCompaction: true,
1923
- autoReplanOnFailure: true
1924
1900
  }
1925
1901
  },
1926
1902
  research: {
@@ -1978,14 +1954,6 @@ var DEFAULT_PROFILE_CONFIGS = {
1978
1954
  schemaValidation: "strict",
1979
1955
  retryOnSchemaError: true,
1980
1956
  fallbackPolicy: "keep_structured"
1981
- },
1982
- watchdog: {
1983
- enabled: true,
1984
- tokenDriftThreshold: 2600,
1985
- overToolingSpikeThreshold: 0.5,
1986
- contextRotThreshold: 0.45,
1987
- autoCompaction: true,
1988
- autoReplanOnFailure: true
1989
1957
  }
1990
1958
  }
1991
1959
  };
@@ -2062,11 +2030,6 @@ function normalizeSmartAgentOptions(opts) {
2062
2030
  ...opts.toolResponses?.toolResponseRetentionByTool || {}
2063
2031
  },
2064
2032
  criticalTools: opts.toolResponses?.criticalTools ?? customProfile.toolResponses?.criticalTools ?? preset.toolResponses.criticalTools
2065
- },
2066
- watchdog: {
2067
- ...preset.watchdog,
2068
- ...customProfile.watchdog || {},
2069
- ...opts.watchdog || {}
2070
2033
  }
2071
2034
  };
2072
2035
  }
@@ -2297,7 +2260,7 @@ function createToolsNode(initialTools, opts) {
2297
2260
  if (toolCallId) {
2298
2261
  ctx.__toolSchemaError = { toolName, toolCallId, message };
2299
2262
  }
2300
- if (resolved.watchdog.autoReplanOnFailure) {
2263
+ if (resolved.planning.replanPolicy === "on_failure") {
2301
2264
  ctx.__planNeedsReplan = true;
2302
2265
  }
2303
2266
  state.ctx = ctx;
@@ -3184,7 +3147,23 @@ function createAgent(opts) {
3184
3147
  state = { ...state, ...await finalizeNode(state) };
3185
3148
  continue;
3186
3149
  }
3187
- if (toolCalls.length === 0) break;
3150
+ if (toolCalls.length === 0) {
3151
+ if (opts.outputSchema && !state.ctx?.__finalizedDueToStructuredOutput && !state.ctx?.__structuredOutputForceFinalize) {
3152
+ const forceMsg = {
3153
+ role: "system",
3154
+ content: [
3155
+ "A structured output schema is active.",
3156
+ "You MUST now call tool `response` with the final JSON object that matches the schema.",
3157
+ "Do not write the JSON in the assistant message.",
3158
+ "Call `response` exactly once, then stop."
3159
+ ].join("\n")
3160
+ };
3161
+ const ctx = { ...state.ctx || {}, __structuredOutputForceFinalize: true };
3162
+ state = { ...state, messages: [...state.messages, forceMsg], ctx };
3163
+ continue;
3164
+ }
3165
+ break;
3166
+ }
3188
3167
  onProgress?.({ stage: "tools", message: "Running tools" });
3189
3168
  if (cancelIfRequested("before_tools")) break;
3190
3169
  state = { ...state, ...await toolsNode(state) };
@@ -3197,31 +3176,31 @@ function createAgent(opts) {
3197
3176
  const last = state.messages[state.messages.length - 1];
3198
3177
  const lastHasToolCalls = Array.isArray(last?.tool_calls) && last.tool_calls.length > 0;
3199
3178
  if (!lastHasToolCalls) {
3200
- const forceMsg = {
3201
- role: "system",
3202
- content: [
3203
- "A structured output schema is active.",
3204
- "You MUST now call tool `response` with the final JSON object that matches the schema.",
3205
- "Do not write the JSON in the assistant message.",
3206
- "Call `response` exactly once, then stop."
3207
- ].join("\n")
3208
- };
3209
3179
  const alreadyForced = Boolean(state.ctx?.__structuredOutputForceFinalize);
3210
- if (!alreadyForced) {
3211
- const ctx = { ...state.ctx || {}, __structuredOutputForceFinalize: true };
3212
- state = { ...state, messages: [...state.messages, forceMsg], ctx };
3213
- try {
3214
- state = { ...state, ...await agentCore(state) };
3215
- const lastAfter = state.messages[state.messages.length - 1];
3216
- const toolCallsAfter = Array.isArray(lastAfter?.tool_calls) ? lastAfter.tool_calls : [];
3217
- if (toolCallsAfter.length > 0) {
3218
- state = { ...state, ...await toolsNode(state) };
3219
- }
3220
- } catch (err) {
3221
- const errMsg = err instanceof Error ? err.message : String(err);
3222
- emit?.({ type: "metadata", error: `Structured output force-finalize failed: ${errMsg}` });
3223
- throw err;
3180
+ if (alreadyForced) {
3181
+ const finalNudge = {
3182
+ role: "system",
3183
+ content: [
3184
+ "A structured output schema is active.",
3185
+ "You MUST now call tool `response` with the final JSON object that matches the schema.",
3186
+ "Do not write the JSON in the assistant message.",
3187
+ "Call `response` exactly once, then stop.",
3188
+ "Do NOT call any other tools. Produce the response NOW based on whatever information you have gathered so far."
3189
+ ].join("\n")
3190
+ };
3191
+ state = { ...state, messages: [...state.messages, finalNudge] };
3192
+ }
3193
+ try {
3194
+ state = { ...state, ...await agentCore(state) };
3195
+ const lastAfter = state.messages[state.messages.length - 1];
3196
+ const toolCallsAfter = Array.isArray(lastAfter?.tool_calls) ? lastAfter.tool_calls : [];
3197
+ if (toolCallsAfter.length > 0) {
3198
+ state = { ...state, ...await toolsNode(state) };
3224
3199
  }
3200
+ } catch (err) {
3201
+ const errMsg = err instanceof Error ? err.message : String(err);
3202
+ emit?.({ type: "metadata", error: `Structured output force-finalize failed: ${errMsg}` });
3203
+ throw err;
3225
3204
  }
3226
3205
  }
3227
3206
  }
@@ -3596,15 +3575,6 @@ function buildModelMessages(state, config) {
3596
3575
  ];
3597
3576
  return clampToBudget(assembled, config.limits.maxContextTokens);
3598
3577
  }
3599
- function estimateContextRotScore(state) {
3600
- const summaryCount = state.summaryRecords?.length || 0;
3601
- const archivedCount = state.toolHistoryArchived?.length || 0;
3602
- const messageCount = state.messages?.length || 0;
3603
- const summarizedMessages = state.messages?.filter((message) => message.role === "tool" && typeof message.content === "string" && (message.content === "SUMMARIZED" || message.content.startsWith("SUMMARIZED_TOOL_RESPONSE"))).length || 0;
3604
- const numerator = summaryCount * 2 + archivedCount + summarizedMessages;
3605
- const denominator = Math.max(messageCount, 1);
3606
- return Number((numerator / denominator).toFixed(3));
3607
- }
3608
3578
 
3609
3579
  // src/nodes/contextSummarize.ts
3610
3580
  var systemMessage = (content) => ({ role: "system", content });
@@ -3749,6 +3719,9 @@ function findToolHistoryEntry(state, toolCallId, toolName) {
3749
3719
  }
3750
3720
  }
3751
3721
  }
3722
+ if (!toolName) {
3723
+ return void 0;
3724
+ }
3752
3725
  for (let index = entries.length - 1; index >= 0; index -= 1) {
3753
3726
  const entry = entries[index];
3754
3727
  if (entry?.toolName === toolName) {
@@ -3837,8 +3810,20 @@ function createContextSummarizeNode(opts) {
3837
3810
  const messages = state.messages || [];
3838
3811
  const onEvent = state.ctx?.__onEvent;
3839
3812
  const traceSession = state.ctx?.__traceSession;
3813
+ const toolResponsesConfigEarly = resolved.toolResponses;
3840
3814
  const compressableMessages = messages.filter(
3841
- (m) => m.role === "tool" && !isSummarizedToolPlaceholder(m.content) && !isSyntheticSummaryToolMessage(m)
3815
+ (m) => {
3816
+ if (m.role !== "tool") return false;
3817
+ if (isSummarizedToolPlaceholder(m.content)) return false;
3818
+ if (isSyntheticSummaryToolMessage(m)) return false;
3819
+ const histEntry = findToolHistoryEntry(state, m.tool_call_id, m.name);
3820
+ if (histEntry?.retentionPolicy === "keep_full") return false;
3821
+ if (!histEntry?.retentionPolicy) {
3822
+ const byTool = toolResponsesConfigEarly.toolResponseRetentionByTool?.[m.name || ""];
3823
+ if ((byTool || toolResponsesConfigEarly.defaultPolicy) === "keep_full") return false;
3824
+ }
3825
+ return true;
3826
+ }
3842
3827
  );
3843
3828
  if (compressableMessages.length === 0) {
3844
3829
  return {};
@@ -3859,6 +3844,13 @@ function createContextSummarizeNode(opts) {
3859
3844
  else if (Array.isArray(m.content)) {
3860
3845
  content = m.content.map((c) => c.text || JSON.stringify(c)).join(" ");
3861
3846
  }
3847
+ if (m.role === "tool" && isSummarizedToolPlaceholder(content)) {
3848
+ const historyEntry = findToolHistoryEntry(state, m.tool_call_id, m.name);
3849
+ if (historyEntry) {
3850
+ const original = historyEntry.rawOutput ?? historyEntry.output;
3851
+ content = typeof original === "string" ? original : JSON.stringify(original);
3852
+ }
3853
+ }
3862
3854
  const maxContentLength = 2e3;
3863
3855
  if (content.length > maxContentLength) {
3864
3856
  content = content.substring(0, maxContentLength) + "... [TRUNCATED]";
@@ -3994,6 +3986,23 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
3994
3986
  });
3995
3987
  }
3996
3988
  });
3989
+ const protectedToolCallIds = /* @__PURE__ */ new Set();
3990
+ for (let i = messages.length - 1; i >= 0; i--) {
3991
+ const m = messages[i];
3992
+ if (m.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
3993
+ const thisToolCallIds = new Set(m.tool_calls.map((tc) => tc.id).filter(Boolean));
3994
+ const otherCompressable = compressableMessages.filter(
3995
+ (cm) => !thisToolCallIds.has(cm.tool_call_id)
3996
+ );
3997
+ if (otherCompressable.length > 0) {
3998
+ for (const tc of m.tool_calls) {
3999
+ if (tc.id) protectedToolCallIds.add(tc.id);
4000
+ }
4001
+ }
4002
+ break;
4003
+ }
4004
+ }
4005
+ const toolResponsesConfig = resolved.toolResponses;
3997
4006
  const newMessages = messages.map((m) => {
3998
4007
  if (m.role === "tool") {
3999
4008
  if (isSyntheticSummaryToolMessage(m)) {
@@ -4004,6 +4013,16 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
4004
4013
  return null;
4005
4014
  }
4006
4015
  if (isSummarizedToolPlaceholder(m.content)) return m;
4016
+ if (toolCallId && protectedToolCallIds.has(toolCallId)) return m;
4017
+ const toolName = m.name || "";
4018
+ const historyEntry = findToolHistoryEntry(state, toolCallId, toolName);
4019
+ const entryRetention = historyEntry?.retentionPolicy;
4020
+ if (entryRetention === "keep_full") return m;
4021
+ if (!entryRetention) {
4022
+ const byTool = toolResponsesConfig.toolResponseRetentionByTool?.[toolName];
4023
+ const configPolicy = byTool || toolResponsesConfig.defaultPolicy;
4024
+ if (configPolicy === "keep_full") return m;
4025
+ }
4007
4026
  return {
4008
4027
  ...m,
4009
4028
  content: buildSummarizedToolMessage(m, state)
@@ -4011,6 +4030,12 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
4011
4030
  }
4012
4031
  return m;
4013
4032
  }).filter((m) => m !== null);
4033
+ const actuallyCompressed = newMessages.filter(
4034
+ (m) => m.role === "tool" && typeof m.content === "string" && m.content.startsWith("SUMMARIZED_TOOL_RESPONSE") && !messages.some((orig) => orig.tool_call_id === m.tool_call_id && isSummarizedToolPlaceholder(orig.content))
4035
+ );
4036
+ if (actuallyCompressed.length === 0) {
4037
+ return {};
4038
+ }
4014
4039
  const validatedMessages = validateMessageSequence(newMessages);
4015
4040
  const summaryToolCallId = `call_summary_${Date.now()}`;
4016
4041
  const assistantSummaryCall = {
@@ -4086,12 +4111,7 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
4086
4111
  return {
4087
4112
  messages: finalMessages,
4088
4113
  summaries,
4089
- summaryRecords,
4090
- watchdog: {
4091
- ...state.watchdog || {},
4092
- compactions: (state.watchdog?.compactions || 0) + 1,
4093
- lastAction: "summarized"
4094
- }
4114
+ summaryRecords
4095
4115
  };
4096
4116
  };
4097
4117
  }
@@ -4390,8 +4410,7 @@ function needsSummarization(state, opts, summarizationEnabled) {
4390
4410
  return "";
4391
4411
  }).join("\n");
4392
4412
  const tokenCount = countApproxTokens(allText);
4393
- const contextRotScore = state.watchdog?.contextRotScore || 0;
4394
- const needsSum = tokenCount > maxTok || resolved.watchdog.enabled && resolved.watchdog.autoCompaction && contextRotScore >= resolved.watchdog.contextRotThreshold;
4413
+ const needsSum = tokenCount > maxTok;
4395
4414
  if (process.env.DEBUG_SUMMARIZATION) {
4396
4415
  const msgCount = (state.messages || []).length;
4397
4416
  const toolMsgs = (state.messages || []).filter((m) => m.role === "tool");
@@ -4401,7 +4420,7 @@ function needsSummarization(state, opts, summarizationEnabled) {
4401
4420
  });
4402
4421
  console.log(`[Summarization] Messages: ${msgCount}, Tool messages: ${toolMsgs.length}`);
4403
4422
  toolDetails.forEach((d) => console.log(` ${d}`));
4404
- console.log(`[Summarization] Token count: ${tokenCount}, Max: ${maxTok}, Context rot: ${contextRotScore}, Needs summarization: ${needsSum}`);
4423
+ console.log(`[Summarization] Token count: ${tokenCount}, Max: ${maxTok}, Needs summarization: ${needsSum}`);
4405
4424
  }
4406
4425
  return needsSum;
4407
4426
  } catch {
@@ -4555,7 +4574,6 @@ function createSmartAgent(opts) {
4555
4574
  delegation: resolved.delegation,
4556
4575
  memory: { ...resolved.memory, store: memoryStore },
4557
4576
  toolResponses: resolved.toolResponses,
4558
- watchdog: resolved.watchdog,
4559
4577
  useTodoList: planningEnabled
4560
4578
  };
4561
4579
  const stateRef = { toolHistory: void 0, toolHistoryArchived: void 0, todoList: void 0, planVersion: 0, adherenceScore: 0 };
@@ -4638,7 +4656,6 @@ function createSmartAgent(opts) {
4638
4656
  let rawMessages = [...seedMessages];
4639
4657
  const effectiveMaxToolCalls = config?.limits?.maxToolCalls ?? resolved.limits.maxToolCalls ?? 10;
4640
4658
  const iterationLimit = Math.max(effectiveMaxToolCalls * 3 + 5, 30);
4641
- let previousTokenCount = countApproxTokens(rawMessages.map((message) => typeof message.content === "string" ? message.content : JSON.stringify(message.content)).join("\n"));
4642
4659
  for (let i = 0; i < iterationLimit; i++) {
4643
4660
  state = { ...state, messages: rawMessages };
4644
4661
  const next = summarizationEnabled ? decideBefore(state) : "agent";
@@ -4672,27 +4689,6 @@ function createSmartAgent(opts) {
4672
4689
  state = syncPlanState(await syncMemory(state));
4673
4690
  stateRef.toolHistory = state.toolHistory;
4674
4691
  stateRef.toolHistoryArchived = state.toolHistoryArchived;
4675
- const currentTokenCount = countApproxTokens(rawMessages.map((message) => typeof message.content === "string" ? message.content : JSON.stringify(message.content)).join("\n"));
4676
- const tokenDrift = Math.max(0, currentTokenCount - previousTokenCount);
4677
- const toolMessagesThisTurn = appendedMessages.filter((message) => message.role === "tool").length;
4678
- const overToolingRate = appendedMessages.length === 0 ? 0 : Number((toolMessagesThisTurn / appendedMessages.length).toFixed(2));
4679
- state = {
4680
- ...state,
4681
- watchdog: {
4682
- tokenDrift,
4683
- contextRotScore: estimateContextRotScore(state),
4684
- overToolingRate,
4685
- compactions: state.watchdog?.compactions || 0,
4686
- lastAction: appendedMessages.length > 0 ? "agent_turn" : state.watchdog?.lastAction
4687
- }
4688
- };
4689
- previousTokenCount = currentTokenCount;
4690
- if (resolved.watchdog.enabled && resolved.watchdog.autoCompaction) {
4691
- const shouldCompact = tokenDrift >= resolved.watchdog.tokenDriftThreshold || (state.watchdog?.overToolingRate || 0) >= resolved.watchdog.overToolingSpikeThreshold || (state.watchdog?.contextRotScore || 0) >= resolved.watchdog.contextRotThreshold;
4692
- if (shouldCompact) {
4693
- state = { ...state, ctx: { ...state.ctx || {}, __needsSummarization: true } };
4694
- }
4695
- }
4696
4692
  if (state.ctx?.__needsSummarization && summarizer) {
4697
4693
  const ctx = { ...state.ctx || {} };
4698
4694
  delete ctx.__needsSummarization;
@@ -4724,12 +4720,12 @@ function createSmartAgent(opts) {
4724
4720
  }
4725
4721
  if (state.summaries && state.summaries.length > 0) {
4726
4722
  if (lastResult.state) {
4727
- lastResult = { ...lastResult, state: { ...lastResult.state, summaries: state.summaries, summaryRecords: state.summaryRecords, memoryFacts: state.memoryFacts, plan: state.plan, planVersion: state.planVersion, watchdog: state.watchdog, messages: rawMessages } };
4723
+ lastResult = { ...lastResult, state: { ...lastResult.state, summaries: state.summaries, summaryRecords: state.summaryRecords, memoryFacts: state.memoryFacts, plan: state.plan, planVersion: state.planVersion, messages: rawMessages } };
4728
4724
  } else {
4729
- lastResult = { ...lastResult, state: { ...state, summaries: state.summaries, summaryRecords: state.summaryRecords, memoryFacts: state.memoryFacts, plan: state.plan, planVersion: state.planVersion, watchdog: state.watchdog, messages: rawMessages } };
4725
+ lastResult = { ...lastResult, state: { ...state, summaries: state.summaries, summaryRecords: state.summaryRecords, memoryFacts: state.memoryFacts, plan: state.plan, planVersion: state.planVersion, messages: rawMessages } };
4730
4726
  }
4731
4727
  } else if (lastResult.state) {
4732
- lastResult = { ...lastResult, state: { ...lastResult.state, memoryFacts: state.memoryFacts, plan: state.plan, planVersion: state.planVersion, watchdog: state.watchdog, messages: rawMessages } };
4728
+ lastResult = { ...lastResult, state: { ...lastResult.state, memoryFacts: state.memoryFacts, plan: state.plan, planVersion: state.planVersion, messages: rawMessages } };
4733
4729
  }
4734
4730
  return lastResult;
4735
4731
  },