deepagents 1.16.3 → 1.16.4

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.
@@ -1,6 +1,6 @@
1
- import { AIMessage, HumanMessage, SystemMessage, ToolMessage, anthropicPromptCachingMiddleware, bedrockPromptCachingMiddleware, context, countTokensApproximately, createAgent, createMiddleware, humanInTheLoopMiddleware, todoListMiddleware, tool } from "langchain";
1
+ import { AIMessage, HumanMessage, SystemMessage, ToolMessage, anthropicPromptCachingMiddleware, bedrockPromptCachingMiddleware, context, countTokensApproximately, createAgent, createMiddleware, humanInTheLoopMiddleware, modelRefusalMiddleware, todoListMiddleware, tool } from "langchain";
2
2
  import { omitPayload } from "@langchain/core/tracers/tracer_langchain";
3
- import { ContextOverflowError } from "@langchain/core/errors";
3
+ import { ContextOverflowError, ModelRefusalError } from "@langchain/core/errors";
4
4
  import { Command, Overwrite, REMOVE_ALL_MESSAGES, ReducedValue, StateSchema, getConfig, getCurrentTaskInput, getStore, isCommand, isGraphBubbleUp } from "@langchain/langgraph";
5
5
  import { z } from "zod/v4";
6
6
  import micromatch from "micromatch";
@@ -3540,6 +3540,54 @@ function createFilesystemMiddleware(options = {}) {
3540
3540
  }
3541
3541
  });
3542
3542
  }
3543
+ // src/middleware/refusal.ts
3544
+ /**
3545
+ * The task result reported when a model in the subagent refused.
3546
+ *
3547
+ * @param refusal - The refusal block from the model's reply.
3548
+ */
3549
+ function refusalNotice(refusal) {
3550
+ let notice = "The subagent stopped because a model refused the request.";
3551
+ const category = refusal.extras?.category;
3552
+ if (category) notice += ` Category: ${String(category)}.`;
3553
+ if (refusal.refusal) notice += ` Explanation: "${refusal.refusal}"`;
3554
+ return `${notice} Retrying the same request is unlikely to succeed; rephrase it or continue without it.`;
3555
+ }
3556
+ /**
3557
+ * The refusal block in `message`, if it is a message that refused.
3558
+ *
3559
+ * @param message - The message to check. Callers often take it from an
3560
+ * unchecked cast, so non-messages are treated as no refusal.
3561
+ */
3562
+ function refusalIn(message) {
3563
+ if (!BaseMessage.isInstance(message)) return void 0;
3564
+ try {
3565
+ return message.contentBlocks.find((block) => block.type === "refusal");
3566
+ } catch {
3567
+ return;
3568
+ }
3569
+ }
3570
+ /**
3571
+ * The task result for an error caused by a refusal, or `undefined` to rethrow it.
3572
+ *
3573
+ * Middleware wraps errors in `MiddlewareError`, so this walks the `cause` chain.
3574
+ *
3575
+ * @param error - The error the subagent run threw.
3576
+ */
3577
+ function refusalNoticeFor(error) {
3578
+ let current = error;
3579
+ while (current) {
3580
+ if (ModelRefusalError.isInstance(current)) return refusalNotice(refusalIn(current.rawMessage) ?? {
3581
+ type: "refusal",
3582
+ refusal: current.message
3583
+ });
3584
+ if (typeof current === "object" && "aiMessage" in current) {
3585
+ const refusal = refusalIn(current.aiMessage);
3586
+ if (refusal) return refusalNotice(refusal);
3587
+ }
3588
+ current = typeof current === "object" && "cause" in current ? current.cause : void 0;
3589
+ }
3590
+ }
3543
3591
  // src/middleware/summarization.ts
