deepagents 1.15.1 → 1.16.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.
@@ -1,10 +1,10 @@
1
1
  import { AIMessage, HumanMessage, SystemMessage, ToolMessage, anthropicPromptCachingMiddleware, bedrockPromptCachingMiddleware, context, countTokensApproximately, createAgent, createMiddleware, humanInTheLoopMiddleware, todoListMiddleware, tool } from "langchain";
2
2
  import { ContextOverflowError } from "@langchain/core/errors";
3
- import { Command, Overwrite, REMOVE_ALL_MESSAGES, ReducedValue, StateSchema, getConfig, getCurrentTaskInput, getStore, isCommand } from "@langchain/langgraph";
3
+ import { Command, Overwrite, REMOVE_ALL_MESSAGES, ReducedValue, StateSchema, getConfig, getCurrentTaskInput, getStore, isCommand, isGraphBubbleUp } from "@langchain/langgraph";
4
4
  import { z } from "zod/v4";
5
5
  import micromatch from "micromatch";
6
6
  import { createHash } from "node:crypto";
7
- import { AIMessage as AIMessage$1, HumanMessage as HumanMessage$1, RemoveMessage, SystemMessage as SystemMessage$1, ToolMessage as ToolMessage$1, getBufferString } from "@langchain/core/messages";
7
+ import { AIMessage as AIMessage$1, BaseMessage, HumanMessage as HumanMessage$1, RemoveMessage, SystemMessage as SystemMessage$1, ToolMessage as ToolMessage$1, coerceMessageLikeToMessage, getBufferString } from "@langchain/core/messages";
8
8
  import * as z$2 from "zod";
9
9
  import { z as z$1 } from "zod";
10
10
  import { initChatModel } from "langchain/chat_models/universal";
@@ -16,6 +16,7 @@ import { convertToOpenAIFunction } from "@langchain/core/utils/function_calling"
16
16
  import { toJsonSchema } from "@langchain/core/utils/json_schema";
17
17
  import { isInteropZodSchema } from "@langchain/core/utils/types";
18
18
  import { Client } from "@langchain/langgraph-sdk";
19
+ import { getCurrentRunTree } from "langsmith/traceable";
19
20
  import { Client as Client$1 } from "langsmith";
20
21
  import { LangSmithResourceNotFoundError, LangSmithSandboxError, SandboxClient } from "langsmith/experimental/sandbox";
21
22
  //#region src/backends/realpath.ts
@@ -1444,6 +1445,14 @@ async function hydrateMessages(messages, backend, prefix, cache) {
1444
1445
  }
1445
1446
  return restorePayloads(messages, payloads);
1446
1447
  }
1448
+ /**
1449
+ * Replace each blob reference in `messages` with a notice that the content is
1450
+ * unavailable, for an agent that can't load blobs, so the model still accepts
1451
+ * the request.
1452
+ */
1453
+ function withoutBlobRefs(messages) {
1454
+ return messages.some(messageHasRefs) ? restorePayloads(messages, /* @__PURE__ */ new Map()) : messages;
1455
+ }
1447
1456
  //#endregion
1448
1457
  //#region src/middleware/unsupportedContent.ts
1449
1458
  const PDF_MIME_TYPE = "application/pdf";
@@ -3372,7 +3381,7 @@ function createFilesystemMiddleware(options = {}) {
3372
3381
  pending: []
3373
3382
  }, resolvedBackend, BLOBS_PREFIX, blobCache);
3374
3383
  messages = await hydrateMessages(messages, resolvedBackend, BLOBS_PREFIX, blobCache);
