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.
@@ -40,6 +40,7 @@ let _langchain_core_utils_function_calling = require("@langchain/core/utils/func
40
40
  let _langchain_core_utils_json_schema = require("@langchain/core/utils/json_schema");
41
41
  let _langchain_core_utils_types = require("@langchain/core/utils/types");
42
42
  let _langchain_langgraph_sdk = require("@langchain/langgraph-sdk");
43
+ let langsmith_traceable = require("langsmith/traceable");
43
44
  let langsmith = require("langsmith");
44
45
  let langsmith_experimental_sandbox = require("langsmith/experimental/sandbox");
45
46
  //#region src/backends/realpath.ts
@@ -1468,6 +1469,14 @@ async function hydrateMessages(messages, backend, prefix, cache) {
1468
1469
  }
1469
1470
  return restorePayloads(messages, payloads);
1470
1471
  }
1472
+ /**
1473
+ * Replace each blob reference in `messages` with a notice that the content is
1474
+ * unavailable, for an agent that can't load blobs, so the model still accepts
1475
+ * the request.
1476
+ */
1477
+ function withoutBlobRefs(messages) {
1478
+ return messages.some(messageHasRefs) ? restorePayloads(messages, /* @__PURE__ */ new Map()) : messages;
1479
+ }
1471
1480
  //#endregion
1472
1481
  //#region src/middleware/unsupportedContent.ts
1473
1482
  const PDF_MIME_TYPE = "application/pdf";
@@ -3396,7 +3405,7 @@ function createFilesystemMiddleware(options = {}) {
3396
3405
  pending: []
3397
3406
  }, resolvedBackend, BLOBS_PREFIX, blobCache);
3398
3407
  messages = await hydrateMessages(messages, resolvedBackend, BLOBS_PREFIX, blobCache);
