@cognipeer/agent-sdk 0.6.1 → 0.6.3

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.mjs CHANGED
@@ -617,6 +617,7 @@ function buildSystemPrompt(extra, planning, name = "Agent", todoListPrompt) {
617
617
  "- Keep privacy and safety: do not reveal secrets or sensitive data.",
618
618
  "- If inputs are ambiguous or missing, ask one concise clarifying question.",
619
619
  "- Reuse prior tool results already present in the conversation when sufficient.",
620
+ '- Use recovery tools such as "get_tool_response" only when the visible transcript explicitly shows a reduced tool-response marker (for example ARCHIVED_TOOL_RESPONSE, STRUCTURED_TOOL_RESPONSE, SUMMARIZED_TOOL_RESPONSE, DROPPED_TOOL_RESPONSE, or a truncation note with an executionId). Never use a recovery tool to re-fetch a normal tool result already visible in context.',
620
621
  planningBlock,
621
622
  extraTrimmed ? `Extra instructions: ${extraTrimmed}` : ""
622
623
  ].filter(Boolean).join("\n");
@@ -2099,8 +2100,6 @@ var BASE_DEFAULTS = {
2099
2100
  policy: "hybrid",
2100
2101
  lastTurnsToKeep: 8,
2101
2102
  toolResponsePolicy: "summarize_archive",
2102
- archiveLargeToolResponses: true,
2103
- retrieveArchivedToolResponseOnDemand: true,
2104
2103
  budget: {
2105
2104
  systemReserveTokens: 1200,
2106
2105
  goalsReserveTokens: 1200,
@@ -2133,8 +2132,7 @@ var BASE_DEFAULTS = {
2133
2132
  defaultPolicy: "summarize_archive",
2134
2133
  toolResponseRetentionByTool: {},
2135
2134
  criticalTools: [...DEFAULT_CRITICAL_TOOLS],
2136
- schemaValidation: "strict",
2137
- retryOnSchemaError: true
2135
+ schemaValidation: "strict"
2138
2136
  }
2139
2137
  };
2140
2138
  function buildProfile(overrides) {
@@ -2545,6 +2543,7 @@ function createToolsNode(initialTools, opts) {
2545
2543
  anyTool._stateRef.toolHistory = state.toolHistory;
2546
2544
  anyTool._stateRef.toolHistoryArchived = state.toolHistoryArchived;
2547
2545
  anyTool._stateRef.pendingApprovals = pendingApprovals;
2546
+ anyTool._stateRef.messages = state.messages;
2548
2547
  anyTool._stateRef.ctx = state.ctx || (state.ctx = {});
2549
2548
  anyTool._stateRef.__onEvent = onEvent;
2550
2549
  }
@@ -4013,8 +4012,10 @@ function createAgent(opts) {
4013
4012
  agentRuntime: res.agent || runtime,
4014
4013
  status: "success"
4015
4014
  });
4016
- const finalAssistantMsg = getLastAssistantMessage(res.messages);
4017
- const content = extractMessageText2(finalAssistantMsg);
4015
+ const isTransientSummarizationExit = !!res.ctx?.__needsSummarization;
4016
+ const finalAssistantMsg = isTransientSummarizationExit ? void 0 : getLastAssistantMessage(res.messages);
4017
+ const finalIsSyntheticSummary = !isTransientSummarizationExit && finalAssistantMsg && isSyntheticSummaryMessage(finalAssistantMsg);
4018
+ const content = isTransientSummarizationExit || finalIsSyntheticSummary ? "" : extractMessageText2(finalAssistantMsg);
4018
4019
  let parsed = void 0;
4019
4020
  let outputError = void 0;
4020
4021
  if (soManager) {
@@ -4027,17 +4028,19 @@ function createAgent(opts) {
4027
4028
  } else {
4028
4029
  outputError = fallbackResult.error;
4029
4030
  }
4030
- } else {
4031
+ } else if (!isTransientSummarizationExit) {
4031
4032
  const noResult = soManager.noOutputResult(1);
4032
4033
  if (!noResult.success) {
4033
4034
  outputError = noResult.error;
4034
4035
  }
4035
4036
  }
4036
4037
  }
