@cognipeer/agent-sdk 0.4.7 → 0.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1793,14 +1793,6 @@ var DEFAULT_PROFILE_CONFIGS = {
1793
1793
  schemaValidation: "strict",
1794
1794
  retryOnSchemaError: true,
1795
1795
  fallbackPolicy: "keep_structured"
1796
- },
1797
- watchdog: {
1798
- enabled: true,
1799
- tokenDriftThreshold: 1200,
1800
- overToolingSpikeThreshold: 0.7,
1801
- contextRotThreshold: 0.65,
1802
- autoCompaction: true,
1803
- autoReplanOnFailure: true
1804
1796
  }
1805
1797
  },
1806
1798
  balanced: {
@@ -1858,14 +1850,6 @@ var DEFAULT_PROFILE_CONFIGS = {
1858
1850
  schemaValidation: "strict",
1859
1851
  retryOnSchemaError: true,
1860
1852
  fallbackPolicy: "keep_structured"
1861
- },
1862
- watchdog: {
1863
- enabled: true,
1864
- tokenDriftThreshold: 1800,
1865
- overToolingSpikeThreshold: 0.6,
1866
- contextRotThreshold: 0.55,
1867
- autoCompaction: true,
1868
- autoReplanOnFailure: true
1869
1853
  }
1870
1854
  },
1871
1855
  deep: {
@@ -1923,14 +1907,6 @@ var DEFAULT_PROFILE_CONFIGS = {
1923
1907
  schemaValidation: "strict",
1924
1908
  retryOnSchemaError: true,
1925
1909
  fallbackPolicy: "keep_structured"
1926
- },
1927
- watchdog: {
1928
- enabled: true,
1929
- tokenDriftThreshold: 2200,
1930
- overToolingSpikeThreshold: 0.55,
1931
- contextRotThreshold: 0.5,
1932
- autoCompaction: true,
1933
- autoReplanOnFailure: true
1934
1910
  }
1935
1911
  },
1936
1912
  research: {
@@ -1988,14 +1964,6 @@ var DEFAULT_PROFILE_CONFIGS = {
1988
1964
  schemaValidation: "strict",
1989
1965
  retryOnSchemaError: true,
1990
1966
  fallbackPolicy: "keep_structured"
1991
- },
1992
- watchdog: {
1993
- enabled: true,
1994
- tokenDriftThreshold: 2600,
1995
- overToolingSpikeThreshold: 0.5,
1996
- contextRotThreshold: 0.45,
1997
- autoCompaction: true,
1998
- autoReplanOnFailure: true
1999
1967
  }
2000
1968
  }
2001
1969
  };
@@ -2072,11 +2040,6 @@ function normalizeSmartAgentOptions(opts) {
2072
2040
  ...opts.toolResponses?.toolResponseRetentionByTool || {}
2073
2041
  },
2074
2042
  criticalTools: opts.toolResponses?.criticalTools ?? customProfile.toolResponses?.criticalTools ?? preset.toolResponses.criticalTools
2075
- },
2076
- watchdog: {
2077
- ...preset.watchdog,
2078
- ...customProfile.watchdog || {},
2079
- ...opts.watchdog || {}
2080
2043
  }
2081
2044
  };
2082
2045
  }
@@ -2307,7 +2270,7 @@ function createToolsNode(initialTools, opts) {
2307
2270
  if (toolCallId) {
2308
2271
  ctx.__toolSchemaError = { toolName, toolCallId, message };
2309
2272
  }
2310
- if (resolved.watchdog.autoReplanOnFailure) {
2273
+ if (resolved.planning.replanPolicy === "on_failure") {
2311
2274
  ctx.__planNeedsReplan = true;
2312
2275
  }
2313
2276
  state.ctx = ctx;
@@ -3606,15 +3569,6 @@ function buildModelMessages(state, config) {
3606
3569
  ];
3607
3570
  return clampToBudget(assembled, config.limits.maxContextTokens);
3608
3571
  }
3609
- function estimateContextRotScore(state) {
3610
- const summaryCount = state.summaryRecords?.length || 0;
3611
- const archivedCount = state.toolHistoryArchived?.length || 0;
3612
- const messageCount = state.messages?.length || 0;
3613
- const summarizedMessages = state.messages?.filter((message) => message.role === "tool" && typeof message.content === "string" && (message.content === "SUMMARIZED" || message.content.startsWith("SUMMARIZED_TOOL_RESPONSE"))).length || 0;
3614
- const numerator = summaryCount * 2 + archivedCount + summarizedMessages;
3615
- const denominator = Math.max(messageCount, 1);
3616
- return Number((numerator / denominator).toFixed(3));
3617
- }
3618
3572
 
3619
3573
  // src/nodes/contextSummarize.ts
3620
3574
  var systemMessage = (content) => ({ role: "system", content });
@@ -3759,6 +3713,9 @@ function findToolHistoryEntry(state, toolCallId, toolName) {
3759
3713
  }
3760
3714
  }