3399
- }
3408
+ } else if (messages) messages = withoutBlobRefs(messages);
3400
3409
  const finalRequest = {
3401
3410
  ...request,
3402
3411
  tools,
@@ -6263,6 +6272,9 @@ function createSkillsMiddleware(options) {
6263
6272
  *
6264
6273
  * @experimental - this middleware is experimental and may change in future releases.
6265
6274
  *
6275
+ * @deprecated `createDeepAgent` now notifies the launching agent on its own;
6276
+ * adding this middleware too sends the parent two notifications per task.
6277
+ *
6266
6278
  * This middleware sends a notification to a callback thread when a subagent
6267
6279
  * completes successfully or raises an error. The callback agent can then
6268
6280
  * process that notification instead of relying only on polling via
@@ -6371,7 +6383,7 @@ function resolveHeaders(headers) {
6371
6383
  * @param message - The message content to send.
6372
6384
  * @param options - Optional url and headers for the callback server.
6373
6385
  */
6374
- async function notifyParent(callbackGraphId, callbackThreadId, message, options) {
6386
+ async function notifyParent$1(callbackGraphId, callbackThreadId, message, options) {
6375
6387
  try {
6376
6388
  await new _langchain_langgraph_sdk.Client({
6377
6389
  apiUrl: options?.url ?? void 0,
@@ -6422,6 +6434,9 @@ function extractLastMessage(state, taskId) {
6422
6434
  * If `callbackThreadId` is not present in state, the middleware does
6423
6435
  * nothing.
6424
6436
  *
6437
+ * @deprecated `createDeepAgent` now notifies the launching agent on its own;
6438
+ * adding this middleware too sends the parent two notifications per task.
6439
+ *
6425
6440
  * @param options - Configuration options.
6426
6441
  * @returns An `AgentMiddleware` instance.
6427
6442
  *
@@ -6445,7 +6460,7 @@ function createCompletionCallbackMiddleware(options) {
6445
6460
  * Send a notification to the callback destination.
6446
6461
  */
6447
6462
  async function sendNotification(callbackThreadId, message) {
6448
- await notifyParent(callbackGraphId, callbackThreadId, message, {
6463
+ await notifyParent$1(callbackGraphId, callbackThreadId, message, {
6449
6464
  url,
6450
6465
  headers
6451
6466
  });
@@ -6515,6 +6530,7 @@ const AsyncTaskSchema = zod_v4.z.object({
6515
6530
  agentName: zod_v4.z.string(),
6516
6531
  threadId: zod_v4.z.string(),
6517
6532
  runId: zod_v4.z.string(),
6533
+ supersededRunIds: zod_v4.z.array(zod_v4.z.string()).optional(),
6518
6534
  status: zod_v4.z.string(),
6519
6535
  createdAt: zod_v4.z.string(),
6520
6536
  description: zod_v4.z.string().optional(),
@@ -6562,16 +6578,11 @@ Available async agent types:
6562
6578
 
6563
6579
  ## Usage notes:
6564
6580
  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.
6565
- 2. Use \`check_async_task\` only when the user asks for a status update or result.
6581
+ 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.
6566
6582
  3. Use \`update_async_task\` to send new instructions to a running task.
6567
6583
  4. Multiple async subagents can run concurrently — launch several and let them run in the background.
6568
- 5. The subagent runs on a remote server, so it has its own tools and capabilities.`;
6569
- /**
6570
- * Task statuses that will never change.
6571
- *
6572
- * When listing tasks, live-status fetches are skipped for tasks whose
6573
- * cached status is in this set, since they are guaranteed to be final.
6574
- */
6584
+ 5. The subagent runs on a remote server, so it has its own tools and capabilities.
6585
+ 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.`;
6575
6586
  /**
6576
6587
  * Names of the tools added by the async subagent middleware.
6577
6588
  *
@@ -6585,6 +6596,7 @@ const ASYNC_TASK_TOOL_NAMES = [
6585
6596
  "cancel_async_task",
6586
6597
  "list_async_tasks"
6587
6598
  ];
6599
+ /** Task statuses that never change, so live-status fetches can be skipped; `waiting` can still resume. */
6588
6600
  const TERMINAL_STATUSES = /* @__PURE__ */ new Set([
6589
6601
  "cancelled",
6590
6602
  "success",
@@ -6604,32 +6616,141 @@ function resolveTrackedTask(taskId, state) {
6604
6616
  if (!tracked) return `No tracked task found for taskId: '${taskId}'`;
6605
6617
  return tracked;
6606
6618
  }
6619
+ /** Guidance for a task whose latest run hasn't started. */
6620
+ const PENDING_NOTE = "The latest run hasn't started yet. If it is a queued follow-up, an earlier run may still be working.";
6621
+ /** Task status implied by the thread when the tracked run finished but the thread moved on. */
6622
+ const THREAD_TO_TASK_STATUS = {
6623
+ interrupted: "waiting",
6624
+ busy: "running",
6625
+ error: "error"
6626
+ };
6627
+ /**
6628
+ * Return a task's status from its latest run, reading the thread to spot pauses.
6629
+ *
6630
+ * A run that hits `interrupt()` ends as `success`; only its thread shows the pause.
6631
+ * A run cancelled on the server ends `interrupted`, which a task reports as `cancelled`.
6632
+ */
6633
+ function taskStatus(run, thread) {
6634
+ if (run.status === "interrupted") return "cancelled";
6635
+ if (run.status !== "success" || thread === null) return run.status;
6636
+ return THREAD_TO_TASK_STATUS[thread.status] ?? "success";
6637
+ }
6638
+ /** Whether a newer run exists than the tracked one, e.g. after a resume from another client. */
6639
+ function needsLatestRun(run, thread) {
6640
+ return run.status === "success" && thread !== null && (thread.status === "busy" || thread.status === "error");
6641
+ }
6607
6642
  /**
6608
- * Build a check result from a run's current status and thread state values.
6643
+ * Fetch a task's latest run and, when that run finished, its thread (else `null`).
6609
6644
  *
6610
- * For successful runs, extracts the last message's content from the remote
6611
- * thread's state values. For errored runs, includes a generic error message.
6645
+ * Throws if the thread can't be read, since a paused run also ends as `success`.
6646
+ * A run replaced by another client's run hands over to the newest one, except for
6647
+ * a task the parent cancelled.
6648
+ */
6649
+ async function observeTaskRun(client, task, signal) {
6650
+ let run = await client.runs.get(task.threadId, task.runId, { signal });
6651
+ if (run.status === "interrupted" && task.status !== "cancelled") {
6652
+ const [latest] = await client.runs.list(task.threadId, {
6653
+ limit: 1,
6654
+ signal
6655
+ });
6656
+ run = latest ?? run;
6657
+ }
6658
+ if (run.status !== "success") return [run, null];
6659
+ const thread = await client.threads.get(task.threadId, { signal });
6660
+ if (needsLatestRun(run, thread)) {
6661
+ const [latest] = await client.runs.list(task.threadId, {
6662
+ limit: 1,
6663
+ signal
6664
+ });
6665
+ run = latest ?? run;
6666
+ }
6667
+ return [run, thread];
6668
+ }
6669
+ /** Flatten a thread's pending interrupts, including ones raised inside subgraphs. */
6670
+ function pendingInterrupts(thread) {
6671
+ if (!thread?.interrupts) return [];
6672
+ return Object.values(thread.interrupts).flat();
6673
+ }
6674
+ 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.";
6675
+ /** The thread's messages, if its values hold any. */
6676
+ function threadMessages(values) {
6677
+ if (values === null || typeof values !== "object" || Array.isArray(values)) return [];
6678
+ const messages = values.messages;
6679
+ return Array.isArray(messages) ? messages : [];
6680
+ }
6681
+ /** A thread message's content as text, whatever shape the server sent it in. */
6682
+ function messageText(message) {
6683
+ if (_langchain_core_messages.BaseMessage.isInstance(message)) return message.text;
6684
+ const content = typeof message === "object" && message !== null && "content" in message ? message.content : message;
6685
+ return typeof content === "string" ? content : JSON.stringify(content);
6686
+ }
6687
+ /**
6688
+ * Build a check result from a task's latest run and its thread.
6612
6689
  *
6613
- * @param run - The run object from the SDK.
6614
- * @param threadId - The thread ID for the run.
6615
- * @param threadValues - The `values` from `ThreadState` (the remote subagent's state).
6690
+ * @param run - The task's latest run.
6691
+ * @param threadId - The task's thread ID.
6692
+ * @param thread - The task's thread, when its run finished.
6616
6693
  */
6617
- function buildCheckResult(run, threadId, threadValues) {
6694
+ function buildCheckResult(run, threadId, thread) {
6695
+ const status = taskStatus(run, thread);
6618
6696
  const checkResult = {
6619
- status: run.status,
6697
+ status,
6620
6698
  threadId
6621
6699
  };
6622
- if (run.status === "success") {
6623
- const messages = (Array.isArray(threadValues) ? {} : threadValues)?.messages ?? [];
6624
- if (messages.length > 0) {
6625
- const last = messages[messages.length - 1];
6626
- const rawContent = typeof last === "object" && last !== null && "content" in last ? last.content : last;
6627
- checkResult.result = typeof rawContent === "string" ? rawContent : JSON.stringify(rawContent);
6628
- } else checkResult.result = "Completed with no output messages.";
6629
- } else if (run.status === "error") checkResult.error = "The async subagent encountered an error.";
6700
+ if (status === "pending") checkResult.note = PENDING_NOTE;
6701
+ else if (status === "success") checkResult.result = finalContent(thread?.values);
6702
+ else if (status === "error") checkResult.error = "The async subagent encountered an error.";
6703
+ else if (status === "waiting") {
6704
+ checkResult.interrupts = pendingInterrupts(thread).map((item) => ({
6705
+ id: item.id ?? "",
6706
+ value: item.value
6707
+ }));
6708
+ checkResult.note = WAITING_NOTE;
6709
+ }
6630
6710
  return checkResult;
6631
6711
  }
6632
6712
  /**
6713
+ * A check result as tool output: JSON, with a text-only answer's text in `result`.
6714
+ *
6715
+ * An answer with media follows the JSON as its own blocks, in order. Reasoning and
6716
+ * tool-call blocks are dropped; the text isn't cut.
6717
+ */
6718
+ function checkOutput(result) {
6719
+ const blocks = result.result;
6720
+ if (!blocks) return JSON.stringify(result);
6721
+ const text = (block) => String(block.text);
6722
+ if (!blocks.some((block) => MEDIA_BLOCK_TYPES.has(block.type))) {
6723
+ const answer = blocks.filter((block) => block.type === "text").map(text);
6724
+ return JSON.stringify({
6725
+ ...result,
6726
+ result: answer.join("")
6727
+ });
6728
+ }
6729
+ const { result: _answer, ...status } = result;
6730
+ const answer = blocks.filter((block) => block.type === "text" || MEDIA_BLOCK_TYPES.has(block.type)).map((block) => block.type === "text" ? textBlock(text(block)) : { ...block });
6731
+ return [textBlock(JSON.stringify(status)), ...answer];
6732
+ }
6733
+ /** Keep a task cancelled while paused as cancelled; its thread still shows the old pause. */
6734
+ function keepCancelled(task, result) {
6735
+ if (task.status === "cancelled" && result.status === "waiting") return {
6736
+ status: "cancelled",
6737
+ threadId: result.threadId
6738
+ };
6739
+ return result;
6740
+ }
6741
+ /** `task` updated to what a check found. */
6742
+ function observed(task, status, runId) {
6743
+ const now = (/* @__PURE__ */ new Date()).toISOString();
6744
+ const changed = status !== task.status || runId !== task.runId;
6745
+ return {
6746
+ ...task,
6747
+ runId,
6748
+ status,
6749
+ updatedAt: changed ? now : task.updatedAt,
6750
+ checkedAt: now
6751
+ };
6752
+ }
6753
+ /**
6633
6754
  * Filter tasks by cached status from agent state.
6634
6755
  *
6635
6756
  * Filtering uses the cached status, not live server status. Live statuses
@@ -6644,17 +6765,17 @@ function filterTasks(tasks, statusFilter) {
6644
6765
  return Object.values(tasks).filter((task) => task.status === statusFilter);
6645
6766
  }
6646
6767
  /**
6647
- * Fetch the current run status from the server.
6768
+ * Fetch a task's current status and run ID.
6648
6769
  *
6649
- * Returns the cached status immediately for terminal tasks (avoiding
6650
- * unnecessary API calls). Falls back to the cached status on SDK errors.
6770
+ * Returns the cached values for terminal tasks and on SDK errors.
6651
6771
  */
6652
6772
  async function fetchLiveTaskStatus(clients, task) {
6653
- if (TERMINAL_STATUSES.has(task.status)) return task.status;
6773
+ if (TERMINAL_STATUSES.has(task.status)) return [task.status, task.runId];
6654
6774
  try {
6655
- return (await clients.getClient(task.agentName).runs.get(task.threadId, task.runId)).status;
6775
+ const [run, thread] = await observeTaskRun(clients.getClient(task.agentName), task);
6776
+ return [taskStatus(run, thread), run.run_id];
6656
6777
  } catch {
6657
- return task.status;
6778
+ return [task.status, task.runId];
6658
6779
  }
6659
6780
  }
6660
6781
  /**
@@ -6697,9 +6818,18 @@ var ClientCache = class {
6697
6818
  }
6698
6819
  /**
6699
6820
  * Get or create a `Client` for the named agent.
6821
+ *
6822
+ * With `extraHeaders` (such as one launch's trace headers), returns a new, uncached client.
6700
6823
  */
6701
- getClient(name) {
6824
+ getClient(name, extraHeaders = {}) {
6702
6825
  const spec = this.agents[name];
6826
+ if (Object.keys(extraHeaders).length > 0) return new _langchain_langgraph_sdk.Client({
6827
+ apiUrl: spec.url,
6828
+ defaultHeaders: {
6829
+ ...this.resolveHeaders(spec),
6830
+ ...extraHeaders
6831
+ }
6832
+ });
6703
6833
  const key = this.cacheKey(spec);
6704
6834
  const existing = this.clients.get(key);
6705
6835
  if (existing) return existing;
@@ -6713,6 +6843,318 @@ var ClientCache = class {
6713
6843
  }
6714
6844
  };
6715
6845
  /**
6846
+ * Baggage metadata key (JSON `true`) marking trace headers as a parent to nest under.
6847
+ *
6848
+ * Receivers that adopt the trace check for it, so keep the name stable.
6849
+ */
6850
+ const NEST_UNDER_PARENT = "ls_nest_under_parent";
6851
+ /**
6852
+ * Build LangSmith headers pointing at the current span, or `{}` when tracing is off.
6853
+ *
6854
+ * Only sent to subagents on this deployment (no `url`). The baggage carries the
6855
+ * project and `NEST_UNDER_PARENT`, not the caller's run metadata. Any `baggage`
6856
+ * in the spec's headers is kept.
6857
+ */
6858
+ function traceHeaders(spec) {
6859
+ if (spec.url) return {};
6860
+ const runTree = (0, langsmith_traceable.getCurrentRunTree)(true);
6861
+ if (!runTree?.tracingEnabled || !runTree.trace_id || !runTree.dotted_order) return {};
6862
+ const baggage = Object.entries(spec.headers ?? {}).filter(([key, value]) => key.toLowerCase() === "baggage" && value).map(([, value]) => value);
6863
+ baggage.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify({ [NEST_UNDER_PARENT]: true }))}`);
6864
+ if (runTree.project_name) baggage.push(`langsmith-project=${encodeURIComponent(runTree.project_name)}`);
6865
+ return {
6866
+ "langsmith-trace": runTree.dotted_order,
6867
+ baggage: baggage.join(",")
6868
+ };
6869
+ }
6870
+ /**
6871
+ * `configurable` key carrying the launching agent's reference to an async subagent's run.
6872
+ *
6873
+ * Apps read it directly, and Python deep agents use the same key, so keep the key and shape stable.
6874
+ */
6875
+ const PARENT_KEY = "deepagents_parent";
6876
+ /** Describe the running agent so the async subagent it launches can find it. */
6877
+ function parentReference(config) {
6878
+ const reference = {};
6879
+ const configurable = config?.configurable ?? {};
6880
+ const metadata = config?.metadata ?? {};
6881
+ if (configurable.thread_id) reference.thread_id = String(configurable.thread_id);
6882
+ const assistantId = metadata.assistant_id || configurable.assistant_id;
6883
+ if (assistantId) reference.assistant_id = String(assistantId);
6884
+ return reference;
6885
+ }
6886
+ /**
6887
+ * The parent reference sent to `spec`'s runs.
6888
+ *
6889
+ * A subagent on another server (`url`) or with `notifyParent: false` gets only the
6890
+ * parent's thread: the assistant is for waking the parent, which it can't do.
6891
+ */
6892
+ function referenceFor(spec, config) {
6893
+ const { thread_id, assistant_id } = parentReference(config);
6894
+ const wakesParent = !spec.url && spec.notifyParent !== false;
6895
+ return {
6896
+ ...thread_id && { thread_id },
6897
+ ...wakesParent && assistant_id && { assistant_id }
6898
+ };
6899
+ }
6900
+ /**
6901
+ * Metadata for a task's thread, so apps can find a parent's subagent threads with `threads.search`.
6902
+ *
6903
+ * It names the subagent as the parent knows it, and for subagents on this deployment
6904
+ * keeps the parent's assistant, so other runs on the thread (such as the user
6905
+ * answering the subagent) can still notify the parent.
6906
+ */
6907
+ function threadMetadata(spec, config) {
6908
+ const reference = referenceFor(spec, config);
6909
+ const metadata = { subagent_name: spec.name };
6910
+ if (reference.thread_id) metadata.parent_thread_id = reference.thread_id;
6911
+ if (reference.assistant_id) metadata.parent_assistant_id = reference.assistant_id;
6912
+ return metadata;
6913
+ }
6914
+ 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";
6915
+ /** A message as portable input for another run, without parent-local eviction tags. */
6916
+ function serializeForkMessage(message) {
6917
+ const { lc_evicted_to: _evicted, ...additionalKwargs } = message.additional_kwargs ?? {};
6918
+ const serialized = {
6919
+ type: message.type,
6920
+ content: message.content,
6921
+ additional_kwargs: additionalKwargs
6922
+ };
6923
+ if (message.id) serialized.id = message.id;
6924
+ if (message.name) serialized.name = message.name;
6925
+ if (_langchain_core_messages.AIMessage.isInstance(message)) serialized.tool_calls = message.tool_calls;
6926
+ if (_langchain_core_messages.ToolMessage.isInstance(message)) {
6927
+ serialized.tool_call_id = message.tool_call_id;
6928
+ serialized.status = message.status;
6929
+ }
6930
+ return serialized;
6931
+ }
6932
+ /**
6933
+ * The task's input messages: the parent's effective conversation for forks, or only the task.
6934
+ *
6935
+ * A fork keeps references to the parent's offloaded media; a subagent sharing the
6936
+ * parent's backend loads them, and any other sees that the content is unavailable.
6937
+ */
6938
+ function startTaskMessages(spec, state, description) {
6939
+ if (spec.mode !== "fork") return [{
6940
+ role: "user",
6941
+ content: description
6942
+ }];
6943
+ return [...getEffectiveMessages(stripInFlightAIMessage(state.messages ?? []), state), new _langchain_core_messages.HumanMessage({ content: ASYNC_FORK_TASK_PREAMBLE + description })].map(serializeForkMessage);
6944
+ }
6945
+ /** Describe a subagent's context inheritance without promising shared tools. */
6946
+ function describeAsyncSubAgent(spec) {
6947
+ const suffix = spec.mode === "fork" ? " (inherits your conversation at launch; uses its own system prompt and tools)" : "";
6948
+ return `- ${spec.name}: ${spec.description}${suffix}`;
6949
+ }
6950
+ /**
6951
+ * The `runs.create` options that link a run to this agent and set the subagent's webhook.
6952
+ *
6953
+ * A subagent on this deployment runs with this agent's context. The Agent Server
6954
+ * takes `context` or `configurable`, not both, so the parent reference then goes
6955
+ * through the thread's metadata.
6956
+ */
6957
+ function runOptions(spec, runtime) {
6958
+ const webhook = spec.webhook ? { webhook: spec.webhook } : {};
6959
+ const context = spec.url ? void 0 : forwardedContext(runtime.context);
6960
+ if (context) return {
6961
+ ...webhook,
6962
+ context
6963
+ };
6964
+ const reference = referenceFor(spec, runtime.config);
6965
+ return Object.keys(reference).length > 0 ? {
6966
+ ...webhook,
6967
+ config: { configurable: { [PARENT_KEY]: reference } }
6968
+ } : webhook;
6969
+ }
6970
+ /** A run context as JSON data for another run, without deepagents' parent reference. */
6971
+ function forwardedContext(context) {
6972
+ if (!context || typeof context !== "object" || Array.isArray(context)) return;
6973
+ const entries = Object.entries(context).filter(([key]) => key !== PARENT_KEY);
6974
+ return entries.length > 0 ? Object.fromEntries(entries) : void 0;
6975
+ }
6976
+ /**
6977
+ * The agent that launched this run's task, or `null` if no async subagent tool did.
6978
+ *
6979
+ * Read from the run's config, or else from the task thread's metadata, which the
6980
+ * Agent Server copies into every run on the thread (such as the user's answer).
6981
+ */
6982
+ function launchingAgent(config) {
6983
+ const reference = (config?.configurable ?? {})[PARENT_KEY];
6984
+ if (reference && typeof reference === "object" && !Array.isArray(reference)) return reference;
6985
+ const metadata = config?.metadata ?? {};
6986
+ if (!metadata.parent_thread_id) return null;
6987
+ const fallback = { thread_id: String(metadata.parent_thread_id) };
6988
+ if (metadata.parent_assistant_id) fallback.assistant_id = String(metadata.parent_assistant_id);
6989
+ return fallback;
6990
+ }
6991
+ /** Message field (`additional_kwargs` key) marking a task notification and carrying its {@link TaskEvent}. */
6992
+ const NOTIFICATION_KEY = "deepagents_notification";
6993
+ /** Results longer than this are cut in notifications, matching the limit for large tool results. */
6994
+ const MAX_RESULT_CHARS = 8e4;
6995
+ const NEXT_STEP = {
6996
+ success: "Use the result to continue; report back to the user if they're waiting on it.",
6997
+ error: "Use `check_async_task` for details, then decide whether to retry, try another approach, or tell the user.",
6998
+ timeout: "The task ran too long and was stopped. Decide whether to retry with a smaller task, or tell the user.",
6999
+ cancelled: "The task's run was cancelled before it finished, outside your tools. Decide whether to start it again, or tell the user.",
7000
+ 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."
7001
+ };
7002
+ function textBlock(text) {
7003
+ return {
7004
+ type: "text",
7005
+ text
7006
+ };
7007
+ }
7008
+ /** Escape subagent-controlled text so it can't close the notification's tags and pose as the system. */
7009
+ function escape(text) {
7010
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
7011
+ }
7012
+ function clip(text) {
7013
+ if (text.length <= MAX_RESULT_CHARS) return text;
7014
+ return `${text.slice(0, MAX_RESULT_CHARS)}\n... [cut off; use \`check_async_task\` for the full details]`;
7015
+ }
7016
+ /** Standard content blocks passed on as they are; a notification is a user message, where providers reject the rest. */
7017
+ const MEDIA_BLOCK_TYPES = /* @__PURE__ */ new Set([
7018
+ "image",
7019
+ "audio",
7020
+ "video",
7021
+ "file"
7022
+ ]);
7023
+ /**
7024
+ * The subagent's answer as user content: text escaped and cut when very long, media as it is.
7025
+ *
7026
+ * Reasoning, tool calls and blocks LangChain doesn't recognize are dropped.
7027
+ */
7028
+ function resultBlocks(blocks) {
7029
+ const kept = [];
7030
+ for (const block of blocks) if (block.type === "text") kept.push(textBlock(escape(clip(String(block.text)))));
7031
+ else if (MEDIA_BLOCK_TYPES.has(block.type)) kept.push({ ...block });
7032
+ return kept;
7033
+ }
7034
+ /**
7035
+ * Frame a task update as a system notification the model won't mistake for the user.
7036
+ *
7037
+ * The result keeps its own content blocks, so an image reaches the model as an image.
7038
+ */
7039
+ function notificationContent(update) {
7040
+ const blocks = [notificationHeader(update)];
7041
+ if (update.result) blocks.push(textBlock("<result>\n"), ...resultBlocks(update.result), textBlock("\n</result>\n"));
7042
+ const details = Object.fromEntries(["error", "interrupts"].filter((key) => update[key] !== void 0).map((key) => [key, update[key]]));
7043
+ if (Object.keys(details).length > 0) blocks.push(textBlock(`<details>${escape(clip(JSON.stringify(details)))}</details>\n`));
7044
+ blocks.push(textBlock(`</task-notification>\n${NEXT_STEP[update.status]}`));
7045
+ return blocks;
7046
+ }
7047
+ function notificationHeader(event) {
7048
+ return textBlock(`[SYSTEM NOTIFICATION - NOT USER INPUT]
7049
+ 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.
7050
+ <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`);
7051
+ }
7052
+ /**
7053
+ * Reframe an earlier run's notification so the model doesn't think the queued follow-up finished.
7054
+ *
7055
+ * Only the closing next step changes; the earlier run's result and details stay.
7056
+ */
7057
+ function supersededNotificationContent(message, event) {
7058
+ const content = message.content;
7059
+ const closing = Array.isArray(content) ? content.at(-1) : void 0;
7060
+ 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.")];
7061
+ }
7062
+ /** Describe a failure without its message, which can carry internals into the parent's conversation. */
7063
+ function failureText(error) {
7064
+ return `The subagent failed (${typeof error === "object" && error !== null && "name" in error ? String(error.name) : typeof error}).`;
7065
+ }
7066
+ /** The ID of the run this config belongs to, when the Agent Server set it. */
7067
+ function currentRunId(config) {
7068
+ const metadata = config?.metadata ?? {};
7069
+ const configurable = config?.configurable ?? {};
7070
+ const runId = metadata.run_id ?? configurable.run_id;
7071
+ return runId ? String(runId) : void 0;
7072
+ }
7073
+ /** Build a task update; `details` are the status's `result`, `error` or `interrupts`. */
7074
+ function taskUpdate(event, details = {}) {
7075
+ const update = {
7076
+ task_id: event.task_id,
7077
+ agent_name: event.agent_name,
7078
+ status: event.status,
7079
+ ...details
7080
+ };
7081
+ if (event.run_id) update.run_id = event.run_id;
7082
+ return update;
7083
+ }
7084
+ /** Describe how this run's task ended. */
7085
+ function taskEvent(config, agentName, status, details = {}) {
7086
+ const configurable = config?.configurable ?? {};
7087
+ return taskUpdate({
7088
+ task_id: String(configurable.thread_id ?? ""),
7089
+ agent_name: agentName,
7090
+ status,
7091
+ run_id: currentRunId(config)
7092
+ }, details);
7093
+ }
7094
+ /** The subagent's last message as standard content blocks, the task's result; it may hold images. */
7095
+ function finalContent(values) {
7096
+ const messages = threadMessages(values);
7097
+ if (messages.length === 0) return [{
7098
+ type: "text",
7099
+ text: "(completed with no output messages)"
7100
+ }];
7101
+ const last = messages[messages.length - 1];
7102
+ try {
7103
+ return (0, _langchain_core_messages.coerceMessageLikeToMessage)(last).contentBlocks;
7104
+ } catch {
7105
+ return [{
7106
+ type: "text",
7107
+ text: messageText(last)
7108
+ }];
7109
+ }
7110
+ }
7111
+ /** The task event a notification message carries, or `null` for any other message. */
7112
+ function notificationEvent(message) {
7113
+ const event = message?.additional_kwargs?.[NOTIFICATION_KEY];
7114
+ return event && typeof event === "object" && !Array.isArray(event) ? event : null;
7115
+ }
7116
+ /** A task update as the message the parent's model sees, marked with its {@link TaskEvent} so apps can recognize it. */
7117
+ function notificationMessage(update) {
7118
+ const event = {
7119
+ task_id: update.task_id,
7120
+ agent_name: update.agent_name,
7121
+ status: update.status
7122
+ };
7123
+ if (update.run_id) event.run_id = update.run_id;
7124
+ return {
7125
+ role: "user",
7126
+ content: notificationContent(update),
7127
+ additional_kwargs: { [NOTIFICATION_KEY]: event }
7128
+ };
7129
+ }
7130
+ /** Parent thread statuses a notification run can start on: neither running nor waiting for a human. */
7131
+ const DELIVERABLE_THREAD_STATUSES = /* @__PURE__ */ new Set(["idle", "error"]);
7132
+ /**
7133
+ * Start a notification run on the parent's thread only while it's idle (or its last run failed).
7134
+ *
7135
+ * A run on a thread waiting for a human would cancel that approval. Never throws.
7136
+ */
7137
+ async function awakeParent(parentThreadId, assistantId, update, context) {
7138
+ const client = new _langchain_langgraph_sdk.Client();
7139
+ try {
7140
+ const thread = await client.threads.get(parentThreadId);
7141
+ if (!DELIVERABLE_THREAD_STATUSES.has(thread.status)) return;
7142
+ await client.runs.create(parentThreadId, assistantId, {
7143
+ input: { messages: [notificationMessage(update)] },
7144
+ multitaskStrategy: "reject",
7145
+ ...context ? { context } : {}
7146
+ });
7147
+ } catch {}
7148
+ }
7149
+ /**
7150
+ * Wake the parent if it's idle, with this run's context; otherwise it finds out
7151
+ * on its own. Never throws.
7152
+ */
7153
+ async function notifyParent(config, update, context) {
7154
+ const parent = launchingAgent(config);
7155
+ if (parent?.thread_id && parent.assistant_id) await awakeParent(parent.thread_id, parent.assistant_id, update, forwardedContext(context));
7156
+ }
7157
+ /**
6716
7158
  * Extract the callback thread ID from the tool runtime.
6717
7159
  *
6718
7160
  * The thread ID is included in the subagent's input state so the subagent
@@ -6741,15 +7183,14 @@ function buildStartTool(agentMap, clients, toolDescription) {
6741
7183
  const spec = agentMap[input.agentName];
6742
7184
  const callbackContext = extractCallbackContext(runtime);
6743
7185
  try {
6744
- const client = clients.getClient(input.agentName);
6745
- const thread = await client.threads.create();
6746
- const run = await client.runs.create(thread.thread_id, spec.graphId, { input: {
6747
- messages: [{
6748
- role: "user",
6749
- content: input.description
6750
- }],
6751
- ...callbackContext
6752
- } });
7186
+ const thread = await clients.getClient(input.agentName).threads.create({ metadata: threadMetadata(spec, runtime.config) });
7187
+ const run = await clients.getClient(input.agentName, traceHeaders(spec)).runs.create(thread.thread_id, spec.graphId, {
7188
+ input: {
7189
+ messages: startTaskMessages(spec, runtime.state, input.description),
7190
+ ...callbackContext
7191
+ },
7192
+ ...runOptions(spec, runtime)
7193
+ });
6753
7194
  const taskId = thread.thread_id;
6754
7195
  const task = {
6755
7196
  taskId,
@@ -6789,86 +7230,111 @@ function buildCheckTool(clients) {
6789
7230
  return (0, langchain.tool)(async (input, runtime) => {
6790
7231
  const task = resolveTrackedTask(input.taskId, runtime.state);
6791
7232
  if (typeof task === "string") return task;
6792
- const client = clients.getClient(task.agentName);
6793
7233
  let run;
7234
+ let thread;
6794
7235
  try {
6795
- run = await client.runs.get(task.threadId, task.runId);
7236
+ [run, thread] = await observeTaskRun(clients.getClient(task.agentName), task);
6796
7237
  } catch (e) {
6797
7238
  return `Failed to get run status: ${e}`;
6798
7239
  }
6799
- let threadValues = {};
6800
- if (run.status === "success") try {
6801
- threadValues = (await client.threads.getState(task.threadId)).values || {};
6802
- } catch {}
6803
- const result = buildCheckResult(run, task.threadId, threadValues);
6804
- const updatedTask = {
6805
- taskId: task.taskId,
6806
- agentName: task.agentName,
6807
- threadId: task.threadId,
6808
- runId: task.runId,
6809
- status: result.status,
6810
- createdAt: task.createdAt,
6811
- updatedAt: result.status !== task.status ? (/* @__PURE__ */ new Date()).toISOString() : task.updatedAt,
6812
- checkedAt: (/* @__PURE__ */ new Date()).toISOString()
6813
- };
7240
+ const result = keepCancelled(task, buildCheckResult(run, task.threadId, thread));
7241
+ const updatedTask = observed(task, result.status, run.run_id);
6814
7242
  return new _langchain_langgraph.Command({ update: {
6815
7243
  messages: [new langchain.ToolMessage({
6816
- content: JSON.stringify(result),
7244
+ content: checkOutput(result),
6817
7245
  tool_call_id: toolCallIdFromRuntime(runtime)
6818
7246
  })],
6819
7247
  asyncTasks: { [task.taskId]: updatedTask }
6820
7248
  } });
6821
7249
  }, {
6822
7250
  name: "check_async_task",
6823
- 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.",
7251
+ 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.",
6824
7252
  schema: zod_v4.z.object({ taskId: zod_v4.z.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim.") })
6825
7253
  });
6826
7254
  }
7255
+ /** Confirm an update: queued behind an active run, or started, noting when it dropped a waiting human request. */
7256
+ function updateMessage(tracked, strategy) {
7257
+ if (strategy === "enqueue" && (tracked.status === "running" || tracked.status === "pending")) return `Queued follow-up to async subagent without interrupting its current run. taskId: ${tracked.taskId}`;
7258
+ const msg = `Updated async subagent. taskId: ${tracked.taskId}`;
7259
+ return tracked.status === "waiting" ? `${msg}. It was waiting for a human; that request was dropped.` : msg;
7260
+ }
7261
+ /**
7262
+ * Refuse every queued follow-up to a task after the first in one model turn.
7263
+ *
7264
+ * Parallel calls read the same state, so the task would lose track of all but one.
7265
+ */
7266
+ function parallelUpdateError(taskId, runtime) {
7267
+ if (!((runtime.state.messages ?? []).findLast((m) => _langchain_core_messages.AIMessage.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;
7268
+ 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.`;
7269
+ }
7270
+ /**
7271
+ * The runs a queued follow-up leaves behind it.
7272
+ *
7273
+ * The list grows while the task is unfinished, and otherwise restarts with the tracked run.
7274
+ */
7275
+ function supersededAfterUpdate(tracked) {
7276
+ return [...UNFINISHED_STATUSES.has(tracked.status) ? tracked.supersededRunIds ?? [] : [], tracked.runId];
7277
+ }
7278
+ /** The tracked task after a follow-up created `run`, which may still be queued. */
7279
+ function updatedTask(tracked, run, strategy, message) {
7280
+ const task = {
7281
+ ...tracked,
7282
+ runId: run.run_id,
7283
+ status: "running",
7284
+ description: message,
7285
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
7286
+ };
7287
+ if (strategy === "enqueue") {
7288
+ task.status = run.status;
7289
+ task.supersededRunIds = supersededAfterUpdate(tracked);
7290
+ }
7291
+ return task;
7292
+ }
7293
+ 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.";
7294
+ /** The update tool's description, naming the subagents whose follow-ups queue instead. */
7295
+ function updateToolDescription(agentMap) {
7296
+ const queued = Object.values(agentMap).filter((spec) => spec.updateStrategy === "enqueue").map((spec) => `\`${spec.name}\``);
7297
+ if (queued.length === 0) return UPDATE_TOOL_DESCRIPTION;
7298
+ 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.`;
7299
+ }
6827
7300
  /**
6828
7301
  * Build the `update_async_task` tool.
6829
7302
  *
6830
- * Sends a follow-up message to a running async subagent by creating a new
6831
- * run on the same thread with `multitaskStrategy: "interrupt"`. The subagent
6832
- * sees the full conversation history plus the new message. The `taskId`
6833
- * remains the same; only the internal `runId` is updated.
7303
+ * Sends a follow-up message to an async subagent by creating a new run on the
7304
+ * same thread. The subagent sees the full conversation history plus the new
7305
+ * message. The `taskId` remains the same. The subagent's `updateStrategy`
7306
+ * decides whether the new run interrupts the current run or queues behind it.
6834
7307
  */
6835
7308
  function buildUpdateTool(agentMap, clients) {
6836
7309
  return (0, langchain.tool)(async (input, runtime) => {
6837
7310
  const tracked = resolveTrackedTask(input.taskId, runtime.state);
6838
7311
  if (typeof tracked === "string") return tracked;
6839
7312
  const spec = agentMap[tracked.agentName];
7313
+ const strategy = spec.updateStrategy ?? "interrupt";
7314
+ const refused = strategy === "enqueue" && parallelUpdateError(tracked.taskId, runtime);
7315
+ if (refused) return refused;
6840
7316
  try {
6841
- const run = await clients.getClient(tracked.agentName).runs.create(tracked.threadId, spec.graphId, {
7317
+ const run = await clients.getClient(tracked.agentName, traceHeaders(spec)).runs.create(tracked.threadId, spec.graphId, {
6842
7318
  input: { messages: [{
6843
7319
  role: "user",
6844
7320
  content: input.message
6845
7321
  }] },
6846
- multitaskStrategy: "interrupt"
7322
+ multitaskStrategy: strategy,
7323
+ ...runOptions(spec, runtime)
6847
7324
  });
6848
- const task = {
6849
- taskId: tracked.taskId,
6850
- agentName: tracked.agentName,
6851
- threadId: tracked.threadId,
6852
- runId: run.run_id,
6853
- status: "running",
6854
- createdAt: tracked.createdAt,
6855
- description: input.message,
6856
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
6857
- checkedAt: tracked.checkedAt
6858
- };
6859
7325
  return new _langchain_langgraph.Command({ update: {
6860
7326
  messages: [new langchain.ToolMessage({
6861
- content: `Updated async subagent. taskId: ${tracked.taskId}`,
7327
+ content: updateMessage(tracked, strategy),
6862
7328
  tool_call_id: toolCallIdFromRuntime(runtime)
6863
7329
  })],
6864
- asyncTasks: { [tracked.taskId]: task }
7330
+ asyncTasks: { [tracked.taskId]: updatedTask(tracked, run, strategy, input.message) }
6865
7331
  } });
6866
7332
  } catch (e) {
6867
7333
  return `Failed to update async subagent: ${e}`;
6868
7334
  }
6869
7335
  }, {
6870
7336
  name: "update_async_task",
6871
- 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.",
7337
+ description: updateToolDescription(agentMap),
6872
7338
  schema: zod_v4.z.object({
6873
7339
  taskId: zod_v4.z.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim."),
6874
7340
  message: zod_v4.z.string().describe("Follow-up instructions or context to send to the subagent")
@@ -6876,6 +7342,20 @@ function buildUpdateTool(agentMap, clients) {
6876
7342
  });
6877
7343
  }
6878
7344
  /**
7345
+ * Cancel earlier runs that are still pending or running, newest first.
7346
+ *
7347
+ * Newest first, so a queued run doesn't start when the run ahead of it is cancelled.
7348
+ * A run that can't be read or cancelled is skipped.
7349
+ */
7350
+ async function cancelEarlierRuns(client, task) {
7351
+ for (const runId of [...task.supersededRunIds ?? []].reverse()) try {
7352
+ const run = await client.runs.get(task.threadId, runId);
7353
+ if (run.status === "running" || run.status === "pending") await client.runs.cancel(task.threadId, runId);
7354
+ } catch (e) {
7355
+ console.warn(`Failed to cancel earlier run ${runId} of task ${task.taskId}:`, e);
7356
+ }
7357
+ }
7358
+ /**
6879
7359
  * Build the `cancel_async_task` tool.
6880
7360
  *
6881
7361
  * Cancels the current run on the remote server and updates the task's
@@ -6885,21 +7365,17 @@ function buildCancelTool(clients) {
6885
7365
  return (0, langchain.tool)(async (input, runtime) => {
6886
7366
  const tracked = resolveTrackedTask(input.taskId, runtime.state);
6887
7367
  if (typeof tracked === "string") return tracked;
6888
- const client = clients.getClient(tracked.agentName);
6889
- try {
7368
+ if (tracked.status !== "waiting") try {
7369
+ const client = clients.getClient(tracked.agentName);
6890
7370
  await client.runs.cancel(tracked.threadId, tracked.runId);
7371
+ await cancelEarlierRuns(client, tracked);
6891
7372
  } catch (e) {
6892
7373
  return `Failed to cancel run: ${e}`;
6893
7374
  }
6894
7375
  const updated = {
6895
- taskId: tracked.taskId,
6896
- agentName: tracked.agentName,
6897
- threadId: tracked.threadId,
6898
- runId: tracked.runId,
7376
+ ...tracked,
6899
7377
  status: "cancelled",
6900
- createdAt: tracked.createdAt,
6901
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
6902
- checkedAt: tracked.checkedAt
7378
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
6903
7379
  };
6904
7380
  return new _langchain_langgraph.Command({ update: {
6905
7381
  messages: [new langchain.ToolMessage({
@@ -6910,7 +7386,7 @@ function buildCancelTool(clients) {
6910
7386
  } });
6911
7387
  }, {
6912
7388
  name: "cancel_async_task",
6913
- description: "Cancel a running async subagent task. Use this to stop a task that is no longer needed.",
7389
+ description: "Cancel a running, pending, or waiting async subagent task. Use this to stop a task that is no longer needed.",
6914
7390
  schema: zod_v4.z.object({ taskId: zod_v4.z.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim.") })
6915
7391
  });
6916
7392
  }
@@ -6924,24 +7400,14 @@ function buildListTool(clients) {
6924
7400
  return (0, langchain.tool)(async (input, runtime) => {
6925
7401
  const filtered = filterTasks(runtime.state.asyncTasks ?? {}, input.statusFilter ?? void 0);
6926
7402
  if (filtered.length === 0) return "No async subagent tasks tracked";
6927
- const statuses = await Promise.all(filtered.map((task) => fetchLiveTaskStatus(clients, task)));
7403
+ const live = await Promise.all(filtered.map((task) => fetchLiveTaskStatus(clients, task)));
6928
7404
  const updatedTasks = {};
6929
7405
  const entries = [];
6930
7406
  for (let idx = 0; idx < filtered.length; idx++) {
6931
7407
  const task = filtered[idx];
6932
- const status = statuses[idx];
6933
- const taskEntry = formatTaskEntry(task, status);
6934
- entries.push(taskEntry);
6935
- updatedTasks[task.taskId] = {
6936
- taskId: task.taskId,
6937
- agentName: task.agentName,
6938
- threadId: task.threadId,
6939
- runId: task.runId,
6940
- status,
6941
- createdAt: task.createdAt,
6942
- updatedAt: status !== task.status ? (/* @__PURE__ */ new Date()).toISOString() : task.updatedAt,
6943
- checkedAt: task.checkedAt
6944
- };
7408
+ const [status, runId] = live[idx];
7409
+ entries.push(formatTaskEntry(task, status));
7410
+ updatedTasks[task.taskId] = observed(task, status, runId);
6945
7411
  }
6946
7412
  return new _langchain_langgraph.Command({ update: {
6947
7413
  messages: [new langchain.ToolMessage({
@@ -6952,10 +7418,107 @@ function buildListTool(clients) {
6952
7418
  } });
6953
7419
  }, {
6954
7420
  name: "list_async_tasks",
6955
- 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.",
6956
- schema: zod_v4.z.object({ statusFilter: zod_v4.z.string().nullish().describe("Filter tasks by status. One of: 'running', 'success', 'error', 'cancelled', 'all'. Defaults to 'all'.") })
7421
+ 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.",
7422
+ schema: zod_v4.z.object({ statusFilter: zod_v4.z.string().nullish().describe("Filter tasks by status. One of: 'running', 'pending', 'waiting', 'success', 'error', 'cancelled', 'all'. Defaults to 'all'.") })
6957
7423
  });
6958
7424
  }
7425
+ /** The notification for a task outcome a check found, or `null` for outcomes not worth waking for. */
7426
+ function checkEvent(task, run, thread, status) {
7427
+ if (!NOTIFIED_STATUSES.has(status)) return null;
7428
+ const result = buildCheckResult(run, task.threadId, thread);
7429
+ const details = {};
7430
+ if (result.interrupts) details.interrupts = result.interrupts;
7431
+ if (status === "success") details.result = result.result;
7432
+ if (status === "error") details.error = "The subagent failed.";
7433
+ return taskUpdate({
7434
+ task_id: task.taskId,
7435
+ agent_name: task.agentName,
7436
+ status,
7437
+ run_id: run.run_id ?? task.runId
7438
+ }, details);
7439
+ }
7440
+ /** Task outcomes that notify the parent. */
7441
+ const NOTIFIED_STATUSES = /* @__PURE__ */ new Set([
7442
+ "success",
7443
+ "error",
7444
+ "timeout",
7445
+ "cancelled",
7446
+ "waiting"
7447
+ ]);
7448
+ /** How long the parent waits on one task's status before skipping it until the next check. */
7449
+ const PULL_TIMEOUT_MS = 5e3;
7450
+ /** Tracked task statuses that can still change, so the parent checks them for status updates. */
7451
+ const UNFINISHED_STATUSES = /* @__PURE__ */ new Set([
7452
+ "running",
7453
+ "pending",
7454
+ "waiting"
7455
+ ]);
7456
+ /** Observe a task, or `null` when it can't be checked in time; it's checked again next time. */
7457
+ async function observeTask(clients, task) {
7458
+ try {
7459
+ return await observeTaskRun(clients.getClient(task.agentName), task, AbortSignal.timeout(PULL_TIMEOUT_MS));
7460
+ } catch (e) {
7461
+ console.warn(`Failed to check task ${task.taskId}:`, e);
7462
+ return null;
7463
+ }
7464
+ }
7465
+ /**
7466
+ * Check unfinished tasks; return their updated records and a notification per new outcome.
7467
+ *
7468
+ * Outcomes the agent already saw aren't reported again; a task that can't be
7469
+ * checked is skipped until the next check.
7470
+ */
7471
+ async function pull(clients, tasks) {
7472
+ const unfinished = Object.values(tasks).filter((task) => UNFINISHED_STATUSES.has(task.status));
7473
+ const found = await Promise.all(unfinished.map((task) => observeTask(clients, task)));
7474
+ const records = {};
7475
+ const messages = [];
7476
+ unfinished.forEach((task, idx) => {
7477
+ if (found[idx] === null) return;
7478
+ const [run, thread] = found[idx];
7479
+ const status = taskStatus(run, thread);
7480
+ if (status === task.status && run.run_id === task.runId) return;
7481
+ records[task.taskId] = observed(task, status, run.run_id);
7482
+ const event = status !== task.status ? checkEvent(task, run, thread, status) : null;
7483
+ if (event) messages.push((0, _langchain_core_messages.coerceMessageLikeToMessage)(notificationMessage(event)));
7484
+ });
7485
+ const update = {};
7486
+ if (Object.keys(records).length > 0) update.asyncTasks = records;
7487
+ if (messages.length > 0) update.messages = messages;
7488
+ return update;
7489
+ }
7490
+ /**
7491
+ * When a task notification started this run, record the task's outcome so checks don't report it again.
7492
+ *
7493
+ * A notification from an earlier run that a queued follow-up replaced is rewritten
7494
+ * instead, so the model doesn't take it as the task's outcome.
7495
+ */
7496
+ function recordNotification(messages, tasks) {
7497
+ const last = messages[messages.length - 1];
7498
+ const event = notificationEvent(last);
7499
+ const task = event ? tasks[event.task_id] : void 0;
7500
+ if (!event || !task || task.status === "cancelled") return {};
7501
+ const runId = event.run_id ?? task.runId;
7502
+ if (task.supersededRunIds?.includes(runId)) {
7503
+ const content = supersededNotificationContent(last, event);
7504
+ return { messages: [new _langchain_core_messages.HumanMessage({
7505
+ id: last.id,
7506
+ content,
7507
+ additional_kwargs: last.additional_kwargs
7508
+ })] };
7509
+ }
7510
+ if (runId !== task.runId && !UNFINISHED_STATUSES.has(task.status)) return {};
7511
+ return { asyncTasks: { [task.taskId]: observed(task, event.status, runId) } };
7512
+ }
7513
+ /** The tasks tracked in state; the state schema stores `status` as a plain string. */
7514
+ function trackedTasks(state) {
7515
+ return state.asyncTasks ?? {};
7516
+ }
7517
+ /** Whether the last message is a final answer: an AI message with no tool calls. */
7518
+ function isFinalAnswer(messages) {
7519
+ const last = messages[messages.length - 1];
7520
+ return last !== void 0 && !last.tool_calls?.length;
7521
+ }
6959
7522
  /**
6960
7523
  * Create middleware that adds async subagent tools to an agent.
6961
7524
  *
@@ -6967,6 +7530,11 @@ function buildListTool(clients) {
6967
7530
  * Works with any Agent Protocol-compliant server — LangGraph Platform (managed)
6968
7531
  * or self-hosted (e.g. a Hono/Express server implementing the Agent Protocol spec).
6969
7532
  *
7533
+ * On an Agent Server, the agent is told when its tasks finish, fail or wait for
7534
+ * the user: by checking while it runs, and through a new run when it's idle.
7535
+ *
7536
+ * @experimental Task notifications are experimental and subject to change.
7537
+ *
6970
7538
  * @throws {Error} If no async subagents are provided or names are duplicated.
6971
7539
  *
6972
7540
  * @example
@@ -6996,9 +7564,15 @@ function createAsyncSubAgentMiddleware(options) {
6996
7564
  const names = asyncSubAgents.map((a) => a.name);
6997
7565
  const duplicates = names.filter((n, i) => names.indexOf(n) !== i);
6998
7566
  if (duplicates.length > 0) throw new Error(`Duplicate async subagent names: ${[...new Set(duplicates)].join(", ")}`);
7567
+ for (const spec of asyncSubAgents) {
7568
+ const strategy = spec.updateStrategy ?? "interrupt";
7569
+ if (strategy !== "interrupt" && strategy !== "enqueue") throw new Error(`AsyncSubAgent '${spec.name}' has invalid updateStrategy '${strategy}'; expected 'interrupt' or 'enqueue'`);
7570
+ const mode = spec.mode ?? "isolated";
7571
+ if (mode !== "isolated" && mode !== "fork") throw new Error(`AsyncSubAgent '${spec.name}' has invalid mode '${mode}'; expected 'isolated' or 'fork'`);
7572
+ }
6999
7573
  const agentMap = Object.fromEntries(asyncSubAgents.map((a) => [a.name, a]));
7000
7574
  const clients = new ClientCache(agentMap);
7001
- const agentsDescription = asyncSubAgents.map((a) => `- ${a.name}: ${a.description}`).join("\n");
7575
+ const agentsDescription = asyncSubAgents.map(describeAsyncSubAgent).join("\n");
7002
7576
  const tools = [
7003
7577
  buildStartTool(agentMap, clients, ASYNC_TASK_TOOL_DESCRIPTION.replace("{available_agents}", agentsDescription)),
7004
7578
  buildCheckTool(clients),
@@ -7011,6 +7585,41 @@ function createAsyncSubAgentMiddleware(options) {
7011
7585
  name: "asyncSubAgentMiddleware",
7012
7586
  stateSchema: AsyncTaskStateSchema,
7013
7587
  tools,
7588
+ beforeAgent: async (state) => {
7589
+ const messages = state.messages ?? [];
7590
+ const tasks = trackedTasks(state);
7591
+ const recorded = recordNotification(messages, tasks);
7592
+ const updates = await pull(clients, {
7593
+ ...tasks,
7594
+ ...recorded.asyncTasks
7595
+ });
7596
+ const asyncTasks = {
7597
+ ...recorded.asyncTasks,
7598
+ ...updates.asyncTasks
7599
+ };
7600
+ const notes = [...recorded.messages ?? [], ...updates.messages ?? []];
7601
+ if (Object.keys(asyncTasks).length === 0 && notes.length === 0) return;
7602
+ return {
7603
+ asyncTasks,
7604
+ ...notes.length > 0 && { messages: notes }
7605
+ };
7606
+ },
7607
+ beforeModel: async (state) => {
7608
+ const updates = await pull(clients, trackedTasks(state));
7609
+ return Object.keys(updates).length > 0 ? updates : void 0;
7610
+ },
7611
+ afterModel: {
7612
+ canJumpTo: ["model"],
7613
+ hook: async (state) => {
7614
+ if (!isFinalAnswer(state.messages ?? [])) return;
7615
+ const updates = await pull(clients, trackedTasks(state));
7616
+ if (!updates.messages) return Object.keys(updates).length > 0 ? updates : void 0;
7617
+ return {
7618
+ ...updates,
7619
+ jumpTo: "model"
7620
+ };
7621
+ }
7622
+ },
7014
7623
  wrapModelCall: async (request, handler) => {
7015
7624
  if (fullSystemPrompt !== null) return handler({
7016
7625
  ...request,
@@ -7071,6 +7680,53 @@ function createCacheBreakpointMiddleware() {
7071
7680
  });
7072
7681
  }
7073
7682
  //#endregion
7683
+ //#region src/middleware/parent_notifier.ts
7684
+ /** Whether this is the outermost graph of a task run, not a graph nested in it. */
7685
+ function isTopLevelGraph(config) {
7686
+ const configurable = config.configurable ?? {};
7687
+ return !String(configurable.checkpoint_ns ?? "").includes("|");
7688
+ }
7689
+ /** Whether `error` comes from the run being aborted rather than from the subagent failing. */
7690
+ function wasAborted(error, signal) {
7691
+ return signal?.aborted === true || (0, _langchain_langgraph.getConfig)()?.signal?.aborted === true || typeof error === "object" && error !== null && error.name === "AbortError";
7692
+ }
7693
+ /**
7694
+ * Wake the agent that started this run with `start_async_task`, when the run ends.
7695
+ *
7696
+ * `createDeepAgent` attaches it to every deep agent. It does nothing unless the
7697
+ * run carries the parent reference, and skips nested runs.
7698
+ */
7699
+ function createParentNotifierMiddleware() {
7700
+ /**
7701
+ * Notify for this graph's own run that an async subagent tool started.
7702
+ *
7703
+ * The run's context comes from its config: hooks only see the context fields
7704
+ * a middleware's `contextSchema` declares, and this one declares none.
7705
+ */
7706
+ async function report(status, details) {
7707
+ const config = (0, _langchain_langgraph.getConfig)();
7708
+ if (!launchingAgent(config) || !isTopLevelGraph(config)) return;
7709
+ if (currentRunId(config) === void 0) return;
7710
+ const metadata = config.metadata ?? {};
7711
+ const configurable = config.configurable ?? {};
7712
+ await notifyParent(config, taskEvent(config, String(metadata.subagent_name ?? metadata.graph_id ?? configurable.graph_id ?? "subagent"), status, details), config.context);
7713
+ }
7714
+ return (0, langchain.createMiddleware)({
7715
+ name: "parentNotifierMiddleware",
7716
+ afterAgent: async (state) => {
7717
+ await report("success", { result: finalContent(state) });
7718
+ },
7719
+ wrapModelCall: async (request, handler) => {
7720
+ try {
7721
+ return await handler(request);
7722
+ } catch (e) {
7723
+ if (!(0, _langchain_langgraph.isGraphBubbleUp)(e) && !wasAborted(e, request.runtime.signal)) await report("error", { error: failureText(e) });
7724
+ throw e;
7725
+ }
7726
+ }
7727
+ });
7728
+ }
7729
+ //#endregion
7074
7730
  //#region src/middleware/tool_exclusion.ts
7075
7731
  function hasToolName(tool) {
7076
7732
  return tool !== null && typeof tool === "object" && "name" in tool && typeof tool.name === "string";
@@ -7976,6 +8632,7 @@ function createDeepAgent(params = {}) {
7976
8632
  createPatchToolCallsMiddleware()
7977
8633
  ];
7978
8634
  let middleware = mergeMiddlewareStack([
8635
+ createParentNotifierMiddleware(),
7979
8636
  fsMiddleware,
7980
8637
  subagentMiddleware,
7981
8638
  summarizationMiddleware,
@@ -10486,4 +11143,4 @@ Object.defineProperty(exports, "skillsMetadataValue", {
10486
11143
  }
10487
11144
  });
10488
11145
 
10489
- //# sourceMappingURL=langsmith-IOLMJEwi.cjs.map
11146
+ //# sourceMappingURL=langsmith-Bf4pcnIO.cjs.map