deepagents 1.9.1 → 1.10.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
@@ -25,30 +25,30 @@ let langchain = require("langchain");
25
25
  let _langchain_langgraph = require("@langchain/langgraph");
26
26
  let zod_v4 = require("zod/v4");
27
27
  let micromatch = require("micromatch");
28
- micromatch = __toESM(micromatch);
28
+ micromatch = __toESM(micromatch, 1);
29
29
  let path = require("path");
30
- path = __toESM(path);
30
+ path = __toESM(path, 1);
31
31
  let _langchain_core_messages = require("@langchain/core/messages");
32
32
  let zod = require("zod");
33
- zod = __toESM(zod);
33
+ zod = __toESM(zod, 1);
34
34
  let yaml = require("yaml");
35
- yaml = __toESM(yaml);
35
+ yaml = __toESM(yaml, 1);
36
36
  let _langchain_langgraph_sdk = require("@langchain/langgraph-sdk");
37
37
  let _langchain_core_errors = require("@langchain/core/errors");
38
38
  let langchain_chat_models_universal = require("langchain/chat_models/universal");
39
39
  let node_fs_promises = require("node:fs/promises");
40
- node_fs_promises = __toESM(node_fs_promises);
40
+ node_fs_promises = __toESM(node_fs_promises, 1);
41
41
  let node_fs = require("node:fs");
42
- node_fs = __toESM(node_fs);
42
+ node_fs = __toESM(node_fs, 1);
43
43
  let node_path = require("node:path");
44
- node_path = __toESM(node_path);
44
+ node_path = __toESM(node_path, 1);
45
45
  let node_child_process = require("node:child_process");
46
- node_child_process = __toESM(node_child_process);
46
+ node_child_process = __toESM(node_child_process, 1);
47
47
  let fast_glob = require("fast-glob");
48
- fast_glob = __toESM(fast_glob);
48
+ fast_glob = __toESM(fast_glob, 1);
49
49
  let langsmith_experimental_sandbox = require("langsmith/experimental/sandbox");
50
50
  let node_os = require("node:os");
51
- node_os = __toESM(node_os);
51
+ node_os = __toESM(node_os, 1);
52
52
  //#region src/backends/utils.ts