3761
3715
  }
3716
+ if (!toolName) {
3717
+ return void 0;
3718
+ }
3762
3719
  for (let index = entries.length - 1; index >= 0; index -= 1) {
3763
3720
  const entry = entries[index];
3764
3721
  if (entry?.toolName === toolName) {
@@ -3847,8 +3804,20 @@ function createContextSummarizeNode(opts) {
3847
3804
  const messages = state.messages || [];
3848
3805
  const onEvent = state.ctx?.__onEvent;
3849
3806
  const traceSession = state.ctx?.__traceSession;
3807
+ const toolResponsesConfigEarly = resolved.toolResponses;
3850
3808
  const compressableMessages = messages.filter(
3851
- (m) => m.role === "tool" && !isSummarizedToolPlaceholder(m.content) && !isSyntheticSummaryToolMessage(m)
3809
+ (m) => {
3810
+ if (m.role !== "tool") return false;
3811
+ if (isSummarizedToolPlaceholder(m.content)) return false;
3812
+ if (isSyntheticSummaryToolMessage(m)) return false;
3813
+ const histEntry = findToolHistoryEntry(state, m.tool_call_id, m.name);
3814
+ if (histEntry?.retentionPolicy === "keep_full") return false;
3815
+ if (!histEntry?.retentionPolicy) {
3816
+ const byTool = toolResponsesConfigEarly.toolResponseRetentionByTool?.[m.name || ""];
3817
+ if ((byTool || toolResponsesConfigEarly.defaultPolicy) === "keep_full") return false;
3818
+ }
3819
+ return true;
3820
+ }
3852
3821
  );
3853
3822
  if (compressableMessages.length === 0) {
3854
3823
  return {};
@@ -3869,6 +3838,13 @@ function createContextSummarizeNode(opts) {
3869
3838
  else if (Array.isArray(m.content)) {
3870
3839
  content = m.content.map((c) => c.text || JSON.stringify(c)).join(" ");
3871
3840
  }
3841
+ if (m.role === "tool" && isSummarizedToolPlaceholder(content)) {
3842
+ const historyEntry = findToolHistoryEntry(state, m.tool_call_id, m.name);
3843
+ if (historyEntry) {
3844
+ const original = historyEntry.rawOutput ?? historyEntry.output;
3845
+ content = typeof original === "string" ? original : JSON.stringify(original);
3846
+ }
3847
+ }
3872
3848
  const maxContentLength = 2e3;
3873
3849
  if (content.length > maxContentLength) {
3874
3850
  content = content.substring(0, maxContentLength) + "... [TRUNCATED]";
@@ -4004,6 +3980,23 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
4004
3980
  });
4005
3981
  }
4006
3982
  });
3983
+ const protectedToolCallIds = /* @__PURE__ */ new Set();
3984
+ for (let i = messages.length - 1; i >= 0; i--) {
3985
+ const m = messages[i];
3986
+ if (m.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
3987
+ const thisToolCallIds = new Set(m.tool_calls.map((tc) => tc.id).filter(Boolean));
3988
+ const otherCompressable = compressableMessages.filter(
3989
+ (cm) => !thisToolCallIds.has(cm.tool_call_id)
3990
+ );
3991
+ if (otherCompressable.length > 0) {
3992
+ for (const tc of m.tool_calls) {
3993
+ if (tc.id) protectedToolCallIds.add(tc.id);
3994
+ }
3995
+ }
3996
+ break;
3997
+ }
3998
+ }
3999
+ const toolResponsesConfig = resolved.toolResponses;
4007
4000
  const newMessages = messages.map((m) => {
4008
4001
  if (m.role === "tool") {
4009
4002
  if (isSyntheticSummaryToolMessage(m)) {
@@ -4014,6 +4007,16 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
4014
4007
  return null;
4015
4008
  }
4016
4009
  if (isSummarizedToolPlaceholder(m.content)) return m;
4010
+ if (toolCallId && protectedToolCallIds.has(toolCallId)) return m;
4011
+ const toolName = m.name || "";
4012
+ const historyEntry = findToolHistoryEntry(state, toolCallId, toolName);
4013
+ const entryRetention = historyEntry?.retentionPolicy;
4014
+ if (entryRetention === "keep_full") return m;
4015
+ if (!entryRetention) {
4016
+ const byTool = toolResponsesConfig.toolResponseRetentionByTool?.[toolName];
4017
+ const configPolicy = byTool || toolResponsesConfig.defaultPolicy;
4018
+ if (configPolicy === "keep_full") return m;
4019
+ }
4017
4020
  return {
4018
4021
  ...m,
4019
4022
  content: buildSummarizedToolMessage(m, state)
@@ -4021,6 +4024,12 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
4021
4024
  }
4022
4025
  return m;
4023
4026
  }).filter((m) => m !== null);
4027
+ const actuallyCompressed = newMessages.filter(
4028
+ (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))
4029
+ );
4030
+ if (actuallyCompressed.length === 0) {
4031
+ return {};
4032
+ }
4024
4033
  const validatedMessages = validateMessageSequence(newMessages);
4025
4034
  const summaryToolCallId = `call_summary_${Date.now()}`;
4026
4035
  const assistantSummaryCall = {
@@ -4096,12 +4105,7 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
4096
4105
  return {
4097
4106
  messages: finalMessages,
4098
4107
  summaries,
4099
- summaryRecords,
4100
- watchdog: {
4101
- ...state.watchdog || {},
4102
- compactions: (state.watchdog?.compactions || 0) + 1,
4103
- lastAction: "summarized"
4104
- }
4108
+ summaryRecords
4105
4109
  };
4106
4110
  };
4107
4111
  }
