@cognipeer/agent-sdk 0.19.0 → 0.20.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
@@ -1258,7 +1258,7 @@ function cacheWriteTokensOf(raw) {
1258
1258
  init_content();
1259
1259
 
1260
1260
  // src/version.ts
1261
- var SDK_VERSION = "0.19.0";
1261
+ var SDK_VERSION = "0.20.0";
1262
1262
 
1263
1263
  // src/utils/otlp/content.ts
1264
1264
  init_content();
@@ -10875,6 +10875,13 @@ function buildModelMessages(state, config) {
10875
10875
  var systemMessage = (content) => ({ role: "system", content });
10876
10876
  var humanMessage = (content) => ({ role: "user", content });
10877
10877
  var LAST_SUMMARIZATION_CALL_KEY = "__lastSummarizationCall";
10878
+ var SUMMARIZATION_TRIGGER_KEY = "__summarizationTrigger";
10879
+ var SUMMARIZATION_TRIGGERS = ["pre_leg", "mid_leg", "post_tools"];
10880
+ var MAX_EVENT_ERROR_CHARS = 300;
10881
+ function eventErrorText(message) {
10882
+ if (!message) return void 0;
10883
+ return message.length > MAX_EVENT_ERROR_CHARS ? `${message.slice(0, MAX_EVENT_ERROR_CHARS - 3)}...` : message;
10884
+ }
10878
10885
  var MAX_MESSAGE_CHARS = 2e3;
10879
10886
  var MAX_USER_MESSAGE_CHARS = 4e3;
10880
10887
  function validateMessageSequence(messages) {
@@ -11201,7 +11208,7 @@ function repairStructuredSummary(previous, current, integrity) {
11201
11208
  return { ...current, user_directives: directives, stable_facts: filteredFacts };
11202
11209
  }
11203
11210
  function createContextSummarizeNode(opts) {
11204
- return async (state) => {
11211
+ const summarizePass = async (state, events) => {
11205
11212
  const resolved = getResolvedSmartConfig(opts, state.agent);
11206
11213
  const config = resolved.summarization;
11207
11214
  if (!config.enable) return {};
@@ -11392,11 +11399,25 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
11392
11399
  ...summaryPrompt,
11393
11400
  ...rawModelOutput !== void 0 ? [{ role: "assistant", content: rawModelOutput, name: "summarization_result" }] : []
11394
11401
  ]));
11402
+ const summaryToolCallId = `call_summary_${Date.now()}_${nanoid.nanoid(6)}`;
11403
+ const passNumber = (Array.isArray(state.summaries) ? state.summaries.length : 0) + 1;
11404
+ const rawTrigger = state.ctx?.[SUMMARIZATION_TRIGGER_KEY];
11405
+ const trigger = SUMMARIZATION_TRIGGERS.includes(rawTrigger) ? rawTrigger : void 0;
11406
+ const passIdentity = {
11407
+ id: summaryToolCallId,
11408
+ pass: passNumber,
11409
+ ...trigger ? { trigger } : {}
11410
+ };
11395
11411
  const startTime = Date.now();
11396
11412
  try {
11397
11413
  if (!model || typeof model.invoke !== "function") {
11398
11414
  throw new Error("Summarization model is unavailable.");
11399
11415
  }
11416
+ events.started = passIdentity;
11417
+ try {
11418
+ onEvent?.({ type: "summarization", phase: "start", ...passIdentity, summary: "" });
11419
+ } catch {
11420
+ }
11400
11421
  const langchainRunOptions = model?._lc ? { runName: "summarize_context", tags: ["cognipeer:summarization"], metadata: { cognipeer_event: "summarization" } } : void 0;
11401
11422
  const response = langchainRunOptions ? await model.invoke(summaryPrompt, langchainRunOptions) : await model.invoke(summaryPrompt);
11402
11423
  durationMs = Date.now() - startTime;
@@ -11438,24 +11459,9 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
11438
11459
  structuredSummary = groundDirectives(structuredSummary);
11439
11460
  integrity = noteDroppedDirectives({ passed: true, criticalFactLoss: false, obsoleteFactRevived: false, notes: ["Fallback summary generated locally."] });
11440
11461
  summaryText = renderStructuredSummary(structuredSummary);
11441
- const errorEvent = {
11442
- type: "summarization",
11443
- summary: summaryText,
11444
- messagesCompressed: compressableMessages.length,
11445
- inputTokens: inputTokensEstimate,
11446
- outputTokens: countApproxTokens(summaryText),
11447
- durationMs,
11448
- previousSummary: previousSummary || void 0,
11449
- tokenCountBefore,
11450
- tokenCountAfter: tokenCountBefore,
11451
- structuredSummary,
11452
- integrity,
11453
- ...modelName ? { model: modelName } : {},
11454
- ...droppedDirectives.length > 0 ? { droppedDirectives } : {}
11455
- };
11456
- onEvent?.(errorEvent);
11457
11462
  summarizerError = traceErrorOf(err);
11458
11463
  }
11464
+ const eventError = eventErrorText(summarizerError?.message);
11459
11465
  const toolCallIdToAssistantIdx = /* @__PURE__ */ new Map();
11460
11466
  messages.forEach((m, idx) => {
11461
11467
  if (m.role === "assistant" && m.tool_calls && Array.isArray(m.tool_calls)) {
@@ -11547,10 +11553,19 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
11547
11553
  (m) => m.role === "tool" && isSummarizedToolPlaceholder(m.content) && !messages.some((orig) => orig.tool_call_id === m.tool_call_id && isSummarizedToolPlaceholder(orig.content))
11548
11554
  );
11549
11555
  if (actuallyCompressed.length === 0) {
11556
+ if (events.started) {
11557
+ events.ended = true;
11558
+ onEvent?.({
11559
+ type: "summarization",
11560
+ phase: "skipped",
11561
+ ...passIdentity,
11562
+ summary: "",
11563
+ ...fallback ? { status: "fallback", ...eventError ? { error: eventError } : {} } : {}
11564
+ });
11565
+ }
11550
11566
  return {};
11551
11567
  }
11552
11568
  const validatedMessages = validateMessageSequence(newMessages);
11553
- const summaryToolCallId = `call_summary_${Date.now()}`;
11554
11569
  const assistantSummaryCall = {
11555
11570
  role: "assistant",
11556
11571
  // "assistant"
@@ -11579,6 +11594,11 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
11579
11594
  const tokenCountAfter = countMessagesTokens(finalMessages);
11580
11595
  const summarizationEvent = {
11581
11596
  type: "summarization",
11597
+ phase: "done",
11598
+ ...passIdentity,
11599
+ status: fallback ? "fallback" : "ok",
11600
+ ...fallback && eventError ? { error: eventError } : {},
11601
+ compactedTools: actuallyCompressed.filter((m) => typeof m.tool_call_id === "string" && m.tool_call_id).map((m) => ({ toolCallId: m.tool_call_id, toolName: m.name || "" })),
11582
11602
  summary: summaryText,
11583
11603
  messagesCompressed: compressableMessages.length,
11584
11604
  inputTokens: inputTokensActual ?? inputTokensEstimate,
@@ -11596,6 +11616,7 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
11596
11616
  ...modelName ? { model: modelName } : {},
11597
11617
  ...droppedDirectives.length > 0 ? { droppedDirectives } : {}
11598
11618
  };
11619
+ events.ended = true;
11599
11620
  onEvent?.(summarizationEvent);
11600
11621
  traceSummarization({
11601
11622
  type: "summarization",
@@ -11658,6 +11679,7 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
11658
11679
  fallback
11659
11680
  }
11660
11681
  });
11682
+ const { [SUMMARIZATION_TRIGGER_KEY]: _passTrigger, ...carriedCtx } = ctxWithDeferredTrace ?? state.ctx ?? {};
11661
11683
  return {
11662
11684
  messages: finalMessages,
11663
11685
  summaries,
@@ -11667,7 +11689,7 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
11667
11689
  // held for the next leg. The smart driver merges ctx and removes the
11668
11690
  // call record once the hook has seen it.
11669
11691
  ctx: {
11670
- ...ctxWithDeferredTrace ?? state.ctx ?? {},
11692
+ ...carriedCtx,
11671
11693
  [LAST_SUMMARIZATION_CALL_KEY]: {
11672
11694
  ...modelName ? { model: modelName } : {},
11673
11695
  durationMs,
@@ -11685,6 +11707,30 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
11685
11707
  }
11686
11708
  };
11687
11709
  };
11710
+ return async (state) => {
11711
+ const events = {};
11712
+ try {
11713
+ return await summarizePass(state, events);
11714
+ } catch (err) {
11715
+ if (events.started && !events.ended) {
11716
+ events.ended = true;
11717
+ const onEvent = state.ctx?.__onEvent;
11718
+ const error = eventErrorText(traceErrorOf(err).message);
11719
+ try {
11720
+ onEvent?.({
11721
+ type: "summarization",
11722
+ phase: "skipped",
11723
+ ...events.started,
11724
+ summary: "",
11725
+ status: "error",
11726
+ ...error ? { error } : {}
11727
+ });
11728
+ } catch {
11729
+ }
11730
+ }
11731
+ throw err;
11732
+ }
11733
+ };
11688
11734
  }
11689
11735
 
11690
11736
  // src/index.ts
@@ -11853,9 +11899,10 @@ function createPlanTool(stateRef, toolName, description) {
11853
11899
  expectedVersion: zod.z.number().int().min(0).optional(),
11854
11900
  todoList: zod.z.array(todoItemWireSchema).optional()
11855
11901
  }),
11856
- func: async ({ operation, expectedVersion, todoList }) => {
11902
+ func: async ({ operation, expectedVersion, todoList }, context) => {
11857
11903
  const toolStateRef = manageTodo._stateRef;
11858
11904
  const onEvent = toolStateRef?.__onEvent;
11905
+ const toolCallId = context?.toolCallId || toolStateRef?.__currentToolCallId || void 0;
11859
11906
  const emitPlanEvent = (list) => {
11860
11907
  const version = stateRef.planVersion || 1;
11861
11908
  const adherenceScore = stateRef.adherenceScore || 0;
@@ -11864,7 +11911,8 @@ function createPlanTool(stateRef, toolName, description) {
11864
11911
  operation,
11865
11912
  version,
11866
11913
  adherenceScore,
11867
- count: Array.isArray(list) ? list.length : 0
11914
+ count: Array.isArray(list) ? list.length : 0,
11915
+ ...toolCallId ? { toolCallId } : {}
11868
11916
  };
11869
11917
  onEvent?.({ type: "plan", todoList: list, ...planData });
11870
11918
  const traceSession = toolStateRef?.ctx?.__traceSession;
@@ -13525,7 +13573,7 @@ ${pluginAppend}`;
13525
13573
  const toolCalls = Array.isArray(lastAssistant.tool_calls) ? lastAssistant.tool_calls : [];
13526
13574
  return toolCalls.length === 0;
13527
13575
  }
13528
- async function trySummarize(currentState, currentRawMessages, ref) {
13576
+ async function trySummarize(currentState, currentRawMessages, ref, trigger) {
13529
13577
  if (!summarizer) return { state: currentState, rawMessages: currentRawMessages, compressed: false };
13530
13578
  const compactHost = currentState.ctx?.__plugins;
13531
13579
  const tokensBefore = countMessagesTokens(currentState.messages || []);
@@ -13545,7 +13593,9 @@ ${pluginAppend}`;
13545
13593
  return { state: { ...currentState, ctx: ctx2 }, rawMessages: currentRawMessages, compressed: false };
13546
13594
  }
13547
13595
  }
13548
- const delta = await summarizer(currentState);
13596
+ const nodeState = { ...currentState, ctx: { ...currentState.ctx || {}, [SUMMARIZATION_TRIGGER_KEY]: trigger } };
13597
+ const delta = await summarizer(nodeState);
13598
+ if (nodeState.usage !== currentState.usage) currentState.usage = nodeState.usage;
13549
13599
  if (!delta || Object.keys(delta).length === 0) {
13550
13600
  const ctx2 = {
13551
13601
  ...currentState.ctx || {},
@@ -13557,6 +13607,7 @@ ${pluginAppend}`;
13557
13607
  const ctx = { ...currentState.ctx || {}, ...delta.ctx || {} };
13558
13608
  const summarizationCall = ctx[LAST_SUMMARIZATION_CALL_KEY];
13559
13609
  delete ctx[LAST_SUMMARIZATION_CALL_KEY];
13610
+ delete ctx[SUMMARIZATION_TRIGGER_KEY];
13560
13611
  delete ctx.__summarizationExhausted;
13561
13612
  delete ctx.__summarizationExhaustedAtToolCount;
13562
13613
  const updated = await persistLatestSummary(syncPlanStateWith(ref, { ...currentState, ...delta, ctx }));
@@ -13780,7 +13831,7 @@ ${pluginAppend}`;
13780
13831
  state = syncRuntimeTools({ ...state, messages: rawMessages }, rawMessages, toolSet);
13781
13832
  const next = summarizationEnabled ? decideBefore(state) : "agent";
13782
13833
  if (next === "contextSummarize" && summarizer) {
13783
- const result = await trySummarize(state, rawMessages, stateRef);
13834
+ const result = await trySummarize(state, rawMessages, stateRef, "pre_leg");
13784
13835
  state = result.state;
13785
13836
  rawMessages = result.rawMessages;
13786
13837
  noteTraceHandoff(state);
@@ -13815,7 +13866,7 @@ ${pluginAppend}`;
13815
13866
  const ctx = { ...state.ctx || {} };
13816
13867
  delete ctx.__needsSummarization;
13817
13868
  state = { ...state, ctx };
13818
- const result = await trySummarize(state, rawMessages, stateRef);
13869
+ const result = await trySummarize(state, rawMessages, stateRef, "mid_leg");
13819
13870
  state = result.state;
13820
13871
  rawMessages = result.rawMessages;
13821
13872
  noteTraceHandoff(state);
@@ -13827,7 +13878,7 @@ ${pluginAppend}`;
13827
13878
  if (summarizationEnabled) {
13828
13879
  const after = decideAfter(state);
13829
13880
  if (after === "contextSummarize" && summarizer) {
13830
- const result = await trySummarize(state, rawMessages, stateRef);
13881
+ const result = await trySummarize(state, rawMessages, stateRef, "post_tools");
13831
13882
  state = result.state;
13832
13883
  rawMessages = result.rawMessages;
13833
13884
  noteTraceHandoff(state);
@@ -22078,6 +22129,7 @@ exports.OpenAIProvider = OpenAIProvider;
22078
22129
  exports.PREOPEN_TOOL_CALL_PREFIX = PREOPEN_TOOL_CALL_PREFIX;
22079
22130
  exports.ProviderError = ProviderError;
22080
22131
  exports.SMALL_TIER_SKILL_POLICY = SMALL_TIER_SKILL_POLICY;
22132
+ exports.SUMMARIZATION_TRIGGER_KEY = SUMMARIZATION_TRIGGER_KEY;
22081
22133
  exports.StructuredOutputManager = StructuredOutputManager;
22082
22134
  exports.TOOL_INPUT_DIGEST_KEY = TOOL_INPUT_DIGEST_KEY;
22083
22135
  exports.ToolBasedStrategy = ToolBasedStrategy;