@cognipeer/agent-sdk 0.2.6 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -75,15 +75,16 @@ interface ToolInterface<TInput = any, TOutput = any, TCallOptions = any> {
75
75
  approvalDefaults?: any;
76
76
  [key: string]: any;
77
77
  }
78
- type RunnableConfig = Record<string, unknown>;
78
+ type RunnableConfig = {
79
+ [key: string]: any;
80
+ };
79
81
  type BaseMessage = {
80
82
  role: string;
81
83
  name?: string;
82
84
  content: string | ContentPart[];
83
85
  tool_calls?: any;
84
86
  tool_call_id?: string;
85
- metadata?: Record<string, any>;
86
- additional_kwargs?: Record<string, any>;
87
+ [key: string]: any;
87
88
  };
88
89
  type AIMessage = BaseMessage & {
89
90
  role: 'assistant';
@@ -143,7 +144,6 @@ type AgentLimits = {
143
144
  maxToolCalls?: number;
144
145
  maxParallelTools?: number;
145
146
  };
146
- /** @deprecated Use AgentLimits instead */
147
147
  type SmartAgentLimits = AgentLimits;
148
148
  type TraceSinkFileConfig = {
149
149
  type: "file";
@@ -168,20 +168,15 @@ type TraceSinkConfig = TraceSinkFileConfig | TraceSinkCustomConfig | TraceSinkCo
168
168
  type TracingMode = "batched" | "streaming";
169
169
  type TracingConfig = {
170
170
  enabled: boolean;
171
- logData?: boolean;
172
- /** Tracing mode:
173
- * - "batched" (default): Events are collected and sent together when session ends
174
- * - "streaming": Session starts immediately, events are sent in real-time as they occur
175
- */
176
171
  mode?: TracingMode;
172
+ logData?: boolean;
177
173
  sink?: TraceSinkConfig;
178
174
  };
179
- /** @deprecated Use TracingConfig instead */
180
175
  type SmartAgentTracingConfig = TracingConfig;
181
176
  type AgentOptions = {
182
177
  name?: string;
183
178
  version?: string;
184
- model: BaseChatModel;
179
+ model: any;
185
180
  tools?: Array<ToolInterface<any, any, any>>;
186
181
  guardrails?: ConversationGuardrail[];
187
182
  handoffs?: HandoffDescriptor[];
@@ -193,7 +188,7 @@ type AgentOptions = {
193
188
  type SmartAgentOptions = {
194
189
  name?: string;
195
190
  version?: string;
196
- model: BaseChatModel;
191
+ model: any;
197
192
  tools?: Array<ToolInterface<any, any, any>>;
198
193
  guardrails?: ConversationGuardrail[];
199
194
  handoffs?: HandoffDescriptor[];
@@ -215,7 +210,7 @@ type SmartAgentOptions = {
215
210
  type AgentRuntimeConfig = {
216
211
  name?: string;
217
212
  version?: string;
218
- model: BaseChatModel;
213
+ model: any;
219
214
  tools: Array<ToolInterface<any, any, any>>;
220
215
  guardrails?: ConversationGuardrail[];
221
216
  systemPrompt?: string;
@@ -393,9 +388,7 @@ type TraceSessionRuntime = {
393
388
  errors: TraceErrorRecord[];
394
389
  fileBaseDir?: string;
395
390
  fileSessionDir?: string;
396
- /** For streaming mode: whether session start has been sent to sink */
397
391
  sessionStarted?: boolean;
398
- /** Agent info for streaming mode session start */
399
392
  agentInfo?: {
400
393
  name?: string;
401
394
  version?: string;
@@ -758,6 +751,17 @@ declare function applyTokenLimits({ state, limits, }: {
758
751
  * For production accuracy, consider using a proper tokenizer like tiktoken.
759
752
  */
760
753
  declare function countApproxTokens(text: string): number;
754
+ /**
755
+ * Estimates the total token count for an array of messages.
756
+ *
757
+ * Unlike counting only `.content`, this includes:
758
+ * - `tool_calls[].function.arguments` (can be massive JSON)
759
+ * - `tool_calls[].function.name`
760
+ * - `additional_kwargs.tool_calls` (LangChain/Bedrock)
761
+ * - Per-message overhead (role, name, formatting)
762
+ * - Anthropic tool_use content blocks
763
+ */
764
+ declare function countMessagesTokens(messages: any[]): number;
761
765
 
762
766
  declare function createContextTools(stateRef: {
763
767
  toolHistory?: any[];
@@ -914,4 +918,4 @@ declare function httpSink(url: string, headers?: Record<string, string>): TraceS
914
918
  */
915
919
  declare function startStreamingSession(session: TraceSessionRuntime | undefined, agentRuntime?: AgentRuntimeConfig): Promise<void>;
916
920
 
917
- export { type AIMessage, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type ConversationGuardrail, type CustomRuleCallback, type CustomRuleOptions, type GuardrailContext, type GuardrailDisposition, type GuardrailEvent, type GuardrailIncident, type GuardrailOutcome, GuardrailPhase, type GuardrailRule, type HandoffDescriptor, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, type Message, type PendingToolApproval, type RegexGuardrailOptions, type RegexRuleOptions, type ResolvedTraceConfig, type ResolvedTraceSink, type RestoreSnapshotOptions, type SerializableSmartState, type SmartAgentEvent, type SmartAgentInstance, type SmartAgentLimits, type SmartAgentOptions, type SmartAgentTracingConfig, type SmartModel, type SmartState, type SmartToolFn, type SnapshotOptions, type SnapshotRuntimeHint, type TokenLimits, type ToolApprovalEvent, type ToolApprovalResolution, type ToolInterface, type TraceDataSection, type TraceErrorRecord, type TraceEventRecord, type TraceMessageSection, type TraceMetadataSection, type TraceSessionConfigSnapshot, type TraceSessionFile, type TraceSessionStatus, type TraceSessionSummary, type TraceSinkCognipeerConfig, type TraceSinkConfig, type TraceSinkCustomConfig, type TraceSinkFileConfig, type TraceSinkHttpConfig, type TraceSinkSnapshot, type TraceSummarySection, type TraceToolCallSection, type TraceToolResultSection, type TracingConfig, type TracingMode, agentVerdictRule, applyTokenLimits, buildSystemPrompt, captureSnapshot, codePresenceRule, cognipeerSink, countApproxTokens, createAgent, createAgentNode, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGuardrail, createJsonGuardrail, createRegexGuardrail, createResolverNode, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, evaluateGuardrails, fileSink, fromLangchainModel, fromLangchainTools, httpSink, isSmartModel, jsonSchemaRule, regexRule, resolveToolApprovalState, restoreSnapshot, startStreamingSession, withTools };
921
+ export { type AIMessage, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type ConversationGuardrail, type CustomRuleCallback, type CustomRuleOptions, type GuardrailContext, type GuardrailDisposition, type GuardrailEvent, type GuardrailIncident, type GuardrailOutcome, GuardrailPhase, type GuardrailRule, type HandoffDescriptor, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, type Message, type PendingToolApproval, type RegexGuardrailOptions, type RegexRuleOptions, type ResolvedTraceConfig, type ResolvedTraceSink, type RestoreSnapshotOptions, type SerializableSmartState, type SmartAgentEvent, type SmartAgentInstance, type SmartAgentLimits, type SmartAgentOptions, type SmartAgentTracingConfig, type SmartModel, type SmartState, type SmartToolFn, type SnapshotOptions, type SnapshotRuntimeHint, type TokenLimits, type ToolApprovalEvent, type ToolApprovalResolution, type ToolInterface, type TraceDataSection, type TraceErrorRecord, type TraceEventRecord, type TraceMessageSection, type TraceMetadataSection, type TraceSessionConfigSnapshot, type TraceSessionFile, type TraceSessionStatus, type TraceSessionSummary, type TraceSinkCognipeerConfig, type TraceSinkConfig, type TraceSinkCustomConfig, type TraceSinkFileConfig, type TraceSinkHttpConfig, type TraceSinkSnapshot, type TraceSummarySection, type TraceToolCallSection, type TraceToolResultSection, type TracingConfig, type TracingMode, agentVerdictRule, applyTokenLimits, buildSystemPrompt, captureSnapshot, codePresenceRule, cognipeerSink, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGuardrail, createJsonGuardrail, createRegexGuardrail, createResolverNode, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, evaluateGuardrails, fileSink, fromLangchainModel, fromLangchainTools, httpSink, isSmartModel, jsonSchemaRule, regexRule, resolveToolApprovalState, restoreSnapshot, startStreamingSession, withTools };
package/dist/index.d.ts CHANGED
@@ -75,15 +75,16 @@ interface ToolInterface<TInput = any, TOutput = any, TCallOptions = any> {
75
75
  approvalDefaults?: any;
76
76
  [key: string]: any;
77
77
  }
78
- type RunnableConfig = Record<string, unknown>;
78
+ type RunnableConfig = {
79
+ [key: string]: any;
80
+ };
79
81
  type BaseMessage = {
80
82
  role: string;
81
83
  name?: string;
82
84
  content: string | ContentPart[];
83
85
  tool_calls?: any;
84
86
  tool_call_id?: string;
85
- metadata?: Record<string, any>;
86
- additional_kwargs?: Record<string, any>;
87
+ [key: string]: any;
87
88
  };
88
89
  type AIMessage = BaseMessage & {
89
90
  role: 'assistant';
@@ -143,7 +144,6 @@ type AgentLimits = {
143
144
  maxToolCalls?: number;
144
145
  maxParallelTools?: number;
145
146
  };
146
- /** @deprecated Use AgentLimits instead */
147
147
  type SmartAgentLimits = AgentLimits;
148
148
  type TraceSinkFileConfig = {
149
149
  type: "file";
@@ -168,20 +168,15 @@ type TraceSinkConfig = TraceSinkFileConfig | TraceSinkCustomConfig | TraceSinkCo
168
168
  type TracingMode = "batched" | "streaming";
169
169
  type TracingConfig = {
170
170
  enabled: boolean;
171
- logData?: boolean;
172
- /** Tracing mode:
173
- * - "batched" (default): Events are collected and sent together when session ends
174
- * - "streaming": Session starts immediately, events are sent in real-time as they occur
175
- */
176
171
  mode?: TracingMode;
172
+ logData?: boolean;
177
173
  sink?: TraceSinkConfig;
178
174
  };
179
- /** @deprecated Use TracingConfig instead */
180
175
  type SmartAgentTracingConfig = TracingConfig;
181
176
  type AgentOptions = {
182
177
  name?: string;
183
178
  version?: string;
184
- model: BaseChatModel;
179
+ model: any;
185
180
  tools?: Array<ToolInterface<any, any, any>>;
186
181
  guardrails?: ConversationGuardrail[];
187
182
  handoffs?: HandoffDescriptor[];
@@ -193,7 +188,7 @@ type AgentOptions = {
193
188
  type SmartAgentOptions = {
194
189
  name?: string;
195
190
  version?: string;
196
- model: BaseChatModel;
191
+ model: any;
197
192
  tools?: Array<ToolInterface<any, any, any>>;
198
193
  guardrails?: ConversationGuardrail[];
199
194
  handoffs?: HandoffDescriptor[];
@@ -215,7 +210,7 @@ type SmartAgentOptions = {
215
210
  type AgentRuntimeConfig = {
216
211
  name?: string;
217
212
  version?: string;
218
- model: BaseChatModel;
213
+ model: any;
219
214
  tools: Array<ToolInterface<any, any, any>>;
220
215
  guardrails?: ConversationGuardrail[];
221
216
  systemPrompt?: string;
@@ -393,9 +388,7 @@ type TraceSessionRuntime = {
393
388
  errors: TraceErrorRecord[];
394
389
  fileBaseDir?: string;
395
390
  fileSessionDir?: string;
396
- /** For streaming mode: whether session start has been sent to sink */
397
391
  sessionStarted?: boolean;
398
- /** Agent info for streaming mode session start */
399
392
  agentInfo?: {
400
393
  name?: string;
401
394
  version?: string;
@@ -758,6 +751,17 @@ declare function applyTokenLimits({ state, limits, }: {
758
751
  * For production accuracy, consider using a proper tokenizer like tiktoken.
759
752
  */
760
753
  declare function countApproxTokens(text: string): number;
754
+ /**
755
+ * Estimates the total token count for an array of messages.
756
+ *
757
+ * Unlike counting only `.content`, this includes:
758
+ * - `tool_calls[].function.arguments` (can be massive JSON)
759
+ * - `tool_calls[].function.name`
760
+ * - `additional_kwargs.tool_calls` (LangChain/Bedrock)
761
+ * - Per-message overhead (role, name, formatting)
762
+ * - Anthropic tool_use content blocks
763
+ */
764
+ declare function countMessagesTokens(messages: any[]): number;
761
765
 
762
766
  declare function createContextTools(stateRef: {
763
767
  toolHistory?: any[];
@@ -914,4 +918,4 @@ declare function httpSink(url: string, headers?: Record<string, string>): TraceS
914
918
  */
915
919
  declare function startStreamingSession(session: TraceSessionRuntime | undefined, agentRuntime?: AgentRuntimeConfig): Promise<void>;
916
920
 
917
- export { type AIMessage, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type ConversationGuardrail, type CustomRuleCallback, type CustomRuleOptions, type GuardrailContext, type GuardrailDisposition, type GuardrailEvent, type GuardrailIncident, type GuardrailOutcome, GuardrailPhase, type GuardrailRule, type HandoffDescriptor, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, type Message, type PendingToolApproval, type RegexGuardrailOptions, type RegexRuleOptions, type ResolvedTraceConfig, type ResolvedTraceSink, type RestoreSnapshotOptions, type SerializableSmartState, type SmartAgentEvent, type SmartAgentInstance, type SmartAgentLimits, type SmartAgentOptions, type SmartAgentTracingConfig, type SmartModel, type SmartState, type SmartToolFn, type SnapshotOptions, type SnapshotRuntimeHint, type TokenLimits, type ToolApprovalEvent, type ToolApprovalResolution, type ToolInterface, type TraceDataSection, type TraceErrorRecord, type TraceEventRecord, type TraceMessageSection, type TraceMetadataSection, type TraceSessionConfigSnapshot, type TraceSessionFile, type TraceSessionStatus, type TraceSessionSummary, type TraceSinkCognipeerConfig, type TraceSinkConfig, type TraceSinkCustomConfig, type TraceSinkFileConfig, type TraceSinkHttpConfig, type TraceSinkSnapshot, type TraceSummarySection, type TraceToolCallSection, type TraceToolResultSection, type TracingConfig, type TracingMode, agentVerdictRule, applyTokenLimits, buildSystemPrompt, captureSnapshot, codePresenceRule, cognipeerSink, countApproxTokens, createAgent, createAgentNode, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGuardrail, createJsonGuardrail, createRegexGuardrail, createResolverNode, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, evaluateGuardrails, fileSink, fromLangchainModel, fromLangchainTools, httpSink, isSmartModel, jsonSchemaRule, regexRule, resolveToolApprovalState, restoreSnapshot, startStreamingSession, withTools };
921
+ export { type AIMessage, type AgentInstance, type AgentInvokeResult, type AgentLimits, type AgentOptions, type AgentRuleOptions, type AgentRuntimeConfig, type AgentSnapshot, type AgentSnapshotMetadata, type AgentState, type BaseChatMessage, type BaseChatMessagePart, type BaseChatModel, type BaseMessage, type CodeDetectionRuleOptions, type CodeGuardrailOptions, type ConversationGuardrail, type CustomRuleCallback, type CustomRuleOptions, type GuardrailContext, type GuardrailDisposition, type GuardrailEvent, type GuardrailIncident, type GuardrailOutcome, GuardrailPhase, type GuardrailRule, type HandoffDescriptor, type InvokeConfig, type JsonGuardrailOptions, type JsonSchemaRuleOptions, type Message, type PendingToolApproval, type RegexGuardrailOptions, type RegexRuleOptions, type ResolvedTraceConfig, type ResolvedTraceSink, type RestoreSnapshotOptions, type SerializableSmartState, type SmartAgentEvent, type SmartAgentInstance, type SmartAgentLimits, type SmartAgentOptions, type SmartAgentTracingConfig, type SmartModel, type SmartState, type SmartToolFn, type SnapshotOptions, type SnapshotRuntimeHint, type TokenLimits, type ToolApprovalEvent, type ToolApprovalResolution, type ToolInterface, type TraceDataSection, type TraceErrorRecord, type TraceEventRecord, type TraceMessageSection, type TraceMetadataSection, type TraceSessionConfigSnapshot, type TraceSessionFile, type TraceSessionStatus, type TraceSessionSummary, type TraceSinkCognipeerConfig, type TraceSinkConfig, type TraceSinkCustomConfig, type TraceSinkFileConfig, type TraceSinkHttpConfig, type TraceSinkSnapshot, type TraceSummarySection, type TraceToolCallSection, type TraceToolResultSection, type TracingConfig, type TracingMode, agentVerdictRule, applyTokenLimits, buildSystemPrompt, captureSnapshot, codePresenceRule, cognipeerSink, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGuardrail, createJsonGuardrail, createRegexGuardrail, createResolverNode, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, evaluateGuardrails, fileSink, fromLangchainModel, fromLangchainTools, httpSink, isSmartModel, jsonSchemaRule, regexRule, resolveToolApprovalState, restoreSnapshot, startStreamingSession, withTools };
package/dist/index.mjs CHANGED
@@ -183,7 +183,9 @@ function fromLangchainModel(lcModel) {
183
183
  stream: async function* (messages, options) {
184
184
  if (typeof lcModel.stream !== "function") return;
185
185
  const lcMessages = messages.map(toLC);
186
- for await (const chunk of lcModel.stream(lcMessages, options)) {
186
+ const streamResult = lcModel.stream(lcMessages, options);
187
+ const stream = typeof streamResult?.then === "function" ? await streamResult : streamResult;
188
+ for await (const chunk of stream) {
187
189
  yield chunk;
188
190
  }
189
191
  },
@@ -305,17 +307,17 @@ function normalizeUsage(raw) {
305
307
  raw.totalTokens,
306
308
  (typeof prompt === "number" ? prompt : 0) + (typeof completion === "number" ? completion : 0)
307
309
  );
308
- const promptDetailsSrc = raw.prompt_tokens_details || raw.promptTokensDetails || {};
309
- const completionDetailsSrc = raw.completion_tokens_details || raw.completionTokensDetails || {};
310
+ const promptDetailsSrc = raw.prompt_tokens_details || raw.promptTokensDetails || raw.input_token_details || raw.inputTokenDetails || {};
311
+ const completionDetailsSrc = raw.completion_tokens_details || raw.completionTokensDetails || raw.output_token_details || raw.outputTokenDetails || {};
310
312
  const normalized = {
311
313
  prompt_tokens: safe(prompt),
312
314
  completion_tokens: safe(completion),
313
315
  total_tokens: safe(total || (prompt || 0) + (completion || 0)),
314
316
  prompt_tokens_details: {
315
317
  cached_tokens: safe(
316
- promptDetailsSrc.cached_tokens || promptDetailsSrc.cached || raw.cached_input_tokens || raw.cached_prompt_tokens
318
+ promptDetailsSrc.cached_tokens || promptDetailsSrc.cached || promptDetailsSrc.cache_read || raw.cached_input_tokens || raw.cached_prompt_tokens || raw.cache_read_input_tokens
317
319
  ),
318
- audio_tokens: safe(promptDetailsSrc.audio_tokens)
320
+ audio_tokens: safe(promptDetailsSrc.audio_tokens || promptDetailsSrc.audio)
319
321
  },
320
322
  completion_tokens_details: {
321
323
  reasoning_tokens: safe(completionDetailsSrc.reasoning_tokens),
@@ -636,7 +638,7 @@ async function postStreamingSessionStart(baseUrl, headers, payload) {
636
638
  if (!fetchFn) {
637
639
  throw new Error("HTTP sink requires fetch to be available in this runtime.");
638
640
  }
639
- const url = `${baseUrl.replace(/\/$/, "")}/${payload.sessionId}/start`;
641
+ const url = `${baseUrl.replace(/\/$/, "")}/stream/${payload.sessionId}/start`;
640
642
  const finalHeaders = { ...headers || {} };
641
643
  if (!Object.keys(finalHeaders).some((key) => key.toLowerCase() === "content-type")) {
642
644
  finalHeaders["content-type"] = "application/json";
@@ -670,7 +672,7 @@ async function postStreamingEvent(baseUrl, headers, sessionId, event) {
670
672
  if (!fetchFn) {
671
673
  throw new Error("HTTP sink requires fetch to be available in this runtime.");
672
674
  }
673
- const url = `${baseUrl.replace(/\/$/, "")}/${sessionId}/events`;
675
+ const url = `${baseUrl.replace(/\/$/, "")}/stream/${sessionId}/events`;
674
676
  const finalHeaders = { ...headers || {} };
675
677
  if (!Object.keys(finalHeaders).some((key) => key.toLowerCase() === "content-type")) {
676
678
  finalHeaders["content-type"] = "application/json";
@@ -704,7 +706,7 @@ async function postStreamingSessionEnd(baseUrl, headers, payload) {
704
706
  if (!fetchFn) {
705
707
  throw new Error("HTTP sink requires fetch to be available in this runtime.");
706
708
  }
707
- const url = `${baseUrl.replace(/\/$/, "")}/${payload.sessionId}/end`;
709
+ const url = `${baseUrl.replace(/\/$/, "")}/stream/${payload.sessionId}/end`;
708
710
  const finalHeaders = { ...headers || {} };
709
711
  if (!Object.keys(finalHeaders).some((key) => key.toLowerCase() === "content-type")) {
710
712
  finalHeaders["content-type"] = "application/json";
@@ -1001,8 +1003,12 @@ function recordTraceEvent(session, event) {
1001
1003
  session.summary.eventCounts[event.type] = (session.summary.eventCounts[event.type] || 0) + 1;
1002
1004
  let sections;
1003
1005
  if (session.resolvedConfig.logData) {
1004
- const converted = convertMessageListToSections(event.messageList);
1005
- sections = ensureUniqueSections(id, converted);
1006
+ if (event.sections && event.sections.length > 0) {
1007
+ sections = ensureUniqueSections(id, event.sections);
1008
+ } else {
1009
+ const converted = convertMessageListToSections(event.messageList);
1010
+ sections = ensureUniqueSections(id, converted);
1011
+ }
1006
1012
  }
1007
1013
  const resolvedModel = event.model ?? inferModelFromMessages(event.messageList);
1008
1014
  const resolvedProvider = event.provider ?? inferProviderFromMessages(event.messageList);
@@ -1265,18 +1271,7 @@ function createAgentCoreNode(opts) {
1265
1271
  outputSchema: opts.outputSchema,
1266
1272
  tracing: opts.tracing
1267
1273
  };
1268
- const rawTools = runtime.tools ?? [];
1269
- const seenNames = /* @__PURE__ */ new Map();
1270
- const tools = [];
1271
- for (const t of rawTools) {
1272
- const tName = t.name ?? t.schema?.title;
1273
- if (tName && seenNames.has(tName)) {
1274
- tools[seenNames.get(tName)] = t;
1275
- } else {
1276
- if (tName) seenNames.set(tName, tools.length);
1277
- tools.push(t);
1278
- }
1279
- }
1274
+ const tools = runtime.tools ?? [];
1280
1275
  const modelWithTools = runtime.model?.bindTools ? runtime.model.bindTools(tools) : runtime.model;
1281
1276
  const traceSession = state.ctx?.__traceSession;
1282
1277
  const actorName = runtime.name ?? opts.name ?? "agent";
@@ -1329,6 +1324,26 @@ function createAgentCoreNode(opts) {
1329
1324
  }
1330
1325
  return filteredMsgs;
1331
1326
  };
1327
+ const debugToolPairing = (messagesToSend) => {
1328
+ try {
1329
+ const msgs = Array.isArray(messagesToSend) ? messagesToSend : [];
1330
+ const toolUseIds = [];
1331
+ const missingResults = [];
1332
+ for (let i = 0; i < msgs.length; i++) {
1333
+ const m = msgs[i];
1334
+ if (m?.role === "assistant") {
1335
+ for (const tu of extractToolUses(m)) {
1336
+ toolUseIds.push(tu.id);
1337
+ const next = msgs[i + 1];
1338
+ if (!(next && next.role === "tool" && (next.tool_call_id === tu.id || next.tool_call_id === m?.tool_call_id))) {
1339
+ missingResults.push({ id: tu.id, atIndex: i, tool: tu.name });
1340
+ }
1341
+ }
1342
+ }
1343
+ }
1344
+ } catch (e) {
1345
+ }
1346
+ };
1332
1347
  const onEvent = state.ctx?.__onEvent;
1333
1348
  const onStream = state.ctx?.__onStream;
1334
1349
  const streamingEnabled = Boolean(state.ctx?.__streaming);
@@ -1347,124 +1362,8 @@ function createAgentCoreNode(opts) {
1347
1362
  };
1348
1363
  let response;
1349
1364
  try {
1350
- const ensureUniqueToolCallIds = (input) => {
1351
- const msgs = Array.isArray(input) ? input.map((m) => ({ ...m })) : [];
1352
- const usedIds = /* @__PURE__ */ new Set();
1353
- let counter = 0;
1354
- for (let i = 0; i < msgs.length; i++) {
1355
- const m = msgs[i];
1356
- if (m?.role !== "assistant") continue;
1357
- const hasToolCalls = Array.isArray(m.tool_calls) && m.tool_calls.length > 0;
1358
- const contentArr = Array.isArray(m.content) ? m.content : [];
1359
- const hasContentToolUse = contentArr.some((c) => c?.type === "tool_use" && c?.id);
1360
- const hasAdditionalToolCalls = Array.isArray(m.additional_kwargs?.tool_calls) && m.additional_kwargs.tool_calls.length > 0;
1361
- if (!hasToolCalls && !hasContentToolUse && !hasAdditionalToolCalls) continue;
1362
- if (hasToolCalls && hasContentToolUse) {
1363
- const toolCallIds = new Set(
1364
- m.tool_calls.filter((tc) => tc?.id).map((tc) => tc.id)
1365
- );
1366
- const filtered = contentArr.filter((c) => {
1367
- if (c?.type === "tool_use" && c?.id && toolCallIds.has(c.id)) return false;
1368
- return true;
1369
- });
1370
- if (filtered.length === 0) {
1371
- m.content = "";
1372
- } else if (filtered.length !== contentArr.length) {
1373
- m.content = filtered.length === 1 && filtered[0]?.type === "text" ? filtered[0].text ?? "" : filtered;
1374
- }
1375
- }
1376
- if (hasAdditionalToolCalls && Array.isArray(m.content)) {
1377
- const akIds = new Set(
1378
- m.additional_kwargs.tool_calls.filter((tc) => tc?.id).map((tc) => tc.id)
1379
- );
1380
- const arr = m.content;
1381
- const filtered = arr.filter((c) => {
1382
- if (c?.type === "tool_use" && c?.id && akIds.has(c.id)) return false;
1383
- return true;
1384
- });
1385
- if (filtered.length !== arr.length) {
1386
- m.content = filtered.length === 0 ? "" : filtered.length === 1 && filtered[0]?.type === "text" ? filtered[0].text ?? "" : filtered;
1387
- }
1388
- }
1389
- if (hasToolCalls) {
1390
- m.tool_calls = m.tool_calls.map((tc) => ({ ...tc }));
1391
- }
1392
- if (hasAdditionalToolCalls) {
1393
- m.additional_kwargs = { ...m.additional_kwargs };
1394
- m.additional_kwargs.tool_calls = m.additional_kwargs.tool_calls.map((tc) => ({ ...tc }));
1395
- }
1396
- const remainingContentArr = Array.isArray(m.content) ? m.content : [];
1397
- const hasRemainingContentToolUse = remainingContentArr.some((c) => c?.type === "tool_use" && c?.id);
1398
- if (hasRemainingContentToolUse) {
1399
- m.content = remainingContentArr.map(
1400
- (c) => c && typeof c === "object" ? { ...c } : c
1401
- );
1402
- }
1403
- const idsInMessage = /* @__PURE__ */ new Set();
1404
- if (hasToolCalls) {
1405
- for (const tc of m.tool_calls) {
1406
- if (tc?.id) idsInMessage.add(tc.id);
1407
- }
1408
- }
1409
- if (hasRemainingContentToolUse) {
1410
- for (const c of m.content) {
1411
- if (c?.type === "tool_use" && c?.id) idsInMessage.add(c.id);
1412
- }
1413
- }
1414
- if (hasAdditionalToolCalls) {
1415
- for (const tc of m.additional_kwargs.tool_calls) {
1416
- if (tc?.id) idsInMessage.add(tc.id);
1417
- }
1418
- }
1419
- for (const id of idsInMessage) {
1420
- if (!usedIds.has(id)) {
1421
- usedIds.add(id);
1422
- continue;
1423
- }
1424
- const newId = `${id}_${Date.now()}_${counter++}`;
1425
- if (hasToolCalls) {
1426
- for (const tc of m.tool_calls) {
1427
- if (tc.id === id) tc.id = newId;
1428
- }
1429
- }
1430
- if (hasRemainingContentToolUse && Array.isArray(m.content)) {
1431
- for (const c of m.content) {
1432
- if (c?.type === "tool_use" && c.id === id) c.id = newId;
1433
- }
1434
- }
1435
- if (hasAdditionalToolCalls) {
1436
- for (const tc of m.additional_kwargs.tool_calls) {
1437
- if (tc.id === id) tc.id = newId;
1438
- }
1439
- }
1440
- for (let j = i + 1; j < msgs.length; j++) {
1441
- const next = msgs[j];
1442
- if (next?.role === "assistant") break;
1443
- if (next?.role === "tool" && next.tool_call_id === id) {
1444
- next.tool_call_id = newId;
1445
- }
1446
- if (Array.isArray(next?.content)) {
1447
- let contentCloned = false;
1448
- for (let k = 0; k < next.content.length; k++) {
1449
- const block = next.content[k];
1450
- if (block?.type === "tool_result" && block.tool_use_id === id) {
1451
- if (!contentCloned) {
1452
- next.content = next.content.map((x) => x && typeof x === "object" ? { ...x } : x);
1453
- contentCloned = true;
1454
- }
1455
- next.content[k].tool_use_id = newId;
1456
- }
1457
- }
1458
- }
1459
- }
1460
- usedIds.add(newId);
1461
- }
1462
- }
1463
- return msgs;
1464
- };
1465
- const normalizedMessages = ensureUniqueToolCallIds(
1466
- normalizeBedrockToolPairing([...state.messages])
1467
- );
1365
+ const normalizedMessages = normalizeBedrockToolPairing([...state.messages]);
1366
+ debugToolPairing(normalizedMessages);
1468
1367
  if (streamingEnabled && typeof modelWithTools.stream === "function") {
1469
1368
  let streamedText = "";
1470
1369
  let streamedMessage;
@@ -1604,41 +1503,6 @@ function createToolsNode(initialTools, opts) {
1604
1503
  const remaining = Math.max(0, limits.maxToolCalls - toolCount);
1605
1504
  const planned = toolCalls.slice(0, remaining);
1606
1505
  const skipped = toolCalls.slice(remaining);
1607
- for (const tc of skipped) {
1608
- onEvent?.({ type: "tool_call", phase: "skipped", name: tc.name, id: tc.id, args: tc.args });
1609
- const sanitizedArgs = sanitizeTracePayload(tc.args);
1610
- const messageList = [
1611
- {
1612
- role: "assistant",
1613
- name: tc.name,
1614
- content: `Skipped tool due to tool-call limit: ${tc.name}`,
1615
- tool_calls: [
1616
- {
1617
- id: tc.id,
1618
- type: "function",
1619
- function: {
1620
- name: tc.name,
1621
- arguments: sanitizedArgs
1622
- }
1623
- }
1624
- ]
1625
- }
1626
- ];
1627
- recordTraceEvent(traceSession, {
1628
- type: "tool_call",
1629
- label: `Tool Skipped - ${tc.name}`,
1630
- actor: { scope: "tool", name: tc.name, role: "tool" },
1631
- status: "skipped",
1632
- toolExecutionId: tc.id,
1633
- messageList
1634
- });
1635
- appended.push({
1636
- role: "tool",
1637
- content: `Skipped tool due to tool-call limit: ${tc.name}`,
1638
- tool_call_id: tc.id || `${tc.name}_${appended.length}`,
1639
- name: tc.name
1640
- });
1641
- }
1642
1506
  const isCancelled = () => {
1643
1507
  if (abortSignal?.aborted) return { cancelled: true, reason: "aborted" };
1644
1508
  if (cancellationToken && cancellationToken.isCancellationRequested) return { cancelled: true, reason: "cancelled" };
@@ -1879,6 +1743,42 @@ function createToolsNode(initialTools, opts) {
1879
1743
  break;
1880
1744
  }
1881
1745
  }
1746
+ for (const tc of skipped) {
1747
+ onEvent?.({ type: "tool_call", phase: "skipped", name: tc.name, id: tc.id, args: tc.args });
1748
+ const sanitizedArgs = sanitizeTracePayload(tc.args);
1749
+ const messageList = [
1750
+ {
1751
+ role: "assistant",
1752
+ name: tc.name,
1753
+ content: `Skipped tool due to tool-call limit: ${tc.name}`,
1754
+ tool_calls: [
1755
+ {
1756
+ id: tc.id,
1757
+ type: "function",
1758
+ function: {
1759
+ name: tc.name,
1760
+ arguments: sanitizedArgs
1761
+ }
1762
+ }
1763
+ ]
1764
+ }
1765
+ ];
1766
+ recordTraceEvent(traceSession, {
1767
+ type: "tool_call",
1768
+ label: `Tool Skipped - ${tc.name}`,
1769
+ actor: { scope: "tool", name: tc.name, role: "tool" },
1770
+ status: "skipped",
1771
+ toolExecutionId: tc.id,
1772
+ messageList
1773
+ });
1774
+ appended.push({
1775
+ role: "tool",
1776
+ content: `Skipped tool due to tool-call limit: ${tc.name}`,
1777
+ tool_call_id: tc.id || `${tc.name}_${appended.length}`,
1778
+ name: tc.name
1779
+ });
1780
+ toolCount += 1;
1781
+ }
1882
1782
  if (!awaitingApproval && state.ctx?.__awaitingApproval) {
1883
1783
  const ctx = { ...state.ctx };
1884
1784
  delete ctx.__awaitingApproval;
@@ -2114,6 +2014,59 @@ function countApproxTokens(text) {
2114
2014
  const asciiCount = text.length - nonAsciiCount;
2115
2015
  return Math.ceil(asciiCount / 4 + nonAsciiCount / 1.5);
2116
2016
  }
2017
+ function extractMessageText(m) {
2018
+ if (!m) return "";
2019
+ const parts = [];
2020
+ parts.push(m.role || "");
2021
+ if (m.name) parts.push(m.name);
2022
+ if (typeof m.content === "string") {
2023
+ parts.push(m.content);
2024
+ } else if (Array.isArray(m.content)) {
2025
+ for (const c of m.content) {
2026
+ if (typeof c === "string") parts.push(c);
2027
+ else if (c?.text) parts.push(c.text);
2028
+ else if (c?.content) parts.push(c.content);
2029
+ else if (c?.type === "tool_use" && c?.input) {
2030
+ parts.push(c.name || "");
2031
+ parts.push(typeof c.input === "string" ? c.input : JSON.stringify(c.input));
2032
+ } else if (c != null && typeof c === "object") {
2033
+ parts.push(JSON.stringify(c));
2034
+ }
2035
+ }
2036
+ } else if (m.content != null && typeof m.content === "object") {
2037
+ parts.push(JSON.stringify(m.content));
2038
+ }
2039
+ if (Array.isArray(m.tool_calls)) {
2040
+ for (const tc of m.tool_calls) {
2041
+ if (tc?.function?.name) parts.push(tc.function.name);
2042
+ if (tc?.function?.arguments) {
2043
+ parts.push(
2044
+ typeof tc.function.arguments === "string" ? tc.function.arguments : JSON.stringify(tc.function.arguments)
2045
+ );
2046
+ }
2047
+ if (tc?.name && !tc?.function?.name) parts.push(tc.name);
2048
+ if (tc?.args && !tc?.function?.arguments) {
2049
+ parts.push(typeof tc.args === "string" ? tc.args : JSON.stringify(tc.args));
2050
+ }
2051
+ }
2052
+ }
2053
+ if (Array.isArray(m.additional_kwargs?.tool_calls)) {
2054
+ for (const tc of m.additional_kwargs.tool_calls) {
2055
+ if (tc?.function?.name) parts.push(tc.function.name);
2056
+ if (tc?.function?.arguments) {
2057
+ parts.push(
2058
+ typeof tc.function.arguments === "string" ? tc.function.arguments : JSON.stringify(tc.function.arguments)
2059
+ );
2060
+ }
2061
+ }
2062
+ }
2063
+ return parts.join("\n");
2064
+ }
2065
+ function countMessagesTokens(messages) {
2066
+ if (!Array.isArray(messages) || messages.length === 0) return 0;
2067
+ const allText = messages.map(extractMessageText).join("\n");
2068
+ return countApproxTokens(allText) + messages.length * 4;
2069
+ }
2117
2070
 
2118
2071
  // src/agent.ts
2119
2072
  function createAgent(opts) {
@@ -2283,8 +2236,7 @@ function createAgent(opts) {
2283
2236
  maxTok = 5e4;
2284
2237
  }
2285
2238
  if (maxTok) {
2286
- const allText = (state.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");
2287
- const tokenCount = countApproxTokens(allText);
2239
+ const tokenCount = countMessagesTokens(state.messages || []);
2288
2240
  if (tokenCount > maxTok) {
2289
2241
  const ctx = { ...state.ctx || {}, __needsSummarization: true };
2290
2242
  state = { ...state, ctx };
@@ -3039,7 +2991,19 @@ function needsSummarization(state, opts, summarizationEnabled) {
3039
2991
  return "";
3040
2992
  }).join("\n");
3041
2993
  const tokenCount = countApproxTokens(allText);
3042
- return tokenCount > maxTok;
2994
+ const needsSum = tokenCount > maxTok;
2995
+ if (process.env.DEBUG_SUMMARIZATION) {
2996
+ const msgCount = (state.messages || []).length;
2997
+ const toolMsgs = (state.messages || []).filter((m) => m.role === "tool");
2998
+ const toolDetails = toolMsgs.map((m, i) => {
2999
+ const contentStr = typeof m.content === "string" ? m.content : JSON.stringify(m.content);
3000
+ return `[${i}] id:${m.tool_call_id?.slice(-8) || "none"} len:${contentStr.length} preview:"${contentStr.slice(0, 30)}..."`;
3001
+ });
3002
+ console.log(`[Summarization] Messages: ${msgCount}, Tool messages: ${toolMsgs.length}`);
3003
+ toolDetails.forEach((d) => console.log(` ${d}`));
3004
+ console.log(`[Summarization] Token count: ${tokenCount}, Max: ${maxTok}, Needs summarization: ${needsSum}`);
3005
+ }
3006
+ return needsSum;
3043
3007
  } catch (e) {
3044
3008
  return false;
3045
3009
  }
@@ -3437,6 +3401,6 @@ function createCodeGuardrail(options) {
3437
3401
  });
3438
3402
  }
3439
3403
 
3440
- export { GuardrailPhase, agentVerdictRule, applyTokenLimits, buildSystemPrompt, captureSnapshot, codePresenceRule, cognipeerSink, countApproxTokens, createAgent, createAgentNode, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGuardrail, createJsonGuardrail, createRegexGuardrail, createResolverNode, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, evaluateGuardrails, fileSink, fromLangchainModel, fromLangchainTools, httpSink, isSmartModel, jsonSchemaRule, regexRule, resolveToolApprovalState, restoreSnapshot, startStreamingSession, withTools };
3404
+ export { GuardrailPhase, agentVerdictRule, applyTokenLimits, buildSystemPrompt, captureSnapshot, codePresenceRule, cognipeerSink, countApproxTokens, countMessagesTokens, createAgent, createAgentNode, createCodeGuardrail, createContextSummarizeNode, createContextTools, createGuardrail, createJsonGuardrail, createRegexGuardrail, createResolverNode, createSmartAgent, createTool, createToolLimitFinalizeNode, createToolsNode, customCallbackRule, customSink, evaluateGuardrails, fileSink, fromLangchainModel, fromLangchainTools, httpSink, isSmartModel, jsonSchemaRule, regexRule, resolveToolApprovalState, restoreSnapshot, startStreamingSession, withTools };
3441
3405
  //# sourceMappingURL=index.mjs.map
3442
3406
  //# sourceMappingURL=index.mjs.map