@cognipeer/agent-sdk 0.8.11 → 0.9.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
@@ -5309,7 +5309,10 @@ function shouldSignalSummarization(state, threshold) {
5309
5309
  });
5310
5310
  const tokenCount = countMessagesTokens(tokCountMessages);
5311
5311
  if (tokenCount <= threshold) return "skip";
5312
- if (state.ctx?.__summarizationExhausted) return "skip";
5312
+ if (state.ctx?.__summarizationExhausted) {
5313
+ const exhaustedAt = state.ctx?.__summarizationExhaustedAtToolCount;
5314
+ if (typeof exhaustedAt !== "number" || (state.toolHistory || []).length <= exhaustedAt) return "skip";
5315
+ }
5313
5316
  const hasFreshSummary = (state.messages || []).some(
5314
5317
  (m) => m.role === "tool" && typeof m.content === "string" && (m.content === "SUMMARIZED" || m.content.startsWith("SUMMARIZED_TOOL_RESPONSE"))
5315
5318
  );
@@ -6354,6 +6357,20 @@ function extractCanonicalFacts(messages) {
6354
6357
  function isSummarizedToolPlaceholder(content) {
6355
6358
  return typeof content === "string" && (content === "SUMMARIZED" || content.startsWith("SUMMARIZED_TOOL_RESPONSE") || content.startsWith("ARCHIVED_TOOL_RESPONSE") || content.startsWith("STRUCTURED_TOOL_RESPONSE") || content.startsWith("DROPPED_TOOL_RESPONSE"));
6356
6359
  }
6360
+ function collectLatestTurnToolCallIds(messages) {
6361
+ const ids = /* @__PURE__ */ new Set();
6362
+ for (let i = messages.length - 1; i >= 0; i--) {
6363
+ const m = messages[i];
6364
+ if (isSyntheticSummaryMessage(m)) continue;
6365
+ if (m.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
6366
+ for (const tc of m.tool_calls) {
6367
+ if (tc.id) ids.add(tc.id);
6368
+ }
6369
+ break;
6370
+ }
6371
+ }
6372
+ return ids;
6373
+ }
6357
6374
  function findToolHistoryEntry(state, toolCallId, toolName) {
6358
6375
  const entries = [
6359
6376
  ...state.toolHistory || [],
@@ -6448,6 +6465,10 @@ function createContextSummarizeNode(opts) {
6448
6465
  if (compressableMessages.length === 0) {
6449
6466
  return {};
6450
6467
  }
6468
+ const protectedToolCallIds = collectLatestTurnToolCallIds(messages);
6469
+ if (compressableMessages.every((m) => m.tool_call_id && protectedToolCallIds.has(m.tool_call_id))) {
6470
+ return {};
6471
+ }
6451
6472
  const tokenCountBefore = countMessagesTokens(messages);
6452
6473
  const summaryPromptMaxTokens = config.summaryPromptMaxTokens;
6453
6474
  const availableTokensForConversation = summaryPromptMaxTokens - 500;
@@ -6467,7 +6488,8 @@ function createContextSummarizeNode(opts) {
6467
6488
  const historyEntry = findToolHistoryEntry(state, m.tool_call_id, m.name);
6468
6489
  if (historyEntry) {
6469
6490
  const original = historyEntry.rawOutput ?? historyEntry.output;
6470
- content = typeof original === "string" ? original : JSON.stringify(original);
6491
+ const recovered = typeof original === "string" ? original : JSON.stringify(original);
6492
+ if (typeof recovered === "string") content = recovered;
6471
6493
  }
6472
6494
  }
6473
6495
  const maxContentLength = 2e3;
@@ -6606,22 +6628,6 @@ ${canonicalFacts.length > 0 ? canonicalFacts.map((fact) => `- ${fact.key}: ${fac
6606
6628
  });
6607
6629
  }
6608
6630
  });
6609
- const protectedToolCallIds = /* @__PURE__ */ new Set();
6610
- for (let i = messages.length - 1; i >= 0; i--) {
6611
- const m = messages[i];
6612
- if (m.role === "assistant" && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {
6613
- const thisToolCallIds = new Set(m.tool_calls.map((tc) => tc.id).filter(Boolean));
6614
- const otherCompressable = compressableMessages.filter(
6615
- (cm) => !thisToolCallIds.has(cm.tool_call_id)
6616
- );
6617
- if (otherCompressable.length > 0) {
6618
- for (const tc of m.tool_calls) {
6619
- if (tc.id) protectedToolCallIds.add(tc.id);
6620
- }
6621
- }
6622
- break;
6623
- }
6624
- }
6625
6631
  const retentionDeclarations = collectToolRetentionDeclarations(state.agent?.tools);
6626
6632
  const digestableToolCallIds = /* @__PURE__ */ new Set();
6627
6633
  for (const m of messages) {
@@ -7550,6 +7556,127 @@ function createSkillTools(deps) {
7550
7556
  if (isSearchDisclosure(deps.policy)) tools.unshift(createSearchSkillsTool(deps));
7551
7557
  return tools;
7552
7558
  }
7559
+ var PREOPEN_TOOL_CALL_PREFIX = "preopen_skill_";
7560
+ var OPEN_SKILL_TOOL_NAME = "open_skill";
7561
+ function preopenToolCallId(skillKey) {
7562
+ return `${PREOPEN_TOOL_CALL_PREFIX}${skillKey.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
7563
+ }
7564
+ function messagesContainCallId(messages, callId) {
7565
+ if (!Array.isArray(messages)) return false;
7566
+ return messages.some((message) => {
7567
+ const calls = message?.tool_calls;
7568
+ return Array.isArray(calls) && calls.some((call) => call?.id === callId);
7569
+ });
7570
+ }
7571
+ function serializeToolContent(result) {
7572
+ if (typeof result === "string") return result;
7573
+ try {
7574
+ return JSON.stringify(result);
7575
+ } catch {
7576
+ return String(result);
7577
+ }
7578
+ }
7579
+ async function preopenSkills(input) {
7580
+ const empty = { messages: [], toolHistory: [], openedKeys: [], skipped: [] };
7581
+ const requested = [...new Set(
7582
+ (input.skillKeys ?? []).map((key) => String(key ?? "").trim()).filter(Boolean)
7583
+ )];
7584
+ if (requested.length === 0) return empty;
7585
+ const openSkillTool = input.tools.find((tool) => tool?.name === OPEN_SKILL_TOOL_NAME);
7586
+ if (!openSkillTool) {
7587
+ return { ...empty, skipped: requested.map((skillKey) => ({ skillKey, reason: "open_skill tool is not wired" })) };
7588
+ }
7589
+ const alreadyOpen = new Set(input.alreadyOpenedKeys ?? []);
7590
+ const toolCalls = [];
7591
+ const toolMessages = [];
7592
+ const toolHistory = [];
7593
+ const openedKeys = [];
7594
+ const skipped = [];
7595
+ for (const skillKey of requested) {
7596
+ const toolCallId = preopenToolCallId(skillKey);
7597
+ if (alreadyOpen.has(skillKey) || messagesContainCallId(input.existingMessages, toolCallId)) {
7598
+ skipped.push({ skillKey, reason: "already open" });
7599
+ continue;
7600
+ }
7601
+ const args = { skillKey };
7602
+ input.onEvent?.({ type: "tool_call", phase: "start", name: OPEN_SKILL_TOOL_NAME, id: toolCallId, args });
7603
+ const start = Date.now();
7604
+ let result;
7605
+ try {
7606
+ result = await openSkillTool.invoke(args);
7607
+ } catch (error) {
7608
+ const message = error instanceof Error ? error.message : "open_skill failed";
7609
+ input.onEvent?.({
7610
+ type: "tool_call",
7611
+ phase: "error",
7612
+ name: OPEN_SKILL_TOOL_NAME,
7613
+ id: toolCallId,
7614
+ args,
7615
+ error: { message },
7616
+ durationMs: Date.now() - start
7617
+ });
7618
+ skipped.push({ skillKey, reason: message });
7619
+ continue;
7620
+ }
7621
+ const durationMs = Date.now() - start;
7622
+ if (result && typeof result === "object" && typeof result.error === "string") {
7623
+ input.onEvent?.({
7624
+ type: "tool_call",
7625
+ phase: "skipped",
7626
+ name: OPEN_SKILL_TOOL_NAME,
7627
+ id: toolCallId,
7628
+ args,
7629
+ error: { message: result.error },
7630
+ durationMs
7631
+ });
7632
+ skipped.push({ skillKey, reason: result.error });
7633
+ continue;
7634
+ }
7635
+ if (result && typeof result === "object") delete result.__runtimeToolsDelta;
7636
+ toolCalls.push({
7637
+ id: toolCallId,
7638
+ type: "function",
7639
+ function: { name: OPEN_SKILL_TOOL_NAME, arguments: JSON.stringify(args) }
7640
+ });
7641
+ toolMessages.push({
7642
+ role: "tool",
7643
+ name: OPEN_SKILL_TOOL_NAME,
7644
+ tool_call_id: toolCallId,
7645
+ content: serializeToolContent(result)
7646
+ });
7647
+ toolHistory.push({
7648
+ executionId: nanoid.nanoid(),
7649
+ toolName: OPEN_SKILL_TOOL_NAME,
7650
+ args,
7651
+ output: result,
7652
+ rawOutput: result,
7653
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
7654
+ tool_call_id: toolCallId,
7655
+ summarized: false,
7656
+ retentionPolicy: "keep_full",
7657
+ status: "success"
7658
+ });
7659
+ openedKeys.push(skillKey);
7660
+ input.onEvent?.({
7661
+ type: "tool_call",
7662
+ phase: "success",
7663
+ name: OPEN_SKILL_TOOL_NAME,
7664
+ id: toolCallId,
7665
+ args,
7666
+ result,
7667
+ durationMs
7668
+ });
7669
+ }
7670
+ if (toolCalls.length === 0) {
7671
+ return { ...empty, skipped };
7672
+ }
7673
+ const assistantMessage = {
7674
+ role: "assistant",
7675
+ content: `Opening the ${openedKeys.join(", ")} skill${openedKeys.length > 1 ? "s" : ""} required for this task.`,
7676
+ tool_calls: toolCalls
7677
+ };
7678
+ return { messages: [assistantMessage, ...toolMessages], toolHistory, openedKeys, skipped };
7679
+ }
7553
7680
 
7554
7681
  // src/smart/subagents/types.ts
7555
7682
  var DEFAULT_SUBAGENT_POLICY = {
@@ -8206,11 +8333,16 @@ function createSmartAgent(opts) {
8206
8333
  if (!summarizer) return { state: currentState, rawMessages: currentRawMessages, compressed: false };
8207
8334
  const delta = await summarizer(currentState);
8208
8335
  if (!delta || Object.keys(delta).length === 0) {
8209
- const ctx2 = { ...currentState.ctx || {}, __summarizationExhausted: true };
8336
+ const ctx2 = {
8337
+ ...currentState.ctx || {},
8338
+ __summarizationExhausted: true,
8339
+ __summarizationExhaustedAtToolCount: (currentState.toolHistory || []).length
8340
+ };
8210
8341
  return { state: { ...currentState, ctx: ctx2 }, rawMessages: currentRawMessages, compressed: false };
8211
8342
  }
8212
8343
  const ctx = { ...currentState.ctx || {} };
8213
8344
  delete ctx.__summarizationExhausted;
8345
+ delete ctx.__summarizationExhaustedAtToolCount;
8214
8346
  const updated = await persistLatestSummary(syncPlanStateWith(ref, { ...currentState, ...delta, ctx }));
8215
8347
  return { state: updated, rawMessages: [...updated.messages || currentRawMessages], compressed: true };
8216
8348
  }
@@ -8251,7 +8383,25 @@ function createSmartAgent(opts) {
8251
8383
  const disclosureBlock = [skillBlock, subagentBlock].filter(Boolean).join("\n\n") || void 0;
8252
8384
  const alreadyHasSystem = Array.isArray(input.messages) && input.messages[0]?.role === "system";
8253
8385
  const seedMessages = alreadyHasSystem ? [...input.messages || []] : [systemMessage2(disclosureBlock), ...input.messages || []];
8254
- let state = syncRuntimeTools(await syncMemory({ ...input, messages: seedMessages }), seedMessages, toolSet);
8386
+ let seedToolHistory = input.toolHistory;
8387
+ if (skillsEnabled && toolSet.skillRegistryRef) {
8388
+ const preopenKeys = config?.preopenedSkills ?? [];
8389
+ if (preopenKeys.length > 0) {
8390
+ const preopened = await preopenSkills({
8391
+ skillKeys: preopenKeys,
8392
+ tools: toolSet.toolsWithoutRecovery,
8393
+ alreadyOpenedKeys: toolSet.skillRegistryRef.openedSkillKeys,
8394
+ existingMessages: seedMessages,
8395
+ onEvent: config?.onEvent ?? opts.onEvent
8396
+ });
8397
+ if (preopened.messages.length > 0) {
8398
+ seedMessages.push(...preopened.messages);
8399
+ seedToolHistory = [...seedToolHistory ?? [], ...preopened.toolHistory];
8400
+ stateRef.toolHistory = seedToolHistory;
8401
+ }
8402
+ }
8403
+ }
8404
+ let state = syncRuntimeTools(await syncMemory({ ...input, messages: seedMessages, toolHistory: seedToolHistory }), seedMessages, toolSet);
8255
8405
  let lastResult = null;
8256
8406
  let rawMessages = [...seedMessages];
8257
8407
  const effectiveMaxToolCalls = config?.limits?.maxToolCalls ?? resolved.limits.maxToolCalls ?? 10;
@@ -11533,6 +11683,7 @@ exports.InMemoryMemoryStore = InMemoryMemoryStore;
11533
11683
  exports.NativeJsonSchemaStrategy = NativeJsonSchemaStrategy;
11534
11684
  exports.OpenAICompatibleProvider = OpenAICompatibleProvider;
11535
11685
  exports.OpenAIProvider = OpenAIProvider;
11686
+ exports.PREOPEN_TOOL_CALL_PREFIX = PREOPEN_TOOL_CALL_PREFIX;
11536
11687
  exports.ProviderError = ProviderError;
11537
11688
  exports.SMALL_TIER_SKILL_POLICY = SMALL_TIER_SKILL_POLICY;
11538
11689
  exports.StructuredOutputManager = StructuredOutputManager;
@@ -11619,6 +11770,8 @@ exports.loadSkillsFromDisk = loadSkillsFromDisk;
11619
11770
  exports.normalizeSmartAgentOptions = normalizeSmartAgentOptions;
11620
11771
  exports.otlpSink = otlpSink;
11621
11772
  exports.parseSkillFrontmatter = parseSkillFrontmatter;
11773
+ exports.preopenSkills = preopenSkills;
11774
+ exports.preopenToolCallId = preopenToolCallId;
11622
11775
  exports.readMemoryFacts = readMemoryFacts;
11623
11776
  exports.regexRule = regexRule;
11624
11777
  exports.resolveAvailableSkills = resolveAvailableSkills;