@cognipeer/agent-sdk 0.6.2 → 0.6.4
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 +248 -154
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +16 -4
- package/dist/index.d.ts +16 -4
- package/dist/index.mjs +246 -155
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
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");
|
|
@@ -2228,6 +2229,7 @@ function normalizeSmartAgentOptions(opts) {
|
|
|
2228
2229
|
const summarizationOverride = typeof opts.summarization === "object" ? opts.summarization : {};
|
|
2229
2230
|
const planningMode = opts.planning?.mode ?? customProfile.planning?.mode ?? (useTodoList ? "todo" : preset.planning.mode);
|
|
2230
2231
|
const memoryStore = opts.memory?.store ?? customProfile.memory?.store;
|
|
2232
|
+
const contextToolResponsePolicy = opts.context?.toolResponsePolicy ?? customProfile.context?.toolResponsePolicy ?? preset.context.toolResponsePolicy;
|
|
2231
2233
|
return {
|
|
2232
2234
|
runtimeProfile,
|
|
2233
2235
|
baseProfile,
|
|
@@ -2250,7 +2252,7 @@ function normalizeSmartAgentOptions(opts) {
|
|
|
2250
2252
|
...customProfile.context?.budget || {},
|
|
2251
2253
|
...opts.context?.budget || {}
|
|
2252
2254
|
},
|
|
2253
|
-
toolResponsePolicy:
|
|
2255
|
+
toolResponsePolicy: contextToolResponsePolicy
|
|
2254
2256
|
},
|
|
2255
2257
|
planning: {
|
|
2256
2258
|
...preset.planning,
|
|
@@ -2273,6 +2275,7 @@ function normalizeSmartAgentOptions(opts) {
|
|
|
2273
2275
|
...preset.toolResponses,
|
|
2274
2276
|
...customProfile.toolResponses || {},
|
|
2275
2277
|
...opts.toolResponses || {},
|
|
2278
|
+
defaultPolicy: opts.toolResponses?.defaultPolicy ?? customProfile.toolResponses?.defaultPolicy ?? contextToolResponsePolicy,
|
|
2276
2279
|
toolResponseRetentionByTool: {
|
|
2277
2280
|
...preset.toolResponses.toolResponseRetentionByTool,
|
|
2278
2281
|
...customProfile.toolResponses?.toolResponseRetentionByTool || {},
|
|
@@ -2542,6 +2545,7 @@ function createToolsNode(initialTools, opts) {
|
|
|
2542
2545
|
anyTool._stateRef.toolHistory = state.toolHistory;
|
|
2543
2546
|
anyTool._stateRef.toolHistoryArchived = state.toolHistoryArchived;
|
|
2544
2547
|
anyTool._stateRef.pendingApprovals = pendingApprovals;
|
|
2548
|
+
anyTool._stateRef.messages = state.messages;
|
|
2545
2549
|
anyTool._stateRef.ctx = state.ctx || (state.ctx = {});
|
|
2546
2550
|
anyTool._stateRef.__onEvent = onEvent;
|
|
2547
2551
|
}
|
|
@@ -4010,8 +4014,10 @@ function createAgent(opts) {
|
|
|
4010
4014
|
agentRuntime: res.agent || runtime,
|
|
4011
4015
|
status: "success"
|
|
4012
4016
|
});
|
|
4013
|
-
const
|
|
4014
|
-
const
|
|
4017
|
+
const isTransientSummarizationExit = !!res.ctx?.__needsSummarization;
|
|
4018
|
+
const finalAssistantMsg = isTransientSummarizationExit ? void 0 : getLastAssistantMessage(res.messages);
|
|
4019
|
+
const finalIsSyntheticSummary = !isTransientSummarizationExit && finalAssistantMsg && isSyntheticSummaryMessage(finalAssistantMsg);
|
|
4020
|
+
const content = isTransientSummarizationExit || finalIsSyntheticSummary ? "" : extractMessageText2(finalAssistantMsg);
|
|
4015
4021
|
let parsed = void 0;
|
|
4016
4022
|
let outputError = void 0;
|
|
4017
4023
|
if (soManager) {
|
|
@@ -4024,17 +4030,19 @@ function createAgent(opts) {
|
|
|
4024
4030
|
} else {
|
|
4025
4031
|
outputError = fallbackResult.error;
|
|
4026
4032
|
}
|
|
4027
|
-
} else {
|
|
4033
|
+
} else if (!isTransientSummarizationExit) {
|
|
4028
4034
|
const noResult = soManager.noOutputResult(1);
|
|
4029
4035
|
if (!noResult.success) {
|
|
4030
4036
|
outputError = noResult.error;
|
|
4031
4037
|
}
|
|
4032
4038
|
}
|
|
4033
4039
|
}
|
|
4034
|
-
|
|
4035
|
-
|
|
4036
|
-
|
|
4037
|
-
|
|
4040
|
+
if (!isTransientSummarizationExit && !finalIsSyntheticSummary) {
|
|
4041
|
+
emit({ type: "finalAnswer", content });
|
|
4042
|
+
if (streamEnabled && content) {
|
|
4043
|
+
onStream?.({ text: content, isFinal: true });
|
|
4044
|
+
emit({ type: "stream", text: content, isFinal: true });
|
|
4045
|
+
}
|
|
4038
4046
|
}
|
|
4039
4047
|
return {
|
|
4040
4048
|
content,
|
|
@@ -4832,6 +4840,13 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
|
|
|
4832
4840
|
};
|
|
4833
4841
|
};
|
|
4834
4842
|
}
|
|
4843
|
+
var TOOL_RESPONSE_RECOVERY_MARKERS = [
|
|
4844
|
+
/ARCHIVED_TOOL_RESPONSE\s*\[/,
|
|
4845
|
+
/STRUCTURED_TOOL_RESPONSE\s*\[/,
|
|
4846
|
+
/SUMMARIZED_TOOL_RESPONSE\b/,
|
|
4847
|
+
/DROPPED_TOOL_RESPONSE\s*\[/,
|
|
4848
|
+
/Use get_tool_response with executionId/i
|
|
4849
|
+
];
|
|
4835
4850
|
var todoStatusSchema = z.enum(["not-started", "in-progress", "completed", "blocked"]);
|
|
4836
4851
|
var todoWriteItemSchema = z.object({
|
|
4837
4852
|
id: z.number().int().min(1).describe("Sequential id starting from 1"),
|
|
@@ -4900,180 +4915,223 @@ function formatTodoListSummary(todoList) {
|
|
|
4900
4915
|
}
|
|
4901
4916
|
return todoList.map((item) => `${item.id}. ${item.title || item.step || item.description || `Step ${item.id}`} [${item.status}]`).join("\n");
|
|
4902
4917
|
}
|
|
4903
|
-
function
|
|
4904
|
-
|
|
4905
|
-
|
|
4906
|
-
|
|
4907
|
-
|
|
4908
|
-
|
|
4909
|
-
|
|
4910
|
-
|
|
4911
|
-
|
|
4912
|
-
|
|
4913
|
-
|
|
4914
|
-
|
|
4915
|
-
|
|
4916
|
-
|
|
4917
|
-
|
|
4918
|
-
|
|
4919
|
-
|
|
4920
|
-
|
|
4921
|
-
|
|
4918
|
+
function flattenRecoveryContent(content) {
|
|
4919
|
+
if (typeof content === "string") {
|
|
4920
|
+
return content;
|
|
4921
|
+
}
|
|
4922
|
+
if (Array.isArray(content)) {
|
|
4923
|
+
return content.map((part) => {
|
|
4924
|
+
if (typeof part === "string") {
|
|
4925
|
+
return part;
|
|
4926
|
+
}
|
|
4927
|
+
if (part && typeof part === "object") {
|
|
4928
|
+
if (typeof part.text === "string") {
|
|
4929
|
+
return part.text;
|
|
4930
|
+
}
|
|
4931
|
+
if (typeof part.content === "string") {
|
|
4932
|
+
return part.content;
|
|
4933
|
+
}
|
|
4934
|
+
}
|
|
4935
|
+
return "";
|
|
4936
|
+
}).filter(Boolean).join("\n");
|
|
4937
|
+
}
|
|
4938
|
+
return "";
|
|
4939
|
+
}
|
|
4940
|
+
function hasToolResponseRecoveryReference(messages, executionId) {
|
|
4941
|
+
if (!Array.isArray(messages) || messages.length === 0) {
|
|
4942
|
+
return false;
|
|
4943
|
+
}
|
|
4944
|
+
return messages.some((message) => {
|
|
4945
|
+
if (message?.role === "system") {
|
|
4946
|
+
return false;
|
|
4947
|
+
}
|
|
4948
|
+
const content = flattenRecoveryContent(message?.content);
|
|
4949
|
+
if (!content) {
|
|
4950
|
+
return false;
|
|
4951
|
+
}
|
|
4952
|
+
const hasRecoveryMarker = TOOL_RESPONSE_RECOVERY_MARKERS.some((pattern) => pattern.test(content));
|
|
4953
|
+
if (!hasRecoveryMarker) {
|
|
4954
|
+
return false;
|
|
4955
|
+
}
|
|
4956
|
+
return executionId ? content.includes(executionId) : true;
|
|
4957
|
+
});
|
|
4958
|
+
}
|
|
4959
|
+
function createManageTodoTool(stateRef) {
|
|
4960
|
+
const manageTodo = createTool({
|
|
4961
|
+
name: "manage_todo_list",
|
|
4962
|
+
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",
|
|
4963
|
+
schema: z.object({
|
|
4964
|
+
operation: z.enum(["write", "read", "update"]),
|
|
4965
|
+
expectedVersion: z.number().int().min(0).optional(),
|
|
4966
|
+
todoList: z.array(z.union([todoWriteItemSchema, todoUpdateItemSchema])).optional()
|
|
4967
|
+
}),
|
|
4968
|
+
func: async ({ operation, expectedVersion, todoList }) => {
|
|
4969
|
+
const toolStateRef = manageTodo._stateRef;
|
|
4970
|
+
const onEvent = toolStateRef?.__onEvent;
|
|
4971
|
+
const emitPlanEvent = (list) => {
|
|
4972
|
+
const version = stateRef.planVersion || 1;
|
|
4973
|
+
const adherenceScore = stateRef.adherenceScore || 0;
|
|
4974
|
+
const planData = {
|
|
4975
|
+
source: "manage_todo_list",
|
|
4976
|
+
operation,
|
|
4977
|
+
version,
|
|
4978
|
+
adherenceScore,
|
|
4979
|
+
count: Array.isArray(list) ? list.length : 0
|
|
4980
|
+
};
|
|
4981
|
+
onEvent?.({ type: "plan", todoList: list, ...planData });
|
|
4982
|
+
const traceSession = toolStateRef?.ctx?.__traceSession;
|
|
4983
|
+
recordTraceEvent(traceSession, {
|
|
4984
|
+
type: "plan",
|
|
4985
|
+
label: `Plan ${operation}`,
|
|
4986
|
+
actor: { scope: "agent", name: "manage_todo_list", role: "planner" },
|
|
4987
|
+
sections: [
|
|
4988
|
+
{
|
|
4989
|
+
kind: "summary",
|
|
4990
|
+
label: "Todo List",
|
|
4991
|
+
content: formatTodoListSummary(list)
|
|
4992
|
+
},
|
|
4993
|
+
{
|
|
4994
|
+
kind: "metadata",
|
|
4995
|
+
label: "Plan Metadata",
|
|
4996
|
+
data: planData
|
|
4997
|
+
}
|
|
4998
|
+
],
|
|
4999
|
+
debug: planData
|
|
5000
|
+
});
|
|
5001
|
+
};
|
|
5002
|
+
const currentVersion = stateRef.planVersion || 0;
|
|
5003
|
+
if (operation === "read") {
|
|
5004
|
+
const list = stateRef.todoList || [];
|
|
5005
|
+
emitPlanEvent(list);
|
|
5006
|
+
return list;
|
|
5007
|
+
}
|
|
5008
|
+
if (typeof expectedVersion === "number" && expectedVersion !== currentVersion) {
|
|
5009
|
+
return {
|
|
5010
|
+
status: "error",
|
|
5011
|
+
operation,
|
|
5012
|
+
error: "Plan version mismatch. Read the latest plan and retry.",
|
|
5013
|
+
version: currentVersion,
|
|
5014
|
+
adherenceScore: stateRef.adherenceScore || 0
|
|
5015
|
+
};
|
|
5016
|
+
}
|
|
5017
|
+
if (!Array.isArray(todoList)) {
|
|
5018
|
+
return {
|
|
5019
|
+
status: "error",
|
|
5020
|
+
operation,
|
|
5021
|
+
error: "todoList is required for write and update operations.",
|
|
5022
|
+
version: currentVersion,
|
|
5023
|
+
adherenceScore: stateRef.adherenceScore || 0
|
|
5024
|
+
};
|
|
5025
|
+
}
|
|
5026
|
+
if (operation === "write") {
|
|
5027
|
+
const parsed = z.array(todoWriteItemSchema).safeParse(todoList);
|
|
5028
|
+
if (!parsed.success) {
|
|
5029
|
+
return {
|
|
5030
|
+
status: "error",
|
|
4922
5031
|
operation,
|
|
4923
|
-
|
|
4924
|
-
|
|
4925
|
-
|
|
5032
|
+
error: parsed.error.issues[0]?.message || "Invalid todoList for write.",
|
|
5033
|
+
version: currentVersion,
|
|
5034
|
+
adherenceScore: stateRef.adherenceScore || 0
|
|
4926
5035
|
};
|
|
4927
|
-
onEvent?.({ type: "plan", todoList: list, ...planData });
|
|
4928
|
-
const traceSession = toolStateRef?.ctx?.__traceSession;
|
|
4929
|
-
recordTraceEvent(traceSession, {
|
|
4930
|
-
type: "plan",
|
|
4931
|
-
label: `Plan ${operation}`,
|
|
4932
|
-
actor: { scope: "agent", name: "manage_todo_list", role: "planner" },
|
|
4933
|
-
sections: [
|
|
4934
|
-
{
|
|
4935
|
-
kind: "summary",
|
|
4936
|
-
label: "Todo List",
|
|
4937
|
-
content: formatTodoListSummary(list)
|
|
4938
|
-
},
|
|
4939
|
-
{
|
|
4940
|
-
kind: "metadata",
|
|
4941
|
-
label: "Plan Metadata",
|
|
4942
|
-
data: planData
|
|
4943
|
-
}
|
|
4944
|
-
],
|
|
4945
|
-
debug: planData
|
|
4946
|
-
});
|
|
4947
|
-
};
|
|
4948
|
-
const currentVersion = stateRef.planVersion || 0;
|
|
4949
|
-
if (operation === "read") {
|
|
4950
|
-
const list = stateRef.todoList || [];
|
|
4951
|
-
emitPlanEvent(list);
|
|
4952
|
-
return list;
|
|
4953
5036
|
}
|
|
4954
|
-
|
|
5037
|
+
const normalizedList = parsed.data.map((item) => normalizeTodoItem(item));
|
|
5038
|
+
const validation = validatePlanInvariants(normalizedList, true);
|
|
5039
|
+
if (!validation.ok) {
|
|
4955
5040
|
return {
|
|
4956
5041
|
status: "error",
|
|
4957
5042
|
operation,
|
|
4958
|
-
error:
|
|
5043
|
+
error: validation.error,
|
|
4959
5044
|
version: currentVersion,
|
|
4960
5045
|
adherenceScore: stateRef.adherenceScore || 0
|
|
4961
5046
|
};
|
|
4962
5047
|
}
|
|
4963
|
-
|
|
5048
|
+
stateRef.todoList = normalizedList;
|
|
5049
|
+
} else if (operation === "update") {
|
|
5050
|
+
const parsed = z.array(todoUpdateItemSchema).safeParse(todoList);
|
|
5051
|
+
if (!parsed.success) {
|
|
4964
5052
|
return {
|
|
4965
5053
|
status: "error",
|
|
4966
5054
|
operation,
|
|
4967
|
-
error: "todoList
|
|
5055
|
+
error: parsed.error.issues[0]?.message || "Invalid todoList for update.",
|
|
4968
5056
|
version: currentVersion,
|
|
4969
5057
|
adherenceScore: stateRef.adherenceScore || 0
|
|
4970
5058
|
};
|
|
4971
5059
|
}
|
|
4972
|
-
|
|
4973
|
-
|
|
4974
|
-
|
|
4975
|
-
|
|
4976
|
-
|
|
4977
|
-
|
|
4978
|
-
|
|
4979
|
-
|
|
4980
|
-
|
|
4981
|
-
|
|
4982
|
-
|
|
4983
|
-
|
|
4984
|
-
|
|
4985
|
-
if (
|
|
4986
|
-
return {
|
|
4987
|
-
status: "error",
|
|
4988
|
-
operation,
|
|
4989
|
-
error: validation.error,
|
|
4990
|
-
version: currentVersion,
|
|
4991
|
-
adherenceScore: stateRef.adherenceScore || 0
|
|
4992
|
-
};
|
|
4993
|
-
}
|
|
4994
|
-
stateRef.todoList = normalizedList;
|
|
4995
|
-
} else if (operation === "update") {
|
|
4996
|
-
const parsed = z.array(todoUpdateItemSchema).safeParse(todoList);
|
|
4997
|
-
if (!parsed.success) {
|
|
4998
|
-
return {
|
|
4999
|
-
status: "error",
|
|
5000
|
-
operation,
|
|
5001
|
-
error: parsed.error.issues[0]?.message || "Invalid todoList for update.",
|
|
5002
|
-
version: currentVersion,
|
|
5003
|
-
adherenceScore: stateRef.adherenceScore || 0
|
|
5004
|
-
};
|
|
5005
|
-
}
|
|
5006
|
-
const currentList = Array.isArray(stateRef.todoList) ? stateRef.todoList : [];
|
|
5007
|
-
if (currentList.length === 0) {
|
|
5060
|
+
const currentList = Array.isArray(stateRef.todoList) ? stateRef.todoList : [];
|
|
5061
|
+
if (currentList.length === 0) {
|
|
5062
|
+
return {
|
|
5063
|
+
status: "error",
|
|
5064
|
+
operation,
|
|
5065
|
+
error: "No existing plan to update. Use write first.",
|
|
5066
|
+
version: currentVersion,
|
|
5067
|
+
adherenceScore: stateRef.adherenceScore || 0
|
|
5068
|
+
};
|
|
5069
|
+
}
|
|
5070
|
+
const currentMap = new Map(currentList.map((item) => [item.id, item]));
|
|
5071
|
+
const patchMap = /* @__PURE__ */ new Map();
|
|
5072
|
+
for (const item of parsed.data) {
|
|
5073
|
+
if (patchMap.has(item.id)) {
|
|
5008
5074
|
return {
|
|
5009
5075
|
status: "error",
|
|
5010
5076
|
operation,
|
|
5011
|
-
error: "
|
|
5077
|
+
error: "Update payload contains duplicate todo ids.",
|
|
5012
5078
|
version: currentVersion,
|
|
5013
5079
|
adherenceScore: stateRef.adherenceScore || 0
|
|
5014
5080
|
};
|
|
5015
5081
|
}
|
|
5016
|
-
|
|
5017
|
-
|
|
5018
|
-
for (const item of parsed.data) {
|
|
5019
|
-
if (patchMap.has(item.id)) {
|
|
5020
|
-
return {
|
|
5021
|
-
status: "error",
|
|
5022
|
-
operation,
|
|
5023
|
-
error: "Update payload contains duplicate todo ids.",
|
|
5024
|
-
version: currentVersion,
|
|
5025
|
-
adherenceScore: stateRef.adherenceScore || 0
|
|
5026
|
-
};
|
|
5027
|
-
}
|
|
5028
|
-
patchMap.set(item.id, item);
|
|
5029
|
-
if (!currentMap.has(item.id)) {
|
|
5030
|
-
return {
|
|
5031
|
-
status: "error",
|
|
5032
|
-
operation,
|
|
5033
|
-
error: `Cannot update missing todo id ${item.id}. Use write to replace the plan.`,
|
|
5034
|
-
version: currentVersion,
|
|
5035
|
-
adherenceScore: stateRef.adherenceScore || 0
|
|
5036
|
-
};
|
|
5037
|
-
}
|
|
5038
|
-
}
|
|
5039
|
-
const mergedList = currentList.map((item) => {
|
|
5040
|
-
const patch = patchMap.get(item.id);
|
|
5041
|
-
return patch ? normalizeTodoItem(patch, item) : item;
|
|
5042
|
-
});
|
|
5043
|
-
const validation = validatePlanInvariants(mergedList, false);
|
|
5044
|
-
if (!validation.ok) {
|
|
5082
|
+
patchMap.set(item.id, item);
|
|
5083
|
+
if (!currentMap.has(item.id)) {
|
|
5045
5084
|
return {
|
|
5046
5085
|
status: "error",
|
|
5047
5086
|
operation,
|
|
5048
|
-
error:
|
|
5087
|
+
error: `Cannot update missing todo id ${item.id}. Use write to replace the plan.`,
|
|
5049
5088
|
version: currentVersion,
|
|
5050
5089
|
adherenceScore: stateRef.adherenceScore || 0
|
|
5051
5090
|
};
|
|
5052
5091
|
}
|
|
5053
|
-
stateRef.todoList = mergedList;
|
|
5054
5092
|
}
|
|
5055
|
-
|
|
5056
|
-
|
|
5057
|
-
|
|
5058
|
-
|
|
5059
|
-
|
|
5060
|
-
|
|
5061
|
-
|
|
5062
|
-
|
|
5063
|
-
|
|
5064
|
-
|
|
5065
|
-
|
|
5066
|
-
|
|
5067
|
-
|
|
5068
|
-
|
|
5069
|
-
|
|
5070
|
-
|
|
5093
|
+
const mergedList = currentList.map((item) => {
|
|
5094
|
+
const patch = patchMap.get(item.id);
|
|
5095
|
+
return patch ? normalizeTodoItem(patch, item) : item;
|
|
5096
|
+
});
|
|
5097
|
+
const validation = validatePlanInvariants(mergedList, false);
|
|
5098
|
+
if (!validation.ok) {
|
|
5099
|
+
return {
|
|
5100
|
+
status: "error",
|
|
5101
|
+
operation,
|
|
5102
|
+
error: validation.error,
|
|
5103
|
+
version: currentVersion,
|
|
5104
|
+
adherenceScore: stateRef.adherenceScore || 0
|
|
5105
|
+
};
|
|
5106
|
+
}
|
|
5107
|
+
stateRef.todoList = mergedList;
|
|
5108
|
+
}
|
|
5109
|
+
stateRef.planVersion = currentVersion + 1;
|
|
5110
|
+
stateRef.adherenceScore = calculateAdherenceScore(stateRef.todoList || []);
|
|
5111
|
+
const payload = {
|
|
5112
|
+
status: "ok",
|
|
5113
|
+
operation,
|
|
5114
|
+
count: Array.isArray(todoList) ? todoList.length : void 0,
|
|
5115
|
+
version: stateRef.planVersion || 1,
|
|
5116
|
+
adherenceScore: stateRef.adherenceScore || 0
|
|
5117
|
+
};
|
|
5118
|
+
emitPlanEvent(stateRef.todoList || []);
|
|
5119
|
+
return payload;
|
|
5120
|
+
}
|
|
5121
|
+
});
|
|
5122
|
+
manageTodo._stateRef = stateRef;
|
|
5123
|
+
return manageTodo;
|
|
5124
|
+
}
|
|
5125
|
+
function createGetToolResponseTool(stateRef) {
|
|
5071
5126
|
const getTool = createTool({
|
|
5072
5127
|
name: "get_tool_response",
|
|
5073
|
-
description: "RETRIEVE the full output of a tool execution whose response was archived, dropped, or later compacted in conversation history.
|
|
5128
|
+
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.",
|
|
5074
5129
|
schema: z.object({ executionId: z.string().describe("Tool execution id or original tool_call_id") }),
|
|
5075
5130
|
maxExecutionsPerRun: 8,
|
|
5076
5131
|
func: async ({ executionId }) => {
|
|
5132
|
+
if (!hasToolResponseRecoveryReference(stateRef.messages, executionId)) {
|
|
5133
|
+
return "Execution not recoverable from the visible transcript. Use this only when the conversation already shows a reduced tool-response marker for that executionId.";
|
|
5134
|
+
}
|
|
5077
5135
|
const matchesExecution = (t) => t?.executionId === executionId || t?.tool_call_id === executionId;
|
|
5078
5136
|
let execution = stateRef.toolHistory?.find((t) => matchesExecution(t));
|
|
5079
5137
|
if (!execution) {
|
|
@@ -5086,7 +5144,16 @@ function createContextTools(stateRef, opts) {
|
|
|
5086
5144
|
}
|
|
5087
5145
|
});
|
|
5088
5146
|
getTool._stateRef = stateRef;
|
|
5089
|
-
|
|
5147
|
+
return getTool;
|
|
5148
|
+
}
|
|
5149
|
+
function createContextTools(stateRef, opts) {
|
|
5150
|
+
const tools = [];
|
|
5151
|
+
if (opts?.planningEnabled) {
|
|
5152
|
+
tools.push(createManageTodoTool(stateRef));
|
|
5153
|
+
}
|
|
5154
|
+
if (opts?.includeGetToolResponse ?? true) {
|
|
5155
|
+
tools.push(createGetToolResponseTool(stateRef));
|
|
5156
|
+
}
|
|
5090
5157
|
return tools;
|
|
5091
5158
|
}
|
|
5092
5159
|
|
|
@@ -5254,9 +5321,11 @@ function createSmartAgent(opts) {
|
|
|
5254
5321
|
useTodoList: planningEnabled
|
|
5255
5322
|
};
|
|
5256
5323
|
const stateRef = { toolHistory: void 0, toolHistoryArchived: void 0, todoList: void 0, planVersion: 0, adherenceScore: 0 };
|
|
5257
|
-
const contextTools = createContextTools(stateRef, { planningEnabled });
|
|
5258
|
-
const
|
|
5259
|
-
const
|
|
5324
|
+
const contextTools = createContextTools(stateRef, { planningEnabled, includeGetToolResponse: false });
|
|
5325
|
+
const getToolResponseTool = createGetToolResponseTool(stateRef);
|
|
5326
|
+
const toolsWithoutRecovery = [...opts.tools ?? [], ...contextTools];
|
|
5327
|
+
const toolsWithRecovery = [...toolsWithoutRecovery, getToolResponseTool];
|
|
5328
|
+
const base = createAgent({ ...runtimeOpts, tools: toolsWithoutRecovery });
|
|
5260
5329
|
base.__runtime.runtimeProfile = resolved.runtimeProfile;
|
|
5261
5330
|
base.__runtime.smart = resolved;
|
|
5262
5331
|
const summarizationEnabled = resolved.summarization.enable !== false;
|
|
@@ -5314,6 +5383,27 @@ function createSmartAgent(opts) {
|
|
|
5314
5383
|
);
|
|
5315
5384
|
return { role: "system", content: sys };
|
|
5316
5385
|
}
|
|
5386
|
+
function syncRuntimeTools(currentState, currentMessages) {
|
|
5387
|
+
const needsRecoveryTool = hasToolResponseRecoveryReference(currentMessages);
|
|
5388
|
+
const nextTools = needsRecoveryTool ? toolsWithRecovery : toolsWithoutRecovery;
|
|
5389
|
+
const currentRuntime = currentState.agent || base.__runtime;
|
|
5390
|
+
if (currentRuntime.tools === nextTools) {
|
|
5391
|
+
return currentState;
|
|
5392
|
+
}
|
|
5393
|
+
return {
|
|
5394
|
+
...currentState,
|
|
5395
|
+
agent: {
|
|
5396
|
+
...currentRuntime,
|
|
5397
|
+
tools: nextTools
|
|
5398
|
+
}
|
|
5399
|
+
};
|
|
5400
|
+
}
|
|
5401
|
+
function producedTerminalAssistantTurn(messages) {
|
|
5402
|
+
const lastAssistant = [...messages].reverse().find((message) => message?.role === "assistant");
|
|
5403
|
+
if (!lastAssistant) return false;
|
|
5404
|
+
const toolCalls = Array.isArray(lastAssistant.tool_calls) ? lastAssistant.tool_calls : [];
|
|
5405
|
+
return toolCalls.length === 0;
|
|
5406
|
+
}
|
|
5317
5407
|
async function trySummarize(currentState, currentRawMessages) {
|
|
5318
5408
|
if (!summarizer) return { state: currentState, rawMessages: currentRawMessages, compressed: false };
|
|
5319
5409
|
const delta = await summarizer(currentState);
|
|
@@ -5335,13 +5425,13 @@ function createSmartAgent(opts) {
|
|
|
5335
5425
|
stateRef.adherenceScore = input.plan?.adherenceScore || 0;
|
|
5336
5426
|
const alreadyHasSystem = Array.isArray(input.messages) && input.messages[0]?.role === "system";
|
|
5337
5427
|
const seedMessages = alreadyHasSystem ? [...input.messages || []] : [systemMessage2(), ...input.messages || []];
|
|
5338
|
-
let state = await syncMemory({ ...input, messages: seedMessages });
|
|
5428
|
+
let state = syncRuntimeTools(await syncMemory({ ...input, messages: seedMessages }), seedMessages);
|
|
5339
5429
|
let lastResult = null;
|
|
5340
5430
|
let rawMessages = [...seedMessages];
|
|
5341
5431
|
const effectiveMaxToolCalls = config?.limits?.maxToolCalls ?? resolved.limits.maxToolCalls ?? 10;
|
|
5342
5432
|
const iterationLimit = Math.max(effectiveMaxToolCalls * 3 + 5, 30);
|
|
5343
5433
|
for (let i = 0; i < iterationLimit; i++) {
|
|
5344
|
-
state = { ...state, messages: rawMessages };
|
|
5434
|
+
state = syncRuntimeTools({ ...state, messages: rawMessages }, rawMessages);
|
|
5345
5435
|
const next = summarizationEnabled ? decideBefore(state) : "agent";
|
|
5346
5436
|
if (next === "contextSummarize" && summarizer) {
|
|
5347
5437
|
const result = await trySummarize(state, rawMessages);
|
|
@@ -5368,7 +5458,7 @@ function createSmartAgent(opts) {
|
|
|
5368
5458
|
if (currentPlan && !state.plan) {
|
|
5369
5459
|
state = { ...state, plan: currentPlan };
|
|
5370
5460
|
}
|
|
5371
|
-
state = syncPlanState(await syncMemory(state));
|
|
5461
|
+
state = syncRuntimeTools(syncPlanState(await syncMemory(state)), rawMessages);
|
|
5372
5462
|
stateRef.toolHistory = state.toolHistory;
|
|
5373
5463
|
stateRef.toolHistoryArchived = state.toolHistoryArchived;
|
|
5374
5464
|
if (state.ctx?.__needsSummarization && summarizer) {
|
|
@@ -5382,6 +5472,7 @@ function createSmartAgent(opts) {
|
|
|
5382
5472
|
}
|
|
5383
5473
|
if (state.ctx?.__finalizedDueToStructuredOutput) break;
|
|
5384
5474
|
if (opts.outputSchema && lastResult?.output != null) break;
|
|
5475
|
+
if (producedTerminalAssistantTurn(appendedMessages)) break;
|
|
5385
5476
|
if (summarizationEnabled) {
|
|
5386
5477
|
const after = decideAfter(state);
|
|
5387
5478
|
if (after === "contextSummarize" && summarizer) {
|
|
@@ -6030,7 +6121,7 @@ var OpenAIProvider = class extends BaseProvider {
|
|
|
6030
6121
|
if (request.tools?.length) {
|
|
6031
6122
|
body.tools = request.tools.map((t) => this.toOpenAITool(t));
|
|
6032
6123
|
}
|
|
6033
|
-
if (request.toolChoice != null) {
|
|
6124
|
+
if (request.toolChoice != null && request.tools?.length) {
|
|
6034
6125
|
if (typeof request.toolChoice === "string") {
|
|
6035
6126
|
body.tool_choice = request.toolChoice;
|
|
6036
6127
|
} else {
|
|
@@ -7311,7 +7402,7 @@ function fromNativeProvider(provider, options) {
|
|
|
7311
7402
|
const reasoningCfg = reasoningOverride ?? opts?.reasoning;
|
|
7312
7403
|
if (reasoningCfg) req.reasoning = reasoningCfg;
|
|
7313
7404
|
const tc = invokeOptions?.tool_choice ?? invokeOptions?.toolChoice;
|
|
7314
|
-
if (tc) {
|
|
7405
|
+
if (tc && tools?.length) {
|
|
7315
7406
|
req.toolChoice = tc;
|
|
7316
7407
|
}
|
|
7317
7408
|
const rf = invokeOptions?.response_format;
|
|
@@ -7655,6 +7746,6 @@ function createProvider(config) {
|
|
|
7655
7746
|
}
|
|
7656
7747
|
}
|
|
7657
7748
|
|
|
7658
|
-
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 };
|
|
7749
|
+
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 };
|
|
7659
7750
|
//# sourceMappingURL=index.mjs.map
|
|
7660
7751
|
//# sourceMappingURL=index.mjs.map
|