3375
- }
3384
+ } else if (messages) messages = withoutBlobRefs(messages);
3376
3385
  const finalRequest = {
3377
3386
  ...request,
3378
3387
  tools,
@@ -6239,6 +6248,9 @@ function createSkillsMiddleware(options) {
6239
6248
  *
6240
6249
  * @experimental - this middleware is experimental and may change in future releases.
6241
6250
  *
6251
+ * @deprecated `createDeepAgent` now notifies the launching agent on its own;
6252
+ * adding this middleware too sends the parent two notifications per task.
6253
+ *
6242
6254
  * This middleware sends a notification to a callback thread when a subagent
6243
6255
  * completes successfully or raises an error. The callback agent can then
6244
6256
  * process that notification instead of relying only on polling via
@@ -6347,7 +6359,7 @@ function resolveHeaders(headers) {
6347
6359
  * @param message - The message content to send.
6348
6360
  * @param options - Optional url and headers for the callback server.
6349
6361
  */
6350
- async function notifyParent(callbackGraphId, callbackThreadId, message, options) {
6362
+ async function notifyParent$1(callbackGraphId, callbackThreadId, message, options) {
6351
6363
  try {
6352
6364
  await new Client({
6353
6365
  apiUrl: options?.url ?? void 0,
@@ -6398,6 +6410,9 @@ function extractLastMessage(state, taskId) {
6398
6410
  * If `callbackThreadId` is not present in state, the middleware does
6399
6411
  * nothing.
6400
6412
  *
6413
+ * @deprecated `createDeepAgent` now notifies the launching agent on its own;
6414
+ * adding this middleware too sends the parent two notifications per task.
6415
+ *
6401
6416
  * @param options - Configuration options.
6402
6417
  * @returns An `AgentMiddleware` instance.
6403
6418
  *
@@ -6421,7 +6436,7 @@ function createCompletionCallbackMiddleware(options) {
6421
6436
  * Send a notification to the callback destination.
6422
6437
  */
6423
6438
  async function sendNotification(callbackThreadId, message) {
6424
- await notifyParent(callbackGraphId, callbackThreadId, message, {
6439
+ await notifyParent$1(callbackGraphId, callbackThreadId, message, {
6425
6440
  url,
6426
6441
  headers
6427
6442
  });
@@ -6491,6 +6506,7 @@ const AsyncTaskSchema = z.object({
6491
6506
  agentName: z.string(),
6492
6507
  threadId: z.string(),
6493
6508
  runId: z.string(),
6509
+ supersededRunIds: z.array(z.string()).optional(),
6494
6510
  status: z.string(),
6495
6511
  createdAt: z.string(),
6496
6512
  description: z.string().optional(),
@@ -6538,16 +6554,11 @@ Available async agent types:
6538
6554
 
6539
6555
  ## Usage notes:
6540
6556
  1. This tool launches a background task and returns immediately with a task ID. Report the task ID to the user and stop — do NOT immediately check status.
6541
- 2. Use \`check_async_task\` only when the user asks for a status update or result.
6557
+ 2. You'll usually be told when a task finishes, fails or needs input, so don't check just to see if it's done; use \`check_async_task\` when the user asks or a notification says to.
6542
6558
  3. Use \`update_async_task\` to send new instructions to a running task.
6543
6559
  4. Multiple async subagents can run concurrently — launch several and let them run in the background.
6544
- 5. The subagent runs on a remote server, so it has its own tools and capabilities.`;
6545
- /**
6546
- * Task statuses that will never change.
6547
- *
6548
- * When listing tasks, live-status fetches are skipped for tasks whose
6549
- * cached status is in this set, since they are guaranteed to be final.
6550
- */
6560
+ 5. The subagent runs on a remote server, so it has its own tools and capabilities.
6561
+ 6. A task with status \`waiting\` is waiting for a human (an approval or an answer). The user answers it directly; you can't answer or approve it for them. Keep working, and tell the user it's waiting if they ask.`;
6551
6562
  /**
6552
6563
  * Names of the tools added by the async subagent middleware.
6553
6564
  *
@@ -6561,6 +6572,7 @@ const ASYNC_TASK_TOOL_NAMES = [
6561
6572
  "cancel_async_task",
6562
6573
  "list_async_tasks"
6563
6574
  ];
6575
+ /** Task statuses that never change, so live-status fetches can be skipped; `waiting` can still resume. */
6564
6576
  const TERMINAL_STATUSES = /* @__PURE__ */ new Set([
6565
6577
  "cancelled",
6566
6578
  "success",
@@ -6580,32 +6592,141 @@ function resolveTrackedTask(taskId, state) {
6580
6592
  if (!tracked) return `No tracked task found for taskId: '${taskId}'`;
6581
6593
  return tracked;
6582
6594
  }
6595
+ /** Guidance for a task whose latest run hasn't started. */
6596
+ const PENDING_NOTE = "The latest run hasn't started yet. If it is a queued follow-up, an earlier run may still be working.";
6597
+ /** Task status implied by the thread when the tracked run finished but the thread moved on. */
6598
+ const THREAD_TO_TASK_STATUS = {
6599
+ interrupted: "waiting",
6600
+ busy: "running",
6601
+ error: "error"
6602
+ };
6603
+ /**
6604
+ * Return a task's status from its latest run, reading the thread to spot pauses.
6605
+ *
6606
+ * A run that hits `interrupt()` ends as `success`; only its thread shows the pause.
6607
+ * A run cancelled on the server ends `interrupted`, which a task reports as `cancelled`.
6608
+ */
6609
+ function taskStatus(run, thread) {
6610
+ if (run.status === "interrupted") return "cancelled";
6611
+ if (run.status !== "success" || thread === null) return run.status;
6612
+ return THREAD_TO_TASK_STATUS[thread.status] ?? "success";
6613
+ }
6614
+ /** Whether a newer run exists than the tracked one, e.g. after a resume from another client. */
6615
+ function needsLatestRun(run, thread) {
6616
+ return run.status === "success" && thread !== null && (thread.status === "busy" || thread.status === "error");
6617
+ }
6583
6618
  /**
6584
- * Build a check result from a run's current status and thread state values.
6619
+ * Fetch a task's latest run and, when that run finished, its thread (else `null`).
6585
6620
  *
6586
- * For successful runs, extracts the last message's content from the remote
6587
- * thread's state values. For errored runs, includes a generic error message.
6621
+ * Throws if the thread can't be read, since a paused run also ends as `success`.
6622
+ * A run replaced by another client's run hands over to the newest one, except for
6623
+ * a task the parent cancelled.
6624
+ */
6625
+ async function observeTaskRun(client, task, signal) {
6626
+ let run = await client.runs.get(task.threadId, task.runId, { signal });
6627
+ if (run.status === "interrupted" && task.status !== "cancelled") {
6628
+ const [latest] = await client.runs.list(task.threadId, {
6629
+ limit: 1,
6630
+ signal
6631
+ });
6632
+ run = latest ?? run;
6633
+ }
6634
+ if (run.status !== "success") return [run, null];
6635
+ const thread = await client.threads.get(task.threadId, { signal });
6636
+ if (needsLatestRun(run, thread)) {
6637
+ const [latest] = await client.runs.list(task.threadId, {
6638
+ limit: 1,
6639
+ signal
6640
+ });
6641
+ run = latest ?? run;
6642
+ }
6643
+ return [run, thread];
6644
+ }
6645
+ /** Flatten a thread's pending interrupts, including ones raised inside subgraphs. */
6646
+ function pendingInterrupts(thread) {
6647
+ if (!thread?.interrupts) return [];
6648
+ return Object.values(thread.interrupts).flat();
6649
+ }
6650
+ const WAITING_NOTE = "The subagent is waiting for a human. The user answers it directly; you can't answer or approve it. Keep working; check again later for its result.";
6651
+ /** The thread's messages, if its values hold any. */
6652
+ function threadMessages(values) {
6653
+ if (values === null || typeof values !== "object" || Array.isArray(values)) return [];
6654
+ const messages = values.messages;
6655
+ return Array.isArray(messages) ? messages : [];
6656
+ }
6657
+ /** A thread message's content as text, whatever shape the server sent it in. */
6658
+ function messageText(message) {
6659
+ if (BaseMessage.isInstance(message)) return message.text;
6660
+ const content = typeof message === "object" && message !== null && "content" in message ? message.content : message;
6661
+ return typeof content === "string" ? content : JSON.stringify(content);
6662
+ }
6663
+ /**
6664
+ * Build a check result from a task's latest run and its thread.
6588
6665
  *
6589
- * @param run - The run object from the SDK.
6590
- * @param threadId - The thread ID for the run.
6591
- * @param threadValues - The `values` from `ThreadState` (the remote subagent's state).
6666
+ * @param run - The task's latest run.
6667
+ * @param threadId - The task's thread ID.
6668
+ * @param thread - The task's thread, when its run finished.
6592
6669
  */
6593
- function buildCheckResult(run, threadId, threadValues) {
6670
+ function buildCheckResult(run, threadId, thread) {
6671
+ const status = taskStatus(run, thread);
6594
6672
  const checkResult = {
6595
- status: run.status,
6673
+ status,
6596
6674
  threadId
6597
6675
  };
6598
- if (run.status === "success") {
6599
- const messages = (Array.isArray(threadValues) ? {} : threadValues)?.messages ?? [];
6600
- if (messages.length > 0) {
6601
- const last = messages[messages.length - 1];
6602
- const rawContent = typeof last === "object" && last !== null && "content" in last ? last.content : last;
6603
- checkResult.result = typeof rawContent === "string" ? rawContent : JSON.stringify(rawContent);
6604
- } else checkResult.result = "Completed with no output messages.";
6605
- } else if (run.status === "error") checkResult.error = "The async subagent encountered an error.";
6676
+ if (status === "pending") checkResult.note = PENDING_NOTE;
6677
+ else if (status === "success") checkResult.result = finalContent(thread?.values);
6678
+ else if (status === "error") checkResult.error = "The async subagent encountered an error.";
6679
+ else if (status === "waiting") {
6680
+ checkResult.interrupts = pendingInterrupts(thread).map((item) => ({
6681
+ id: item.id ?? "",
6682
+ value: item.value
6683
+ }));
6684
+ checkResult.note = WAITING_NOTE;
6685
+ }
6606
6686
  return checkResult;
6607
6687
  }
6608
6688
  /**
6689
+ * A check result as tool output: JSON, with a text-only answer's text in `result`.
6690
+ *
6691
+ * An answer with media follows the JSON as its own blocks, in order. Reasoning and
6692
+ * tool-call blocks are dropped; the text isn't cut.
6693
+ */
6694
+ function checkOutput(result) {
6695
+ const blocks = result.result;
6696
+ if (!blocks) return JSON.stringify(result);
6697
+ const text = (block) => String(block.text);
6698
+ if (!blocks.some((block) => MEDIA_BLOCK_TYPES.has(block.type))) {
6699
+ const answer = blocks.filter((block) => block.type === "text").map(text);
6700
+ return JSON.stringify({
6701
+ ...result,
6702
+ result: answer.join("")
6703
+ });
6704
+ }
6705
+ const { result: _answer, ...status } = result;
6706
+ const answer = blocks.filter((block) => block.type === "text" || MEDIA_BLOCK_TYPES.has(block.type)).map((block) => block.type === "text" ? textBlock(text(block)) : { ...block });
6707
+ return [textBlock(JSON.stringify(status)), ...answer];
6708
+ }
6709
+ /** Keep a task cancelled while paused as cancelled; its thread still shows the old pause. */
6710
+ function keepCancelled(task, result) {
6711
+ if (task.status === "cancelled" && result.status === "waiting") return {
6712
+ status: "cancelled",
6713
+ threadId: result.threadId
6714
+ };
6715
+ return result;
6716
+ }
6717
+ /** `task` updated to what a check found. */
6718
+ function observed(task, status, runId) {
6719
+ const now = (/* @__PURE__ */ new Date()).toISOString();
6720
+ const changed = status !== task.status || runId !== task.runId;
6721
+ return {
6722
+ ...task,
6723
+ runId,
6724
+ status,
6725
+ updatedAt: changed ? now : task.updatedAt,
6726
+ checkedAt: now
6727
+ };
6728
+ }
6729
+ /**
6609
6730
  * Filter tasks by cached status from agent state.
6610
6731
  *
6611
6732
  * Filtering uses the cached status, not live server status. Live statuses
@@ -6620,17 +6741,17 @@ function filterTasks(tasks, statusFilter) {
6620
6741
  return Object.values(tasks).filter((task) => task.status === statusFilter);
6621
6742
  }
6622
6743
  /**
6623
- * Fetch the current run status from the server.
6744
+ * Fetch a task's current status and run ID.
6624
6745
  *
6625
- * Returns the cached status immediately for terminal tasks (avoiding
6626
- * unnecessary API calls). Falls back to the cached status on SDK errors.
6746
+ * Returns the cached values for terminal tasks and on SDK errors.
6627
6747
  */
6628
6748
  async function fetchLiveTaskStatus(clients, task) {
6629
- if (TERMINAL_STATUSES.has(task.status)) return task.status;
6749
+ if (TERMINAL_STATUSES.has(task.status)) return [task.status, task.runId];
6630
6750
  try {
6631
- return (await clients.getClient(task.agentName).runs.get(task.threadId, task.runId)).status;
6751
+ const [run, thread] = await observeTaskRun(clients.getClient(task.agentName), task);
6752
+ return [taskStatus(run, thread), run.run_id];
6632
6753
  } catch {
6633
- return task.status;
6754
+ return [task.status, task.runId];
6634
6755
  }
6635
6756
  }
6636
6757
  /**
@@ -6673,9 +6794,18 @@ var ClientCache = class {
6673
6794
  }
6674
6795
  /**
6675
6796
  * Get or create a `Client` for the named agent.
6797
+ *
6798
+ * With `extraHeaders` (such as one launch's trace headers), returns a new, uncached client.
6676
6799
  */
6677
- getClient(name) {
6800
+ getClient(name, extraHeaders = {}) {
6678
6801
  const spec = this.agents[name];
6802
+ if (Object.keys(extraHeaders).length > 0) return new Client({
6803
+ apiUrl: spec.url,
6804
+ defaultHeaders: {
6805
+ ...this.resolveHeaders(spec),
6806
+ ...extraHeaders
6807
+ }
6808
+ });
6679
6809
  const key = this.cacheKey(spec);
6680
6810
  const existing = this.clients.get(key);
6681
6811
  if (existing) return existing;
@@ -6689,6 +6819,318 @@ var ClientCache = class {
6689
6819
  }
6690
6820
  };
6691
6821
  /**
6822
+ * Baggage metadata key (JSON `true`) marking trace headers as a parent to nest under.
6823
+ *
6824
+ * Receivers that adopt the trace check for it, so keep the name stable.
6825
+ */
6826
+ const NEST_UNDER_PARENT = "ls_nest_under_parent";
6827
+ /**
6828
+ * Build LangSmith headers pointing at the current span, or `{}` when tracing is off.
6829
+ *
6830
+ * Only sent to subagents on this deployment (no `url`). The baggage carries the
6831
+ * project and `NEST_UNDER_PARENT`, not the caller's run metadata. Any `baggage`
6832
+ * in the spec's headers is kept.
6833
+ */
6834
+ function traceHeaders(spec) {
6835
+ if (spec.url) return {};
6836
+ const runTree = getCurrentRunTree(true);
6837
+ if (!runTree?.tracingEnabled || !runTree.trace_id || !runTree.dotted_order) return {};
6838
+ const baggage = Object.entries(spec.headers ?? {}).filter(([key, value]) => key.toLowerCase() === "baggage" && value).map(([, value]) => value);
6839
+ baggage.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify({ [NEST_UNDER_PARENT]: true }))}`);
6840
+ if (runTree.project_name) baggage.push(`langsmith-project=${encodeURIComponent(runTree.project_name)}`);
6841
+ return {
6842
+ "langsmith-trace": runTree.dotted_order,
6843
+ baggage: baggage.join(",")
6844
+ };
6845
+ }
6846
+ /**
6847
+ * `configurable` key carrying the launching agent's reference to an async subagent's run.
6848
+ *
6849
+ * Apps read it directly, and Python deep agents use the same key, so keep the key and shape stable.
6850
+ */
6851
+ const PARENT_KEY = "deepagents_parent";
6852
+ /** Describe the running agent so the async subagent it launches can find it. */
6853
+ function parentReference(config) {
6854
+ const reference = {};
6855
+ const configurable = config?.configurable ?? {};
6856
+ const metadata = config?.metadata ?? {};
6857
+ if (configurable.thread_id) reference.thread_id = String(configurable.thread_id);
6858
+ const assistantId = metadata.assistant_id || configurable.assistant_id;
6859
+ if (assistantId) reference.assistant_id = String(assistantId);
6860
+ return reference;
6861
+ }
6862
+ /**
6863
+ * The parent reference sent to `spec`'s runs.
6864
+ *
6865
+ * A subagent on another server (`url`) or with `notifyParent: false` gets only the
6866
+ * parent's thread: the assistant is for waking the parent, which it can't do.
6867
+ */
6868
+ function referenceFor(spec, config) {
6869
+ const { thread_id, assistant_id } = parentReference(config);
6870
+ const wakesParent = !spec.url && spec.notifyParent !== false;
6871
+ return {
6872
+ ...thread_id && { thread_id },
6873
+ ...wakesParent && assistant_id && { assistant_id }
6874
+ };
6875
+ }
6876
+ /**
6877
+ * Metadata for a task's thread, so apps can find a parent's subagent threads with `threads.search`.
6878
+ *
6879
+ * It names the subagent as the parent knows it, and for subagents on this deployment
6880
+ * keeps the parent's assistant, so other runs on the thread (such as the user
6881
+ * answering the subagent) can still notify the parent.
6882
+ */
6883
+ function threadMetadata(spec, config) {
6884
+ const reference = referenceFor(spec, config);
6885
+ const metadata = { subagent_name: spec.name };
6886
+ if (reference.thread_id) metadata.parent_thread_id = reference.thread_id;
6887
+ if (reference.assistant_id) metadata.parent_assistant_id = reference.assistant_id;
6888
+ return metadata;
6889
+ }
6890
+ const ASYNC_FORK_TASK_PREAMBLE = "[The messages above are prior conversation inherited from the parent agent. You are the background subagent it has already invoked. Use the established context to complete the task below, not to repeat the prior delegation. You have your own tools and runtime; the parent's resources may not be available.]\n\n";
6891
+ /** A message as portable input for another run, without parent-local eviction tags. */
6892
+ function serializeForkMessage(message) {
6893
+ const { lc_evicted_to: _evicted, ...additionalKwargs } = message.additional_kwargs ?? {};
6894
+ const serialized = {
6895
+ type: message.type,
6896
+ content: message.content,
6897
+ additional_kwargs: additionalKwargs
6898
+ };
6899
+ if (message.id) serialized.id = message.id;
6900
+ if (message.name) serialized.name = message.name;
6901
+ if (AIMessage$1.isInstance(message)) serialized.tool_calls = message.tool_calls;
6902
+ if (ToolMessage$1.isInstance(message)) {
6903
+ serialized.tool_call_id = message.tool_call_id;
6904
+ serialized.status = message.status;
6905
+ }
6906
+ return serialized;
6907
+ }
6908
+ /**
6909
+ * The task's input messages: the parent's effective conversation for forks, or only the task.
6910
+ *
6911
+ * A fork keeps references to the parent's offloaded media; a subagent sharing the
6912
+ * parent's backend loads them, and any other sees that the content is unavailable.
6913
+ */
6914
+ function startTaskMessages(spec, state, description) {
6915
+ if (spec.mode !== "fork") return [{
6916
+ role: "user",
6917
+ content: description
6918
+ }];
6919
+ return [...getEffectiveMessages(stripInFlightAIMessage(state.messages ?? []), state), new HumanMessage$1({ content: ASYNC_FORK_TASK_PREAMBLE + description })].map(serializeForkMessage);
6920
+ }
6921
+ /** Describe a subagent's context inheritance without promising shared tools. */
6922
+ function describeAsyncSubAgent(spec) {
6923
+ const suffix = spec.mode === "fork" ? " (inherits your conversation at launch; uses its own system prompt and tools)" : "";
6924
+ return `- ${spec.name}: ${spec.description}${suffix}`;
6925
+ }
6926
+ /**
6927
+ * The `runs.create` options that link a run to this agent and set the subagent's webhook.
6928
+ *
6929
+ * A subagent on this deployment runs with this agent's context. The Agent Server
6930
+ * takes `context` or `configurable`, not both, so the parent reference then goes
6931
+ * through the thread's metadata.
6932
+ */
6933
+ function runOptions(spec, runtime) {
6934
+ const webhook = spec.webhook ? { webhook: spec.webhook } : {};
6935
+ const context = spec.url ? void 0 : forwardedContext(runtime.context);
6936
+ if (context) return {
6937
+ ...webhook,
6938
+ context
6939
+ };
6940
+ const reference = referenceFor(spec, runtime.config);
6941
+ return Object.keys(reference).length > 0 ? {
6942
+ ...webhook,
6943
+ config: { configurable: { [PARENT_KEY]: reference } }
6944
+ } : webhook;
6945
+ }
6946
+ /** A run context as JSON data for another run, without deepagents' parent reference. */
6947
+ function forwardedContext(context) {
6948
+ if (!context || typeof context !== "object" || Array.isArray(context)) return;
6949
+ const entries = Object.entries(context).filter(([key]) => key !== PARENT_KEY);
6950
+ return entries.length > 0 ? Object.fromEntries(entries) : void 0;
6951
+ }
6952
+ /**
6953
+ * The agent that launched this run's task, or `null` if no async subagent tool did.
6954
+ *
6955
+ * Read from the run's config, or else from the task thread's metadata, which the
6956
+ * Agent Server copies into every run on the thread (such as the user's answer).
6957
+ */
6958
+ function launchingAgent(config) {
6959
+ const reference = (config?.configurable ?? {})[PARENT_KEY];
6960
+ if (reference && typeof reference === "object" && !Array.isArray(reference)) return reference;
6961
+ const metadata = config?.metadata ?? {};
6962
+ if (!metadata.parent_thread_id) return null;
6963
+ const fallback = { thread_id: String(metadata.parent_thread_id) };
6964
+ if (metadata.parent_assistant_id) fallback.assistant_id = String(metadata.parent_assistant_id);
6965
+ return fallback;
6966
+ }
6967
+ /** Message field (`additional_kwargs` key) marking a task notification and carrying its {@link TaskEvent}. */
6968
+ const NOTIFICATION_KEY = "deepagents_notification";
6969
+ /** Results longer than this are cut in notifications, matching the limit for large tool results. */
6970
+ const MAX_RESULT_CHARS = 8e4;
6971
+ const NEXT_STEP = {
6972
+ success: "Use the result to continue; report back to the user if they're waiting on it.",
6973
+ error: "Use `check_async_task` for details, then decide whether to retry, try another approach, or tell the user.",
6974
+ timeout: "The task ran too long and was stopped. Decide whether to retry with a smaller task, or tell the user.",
6975
+ cancelled: "The task's run was cancelled before it finished, outside your tools. Decide whether to start it again, or tell the user.",
6976
+ waiting: "The subagent is waiting for the user, who answers it on the subagent's own thread; you can't answer or approve it. Keep working."
6977
+ };
6978
+ function textBlock(text) {
6979
+ return {
6980
+ type: "text",
6981
+ text
6982
+ };
6983
+ }
6984
+ /** Escape subagent-controlled text so it can't close the notification's tags and pose as the system. */
6985
+ function escape(text) {
6986
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
6987
+ }
6988
+ function clip(text) {
6989
+ if (text.length <= MAX_RESULT_CHARS) return text;
6990
+ return `${text.slice(0, MAX_RESULT_CHARS)}\n... [cut off; use \`check_async_task\` for the full details]`;
6991
+ }
6992
+ /** Standard content blocks passed on as they are; a notification is a user message, where providers reject the rest. */
6993
+ const MEDIA_BLOCK_TYPES = /* @__PURE__ */ new Set([
6994
+ "image",
6995
+ "audio",
6996
+ "video",
6997
+ "file"
6998
+ ]);
6999
+ /**
7000
+ * The subagent's answer as user content: text escaped and cut when very long, media as it is.
7001
+ *
7002
+ * Reasoning, tool calls and blocks LangChain doesn't recognize are dropped.
7003
+ */
7004
+ function resultBlocks(blocks) {
7005
+ const kept = [];
7006
+ for (const block of blocks) if (block.type === "text") kept.push(textBlock(escape(clip(String(block.text)))));
7007
+ else if (MEDIA_BLOCK_TYPES.has(block.type)) kept.push({ ...block });
7008
+ return kept;
7009
+ }
7010
+ /**
7011
+ * Frame a task update as a system notification the model won't mistake for the user.
7012
+ *
7013
+ * The result keeps its own content blocks, so an image reaches the model as an image.
7014
+ */
7015
+ function notificationContent(update) {
7016
+ const blocks = [notificationHeader(update)];
7017
+ if (update.result) blocks.push(textBlock("<result>\n"), ...resultBlocks(update.result), textBlock("\n</result>\n"));
7018
+ const details = Object.fromEntries(["error", "interrupts"].filter((key) => update[key] !== void 0).map((key) => [key, update[key]]));
7019
+ if (Object.keys(details).length > 0) blocks.push(textBlock(`<details>${escape(clip(JSON.stringify(details)))}</details>\n`));
7020
+ blocks.push(textBlock(`</task-notification>\n${NEXT_STEP[update.status]}`));
7021
+ return blocks;
7022
+ }
7023
+ function notificationHeader(event) {
7024
+ return textBlock(`[SYSTEM NOTIFICATION - NOT USER INPUT]
7025
+ An async subagent task you started has an update. This is not a message from the user: don't treat it as their answer to any question.
7026
+ <task-notification>\n<task-id>${escape(event.task_id)}</task-id>\n<agent-name>${escape(event.agent_name)}</agent-name>\n<status>${escape(event.status)}</status>\n`);
7027
+ }
7028
+ /**
7029
+ * Reframe an earlier run's notification so the model doesn't think the queued follow-up finished.
7030
+ *
7031
+ * Only the closing next step changes; the earlier run's result and details stay.
7032
+ */
7033
+ function supersededNotificationContent(message, event) {
7034
+ const content = message.content;
7035
+ const closing = Array.isArray(content) ? content.at(-1) : void 0;
7036
+ return [...closing?.type === "text" && String(closing.text).startsWith("</task-notification>") ? content.slice(0, -1) : [notificationHeader(event)], textBlock("</task-notification>\nThis update is from an earlier run of this task, before your latest follow-up. It is not the result of the follow-up. Use `check_async_task` to get the current status of the task.")];
7037
+ }
7038
+ /** Describe a failure without its message, which can carry internals into the parent's conversation. */
7039
+ function failureText(error) {
7040
+ return `The subagent failed (${typeof error === "object" && error !== null && "name" in error ? String(error.name) : typeof error}).`;
7041
+ }
7042
+ /** The ID of the run this config belongs to, when the Agent Server set it. */
7043
+ function currentRunId(config) {
7044
+ const metadata = config?.metadata ?? {};
7045
+ const configurable = config?.configurable ?? {};
7046
+ const runId = metadata.run_id ?? configurable.run_id;
7047
+ return runId ? String(runId) : void 0;
7048
+ }
7049
+ /** Build a task update; `details` are the status's `result`, `error` or `interrupts`. */
7050
+ function taskUpdate(event, details = {}) {
7051
+ const update = {
7052
+ task_id: event.task_id,
7053
+ agent_name: event.agent_name,
7054
+ status: event.status,
7055
+ ...details
7056
+ };
7057
+ if (event.run_id) update.run_id = event.run_id;
7058
+ return update;
7059
+ }
7060
+ /** Describe how this run's task ended. */
7061
+ function taskEvent(config, agentName, status, details = {}) {
7062
+ const configurable = config?.configurable ?? {};
7063
+ return taskUpdate({
7064
+ task_id: String(configurable.thread_id ?? ""),
7065
+ agent_name: agentName,
7066
+ status,
7067
+ run_id: currentRunId(config)
7068
+ }, details);
7069
+ }
7070
+ /** The subagent's last message as standard content blocks, the task's result; it may hold images. */
7071
+ function finalContent(values) {
7072
+ const messages = threadMessages(values);
7073
+ if (messages.length === 0) return [{
7074
+ type: "text",
7075
+ text: "(completed with no output messages)"
7076
+ }];
7077
+ const last = messages[messages.length - 1];
7078
+ try {
7079
+ return coerceMessageLikeToMessage(last).contentBlocks;
7080
+ } catch {
7081
+ return [{
7082
+ type: "text",
7083
+ text: messageText(last)
7084
+ }];
7085
+ }
7086
+ }
7087
+ /** The task event a notification message carries, or `null` for any other message. */
7088
+ function notificationEvent(message) {
7089
+ const event = message?.additional_kwargs?.[NOTIFICATION_KEY];
7090
+ return event && typeof event === "object" && !Array.isArray(event) ? event : null;
7091
+ }
7092
+ /** A task update as the message the parent's model sees, marked with its {@link TaskEvent} so apps can recognize it. */
7093
+ function notificationMessage(update) {
7094
+ const event = {
7095
+ task_id: update.task_id,
7096
+ agent_name: update.agent_name,
7097
+ status: update.status
7098
+ };
7099
+ if (update.run_id) event.run_id = update.run_id;
7100
+ return {
7101
+ role: "user",
7102
+ content: notificationContent(update),
7103
+ additional_kwargs: { [NOTIFICATION_KEY]: event }
7104
+ };
7105
+ }
7106
+ /** Parent thread statuses a notification run can start on: neither running nor waiting for a human. */
7107
+ const DELIVERABLE_THREAD_STATUSES = /* @__PURE__ */ new Set(["idle", "error"]);
7108
+ /**
7109
+ * Start a notification run on the parent's thread only while it's idle (or its last run failed).
7110
+ *
7111
+ * A run on a thread waiting for a human would cancel that approval. Never throws.
7112
+ */
7113
+ async function awakeParent(parentThreadId, assistantId, update, context) {
7114
+ const client = new Client();
7115
+ try {
7116
+ const thread = await client.threads.get(parentThreadId);
7117
+ if (!DELIVERABLE_THREAD_STATUSES.has(thread.status)) return;
7118
+ await client.runs.create(parentThreadId, assistantId, {
7119
+ input: { messages: [notificationMessage(update)] },
7120
+ multitaskStrategy: "reject",
7121
+ ...context ? { context } : {}
7122
+ });
7123
+ } catch {}
7124
+ }
7125
+ /**
7126
+ * Wake the parent if it's idle, with this run's context; otherwise it finds out
7127
+ * on its own. Never throws.
7128
+ */
7129
+ async function notifyParent(config, update, context) {
7130
+ const parent = launchingAgent(config);
7131
+ if (parent?.thread_id && parent.assistant_id) await awakeParent(parent.thread_id, parent.assistant_id, update, forwardedContext(context));
7132
+ }
7133
+ /**
6692
7134
  * Extract the callback thread ID from the tool runtime.
6693
7135
  *
6694
7136
  * The thread ID is included in the subagent's input state so the subagent
@@ -6717,15 +7159,14 @@ function buildStartTool(agentMap, clients, toolDescription) {
6717
7159
  const spec = agentMap[input.agentName];
6718
7160
  const callbackContext = extractCallbackContext(runtime);
6719
7161
  try {
6720
- const client = clients.getClient(input.agentName);
6721
- const thread = await client.threads.create();
6722
- const run = await client.runs.create(thread.thread_id, spec.graphId, { input: {
6723
- messages: [{
6724
- role: "user",
6725
- content: input.description
6726
- }],
6727
- ...callbackContext
6728
- } });
7162
+ const thread = await clients.getClient(input.agentName).threads.create({ metadata: threadMetadata(spec, runtime.config) });
7163
+ const run = await clients.getClient(input.agentName, traceHeaders(spec)).runs.create(thread.thread_id, spec.graphId, {
7164
+ input: {
7165
+ messages: startTaskMessages(spec, runtime.state, input.description),
7166
+ ...callbackContext
7167
+ },
7168
+ ...runOptions(spec, runtime)
7169
+ });
6729
7170
  const taskId = thread.thread_id;
6730
7171
  const task = {
6731
7172
  taskId,
@@ -6765,86 +7206,111 @@ function buildCheckTool(clients) {
6765
7206
  return tool(async (input, runtime) => {
6766
7207
  const task = resolveTrackedTask(input.taskId, runtime.state);
6767
7208
  if (typeof task === "string") return task;
6768
- const client = clients.getClient(task.agentName);
6769
7209
  let run;
7210
+ let thread;
6770
7211
  try {
6771
- run = await client.runs.get(task.threadId, task.runId);
7212
+ [run, thread] = await observeTaskRun(clients.getClient(task.agentName), task);
6772
7213
  } catch (e) {
6773
7214
  return `Failed to get run status: ${e}`;
6774
7215
  }
6775
- let threadValues = {};
6776
- if (run.status === "success") try {
6777
- threadValues = (await client.threads.getState(task.threadId)).values || {};
6778
- } catch {}
6779
- const result = buildCheckResult(run, task.threadId, threadValues);
6780
- const updatedTask = {
6781
- taskId: task.taskId,
6782
- agentName: task.agentName,
6783
- threadId: task.threadId,
6784
- runId: task.runId,
6785
- status: result.status,
6786
- createdAt: task.createdAt,
6787
- updatedAt: result.status !== task.status ? (/* @__PURE__ */ new Date()).toISOString() : task.updatedAt,
6788
- checkedAt: (/* @__PURE__ */ new Date()).toISOString()
6789
- };
7216
+ const result = keepCancelled(task, buildCheckResult(run, task.threadId, thread));
7217
+ const updatedTask = observed(task, result.status, run.run_id);
6790
7218
  return new Command({ update: {
6791
7219
  messages: [new ToolMessage({
6792
- content: JSON.stringify(result),
7220
+ content: checkOutput(result),
6793
7221
  tool_call_id: toolCallIdFromRuntime(runtime)
6794
7222
  })],
6795
7223
  asyncTasks: { [task.taskId]: updatedTask }
6796
7224
  } });
6797
7225
  }, {
6798
7226
  name: "check_async_task",
6799
- description: "Check the status of an async subagent task. Returns the current status and, if complete, the result. Statuses shown earlier in the conversation are always stale, so call this to get the current status rather than reporting a status from a previous tool result.",
7227
+ description: "Check the status of an async subagent task. Returns the current status and, if complete, the result. If the status is `waiting`, it also returns what the subagent is asking the user. Statuses shown earlier in the conversation are always stale, so call this to get the current status rather than reporting a status from a previous tool result.",
6800
7228
  schema: z.object({ taskId: z.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim.") })
6801
7229
  });
6802
7230
  }
7231
+ /** Confirm an update: queued behind an active run, or started, noting when it dropped a waiting human request. */
7232
+ function updateMessage(tracked, strategy) {
7233
+ if (strategy === "enqueue" && (tracked.status === "running" || tracked.status === "pending")) return `Queued follow-up to async subagent without interrupting its current run. taskId: ${tracked.taskId}`;
7234
+ const msg = `Updated async subagent. taskId: ${tracked.taskId}`;
7235
+ return tracked.status === "waiting" ? `${msg}. It was waiting for a human; that request was dropped.` : msg;
7236
+ }
7237
+ /**
7238
+ * Refuse every queued follow-up to a task after the first in one model turn.
7239
+ *
7240
+ * Parallel calls read the same state, so the task would lose track of all but one.
7241
+ */
7242
+ function parallelUpdateError(taskId, runtime) {
7243
+ if (!((runtime.state.messages ?? []).findLast((m) => AIMessage$1.isInstance(m))?.tool_calls ?? []).filter((call) => call.name === "update_async_task" && String(call.args.taskId ?? "").trim() === taskId).map((call) => call.id).slice(1).includes(toolCallIdFromRuntime(runtime))) return null;
7244
+ return `Not sent: an earlier \`update_async_task\` call in this turn already queues a follow-up for task ${taskId}. Send this follow-up in a later turn, or combine the two into one message.`;
7245
+ }
7246
+ /**
7247
+ * The runs a queued follow-up leaves behind it.
7248
+ *
7249
+ * The list grows while the task is unfinished, and otherwise restarts with the tracked run.
7250
+ */
7251
+ function supersededAfterUpdate(tracked) {
7252
+ return [...UNFINISHED_STATUSES.has(tracked.status) ? tracked.supersededRunIds ?? [] : [], tracked.runId];
7253
+ }
7254
+ /** The tracked task after a follow-up created `run`, which may still be queued. */
7255
+ function updatedTask(tracked, run, strategy, message) {
7256
+ const task = {
7257
+ ...tracked,
7258
+ runId: run.run_id,
7259
+ status: "running",
7260
+ description: message,
7261
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
7262
+ };
7263
+ if (strategy === "enqueue") {
7264
+ task.status = run.status;
7265
+ task.supersededRunIds = supersededAfterUpdate(tracked);
7266
+ }
7267
+ return task;
7268
+ }
7269
+ const UPDATE_TOOL_DESCRIPTION = "send updated instructions to an async subagent. Interrupts the current run and starts a new one on the same thread so the subagent sees the full conversation history plus your new message. The taskId remains the same.";
7270
+ /** The update tool's description, naming the subagents whose follow-ups queue instead. */
7271
+ function updateToolDescription(agentMap) {
7272
+ const queued = Object.values(agentMap).filter((spec) => spec.updateStrategy === "enqueue").map((spec) => `\`${spec.name}\``);
7273
+ if (queued.length === 0) return UPDATE_TOOL_DESCRIPTION;
7274
+ return `${UPDATE_TOOL_DESCRIPTION}\n\nException: for ${queued.join(", ")}, follow-ups queue behind the current run without interrupting it. A pending status means the latest follow-up is queued and earlier work may still be running. If the current run stops to ask the user something, the queued follow-up still starts and that request is dropped. Send one follow-up per task per turn; combine several into one message.`;
7275
+ }
6803
7276
  /**
6804
7277
  * Build the `update_async_task` tool.
6805
7278
  *
6806
- * Sends a follow-up message to a running async subagent by creating a new
6807
- * run on the same thread with `multitaskStrategy: "interrupt"`. The subagent
6808
- * sees the full conversation history plus the new message. The `taskId`
6809
- * remains the same; only the internal `runId` is updated.
7279
+ * Sends a follow-up message to an async subagent by creating a new run on the
7280
+ * same thread. The subagent sees the full conversation history plus the new
7281
+ * message. The `taskId` remains the same. The subagent's `updateStrategy`
7282
+ * decides whether the new run interrupts the current run or queues behind it.
6810
7283
  */
6811
7284
  function buildUpdateTool(agentMap, clients) {
6812
7285
  return tool(async (input, runtime) => {
6813
7286
  const tracked = resolveTrackedTask(input.taskId, runtime.state);
6814
7287
  if (typeof tracked === "string") return tracked;
6815
7288
  const spec = agentMap[tracked.agentName];
7289
+ const strategy = spec.updateStrategy ?? "interrupt";
7290
+ const refused = strategy === "enqueue" && parallelUpdateError(tracked.taskId, runtime);
7291
+ if (refused) return refused;
6816
7292
  try {
6817
- const run = await clients.getClient(tracked.agentName).runs.create(tracked.threadId, spec.graphId, {
7293
+ const run = await clients.getClient(tracked.agentName, traceHeaders(spec)).runs.create(tracked.threadId, spec.graphId, {
6818
7294
  input: { messages: [{
6819
7295
  role: "user",
6820
7296
  content: input.message
6821
7297
  }] },
6822
- multitaskStrategy: "interrupt"
7298
+ multitaskStrategy: strategy,
7299
+ ...runOptions(spec, runtime)
6823
7300
  });
6824
- const task = {
6825
- taskId: tracked.taskId,
6826
- agentName: tracked.agentName,
6827
- threadId: tracked.threadId,
6828
- runId: run.run_id,
6829
- status: "running",
6830
- createdAt: tracked.createdAt,
6831
- description: input.message,
6832
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
6833
- checkedAt: tracked.checkedAt
6834
- };
6835
7301
  return new Command({ update: {
6836
7302
  messages: [new ToolMessage({
6837
- content: `Updated async subagent. taskId: ${tracked.taskId}`,
7303
+ content: updateMessage(tracked, strategy),
6838
7304
  tool_call_id: toolCallIdFromRuntime(runtime)
6839
7305
  })],
6840
- asyncTasks: { [tracked.taskId]: task }
7306
+ asyncTasks: { [tracked.taskId]: updatedTask(tracked, run, strategy, input.message) }
6841
7307
  } });
6842
7308
  } catch (e) {
6843
7309
  return `Failed to update async subagent: ${e}`;
6844
7310
  }
6845
7311
  }, {
6846
7312
  name: "update_async_task",
6847
- description: "send updated instructions to an async subagent. Interrupts the current run and starts a new one on the same thread so the subagent sees the full conversation history plus your new message. The taskId remains the same.",
7313
+ description: updateToolDescription(agentMap),
6848
7314
  schema: z.object({
6849
7315
  taskId: z.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim."),
6850
7316
  message: z.string().describe("Follow-up instructions or context to send to the subagent")
@@ -6852,6 +7318,20 @@ function buildUpdateTool(agentMap, clients) {
6852
7318
  });
6853
7319
  }
6854
7320
  /**
7321
+ * Cancel earlier runs that are still pending or running, newest first.
7322
+ *
7323
+ * Newest first, so a queued run doesn't start when the run ahead of it is cancelled.
7324
+ * A run that can't be read or cancelled is skipped.
7325
+ */
7326
+ async function cancelEarlierRuns(client, task) {
7327
+ for (const runId of [...task.supersededRunIds ?? []].reverse()) try {
7328
+ const run = await client.runs.get(task.threadId, runId);
7329
+ if (run.status === "running" || run.status === "pending") await client.runs.cancel(task.threadId, runId);
7330
+ } catch (e) {
7331
+ console.warn(`Failed to cancel earlier run ${runId} of task ${task.taskId}:`, e);
7332
+ }
7333
+ }
7334
+ /**
6855
7335
  * Build the `cancel_async_task` tool.
6856
7336
  *
6857
7337
  * Cancels the current run on the remote server and updates the task's
@@ -6861,21 +7341,17 @@ function buildCancelTool(clients) {
6861
7341
  return tool(async (input, runtime) => {
6862
7342
  const tracked = resolveTrackedTask(input.taskId, runtime.state);
6863
7343
  if (typeof tracked === "string") return tracked;
6864
- const client = clients.getClient(tracked.agentName);
6865
- try {
7344
+ if (tracked.status !== "waiting") try {
7345
+ const client = clients.getClient(tracked.agentName);
6866
7346
  await client.runs.cancel(tracked.threadId, tracked.runId);
7347
+ await cancelEarlierRuns(client, tracked);
6867
7348
  } catch (e) {
6868
7349
  return `Failed to cancel run: ${e}`;
6869
7350
  }
6870
7351
  const updated = {
6871
- taskId: tracked.taskId,
6872
- agentName: tracked.agentName,
6873
- threadId: tracked.threadId,
6874
- runId: tracked.runId,
7352
+ ...tracked,
6875
7353
  status: "cancelled",
6876
- createdAt: tracked.createdAt,
6877
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
6878
- checkedAt: tracked.checkedAt
7354
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
6879
7355
  };
6880
7356
  return new Command({ update: {
6881
7357
  messages: [new ToolMessage({
@@ -6886,7 +7362,7 @@ function buildCancelTool(clients) {
6886
7362
  } });
6887
7363
  }, {
6888
7364
  name: "cancel_async_task",
6889
- description: "Cancel a running async subagent task. Use this to stop a task that is no longer needed.",
7365
+ description: "Cancel a running, pending, or waiting async subagent task. Use this to stop a task that is no longer needed.",
6890
7366
  schema: z.object({ taskId: z.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim.") })
6891
7367
  });
6892
7368
  }
@@ -6900,24 +7376,14 @@ function buildListTool(clients) {
6900
7376
  return tool(async (input, runtime) => {
6901
7377
  const filtered = filterTasks(runtime.state.asyncTasks ?? {}, input.statusFilter ?? void 0);
6902
7378
  if (filtered.length === 0) return "No async subagent tasks tracked";
6903
- const statuses = await Promise.all(filtered.map((task) => fetchLiveTaskStatus(clients, task)));
7379
+ const live = await Promise.all(filtered.map((task) => fetchLiveTaskStatus(clients, task)));
6904
7380
  const updatedTasks = {};
6905
7381
  const entries = [];
6906
7382
  for (let idx = 0; idx < filtered.length; idx++) {
6907
7383
  const task = filtered[idx];
6908
- const status = statuses[idx];
6909
- const taskEntry = formatTaskEntry(task, status);
6910
- entries.push(taskEntry);
6911
- updatedTasks[task.taskId] = {
6912
- taskId: task.taskId,
6913
- agentName: task.agentName,
6914
- threadId: task.threadId,
6915
- runId: task.runId,
6916
- status,
6917
- createdAt: task.createdAt,
6918
- updatedAt: status !== task.status ? (/* @__PURE__ */ new Date()).toISOString() : task.updatedAt,
6919
- checkedAt: task.checkedAt
6920
- };
7384
+ const [status, runId] = live[idx];
7385
+ entries.push(formatTaskEntry(task, status));
7386
+ updatedTasks[task.taskId] = observed(task, status, runId);
6921
7387
  }
6922
7388
  return new Command({ update: {
6923
7389
  messages: [new ToolMessage({
@@ -6928,10 +7394,107 @@ function buildListTool(clients) {
6928
7394
  } });
6929
7395
  }, {
6930
7396
  name: "list_async_tasks",
6931
- description: "List tracked async subagent tasks with their current live statuses. By default shows all tasks. Use `statusFilter` to narrow by status (e.g., 'running', 'success', 'error', 'cancelled'). Use `check_async_task` to get the full result of a specific completed task. Statuses shown earlier in the conversation are always stale, so call this to read current statuses rather than reporting one from a previous tool result.",
6932
- schema: z.object({ statusFilter: z.string().nullish().describe("Filter tasks by status. One of: 'running', 'success', 'error', 'cancelled', 'all'. Defaults to 'all'.") })
7397
+ description: "List tracked async subagent tasks with their current live statuses. By default shows all tasks. Use `statusFilter` to narrow by status (e.g., 'running', 'pending', 'waiting', 'success', 'error', 'cancelled'). Use `check_async_task` to get the full result of a specific completed task, or what a `waiting` task is asking the user. Statuses shown earlier in the conversation are always stale, so call this to read current statuses rather than reporting one from a previous tool result.",
7398
+ schema: z.object({ statusFilter: z.string().nullish().describe("Filter tasks by status. One of: 'running', 'pending', 'waiting', 'success', 'error', 'cancelled', 'all'. Defaults to 'all'.") })
6933
7399
  });
6934
7400
  }
7401
+ /** The notification for a task outcome a check found, or `null` for outcomes not worth waking for. */
7402
+ function checkEvent(task, run, thread, status) {
7403
+ if (!NOTIFIED_STATUSES.has(status)) return null;
7404
+ const result = buildCheckResult(run, task.threadId, thread);
7405
+ const details = {};
7406
+ if (result.interrupts) details.interrupts = result.interrupts;
7407
+ if (status === "success") details.result = result.result;
7408
+ if (status === "error") details.error = "The subagent failed.";
7409
+ return taskUpdate({
7410
+ task_id: task.taskId,
7411
+ agent_name: task.agentName,
7412
+ status,
7413
+ run_id: run.run_id ?? task.runId
7414
+ }, details);
7415
+ }
7416
+ /** Task outcomes that notify the parent. */
7417
+ const NOTIFIED_STATUSES = /* @__PURE__ */ new Set([
7418
+ "success",
7419
+ "error",
7420
+ "timeout",
7421
+ "cancelled",
7422
+ "waiting"
7423
+ ]);
7424
+ /** How long the parent waits on one task's status before skipping it until the next check. */
7425
+ const PULL_TIMEOUT_MS = 5e3;
7426
+ /** Tracked task statuses that can still change, so the parent checks them for status updates. */
7427
+ const UNFINISHED_STATUSES = /* @__PURE__ */ new Set([
7428
+ "running",
7429
+ "pending",
7430
+ "waiting"
7431
+ ]);
7432
+ /** Observe a task, or `null` when it can't be checked in time; it's checked again next time. */
7433
+ async function observeTask(clients, task) {
7434
+ try {
7435
+ return await observeTaskRun(clients.getClient(task.agentName), task, AbortSignal.timeout(PULL_TIMEOUT_MS));
7436
+ } catch (e) {
7437
+ console.warn(`Failed to check task ${task.taskId}:`, e);
7438
+ return null;
7439
+ }
7440
+ }
7441
+ /**
7442
+ * Check unfinished tasks; return their updated records and a notification per new outcome.
7443
+ *
7444
+ * Outcomes the agent already saw aren't reported again; a task that can't be
7445
+ * checked is skipped until the next check.
7446
+ */
7447
+ async function pull(clients, tasks) {
7448
+ const unfinished = Object.values(tasks).filter((task) => UNFINISHED_STATUSES.has(task.status));
7449
+ const found = await Promise.all(unfinished.map((task) => observeTask(clients, task)));
7450
+ const records = {};
7451
+ const messages = [];
7452
+ unfinished.forEach((task, idx) => {
7453
+ if (found[idx] === null) return;
7454
+ const [run, thread] = found[idx];
7455
+ const status = taskStatus(run, thread);
7456
+ if (status === task.status && run.run_id === task.runId) return;
7457
+ records[task.taskId] = observed(task, status, run.run_id);
7458
+ const event = status !== task.status ? checkEvent(task, run, thread, status) : null;
7459
+ if (event) messages.push(coerceMessageLikeToMessage(notificationMessage(event)));
7460
+ });
7461
+ const update = {};
7462
+ if (Object.keys(records).length > 0) update.asyncTasks = records;
7463
+ if (messages.length > 0) update.messages = messages;
7464
+ return update;
7465
+ }
7466
+ /**
7467
+ * When a task notification started this run, record the task's outcome so checks don't report it again.
7468
+ *
7469
+ * A notification from an earlier run that a queued follow-up replaced is rewritten
7470
+ * instead, so the model doesn't take it as the task's outcome.
7471
+ */
7472
+ function recordNotification(messages, tasks) {
7473
+ const last = messages[messages.length - 1];
7474
+ const event = notificationEvent(last);
7475
+ const task = event ? tasks[event.task_id] : void 0;
7476
+ if (!event || !task || task.status === "cancelled") return {};
7477
+ const runId = event.run_id ?? task.runId;
7478
+ if (task.supersededRunIds?.includes(runId)) {
7479
+ const content = supersededNotificationContent(last, event);
7480
+ return { messages: [new HumanMessage$1({
7481
+ id: last.id,
7482
+ content,
7483
+ additional_kwargs: last.additional_kwargs
7484
+ })] };
7485
+ }
7486
+ if (runId !== task.runId && !UNFINISHED_STATUSES.has(task.status)) return {};
7487
+ return { asyncTasks: { [task.taskId]: observed(task, event.status, runId) } };
7488
+ }
7489
+ /** The tasks tracked in state; the state schema stores `status` as a plain string. */
7490
+ function trackedTasks(state) {
7491
+ return state.asyncTasks ?? {};
7492
+ }
7493
+ /** Whether the last message is a final answer: an AI message with no tool calls. */
7494
+ function isFinalAnswer(messages) {
7495
+ const last = messages[messages.length - 1];
7496
+ return last !== void 0 && !last.tool_calls?.length;
7497
+ }
6935
7498
  /**
6936
7499
  * Create middleware that adds async subagent tools to an agent.
6937
7500
  *
@@ -6943,6 +7506,11 @@ function buildListTool(clients) {
6943
7506
  * Works with any Agent Protocol-compliant server — LangGraph Platform (managed)
6944
7507
  * or self-hosted (e.g. a Hono/Express server implementing the Agent Protocol spec).
6945
7508
  *
7509
+ * On an Agent Server, the agent is told when its tasks finish, fail or wait for
7510
+ * the user: by checking while it runs, and through a new run when it's idle.
7511
+ *
7512
+ * @experimental Task notifications are experimental and subject to change.
7513
+ *
6946
7514
  * @throws {Error} If no async subagents are provided or names are duplicated.
6947
7515
  *
6948
7516
  * @example
@@ -6972,9 +7540,15 @@ function createAsyncSubAgentMiddleware(options) {
6972
7540
  const names = asyncSubAgents.map((a) => a.name);
6973
7541
  const duplicates = names.filter((n, i) => names.indexOf(n) !== i);
6974
7542
  if (duplicates.length > 0) throw new Error(`Duplicate async subagent names: ${[...new Set(duplicates)].join(", ")}`);
7543
+ for (const spec of asyncSubAgents) {
7544
+ const strategy = spec.updateStrategy ?? "interrupt";
7545
+ if (strategy !== "interrupt" && strategy !== "enqueue") throw new Error(`AsyncSubAgent '${spec.name}' has invalid updateStrategy '${strategy}'; expected 'interrupt' or 'enqueue'`);
7546
+ const mode = spec.mode ?? "isolated";
7547
+ if (mode !== "isolated" && mode !== "fork") throw new Error(`AsyncSubAgent '${spec.name}' has invalid mode '${mode}'; expected 'isolated' or 'fork'`);
7548
+ }
6975
7549
  const agentMap = Object.fromEntries(asyncSubAgents.map((a) => [a.name, a]));
6976
7550
  const clients = new ClientCache(agentMap);
6977
- const agentsDescription = asyncSubAgents.map((a) => `- ${a.name}: ${a.description}`).join("\n");
7551
+ const agentsDescription = asyncSubAgents.map(describeAsyncSubAgent).join("\n");
6978
7552
  const tools = [
6979
7553
  buildStartTool(agentMap, clients, ASYNC_TASK_TOOL_DESCRIPTION.replace("{available_agents}", agentsDescription)),
6980
7554
  buildCheckTool(clients),
@@ -6987,6 +7561,41 @@ function createAsyncSubAgentMiddleware(options) {
6987
7561
  name: "asyncSubAgentMiddleware",
6988
7562
  stateSchema: AsyncTaskStateSchema,
6989
7563
  tools,
7564
+ beforeAgent: async (state) => {
7565
+ const messages = state.messages ?? [];
7566
+ const tasks = trackedTasks(state);
7567
+ const recorded = recordNotification(messages, tasks);
7568
+ const updates = await pull(clients, {
7569
+ ...tasks,
7570
+ ...recorded.asyncTasks
7571
+ });
7572
+ const asyncTasks = {
7573
+ ...recorded.asyncTasks,
7574
+ ...updates.asyncTasks
7575
+ };
7576
+ const notes = [...recorded.messages ?? [], ...updates.messages ?? []];
7577
+ if (Object.keys(asyncTasks).length === 0 && notes.length === 0) return;
7578
+ return {
7579
+ asyncTasks,
7580
+ ...notes.length > 0 && { messages: notes }
7581
+ };
7582
+ },
7583
+ beforeModel: async (state) => {
7584
+ const updates = await pull(clients, trackedTasks(state));
7585
+ return Object.keys(updates).length > 0 ? updates : void 0;
7586
+ },
7587
+ afterModel: {
7588
+ canJumpTo: ["model"],
7589
+ hook: async (state) => {
7590
+ if (!isFinalAnswer(state.messages ?? [])) return;
7591
+ const updates = await pull(clients, trackedTasks(state));
7592
+ if (!updates.messages) return Object.keys(updates).length > 0 ? updates : void 0;
7593
+ return {
7594
+ ...updates,
7595
+ jumpTo: "model"
7596
+ };
7597
+ }
7598
+ },
6990
7599
  wrapModelCall: async (request, handler) => {
6991
7600
  if (fullSystemPrompt !== null) return handler({
6992
7601
  ...request,
@@ -7047,6 +7656,53 @@ function createCacheBreakpointMiddleware() {
7047
7656
  });
7048
7657
  }
7049
7658
  //#endregion
7659
+ //#region src/middleware/parent_notifier.ts
7660
+ /** Whether this is the outermost graph of a task run, not a graph nested in it. */
7661
+ function isTopLevelGraph(config) {
7662
+ const configurable = config.configurable ?? {};
7663
+ return !String(configurable.checkpoint_ns ?? "").includes("|");
7664
+ }
7665
+ /** Whether `error` comes from the run being aborted rather than from the subagent failing. */
7666
+ function wasAborted(error, signal) {
7667
+ return signal?.aborted === true || getConfig()?.signal?.aborted === true || typeof error === "object" && error !== null && error.name === "AbortError";
7668
+ }
7669
+ /**
7670
+ * Wake the agent that started this run with `start_async_task`, when the run ends.
7671
+ *
7672
+ * `createDeepAgent` attaches it to every deep agent. It does nothing unless the
7673
+ * run carries the parent reference, and skips nested runs.
7674
+ */
7675
+ function createParentNotifierMiddleware() {
7676
+ /**
7677
+ * Notify for this graph's own run that an async subagent tool started.
7678
+ *
7679
+ * The run's context comes from its config: hooks only see the context fields
7680
+ * a middleware's `contextSchema` declares, and this one declares none.
7681
+ */
7682
+ async function report(status, details) {
7683
+ const config = getConfig();
7684
+ if (!launchingAgent(config) || !isTopLevelGraph(config)) return;
7685
+ if (currentRunId(config) === void 0) return;
7686
+ const metadata = config.metadata ?? {};
7687
+ const configurable = config.configurable ?? {};
7688
+ await notifyParent(config, taskEvent(config, String(metadata.subagent_name ?? metadata.graph_id ?? configurable.graph_id ?? "subagent"), status, details), config.context);
7689
+ }
7690
+ return createMiddleware({
7691
+ name: "parentNotifierMiddleware",
7692
+ afterAgent: async (state) => {
7693
+ await report("success", { result: finalContent(state) });
7694
+ },
7695
+ wrapModelCall: async (request, handler) => {
7696
+ try {
7697
+ return await handler(request);
7698
+ } catch (e) {
7699
+ if (!isGraphBubbleUp(e) && !wasAborted(e, request.runtime.signal)) await report("error", { error: failureText(e) });
7700
+ throw e;
7701
+ }
7702
+ }
7703
+ });
7704
+ }
7705
+ //#endregion
7050
7706
  //#region src/middleware/tool_exclusion.ts
7051
7707
  function hasToolName(tool) {
7052
7708
  return tool !== null && typeof tool === "object" && "name" in tool && typeof tool.name === "string";
@@ -7952,6 +8608,7 @@ function createDeepAgent(params = {}) {
7952
8608
  createPatchToolCallsMiddleware()
7953
8609
  ];
7954
8610
  let middleware = mergeMiddlewareStack([
8611
+ createParentNotifierMiddleware(),
7955
8612
  fsMiddleware,
7956
8613
  subagentMiddleware,
7957
8614
  summarizationMiddleware,
@@ -10103,4 +10760,4 @@ var LangSmithSandbox = class LangSmithSandbox extends BaseSandbox {
10103
10760
  //#endregion
10104
10761
  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 };
10105
10762
 
10106
- //# sourceMappingURL=langsmith-C-EMyQJ_.js.map
10763
+ //# sourceMappingURL=langsmith-WS8VrZxE.js.map