3544
3592
  /**
3545
3593
  * Summarization middleware with backend support for conversation history offloading.
@@ -4495,7 +4543,9 @@ const INVALID_TOOL_MESSAGE_BLOCK_TYPES = [
4495
4543
  function returnCommandWithStateUpdate(result, toolCallId) {
4496
4544
  const stateUpdate = filterStateForSubagent(result);
4497
4545
  let content;
4546
+ const refusal = refusalIn(result.messages?.at(-1));
4498
4547
  if (result.structuredResponse != null) content = JSON.stringify(result.structuredResponse);
4548
+ else if (refusal) content = refusalNotice(refusal);
4499
4549
  else {
4500
4550
  const messages = result.messages ?? [];
4501
4551
  content = "Task completed";
@@ -4696,18 +4746,29 @@ function createTaskTool(options) {
4696
4746
  ...config,
4697
4747
  metadata: {
4698
4748
  ...config.metadata,
4699
- lc_agent_name: subagent_type
4749
+ lc_agent_name: subagent_type,
4750
+ ...config.toolCall?.id && { lc_subagent_tool_call_id: config.toolCall.id }
4700
4751
  },
4701
4752
  configurable: {
4702
4753
  ...config.configurable,
4703
4754
  ls_agent_type: "subagent"
4704
4755
  }
4705
4756
  };
4706
- const result = await subagent.invoke(subagentState, subagentConfig);
4757
+ let result;
4758
+ try {
4759
+ result = await subagent.invoke(subagentState, subagentConfig);
4760
+ } catch (error) {
4761
+ const notice = refusalNoticeFor(error);
4762
+ if (notice === void 0) throw error;
4763
+ return notice;
4764
+ }
4707
4765
  if (!config.toolCall?.id) {
4708
4766
  if (result.structuredResponse != null) return JSON.stringify(result.structuredResponse);
4709
4767
  const messages = result.messages;
4710
- let content = (messages?.[messages.length - 1])?.content || "Task completed";
4768
+ const lastMessage = messages?.[messages.length - 1];
4769
+ const refusal = refusalIn(lastMessage);
4770
+ if (refusal) return refusalNotice(refusal);
4771
+ let content = lastMessage?.content || "Task completed";
4711
4772
  if (Array.isArray(content)) {
4712
4773
  content = content.filter((block) => !INVALID_TOOL_MESSAGE_BLOCK_TYPES.includes(block.type));
4713
4774
  if (content.length === 0) return "Task completed";
@@ -7155,7 +7216,13 @@ function finalContent(values) {
7155
7216
  }];
7156
7217
  const last = messages[messages.length - 1];
7157
7218
  try {
7158
- return coerceMessageLikeToMessage(last).contentBlocks;
7219
+ const message = coerceMessageLikeToMessage(last);
7220
+ const refusal = refusalIn(message);
7221
+ if (refusal) return [{
7222
+ type: "text",
7223
+ text: refusalNotice(refusal)
7224
+ }];
7225
+ return message.contentBlocks;
7159
7226
  } catch {
7160
7227
  return [{
7161
7228
  type: "text",
@@ -8641,7 +8708,8 @@ function createDeepAgent(params = {}) {
8641
8708
  backend,
8642
8709
  sources: memory,
8643
8710
  addCacheControl: anthropicModel
8644
- })] : []
8711
+ })] : [],
8712
+ modelRefusalMiddleware()
8645
8713
  ]);
8646
8714
  if (subagentProfile.excludedMiddleware.size > 0) subagentMiddleware = subagentMiddleware.filter((middleware) => !subagentProfile.excludedMiddleware.has(middleware.name));
8647
8715
  if (subagentProfile.excludedTools.size > 0) subagentMiddleware.push(createToolExclusionMiddleware(subagentProfile.excludedTools));
@@ -8698,7 +8766,8 @@ function createDeepAgent(params = {}) {
8698
8766
  ...skillsMiddleware,
8699
8767
  ...cacheMiddleware,
8700
8768
  ...memoryMiddleware,
8701
- ...interruptOn ? [humanInTheLoopMiddleware({ interruptOn })] : []
8769
+ ...interruptOn ? [humanInTheLoopMiddleware({ interruptOn })] : [],
8770
+ modelRefusalMiddleware()
8702
8771
  ]);
8703
8772
  if (harnessProfile.excludedMiddleware.size > 0) {
8704
8773
  const excluded = harnessProfile.excludedMiddleware;
@@ -10834,4 +10903,4 @@ var LangSmithSandbox = class LangSmithSandbox extends BaseSandbox {
10834
10903
  };
10835
10904
  export { adaptSandboxProtocol as $, filesValue as A, createFilesystemMiddleware as B, MAX_SKILL_FILE_SIZE as C, skillsMetadataValue as D, pinnedSkillsValue as E, SUBAGENT_RESPONSE_FORMAT_CONFIG_KEY as F, scrubUnsupportedMultimodalContent as G, MULTIMODAL_BLOCK_TYPES as H, createSubAgent as I, applyGrepMaxCount as J, StateBackend as K, createSubAgentMiddleware as L, DEFAULT_GENERAL_PURPOSE_DESCRIPTION as M, DEFAULT_SUBAGENT_PROMPT as N, ConfigurationError as O, GENERAL_PURPOSE_SUBAGENT as P, adaptBackendProtocol as Q, computeSummarizationDefaults as R, MAX_SKILL_DESCRIPTION_LENGTH as S, createSkillsMiddleware as T, createUnsupportedContentMiddleware as U, CompositeBackend as V, multimodalBlockSupported as W, isSandboxProtocol as X, isSandboxBackend as Y, resolveBackend as Z, createHarnessProfile as _, ASYNC_TASK_SYSTEM_PROMPT as a, setRealpath as at, isAsyncSubAgent as b, TASK_SYSTEM_PROMPT as c, registerHarnessProfile as d, checkEmptyContent as et, generalPurposeSubagentConfigSchema as f, EMPTY_HARNESS_PROFILE as g, serializeProfile as h, StoreBackend as i, performStringReplacement as it, createPatchToolCallsMiddleware as j, createMemoryMiddleware as k, createDeepAgent as l, parseHarnessProfileConfig as m, BaseSandbox as n, isTextMimeType as nt, BASE_AGENT_PROMPT as o, harnessProfileConfigSchema as p, SandboxError as q, ContextHubBackend as r, normalizeReadPagination as rt, EXECUTION_SYSTEM_PROMPT as s, LangSmithSandbox as t, getMimeType as tt, getHarnessProfile as u, REQUIRED_MIDDLEWARE_NAMES as v, MAX_SKILL_NAME_LENGTH as w, createCompletionCallbackMiddleware as x, createAsyncSubAgentMiddleware as y, createSummarizationMiddleware as z };
10836
10905
 
10837
- //# sourceMappingURL=langsmith-BCgECepG.js.map
10906
+ //# sourceMappingURL=langsmith-DfobOVRO.js.map