@cognipeer/agent-sdk 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -2080,235 +2080,134 @@ function createAgentCoreNode(opts) {
2080
2080
 
2081
2081
  // src/smart/runtimeConfig.ts
2082
2082
  var DEFAULT_CRITICAL_TOOLS = ["response", "manage_todo_list", "get_tool_response"];
2083
+ var BASE_DEFAULTS = {
2084
+ limits: { maxToolCalls: 8, maxParallelTools: 2, maxContextTokens: 24e3 },
2085
+ summarization: {
2086
+ enable: true,
2087
+ maxTokens: 24e3,
2088
+ summaryTriggerTokens: 17e3,
2089
+ summaryPromptMaxTokens: 7e3,
2090
+ summaryCompressionRatioTarget: 0.35,
2091
+ summaryMode: "incremental",
2092
+ promptTemplate: "",
2093
+ toolFreeCall: true,
2094
+ integrityCheck: true
2095
+ },
2096
+ context: {
2097
+ policy: "hybrid",
2098
+ lastTurnsToKeep: 8,
2099
+ toolResponsePolicy: "summarize_archive",
2100
+ archiveLargeToolResponses: true,
2101
+ retrieveArchivedToolResponseOnDemand: true,
2102
+ budget: {
2103
+ systemReserveTokens: 1200,
2104
+ goalsReserveTokens: 1200,
2105
+ recentTurnsReserveTokens: 5200,
2106
+ toolResponseReserveTokens: 2800
2107
+ }
2108
+ },
2109
+ planning: {
2110
+ mode: "off",
2111
+ replanPolicy: "on_failure",
2112
+ everyNSteps: 0
2113
+ },
2114
+ memory: {
2115
+ provider: "inMemory",
2116
+ scope: "session",
2117
+ writePolicy: "auto_important",
2118
+ readPolicy: "hybrid"
2119
+ },
2120
+ delegation: {
2121
+ mode: "role_based",
2122
+ maxDelegationDepth: 2,
2123
+ maxChildCalls: 4,
2124
+ maxParallelChild: 2,
2125
+ childContextPolicy: "scoped",
2126
+ requireJsonOutputContract: true
2127
+ },
2128
+ toolResponses: {
2129
+ maxToolResponseChars: 3600,
2130
+ maxToolResponseTokens: 1200,
2131
+ defaultPolicy: "keep_structured",
2132
+ largeResponsePolicy: "summarize_archive",
2133
+ toolResponseRetentionByTool: {},
2134
+ criticalTools: [...DEFAULT_CRITICAL_TOOLS],
2135
+ schemaValidation: "strict",
2136
+ retryOnSchemaError: true,
2137
+ fallbackPolicy: "keep_structured"
2138
+ }
2139
+ };
2140
+ function buildProfile(overrides) {
2141
+ return {
2142
+ limits: { ...BASE_DEFAULTS.limits, ...overrides.limits },
2143
+ summarization: { ...BASE_DEFAULTS.summarization, ...overrides.summarization },
2144
+ context: {
2145
+ ...BASE_DEFAULTS.context,
2146
+ ...overrides.context,
2147
+ budget: { ...BASE_DEFAULTS.context.budget, ...overrides.context?.budget }
2148
+ },
2149
+ planning: { ...BASE_DEFAULTS.planning, ...overrides.planning },
2150
+ memory: { ...BASE_DEFAULTS.memory, ...overrides.memory },
2151
+ delegation: { ...BASE_DEFAULTS.delegation, ...overrides.delegation },
2152
+ toolResponses: {
2153
+ ...BASE_DEFAULTS.toolResponses,
2154
+ ...overrides.toolResponses,
2155
+ criticalTools: overrides.toolResponses?.criticalTools ?? [...DEFAULT_CRITICAL_TOOLS],
2156
+ toolResponseRetentionByTool: overrides.toolResponses?.toolResponseRetentionByTool ?? {}
2157
+ }
2158
+ };
2159
+ }
2083
2160
  var DEFAULT_PROFILE_CONFIGS = {
2084
- fast: {
2161
+ fast: buildProfile({
2085
2162
  limits: { maxToolCalls: 4, maxParallelTools: 1, maxContextTokens: 12e3 },
2086
2163
  summarization: {
2087
- enable: true,
2088
2164
  maxTokens: 12e3,
2089
2165
  summaryTriggerTokens: 9e3,
2090
2166
  summaryPromptMaxTokens: 5e3,
2091
- summaryCompressionRatioTarget: 0.4,
2092
- summaryMode: "incremental",
2093
- promptTemplate: "",
2094
- toolFreeCall: true,
2095
- integrityCheck: true
2167
+ summaryCompressionRatioTarget: 0.4
2096
2168
  },
2097
2169
  context: {
2098
- policy: "hybrid",
2099
2170
  lastTurnsToKeep: 6,
2100
2171
  toolResponsePolicy: "keep_structured",
2101
- archiveLargeToolResponses: true,
2102
- retrieveArchivedToolResponseOnDemand: true,
2103
- budget: {
2104
- systemReserveTokens: 1e3,
2105
- goalsReserveTokens: 900,
2106
- recentTurnsReserveTokens: 3200,
2107
- toolResponseReserveTokens: 1800
2108
- }
2109
- },
2110
- planning: {
2111
- mode: "off",
2112
- replanPolicy: "on_failure",
2113
- everyNSteps: 0
2114
- },
2115
- memory: {
2116
- provider: "inMemory",
2117
- scope: "session",
2118
- writePolicy: "auto_important",
2119
- readPolicy: "recent_only"
2172
+ budget: { systemReserveTokens: 1e3, goalsReserveTokens: 900, recentTurnsReserveTokens: 3200, toolResponseReserveTokens: 1800 }
2120
2173
  },
2121
- delegation: {
2122
- mode: "off",
2123
- maxDelegationDepth: 1,
2124
- maxChildCalls: 2,
2125
- maxParallelChild: 1,
2126
- childContextPolicy: "minimal",
2127
- requireJsonOutputContract: true
2128
- },
2129
- toolResponses: {
2130
- maxToolResponseChars: 2400,
2131
- maxToolResponseTokens: 800,
2132
- defaultPolicy: "keep_structured",
2133
- largeResponsePolicy: "summarize_archive",
2134
- toolResponseRetentionByTool: {},
2135
- criticalTools: [...DEFAULT_CRITICAL_TOOLS],
2136
- schemaValidation: "strict",
2137
- retryOnSchemaError: true,
2138
- fallbackPolicy: "keep_structured"
2139
- }
2140
- },
2141
- balanced: {
2142
- limits: { maxToolCalls: 8, maxParallelTools: 2, maxContextTokens: 24e3 },
2143
- summarization: {
2144
- enable: true,
2145
- maxTokens: 24e3,
2146
- summaryTriggerTokens: 17e3,
2147
- summaryPromptMaxTokens: 7e3,
2148
- summaryCompressionRatioTarget: 0.35,
2149
- summaryMode: "incremental",
2150
- promptTemplate: "",
2151
- toolFreeCall: true,
2152
- integrityCheck: true
2153
- },
2154
- context: {
2155
- policy: "hybrid",
2156
- lastTurnsToKeep: 8,
2157
- toolResponsePolicy: "summarize_archive",
2158
- archiveLargeToolResponses: true,
2159
- retrieveArchivedToolResponseOnDemand: true,
2160
- budget: {
2161
- systemReserveTokens: 1200,
2162
- goalsReserveTokens: 1200,
2163
- recentTurnsReserveTokens: 5200,
2164
- toolResponseReserveTokens: 2800
2165
- }
2166
- },
2167
- planning: {
2168
- mode: "off",
2169
- replanPolicy: "on_failure",
2170
- everyNSteps: 0
2171
- },
2172
- memory: {
2173
- provider: "inMemory",
2174
- scope: "session",
2175
- writePolicy: "auto_important",
2176
- readPolicy: "hybrid"
2177
- },
2178
- delegation: {
2179
- mode: "role_based",
2180
- maxDelegationDepth: 2,
2181
- maxChildCalls: 4,
2182
- maxParallelChild: 2,
2183
- childContextPolicy: "scoped",
2184
- requireJsonOutputContract: true
2185
- },
2186
- toolResponses: {
2187
- maxToolResponseChars: 3600,
2188
- maxToolResponseTokens: 1200,
2189
- defaultPolicy: "keep_structured",
2190
- largeResponsePolicy: "summarize_archive",
2191
- toolResponseRetentionByTool: {},
2192
- criticalTools: [...DEFAULT_CRITICAL_TOOLS],
2193
- schemaValidation: "strict",
2194
- retryOnSchemaError: true,
2195
- fallbackPolicy: "keep_structured"
2196
- }
2197
- },
2198
- deep: {
2174
+ memory: { readPolicy: "recent_only" },
2175
+ delegation: { mode: "off", maxDelegationDepth: 1, maxChildCalls: 2, maxParallelChild: 1, childContextPolicy: "minimal" },
2176
+ toolResponses: { maxToolResponseChars: 2400, maxToolResponseTokens: 800 }
2177
+ }),
2178
+ balanced: buildProfile({}),
2179
+ deep: buildProfile({
2199
2180
  limits: { maxToolCalls: 14, maxParallelTools: 3, maxContextTokens: 42e3 },
2200
2181
  summarization: {
2201
- enable: true,
2202
2182
  maxTokens: 42e3,
2203
2183
  summaryTriggerTokens: 3e4,
2204
2184
  summaryPromptMaxTokens: 9e3,
2205
- summaryCompressionRatioTarget: 0.3,
2206
- summaryMode: "incremental",
2207
- promptTemplate: "",
2208
- toolFreeCall: true,
2209
- integrityCheck: true
2185
+ summaryCompressionRatioTarget: 0.3
2210
2186
  },
2211
2187
  context: {
2212
- policy: "hybrid",
2213
2188
  lastTurnsToKeep: 12,
2214
- toolResponsePolicy: "summarize_archive",
2215
- archiveLargeToolResponses: true,
2216
- retrieveArchivedToolResponseOnDemand: true,
2217
- budget: {
2218
- systemReserveTokens: 1400,
2219
- goalsReserveTokens: 1600,
2220
- recentTurnsReserveTokens: 7e3,
2221
- toolResponseReserveTokens: 3600
2222
- }
2223
- },
2224
- planning: {
2225
- mode: "off",
2226
- replanPolicy: "on_failure",
2227
- everyNSteps: 0
2228
- },
2229
- memory: {
2230
- provider: "inMemory",
2231
- scope: "workspace",
2232
- writePolicy: "auto_important",
2233
- readPolicy: "hybrid"
2189
+ budget: { systemReserveTokens: 1400, goalsReserveTokens: 1600, recentTurnsReserveTokens: 7e3, toolResponseReserveTokens: 3600 }
2234
2190
  },
2235
- delegation: {
2236
- mode: "role_based",
2237
- maxDelegationDepth: 3,
2238
- maxChildCalls: 6,
2239
- maxParallelChild: 2,
2240
- childContextPolicy: "scoped",
2241
- requireJsonOutputContract: true
2242
- },
2243
- toolResponses: {
2244
- maxToolResponseChars: 5400,
2245
- maxToolResponseTokens: 1800,
2246
- defaultPolicy: "keep_structured",
2247
- largeResponsePolicy: "summarize_archive",
2248
- toolResponseRetentionByTool: {},
2249
- criticalTools: [...DEFAULT_CRITICAL_TOOLS],
2250
- schemaValidation: "strict",
2251
- retryOnSchemaError: true,
2252
- fallbackPolicy: "keep_structured"
2253
- }
2254
- },
2255
- research: {
2191
+ memory: { scope: "workspace" },
2192
+ delegation: { maxDelegationDepth: 3, maxChildCalls: 6 },
2193
+ toolResponses: { maxToolResponseChars: 5400, maxToolResponseTokens: 1800 }
2194
+ }),
2195
+ research: buildProfile({
2256
2196
  limits: { maxToolCalls: 20, maxParallelTools: 4, maxContextTokens: 56e3 },
2257
2197
  summarization: {
2258
- enable: true,
2259
2198
  maxTokens: 56e3,
2260
2199
  summaryTriggerTokens: 42e3,
2261
2200
  summaryPromptMaxTokens: 1e4,
2262
- summaryCompressionRatioTarget: 0.28,
2263
- summaryMode: "incremental",
2264
- promptTemplate: "",
2265
- toolFreeCall: true,
2266
- integrityCheck: true
2201
+ summaryCompressionRatioTarget: 0.28
2267
2202
  },
2268
2203
  context: {
2269
- policy: "hybrid",
2270
2204
  lastTurnsToKeep: 20,
2271
- toolResponsePolicy: "summarize_archive",
2272
- archiveLargeToolResponses: true,
2273
- retrieveArchivedToolResponseOnDemand: true,
2274
- budget: {
2275
- systemReserveTokens: 1600,
2276
- goalsReserveTokens: 1800,
2277
- recentTurnsReserveTokens: 9e3,
2278
- toolResponseReserveTokens: 4800
2279
- }
2280
- },
2281
- planning: {
2282
- mode: "off",
2283
- replanPolicy: "on_failure",
2284
- everyNSteps: 0
2285
- },
2286
- memory: {
2287
- provider: "inMemory",
2288
- scope: "workspace",
2289
- writePolicy: "auto_important",
2290
- readPolicy: "hybrid"
2291
- },
2292
- delegation: {
2293
- mode: "automatic",
2294
- maxDelegationDepth: 4,
2295
- maxChildCalls: 8,
2296
- maxParallelChild: 3,
2297
- childContextPolicy: "full",
2298
- requireJsonOutputContract: true
2205
+ budget: { systemReserveTokens: 1600, goalsReserveTokens: 1800, recentTurnsReserveTokens: 9e3, toolResponseReserveTokens: 4800 }
2299
2206
  },
2300
- toolResponses: {
2301
- maxToolResponseChars: 7200,
2302
- maxToolResponseTokens: 2200,
2303
- defaultPolicy: "keep_structured",
2304
- largeResponsePolicy: "summarize_archive",
2305
- toolResponseRetentionByTool: {},
2306
- criticalTools: [...DEFAULT_CRITICAL_TOOLS],
2307
- schemaValidation: "strict",
2308
- retryOnSchemaError: true,
2309
- fallbackPolicy: "keep_structured"
2310
- }
2311
- }
2207
+ memory: { scope: "workspace" },
2208
+ delegation: { mode: "automatic", maxDelegationDepth: 4, maxChildCalls: 8, maxParallelChild: 3, childContextPolicy: "full" },
2209
+ toolResponses: { maxToolResponseChars: 7200, maxToolResponseTokens: 2200 }
2210
+ })
2312
2211
  };
2313
2212
  function mergeLimits(base, override) {
2314
2213
  return {
@@ -2451,16 +2350,52 @@ function countMessagesTokens(messages) {
2451
2350
  return countApproxTokens(allText) + messages.length * 4;
2452
2351
  }
2453
2352
 
2454
- // src/smart/toolResponses.ts
2455
- function safeStringify(value) {
2353
+ // src/utils/content.ts
2354
+ function contentToString(content) {
2355
+ try {
2356
+ if (content == null) return "";
2357
+ if (typeof content === "string") return content;
2358
+ if (Array.isArray(content)) {
2359
+ return content.map((p) => {
2360
+ if (!p || typeof p !== "object") return String(p);
2361
+ if (p.type === "text") return String(p.text ?? "");
2362
+ if (p.type === "image_url") {
2363
+ const img = p.image_url;
2364
+ const url = typeof img === "string" ? img : img?.url;
2365
+ const detail = typeof img === "string" ? void 0 : img?.detail;
2366
+ return `[image:${url || "unknown"}${detail ? ` detail=${detail}` : ""}]`;
2367
+ }
2368
+ return JSON.stringify(p);
2369
+ }).join("\n");
2370
+ }
2371
+ return JSON.stringify(content);
2372
+ } catch {
2373
+ return String(content);
2374
+ }
2375
+ }
2376
+ function mergeContentsToString(contents) {
2377
+ return contents.map((c) => contentToString(c)).join("\n");
2378
+ }
2379
+ function safeStringify(value, pretty = false) {
2380
+ if (value == null) return "";
2456
2381
  if (typeof value === "string") return value;
2457
2382
  try {
2458
- const serialized = JSON.stringify(value);
2459
- return typeof serialized === "string" ? serialized : String(value);
2383
+ return JSON.stringify(value, null, pretty ? 2 : void 0) ?? String(value);
2460
2384
  } catch {
2461
2385
  return String(value);
2462
2386
  }
2463
2387
  }
2388
+ function extractMessageText2(message) {
2389
+ if (!message) return "";
2390
+ const content = message.content;
2391
+ if (typeof content === "string") return content;
2392
+ if (Array.isArray(content)) {
2393
+ return content.map((part) => typeof part === "string" ? part : part?.text ?? part?.content ?? "").join("");
2394
+ }
2395
+ return "";
2396
+ }
2397
+
2398
+ // src/smart/toolResponses.ts
2464
2399
  function summarizeObject(value) {
2465
2400
  if (value == null) return "null";
2466
2401
  if (typeof value === "string") {
@@ -3224,6 +3159,21 @@ function resolveToolApprovalState(state, resolution) {
3224
3159
  };
3225
3160
  }
3226
3161
 
3162
+ // src/utils/syntheticMessages.ts
3163
+ function isSyntheticSummaryMessage(message) {
3164
+ if (!message) return false;
3165
+ if (message.role === "tool" && message.name === "summarize_context") {
3166
+ return true;
3167
+ }
3168
+ if (message.role === "assistant" && Array.isArray(message.tool_calls)) {
3169
+ return message.tool_calls.some((toolCall) => {
3170
+ const toolName = toolCall?.function?.name || toolCall?.name;
3171
+ return toolName === "summarize_context";
3172
+ });
3173
+ }
3174
+ return false;
3175
+ }
3176
+
3227
3177
  // src/structuredOutput/manager.ts
3228
3178
  var StructuredOutputManager = class {
3229
3179
  constructor(schema, strategy, config) {
@@ -3372,26 +3322,6 @@ var StructuredOutputManager = class {
3372
3322
  };
3373
3323
 
3374
3324
  // src/agent.ts
3375
- function isSyntheticSummaryMessage(message) {
3376
- if (!message) return false;
3377
- if (message.role === "tool" && message.name === "summarize_context") {
3378
- return true;
3379
- }
3380
- if (message.role === "assistant" && Array.isArray(message.tool_calls)) {
3381
- return message.tool_calls.some((toolCall) => {
3382
- const toolName = toolCall?.function?.name || toolCall?.name;
3383
- return toolName === "summarize_context";
3384
- });
3385
- }
3386
- return false;
3387
- }
3388
- function getMessageText(message) {
3389
- if (typeof message?.content === "string") return message.content;
3390
- if (Array.isArray(message?.content)) {
3391
- return message.content.map((chunk) => typeof chunk === "string" ? chunk : chunk?.text ?? chunk?.content ?? "").join("");
3392
- }
3393
- return "";
3394
- }
3395
3325
  function getLastAssistantMessage(messages) {
3396
3326
  for (let index = messages.length - 1; index >= 0; index -= 1) {
3397
3327
  if (messages[index]?.role === "assistant") {
@@ -3685,6 +3615,21 @@ function createAgent(opts) {
3685
3615
  }
3686
3616
  if (toolCalls.length === 0) {
3687
3617
  if (soManager && !state.ctx?.__finalizedDueToStructuredOutput && !state.ctx?.__structuredOutputForceFinalize) {
3618
+ if (soManager.strategy.kind === "native") {
3619
+ const assistantText = extractMessageText2(lastMsg);
3620
+ if (assistantText) {
3621
+ const parsed = soManager.parseFromContent(assistantText);
3622
+ if (parsed.success) {
3623
+ const ctx2 = {
3624
+ ...state.ctx || {},
3625
+ __finalizedDueToStructuredOutput: true,
3626
+ __structuredOutputParsed: parsed.data
3627
+ };
3628
+ state = { ...state, ctx: ctx2 };
3629
+ }
3630
+ }
3631
+ break;
3632
+ }
3688
3633
  const nudge = soManager.buildNudgeMessage(false);
3689
3634
  const ctx = { ...state.ctx || {}, __structuredOutputForceFinalize: true };
3690
3635
  state = { ...state, messages: [...state.messages, nudge], ctx };
@@ -3701,6 +3646,23 @@ function createAgent(opts) {
3701
3646
  if (state.ctx?.__finalizedDueToStructuredOutput) break;
3702
3647
  }
3703
3648
  if (soManager && !state.ctx?.__finalizedDueToStructuredOutput) {
3649
+ const lastForParse = state.messages[state.messages.length - 1];
3650
+ if (lastForParse?.role === "assistant") {
3651
+ const assistantText = extractMessageText2(lastForParse);
3652
+ if (assistantText) {
3653
+ const parsed = soManager.parseFromContent(assistantText);
3654
+ if (parsed.success) {
3655
+ const ctx = {
3656
+ ...state.ctx || {},
3657
+ __finalizedDueToStructuredOutput: true,
3658
+ __structuredOutputParsed: parsed.data
3659
+ };
3660
+ state = { ...state, ctx };
3661
+ }
3662
+ }
3663
+ }
3664
+ }
3665
+ if (soManager && soManager.strategy.kind === "tool_based" && !state.ctx?.__finalizedDueToStructuredOutput) {
3704
3666
  const maxPostLoopRetries = soManager.maxRetries;
3705
3667
  for (let postRetry = 0; postRetry < maxPostLoopRetries; postRetry++) {
3706
3668
  if (state.ctx?.__finalizedDueToStructuredOutput) break;
@@ -3809,7 +3771,7 @@ function createAgent(opts) {
3809
3771
  status: "success"
3810
3772
  });
3811
3773
  const finalAssistantMsg = getLastAssistantMessage(res.messages);
3812
- const content = getMessageText(finalAssistantMsg);
3774
+ const content = extractMessageText2(finalAssistantMsg);
3813
3775
  let parsed = void 0;
3814
3776
  let outputError = void 0;
3815
3777
  if (soManager) {
@@ -4009,13 +3971,6 @@ function createAgentNode(opts) {
4009
3971
  }
4010
3972
 
4011
3973
  // src/smart/contextPolicy.ts
4012
- function messageText(message) {
4013
- if (typeof message.content === "string") return message.content;
4014
- if (Array.isArray(message.content)) {
4015
- return message.content.map((part) => typeof part === "string" ? part : part?.text ?? part?.content ?? JSON.stringify(part)).join(" ");
4016
- }
4017
- return "";
4018
- }
4019
3974
  function collectRecentTurns(messages, lastTurnsToKeep) {
4020
3975
  if (lastTurnsToKeep <= 0) return [];
4021
3976
  const systemPrefix = messages.filter((message, index) => index === 0 && message.role === "system");
@@ -4056,10 +4011,6 @@ function renderStructuredSummary(summary) {
4056
4011
  lines.push("Open questions:");
4057
4012
  lines.push(...summary.open_questions.map((question) => `- ${question}`));
4058
4013
  }
4059
- if (summary.discarded_obsolete.length > 0) {
4060
- lines.push("Discarded obsolete:");
4061
- lines.push(...summary.discarded_obsolete.map((item) => `- ${item}`));
4062
- }
4063
4014
  return lines.join("\n");
4064
4015
  }
4065
4016
  function renderMemoryBlock(facts) {
@@ -4072,7 +4023,7 @@ function renderMemoryBlock(facts) {
4072
4023
  function clampToBudget(messages, maxContextTokens) {
4073
4024
  let working = [...messages];
4074
4025
  while (working.length > 2) {
4075
- const tokenCount = countApproxTokens(working.map(messageText).join("\n"));
4026
+ const tokenCount = countApproxTokens(working.map(extractMessageText2).join("\n"));
4076
4027
  if (tokenCount <= maxContextTokens) return working;
4077
4028
  const firstNonSystem = working.findIndex((message, index) => !(index === 0 && message.role === "system"));
4078
4029
  if (firstNonSystem < 0) break;
@@ -4146,18 +4097,6 @@ function buildModelMessages(state, config) {
4146
4097
  // src/nodes/contextSummarize.ts
4147
4098
  var systemMessage = (content) => ({ role: "system", content });
4148
4099
  var humanMessage = (content) => ({ role: "user", content });
4149
- function isSyntheticSummaryToolMessage(message) {
4150
- return message.role === "tool" && message.name === "summarize_context";
4151
- }
4152
- function isSyntheticSummaryAssistantMessage(message) {
4153
- if (message.role !== "assistant" || !Array.isArray(message.tool_calls)) {
4154
- return false;
4155
- }
4156
- return message.tool_calls.some((toolCall) => {
4157
- const toolName = toolCall?.function?.name || toolCall?.name;
4158
- return toolName === "summarize_context";
4159
- });
4160
- }
4161
4100
  function validateMessageSequence(messages) {
4162
4101
  const validated = [];
4163
4102
  const pendingToolCallIds = /* @__PURE__ */ new Set();
@@ -4382,7 +4321,7 @@ function createContextSummarizeNode(opts) {
4382
4321
  (m) => {
4383
4322
  if (m.role !== "tool") return false;
4384
4323
  if (isSummarizedToolPlaceholder(m.content)) return false;
4385
- if (isSyntheticSummaryToolMessage(m)) return false;
4324
+ if (isSyntheticSummaryMessage(m)) return false;
4386
4325
  const histEntry = findToolHistoryEntry(state, m.tool_call_id, m.name);
4387
4326
  if (histEntry?.retentionPolicy === "keep_full") return false;
4388
4327
  if (!histEntry?.retentionPolicy) {
@@ -4395,15 +4334,14 @@ function createContextSummarizeNode(opts) {
4395
4334
  if (compressableMessages.length === 0) {
4396
4335
  return {};
4397
4336
  }
4398
- const allTextBefore = messages.map((m) => typeof m.content === "string" ? m.content : Array.isArray(m.content) ? m.content.map((c) => typeof c === "string" ? c : c?.text ?? c?.content ?? "").join("") : "").join("\n");
4399
- const tokenCountBefore = countApproxTokens(allTextBefore);
4337
+ const tokenCountBefore = countMessagesTokens(messages);
4400
4338
  const summaryPromptMaxTokens = config.summaryPromptMaxTokens;
4401
4339
  const availableTokensForConversation = summaryPromptMaxTokens - 500;
4402
4340
  const messageTexts = [];
4403
4341
  let accumulatedTokens = 0;
4404
4342
  for (let i = messages.length - 1; i >= 0; i--) {
4405
4343
  const m = messages[i];
4406
- if (isSyntheticSummaryToolMessage(m) || isSyntheticSummaryAssistantMessage(m)) {
4344
+ if (isSyntheticSummaryMessage(m) || isSyntheticSummaryMessage(m)) {
4407
4345
  continue;
4408
4346
  }
4409
4347
  let content = "";
@@ -4424,13 +4362,13 @@ function createContextSummarizeNode(opts) {
4424
4362
  }
4425
4363
  let prefix = `${m.role.toUpperCase()}`;
4426
4364
  if (m.name) prefix += ` (${m.name})`;
4427
- const messageText2 = `${prefix}: ${content}`;
4428
- const messageTokens = countApproxTokens(messageText2);
4365
+ const messageText = `${prefix}: ${content}`;
4366
+ const messageTokens = countApproxTokens(messageText);
4429
4367
  if (accumulatedTokens + messageTokens > availableTokensForConversation) {
4430
4368
  messageTexts.unshift("[Earlier conversation history omitted for brevity]");
4431
4369
  break;
4432
4370
  }
4433
- messageTexts.unshift(messageText2);
4371
+ messageTexts.unshift(messageText);
4434
4372
  accumulatedTokens += messageTokens;
4435
4373
  }
4436
4374
  const conversationText = messageTexts.join("\n\n");
@@ -4572,7 +4510,7 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
4572
4510
  const toolResponsesConfig = resolved.toolResponses;
4573
4511
  const newMessages = messages.map((m) => {
4574
4512
  if (m.role === "tool") {
4575
- if (isSyntheticSummaryToolMessage(m)) {
4513
+ if (isSyntheticSummaryMessage(m)) {
4576
4514
  return m;
4577
4515
  }
4578
4516
  const toolCallId = m.tool_call_id;
@@ -4630,8 +4568,7 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
4630
4568
  const summaries = Array.isArray(state.summaries) ? [...state.summaries, summaryText] : [summaryText];
4631
4569
  const summaryRecords = Array.isArray(state.summaryRecords) ? [...state.summaryRecords, { ...structuredSummary || normalizeStructuredSummary(void 0, summaryText), integrity, createdAt: (/* @__PURE__ */ new Date()).toISOString() }] : [{ ...structuredSummary || normalizeStructuredSummary(void 0, summaryText), integrity, createdAt: (/* @__PURE__ */ new Date()).toISOString() }];
4632
4570
  const finalMessages = [...validatedMessages, assistantSummaryCall, toolSummaryResponse];
4633
- const allTextAfter = finalMessages.map((m) => typeof m.content === "string" ? m.content : Array.isArray(m.content) ? m.content.map((c) => typeof c === "string" ? c : c?.text ?? c?.content ?? "").join("") : "").join("\n");
4634
- const tokenCountAfter = countApproxTokens(allTextAfter);
4571
+ const tokenCountAfter = countMessagesTokens(finalMessages);
4635
4572
  const summarizationEvent = {
4636
4573
  type: "summarization",
4637
4574
  summary: summaryText,
@@ -4682,25 +4619,6 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
4682
4619
  };
4683
4620
  };
4684
4621
  }
4685
-
4686
- // src/utils/tokenManager.ts
4687
- async function applyTokenLimits({
4688
- state,
4689
- limits
4690
- }) {
4691
- const messages = state.messages || [];
4692
- const budget = limits.contextTokenLimit;
4693
- let total = messages.reduce((acc, m) => acc + countApproxTokens(String(m.content || "")), 0);
4694
- if (total <= budget) return state;
4695
- const newMessages = [...messages];
4696
- while (total > budget && newMessages.length > 1) {
4697
- const idx = newMessages.findIndex((m) => m.role !== "system");
4698
- if (idx === -1) break;
4699
- const removed = newMessages.splice(idx, 1)[0];
4700
- total -= countApproxTokens(String(removed.content || ""));
4701
- }
4702
- return { ...state, messages: newMessages };
4703
- }
4704
4622
  var todoStatusSchema = z.enum(["not-started", "in-progress", "completed", "blocked"]);
4705
4623
  var todoWriteItemSchema = z.object({
4706
4624
  id: z.number().int().min(1).describe("Sequential id starting from 1"),
@@ -4959,19 +4877,6 @@ function createContextTools(stateRef, opts) {
4959
4877
  }
4960
4878
 
4961
4879
  // src/graph/decisions.ts
4962
- function isSyntheticSummaryMessage2(message) {
4963
- if (!message) return false;
4964
- if (message.role === "tool" && message.name === "summarize_context") {
4965
- return true;
4966
- }
4967
- if (message.role === "assistant" && Array.isArray(message.tool_calls)) {
4968
- return message.tool_calls.some((toolCall) => {
4969
- const toolName = toolCall?.function?.name || toolCall?.name;
4970
- return toolName === "summarize_context";
4971
- });
4972
- }
4973
- return false;
4974
- }
4975
4880
  function needsSummarization(state, opts, summarizationEnabled) {
4976
4881
  if (!summarizationEnabled) {
4977
4882
  return false;
@@ -4985,30 +4890,9 @@ function needsSummarization(state, opts, summarizationEnabled) {
4985
4890
  }
4986
4891
  const maxTok = resolved.summarization.summaryTriggerTokens;
4987
4892
  try {
4988
- const allText = (state.messages || []).filter((message) => !isSyntheticSummaryMessage2(message)).map((m) => {
4989
- if (typeof m.content === "string") return m.content;
4990
- if (Array.isArray(m.content)) {
4991
- return m.content.map((c) => typeof c === "string" ? c : c?.text ?? c?.content ?? JSON.stringify(c)).join("");
4992
- }
4993
- if (m.content && typeof m.content === "object") {
4994
- return JSON.stringify(m.content);
4995
- }
4996
- return "";
4997
- }).join("\n");
4998
- const tokenCount = countApproxTokens(allText);
4999
- const needsSum = tokenCount > maxTok;
5000
- if (process.env.DEBUG_SUMMARIZATION) {
5001
- const msgCount = (state.messages || []).length;
5002
- const toolMsgs = (state.messages || []).filter((m) => m.role === "tool");
5003
- const toolDetails = toolMsgs.map((m, i) => {
5004
- const contentStr = typeof m.content === "string" ? m.content : JSON.stringify(m.content);
5005
- return `[${i}] id:${m.tool_call_id?.slice(-8) || "none"} len:${contentStr.length} preview:"${contentStr.slice(0, 30)}..."`;
5006
- });
5007
- console.log(`[Summarization] Messages: ${msgCount}, Tool messages: ${toolMsgs.length}`);
5008
- toolDetails.forEach((d) => console.log(` ${d}`));
5009
- console.log(`[Summarization] Token count: ${tokenCount}, Max: ${maxTok}, Needs summarization: ${needsSum}`);
5010
- }
5011
- return needsSum;
4893
+ const filtered = (state.messages || []).filter((message) => !isSyntheticSummaryMessage(message));
4894
+ const tokenCount = countMessagesTokens(filtered);
4895
+ return tokenCount > maxTok;
5012
4896
  } catch {
5013
4897
  return false;
5014
4898
  }
@@ -5137,13 +5021,6 @@ async function writeSummaryFactsToMemory(store, config, summary, sourceTurn) {
5137
5021
  }
5138
5022
  return store.get(config.memory.scope, { limit: config.context.lastTurnsToKeep + summary.stable_facts.length });
5139
5023
  }
5140
- function renderMemoryFacts(facts) {
5141
- if (facts.length === 0) return "";
5142
- return [
5143
- "Memory facts:",
5144
- ...facts.map((fact) => `- ${fact.key}: ${fact.value} (confidence ${fact.confidence.toFixed(2)})`)
5145
- ].join("\n");
5146
- }
5147
5024
 
5148
5025
  // src/smart/index.ts
5149
5026
  function createSmartAgent(opts) {
@@ -5183,8 +5060,7 @@ function createSmartAgent(opts) {
5183
5060
  ].join("\n");
5184
5061
  function latestUserPrompt(messages) {
5185
5062
  const latest = [...messages].reverse().find((message) => message.role === "user");
5186
- if (!latest) return "";
5187
- return typeof latest.content === "string" ? latest.content : Array.isArray(latest.content) ? latest.content.map((part) => typeof part === "string" ? part : part?.text ?? part?.content ?? "").join(" ") : "";
5063
+ return latest ? extractMessageText2(latest) : "";
5188
5064
  }
5189
5065
  async function syncMemory(state) {
5190
5066
  const query = latestUserPrompt(state.messages || []);
@@ -5224,6 +5100,18 @@ function createSmartAgent(opts) {
5224
5100
  );
5225
5101
  return { role: "system", content: sys };
5226
5102
  }
5103
+ async function trySummarize(currentState, currentRawMessages) {
5104
+ if (!summarizer) return { state: currentState, rawMessages: currentRawMessages, compressed: false };
5105
+ const delta = await summarizer(currentState);
5106
+ if (!delta || Object.keys(delta).length === 0) {
5107
+ const ctx2 = { ...currentState.ctx || {}, __summarizationExhausted: true };
5108
+ return { state: { ...currentState, ctx: ctx2 }, rawMessages: currentRawMessages, compressed: false };
5109
+ }
5110
+ const ctx = { ...currentState.ctx || {} };
5111
+ delete ctx.__summarizationExhausted;
5112
+ const updated = await persistLatestSummary(syncPlanState({ ...currentState, ...delta, ctx }));
5113
+ return { state: updated, rawMessages: [...updated.messages || currentRawMessages], compressed: true };
5114
+ }
5227
5115
  const instance = {
5228
5116
  invoke: async (input, config) => {
5229
5117
  stateRef.toolHistory = input.toolHistory;
@@ -5242,17 +5130,10 @@ function createSmartAgent(opts) {
5242
5130
  state = { ...state, messages: rawMessages };
5243
5131
  const next = summarizationEnabled ? decideBefore(state) : "agent";
5244
5132
  if (next === "contextSummarize" && summarizer) {
5245
- const delta = await summarizer(state);
5246
- if (!delta || Object.keys(delta).length === 0) {
5247
- const ctx = { ...state.ctx || {}, __summarizationExhausted: true };
5248
- state = { ...state, ctx };
5249
- } else {
5250
- const ctx = { ...state.ctx || {} };
5251
- delete ctx.__summarizationExhausted;
5252
- state = await persistLatestSummary(syncPlanState({ ...state, ...delta, ctx }));
5253
- rawMessages = [...state.messages || rawMessages];
5254
- continue;
5255
- }
5133
+ const result = await trySummarize(state, rawMessages);
5134
+ state = result.state;
5135
+ rawMessages = result.rawMessages;
5136
+ if (result.compressed) continue;
5256
5137
  }
5257
5138
  const modelMessages = buildModelMessages(state, resolved);
5258
5139
  const res = await base.invoke({ ...state, messages: modelMessages }, config);
@@ -5280,35 +5161,20 @@ function createSmartAgent(opts) {
5280
5161
  const ctx = { ...state.ctx || {} };
5281
5162
  delete ctx.__needsSummarization;
5282
5163
  state = { ...state, ctx };
5283
- const delta = await summarizer(state);
5284
- if (delta && Object.keys(delta).length > 0) {
5285
- const successCtx = { ...state.ctx || {} };
5286
- delete successCtx.__summarizationExhausted;
5287
- state = await persistLatestSummary(syncPlanState({ ...state, ...delta, ctx: successCtx }));
5288
- rawMessages = [...state.messages || rawMessages];
5289
- continue;
5290
- } else {
5291
- const exhaustedCtx = { ...state.ctx || {}, __summarizationExhausted: true };
5292
- state = { ...state, ctx: exhaustedCtx };
5293
- continue;
5294
- }
5164
+ const result = await trySummarize(state, rawMessages);
5165
+ state = result.state;
5166
+ rawMessages = result.rawMessages;
5167
+ continue;
5295
5168
  }
5296
5169
  if (state.ctx?.__finalizedDueToStructuredOutput) break;
5297
5170
  if (opts.outputSchema && lastResult?.output != null) break;
5298
5171
  if (summarizationEnabled) {
5299
5172
  const after = decideAfter(state);
5300
5173
  if (after === "contextSummarize" && summarizer) {
5301
- const delta = await summarizer(state);
5302
- if (delta && Object.keys(delta).length > 0) {
5303
- const successCtx = { ...state.ctx || {} };
5304
- delete successCtx.__summarizationExhausted;
5305
- state = await persistLatestSummary(syncPlanState({ ...state, ...delta, ctx: successCtx }));
5306
- rawMessages = [...state.messages || rawMessages];
5307
- continue;
5308
- } else {
5309
- const exhaustedCtx = { ...state.ctx || {}, __summarizationExhausted: true };
5310
- state = { ...state, ctx: exhaustedCtx };
5311
- }
5174
+ const result = await trySummarize(state, rawMessages);
5175
+ state = result.state;
5176
+ rawMessages = result.rawMessages;
5177
+ if (result.compressed) continue;
5312
5178
  }
5313
5179
  }
5314
5180
  break;
@@ -5472,35 +5338,6 @@ async function runSmartAgentEvalHarness(params) {
5472
5338
  }
5473
5339
  return results;
5474
5340
  }
5475
-
5476
- // src/utils/content.ts
5477
- function contentToString(content) {
5478
- try {
5479
- if (content == null) return "";
5480
- if (typeof content === "string") return content;
5481
- if (Array.isArray(content)) {
5482
- return content.map((p) => {
5483
- if (!p || typeof p !== "object") return String(p);
5484
- if (p.type === "text") return String(p.text ?? "");
5485
- if (p.type === "image_url") {
5486
- const img = p.image_url;
5487
- const url = typeof img === "string" ? img : img?.url;
5488
- const detail = typeof img === "string" ? void 0 : img?.detail;
5489
- return `[image:${url || "unknown"}${detail ? ` detail=${detail}` : ""}]`;
5490
- }
5491
- return JSON.stringify(p);
5492
- }).join("\n");
5493
- }
5494
- return JSON.stringify(content);
5495
- } catch {
5496
- return String(content);
5497
- }
5498
- }
5499
- function mergeContentsToString(contents) {
5500
- return contents.map((c) => contentToString(c)).join("\n");
5501
- }
5502
-
5503
- // src/guardrails/checks.ts
5504
5341
  var Ajv = AjvModule?.default ?? AjvModule;
5505
5342
  var defaultAjv = new Ajv({ allErrors: true });
5506
5343
  defaultAjv.opts.strict = false;
@@ -7298,6 +7135,9 @@ function convertToJsonSchema(schema, strict = false) {
7298
7135
  function normalizeStrictSchema(schema) {
7299
7136
  if (!schema || typeof schema !== "object") return schema;
7300
7137
  const clone2 = { ...schema };
7138
+ if (typeof clone2.format === "string") {
7139
+ delete clone2.format;
7140
+ }
7301
7141
  if (clone2.type === "object" || clone2.properties) {
7302
7142
  if (!clone2.type) clone2.type = "object";
7303
7143
  if (clone2.properties && typeof clone2.properties === "object") {
@@ -7484,6 +7324,6 @@ function createProvider(config) {
7484
7324
  }
7485
7325
  }
7486
7326
 
7487
- export { AnthropicProvider, AzureProvider, BaseProvider, BedrockProvider, DEFAULT_PROFILE_CONFIGS, GuardrailPhase, InMemoryMemoryStore, NativeJsonSchemaStrategy, OpenAICompatibleProvider, OpenAIProvider, ProviderError, StructuredOutputManager, ToolBasedStrategy, VertexProvider, agentVerdictRule, applyTokenLimits, 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, renderMemoryFacts, resolveMemoryStore, resolveStrategy, resolveToolApprovalState, restoreSnapshot, runSmartAgentEvalHarness, startStreamingSession, traceSessionToOtlp, withTools, writeSummaryFactsToMemory };
7327
+ 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 };
7488
7328
  //# sourceMappingURL=index.mjs.map
7489
7329
  //# sourceMappingURL=index.mjs.map