@@ -4400,8 +4404,7 @@ function needsSummarization(state, opts, summarizationEnabled) {
4400
4404
  return "";
4401
4405
  }).join("\n");
4402
4406
  const tokenCount = countApproxTokens(allText);
4403
- const contextRotScore = state.watchdog?.contextRotScore || 0;
4404
- const needsSum = tokenCount > maxTok || resolved.watchdog.enabled && resolved.watchdog.autoCompaction && contextRotScore >= resolved.watchdog.contextRotThreshold;
4407
+ const needsSum = tokenCount > maxTok;
4405
4408
  if (process.env.DEBUG_SUMMARIZATION) {
4406
4409
  const msgCount = (state.messages || []).length;
4407
4410
  const toolMsgs = (state.messages || []).filter((m) => m.role === "tool");
@@ -4411,7 +4414,7 @@ function needsSummarization(state, opts, summarizationEnabled) {
4411
4414
  });
4412
4415
  console.log(`[Summarization] Messages: ${msgCount}, Tool messages: ${toolMsgs.length}`);
4413
4416
  toolDetails.forEach((d) => console.log(` ${d}`));
4414
- console.log(`[Summarization] Token count: ${tokenCount}, Max: ${maxTok}, Context rot: ${contextRotScore}, Needs summarization: ${needsSum}`);
4417
+ console.log(`[Summarization] Token count: ${tokenCount}, Max: ${maxTok}, Needs summarization: ${needsSum}`);
4415
4418
  }
4416
4419
  return needsSum;
