@cognipeer/agent-sdk 0.6.0 → 0.6.1

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
@@ -1978,7 +1978,9 @@ function createAgentCoreNode(opts) {
1978
1978
  const cancellationToken = state.ctx?.__cancellationToken;
1979
1979
  const abortSignal = state.ctx?.__abortSignal;
1980
1980
  const responseFormat = runtime.responseFormat;
1981
- const extractText = (chunk) => {
1981
+ const reasoningForCall = state.ctx?.__reasoning;
1982
+ const reasoningInvokeOpts = reasoningForCall ? { reasoning: reasoningForCall } : void 0;
1983
+ const extractText2 = (chunk) => {
1982
1984
  if (chunk == null) return "";
1983
1985
  if (typeof chunk === "string") return chunk;
1984
1986
  if (typeof chunk?.content === "string") return chunk.content;
@@ -1996,7 +1998,7 @@ function createAgentCoreNode(opts) {
1996
1998
  if (streamingEnabled && typeof modelWithTools.stream === "function") {
1997
1999
  let streamedText = "";
1998
2000
  let streamedMessage;
1999
- const streamOptions = { signal: abortSignal, cancellationToken, ...responseFormat };
2001
+ const streamOptions = { signal: abortSignal, cancellationToken, ...responseFormat, ...reasoningInvokeOpts };
2000
2002
  for await (const chunk of modelWithTools.stream(normalizedMessages, streamOptions)) {
2001
2003
  if (cancellationToken && cancellationToken.isCancellationRequested || abortSignal?.aborted) {
2002
2004
  break;
@@ -2004,7 +2006,7 @@ function createAgentCoreNode(opts) {
2004
2006
  if (chunk && typeof chunk === "object" && chunk.role) {
2005
2007
  streamedMessage = chunk;
2006
2008
  }
2007
- const text = extractText(chunk);
2009
+ const text = extractText2(chunk);
2008
2010
  if (text) {
2009
2011
  streamedText += text;
2010
2012
  onStream?.({ text });
@@ -2020,7 +2022,7 @@ function createAgentCoreNode(opts) {
2020
2022
  response = { role: "assistant", content: streamedText };
2021
2023
  }
2022
2024
  } else {
2023
- response = await modelWithTools.invoke(normalizedMessages, { signal: abortSignal, cancellationToken, ...responseFormat });
2025
+ response = await modelWithTools.invoke(normalizedMessages, { signal: abortSignal, cancellationToken, ...responseFormat, ...reasoningInvokeOpts });
2024
2026
  }
2025
2027
  } catch (err) {
2026
2028
  const durationMs2 = Date.now() - start;
@@ -2939,6 +2941,246 @@ function createToolLimitFinalizeNode(_opts) {
2939
2941
  return { messages: [...state.messages, notice], ctx };
2940
2942
  };
2941
2943
  }
2944
+ var REFLECTION_SYSTEM_NAME = "agent_reflection";
2945
+ var REFLECTION_ASK_NAME = "agent_reflection_ask";
2946
+ var DEFAULT_REFLECT_PROMPT = `Reflect briefly \u2014 plain text, no JSON, no tool calls.
2947
+ Structure your note (1\u20132 sentences each):
2948
+ 1) What the latest tool results actually tell us (facts, surprises).
2949
+ 2) What is still missing or uncertain before we can finish the user's task.
2950
+ 3) The single next step you plan to take, and why that step over alternatives.
2951
+ Be concrete. Do not repeat the task description. Do not apologize. Max ${"${maxChars}"} characters total.`;
2952
+ function trimToChars(text, maxChars) {
2953
+ if (text.length <= maxChars) return text;
2954
+ return text.slice(0, maxChars - 1).trimEnd() + "\u2026";
2955
+ }
2956
+ function countToolCallsInLastTurn(state) {
2957
+ const ids = [];
2958
+ const names = [];
2959
+ for (let i = state.messages.length - 1; i >= 0; i--) {
2960
+ const m = state.messages[i];
2961
+ if (m?.role === "tool") {
2962
+ if (m.tool_call_id) ids.push(m.tool_call_id);
2963
+ if (m.name) names.push(m.name);
2964
+ } else if (m?.role === "assistant") {
2965
+ break;
2966
+ }
2967
+ }
2968
+ return { ids, names };
2969
+ }
2970
+ function stripReflectionAskMessages(messages) {
2971
+ return messages.filter((m) => !(m?.role === "user" && m?.name === REFLECTION_ASK_NAME));
2972
+ }
2973
+ function shouldRunReflection(cadence, state, ranToolsThisTurn) {
2974
+ if (cadence === "off") return false;
2975
+ if (cadence === "every_turn") return true;
2976
+ if (cadence === "after_tool") return ranToolsThisTurn;
2977
+ if (cadence === "on_branch") {
2978
+ const reflections = state.reflections || [];
2979
+ const lastReflectionTurn = reflections[reflections.length - 1]?.turn ?? -1;
2980
+ const currentTurnId = state.toolCallCount ?? 0;
2981
+ return currentTurnId - lastReflectionTurn >= 2;
2982
+ }
2983
+ return false;
2984
+ }
2985
+ function createReflectionNode(opts, resolved) {
2986
+ return async function reflectNode(state, trigger) {
2987
+ if (!resolved.enabled) return {};
2988
+ const runtime = state.agent || {
2989
+ model: opts.model,
2990
+ name: opts.name,
2991
+ version: opts.version
2992
+ };
2993
+ const model = runtime.model;
2994
+ if (!model?.invoke && !model?.stream) return {};
2995
+ const onEvent = state.ctx?.__onEvent;
2996
+ const traceSession = state.ctx?.__traceSession;
2997
+ const maxChars = resolved.maxChars;
2998
+ const promptBody = (resolved.promptTemplate || DEFAULT_REFLECT_PROMPT).replace(/\$\{maxChars\}/g, String(maxChars));
2999
+ const baseMessages = stripReflectionAskMessages([...state.messages]);
3000
+ const askMessage = {
3001
+ role: "user",
3002
+ name: REFLECTION_ASK_NAME,
3003
+ content: promptBody
3004
+ };
3005
+ const messagesForCall = resolved.mode === "piggyback" ? [...baseMessages, askMessage] : buildSeparateCallMessages(baseMessages, promptBody);
3006
+ const start = Date.now();
3007
+ let response;
3008
+ try {
3009
+ response = await model.invoke(messagesForCall, {
3010
+ // tool_choice:"none" so the model won't try to call tools during reflection
3011
+ tool_choice: "none",
3012
+ toolChoice: "none",
3013
+ // Override max_tokens for the reflection call. BaseChatModel passes this through
3014
+ // to the adapter which forwards into the provider body.
3015
+ max_tokens: resolved.maxTokens,
3016
+ maxTokens: resolved.maxTokens
3017
+ });
3018
+ } catch (err) {
3019
+ recordTraceEvent(traceSession, {
3020
+ type: "reflection",
3021
+ label: "Reflection error",
3022
+ actor: { scope: "agent", name: opts.name || "agent", role: "reflection" },
3023
+ status: "error",
3024
+ error: { message: err?.message || String(err) }
3025
+ });
3026
+ return {};
3027
+ }
3028
+ const durationMs = Date.now() - start;
3029
+ const rawText = extractText(response);
3030
+ const text = trimToChars(String(rawText ?? "").trim(), maxChars);
3031
+ if (!text) return {};
3032
+ const rawUsage = response?.usage_metadata || response?.response_metadata?.usage || response?.usage || response?.additional_kwargs?.usage;
3033
+ const usage = normalizeUsage(rawUsage);
3034
+ const { ids, names } = countToolCallsInLastTurn(state);
3035
+ const turn = state.toolCallCount ?? 0;
3036
+ const record = {
3037
+ id: safeRandomId(),
3038
+ turn,
3039
+ text,
3040
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3041
+ durationMs,
3042
+ anchorMessageIndex: state.messages.length,
3043
+ trigger,
3044
+ usage: usage ? {
3045
+ inputTokens: usage.prompt_tokens,
3046
+ outputTokens: usage.completion_tokens,
3047
+ cachedInputTokens: usage.prompt_tokens_details?.cached_tokens,
3048
+ totalTokens: usage.total_tokens,
3049
+ reasoningTokens: usage.completion_tokens_details?.reasoning_tokens
3050
+ } : void 0,
3051
+ toolCallIds: ids.length > 0 ? ids : void 0
3052
+ };
3053
+ recordTraceEvent(traceSession, {
3054
+ type: "reflection",
3055
+ label: `Reflection turn ${turn}`,
3056
+ actor: { scope: "agent", name: opts.name || "agent", role: "reflection" },
3057
+ status: "success",
3058
+ durationMs,
3059
+ inputTokens: record.usage?.inputTokens,
3060
+ outputTokens: record.usage?.outputTokens,
3061
+ cachedInputTokens: record.usage?.cachedInputTokens,
3062
+ totalTokens: record.usage?.totalTokens,
3063
+ debug: { text, toolNames: names }
3064
+ });
3065
+ if (resolved.emitEvents) {
3066
+ try {
3067
+ onEvent?.({
3068
+ type: "reflection",
3069
+ id: record.id,
3070
+ turn,
3071
+ text,
3072
+ trigger,
3073
+ durationMs,
3074
+ usage: record.usage,
3075
+ toolCallIds: record.toolCallIds
3076
+ });
3077
+ } catch (e) {
3078
+ }
3079
+ }
3080
+ const nextMessages = stripReflectionAskMessages([...state.messages]);
3081
+ const reflections = [...state.reflections || [], record];
3082
+ const kept = reflections.slice(-Math.max(1, resolved.keepLast));
3083
+ const prunedMessages = nextMessages.filter(
3084
+ (m) => !(m?.role === "system" && m?.name === REFLECTION_SYSTEM_NAME)
3085
+ );
3086
+ for (const r of kept) {
3087
+ prunedMessages.push({
3088
+ role: "system",
3089
+ name: REFLECTION_SYSTEM_NAME,
3090
+ content: `<agent_reflection turn=${r.turn} at=${r.createdAt}>
3091
+ ${r.text}
3092
+ </agent_reflection>`,
3093
+ metadata: { reflectionId: r.id, reflectionTurn: r.turn, reflectionTrigger: r.trigger }
3094
+ });
3095
+ }
3096
+ return { messages: prunedMessages, reflections };
3097
+ };
3098
+ }
3099
+ function extractText(chunk) {
3100
+ if (chunk == null) return "";
3101
+ if (typeof chunk === "string") return chunk;
3102
+ if (typeof chunk?.content === "string") return chunk.content;
3103
+ if (Array.isArray(chunk?.content)) {
3104
+ return chunk.content.map((c) => typeof c === "string" ? c : c?.text ?? c?.content ?? "").join("");
3105
+ }
3106
+ if (typeof chunk?.text === "string") return chunk.text;
3107
+ return "";
3108
+ }
3109
+ function buildSeparateCallMessages(base, promptBody) {
3110
+ const systemMessages = base.filter((m) => m?.role === "system");
3111
+ const tail = base.slice(-8);
3112
+ return [
3113
+ ...systemMessages,
3114
+ ...tail,
3115
+ { role: "user", name: REFLECTION_ASK_NAME, content: promptBody }
3116
+ ];
3117
+ }
3118
+ function safeRandomId() {
3119
+ try {
3120
+ return crypto.randomUUID();
3121
+ } catch {
3122
+ return `r_${Math.random().toString(36).slice(2, 10)}_${Date.now().toString(36)}`;
3123
+ }
3124
+ }
3125
+
3126
+ // src/smart/reasoning.ts
3127
+ var LEVEL_DEFAULTS = {
3128
+ low: {
3129
+ native: { effort: "low" },
3130
+ reflection: { maxTokens: 200, maxChars: 600, cadence: "on_branch" }
3131
+ },
3132
+ medium: {
3133
+ native: { effort: "medium" },
3134
+ reflection: { maxTokens: 350, maxChars: 1200, cadence: "after_tool" }
3135
+ },
3136
+ high: {
3137
+ native: { effort: "high" },
3138
+ reflection: { maxTokens: 600, maxChars: 2e3, cadence: "after_tool" }
3139
+ }
3140
+ };
3141
+ function resolveReasoning(input) {
3142
+ if (!input || input.enabled === false) return void 0;
3143
+ const enabled = input.enabled ?? (input.native !== void 0 || input.reflection !== void 0 || input.level !== void 0);
3144
+ if (!enabled) return void 0;
3145
+ const level = input.level ?? "medium";
3146
+ const presets = LEVEL_DEFAULTS[level];
3147
+ let native;
3148
+ if (input.native === false) {
3149
+ native = void 0;
3150
+ } else {
3151
+ native = { ...presets.native, ...input.native ?? {} };
3152
+ }
3153
+ const reflection = resolveReflection(input.reflection, presets.reflection);
3154
+ return { enabled: true, level, native, reflection };
3155
+ }
3156
+ function resolveReflection(input, preset) {
3157
+ if (input === false) {
3158
+ return {
3159
+ enabled: false,
3160
+ cadence: "off",
3161
+ mode: "piggyback",
3162
+ maxTokens: preset.maxTokens,
3163
+ maxChars: preset.maxChars,
3164
+ keepLast: 3,
3165
+ summarize: false,
3166
+ emitEvents: true
3167
+ };
3168
+ }
3169
+ const cfg = input ?? {};
3170
+ const enabled = cfg.enabled ?? true;
3171
+ const cadence = cfg.cadence ?? preset.cadence;
3172
+ return {
3173
+ enabled: enabled && cadence !== "off",
3174
+ cadence: enabled ? cadence : "off",
3175
+ mode: cfg.mode ?? "piggyback",
3176
+ maxTokens: cfg.maxTokens ?? preset.maxTokens,
3177
+ maxChars: cfg.maxChars ?? preset.maxChars,
3178
+ keepLast: cfg.keepLast ?? 3,
3179
+ summarize: cfg.summarize ?? false,
3180
+ promptTemplate: cfg.promptTemplate,
3181
+ emitEvents: cfg.emitEvents ?? true
3182
+ };
3183
+ }
2942
3184
  function ensureArray(value) {
2943
3185
  return Array.isArray(value) ? value : [];
2944
3186
  }
@@ -3352,6 +3594,8 @@ function createAgent(opts) {
3352
3594
  }
3353
3595
  const toolsNode = createToolsNode(toolsBase, opts);
3354
3596
  const finalizeNode = createToolLimitFinalizeNode();
3597
+ const resolvedReasoning = resolveReasoning(opts.reasoning);
3598
+ const reflectNode = resolvedReasoning?.reflection.enabled ? createReflectionNode(opts, resolvedReasoning.reflection) : void 0;
3355
3599
  const mergeGuardrailOutcomes = (prev, next) => {
3356
3600
  if (!prev) return next;
3357
3601
  return {
@@ -3406,6 +3650,13 @@ function createAgent(opts) {
3406
3650
  if (summarizationThreshold === void 0) {
3407
3651
  state = clearNeedsSummarization(state);
3408
3652
  }
3653
+ if (resolvedReasoning?.native) {
3654
+ const ctx = { ...state.ctx || {} };
3655
+ if (!ctx.__reasoning) {
3656
+ ctx.__reasoning = resolvedReasoning.native;
3657
+ state = { ...state, ctx };
3658
+ }
3659
+ }
3409
3660
  const mergedLimits = {
3410
3661
  ...opts.limits || {},
3411
3662
  ...config?.limits || {}
@@ -3634,6 +3885,18 @@ function createAgent(opts) {
3634
3885
  if (state.ctx?.__awaitingApproval) break;
3635
3886
  if (checkpointIfRequested("after_tools")) break;
3636
3887
  if (state.ctx?.__finalizedDueToStructuredOutput) break;
3888
+ if (reflectNode && resolvedReasoning?.reflection.enabled) {
3889
+ const cadence = resolvedReasoning.reflection.cadence;
3890
+ if (shouldRunReflection(cadence, state, true)) {
3891
+ try {
3892
+ const patch = await reflectNode(state, cadence);
3893
+ if (patch && Object.keys(patch).length > 0) {
3894
+ state = { ...state, ...patch };
3895
+ }
3896
+ } catch {
3897
+ }
3898
+ }
3899
+ }
3637
3900
  }
3638
3901
  if (soManager && !state.ctx?.__finalizedDueToStructuredOutput) {
3639
3902
  const lastForParse = state.messages[state.messages.length - 1];
@@ -5643,6 +5906,52 @@ function parseSSEBlock(block) {
5643
5906
  return { event, data: dataLines.join("\n"), id, retry };
5644
5907
  }
5645
5908
 
5909
+ // src/providers/utils/reasoning.ts
5910
+ function applyOpenAIReasoning(body, reasoning, mode = "legacy_effort") {
5911
+ if (!reasoning) return;
5912
+ const effort = normalizeEffort(reasoning.effort);
5913
+ if (mode === "responses") {
5914
+ const obj = {};
5915
+ if (effort) obj.effort = effort;
5916
+ if (reasoning.includeThoughts) obj.summary = "auto";
5917
+ if (reasoning.providerExtras) Object.assign(obj, reasoning.providerExtras);
5918
+ if (Object.keys(obj).length > 0) body.reasoning = obj;
5919
+ } else {
5920
+ if (effort) body.reasoning_effort = effort;
5921
+ if (reasoning.providerExtras) Object.assign(body, reasoning.providerExtras);
5922
+ }
5923
+ }
5924
+ function applyAnthropicReasoning(body, reasoning) {
5925
+ if (!reasoning) return;
5926
+ const budget = resolveBudget(reasoning, { low: 2048, medium: 8192, high: 16384, minimal: 1024 });
5927
+ if (!budget) return;
5928
+ const thinking = { type: "enabled", budget_tokens: budget };
5929
+ if (reasoning.providerExtras) Object.assign(thinking, reasoning.providerExtras);
5930
+ body.thinking = thinking;
5931
+ }
5932
+ function applyGeminiReasoning(generationConfig, reasoning) {
5933
+ if (!reasoning) return;
5934
+ const budget = resolveBudget(reasoning, { low: 1024, medium: 4096, high: 12e3, minimal: 512 });
5935
+ if (budget == null) return;
5936
+ const thinkingConfig = { thinkingBudget: budget };
5937
+ if (reasoning.includeThoughts) thinkingConfig.includeThoughts = true;
5938
+ if (reasoning.providerExtras) Object.assign(thinkingConfig, reasoning.providerExtras);
5939
+ generationConfig.thinkingConfig = thinkingConfig;
5940
+ }
5941
+ function normalizeEffort(effort) {
5942
+ if (!effort) return void 0;
5943
+ const allowed = ["minimal", "low", "medium", "high"];
5944
+ return allowed.includes(effort) ? effort : void 0;
5945
+ }
5946
+ function resolveBudget(reasoning, effortBudget) {
5947
+ if (typeof reasoning.budgetTokens === "number" && reasoning.budgetTokens > 0) {
5948
+ return Math.floor(reasoning.budgetTokens);
5949
+ }
5950
+ const effort = normalizeEffort(reasoning.effort);
5951
+ if (effort && effortBudget[effort]) return effortBudget[effort];
5952
+ return void 0;
5953
+ }
5954
+
5646
5955
  // src/providers/openai.ts
5647
5956
  var OpenAIProvider = class extends BaseProvider {
5648
5957
  constructor(config) {
@@ -5758,6 +6067,7 @@ var OpenAIProvider = class extends BaseProvider {
5758
6067
  if (request.extra) {
5759
6068
  Object.assign(body, request.extra);
5760
6069
  }
6070
+ applyOpenAIReasoning(body, request.reasoning, "legacy_effort");
5761
6071
  return body;
5762
6072
  }
5763
6073
  toOpenAIMessage(m) {
@@ -6016,6 +6326,7 @@ var AnthropicProvider = class extends BaseProvider {
6016
6326
  if (request.extra) {
6017
6327
  Object.assign(body, request.extra);
6018
6328
  }
6329
+ applyAnthropicReasoning(body, request.reasoning);
6019
6330
  return body;
6020
6331
  }
6021
6332
  splitSystemMessages(messages) {
@@ -6670,6 +6981,7 @@ var VertexProvider = class extends BaseProvider {
6670
6981
  }
6671
6982
  }
6672
6983
  }
6984
+ applyGeminiReasoning(generationConfig, request.reasoning);
6673
6985
  if (Object.keys(generationConfig).length > 0) body.generationConfig = generationConfig;
6674
6986
  if (request.tools?.length) {
6675
6987
  body.tools = [
@@ -7008,6 +7320,13 @@ function fromNativeProvider(provider, options) {
7008
7320
  if (opts?.maxTokens != null) req.maxTokens = opts.maxTokens;
7009
7321
  if (tools?.length) req.tools = tools;
7010
7322
  if (opts?.extra) req.extra = opts.extra;
7323
+ const reasoningOverride = invokeOptions?.reasoning;
7324
+ const reasoningCfg = reasoningOverride ?? opts?.reasoning;
7325
+ if (reasoningCfg) req.reasoning = reasoningCfg;
7326
+ const tc = invokeOptions?.tool_choice ?? invokeOptions?.toolChoice;
7327
+ if (tc) {
7328
+ req.toolChoice = tc;
7329
+ }
7011
7330
  const rf = invokeOptions?.response_format;
7012
7331
  if (rf && typeof rf === "object" && rf.type) {
7013
7332
  if (rf.type === "json_schema" && rf.json_schema) {