4037
- emit({ type: "finalAnswer", content });
4038
- if (streamEnabled && content) {
4039
- onStream?.({ text: content, isFinal: true });
4040
- emit({ type: "stream", text: content, isFinal: true });
4038
+ if (!isTransientSummarizationExit && !finalIsSyntheticSummary) {
4039
+ emit({ type: "finalAnswer", content });
4040
+ if (streamEnabled && content) {
4041
+ onStream?.({ text: content, isFinal: true });
4042
+ emit({ type: "stream", text: content, isFinal: true });
4043
+ }
4041
4044
  }
4042
4045
  return {
4043
4046
  content,
@@ -4835,6 +4838,13 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
4835
4838
  };
4836
4839
  };
4837
4840
  }
4841
+ var TOOL_RESPONSE_RECOVERY_MARKERS = [
4842
+ /ARCHIVED_TOOL_RESPONSE\s*\[/,
4843
+ /STRUCTURED_TOOL_RESPONSE\s*\[/,
4844
+ /SUMMARIZED_TOOL_RESPONSE\b/,
4845
+ /DROPPED_TOOL_RESPONSE\s*\[/,
4846
+ /Use get_tool_response with executionId/i
4847
+ ];
4838
4848
  var todoStatusSchema = z.enum(["not-started", "in-progress", "completed", "blocked"]);
4839
4849
  var todoWriteItemSchema = z.object({
4840
4850
  id: z.number().int().min(1).describe("Sequential id starting from 1"),
@@ -4903,180 +4913,223 @@ function formatTodoListSummary(todoList) {
4903
4913
  }
4904
4914
  return todoList.map((item) => `${item.id}. ${item.title || item.step || item.description || `Step ${item.id}`} [${item.status}]`).join("\n");
4905
4915
  }
4906
- function createContextTools(stateRef, opts) {
4907
- const tools = [];
4908
- if (opts?.planningEnabled) {
4909
- const manageTodo = createTool({
4910
- name: "manage_todo_list",
4911
- description: "Manage a structured todo list to track progress and plan tasks throughout your coding session.\n\nOperations:\n- read: return the current plan\n- write: replace the full plan with a complete ordered todoList\n- update: patch existing todo items by id without resending the whole plan\n\nRules:\n- Use write only when creating or fully rewriting the plan\n- After a plan exists, prefer update for status, evidence, or owner changes\n- Update payloads should contain only the changed items\n- When using update, pass expectedVersion to avoid overwriting a newer plan\n- Keep ids unique; write operations must keep ids sequential starting from 1\n- Keep at most ONE item in-progress at a time\n- If update fails due to version mismatch, read the latest plan and retry",
4912
- schema: z.object({
4913
- operation: z.enum(["write", "read", "update"]),
4914
- expectedVersion: z.number().int().min(0).optional(),
4915
- todoList: z.array(z.union([todoWriteItemSchema, todoUpdateItemSchema])).optional()
4916
- }),
4917
- func: async ({ operation, expectedVersion, todoList }) => {
4918
- const toolStateRef = manageTodo._stateRef;
4919
- const onEvent = toolStateRef?.__onEvent;
4920
- const emitPlanEvent = (list) => {
4921
- const version = stateRef.planVersion || 1;
4922
- const adherenceScore = stateRef.adherenceScore || 0;
4923
- const planData = {
4924
- source: "manage_todo_list",
4916
+ function flattenRecoveryContent(content) {
4917
+ if (typeof content === "string") {
4918
+ return content;
4919
+ }
4920
+ if (Array.isArray(content)) {
4921
+ return content.map((part) => {
4922
+ if (typeof part === "string") {
4923
+ return part;
4924
+ }
4925
+ if (part && typeof part === "object") {
4926
+ if (typeof part.text === "string") {
4927
+ return part.text;
4928
+ }
4929
+ if (typeof part.content === "string") {
4930
+ return part.content;
4931
+ }
4932
+ }
4933
+ return "";
4934
+ }).filter(Boolean).join("\n");
4935
+ }
4936
+ return "";
4937
+ }
4938
+ function hasToolResponseRecoveryReference(messages, executionId) {
4939
+ if (!Array.isArray(messages) || messages.length === 0) {
4940
+ return false;
4941
+ }
4942
+ return messages.some((message) => {
4943
+ if (message?.role === "system") {
4944
+ return false;
4945
+ }
4946
+ const content = flattenRecoveryContent(message?.content);
4947
+ if (!content) {
4948
+ return false;
4949
+ }
4950
+ const hasRecoveryMarker = TOOL_RESPONSE_RECOVERY_MARKERS.some((pattern) => pattern.test(content));
4951
+ if (!hasRecoveryMarker) {
4952
+ return false;
4953
+ }
4954
+ return executionId ? content.includes(executionId) : true;
4955
+ });
4956
+ }
4957
+ function createManageTodoTool(stateRef) {
4958
+ const manageTodo = createTool({
4959
+ name: "manage_todo_list",
4960
+ description: "Manage a structured todo list to track progress and plan tasks throughout your coding session.\n\nOperations:\n- read: return the current plan\n- write: replace the full plan with a complete ordered todoList\n- update: patch existing todo items by id without resending the whole plan\n\nRules:\n- Use write only when creating or fully rewriting the plan\n- After a plan exists, prefer update for status, evidence, or owner changes\n- Update payloads should contain only the changed items\n- When using update, pass expectedVersion to avoid overwriting a newer plan\n- Keep ids unique; write operations must keep ids sequential starting from 1\n- Keep at most ONE item in-progress at a time\n- If update fails due to version mismatch, read the latest plan and retry",
4961
+ schema: z.object({
4962
+ operation: z.enum(["write", "read", "update"]),
4963
+ expectedVersion: z.number().int().min(0).optional(),
4964
+ todoList: z.array(z.union([todoWriteItemSchema, todoUpdateItemSchema])).optional()
4965
+ }),
4966
+ func: async ({ operation, expectedVersion, todoList }) => {
4967
+ const toolStateRef = manageTodo._stateRef;
4968
+ const onEvent = toolStateRef?.__onEvent;
4969
+ const emitPlanEvent = (list) => {
4970
+ const version = stateRef.planVersion || 1;
4971
+ const adherenceScore = stateRef.adherenceScore || 0;
4972
+ const planData = {
4973
+ source: "manage_todo_list",
4974
+ operation,
4975
+ version,
4976
+ adherenceScore,
4977
+ count: Array.isArray(list) ? list.length : 0
4978
+ };
4979
+ onEvent?.({ type: "plan", todoList: list, ...planData });
4980
+ const traceSession = toolStateRef?.ctx?.__traceSession;
4981
+ recordTraceEvent(traceSession, {
4982
+ type: "plan",
4983
+ label: `Plan ${operation}`,
4984
+ actor: { scope: "agent", name: "manage_todo_list", role: "planner" },
4985
+ sections: [
4986
+ {
4987
+ kind: "summary",
4988
+ label: "Todo List",
4989
+ content: formatTodoListSummary(list)
4990
+ },
4991
+ {
4992
+ kind: "metadata",
4993
+ label: "Plan Metadata",
4994
+ data: planData
4995
+ }
4996
+ ],
4997
+ debug: planData
4998
+ });
4999
+ };
5000
+ const currentVersion = stateRef.planVersion || 0;
5001
+ if (operation === "read") {
5002
+ const list = stateRef.todoList || [];
5003
+ emitPlanEvent(list);
5004
+ return list;
5005
+ }
5006
+ if (typeof expectedVersion === "number" && expectedVersion !== currentVersion) {
5007
+ return {
5008
+ status: "error",
5009
+ operation,
5010
+ error: "Plan version mismatch. Read the latest plan and retry.",
5011
+ version: currentVersion,
5012
+ adherenceScore: stateRef.adherenceScore || 0
5013
+ };
5014
+ }
5015
+ if (!Array.isArray(todoList)) {
5016
+ return {
5017
+ status: "error",
5018
+ operation,
5019
+ error: "todoList is required for write and update operations.",
5020
+ version: currentVersion,
5021
+ adherenceScore: stateRef.adherenceScore || 0
5022
+ };
5023
+ }
5024
+ if (operation === "write") {
5025
+ const parsed = z.array(todoWriteItemSchema).safeParse(todoList);
5026
+ if (!parsed.success) {
5027
+ return {
5028
+ status: "error",
4925
5029
  operation,
4926
- version,
4927
- adherenceScore,
4928
- count: Array.isArray(list) ? list.length : 0
5030
+ error: parsed.error.issues[0]?.message || "Invalid todoList for write.",
5031
+ version: currentVersion,
5032
+ adherenceScore: stateRef.adherenceScore || 0
4929
5033
  };
4930
- onEvent?.({ type: "plan", todoList: list, ...planData });
4931
- const traceSession = toolStateRef?.ctx?.__traceSession;
4932
- recordTraceEvent(traceSession, {
4933
- type: "plan",
4934
- label: `Plan ${operation}`,
4935
- actor: { scope: "agent", name: "manage_todo_list", role: "planner" },
4936
- sections: [
4937
- {
4938
- kind: "summary",
4939
- label: "Todo List",
4940
- content: formatTodoListSummary(list)
4941
- },
4942
- {
4943
- kind: "metadata",
4944
- label: "Plan Metadata",
4945
- data: planData
4946
- }
4947
- ],
4948
- debug: planData
4949
- });
4950
- };
4951
- const currentVersion = stateRef.planVersion || 0;
4952
- if (operation === "read") {
4953
- const list = stateRef.todoList || [];
4954
- emitPlanEvent(list);
4955
- return list;
4956
5034
  }
4957
- if (typeof expectedVersion === "number" && expectedVersion !== currentVersion) {
5035
+ const normalizedList = parsed.data.map((item) => normalizeTodoItem(item));
5036
+ const validation = validatePlanInvariants(normalizedList, true);
5037
+ if (!validation.ok) {
4958
5038
  return {
4959
5039
  status: "error",
4960
5040
  operation,
4961
- error: "Plan version mismatch. Read the latest plan and retry.",
5041
+ error: validation.error,
4962
5042
  version: currentVersion,
4963
5043
  adherenceScore: stateRef.adherenceScore || 0
4964
5044
  };
4965
5045
  }
4966
- if (!Array.isArray(todoList)) {
5046
+ stateRef.todoList = normalizedList;
5047
+ } else if (operation === "update") {
5048
+ const parsed = z.array(todoUpdateItemSchema).safeParse(todoList);
5049
+ if (!parsed.success) {
4967
5050
  return {
4968
5051
  status: "error",
4969
5052
  operation,
4970
- error: "todoList is required for write and update operations.",
5053
+ error: parsed.error.issues[0]?.message || "Invalid todoList for update.",
4971
5054
  version: currentVersion,
4972
5055
  adherenceScore: stateRef.adherenceScore || 0
4973
5056
  };
4974
5057
  }
4975
- if (operation === "write") {
4976
- const parsed = z.array(todoWriteItemSchema).safeParse(todoList);
4977
- if (!parsed.success) {
4978
- return {
4979
- status: "error",
4980
- operation,
4981
- error: parsed.error.issues[0]?.message || "Invalid todoList for write.",
4982
- version: currentVersion,
4983
- adherenceScore: stateRef.adherenceScore || 0
4984
- };
4985
- }
4986
- const normalizedList = parsed.data.map((item) => normalizeTodoItem(item));
4987
- const validation = validatePlanInvariants(normalizedList, true);
4988
- if (!validation.ok) {
4989
- return {
4990
- status: "error",
4991
- operation,
4992
- error: validation.error,
4993
- version: currentVersion,
4994
- adherenceScore: stateRef.adherenceScore || 0
4995
- };
4996
- }
4997
- stateRef.todoList = normalizedList;
4998
- } else if (operation === "update") {
4999
- const parsed = z.array(todoUpdateItemSchema).safeParse(todoList);
5000
- if (!parsed.success) {
5001
- return {
5002
- status: "error",
5003
- operation,
5004
- error: parsed.error.issues[0]?.message || "Invalid todoList for update.",
5005
- version: currentVersion,
5006
- adherenceScore: stateRef.adherenceScore || 0
5007
- };
5008
- }
5009
- const currentList = Array.isArray(stateRef.todoList) ? stateRef.todoList : [];
5010
- if (currentList.length === 0) {
5058
+ const currentList = Array.isArray(stateRef.todoList) ? stateRef.todoList : [];
5059
+ if (currentList.length === 0) {
5060
+ return {
5061
+ status: "error",
5062
+ operation,
5063
+ error: "No existing plan to update. Use write first.",
5064
+ version: currentVersion,
5065
+ adherenceScore: stateRef.adherenceScore || 0
5066
+ };
5067
+ }
5068
+ const currentMap = new Map(currentList.map((item) => [item.id, item]));
5069
+ const patchMap = /* @__PURE__ */ new Map();
5070
+ for (const item of parsed.data) {
5071
+ if (patchMap.has(item.id)) {
5011
5072
  return {
5012
5073
  status: "error",
5013
5074
  operation,
5014
- error: "No existing plan to update. Use write first.",
5075
+ error: "Update payload contains duplicate todo ids.",
5015
5076
  version: currentVersion,
5016
5077
  adherenceScore: stateRef.adherenceScore || 0
5017
5078
  };
5018
5079
  }
5019
- const currentMap = new Map(currentList.map((item) => [item.id, item]));
5020
- const patchMap = /* @__PURE__ */ new Map();
5021
- for (const item of parsed.data) {
5022
- if (patchMap.has(item.id)) {
5023
- return {
5024
- status: "error",
5025
- operation,
5026
- error: "Update payload contains duplicate todo ids.",
5027
- version: currentVersion,
5028
- adherenceScore: stateRef.adherenceScore || 0
5029
- };
5030
- }
5031
- patchMap.set(item.id, item);
5032
- if (!currentMap.has(item.id)) {
5033
- return {
5034
- status: "error",
5035
- operation,
5036
- error: `Cannot update missing todo id ${item.id}. Use write to replace the plan.`,
5037
- version: currentVersion,
5038
- adherenceScore: stateRef.adherenceScore || 0
5039
- };
5040
- }
5041
- }
5042
- const mergedList = currentList.map((item) => {
5043
- const patch = patchMap.get(item.id);
5044
- return patch ? normalizeTodoItem(patch, item) : item;
5045
- });
5046
- const validation = validatePlanInvariants(mergedList, false);
5047
- if (!validation.ok) {
5080
+ patchMap.set(item.id, item);
5081
+ if (!currentMap.has(item.id)) {
5048
5082
  return {
5049
5083
  status: "error",
5050
5084
  operation,
5051
- error: validation.error,
5085
+ error: `Cannot update missing todo id ${item.id}. Use write to replace the plan.`,
5052
5086
  version: currentVersion,
5053
5087
  adherenceScore: stateRef.adherenceScore || 0
5054
5088
  };
5055
5089
  }
5056
- stateRef.todoList = mergedList;
5057
5090
  }
5058
- stateRef.planVersion = currentVersion + 1;
5059
- stateRef.adherenceScore = calculateAdherenceScore(stateRef.todoList || []);
5060
- const payload = {
5061
- status: "ok",
5062
- operation,
5063
- count: Array.isArray(todoList) ? todoList.length : void 0,
5064
- version: stateRef.planVersion || 1,
5065
- adherenceScore: stateRef.adherenceScore || 0
5066
- };
5067
- emitPlanEvent(stateRef.todoList || []);
5068
- return payload;
5069
- }
5070
- });
5071
- manageTodo._stateRef = stateRef;
5072
- tools.push(manageTodo);
5073
- }
5091
+ const mergedList = currentList.map((item) => {
5092
+ const patch = patchMap.get(item.id);
5093
+ return patch ? normalizeTodoItem(patch, item) : item;
5094
+ });
5095
+ const validation = validatePlanInvariants(mergedList, false);
5096
+ if (!validation.ok) {
5097
+ return {
5098
+ status: "error",
5099
+ operation,
5100
+ error: validation.error,
5101
+ version: currentVersion,
5102
+ adherenceScore: stateRef.adherenceScore || 0
5103
+ };
5104
+ }
5105
+ stateRef.todoList = mergedList;
5106
+ }
5107
+ stateRef.planVersion = currentVersion + 1;
5108
+ stateRef.adherenceScore = calculateAdherenceScore(stateRef.todoList || []);
5109
+ const payload = {
5110
+ status: "ok",
5111
+ operation,
5112
+ count: Array.isArray(todoList) ? todoList.length : void 0,
5113
+ version: stateRef.planVersion || 1,
5114
+ adherenceScore: stateRef.adherenceScore || 0
5115
+ };
5116
+ emitPlanEvent(stateRef.todoList || []);
5117
+ return payload;
5118
+ }
5119
+ });
5120
+ manageTodo._stateRef = stateRef;
5121
+ return manageTodo;
5122
+ }
5123
+ function createGetToolResponseTool(stateRef) {
5074
5124
  const getTool = createTool({
5075
5125
  name: "get_tool_response",
5076
- description: "RETRIEVE the full output of a tool execution whose response was archived, dropped, or later compacted in conversation history. Use this only when the preview or summary is missing a specific field, identifier, snippet, or exact payload you still need to finish the task. Do not call it reflexively for every archived response. When a tool response appears as 'ARCHIVED_TOOL_RESPONSE [executionId=xxx]', 'DROPPED_TOOL_RESPONSE [executionId=xxx]', or 'SUMMARIZED_TOOL_RESPONSE [...]', pass the referenced executionId to this tool to get the complete data. You can also pass the original tool_call_id from the tool call.",
5126
+ description: "RETRIEVE the full output of a tool execution whose response was archived, dropped, truncated, or later compacted in conversation history. This tool is only useful when the visible transcript already shows a reduced tool-response marker for the referenced executionId or tool_call_id. Use it only when a marker such as 'ARCHIVED_TOOL_RESPONSE', 'STRUCTURED_TOOL_RESPONSE', 'SUMMARIZED_TOOL_RESPONSE', 'DROPPED_TOOL_RESPONSE', or an explicit truncation note points you to a missing field you still need. Do not call it to re-fetch a normal tool result that is already present in context.",
5077
5127
  schema: z.object({ executionId: z.string().describe("Tool execution id or original tool_call_id") }),
5078
5128
  maxExecutionsPerRun: 8,
5079
5129
  func: async ({ executionId }) => {
5130
+ if (!hasToolResponseRecoveryReference(stateRef.messages, executionId)) {
5131
+ return "Execution not recoverable from the visible transcript. Use this only when the conversation already shows a reduced tool-response marker for that executionId.";
5132
+ }
5080
5133
  const matchesExecution = (t) => t?.executionId === executionId || t?.tool_call_id === executionId;
5081
5134
  let execution = stateRef.toolHistory?.find((t) => matchesExecution(t));
5082
5135
  if (!execution) {
@@ -5089,7 +5142,16 @@ function createContextTools(stateRef, opts) {
5089
5142
  }
5090
5143
  });
5091
5144
  getTool._stateRef = stateRef;
5092
- tools.push(getTool);
5145
+ return getTool;
5146
+ }
5147
+ function createContextTools(stateRef, opts) {
5148
+ const tools = [];
5149
+ if (opts?.planningEnabled) {
5150
+ tools.push(createManageTodoTool(stateRef));
5151
+ }
5152
+ if (opts?.includeGetToolResponse ?? true) {
5153
+ tools.push(createGetToolResponseTool(stateRef));
5154
+ }
5093
5155
  return tools;
5094
5156
  }
5095
5157
 
@@ -5257,9 +5319,11 @@ function createSmartAgent(opts) {
5257
5319
  useTodoList: planningEnabled
5258
5320
  };
5259
5321
  const stateRef = { toolHistory: void 0, toolHistoryArchived: void 0, todoList: void 0, planVersion: 0, adherenceScore: 0 };
5260
- const contextTools = createContextTools(stateRef, { planningEnabled });
5261
- const mergedTools = [...opts.tools ?? [], ...contextTools];
5262
- const base = createAgent({ ...runtimeOpts, tools: mergedTools });
5322
+ const contextTools = createContextTools(stateRef, { planningEnabled, includeGetToolResponse: false });
5323
+ const getToolResponseTool = createGetToolResponseTool(stateRef);
5324
+ const toolsWithoutRecovery = [...opts.tools ?? [], ...contextTools];
5325
+ const toolsWithRecovery = [...toolsWithoutRecovery, getToolResponseTool];
5326
+ const base = createAgent({ ...runtimeOpts, tools: toolsWithoutRecovery });
5263
5327
  base.__runtime.runtimeProfile = resolved.runtimeProfile;
5264
5328
  base.__runtime.smart = resolved;
5265
5329
  const summarizationEnabled = resolved.summarization.enable !== false;
@@ -5317,6 +5381,27 @@ function createSmartAgent(opts) {
5317
5381
  );
5318
5382
  return { role: "system", content: sys };
5319
5383
  }
5384
+ function syncRuntimeTools(currentState, currentMessages) {
5385
+ const needsRecoveryTool = hasToolResponseRecoveryReference(currentMessages);
5386
+ const nextTools = needsRecoveryTool ? toolsWithRecovery : toolsWithoutRecovery;
5387
+ const currentRuntime = currentState.agent || base.__runtime;
5388
+ if (currentRuntime.tools === nextTools) {
5389
+ return currentState;
5390
+ }
5391
+ return {
5392
+ ...currentState,
5393
+ agent: {
5394
+ ...currentRuntime,
5395
+ tools: nextTools
5396
+ }
5397
+ };
5398
+ }
5399
+ function producedTerminalAssistantTurn(messages) {
5400
+ const lastAssistant = [...messages].reverse().find((message) => message?.role === "assistant");
5401
+ if (!lastAssistant) return false;
5402
+ const toolCalls = Array.isArray(lastAssistant.tool_calls) ? lastAssistant.tool_calls : [];
5403
+ return toolCalls.length === 0;
5404
+ }
5320
5405
  async function trySummarize(currentState, currentRawMessages) {
5321
5406
  if (!summarizer) return { state: currentState, rawMessages: currentRawMessages, compressed: false };
5322
5407
  const delta = await summarizer(currentState);
@@ -5338,13 +5423,13 @@ function createSmartAgent(opts) {
5338
5423
  stateRef.adherenceScore = input.plan?.adherenceScore || 0;
5339
5424
  const alreadyHasSystem = Array.isArray(input.messages) && input.messages[0]?.role === "system";
5340
5425
  const seedMessages = alreadyHasSystem ? [...input.messages || []] : [systemMessage2(), ...input.messages || []];
5341
- let state = await syncMemory({ ...input, messages: seedMessages });
5426
+ let state = syncRuntimeTools(await syncMemory({ ...input, messages: seedMessages }), seedMessages);
5342
5427
  let lastResult = null;
5343
5428
  let rawMessages = [...seedMessages];
5344
5429
  const effectiveMaxToolCalls = config?.limits?.maxToolCalls ?? resolved.limits.maxToolCalls ?? 10;
5345
5430
  const iterationLimit = Math.max(effectiveMaxToolCalls * 3 + 5, 30);
5346
5431
  for (let i = 0; i < iterationLimit; i++) {
5347
- state = { ...state, messages: rawMessages };
5432
+ state = syncRuntimeTools({ ...state, messages: rawMessages }, rawMessages);
5348
5433
  const next = summarizationEnabled ? decideBefore(state) : "agent";
5349
5434
  if (next === "contextSummarize" && summarizer) {
5350
5435
  const result = await trySummarize(state, rawMessages);
@@ -5371,7 +5456,7 @@ function createSmartAgent(opts) {
5371
5456
  if (currentPlan && !state.plan) {
5372
5457
  state = { ...state, plan: currentPlan };
5373
5458
  }
5374
- state = syncPlanState(await syncMemory(state));
5459
+ state = syncRuntimeTools(syncPlanState(await syncMemory(state)), rawMessages);
5375
5460
  stateRef.toolHistory = state.toolHistory;
5376
5461
  stateRef.toolHistoryArchived = state.toolHistoryArchived;
5377
5462
  if (state.ctx?.__needsSummarization && summarizer) {
@@ -5385,6 +5470,7 @@ function createSmartAgent(opts) {
5385
5470
  }
5386
5471
  if (state.ctx?.__finalizedDueToStructuredOutput) break;
5387
5472
  if (opts.outputSchema && lastResult?.output != null) break;
5473
+ if (producedTerminalAssistantTurn(appendedMessages)) break;
5388
5474
  if (summarizationEnabled) {
5389
5475
  const after = decideAfter(state);
5390
5476
  if (after === "contextSummarize" && summarizer) {
@@ -7658,6 +7744,6 @@ function createProvider(config) {
7658
7744
  }
7659
7745
  }
7660
7746
 
7661
- 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, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGuardrail, createJsonGuardrail, createProvider, createRegexGuardrail, createResolverNode, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, emptyUsage, evaluateGuardrails, fileSink, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getModelCapabilities, getNestedValue, getResolvedSmartConfig, httpSink, isSmartModel, jsonSchemaRule, normalizeSmartAgentOptions, otlpSink, readMemoryFacts, regexRule, resolveMemoryStore, resolveStrategy, resolveToolApprovalState, restoreSnapshot, runSmartAgentEvalHarness, startStreamingSession, traceSessionToOtlp, withTools, writeSummaryFactsToMemory };
7747
+ 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, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGetToolResponseTool, createGuardrail, createJsonGuardrail, createManageTodoTool, createProvider, createRegexGuardrail, createResolverNode, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, emptyUsage, evaluateGuardrails, fileSink, formatZodError, fromLangchainModel, fromLangchainTools, fromNativeProvider, generateSpanId, generateTraceId, getModelCapabilities, getNestedValue, getResolvedSmartConfig, hasToolResponseRecoveryReference, httpSink, isSmartModel, jsonSchemaRule, normalizeSmartAgentOptions, otlpSink, readMemoryFacts, regexRule, resolveMemoryStore, resolveStrategy, resolveToolApprovalState, restoreSnapshot, runSmartAgentEvalHarness, startStreamingSession, traceSessionToOtlp, withTools, writeSummaryFactsToMemory };
7662
7748
  //# sourceMappingURL=index.mjs.map
7663
7749
  //# sourceMappingURL=index.mjs.map