4417
4420
  } catch {
@@ -4565,7 +4568,6 @@ function createSmartAgent(opts) {
4565
4568
  delegation: resolved.delegation,
4566
4569
  memory: { ...resolved.memory, store: memoryStore },
4567
4570
  toolResponses: resolved.toolResponses,
4568
- watchdog: resolved.watchdog,
4569
4571
  useTodoList: planningEnabled
4570
4572
  };
4571
4573
  const stateRef = { toolHistory: void 0, toolHistoryArchived: void 0, todoList: void 0, planVersion: 0, adherenceScore: 0 };
@@ -4648,7 +4650,6 @@ function createSmartAgent(opts) {
4648
4650
  let rawMessages = [...seedMessages];
4649
4651
  const effectiveMaxToolCalls = config?.limits?.maxToolCalls ?? resolved.limits.maxToolCalls ?? 10;
4650
4652
  const iterationLimit = Math.max(effectiveMaxToolCalls * 3 + 5, 30);
4651
- let previousTokenCount = countApproxTokens(rawMessages.map((message) => typeof message.content === "string" ? message.content : JSON.stringify(message.content)).join("\n"));
4652
4653
  for (let i = 0; i < iterationLimit; i++) {
4653
4654
  state = { ...state, messages: rawMessages };
4654
4655
  const next = summarizationEnabled ? decideBefore(state) : "agent";
@@ -4682,27 +4683,6 @@ function createSmartAgent(opts) {
4682
4683
  state = syncPlanState(await syncMemory(state));
4683
4684
  stateRef.toolHistory = state.toolHistory;
4684
4685
  stateRef.toolHistoryArchived = state.toolHistoryArchived;
4685
- const currentTokenCount = countApproxTokens(rawMessages.map((message) => typeof message.content === "string" ? message.content : JSON.stringify(message.content)).join("\n"));
4686
- const tokenDrift = Math.max(0, currentTokenCount - previousTokenCount);
4687
- const toolMessagesThisTurn = appendedMessages.filter((message) => message.role === "tool").length;
4688
- const overToolingRate = appendedMessages.length === 0 ? 0 : Number((toolMessagesThisTurn / appendedMessages.length).toFixed(2));
4689
- state = {
4690
- ...state,
4691
- watchdog: {
4692
- tokenDrift,
4693
- contextRotScore: estimateContextRotScore(state),
4694
- overToolingRate,
4695
- compactions: state.watchdog?.compactions || 0,
4696
- lastAction: appendedMessages.length > 0 ? "agent_turn" : state.watchdog?.lastAction
4697
- }
4698
- };
4699
- previousTokenCount = currentTokenCount;
4700
- if (resolved.watchdog.enabled && resolved.watchdog.autoCompaction) {
4701
- const shouldCompact = tokenDrift >= resolved.watchdog.tokenDriftThreshold || (state.watchdog?.overToolingRate || 0) >= resolved.watchdog.overToolingSpikeThreshold || (state.watchdog?.contextRotScore || 0) >= resolved.watchdog.contextRotThreshold;
4702
- if (shouldCompact) {
4703
- state = { ...state, ctx: { ...state.ctx || {}, __needsSummarization: true } };
4704
- }
4705
- }
4706
4686
  if (state.ctx?.__needsSummarization && summarizer) {
4707
4687
  const ctx = { ...state.ctx || {} };
4708
4688
  delete ctx.__needsSummarization;
@@ -4734,12 +4714,12 @@ function createSmartAgent(opts) {
4734
4714
  }
4735
4715
  if (state.summaries && state.summaries.length > 0) {
4736
4716
  if (lastResult.state) {
4737
- 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 } };
4717
+ lastResult = { ...lastResult, state: { ...lastResult.state, summaries: state.summaries, summaryRecords: state.summaryRecords, memoryFacts: state.memoryFacts, plan: state.plan, planVersion: state.planVersion, messages: rawMessages } };
4738
4718
  } else {
4739
- lastResult = { ...lastResult, state: { ...state, summaries: state.summaries, summaryRecords: state.summaryRecords, memoryFacts: state.memoryFacts, plan: state.plan, planVersion: state.planVersion, watchdog: state.watchdog, messages: rawMessages } };
4719
+ lastResult = { ...lastResult, state: { ...state, summaries: state.summaries, summaryRecords: state.summaryRecords, memoryFacts: state.memoryFacts, plan: state.plan, planVersion: state.planVersion, messages: rawMessages } };
4740
4720
  }
4741
4721
  } else if (lastResult.state) {
4742
- lastResult = { ...lastResult, state: { ...lastResult.state, memoryFacts: state.memoryFacts, plan: state.plan, planVersion: state.planVersion, watchdog: state.watchdog, messages: rawMessages } };
4722
+ lastResult = { ...lastResult, state: { ...lastResult.state, memoryFacts: state.memoryFacts, plan: state.plan, planVersion: state.planVersion, messages: rawMessages } };
4743
4723
  }
4744
4724
  return lastResult;
4745
4725
  },