@cognipeer/agent-sdk 0.6.6 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -52,7 +52,7 @@ function getTokenCounter() {
52
52
  function countApproxTokens(text) {
53
53
  return activeTokenCounter(text || "");
54
54
  }
55
- function extractMessageText(m) {
55
+ function extractMessageText2(m) {
56
56
  if (!m) return "";
57
57
  const parts = [];
58
58
  parts.push(m.role || "");
@@ -102,7 +102,7 @@ function extractMessageText(m) {
102
102
  }
103
103
  function countMessagesTokens(messages) {
104
104
  if (!Array.isArray(messages) || messages.length === 0) return 0;
105
- const allText = messages.map(extractMessageText).join("\n");
105
+ const allText = messages.map(extractMessageText2).join("\n");
106
106
  return countApproxTokens(allText) + messages.length * 4;
107
107
  }
108
108
  var activeTokenCounter;
@@ -1272,6 +1272,7 @@ function eventToOtlpSpan(event) {
1272
1272
  stringAttr("cognipeer.actor.role", event.actor?.role),
1273
1273
  stringAttr("cognipeer.model", event.model),
1274
1274
  stringAttr("cognipeer.provider", event.provider),
1275
+ stringAttr("cognipeer.tool.details", event.toolDetails ? JSON.stringify(event.toolDetails) : void 0),
1275
1276
  intAttr("cognipeer.tokens.input", event.inputTokens),
1276
1277
  intAttr("cognipeer.tokens.output", event.outputTokens),
1277
1278
  intAttr("cognipeer.tokens.total", event.totalTokens),
@@ -1743,6 +1744,7 @@ function recordTraceEvent(session, event) {
1743
1744
  responseBytes,
1744
1745
  model: resolvedModel,
1745
1746
  provider: resolvedProvider,
1747
+ toolDetails: session.resolvedConfig.logData ? sanitizeTracePayload(event.toolDetails) : void 0,
1746
1748
  toolExecutionId: event.toolExecutionId,
1747
1749
  retryOf: event.retryOf,
1748
1750
  error: event.error ?? (status === "error" ? { message: "Unknown error" } : void 0) ?? void 0,
@@ -2193,16 +2195,99 @@ function createAgentCoreNode(opts) {
2193
2195
  };
2194
2196
  }
2195
2197
 
2198
+ // src/utils/content.ts
2199
+ function contentToString(content) {
2200
+ try {
2201
+ if (content == null) return "";
2202
+ if (typeof content === "string") return content;
2203
+ if (Array.isArray(content)) {
2204
+ return content.map((p) => {
2205
+ if (!p || typeof p !== "object") return String(p);
2206
+ if (p.type === "text") return String(p.text ?? "");
2207
+ if (p.type === "image_url") {
2208
+ const img = p.image_url;
2209
+ const url = typeof img === "string" ? img : img?.url;
2210
+ const detail = typeof img === "string" ? void 0 : img?.detail;
2211
+ return `[image:${url || "unknown"}${detail ? ` detail=${detail}` : ""}]`;
2212
+ }
2213
+ return JSON.stringify(p);
2214
+ }).join("\n");
2215
+ }
2216
+ return JSON.stringify(content);
2217
+ } catch {
2218
+ return String(content);
2219
+ }
2220
+ }
2221
+ function mergeContentsToString(contents) {
2222
+ return contents.map((c) => contentToString(c)).join("\n");
2223
+ }
2224
+ function safeStringify(value, pretty = false) {
2225
+ if (value == null) return "";
2226
+ if (typeof value === "string") return value;
2227
+ try {
2228
+ return JSON.stringify(value, null, pretty ? 2 : void 0) ?? String(value);
2229
+ } catch {
2230
+ return String(value);
2231
+ }
2232
+ }
2233
+ function extractMessageText(message) {
2234
+ if (!message) return "";
2235
+ const content = message.content;
2236
+ if (typeof content === "string") return content;
2237
+ if (Array.isArray(content)) {
2238
+ return content.map((part) => typeof part === "string" ? part : part?.text ?? part?.content ?? "").join("");
2239
+ }
2240
+ return "";
2241
+ }
2242
+
2243
+ // src/utils/traceSections.ts
2244
+ function truncate(text, max = 500) {
2245
+ if (!text) return "";
2246
+ return text.length > max ? `${text.slice(0, max)}\u2026` : text;
2247
+ }
2248
+ function summarizeToolOutput(output) {
2249
+ if (output == null) return "";
2250
+ if (typeof output === "string") return truncate(output.trim());
2251
+ if (Array.isArray(output)) {
2252
+ const preview = output.slice(0, 3).map((item, index) => `${index + 1}. ${truncate(safeStringify(item))}`).join("\n");
2253
+ const suffix = output.length > 3 ? `
2254
+ \u2026 (+${output.length - 3} more)` : "";
2255
+ return `${preview}${suffix}`.trim();
2256
+ }
2257
+ if (typeof output === "object") {
2258
+ if (Array.isArray(output.items)) {
2259
+ return summarizeToolOutput(output.items);
2260
+ }
2261
+ return truncate(safeStringify(output));
2262
+ }
2263
+ return truncate(String(output));
2264
+ }
2265
+ function extractToolItems(output) {
2266
+ const source = Array.isArray(output) ? output : Array.isArray(output?.items) ? output.items : void 0;
2267
+ if (!Array.isArray(source) || source.length === 0) return void 0;
2268
+ return source.slice(0, 5).map((item) => {
2269
+ if (item && typeof item === "object") {
2270
+ const snippetSource = item.content ?? item.snippet ?? item.description ?? item.text ?? item.summary ?? item;
2271
+ return {
2272
+ title: typeof item.title === "string" ? item.title : void 0,
2273
+ url: typeof item.url === "string" ? item.url : void 0,
2274
+ snippet: truncate(safeStringify(snippetSource))
2275
+ };
2276
+ }
2277
+ return { snippet: truncate(safeStringify(item)) };
2278
+ });
2279
+ }
2280
+
2196
2281
  // src/smart/runtimeConfig.ts
2197
2282
  var DEFAULT_CRITICAL_TOOLS = ["response", "manage_todo_list", "get_tool_response"];
2198
2283
  var BASE_DEFAULTS = {
2199
- limits: { maxToolCalls: 8, maxParallelTools: 2, maxContextTokens: 24e3, maxTotalOutputTokens: 0, maxCostUsd: 0, maxWallClockMs: 0 },
2284
+ limits: { maxToolCalls: 20, maxParallelTools: 5, maxContextTokens: 96e3, maxTotalOutputTokens: 0, maxCostUsd: 0, maxWallClockMs: 0 },
2200
2285
  summarization: {
2201
2286
  enable: true,
2202
- maxTokens: 24e3,
2203
- summaryTriggerTokens: 17e3,
2204
- summaryPromptMaxTokens: 7e3,
2205
- summaryCompressionRatioTarget: 0.35,
2287
+ maxTokens: 96e3,
2288
+ summaryTriggerTokens: 72e3,
2289
+ summaryPromptMaxTokens: 12e3,
2290
+ summaryCompressionRatioTarget: 0.45,
2206
2291
  summaryMode: "incremental",
2207
2292
  promptTemplate: "",
2208
2293
  toolFreeCall: true,
@@ -2210,13 +2295,13 @@ var BASE_DEFAULTS = {
2210
2295
  },
2211
2296
  context: {
2212
2297
  policy: "hybrid",
2213
- lastTurnsToKeep: 8,
2298
+ lastTurnsToKeep: 16,
2214
2299
  toolResponsePolicy: "summarize_archive",
2215
2300
  budget: {
2216
- systemReserveTokens: 1200,
2217
- goalsReserveTokens: 1200,
2218
- recentTurnsReserveTokens: 5200,
2219
- toolResponseReserveTokens: 2800
2301
+ systemReserveTokens: 2e3,
2302
+ goalsReserveTokens: 2e3,
2303
+ recentTurnsReserveTokens: 18e3,
2304
+ toolResponseReserveTokens: 9e3
2220
2305
  }
2221
2306
  },
2222
2307
  planning: {
@@ -2233,14 +2318,14 @@ var BASE_DEFAULTS = {
2233
2318
  delegation: {
2234
2319
  mode: "role_based",
2235
2320
  maxDelegationDepth: 2,
2236
- maxChildCalls: 4,
2237
- maxParallelChild: 2,
2321
+ maxChildCalls: 6,
2322
+ maxParallelChild: 3,
2238
2323
  childContextPolicy: "scoped",
2239
2324
  requireJsonOutputContract: true
2240
2325
  },
2241
2326
  toolResponses: {
2242
- maxToolResponseChars: 12e3,
2243
- maxToolResponseTokens: 3e3,
2327
+ maxToolResponseChars: 32e3,
2328
+ maxToolResponseTokens: 8e3,
2244
2329
  defaultPolicy: "summarize_archive",
2245
2330
  toolResponseRetentionByTool: {},
2246
2331
  criticalTools: [...DEFAULT_CRITICAL_TOOLS],
@@ -2269,54 +2354,54 @@ function buildProfile(overrides) {
2269
2354
  }
2270
2355
  var DEFAULT_PROFILE_CONFIGS = {
2271
2356
  fast: buildProfile({
2272
- limits: { maxToolCalls: 4, maxParallelTools: 1, maxContextTokens: 12e3 },
2357
+ limits: { maxToolCalls: 8, maxParallelTools: 3, maxContextTokens: 32e3 },
2273
2358
  summarization: {
2274
- maxTokens: 12e3,
2275
- summaryTriggerTokens: 9e3,
2276
- summaryPromptMaxTokens: 5e3,
2277
- summaryCompressionRatioTarget: 0.4
2359
+ maxTokens: 32e3,
2360
+ summaryTriggerTokens: 24e3,
2361
+ summaryPromptMaxTokens: 6e3,
2362
+ summaryCompressionRatioTarget: 0.5
2278
2363
  },
2279
2364
  context: {
2280
- lastTurnsToKeep: 6,
2365
+ lastTurnsToKeep: 8,
2281
2366
  toolResponsePolicy: "keep_structured",
2282
- budget: { systemReserveTokens: 1e3, goalsReserveTokens: 900, recentTurnsReserveTokens: 3200, toolResponseReserveTokens: 1800 }
2367
+ budget: { systemReserveTokens: 1500, goalsReserveTokens: 1200, recentTurnsReserveTokens: 6e3, toolResponseReserveTokens: 3500 }
2283
2368
  },
2284
2369
  memory: { readPolicy: "recent_only" },
2285
2370
  delegation: { mode: "off", maxDelegationDepth: 1, maxChildCalls: 2, maxParallelChild: 1, childContextPolicy: "minimal" },
2286
- toolResponses: { maxToolResponseChars: 8e3, maxToolResponseTokens: 2e3 }
2371
+ toolResponses: { maxToolResponseChars: 16e3, maxToolResponseTokens: 4e3 }
2287
2372
  }),
2288
2373
  balanced: buildProfile({}),
2289
2374
  deep: buildProfile({
2290
- limits: { maxToolCalls: 14, maxParallelTools: 3, maxContextTokens: 42e3 },
2375
+ limits: { maxToolCalls: 40, maxParallelTools: 8, maxContextTokens: 2e5 },
2291
2376
  summarization: {
2292
- maxTokens: 42e3,
2293
- summaryTriggerTokens: 3e4,
2294
- summaryPromptMaxTokens: 9e3,
2295
- summaryCompressionRatioTarget: 0.3
2377
+ maxTokens: 2e5,
2378
+ summaryTriggerTokens: 15e4,
2379
+ summaryPromptMaxTokens: 16e3,
2380
+ summaryCompressionRatioTarget: 0.4
2296
2381
  },
2297
2382
  context: {
2298
- lastTurnsToKeep: 12,
2299
- budget: { systemReserveTokens: 1400, goalsReserveTokens: 1600, recentTurnsReserveTokens: 7e3, toolResponseReserveTokens: 3600 }
2383
+ lastTurnsToKeep: 30,
2384
+ budget: { systemReserveTokens: 2500, goalsReserveTokens: 2500, recentTurnsReserveTokens: 36e3, toolResponseReserveTokens: 18e3 }
2300
2385
  },
2301
2386
  memory: { scope: "workspace" },
2302
- delegation: { maxDelegationDepth: 3, maxChildCalls: 6 },
2303
- toolResponses: { maxToolResponseChars: 16e3, maxToolResponseTokens: 4e3 }
2387
+ delegation: { maxDelegationDepth: 3, maxChildCalls: 10, maxParallelChild: 4 },
2388
+ toolResponses: { maxToolResponseChars: 64e3, maxToolResponseTokens: 16e3 }
2304
2389
  }),
2305
2390
  research: buildProfile({
2306
- limits: { maxToolCalls: 20, maxParallelTools: 4, maxContextTokens: 56e3 },
2391
+ limits: { maxToolCalls: 80, maxParallelTools: 10, maxContextTokens: 4e5 },
2307
2392
  summarization: {
2308
- maxTokens: 56e3,
2309
- summaryTriggerTokens: 42e3,
2310
- summaryPromptMaxTokens: 1e4,
2311
- summaryCompressionRatioTarget: 0.28
2393
+ maxTokens: 4e5,
2394
+ summaryTriggerTokens: 3e5,
2395
+ summaryPromptMaxTokens: 24e3,
2396
+ summaryCompressionRatioTarget: 0.35
2312
2397
  },
2313
2398
  context: {
2314
- lastTurnsToKeep: 20,
2315
- budget: { systemReserveTokens: 1600, goalsReserveTokens: 1800, recentTurnsReserveTokens: 9e3, toolResponseReserveTokens: 4800 }
2399
+ lastTurnsToKeep: 60,
2400
+ budget: { systemReserveTokens: 3e3, goalsReserveTokens: 3e3, recentTurnsReserveTokens: 72e3, toolResponseReserveTokens: 32e3 }
2316
2401
  },
2317
2402
  memory: { scope: "workspace" },
2318
- delegation: { mode: "automatic", maxDelegationDepth: 4, maxChildCalls: 8, maxParallelChild: 3, childContextPolicy: "full" },
2319
- toolResponses: { maxToolResponseChars: 24e3, maxToolResponseTokens: 6e3 }
2403
+ delegation: { mode: "automatic", maxDelegationDepth: 4, maxChildCalls: 16, maxParallelChild: 6, childContextPolicy: "full" },
2404
+ toolResponses: { maxToolResponseChars: 96e3, maxToolResponseTokens: 24e3 }
2320
2405
  })
2321
2406
  };
2322
2407
  function mergeLimits(base, override) {
@@ -2406,53 +2491,6 @@ function getResolvedSmartConfig(opts, runtime) {
2406
2491
 
2407
2492
  // src/smart/toolResponses.ts
2408
2493
  init_utilTokens();
2409
-
2410
- // src/utils/content.ts
2411
- function contentToString(content) {
2412
- try {
2413
- if (content == null) return "";
2414
- if (typeof content === "string") return content;
2415
- if (Array.isArray(content)) {
2416
- return content.map((p) => {
2417
- if (!p || typeof p !== "object") return String(p);
2418
- if (p.type === "text") return String(p.text ?? "");
2419
- if (p.type === "image_url") {
2420
- const img = p.image_url;
2421
- const url = typeof img === "string" ? img : img?.url;
2422
- const detail = typeof img === "string" ? void 0 : img?.detail;
2423
- return `[image:${url || "unknown"}${detail ? ` detail=${detail}` : ""}]`;
2424
- }
2425
- return JSON.stringify(p);
2426
- }).join("\n");
2427
- }
2428
- return JSON.stringify(content);
2429
- } catch {
2430
- return String(content);
2431
- }
2432
- }
2433
- function mergeContentsToString(contents) {
2434
- return contents.map((c) => contentToString(c)).join("\n");
2435
- }
2436
- function safeStringify(value, pretty = false) {
2437
- if (value == null) return "";
2438
- if (typeof value === "string") return value;
2439
- try {
2440
- return JSON.stringify(value, null, pretty ? 2 : void 0) ?? String(value);
2441
- } catch {
2442
- return String(value);
2443
- }
2444
- }
2445
- function extractMessageText2(message) {
2446
- if (!message) return "";
2447
- const content = message.content;
2448
- if (typeof content === "string") return content;
2449
- if (Array.isArray(content)) {
2450
- return content.map((part) => typeof part === "string" ? part : part?.text ?? part?.content ?? "").join("");
2451
- }
2452
- return "";
2453
- }
2454
-
2455
- // src/smart/toolResponses.ts
2456
2494
  function summarizeObject(value) {
2457
2495
  if (value == null) return "null";
2458
2496
  if (typeof value === "string") {
@@ -2567,6 +2605,97 @@ function normalizeToolCall(call) {
2567
2605
  args: call.args ?? call.arguments ?? call.input ?? call.function?.arguments ?? call.function_call?.arguments
2568
2606
  };
2569
2607
  }
2608
+ function normalizeToolSchema(tool, toolName) {
2609
+ const schema = tool.schema;
2610
+ if (!schema) return void 0;
2611
+ if (typeof schema === "object" && schema._def) {
2612
+ try {
2613
+ return sanitizeTracePayload(zodToJsonSchema.zodToJsonSchema(schema, { name: toolName }));
2614
+ } catch {
2615
+ }
2616
+ }
2617
+ if (schema && typeof schema === "object" && typeof schema.toJSON === "function") {
2618
+ try {
2619
+ return sanitizeTracePayload(schema.toJSON());
2620
+ } catch {
2621
+ }
2622
+ }
2623
+ return sanitizeTracePayload(schema);
2624
+ }
2625
+ function buildToolDetails(tool, toolName) {
2626
+ if (!tool) return void 0;
2627
+ const details = { name: toolName };
2628
+ if (typeof tool.description === "string" && tool.description.trim().length > 0) {
2629
+ details.description = tool.description;
2630
+ }
2631
+ const inputSchema = normalizeToolSchema(tool, toolName);
2632
+ if (inputSchema !== void 0) details.inputSchema = inputSchema;
2633
+ const needsApproval = typeof tool.needsApproval === "boolean" ? tool.needsApproval : void 0;
2634
+ if (needsApproval !== void 0 || tool.approvalPrompt !== void 0 || tool.approvalDefaults !== void 0) {
2635
+ details.approval = {
2636
+ required: needsApproval,
2637
+ prompt: typeof tool.approvalPrompt === "string" ? tool.approvalPrompt : void 0,
2638
+ defaults: tool.approvalDefaults !== void 0 ? sanitizeTracePayload(tool.approvalDefaults) : void 0
2639
+ };
2640
+ }
2641
+ const cache = tool.cache;
2642
+ if (cache !== void 0) {
2643
+ details.cache = {
2644
+ enabled: Boolean(cache),
2645
+ scope: cache && typeof cache === "object" && typeof cache.scope === "string" ? cache.scope : void 0,
2646
+ ttlMs: cache && typeof cache === "object" && typeof cache.ttlMs === "number" ? cache.ttlMs : void 0,
2647
+ hasKeyFn: Boolean(cache && typeof cache === "object" && typeof cache.keyFn === "function")
2648
+ };
2649
+ }
2650
+ const retry = tool.retry;
2651
+ if (retry && typeof retry === "object") {
2652
+ details.retry = {
2653
+ maxRetries: typeof retry.maxRetries === "number" ? retry.maxRetries : void 0,
2654
+ backoffMs: typeof retry.backoffMs === "number" ? retry.backoffMs : void 0,
2655
+ circuitBreakerThreshold: typeof retry.circuitBreakerThreshold === "number" ? retry.circuitBreakerThreshold : void 0,
2656
+ hasShouldRetry: typeof retry.shouldRetry === "function"
2657
+ };
2658
+ }
2659
+ if (tool.maxExecutionsPerRun !== void 0) {
2660
+ details.limits = { maxExecutionsPerRun: tool.maxExecutionsPerRun };
2661
+ }
2662
+ if (typeof tool.__source === "string") {
2663
+ details.source = tool.__source;
2664
+ }
2665
+ return details;
2666
+ }
2667
+ function buildToolTraceSections(params) {
2668
+ const sanitizedArgs = sanitizeTracePayload(params.args ?? {});
2669
+ const sanitizedOutput = sanitizeTracePayload(params.output);
2670
+ const summary = params.summary ?? summarizeToolOutput(sanitizedOutput);
2671
+ const items = extractToolItems(sanitizedOutput);
2672
+ return [
2673
+ {
2674
+ kind: "tool_call",
2675
+ label: `Tool Call: ${params.toolName}`,
2676
+ tool: params.toolName,
2677
+ arguments: sanitizedArgs,
2678
+ toolDetails: params.toolDetails
2679
+ },
2680
+ {
2681
+ kind: "tool_result",
2682
+ label: `Tool Result: ${params.toolName}`,
2683
+ tool: params.toolName,
2684
+ summary,
2685
+ items,
2686
+ output: sanitizedOutput,
2687
+ toolDetails: params.toolDetails,
2688
+ execution: {
2689
+ id: params.executionId,
2690
+ status: params.status,
2691
+ durationMs: params.durationMs,
2692
+ fromCache: params.fromCache
2693
+ },
2694
+ classification: params.classification,
2695
+ retentionPolicy: params.retentionPolicy
2696
+ }
2697
+ ];
2698
+ }
2570
2699
  function createToolsNode(initialTools, opts) {
2571
2700
  return async (state) => {
2572
2701
  const runtime = state.agent || {
@@ -2675,6 +2804,7 @@ function createToolsNode(initialTools, opts) {
2675
2804
  args = validatedArgs.value;
2676
2805
  }
2677
2806
  const toolName = tool.name || tc.name;
2807
+ const toolDetails = buildToolDetails(tool, toolName);
2678
2808
  const toolStateRef = tool._stateRef && typeof tool._stateRef === "object" ? tool._stateRef : null;
2679
2809
  if (toolStateRef) {
2680
2810
  toolStateRef.pendingApprovals = pendingApprovals;
@@ -2695,21 +2825,17 @@ function createToolsNode(initialTools, opts) {
2695
2825
  label: `Tool Skipped - ${toolName}`,
2696
2826
  actor: { scope: "tool", name: toolName, role: "tool" },
2697
2827
  status: "skipped",
2828
+ toolDetails,
2698
2829
  toolExecutionId: tc.id,
2699
- messageList: [
2700
- {
2701
- role: "assistant",
2702
- name: toolName,
2703
- content: limitMessage,
2704
- tool_calls: [
2705
- {
2706
- id: tc.id,
2707
- type: "function",
2708
- function: { name: toolName, arguments: sanitizeTracePayload(args) }
2709
- }
2710
- ]
2711
- }
2712
- ]
2830
+ sections: buildToolTraceSections({
2831
+ args,
2832
+ executionId: tc.id,
2833
+ output: limitMessage,
2834
+ status: "skipped",
2835
+ summary: limitMessage,
2836
+ toolDetails,
2837
+ toolName
2838
+ })
2713
2839
  });
2714
2840
  toolCount += 1;
2715
2841
  return { status: "error" };
@@ -2796,6 +2922,25 @@ function createToolsNode(initialTools, opts) {
2796
2922
  push({ role: "tool", content: breakerMsg, tool_call_id: toolCallId, name: tc.name });
2797
2923
  markToolFailure(breakerMsg, toolName, toolCallId);
2798
2924
  onEvent?.({ type: "tool_call", phase: "error", name: toolName, id: tc.id, args, error: { message: breakerMsg } });
2925
+ recordTraceEvent(traceSession, {
2926
+ type: "tool_call",
2927
+ label: `Tool Error - ${toolName}`,
2928
+ actor: { scope: "tool", name: toolName, role: "tool" },
2929
+ status: "error",
2930
+ requestBytes: inputBytes,
2931
+ toolDetails,
2932
+ toolExecutionId: toolCallId,
2933
+ error: { message: breakerMsg },
2934
+ sections: buildToolTraceSections({
2935
+ args,
2936
+ executionId: toolCallId,
2937
+ output: { message: breakerMsg },
2938
+ status: "error",
2939
+ summary: breakerMsg,
2940
+ toolDetails,
2941
+ toolName
2942
+ })
2943
+ });
2799
2944
  toolCount += 1;
2800
2945
  return { status: "error" };
2801
2946
  }
@@ -2820,6 +2965,38 @@ function createToolsNode(initialTools, opts) {
2820
2965
  });
2821
2966
  push({ role: "tool", content: responsePolicy2.content, tool_call_id: tc.id || `${tc.name}_${toolCount}`, name: tc.name });
2822
2967
  onEvent?.({ type: "tool_call", phase: "success", name: toolName, id: tc.id, args, result: cachedHit, durationMs: 0 });
2968
+ const sanitizedCachedHit = sanitizeTracePayload(cachedHit);
2969
+ const outputBytes2 = traceSession?.resolvedConfig.logData ? estimatePayloadBytes(sanitizedCachedHit) : void 0;
2970
+ recordTraceEvent(traceSession, {
2971
+ type: "tool_call",
2972
+ label: `Tool Execution - ${toolName}`,
2973
+ actor: { scope: "tool", name: toolName, role: "tool" },
2974
+ durationMs: 0,
2975
+ requestBytes: inputBytes,
2976
+ responseBytes: outputBytes2,
2977
+ toolDetails,
2978
+ toolExecutionId: executionId2,
2979
+ sections: buildToolTraceSections({
2980
+ args,
2981
+ classification: responsePolicy2.classification,
2982
+ durationMs: 0,
2983
+ executionId: executionId2,
2984
+ fromCache: true,
2985
+ output: sanitizedCachedHit,
2986
+ retentionPolicy: "keep_full",
2987
+ status: "cached",
2988
+ summary: responsePolicy2.content,
2989
+ toolDetails,
2990
+ toolName
2991
+ }),
2992
+ debug: {
2993
+ classification: responsePolicy2.classification,
2994
+ retentionPolicy: "keep_full",
2995
+ originalTokenCount: responsePolicy2.tokenCount,
2996
+ truncated: responsePolicy2.truncated,
2997
+ fromCache: true
2998
+ }
2999
+ });
2823
3000
  toolCount += 1;
2824
3001
  return { status: "success" };
2825
3002
  }
@@ -2940,28 +3117,6 @@ function createToolsNode(initialTools, opts) {
2940
3117
  }
2941
3118
  const sanitizedOutput = sanitizeTracePayload(output);
2942
3119
  const outputBytes = traceSession?.resolvedConfig.logData ? estimatePayloadBytes(sanitizedOutput) : void 0;
2943
- const messageList = [
2944
- {
2945
- role: "assistant",
2946
- name: toolName,
2947
- content: "",
2948
- tool_calls: [
2949
- {
2950
- id: tc.id || executionId,
2951
- type: "function",
2952
- function: {
2953
- name: toolName,
2954
- arguments: sanitizedArgs
2955
- }
2956
- }
2957
- ]
2958
- },
2959
- {
2960
- role: "tool",
2961
- name: toolName,
2962
- content: responsePolicy.content
2963
- }
2964
- ];
2965
3120
  recordTraceEvent(traceSession, {
2966
3121
  type: "tool_call",
2967
3122
  label: `Tool Execution - ${toolName}`,
@@ -2969,8 +3124,20 @@ function createToolsNode(initialTools, opts) {
2969
3124
  durationMs,
2970
3125
  requestBytes: inputBytes,
2971
3126
  responseBytes: outputBytes,
3127
+ toolDetails,
2972
3128
  toolExecutionId: executionId,
2973
- messageList,
3129
+ sections: buildToolTraceSections({
3130
+ args: sanitizedArgs,
3131
+ classification: responsePolicy.classification,
3132
+ durationMs,
3133
+ executionId,
3134
+ output: sanitizedOutput,
3135
+ retentionPolicy: "keep_full",
3136
+ status: "success",
3137
+ summary: responsePolicy.content,
3138
+ toolDetails,
3139
+ toolName
3140
+ }),
2974
3141
  debug: {
2975
3142
  classification: responsePolicy.classification,
2976
3143
  retentionPolicy: "keep_full",
@@ -2989,6 +3156,7 @@ function createToolsNode(initialTools, opts) {
2989
3156
  markToolFailure(message, toolName, toolCallId);
2990
3157
  onEvent?.({ type: "tool_call", phase: "error", name: toolName, id: tc.id, args, error: { message } });
2991
3158
  onProgress?.({ stage: "tools", message: `Tool ${tc.name} failed`, detail: { error: message } });
3159
+ const errorOutput = { message, stack: error?.stack };
2992
3160
  recordTraceEvent(traceSession, {
2993
3161
  type: "tool_call",
2994
3162
  label: `Tool Error - ${toolName}`,
@@ -2996,27 +3164,20 @@ function createToolsNode(initialTools, opts) {
2996
3164
  status: "error",
2997
3165
  durationMs,
2998
3166
  requestBytes: inputBytes,
3167
+ responseBytes: traceSession?.resolvedConfig.logData ? estimatePayloadBytes(errorOutput) : void 0,
3168
+ toolDetails,
2999
3169
  toolExecutionId: executionId,
3000
3170
  error: { message, stack: error?.stack },
3001
- messageList: [
3002
- {
3003
- role: "assistant",
3004
- name: toolName,
3005
- content: "",
3006
- tool_calls: [
3007
- {
3008
- id: tc.id || executionId,
3009
- type: "function",
3010
- function: { name: toolName, arguments: sanitizedArgs }
3011
- }
3012
- ]
3013
- },
3014
- {
3015
- role: "tool",
3016
- name: toolName,
3017
- content: `Error executing tool: ${message}`
3018
- }
3019
- ]
3171
+ sections: buildToolTraceSections({
3172
+ args: sanitizedArgs,
3173
+ durationMs,
3174
+ executionId,
3175
+ output: errorOutput,
3176
+ status: "error",
3177
+ summary: `Error executing tool: ${message}`,
3178
+ toolDetails,
3179
+ toolName
3180
+ })
3020
3181
  });
3021
3182
  toolCount += 1;
3022
3183
  return { status: "error", approval: approvalEntry };
@@ -3093,29 +3254,26 @@ function createToolsNode(initialTools, opts) {
3093
3254
  }
3094
3255
  for (const tc of skipped) {
3095
3256
  onEvent?.({ type: "tool_call", phase: "skipped", name: tc.name, id: tc.id, args: tc.args });
3096
- const sanitizedArgs = sanitizeTracePayload(tc.args);
3257
+ const toolDetails = buildToolDetails(toolByName.get(tc.name), tc.name);
3258
+ const skipMessage = `Skipped tool due to tool-call limit: ${tc.name}`;
3097
3259
  recordTraceEvent(traceSession, {
3098
3260
  type: "tool_call",
3099
3261
  label: `Tool Skipped - ${tc.name}`,
3100
3262
  actor: { scope: "tool", name: tc.name, role: "tool" },
3101
3263
  status: "skipped",
3264
+ toolDetails,
3102
3265
  toolExecutionId: tc.id,
3103
- messageList: [
3104
- {
3105
- role: "assistant",
3106
- name: tc.name,
3107
- content: `Skipped tool due to tool-call limit: ${tc.name}`,
3108
- tool_calls: [
3109
- {
3110
- id: tc.id,
3111
- type: "function",
3112
- function: { name: tc.name, arguments: sanitizedArgs }
3113
- }
3114
- ]
3115
- }
3116
- ]
3266
+ sections: buildToolTraceSections({
3267
+ args: tc.args,
3268
+ executionId: tc.id,
3269
+ output: skipMessage,
3270
+ status: "skipped",
3271
+ summary: skipMessage,
3272
+ toolDetails,
3273
+ toolName: tc.name
3274
+ })
3117
3275
  });
3118
- appended.push({ role: "tool", content: `Skipped tool due to tool-call limit: ${tc.name}`, tool_call_id: tc.id || `${tc.name}_${appended.length}`, name: tc.name });
3276
+ appended.push({ role: "tool", content: skipMessage, tool_call_id: tc.id || `${tc.name}_${appended.length}`, name: tc.name });
3119
3277
  toolCount += 1;
3120
3278
  }
3121
3279
  if (!awaitingApproval && state.ctx?.__awaitingApproval) {
@@ -4366,7 +4524,7 @@ function createAgent(opts) {
4366
4524
  if (toolCalls.length === 0) {
4367
4525
  if (soManager && !state.ctx?.__finalizedDueToStructuredOutput && !state.ctx?.__structuredOutputForceFinalize) {
4368
4526
  if (soManager.strategy.kind === "native") {
4369
- const assistantText = extractMessageText2(lastMsg);
4527
+ const assistantText = extractMessageText(lastMsg);
4370
4528
  if (assistantText) {
4371
4529
  const parsed = soManager.parseFromContent(assistantText);
4372
4530
  if (parsed.success) {
@@ -4417,7 +4575,7 @@ function createAgent(opts) {
4417
4575
  if (soManager && !state.ctx?.__finalizedDueToStructuredOutput) {
4418
4576
  const lastForParse = state.messages[state.messages.length - 1];
4419
4577
  if (lastForParse?.role === "assistant") {
4420
- const assistantText = extractMessageText2(lastForParse);
4578
+ const assistantText = extractMessageText(lastForParse);
4421
4579
  if (assistantText) {
4422
4580
  const parsed = soManager.parseFromContent(assistantText);
4423
4581
  if (parsed.success) {
@@ -4570,7 +4728,7 @@ function createAgent(opts) {
4570
4728
  const isTransientSummarizationExit = !!res.ctx?.__needsSummarization;
4571
4729
  const finalAssistantMsg = isTransientSummarizationExit ? void 0 : getLastAssistantMessage(res.messages);
4572
4730
  const finalIsSyntheticSummary = !isTransientSummarizationExit && finalAssistantMsg && isSyntheticSummaryMessage(finalAssistantMsg);
4573
- const content = isTransientSummarizationExit || finalIsSyntheticSummary ? "" : extractMessageText2(finalAssistantMsg);
4731
+ const content = isTransientSummarizationExit || finalIsSyntheticSummary ? "" : extractMessageText(finalAssistantMsg);
4574
4732
  let parsed = void 0;
4575
4733
  let outputError = void 0;
4576
4734
  if (soManager) {
@@ -4878,7 +5036,7 @@ function renderMemoryBlock(facts) {
4878
5036
  function clampToBudget(messages, maxContextTokens) {
4879
5037
  let working = [...messages];
4880
5038
  while (working.length > 2) {
4881
- const tokenCount = countApproxTokens(working.map(extractMessageText2).join("\n"));
5039
+ const tokenCount = countApproxTokens(working.map(extractMessageText).join("\n"));
4882
5040
  if (tokenCount <= maxContextTokens) return working;
4883
5041
  const firstNonSystem = working.findIndex((message, index) => !(index === 0 && message.role === "system"));
4884
5042
  if (firstNonSystem < 0) break;
@@ -5981,7 +6139,7 @@ function createSmartAgent(opts) {
5981
6139
  ].join("\n");
5982
6140
  function latestUserPrompt(messages) {
5983
6141
  const latest = [...messages].reverse().find((message) => message.role === "user");
5984
- return latest ? extractMessageText2(latest) : "";
6142
+ return latest ? extractMessageText(latest) : "";
5985
6143
  }
5986
6144
  async function syncMemory(state) {
5987
6145
  const query = latestUserPrompt(state.messages || []);