53
53
  /**
54
54
  * Shared utility functions for memory backend implementations.
@@ -2470,6 +2470,13 @@ function createPatchToolCallsMiddleware() {
2470
2470
  if (!needsPatch) return;
2471
2471
  return { messages: [new _langchain_core_messages.RemoveMessage({ id: _langchain_langgraph.REMOVE_ALL_MESSAGES }), ...patchedMessages] };
2472
2472
  },
2473
+ /**
2474
+ * Also patch in wrapModelCall as a safety net.
2475
+ * This handles edge cases where:
2476
+ * - HITL rejects a tool call during graph resume
2477
+ * - The state update from beforeAgent might not be applied in time
2478
+ * - The model would otherwise receive dangling tool_call_ids
2479
+ */
2473
2480
  wrapModelCall: async (request, handler) => {
2474
2481
  const messages = request.messages;
2475
2482
  if (!messages || messages.length === 0) return handler(request);
@@ -2571,6 +2578,10 @@ const filesValue = new _langchain_langgraph.ReducedValue(zod.z.record(zod.z.stri
2571
2578
  * State schema for memory middleware.
2572
2579
  */
2573
2580
  const MemoryStateSchema = new _langchain_langgraph.StateSchema({
2581
+ /**
2582
+ * Dict mapping source paths to their loaded content.
2583
+ * Marked as private so it's not included in the final agent state.
2584
+ */
2574
2585
  memoryContents: zod.z.record(zod.z.string(), zod.z.string()).optional(),
2575
2586
  files: filesValue
2576
2587
  });
@@ -3286,7 +3297,9 @@ const CALLBACK_THREAD_ID_KEY = "callbackThreadId";
3286
3297
  * and read by `CompletionCallbackMiddleware` when sending callback
3287
3298
  * notifications.
3288
3299
  */
3289
- const CompletionCallbackStateSchema = zod.object({ [CALLBACK_THREAD_ID_KEY]: zod.string().optional() });
3300
+ const CompletionCallbackStateSchema = zod.object({
3301
+ /** The callback thread ID. Used to address the notification. */
3302
+ [CALLBACK_THREAD_ID_KEY]: zod.string().optional() });
3290
3303
  /**
3291
3304
  * Build headers for the callback LangGraph server.
3292
3305
  *
@@ -3404,12 +3417,25 @@ function createCompletionCallbackMiddleware(options) {
3404
3417
  return (0, langchain.createMiddleware)({
3405
3418
  name: "CompletionCallbackMiddleware",
3406
3419
  stateSchema: CompletionCallbackStateSchema,
3420
+ /**
3421
+ * After-agent hook: fires when the subagent completes successfully.
3422
+ *
3423
+ * Extracts the last message as a summary and sends it to the callback
3424
+ * thread.
3425
+ */
3407
3426
  async afterAgent(state, runtime) {
3408
3427
  const callbackThreadId = state[CALLBACK_THREAD_ID_KEY];
3409
3428
  if (callbackThreadId == null) throw new Error(`Missing required state key '${CALLBACK_THREAD_ID_KEY}'`);
3410
3429
  const taskId = getTaskId(runtime);
3411
3430
  await sendNotification(callbackThreadId, formatNotification(`Completed. Result: ${extractLastMessage(state, typeof taskId === "string" ? taskId : void 0)}`, runtime));
3412
3431
  },
3432
+ /**
3433
+ * Wrap model calls to catch errors and notify the callback thread.
3434
+ *
3435
+ * If a model call raises an exception, a generic error message is
3436
+ * reported to the callback thread before re-raising. The actual error
3437
+ * details are not leaked to the callback agent.
3438
+ */
3413
3439
  async wrapModelCall(request, handler) {
3414
3440
  try {
3415
3441
  return await handler(request);
@@ -3543,15 +3569,22 @@ Summary:`;
3543
3569
  * list on subsequent calls.
3544
3570
  */
3545
3571
  const SummarizationEventSchema = zod.z.object({
3572
+ /**
3573
+ * The index in the state messages list where summarization occurred.
3574
+ * Messages before this index have been summarized. */
3546
3575
  cutoffIndex: zod.z.number(),
3576
+ /** The HumanMessage containing the summary. */
3547
3577
  summaryMessage: zod.z.instanceof(langchain.HumanMessage),
3578
+ /** Path where the conversation history was offloaded, or null if offload failed. */
3548
3579
  filePath: zod.z.string().nullable()
3549
3580
  });
3550
3581
  /**
3551
3582
  * State schema for summarization middleware.
3552
3583
  */
3553
3584
  const SummarizationStateSchema = zod.z.object({
3585
+ /** Session ID for history file naming */
3554
3586
  _summarizationSessionId: zod.z.string().optional(),
3587
+ /** Most recent summarization event (private state, not visible to agent) */
3555
3588
  _summarizationEvent: SummarizationEventSchema.optional()
3556
3589
  });
3557
3590
  /**
@@ -6661,6 +6694,271 @@ function createCacheBreakpointMiddleware() {
6661
6694
  });
6662
6695
  }
6663
6696
  //#endregion
6697
+ //#region src/stream.ts
6698
+ /**
6699
+ * Deep Agent streaming support (experimental).
6700
+ *
6701
+ * Provides:
6702
+ * - `DeepAgentRunStream` — type overlay that adds `.subagents` to the
6703
+ * `AgentRunStream` shape
6704
+ * - `createSubagentTransformer` — a `__native` transformer whose
6705
+ * projection (`subagents`) lands directly on the `GraphRunStream`
6706
+ * instance via langgraph-core's native transformer support
6707
+ *
6708
+ * See protocol proposal §15 (In-Process Streaming Interface) and §16
6709
+ * (Native Stream Transformers).
6710
+ */
6711
+ function hasPrefix(ns, prefix) {
6712
+ if (prefix.length > ns.length) return false;
6713
+ for (let i = 0; i < prefix.length; i += 1) if (ns[i] !== prefix[i]) return false;
6714
+ return true;
6715
+ }
6716
+ /**
6717
+ * Native transformer that correlates `task` tool calls into
6718
+ * {@link SubagentRunStream} objects and routes child-namespace
6719
+ * `tools` and `messages` events into per-subagent channels.
6720
+ *
6721
+ * Marked `__native: true` — the `subagents` projection key lands
6722
+ * directly on the `GraphRunStream` instance as `run.subagents`.
6723
+ */
6724
+ function createSubagentTransformer(path) {
6725
+ return () => {
6726
+ const subagentsLog = _langchain_langgraph.StreamChannel.local();
6727
+ const pendingByCallId = /* @__PURE__ */ new Map();
6728
+ const pendingByNamespaceSegment = /* @__PURE__ */ new Map();
6729
+ const latestValuesByNamespaceSegment = /* @__PURE__ */ new Map();
6730
+ const subagentsByName = /* @__PURE__ */ new Map();
6731
+ /** Maps tools-node namespace segment to subagent name. */
6732
+ const toolsNodeToName = /* @__PURE__ */ new Map();
6733
+ const childToolCalls = /* @__PURE__ */ new Map();
6734
+ /** Active ChatModelStreamImpl per subagent (keyed by subagent name). */
6735
+ const activeMessages = /* @__PURE__ */ new Map();
6736
+ function deletePendingSubagent(pending) {
6737
+ pendingByCallId.delete(pending.callId);
6738
+ for (const [segment, entry] of pendingByNamespaceSegment) if (entry === pending) {
6739
+ pendingByNamespaceSegment.delete(segment);
6740
+ latestValuesByNamespaceSegment.delete(segment);
6741
+ }
6742
+ }
6743
+ function subagentSegment(ns) {
6744
+ return ns.length === path.length + 1 ? ns[path.length] : void 0;
6745
+ }
6746
+ function getOrCreateSubagentLogs(name) {
6747
+ let logs = subagentsByName.get(name);
6748
+ if (!logs) {
6749
+ logs = {
6750
+ messagesLog: _langchain_langgraph.StreamChannel.local(),
6751
+ toolCallsLog: _langchain_langgraph.StreamChannel.local(),
6752
+ nestedSubagentsLog: _langchain_langgraph.StreamChannel.local()
6753
+ };
6754
+ subagentsByName.set(name, logs);
6755
+ }
6756
+ return logs;
6757
+ }
6758
+ return {
6759
+ __native: true,
6760
+ init: () => ({ subagents: subagentsLog }),
6761
+ process(event) {
6762
+ if (!hasPrefix(event.params.namespace, path)) return true;
6763
+ const ns = event.params.namespace;
6764
+ const depth = ns.length - path.length;
6765
+ if (depth <= 1 && event.method === "tools") {
6766
+ const data = event.params.data;
6767
+ const toolCallId = data.tool_call_id;
6768
+ const toolName = data.tool_name;
6769
+ if (toolName === "task" && data.event === "tool-started") {
6770
+ const rawInput = data.input;
6771
+ const input = typeof rawInput === "string" ? JSON.parse(rawInput) : rawInput ?? {};
6772
+ const subagentName = input.subagent_type ?? "unknown";
6773
+ const taskDescription = input.description ?? "";
6774
+ let resolveTaskInput;
6775
+ let resolveOutput;
6776
+ let rejectOutput;
6777
+ const taskInput = new Promise((res) => {
6778
+ resolveTaskInput = res;
6779
+ });
6780
+ const output = new Promise((res, rej) => {
6781
+ resolveOutput = res;
6782
+ rejectOutput = rej;
6783
+ });
6784
+ const pending = {
6785
+ name: subagentName,
6786
+ callId: toolCallId,
6787
+ resolveTaskInput,
6788
+ resolveOutput,
6789
+ rejectOutput
6790
+ };
6791
+ if (toolCallId) pendingByCallId.set(toolCallId, pending);
6792
+ resolveTaskInput(taskDescription);
6793
+ if (depth === 1) {
6794
+ toolsNodeToName.set(ns[path.length], subagentName);
6795
+ pendingByNamespaceSegment.set(ns[path.length], pending);
6796
+ }
6797
+ if (toolCallId) {
6798
+ const taskSegment = `tools:${toolCallId}`;
6799
+ toolsNodeToName.set(taskSegment, subagentName);
6800
+ pendingByNamespaceSegment.set(taskSegment, pending);
6801
+ }
6802
+ const logs = getOrCreateSubagentLogs(subagentName);
6803
+ subagentsLog.push({
6804
+ name: subagentName,
6805
+ taskInput,
6806
+ output,
6807
+ messages: logs.messagesLog,
6808
+ toolCalls: logs.toolCallsLog,
6809
+ subagents: logs.nestedSubagentsLog
6810
+ });
6811
+ }
6812
+ if (toolName === "task" && toolCallId) {
6813
+ const pending = pendingByCallId.get(toolCallId);
6814
+ if (pending) {
6815
+ if (data.event === "tool-finished") {
6816
+ pending.resolveOutput(data.output);
6817
+ deletePendingSubagent(pending);
6818
+ } else if (data.event === "tool-error") {
6819
+ const message = data.message ?? "unknown error";
6820
+ pending.rejectOutput(new Error(message));
6821
+ deletePendingSubagent(pending);
6822
+ }
6823
+ }
6824
+ }
6825
+ }
6826
+ const segment = subagentSegment(ns);
6827
+ const pending = segment ? pendingByNamespaceSegment.get(segment) : void 0;
6828
+ if (pending) {
6829
+ if (event.method === "values") latestValuesByNamespaceSegment.set(segment, event.params.data);
6830
+ else if (event.method === "lifecycle") {
6831
+ const data = event.params.data;
6832
+ if (data.event === "completed" || data.event === "interrupted") {
6833
+ pending.resolveOutput(latestValuesByNamespaceSegment.get(segment));
6834
+ deletePendingSubagent(pending);
6835
+ } else if (data.event === "failed") {
6836
+ pending.rejectOutput(/* @__PURE__ */ new Error(`Subagent ${pending.name} failed`));
6837
+ deletePendingSubagent(pending);
6838
+ }
6839
+ }
6840
+ }
6841
+ if (depth >= 2) {
6842
+ const parentSegment = ns[path.length];
6843
+ const subagentName = toolsNodeToName.get(parentSegment);
6844
+ const logs = subagentName ? subagentsByName.get(subagentName) : void 0;
6845
+ if (logs && subagentName) {
6846
+ if (event.method === "tools") {
6847
+ const data = event.params.data;
6848
+ const toolCallId = data.tool_call_id;
6849
+ const toolName = data.tool_name;
6850
+ if (data.event === "tool-started") {
6851
+ let resolveOutput;
6852
+ let rejectOutput;
6853
+ let resolveStatus;
6854
+ let resolveError;
6855
+ const output = new Promise((res, rej) => {
6856
+ resolveOutput = res;
6857
+ rejectOutput = rej;
6858
+ });
6859
+ const status = new Promise((res) => {
6860
+ resolveStatus = res;
6861
+ });
6862
+ const error = new Promise((res) => {
6863
+ resolveError = res;
6864
+ });
6865
+ childToolCalls.set(toolCallId, {
6866
+ resolveOutput,
6867
+ rejectOutput,
6868
+ resolveStatus,
6869
+ resolveError
6870
+ });
6871
+ const rawInput = data.input;
6872
+ const parsedInput = typeof rawInput === "string" ? JSON.parse(rawInput) : rawInput;
6873
+ logs.toolCallsLog.push({
6874
+ name: toolName ?? "unknown",
6875
+ callId: toolCallId,
6876
+ input: parsedInput,
6877
+ output,
6878
+ status,
6879
+ error
6880
+ });
6881
+ }
6882
+ const pending = toolCallId ? childToolCalls.get(toolCallId) : void 0;
6883
+ if (pending) {
6884
+ if (data.event === "tool-finished") {
6885
+ pending.resolveOutput(data.output);
6886
+ pending.resolveStatus("finished");
6887
+ pending.resolveError(void 0);
6888
+ childToolCalls.delete(toolCallId);
6889
+ } else if (data.event === "tool-error") {
6890
+ const message = data.message ?? "unknown error";
6891
+ pending.rejectOutput(new Error(message));
6892
+ pending.resolveStatus("error");
6893
+ pending.resolveError(message);
6894
+ childToolCalls.delete(toolCallId);
6895
+ }
6896
+ }
6897
+ }
6898
+ if (event.method === "messages") {
6899
+ const data = event.params.data;
6900
+ if (data.event === "message-start") {
6901
+ const eventsLog = _langchain_langgraph.StreamChannel.local();
6902
+ const stream = new _langchain_langgraph.ChatModelStreamImpl(eventsLog);
6903
+ eventsLog.push(data);
6904
+ activeMessages.set(subagentName, {
6905
+ stream,
6906
+ eventsLog
6907
+ });
6908
+ logs.messagesLog.push(stream);
6909
+ } else if (data.event === "message-finish") {
6910
+ const active = activeMessages.get(subagentName);
6911
+ if (active) {
6912
+ active.eventsLog.push(data);
6913
+ active.eventsLog.close();
6914
+ activeMessages.delete(subagentName);
6915
+ }
6916
+ } else activeMessages.get(subagentName)?.eventsLog.push(data);
6917
+ }
6918
+ }
6919
+ }
6920
+ return true;
6921
+ },
6922
+ finalize() {
6923
+ for (const pending of pendingByCallId.values()) pending.resolveOutput(void 0);
6924
+ pendingByCallId.clear();
6925
+ for (const pending of childToolCalls.values()) {
6926
+ pending.resolveOutput(void 0);
6927
+ pending.resolveStatus("finished");
6928
+ pending.resolveError(void 0);
6929
+ }
6930
+ childToolCalls.clear();
6931
+ for (const active of activeMessages.values()) active.eventsLog.fail(/* @__PURE__ */ new Error("run finalized before message completed"));
6932
+ activeMessages.clear();
6933
+ subagentsLog.close();
6934
+ for (const logs of subagentsByName.values()) {
6935
+ logs.toolCallsLog.close();
6936
+ logs.messagesLog.close();
6937
+ logs.nestedSubagentsLog.close();
6938
+ }
6939
+ },
6940
+ fail(err) {
6941
+ for (const pending of pendingByCallId.values()) pending.rejectOutput(err);
6942
+ pendingByCallId.clear();
6943
+ for (const pending of childToolCalls.values()) {
6944
+ pending.rejectOutput(err);
6945
+ pending.resolveStatus("error");
6946
+ pending.resolveError(err instanceof Error ? err.message : String(err));
6947
+ }
6948
+ childToolCalls.clear();
6949
+ for (const active of activeMessages.values()) active.eventsLog.fail(err);
6950
+ activeMessages.clear();
6951
+ subagentsLog.fail(err);
6952
+ for (const logs of subagentsByName.values()) {
6953
+ logs.toolCallsLog.fail(err);
6954
+ logs.messagesLog.fail(err);
6955
+ logs.nestedSubagentsLog.fail(err);
6956
+ }
6957
+ }
6958
+ };
6959
+ };
6960
+ }
6961
+ //#endregion
6664
6962
  //#region src/agent.ts
6665
6963
  const BASE_AGENT_PROMPT = langchain.context`
6666
6964
  You are a Deep Agent, an AI assistant that helps users accomplish tasks using tools. You respond with text and tool calls. The user can see your responses and tool outputs in real time.
@@ -6746,7 +7044,7 @@ function isAnthropicModel(model) {
6746
7044
  * ```
6747
7045
  */
6748
7046
  function createDeepAgent(params = {}) {
6749
- const { model = "anthropic:claude-sonnet-4-6", tools = [], systemPrompt, middleware: customMiddleware = [], subagents = [], responseFormat, contextSchema, checkpointer, store, backend = (config) => new StateBackend(config), interruptOn, name, memory, skills, permissions = [] } = params;
7047
+ const { model = "anthropic:claude-sonnet-4-6", tools = [], systemPrompt, middleware: customMiddleware = [], subagents = [], responseFormat, contextSchema, checkpointer, store, backend = (config) => new StateBackend(config), interruptOn, name, memory, skills, permissions = [], streamTransformers = [] } = params;
6750
7048
  const collidingTools = tools.map((t) => t.name).filter((n) => typeof n === "string" && BUILTIN_TOOL_NAMES.has(n));
6751
7049
  if (collidingTools.length > 0) throw new ConfigurationError(`Tool name(s) [${collidingTools.join(", ")}] conflict with built-in tools. Rename your custom tools to avoid this.`, "TOOL_NAME_COLLISION");
6752
7050
  const anthropicModel = isAnthropicModel(model);
@@ -6841,6 +7139,7 @@ function createDeepAgent(params = {}) {
6841
7139
  * - Middleware: AllMiddleware (built-in + custom + subagent middleware for state inference)
6842
7140
  * - Tools: TTools
6843
7141
  * - Subagents: TSubagents (for type-safe streaming)
7142
+ * - StreamTransformers: TStreamTransformers
6844
7143
  */
6845
7144
  return (0, langchain.createAgent)({
6846
7145
  model,
@@ -6863,7 +7162,8 @@ function createDeepAgent(params = {}) {
6863
7162
  contextSchema,
6864
7163
  checkpointer,
6865
7164
  store,
6866
- name
7165
+ name,
7166
+ streamTransformers: [createSubagentTransformer([]), ...streamTransformers]
6867
7167
  }).withConfig({
6868
7168
  recursionLimit: 1e4,
6869
7169
  metadata: {
@@ -7003,7 +7303,9 @@ function createSettings(options = {}) {
7003
7303
  * State schema for agent memory middleware.
7004
7304
  */
7005
7305
  const AgentMemoryStateSchema = zod.z.object({
7306
+ /** Personal preferences from ~/.deepagents/{agent}/ (applies everywhere) */
7006
7307
  userMemory: zod.z.string().optional(),
7308
+ /** Project-specific context (loaded from project root) */
7007
7309
  projectMemory: zod.z.string().optional()
7008
7310
  });
7009
7311
  /**
@@ -7412,6 +7714,7 @@ exports.createPatchToolCallsMiddleware = createPatchToolCallsMiddleware;
7412
7714
  exports.createSettings = createSettings;
7413
7715
  exports.createSkillsMiddleware = createSkillsMiddleware;
7414
7716
  exports.createSubAgentMiddleware = createSubAgentMiddleware;
7717
+ exports.createSubagentTransformer = createSubagentTransformer;
7415
7718
  exports.createSummarizationMiddleware = createSummarizationMiddleware;
7416
7719
  exports.filesValue = filesValue;
7417
7720
  exports.findProjectRoot = findProjectRoot;