deepagents 1.15.1 → 1.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-CYPLa3Vi.d.cts → agent-BErEClzV.d.cts} +111 -11
- package/dist/{agent-uMkCMHJp.d.ts → agent-DIft4yNY.d.ts} +111 -11
- package/dist/browser.cjs +1 -1
- package/dist/browser.d.cts +2 -2
- package/dist/browser.d.ts +2 -2
- package/dist/browser.js +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/{langsmith-C-EMyQJ_.js → langsmith-B1pbrx3y.js} +855 -135
- package/dist/langsmith-B1pbrx3y.js.map +1 -0
- package/dist/{langsmith-IOLMJEwi.cjs → langsmith-aH3Gwzii.cjs} +853 -133
- package/dist/langsmith-aH3Gwzii.cjs.map +1 -0
- package/dist/node.cjs +2 -2
- package/dist/node.d.cts +2 -2
- package/dist/node.d.ts +2 -2
- package/dist/node.js +2 -2
- package/dist/{src-BTEsBZdJ.js → src-B1Lvbh_S.js} +2 -2
- package/dist/{src-BTEsBZdJ.js.map → src-B1Lvbh_S.js.map} +1 -1
- package/dist/{src-a_7jVcCL.cjs → src-B2jjteSM.cjs} +2 -2
- package/dist/{src-a_7jVcCL.cjs.map → src-B2jjteSM.cjs.map} +1 -1
- package/package.json +1 -1
- package/dist/langsmith-C-EMyQJ_.js.map +0 -1
- package/dist/langsmith-IOLMJEwi.cjs.map +0 -1
|
@@ -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
|
|
@@ -807,6 +808,45 @@ function trimTrailingSlashes$2(path) {
|
|
|
807
808
|
}
|
|
808
809
|
const PREGEL_SEND_KEY = "__pregel_send";
|
|
809
810
|
const PREGEL_READ_KEY = "__pregel_read";
|
|
811
|
+
function isBase64Encoded(data) {
|
|
812
|
+
return !isFileDataV1(data) && data.encoding === "base64" && typeof data.content === "string";
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* Store binary content as base64 text. State is checkpointed as JSON, which
|
|
816
|
+
* turns a Uint8Array into an object of numeric keys that fails the files
|
|
817
|
+
* schema on the next run.
|
|
818
|
+
*/
|
|
819
|
+
function toStoredFileData(data) {
|
|
820
|
+
if (!isFileDataBinary(data)) return data;
|
|
821
|
+
return {
|
|
822
|
+
...data,
|
|
823
|
+
content: Buffer.from(data.content).toString("base64"),
|
|
824
|
+
encoding: "base64"
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
/** Decode base64-stored content so readers keep getting Uint8Array bytes. */
|
|
828
|
+
function fromStoredFileData(data) {
|
|
829
|
+
if (!isBase64Encoded(data)) return data;
|
|
830
|
+
return {
|
|
831
|
+
content: new Uint8Array(Buffer.from(data.content, "base64")),
|
|
832
|
+
mimeType: data.mimeType,
|
|
833
|
+
created_at: data.created_at,
|
|
834
|
+
modified_at: data.modified_at
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
function fileSize(data) {
|
|
838
|
+
if (isFileDataV1(data)) return data.content.join("\n").length;
|
|
839
|
+
if (typeof data.content !== "string") return data.content.byteLength;
|
|
840
|
+
return data.encoding === "base64" ? Buffer.byteLength(data.content, "base64") : data.content.length;
|
|
841
|
+
}
|
|
842
|
+
/** Strict UTF-8 decode; undefined when the bytes are not valid UTF-8. */
|
|
843
|
+
function decodeUtf8(bytes) {
|
|
844
|
+
try {
|
|
845
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
846
|
+
} catch {
|
|
847
|
+
return;
|
|
848
|
+
}
|
|
849
|
+
}
|
|
810
850
|
/**
|
|
811
851
|
* Backend that stores files in agent state (ephemeral).
|
|
812
852
|
*
|
|
@@ -894,11 +934,10 @@ var StateBackend = class {
|
|
|
894
934
|
subdirs.add(normalizedPath + subdirName + "/");
|
|
895
935
|
continue;
|
|
896
936
|
}
|
|
897
|
-
const size = isFileDataV1(fd) ? fd.content.join("\n").length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length;
|
|
898
937
|
infos.push({
|
|
899
938
|
path: k,
|
|
900
939
|
is_dir: false,
|
|
901
|
-
size,
|
|
940
|
+
size: fileSize(fd),
|
|
902
941
|
modified_at: fd.modified_at
|
|
903
942
|
});
|
|
904
943
|
}
|
|
@@ -925,7 +964,7 @@ var StateBackend = class {
|
|
|
925
964
|
read(filePath, offset = 0, limit = 500) {
|
|
926
965
|
const fileData = this.files[filePath];
|
|
927
966
|
if (!fileData) return { error: `File '${filePath}' not found` };
|
|
928
|
-
const fileDataV2 = migrateToFileDataV2(fileData, filePath);
|
|
967
|
+
const fileDataV2 = migrateToFileDataV2(fromStoredFileData(fileData), filePath);
|
|
929
968
|
if (!isTextMimeType(fileDataV2.mimeType)) return {
|
|
930
969
|
content: fileDataV2.content,
|
|
931
970
|
mimeType: fileDataV2.mimeType
|
|
@@ -958,15 +997,19 @@ var StateBackend = class {
|
|
|
958
997
|
readRaw(filePath) {
|
|
959
998
|
const fileData = this.files[filePath];
|
|
960
999
|
if (!fileData) return { error: `File '${filePath}' not found` };
|
|
961
|
-
return { data: fileData };
|
|
1000
|
+
return { data: fromStoredFileData(fileData) };
|
|
962
1001
|
}
|
|
963
1002
|
/**
|
|
964
1003
|
* Write content to a file, creating it or overwriting it if it already exists.
|
|
965
1004
|
* Returns WriteResult with filesUpdate to update LangGraph state.
|
|
966
1005
|
*/
|
|
967
1006
|
write(filePath, content) {
|
|
968
|
-
const
|
|
969
|
-
const
|
|
1007
|
+
const stored = this.files[filePath];
|
|
1008
|
+
const existing = stored && isBase64Encoded(stored) ? {
|
|
1009
|
+
...stored,
|
|
1010
|
+
mimeType: getMimeType(filePath)
|
|
1011
|
+
} : stored;
|
|
1012
|
+
const newFileData = toStoredFileData(createWriteFileData(filePath, content, this.fileFormat, existing));
|
|
970
1013
|
const update = { [filePath]: newFileData };
|
|
971
1014
|
if (!this.isLegacy) {
|
|
972
1015
|
this.sendFilesUpdate(update);
|
|
@@ -1005,7 +1048,7 @@ var StateBackend = class {
|
|
|
1005
1048
|
edit(filePath, oldString, newString, replaceAll = false) {
|
|
1006
1049
|
const fileData = this.files[filePath];
|
|
1007
1050
|
if (!fileData) return { error: `Error: File '${filePath}' not found` };
|
|
1008
|
-
const result = performStringReplacement(fileDataToString(fileData), oldString, newString, replaceAll);
|
|
1051
|
+
const result = performStringReplacement(fileDataToString(fromStoredFileData(fileData)), oldString, newString, replaceAll);
|
|
1009
1052
|
if (typeof result === "string") return { error: result };
|
|
1010
1053
|
const [newContent, occurrences] = result;
|
|
1011
1054
|
const newFileData = updateFileData(fileData, newContent);
|
|
@@ -1045,11 +1088,10 @@ var StateBackend = class {
|
|
|
1045
1088
|
const infos = [];
|
|
1046
1089
|
for (const p of paths) {
|
|
1047
1090
|
const fd = files[p];
|
|
1048
|
-
const size = fd ? isFileDataV1(fd) ? fd.content.join("\n").length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length : 0;
|
|
1049
1091
|
infos.push({
|
|
1050
1092
|
path: p,
|
|
1051
1093
|
is_dir: false,
|
|
1052
|
-
size,
|
|
1094
|
+
size: fd ? fileSize(fd) : 0,
|
|
1053
1095
|
modified_at: fd?.modified_at || ""
|
|
1054
1096
|
});
|
|
1055
1097
|
}
|
|
@@ -1068,9 +1110,7 @@ var StateBackend = class {
|
|
|
1068
1110
|
const responses = [];
|
|
1069
1111
|
const updates = {};
|
|
1070
1112
|
for (const [path, content] of files) try {
|
|
1071
|
-
|
|
1072
|
-
if (this.fileFormat === "v2" && !isTextMimeType(mimeType)) updates[path] = createFileData(content, void 0, "v2", mimeType);
|
|
1073
|
-
else updates[path] = createFileData(new TextDecoder().decode(content), void 0, this.fileFormat, mimeType);
|
|
1113
|
+
updates[path] = toStoredFileData(this.createUploadFileData(path, content));
|
|
1074
1114
|
responses.push({
|
|
1075
1115
|
path,
|
|
1076
1116
|
error: null
|
|
@@ -1090,6 +1130,20 @@ var StateBackend = class {
|
|
|
1090
1130
|
return result;
|
|
1091
1131
|
}
|
|
1092
1132
|
/**
|
|
1133
|
+
* Build FileData for an uploaded file.
|
|
1134
|
+
*
|
|
1135
|
+
* In v2, bytes at a binary MIME type stay binary, and bytes at a text MIME
|
|
1136
|
+
* type that are not valid UTF-8 are kept as application/octet-stream rather
|
|
1137
|
+
* than lossily decoded. v1 cannot hold binary, so it always decodes as text.
|
|
1138
|
+
*/
|
|
1139
|
+
createUploadFileData(path, content) {
|
|
1140
|
+
const mimeType = getMimeType(path);
|
|
1141
|
+
if (this.fileFormat === "v1") return createFileData(new TextDecoder().decode(content), void 0, "v1", mimeType);
|
|
1142
|
+
if (!isTextMimeType(mimeType)) return createFileData(content, void 0, "v2", mimeType);
|
|
1143
|
+
const text = decodeUtf8(content);
|
|
1144
|
+
return text === void 0 ? createFileData(content, void 0, "v2", "application/octet-stream") : createFileData(text, void 0, "v2", mimeType);
|
|
1145
|
+
}
|
|
1146
|
+
/**
|
|
1093
1147
|
* Download multiple files.
|
|
1094
1148
|
*
|
|
1095
1149
|
* @param paths - List of file paths to download
|
|
@@ -1108,7 +1162,7 @@ var StateBackend = class {
|
|
|
1108
1162
|
});
|
|
1109
1163
|
continue;
|
|
1110
1164
|
}
|
|
1111
|
-
const fileDataV2 = migrateToFileDataV2(fileData, path);
|
|
1165
|
+
const fileDataV2 = migrateToFileDataV2(fromStoredFileData(fileData), path);
|
|
1112
1166
|
if (typeof fileDataV2.content === "string") {
|
|
1113
1167
|
const content = new TextEncoder().encode(fileDataV2.content);
|
|
1114
1168
|
responses.push({
|
|
@@ -1444,6 +1498,14 @@ async function hydrateMessages(messages, backend, prefix, cache) {
|
|
|
1444
1498
|
}
|
|
1445
1499
|
return restorePayloads(messages, payloads);
|
|
1446
1500
|
}
|
|
1501
|
+
/**
|
|
1502
|
+
* Replace each blob reference in `messages` with a notice that the content is
|
|
1503
|
+
* unavailable, for an agent that can't load blobs, so the model still accepts
|
|
1504
|
+
* the request.
|
|
1505
|
+
*/
|
|
1506
|
+
function withoutBlobRefs(messages) {
|
|
1507
|
+
return messages.some(messageHasRefs) ? restorePayloads(messages, /* @__PURE__ */ new Map()) : messages;
|
|
1508
|
+
}
|
|
1447
1509
|
//#endregion
|
|
1448
1510
|
//#region src/middleware/unsupportedContent.ts
|
|
1449
1511
|
const PDF_MIME_TYPE = "application/pdf";
|
|
@@ -2343,30 +2405,39 @@ function extractTextFromMessage(message) {
|
|
|
2343
2405
|
if (Array.isArray(message.content)) return message.content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
|
|
2344
2406
|
return String(message.content);
|
|
2345
2407
|
}
|
|
2408
|
+
/**
|
|
2409
|
+
* Whether a content block is an image. Tool-result eviction skips images when
|
|
2410
|
+
* sizing a result and keeps them when evicting it: base64 length says little
|
|
2411
|
+
* about what a provider charges for an image.
|
|
2412
|
+
*/
|
|
2413
|
+
function isImageBlock(block) {
|
|
2414
|
+
return typeof block === "object" && block !== null && "type" in block && (block.type === "image" || block.type === "image_url");
|
|
2415
|
+
}
|
|
2346
2416
|
function stringifyToolContent(content) {
|
|
2347
2417
|
if (typeof content === "string") return content;
|
|
2348
|
-
if (Array.isArray(content)) return content.map((block) => {
|
|
2418
|
+
if (Array.isArray(content)) return content.filter((block) => !isImageBlock(block)).map((block) => {
|
|
2349
2419
|
if (typeof block === "object" && block !== null && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string") return block.text;
|
|
2350
2420
|
return JSON.stringify(block);
|
|
2351
2421
|
}).join("\n");
|
|
2352
2422
|
return String(content);
|
|
2353
2423
|
}
|
|
2354
2424
|
/**
|
|
2355
|
-
* Build replacement content for an evicted
|
|
2425
|
+
* Build replacement content for an evicted message, preserving the blocks `keep` selects.
|
|
2356
2426
|
*
|
|
2357
2427
|
* For plain string content, returns the replacement text directly. For list content
|
|
2358
|
-
* with mixed block types (e.g., text + image), replaces
|
|
2359
|
-
* text block containing the replacement text while keeping
|
|
2428
|
+
* with mixed block types (e.g., text + image), replaces the other blocks with a single
|
|
2429
|
+
* text block containing the replacement text while keeping the selected blocks intact.
|
|
2430
|
+
* By default every non-text block is kept.
|
|
2360
2431
|
*/
|
|
2361
|
-
function
|
|
2432
|
+
function buildEvictedContent(message, replacementText, keep = (block) => block.type !== "text") {
|
|
2362
2433
|
if (typeof message.content === "string") return replacementText;
|
|
2363
2434
|
if (Array.isArray(message.content)) {
|
|
2364
|
-
const
|
|
2365
|
-
if (
|
|
2435
|
+
const keptBlocks = message.content.filter((block) => typeof block === "object" && block !== null && keep(block));
|
|
2436
|
+
if (keptBlocks.length === 0) return replacementText;
|
|
2366
2437
|
return [{
|
|
2367
2438
|
type: "text",
|
|
2368
2439
|
text: replacementText
|
|
2369
|
-
}, ...
|
|
2440
|
+
}, ...keptBlocks];
|
|
2370
2441
|
}
|
|
2371
2442
|
return replacementText;
|
|
2372
2443
|
}
|
|
@@ -2379,7 +2450,7 @@ function buildEvictedHumanContent(message, replacementText) {
|
|
|
2379
2450
|
*/
|
|
2380
2451
|
function buildTruncatedHumanMessage(message, filePath) {
|
|
2381
2452
|
const contentSample = createContentPreview(extractTextFromMessage(message));
|
|
2382
|
-
const evictedContent =
|
|
2453
|
+
const evictedContent = buildEvictedContent(message, TOO_LARGE_HUMAN_MSG.replace("{file_path}", filePath).replace("{content_sample}", contentSample));
|
|
2383
2454
|
return new HumanMessage({
|
|
2384
2455
|
content: evictedContent,
|
|
2385
2456
|
id: message.id,
|
|
@@ -2419,6 +2490,7 @@ const FileDataV1Schema = z.object({
|
|
|
2419
2490
|
const FileDataV2Schema = z.object({
|
|
2420
2491
|
content: z.union([z.string(), z.instanceof(Uint8Array)]),
|
|
2421
2492
|
mimeType: z.string(),
|
|
2493
|
+
encoding: z.enum(["utf-8", "base64"]).optional(),
|
|
2422
2494
|
created_at: z.string(),
|
|
2423
2495
|
modified_at: z.string()
|
|
2424
2496
|
});
|
|
@@ -3305,7 +3377,7 @@ function createFilesystemMiddleware(options = {}) {
|
|
|
3305
3377
|
const replacementText = writeResult.error ? `Tool result too large, but the result could not be saved to the filesystem: ${writeResult.error}` : TOO_LARGE_TOOL_MSG.replace("{tool_call_id}", msg.tool_call_id.length > 32 ? `${msg.tool_call_id.slice(0, 32)}...` : msg.tool_call_id).replace("{file_path}", evictPath).replace("{content_sample}", contentSample);
|
|
3306
3378
|
return {
|
|
3307
3379
|
message: new ToolMessage({
|
|
3308
|
-
content: replacementText,
|
|
3380
|
+
content: buildEvictedContent(msg, replacementText, isImageBlock),
|
|
3309
3381
|
tool_call_id: msg.tool_call_id,
|
|
3310
3382
|
name: msg.name,
|
|
3311
3383
|
id: msg.id,
|
|
@@ -3372,7 +3444,7 @@ function createFilesystemMiddleware(options = {}) {
|
|
|
3372
3444
|
pending: []
|
|
3373
3445
|
}, resolvedBackend, BLOBS_PREFIX, blobCache);
|
|
3374
3446
|
messages = await hydrateMessages(messages, resolvedBackend, BLOBS_PREFIX, blobCache);
|
|
3375
|
-
}
|
|
3447
|
+
} else if (messages) messages = withoutBlobRefs(messages);
|
|
3376
3448
|
const finalRequest = {
|
|
3377
3449
|
...request,
|
|
3378
3450
|
tools,
|
|
@@ -6239,6 +6311,9 @@ function createSkillsMiddleware(options) {
|
|
|
6239
6311
|
*
|
|
6240
6312
|
* @experimental - this middleware is experimental and may change in future releases.
|
|
6241
6313
|
*
|
|
6314
|
+
* @deprecated `createDeepAgent` now notifies the launching agent on its own;
|
|
6315
|
+
* adding this middleware too sends the parent two notifications per task.
|
|
6316
|
+
*
|
|
6242
6317
|
* This middleware sends a notification to a callback thread when a subagent
|
|
6243
6318
|
* completes successfully or raises an error. The callback agent can then
|
|
6244
6319
|
* process that notification instead of relying only on polling via
|
|
@@ -6347,7 +6422,7 @@ function resolveHeaders(headers) {
|
|
|
6347
6422
|
* @param message - The message content to send.
|
|
6348
6423
|
* @param options - Optional url and headers for the callback server.
|
|
6349
6424
|
*/
|
|
6350
|
-
async function notifyParent(callbackGraphId, callbackThreadId, message, options) {
|
|
6425
|
+
async function notifyParent$1(callbackGraphId, callbackThreadId, message, options) {
|
|
6351
6426
|
try {
|
|
6352
6427
|
await new Client({
|
|
6353
6428
|
apiUrl: options?.url ?? void 0,
|
|
@@ -6398,6 +6473,9 @@ function extractLastMessage(state, taskId) {
|
|
|
6398
6473
|
* If `callbackThreadId` is not present in state, the middleware does
|
|
6399
6474
|
* nothing.
|
|
6400
6475
|
*
|
|
6476
|
+
* @deprecated `createDeepAgent` now notifies the launching agent on its own;
|
|
6477
|
+
* adding this middleware too sends the parent two notifications per task.
|
|
6478
|
+
*
|
|
6401
6479
|
* @param options - Configuration options.
|
|
6402
6480
|
* @returns An `AgentMiddleware` instance.
|
|
6403
6481
|
*
|
|
@@ -6421,7 +6499,7 @@ function createCompletionCallbackMiddleware(options) {
|
|
|
6421
6499
|
* Send a notification to the callback destination.
|
|
6422
6500
|
*/
|
|
6423
6501
|
async function sendNotification(callbackThreadId, message) {
|
|
6424
|
-
await notifyParent(callbackGraphId, callbackThreadId, message, {
|
|
6502
|
+
await notifyParent$1(callbackGraphId, callbackThreadId, message, {
|
|
6425
6503
|
url,
|
|
6426
6504
|
headers
|
|
6427
6505
|
});
|
|
@@ -6491,6 +6569,7 @@ const AsyncTaskSchema = z.object({
|
|
|
6491
6569
|
agentName: z.string(),
|
|
6492
6570
|
threadId: z.string(),
|
|
6493
6571
|
runId: z.string(),
|
|
6572
|
+
supersededRunIds: z.array(z.string()).optional(),
|
|
6494
6573
|
status: z.string(),
|
|
6495
6574
|
createdAt: z.string(),
|
|
6496
6575
|
description: z.string().optional(),
|
|
@@ -6538,16 +6617,11 @@ Available async agent types:
|
|
|
6538
6617
|
|
|
6539
6618
|
## Usage notes:
|
|
6540
6619
|
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.
|
|
6620
|
+
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
6621
|
3. Use \`update_async_task\` to send new instructions to a running task.
|
|
6543
6622
|
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
|
-
*/
|
|
6623
|
+
5. The subagent runs on a remote server, so it has its own tools and capabilities.
|
|
6624
|
+
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
6625
|
/**
|
|
6552
6626
|
* Names of the tools added by the async subagent middleware.
|
|
6553
6627
|
*
|
|
@@ -6561,6 +6635,7 @@ const ASYNC_TASK_TOOL_NAMES = [
|
|
|
6561
6635
|
"cancel_async_task",
|
|
6562
6636
|
"list_async_tasks"
|
|
6563
6637
|
];
|
|
6638
|
+
/** Task statuses that never change, so live-status fetches can be skipped; `waiting` can still resume. */
|
|
6564
6639
|
const TERMINAL_STATUSES = /* @__PURE__ */ new Set([
|
|
6565
6640
|
"cancelled",
|
|
6566
6641
|
"success",
|
|
@@ -6580,32 +6655,141 @@ function resolveTrackedTask(taskId, state) {
|
|
|
6580
6655
|
if (!tracked) return `No tracked task found for taskId: '${taskId}'`;
|
|
6581
6656
|
return tracked;
|
|
6582
6657
|
}
|
|
6658
|
+
/** Guidance for a task whose latest run hasn't started. */
|
|
6659
|
+
const PENDING_NOTE = "The latest run hasn't started yet. If it is a queued follow-up, an earlier run may still be working.";
|
|
6660
|
+
/** Task status implied by the thread when the tracked run finished but the thread moved on. */
|
|
6661
|
+
const THREAD_TO_TASK_STATUS = {
|
|
6662
|
+
interrupted: "waiting",
|
|
6663
|
+
busy: "running",
|
|
6664
|
+
error: "error"
|
|
6665
|
+
};
|
|
6583
6666
|
/**
|
|
6584
|
-
*
|
|
6667
|
+
* Return a task's status from its latest run, reading the thread to spot pauses.
|
|
6585
6668
|
*
|
|
6586
|
-
*
|
|
6587
|
-
*
|
|
6669
|
+
* A run that hits `interrupt()` ends as `success`; only its thread shows the pause.
|
|
6670
|
+
* A run cancelled on the server ends `interrupted`, which a task reports as `cancelled`.
|
|
6671
|
+
*/
|
|
6672
|
+
function taskStatus(run, thread) {
|
|
6673
|
+
if (run.status === "interrupted") return "cancelled";
|
|
6674
|
+
if (run.status !== "success" || thread === null) return run.status;
|
|
6675
|
+
return THREAD_TO_TASK_STATUS[thread.status] ?? "success";
|
|
6676
|
+
}
|
|
6677
|
+
/** Whether a newer run exists than the tracked one, e.g. after a resume from another client. */
|
|
6678
|
+
function needsLatestRun(run, thread) {
|
|
6679
|
+
return run.status === "success" && thread !== null && (thread.status === "busy" || thread.status === "error");
|
|
6680
|
+
}
|
|
6681
|
+
/**
|
|
6682
|
+
* Fetch a task's latest run and, when that run finished, its thread (else `null`).
|
|
6588
6683
|
*
|
|
6589
|
-
*
|
|
6590
|
-
*
|
|
6591
|
-
*
|
|
6684
|
+
* Throws if the thread can't be read, since a paused run also ends as `success`.
|
|
6685
|
+
* A run replaced by another client's run hands over to the newest one, except for
|
|
6686
|
+
* a task the parent cancelled.
|
|
6592
6687
|
*/
|
|
6593
|
-
function
|
|
6688
|
+
async function observeTaskRun(client, task, signal) {
|
|
6689
|
+
let run = await client.runs.get(task.threadId, task.runId, { signal });
|
|
6690
|
+
if (run.status === "interrupted" && task.status !== "cancelled") {
|
|
6691
|
+
const [latest] = await client.runs.list(task.threadId, {
|
|
6692
|
+
limit: 1,
|
|
6693
|
+
signal
|
|
6694
|
+
});
|
|
6695
|
+
run = latest ?? run;
|
|
6696
|
+
}
|
|
6697
|
+
if (run.status !== "success") return [run, null];
|
|
6698
|
+
const thread = await client.threads.get(task.threadId, { signal });
|
|
6699
|
+
if (needsLatestRun(run, thread)) {
|
|
6700
|
+
const [latest] = await client.runs.list(task.threadId, {
|
|
6701
|
+
limit: 1,
|
|
6702
|
+
signal
|
|
6703
|
+
});
|
|
6704
|
+
run = latest ?? run;
|
|
6705
|
+
}
|
|
6706
|
+
return [run, thread];
|
|
6707
|
+
}
|
|
6708
|
+
/** Flatten a thread's pending interrupts, including ones raised inside subgraphs. */
|
|
6709
|
+
function pendingInterrupts(thread) {
|
|
6710
|
+
if (!thread?.interrupts) return [];
|
|
6711
|
+
return Object.values(thread.interrupts).flat();
|
|
6712
|
+
}
|
|
6713
|
+
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.";
|
|
6714
|
+
/** The thread's messages, if its values hold any. */
|
|
6715
|
+
function threadMessages(values) {
|
|
6716
|
+
if (values === null || typeof values !== "object" || Array.isArray(values)) return [];
|
|
6717
|
+
const messages = values.messages;
|
|
6718
|
+
return Array.isArray(messages) ? messages : [];
|
|
6719
|
+
}
|
|
6720
|
+
/** A thread message's content as text, whatever shape the server sent it in. */
|
|
6721
|
+
function messageText(message) {
|
|
6722
|
+
if (BaseMessage.isInstance(message)) return message.text;
|
|
6723
|
+
const content = typeof message === "object" && message !== null && "content" in message ? message.content : message;
|
|
6724
|
+
return typeof content === "string" ? content : JSON.stringify(content);
|
|
6725
|
+
}
|
|
6726
|
+
/**
|
|
6727
|
+
* Build a check result from a task's latest run and its thread.
|
|
6728
|
+
*
|
|
6729
|
+
* @param run - The task's latest run.
|
|
6730
|
+
* @param threadId - The task's thread ID.
|
|
6731
|
+
* @param thread - The task's thread, when its run finished.
|
|
6732
|
+
*/
|
|
6733
|
+
function buildCheckResult(run, threadId, thread) {
|
|
6734
|
+
const status = taskStatus(run, thread);
|
|
6594
6735
|
const checkResult = {
|
|
6595
|
-
status
|
|
6736
|
+
status,
|
|
6596
6737
|
threadId
|
|
6597
6738
|
};
|
|
6598
|
-
if (
|
|
6599
|
-
|
|
6600
|
-
|
|
6601
|
-
|
|
6602
|
-
|
|
6603
|
-
|
|
6604
|
-
|
|
6605
|
-
|
|
6739
|
+
if (status === "pending") checkResult.note = PENDING_NOTE;
|
|
6740
|
+
else if (status === "success") checkResult.result = finalContent(thread?.values);
|
|
6741
|
+
else if (status === "error") checkResult.error = "The async subagent encountered an error.";
|
|
6742
|
+
else if (status === "waiting") {
|
|
6743
|
+
checkResult.interrupts = pendingInterrupts(thread).map((item) => ({
|
|
6744
|
+
id: item.id ?? "",
|
|
6745
|
+
value: item.value
|
|
6746
|
+
}));
|
|
6747
|
+
checkResult.note = WAITING_NOTE;
|
|
6748
|
+
}
|
|
6606
6749
|
return checkResult;
|
|
6607
6750
|
}
|
|
6608
6751
|
/**
|
|
6752
|
+
* A check result as tool output: JSON, with a text-only answer's text in `result`.
|
|
6753
|
+
*
|
|
6754
|
+
* An answer with media follows the JSON as its own blocks, in order. Reasoning and
|
|
6755
|
+
* tool-call blocks are dropped; the text isn't cut.
|
|
6756
|
+
*/
|
|
6757
|
+
function checkOutput(result) {
|
|
6758
|
+
const blocks = result.result;
|
|
6759
|
+
if (!blocks) return JSON.stringify(result);
|
|
6760
|
+
const text = (block) => String(block.text);
|
|
6761
|
+
if (!blocks.some((block) => MEDIA_BLOCK_TYPES.has(block.type))) {
|
|
6762
|
+
const answer = blocks.filter((block) => block.type === "text").map(text);
|
|
6763
|
+
return JSON.stringify({
|
|
6764
|
+
...result,
|
|
6765
|
+
result: answer.join("")
|
|
6766
|
+
});
|
|
6767
|
+
}
|
|
6768
|
+
const { result: _answer, ...status } = result;
|
|
6769
|
+
const answer = blocks.filter((block) => block.type === "text" || MEDIA_BLOCK_TYPES.has(block.type)).map((block) => block.type === "text" ? textBlock(text(block)) : { ...block });
|
|
6770
|
+
return [textBlock(JSON.stringify(status)), ...answer];
|
|
6771
|
+
}
|
|
6772
|
+
/** Keep a task cancelled while paused as cancelled; its thread still shows the old pause. */
|
|
6773
|
+
function keepCancelled(task, result) {
|
|
6774
|
+
if (task.status === "cancelled" && result.status === "waiting") return {
|
|
6775
|
+
status: "cancelled",
|
|
6776
|
+
threadId: result.threadId
|
|
6777
|
+
};
|
|
6778
|
+
return result;
|
|
6779
|
+
}
|
|
6780
|
+
/** `task` updated to what a check found. */
|
|
6781
|
+
function observed(task, status, runId) {
|
|
6782
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
6783
|
+
const changed = status !== task.status || runId !== task.runId;
|
|
6784
|
+
return {
|
|
6785
|
+
...task,
|
|
6786
|
+
runId,
|
|
6787
|
+
status,
|
|
6788
|
+
updatedAt: changed ? now : task.updatedAt,
|
|
6789
|
+
checkedAt: now
|
|
6790
|
+
};
|
|
6791
|
+
}
|
|
6792
|
+
/**
|
|
6609
6793
|
* Filter tasks by cached status from agent state.
|
|
6610
6794
|
*
|
|
6611
6795
|
* Filtering uses the cached status, not live server status. Live statuses
|
|
@@ -6620,17 +6804,17 @@ function filterTasks(tasks, statusFilter) {
|
|
|
6620
6804
|
return Object.values(tasks).filter((task) => task.status === statusFilter);
|
|
6621
6805
|
}
|
|
6622
6806
|
/**
|
|
6623
|
-
* Fetch
|
|
6807
|
+
* Fetch a task's current status and run ID.
|
|
6624
6808
|
*
|
|
6625
|
-
* Returns the cached
|
|
6626
|
-
* unnecessary API calls). Falls back to the cached status on SDK errors.
|
|
6809
|
+
* Returns the cached values for terminal tasks and on SDK errors.
|
|
6627
6810
|
*/
|
|
6628
6811
|
async function fetchLiveTaskStatus(clients, task) {
|
|
6629
|
-
if (TERMINAL_STATUSES.has(task.status)) return task.status;
|
|
6812
|
+
if (TERMINAL_STATUSES.has(task.status)) return [task.status, task.runId];
|
|
6630
6813
|
try {
|
|
6631
|
-
|
|
6814
|
+
const [run, thread] = await observeTaskRun(clients.getClient(task.agentName), task);
|
|
6815
|
+
return [taskStatus(run, thread), run.run_id];
|
|
6632
6816
|
} catch {
|
|
6633
|
-
return task.status;
|
|
6817
|
+
return [task.status, task.runId];
|
|
6634
6818
|
}
|
|
6635
6819
|
}
|
|
6636
6820
|
/**
|
|
@@ -6673,9 +6857,18 @@ var ClientCache = class {
|
|
|
6673
6857
|
}
|
|
6674
6858
|
/**
|
|
6675
6859
|
* Get or create a `Client` for the named agent.
|
|
6860
|
+
*
|
|
6861
|
+
* With `extraHeaders` (such as one launch's trace headers), returns a new, uncached client.
|
|
6676
6862
|
*/
|
|
6677
|
-
getClient(name) {
|
|
6863
|
+
getClient(name, extraHeaders = {}) {
|
|
6678
6864
|
const spec = this.agents[name];
|
|
6865
|
+
if (Object.keys(extraHeaders).length > 0) return new Client({
|
|
6866
|
+
apiUrl: spec.url,
|
|
6867
|
+
defaultHeaders: {
|
|
6868
|
+
...this.resolveHeaders(spec),
|
|
6869
|
+
...extraHeaders
|
|
6870
|
+
}
|
|
6871
|
+
});
|
|
6679
6872
|
const key = this.cacheKey(spec);
|
|
6680
6873
|
const existing = this.clients.get(key);
|
|
6681
6874
|
if (existing) return existing;
|
|
@@ -6689,6 +6882,318 @@ var ClientCache = class {
|
|
|
6689
6882
|
}
|
|
6690
6883
|
};
|
|
6691
6884
|
/**
|
|
6885
|
+
* Baggage metadata key (JSON `true`) marking trace headers as a parent to nest under.
|
|
6886
|
+
*
|
|
6887
|
+
* Receivers that adopt the trace check for it, so keep the name stable.
|
|
6888
|
+
*/
|
|
6889
|
+
const NEST_UNDER_PARENT = "ls_nest_under_parent";
|
|
6890
|
+
/**
|
|
6891
|
+
* Build LangSmith headers pointing at the current span, or `{}` when tracing is off.
|
|
6892
|
+
*
|
|
6893
|
+
* Only sent to subagents on this deployment (no `url`). The baggage carries the
|
|
6894
|
+
* project and `NEST_UNDER_PARENT`, not the caller's run metadata. Any `baggage`
|
|
6895
|
+
* in the spec's headers is kept.
|
|
6896
|
+
*/
|
|
6897
|
+
function traceHeaders(spec) {
|
|
6898
|
+
if (spec.url) return {};
|
|
6899
|
+
const runTree = getCurrentRunTree(true);
|
|
6900
|
+
if (!runTree?.tracingEnabled || !runTree.trace_id || !runTree.dotted_order) return {};
|
|
6901
|
+
const baggage = Object.entries(spec.headers ?? {}).filter(([key, value]) => key.toLowerCase() === "baggage" && value).map(([, value]) => value);
|
|
6902
|
+
baggage.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify({ [NEST_UNDER_PARENT]: true }))}`);
|
|
6903
|
+
if (runTree.project_name) baggage.push(`langsmith-project=${encodeURIComponent(runTree.project_name)}`);
|
|
6904
|
+
return {
|
|
6905
|
+
"langsmith-trace": runTree.dotted_order,
|
|
6906
|
+
baggage: baggage.join(",")
|
|
6907
|
+
};
|
|
6908
|
+
}
|
|
6909
|
+
/**
|
|
6910
|
+
* `configurable` key carrying the launching agent's reference to an async subagent's run.
|
|
6911
|
+
*
|
|
6912
|
+
* Apps read it directly, and Python deep agents use the same key, so keep the key and shape stable.
|
|
6913
|
+
*/
|
|
6914
|
+
const PARENT_KEY = "deepagents_parent";
|
|
6915
|
+
/** Describe the running agent so the async subagent it launches can find it. */
|
|
6916
|
+
function parentReference(config) {
|
|
6917
|
+
const reference = {};
|
|
6918
|
+
const configurable = config?.configurable ?? {};
|
|
6919
|
+
const metadata = config?.metadata ?? {};
|
|
6920
|
+
if (configurable.thread_id) reference.thread_id = String(configurable.thread_id);
|
|
6921
|
+
const assistantId = metadata.assistant_id || configurable.assistant_id;
|
|
6922
|
+
if (assistantId) reference.assistant_id = String(assistantId);
|
|
6923
|
+
return reference;
|
|
6924
|
+
}
|
|
6925
|
+
/**
|
|
6926
|
+
* The parent reference sent to `spec`'s runs.
|
|
6927
|
+
*
|
|
6928
|
+
* A subagent on another server (`url`) or with `notifyParent: false` gets only the
|
|
6929
|
+
* parent's thread: the assistant is for waking the parent, which it can't do.
|
|
6930
|
+
*/
|
|
6931
|
+
function referenceFor(spec, config) {
|
|
6932
|
+
const { thread_id, assistant_id } = parentReference(config);
|
|
6933
|
+
const wakesParent = !spec.url && spec.notifyParent !== false;
|
|
6934
|
+
return {
|
|
6935
|
+
...thread_id && { thread_id },
|
|
6936
|
+
...wakesParent && assistant_id && { assistant_id }
|
|
6937
|
+
};
|
|
6938
|
+
}
|
|
6939
|
+
/**
|
|
6940
|
+
* Metadata for a task's thread, so apps can find a parent's subagent threads with `threads.search`.
|
|
6941
|
+
*
|
|
6942
|
+
* It names the subagent as the parent knows it, and for subagents on this deployment
|
|
6943
|
+
* keeps the parent's assistant, so other runs on the thread (such as the user
|
|
6944
|
+
* answering the subagent) can still notify the parent.
|
|
6945
|
+
*/
|
|
6946
|
+
function threadMetadata(spec, config) {
|
|
6947
|
+
const reference = referenceFor(spec, config);
|
|
6948
|
+
const metadata = { subagent_name: spec.name };
|
|
6949
|
+
if (reference.thread_id) metadata.parent_thread_id = reference.thread_id;
|
|
6950
|
+
if (reference.assistant_id) metadata.parent_assistant_id = reference.assistant_id;
|
|
6951
|
+
return metadata;
|
|
6952
|
+
}
|
|
6953
|
+
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";
|
|
6954
|
+
/** A message as portable input for another run, without parent-local eviction tags. */
|
|
6955
|
+
function serializeForkMessage(message) {
|
|
6956
|
+
const { lc_evicted_to: _evicted, ...additionalKwargs } = message.additional_kwargs ?? {};
|
|
6957
|
+
const serialized = {
|
|
6958
|
+
type: message.type,
|
|
6959
|
+
content: message.content,
|
|
6960
|
+
additional_kwargs: additionalKwargs
|
|
6961
|
+
};
|
|
6962
|
+
if (message.id) serialized.id = message.id;
|
|
6963
|
+
if (message.name) serialized.name = message.name;
|
|
6964
|
+
if (AIMessage$1.isInstance(message)) serialized.tool_calls = message.tool_calls;
|
|
6965
|
+
if (ToolMessage$1.isInstance(message)) {
|
|
6966
|
+
serialized.tool_call_id = message.tool_call_id;
|
|
6967
|
+
serialized.status = message.status;
|
|
6968
|
+
}
|
|
6969
|
+
return serialized;
|
|
6970
|
+
}
|
|
6971
|
+
/**
|
|
6972
|
+
* The task's input messages: the parent's effective conversation for forks, or only the task.
|
|
6973
|
+
*
|
|
6974
|
+
* A fork keeps references to the parent's offloaded media; a subagent sharing the
|
|
6975
|
+
* parent's backend loads them, and any other sees that the content is unavailable.
|
|
6976
|
+
*/
|
|
6977
|
+
function startTaskMessages(spec, state, description) {
|
|
6978
|
+
if (spec.mode !== "fork") return [{
|
|
6979
|
+
role: "user",
|
|
6980
|
+
content: description
|
|
6981
|
+
}];
|
|
6982
|
+
return [...getEffectiveMessages(stripInFlightAIMessage(state.messages ?? []), state), new HumanMessage$1({ content: ASYNC_FORK_TASK_PREAMBLE + description })].map(serializeForkMessage);
|
|
6983
|
+
}
|
|
6984
|
+
/** Describe a subagent's context inheritance without promising shared tools. */
|
|
6985
|
+
function describeAsyncSubAgent(spec) {
|
|
6986
|
+
const suffix = spec.mode === "fork" ? " (inherits your conversation at launch; uses its own system prompt and tools)" : "";
|
|
6987
|
+
return `- ${spec.name}: ${spec.description}${suffix}`;
|
|
6988
|
+
}
|
|
6989
|
+
/**
|
|
6990
|
+
* The `runs.create` options that link a run to this agent and set the subagent's webhook.
|
|
6991
|
+
*
|
|
6992
|
+
* A subagent on this deployment runs with this agent's context. The Agent Server
|
|
6993
|
+
* takes `context` or `configurable`, not both, so the parent reference then goes
|
|
6994
|
+
* through the thread's metadata.
|
|
6995
|
+
*/
|
|
6996
|
+
function runOptions(spec, runtime) {
|
|
6997
|
+
const webhook = spec.webhook ? { webhook: spec.webhook } : {};
|
|
6998
|
+
const context = spec.url ? void 0 : forwardedContext(runtime.context);
|
|
6999
|
+
if (context) return {
|
|
7000
|
+
...webhook,
|
|
7001
|
+
context
|
|
7002
|
+
};
|
|
7003
|
+
const reference = referenceFor(spec, runtime.config);
|
|
7004
|
+
return Object.keys(reference).length > 0 ? {
|
|
7005
|
+
...webhook,
|
|
7006
|
+
config: { configurable: { [PARENT_KEY]: reference } }
|
|
7007
|
+
} : webhook;
|
|
7008
|
+
}
|
|
7009
|
+
/** A run context as JSON data for another run, without deepagents' parent reference. */
|
|
7010
|
+
function forwardedContext(context) {
|
|
7011
|
+
if (!context || typeof context !== "object" || Array.isArray(context)) return;
|
|
7012
|
+
const entries = Object.entries(context).filter(([key]) => key !== PARENT_KEY);
|
|
7013
|
+
return entries.length > 0 ? Object.fromEntries(entries) : void 0;
|
|
7014
|
+
}
|
|
7015
|
+
/**
|
|
7016
|
+
* The agent that launched this run's task, or `null` if no async subagent tool did.
|
|
7017
|
+
*
|
|
7018
|
+
* Read from the run's config, or else from the task thread's metadata, which the
|
|
7019
|
+
* Agent Server copies into every run on the thread (such as the user's answer).
|
|
7020
|
+
*/
|
|
7021
|
+
function launchingAgent(config) {
|
|
7022
|
+
const reference = (config?.configurable ?? {})[PARENT_KEY];
|
|
7023
|
+
if (reference && typeof reference === "object" && !Array.isArray(reference)) return reference;
|
|
7024
|
+
const metadata = config?.metadata ?? {};
|
|
7025
|
+
if (!metadata.parent_thread_id) return null;
|
|
7026
|
+
const fallback = { thread_id: String(metadata.parent_thread_id) };
|
|
7027
|
+
if (metadata.parent_assistant_id) fallback.assistant_id = String(metadata.parent_assistant_id);
|
|
7028
|
+
return fallback;
|
|
7029
|
+
}
|
|
7030
|
+
/** Message field (`additional_kwargs` key) marking a task notification and carrying its {@link TaskEvent}. */
|
|
7031
|
+
const NOTIFICATION_KEY = "deepagents_notification";
|
|
7032
|
+
/** Results longer than this are cut in notifications, matching the limit for large tool results. */
|
|
7033
|
+
const MAX_RESULT_CHARS = 8e4;
|
|
7034
|
+
const NEXT_STEP = {
|
|
7035
|
+
success: "Use the result to continue; report back to the user if they're waiting on it.",
|
|
7036
|
+
error: "Use `check_async_task` for details, then decide whether to retry, try another approach, or tell the user.",
|
|
7037
|
+
timeout: "The task ran too long and was stopped. Decide whether to retry with a smaller task, or tell the user.",
|
|
7038
|
+
cancelled: "The task's run was cancelled before it finished, outside your tools. Decide whether to start it again, or tell the user.",
|
|
7039
|
+
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."
|
|
7040
|
+
};
|
|
7041
|
+
function textBlock(text) {
|
|
7042
|
+
return {
|
|
7043
|
+
type: "text",
|
|
7044
|
+
text
|
|
7045
|
+
};
|
|
7046
|
+
}
|
|
7047
|
+
/** Escape subagent-controlled text so it can't close the notification's tags and pose as the system. */
|
|
7048
|
+
function escape(text) {
|
|
7049
|
+
return text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
7050
|
+
}
|
|
7051
|
+
function clip(text) {
|
|
7052
|
+
if (text.length <= MAX_RESULT_CHARS) return text;
|
|
7053
|
+
return `${text.slice(0, MAX_RESULT_CHARS)}\n... [cut off; use \`check_async_task\` for the full details]`;
|
|
7054
|
+
}
|
|
7055
|
+
/** Standard content blocks passed on as they are; a notification is a user message, where providers reject the rest. */
|
|
7056
|
+
const MEDIA_BLOCK_TYPES = /* @__PURE__ */ new Set([
|
|
7057
|
+
"image",
|
|
7058
|
+
"audio",
|
|
7059
|
+
"video",
|
|
7060
|
+
"file"
|
|
7061
|
+
]);
|
|
7062
|
+
/**
|
|
7063
|
+
* The subagent's answer as user content: text escaped and cut when very long, media as it is.
|
|
7064
|
+
*
|
|
7065
|
+
* Reasoning, tool calls and blocks LangChain doesn't recognize are dropped.
|
|
7066
|
+
*/
|
|
7067
|
+
function resultBlocks(blocks) {
|
|
7068
|
+
const kept = [];
|
|
7069
|
+
for (const block of blocks) if (block.type === "text") kept.push(textBlock(escape(clip(String(block.text)))));
|
|
7070
|
+
else if (MEDIA_BLOCK_TYPES.has(block.type)) kept.push({ ...block });
|
|
7071
|
+
return kept;
|
|
7072
|
+
}
|
|
7073
|
+
/**
|
|
7074
|
+
* Frame a task update as a system notification the model won't mistake for the user.
|
|
7075
|
+
*
|
|
7076
|
+
* The result keeps its own content blocks, so an image reaches the model as an image.
|
|
7077
|
+
*/
|
|
7078
|
+
function notificationContent(update) {
|
|
7079
|
+
const blocks = [notificationHeader(update)];
|
|
7080
|
+
if (update.result) blocks.push(textBlock("<result>\n"), ...resultBlocks(update.result), textBlock("\n</result>\n"));
|
|
7081
|
+
const details = Object.fromEntries(["error", "interrupts"].filter((key) => update[key] !== void 0).map((key) => [key, update[key]]));
|
|
7082
|
+
if (Object.keys(details).length > 0) blocks.push(textBlock(`<details>${escape(clip(JSON.stringify(details)))}</details>\n`));
|
|
7083
|
+
blocks.push(textBlock(`</task-notification>\n${NEXT_STEP[update.status]}`));
|
|
7084
|
+
return blocks;
|
|
7085
|
+
}
|
|
7086
|
+
function notificationHeader(event) {
|
|
7087
|
+
return textBlock(`[SYSTEM NOTIFICATION - NOT USER INPUT]
|
|
7088
|
+
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.
|
|
7089
|
+
<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`);
|
|
7090
|
+
}
|
|
7091
|
+
/**
|
|
7092
|
+
* Reframe an earlier run's notification so the model doesn't think the queued follow-up finished.
|
|
7093
|
+
*
|
|
7094
|
+
* Only the closing next step changes; the earlier run's result and details stay.
|
|
7095
|
+
*/
|
|
7096
|
+
function supersededNotificationContent(message, event) {
|
|
7097
|
+
const content = message.content;
|
|
7098
|
+
const closing = Array.isArray(content) ? content.at(-1) : void 0;
|
|
7099
|
+
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.")];
|
|
7100
|
+
}
|
|
7101
|
+
/** Describe a failure without its message, which can carry internals into the parent's conversation. */
|
|
7102
|
+
function failureText(error) {
|
|
7103
|
+
return `The subagent failed (${typeof error === "object" && error !== null && "name" in error ? String(error.name) : typeof error}).`;
|
|
7104
|
+
}
|
|
7105
|
+
/** The ID of the run this config belongs to, when the Agent Server set it. */
|
|
7106
|
+
function currentRunId(config) {
|
|
7107
|
+
const metadata = config?.metadata ?? {};
|
|
7108
|
+
const configurable = config?.configurable ?? {};
|
|
7109
|
+
const runId = metadata.run_id ?? configurable.run_id;
|
|
7110
|
+
return runId ? String(runId) : void 0;
|
|
7111
|
+
}
|
|
7112
|
+
/** Build a task update; `details` are the status's `result`, `error` or `interrupts`. */
|
|
7113
|
+
function taskUpdate(event, details = {}) {
|
|
7114
|
+
const update = {
|
|
7115
|
+
task_id: event.task_id,
|
|
7116
|
+
agent_name: event.agent_name,
|
|
7117
|
+
status: event.status,
|
|
7118
|
+
...details
|
|
7119
|
+
};
|
|
7120
|
+
if (event.run_id) update.run_id = event.run_id;
|
|
7121
|
+
return update;
|
|
7122
|
+
}
|
|
7123
|
+
/** Describe how this run's task ended. */
|
|
7124
|
+
function taskEvent(config, agentName, status, details = {}) {
|
|
7125
|
+
const configurable = config?.configurable ?? {};
|
|
7126
|
+
return taskUpdate({
|
|
7127
|
+
task_id: String(configurable.thread_id ?? ""),
|
|
7128
|
+
agent_name: agentName,
|
|
7129
|
+
status,
|
|
7130
|
+
run_id: currentRunId(config)
|
|
7131
|
+
}, details);
|
|
7132
|
+
}
|
|
7133
|
+
/** The subagent's last message as standard content blocks, the task's result; it may hold images. */
|
|
7134
|
+
function finalContent(values) {
|
|
7135
|
+
const messages = threadMessages(values);
|
|
7136
|
+
if (messages.length === 0) return [{
|
|
7137
|
+
type: "text",
|
|
7138
|
+
text: "(completed with no output messages)"
|
|
7139
|
+
}];
|
|
7140
|
+
const last = messages[messages.length - 1];
|
|
7141
|
+
try {
|
|
7142
|
+
return coerceMessageLikeToMessage(last).contentBlocks;
|
|
7143
|
+
} catch {
|
|
7144
|
+
return [{
|
|
7145
|
+
type: "text",
|
|
7146
|
+
text: messageText(last)
|
|
7147
|
+
}];
|
|
7148
|
+
}
|
|
7149
|
+
}
|
|
7150
|
+
/** The task event a notification message carries, or `null` for any other message. */
|
|
7151
|
+
function notificationEvent(message) {
|
|
7152
|
+
const event = message?.additional_kwargs?.[NOTIFICATION_KEY];
|
|
7153
|
+
return event && typeof event === "object" && !Array.isArray(event) ? event : null;
|
|
7154
|
+
}
|
|
7155
|
+
/** A task update as the message the parent's model sees, marked with its {@link TaskEvent} so apps can recognize it. */
|
|
7156
|
+
function notificationMessage(update) {
|
|
7157
|
+
const event = {
|
|
7158
|
+
task_id: update.task_id,
|
|
7159
|
+
agent_name: update.agent_name,
|
|
7160
|
+
status: update.status
|
|
7161
|
+
};
|
|
7162
|
+
if (update.run_id) event.run_id = update.run_id;
|
|
7163
|
+
return {
|
|
7164
|
+
role: "user",
|
|
7165
|
+
content: notificationContent(update),
|
|
7166
|
+
additional_kwargs: { [NOTIFICATION_KEY]: event }
|
|
7167
|
+
};
|
|
7168
|
+
}
|
|
7169
|
+
/** Parent thread statuses a notification run can start on: neither running nor waiting for a human. */
|
|
7170
|
+
const DELIVERABLE_THREAD_STATUSES = /* @__PURE__ */ new Set(["idle", "error"]);
|
|
7171
|
+
/**
|
|
7172
|
+
* Start a notification run on the parent's thread only while it's idle (or its last run failed).
|
|
7173
|
+
*
|
|
7174
|
+
* A run on a thread waiting for a human would cancel that approval. Never throws.
|
|
7175
|
+
*/
|
|
7176
|
+
async function awakeParent(parentThreadId, assistantId, update, context) {
|
|
7177
|
+
const client = new Client();
|
|
7178
|
+
try {
|
|
7179
|
+
const thread = await client.threads.get(parentThreadId);
|
|
7180
|
+
if (!DELIVERABLE_THREAD_STATUSES.has(thread.status)) return;
|
|
7181
|
+
await client.runs.create(parentThreadId, assistantId, {
|
|
7182
|
+
input: { messages: [notificationMessage(update)] },
|
|
7183
|
+
multitaskStrategy: "reject",
|
|
7184
|
+
...context ? { context } : {}
|
|
7185
|
+
});
|
|
7186
|
+
} catch {}
|
|
7187
|
+
}
|
|
7188
|
+
/**
|
|
7189
|
+
* Wake the parent if it's idle, with this run's context; otherwise it finds out
|
|
7190
|
+
* on its own. Never throws.
|
|
7191
|
+
*/
|
|
7192
|
+
async function notifyParent(config, update, context) {
|
|
7193
|
+
const parent = launchingAgent(config);
|
|
7194
|
+
if (parent?.thread_id && parent.assistant_id) await awakeParent(parent.thread_id, parent.assistant_id, update, forwardedContext(context));
|
|
7195
|
+
}
|
|
7196
|
+
/**
|
|
6692
7197
|
* Extract the callback thread ID from the tool runtime.
|
|
6693
7198
|
*
|
|
6694
7199
|
* The thread ID is included in the subagent's input state so the subagent
|
|
@@ -6717,15 +7222,14 @@ function buildStartTool(agentMap, clients, toolDescription) {
|
|
|
6717
7222
|
const spec = agentMap[input.agentName];
|
|
6718
7223
|
const callbackContext = extractCallbackContext(runtime);
|
|
6719
7224
|
try {
|
|
6720
|
-
const
|
|
6721
|
-
const
|
|
6722
|
-
|
|
6723
|
-
|
|
6724
|
-
|
|
6725
|
-
|
|
6726
|
-
|
|
6727
|
-
|
|
6728
|
-
} });
|
|
7225
|
+
const thread = await clients.getClient(input.agentName).threads.create({ metadata: threadMetadata(spec, runtime.config) });
|
|
7226
|
+
const run = await clients.getClient(input.agentName, traceHeaders(spec)).runs.create(thread.thread_id, spec.graphId, {
|
|
7227
|
+
input: {
|
|
7228
|
+
messages: startTaskMessages(spec, runtime.state, input.description),
|
|
7229
|
+
...callbackContext
|
|
7230
|
+
},
|
|
7231
|
+
...runOptions(spec, runtime)
|
|
7232
|
+
});
|
|
6729
7233
|
const taskId = thread.thread_id;
|
|
6730
7234
|
const task = {
|
|
6731
7235
|
taskId,
|
|
@@ -6765,86 +7269,111 @@ function buildCheckTool(clients) {
|
|
|
6765
7269
|
return tool(async (input, runtime) => {
|
|
6766
7270
|
const task = resolveTrackedTask(input.taskId, runtime.state);
|
|
6767
7271
|
if (typeof task === "string") return task;
|
|
6768
|
-
const client = clients.getClient(task.agentName);
|
|
6769
7272
|
let run;
|
|
7273
|
+
let thread;
|
|
6770
7274
|
try {
|
|
6771
|
-
run = await
|
|
7275
|
+
[run, thread] = await observeTaskRun(clients.getClient(task.agentName), task);
|
|
6772
7276
|
} catch (e) {
|
|
6773
7277
|
return `Failed to get run status: ${e}`;
|
|
6774
7278
|
}
|
|
6775
|
-
|
|
6776
|
-
|
|
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
|
-
};
|
|
7279
|
+
const result = keepCancelled(task, buildCheckResult(run, task.threadId, thread));
|
|
7280
|
+
const updatedTask = observed(task, result.status, run.run_id);
|
|
6790
7281
|
return new Command({ update: {
|
|
6791
7282
|
messages: [new ToolMessage({
|
|
6792
|
-
content:
|
|
7283
|
+
content: checkOutput(result),
|
|
6793
7284
|
tool_call_id: toolCallIdFromRuntime(runtime)
|
|
6794
7285
|
})],
|
|
6795
7286
|
asyncTasks: { [task.taskId]: updatedTask }
|
|
6796
7287
|
} });
|
|
6797
7288
|
}, {
|
|
6798
7289
|
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.",
|
|
7290
|
+
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
7291
|
schema: z.object({ taskId: z.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim.") })
|
|
6801
7292
|
});
|
|
6802
7293
|
}
|
|
7294
|
+
/** Confirm an update: queued behind an active run, or started, noting when it dropped a waiting human request. */
|
|
7295
|
+
function updateMessage(tracked, strategy) {
|
|
7296
|
+
if (strategy === "enqueue" && (tracked.status === "running" || tracked.status === "pending")) return `Queued follow-up to async subagent without interrupting its current run. taskId: ${tracked.taskId}`;
|
|
7297
|
+
const msg = `Updated async subagent. taskId: ${tracked.taskId}`;
|
|
7298
|
+
return tracked.status === "waiting" ? `${msg}. It was waiting for a human; that request was dropped.` : msg;
|
|
7299
|
+
}
|
|
7300
|
+
/**
|
|
7301
|
+
* Refuse every queued follow-up to a task after the first in one model turn.
|
|
7302
|
+
*
|
|
7303
|
+
* Parallel calls read the same state, so the task would lose track of all but one.
|
|
7304
|
+
*/
|
|
7305
|
+
function parallelUpdateError(taskId, runtime) {
|
|
7306
|
+
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;
|
|
7307
|
+
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.`;
|
|
7308
|
+
}
|
|
7309
|
+
/**
|
|
7310
|
+
* The runs a queued follow-up leaves behind it.
|
|
7311
|
+
*
|
|
7312
|
+
* The list grows while the task is unfinished, and otherwise restarts with the tracked run.
|
|
7313
|
+
*/
|
|
7314
|
+
function supersededAfterUpdate(tracked) {
|
|
7315
|
+
return [...UNFINISHED_STATUSES.has(tracked.status) ? tracked.supersededRunIds ?? [] : [], tracked.runId];
|
|
7316
|
+
}
|
|
7317
|
+
/** The tracked task after a follow-up created `run`, which may still be queued. */
|
|
7318
|
+
function updatedTask(tracked, run, strategy, message) {
|
|
7319
|
+
const task = {
|
|
7320
|
+
...tracked,
|
|
7321
|
+
runId: run.run_id,
|
|
7322
|
+
status: "running",
|
|
7323
|
+
description: message,
|
|
7324
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
7325
|
+
};
|
|
7326
|
+
if (strategy === "enqueue") {
|
|
7327
|
+
task.status = run.status;
|
|
7328
|
+
task.supersededRunIds = supersededAfterUpdate(tracked);
|
|
7329
|
+
}
|
|
7330
|
+
return task;
|
|
7331
|
+
}
|
|
7332
|
+
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.";
|
|
7333
|
+
/** The update tool's description, naming the subagents whose follow-ups queue instead. */
|
|
7334
|
+
function updateToolDescription(agentMap) {
|
|
7335
|
+
const queued = Object.values(agentMap).filter((spec) => spec.updateStrategy === "enqueue").map((spec) => `\`${spec.name}\``);
|
|
7336
|
+
if (queued.length === 0) return UPDATE_TOOL_DESCRIPTION;
|
|
7337
|
+
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.`;
|
|
7338
|
+
}
|
|
6803
7339
|
/**
|
|
6804
7340
|
* Build the `update_async_task` tool.
|
|
6805
7341
|
*
|
|
6806
|
-
* Sends a follow-up message to
|
|
6807
|
-
*
|
|
6808
|
-
*
|
|
6809
|
-
*
|
|
7342
|
+
* Sends a follow-up message to an async subagent by creating a new run on the
|
|
7343
|
+
* same thread. The subagent sees the full conversation history plus the new
|
|
7344
|
+
* message. The `taskId` remains the same. The subagent's `updateStrategy`
|
|
7345
|
+
* decides whether the new run interrupts the current run or queues behind it.
|
|
6810
7346
|
*/
|
|
6811
7347
|
function buildUpdateTool(agentMap, clients) {
|
|
6812
7348
|
return tool(async (input, runtime) => {
|
|
6813
7349
|
const tracked = resolveTrackedTask(input.taskId, runtime.state);
|
|
6814
7350
|
if (typeof tracked === "string") return tracked;
|
|
6815
7351
|
const spec = agentMap[tracked.agentName];
|
|
7352
|
+
const strategy = spec.updateStrategy ?? "interrupt";
|
|
7353
|
+
const refused = strategy === "enqueue" && parallelUpdateError(tracked.taskId, runtime);
|
|
7354
|
+
if (refused) return refused;
|
|
6816
7355
|
try {
|
|
6817
|
-
const run = await clients.getClient(tracked.agentName).runs.create(tracked.threadId, spec.graphId, {
|
|
7356
|
+
const run = await clients.getClient(tracked.agentName, traceHeaders(spec)).runs.create(tracked.threadId, spec.graphId, {
|
|
6818
7357
|
input: { messages: [{
|
|
6819
7358
|
role: "user",
|
|
6820
7359
|
content: input.message
|
|
6821
7360
|
}] },
|
|
6822
|
-
multitaskStrategy:
|
|
7361
|
+
multitaskStrategy: strategy,
|
|
7362
|
+
...runOptions(spec, runtime)
|
|
6823
7363
|
});
|
|
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
7364
|
return new Command({ update: {
|
|
6836
7365
|
messages: [new ToolMessage({
|
|
6837
|
-
content:
|
|
7366
|
+
content: updateMessage(tracked, strategy),
|
|
6838
7367
|
tool_call_id: toolCallIdFromRuntime(runtime)
|
|
6839
7368
|
})],
|
|
6840
|
-
asyncTasks: { [tracked.taskId]:
|
|
7369
|
+
asyncTasks: { [tracked.taskId]: updatedTask(tracked, run, strategy, input.message) }
|
|
6841
7370
|
} });
|
|
6842
7371
|
} catch (e) {
|
|
6843
7372
|
return `Failed to update async subagent: ${e}`;
|
|
6844
7373
|
}
|
|
6845
7374
|
}, {
|
|
6846
7375
|
name: "update_async_task",
|
|
6847
|
-
description:
|
|
7376
|
+
description: updateToolDescription(agentMap),
|
|
6848
7377
|
schema: z.object({
|
|
6849
7378
|
taskId: z.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim."),
|
|
6850
7379
|
message: z.string().describe("Follow-up instructions or context to send to the subagent")
|
|
@@ -6852,6 +7381,20 @@ function buildUpdateTool(agentMap, clients) {
|
|
|
6852
7381
|
});
|
|
6853
7382
|
}
|
|
6854
7383
|
/**
|
|
7384
|
+
* Cancel earlier runs that are still pending or running, newest first.
|
|
7385
|
+
*
|
|
7386
|
+
* Newest first, so a queued run doesn't start when the run ahead of it is cancelled.
|
|
7387
|
+
* A run that can't be read or cancelled is skipped.
|
|
7388
|
+
*/
|
|
7389
|
+
async function cancelEarlierRuns(client, task) {
|
|
7390
|
+
for (const runId of [...task.supersededRunIds ?? []].reverse()) try {
|
|
7391
|
+
const run = await client.runs.get(task.threadId, runId);
|
|
7392
|
+
if (run.status === "running" || run.status === "pending") await client.runs.cancel(task.threadId, runId);
|
|
7393
|
+
} catch (e) {
|
|
7394
|
+
console.warn(`Failed to cancel earlier run ${runId} of task ${task.taskId}:`, e);
|
|
7395
|
+
}
|
|
7396
|
+
}
|
|
7397
|
+
/**
|
|
6855
7398
|
* Build the `cancel_async_task` tool.
|
|
6856
7399
|
*
|
|
6857
7400
|
* Cancels the current run on the remote server and updates the task's
|
|
@@ -6861,21 +7404,17 @@ function buildCancelTool(clients) {
|
|
|
6861
7404
|
return tool(async (input, runtime) => {
|
|
6862
7405
|
const tracked = resolveTrackedTask(input.taskId, runtime.state);
|
|
6863
7406
|
if (typeof tracked === "string") return tracked;
|
|
6864
|
-
|
|
6865
|
-
|
|
7407
|
+
if (tracked.status !== "waiting") try {
|
|
7408
|
+
const client = clients.getClient(tracked.agentName);
|
|
6866
7409
|
await client.runs.cancel(tracked.threadId, tracked.runId);
|
|
7410
|
+
await cancelEarlierRuns(client, tracked);
|
|
6867
7411
|
} catch (e) {
|
|
6868
7412
|
return `Failed to cancel run: ${e}`;
|
|
6869
7413
|
}
|
|
6870
7414
|
const updated = {
|
|
6871
|
-
|
|
6872
|
-
agentName: tracked.agentName,
|
|
6873
|
-
threadId: tracked.threadId,
|
|
6874
|
-
runId: tracked.runId,
|
|
7415
|
+
...tracked,
|
|
6875
7416
|
status: "cancelled",
|
|
6876
|
-
|
|
6877
|
-
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
6878
|
-
checkedAt: tracked.checkedAt
|
|
7417
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
6879
7418
|
};
|
|
6880
7419
|
return new Command({ update: {
|
|
6881
7420
|
messages: [new ToolMessage({
|
|
@@ -6886,7 +7425,7 @@ function buildCancelTool(clients) {
|
|
|
6886
7425
|
} });
|
|
6887
7426
|
}, {
|
|
6888
7427
|
name: "cancel_async_task",
|
|
6889
|
-
description: "Cancel a running async subagent task. Use this to stop a task that is no longer needed.",
|
|
7428
|
+
description: "Cancel a running, pending, or waiting async subagent task. Use this to stop a task that is no longer needed.",
|
|
6890
7429
|
schema: z.object({ taskId: z.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim.") })
|
|
6891
7430
|
});
|
|
6892
7431
|
}
|
|
@@ -6900,24 +7439,14 @@ function buildListTool(clients) {
|
|
|
6900
7439
|
return tool(async (input, runtime) => {
|
|
6901
7440
|
const filtered = filterTasks(runtime.state.asyncTasks ?? {}, input.statusFilter ?? void 0);
|
|
6902
7441
|
if (filtered.length === 0) return "No async subagent tasks tracked";
|
|
6903
|
-
const
|
|
7442
|
+
const live = await Promise.all(filtered.map((task) => fetchLiveTaskStatus(clients, task)));
|
|
6904
7443
|
const updatedTasks = {};
|
|
6905
7444
|
const entries = [];
|
|
6906
7445
|
for (let idx = 0; idx < filtered.length; idx++) {
|
|
6907
7446
|
const task = filtered[idx];
|
|
6908
|
-
const status =
|
|
6909
|
-
|
|
6910
|
-
|
|
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
|
-
};
|
|
7447
|
+
const [status, runId] = live[idx];
|
|
7448
|
+
entries.push(formatTaskEntry(task, status));
|
|
7449
|
+
updatedTasks[task.taskId] = observed(task, status, runId);
|
|
6921
7450
|
}
|
|
6922
7451
|
return new Command({ update: {
|
|
6923
7452
|
messages: [new ToolMessage({
|
|
@@ -6928,10 +7457,107 @@ function buildListTool(clients) {
|
|
|
6928
7457
|
} });
|
|
6929
7458
|
}, {
|
|
6930
7459
|
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'.") })
|
|
7460
|
+
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.",
|
|
7461
|
+
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
7462
|
});
|
|
6934
7463
|
}
|
|
7464
|
+
/** The notification for a task outcome a check found, or `null` for outcomes not worth waking for. */
|
|
7465
|
+
function checkEvent(task, run, thread, status) {
|
|
7466
|
+
if (!NOTIFIED_STATUSES.has(status)) return null;
|
|
7467
|
+
const result = buildCheckResult(run, task.threadId, thread);
|
|
7468
|
+
const details = {};
|
|
7469
|
+
if (result.interrupts) details.interrupts = result.interrupts;
|
|
7470
|
+
if (status === "success") details.result = result.result;
|
|
7471
|
+
if (status === "error") details.error = "The subagent failed.";
|
|
7472
|
+
return taskUpdate({
|
|
7473
|
+
task_id: task.taskId,
|
|
7474
|
+
agent_name: task.agentName,
|
|
7475
|
+
status,
|
|
7476
|
+
run_id: run.run_id ?? task.runId
|
|
7477
|
+
}, details);
|
|
7478
|
+
}
|
|
7479
|
+
/** Task outcomes that notify the parent. */
|
|
7480
|
+
const NOTIFIED_STATUSES = /* @__PURE__ */ new Set([
|
|
7481
|
+
"success",
|
|
7482
|
+
"error",
|
|
7483
|
+
"timeout",
|
|
7484
|
+
"cancelled",
|
|
7485
|
+
"waiting"
|
|
7486
|
+
]);
|
|
7487
|
+
/** How long the parent waits on one task's status before skipping it until the next check. */
|
|
7488
|
+
const PULL_TIMEOUT_MS = 5e3;
|
|
7489
|
+
/** Tracked task statuses that can still change, so the parent checks them for status updates. */
|
|
7490
|
+
const UNFINISHED_STATUSES = /* @__PURE__ */ new Set([
|
|
7491
|
+
"running",
|
|
7492
|
+
"pending",
|
|
7493
|
+
"waiting"
|
|
7494
|
+
]);
|
|
7495
|
+
/** Observe a task, or `null` when it can't be checked in time; it's checked again next time. */
|
|
7496
|
+
async function observeTask(clients, task) {
|
|
7497
|
+
try {
|
|
7498
|
+
return await observeTaskRun(clients.getClient(task.agentName), task, AbortSignal.timeout(PULL_TIMEOUT_MS));
|
|
7499
|
+
} catch (e) {
|
|
7500
|
+
console.warn(`Failed to check task ${task.taskId}:`, e);
|
|
7501
|
+
return null;
|
|
7502
|
+
}
|
|
7503
|
+
}
|
|
7504
|
+
/**
|
|
7505
|
+
* Check unfinished tasks; return their updated records and a notification per new outcome.
|
|
7506
|
+
*
|
|
7507
|
+
* Outcomes the agent already saw aren't reported again; a task that can't be
|
|
7508
|
+
* checked is skipped until the next check.
|
|
7509
|
+
*/
|
|
7510
|
+
async function pull(clients, tasks) {
|
|
7511
|
+
const unfinished = Object.values(tasks).filter((task) => UNFINISHED_STATUSES.has(task.status));
|
|
7512
|
+
const found = await Promise.all(unfinished.map((task) => observeTask(clients, task)));
|
|
7513
|
+
const records = {};
|
|
7514
|
+
const messages = [];
|
|
7515
|
+
unfinished.forEach((task, idx) => {
|
|
7516
|
+
if (found[idx] === null) return;
|
|
7517
|
+
const [run, thread] = found[idx];
|
|
7518
|
+
const status = taskStatus(run, thread);
|
|
7519
|
+
if (status === task.status && run.run_id === task.runId) return;
|
|
7520
|
+
records[task.taskId] = observed(task, status, run.run_id);
|
|
7521
|
+
const event = status !== task.status ? checkEvent(task, run, thread, status) : null;
|
|
7522
|
+
if (event) messages.push(coerceMessageLikeToMessage(notificationMessage(event)));
|
|
7523
|
+
});
|
|
7524
|
+
const update = {};
|
|
7525
|
+
if (Object.keys(records).length > 0) update.asyncTasks = records;
|
|
7526
|
+
if (messages.length > 0) update.messages = messages;
|
|
7527
|
+
return update;
|
|
7528
|
+
}
|
|
7529
|
+
/**
|
|
7530
|
+
* When a task notification started this run, record the task's outcome so checks don't report it again.
|
|
7531
|
+
*
|
|
7532
|
+
* A notification from an earlier run that a queued follow-up replaced is rewritten
|
|
7533
|
+
* instead, so the model doesn't take it as the task's outcome.
|
|
7534
|
+
*/
|
|
7535
|
+
function recordNotification(messages, tasks) {
|
|
7536
|
+
const last = messages[messages.length - 1];
|
|
7537
|
+
const event = notificationEvent(last);
|
|
7538
|
+
const task = event ? tasks[event.task_id] : void 0;
|
|
7539
|
+
if (!event || !task || task.status === "cancelled") return {};
|
|
7540
|
+
const runId = event.run_id ?? task.runId;
|
|
7541
|
+
if (task.supersededRunIds?.includes(runId)) {
|
|
7542
|
+
const content = supersededNotificationContent(last, event);
|
|
7543
|
+
return { messages: [new HumanMessage$1({
|
|
7544
|
+
id: last.id,
|
|
7545
|
+
content,
|
|
7546
|
+
additional_kwargs: last.additional_kwargs
|
|
7547
|
+
})] };
|
|
7548
|
+
}
|
|
7549
|
+
if (runId !== task.runId && !UNFINISHED_STATUSES.has(task.status)) return {};
|
|
7550
|
+
return { asyncTasks: { [task.taskId]: observed(task, event.status, runId) } };
|
|
7551
|
+
}
|
|
7552
|
+
/** The tasks tracked in state; the state schema stores `status` as a plain string. */
|
|
7553
|
+
function trackedTasks(state) {
|
|
7554
|
+
return state.asyncTasks ?? {};
|
|
7555
|
+
}
|
|
7556
|
+
/** Whether the last message is a final answer: an AI message with no tool calls. */
|
|
7557
|
+
function isFinalAnswer(messages) {
|
|
7558
|
+
const last = messages[messages.length - 1];
|
|
7559
|
+
return last !== void 0 && !last.tool_calls?.length;
|
|
7560
|
+
}
|
|
6935
7561
|
/**
|
|
6936
7562
|
* Create middleware that adds async subagent tools to an agent.
|
|
6937
7563
|
*
|
|
@@ -6943,6 +7569,11 @@ function buildListTool(clients) {
|
|
|
6943
7569
|
* Works with any Agent Protocol-compliant server — LangGraph Platform (managed)
|
|
6944
7570
|
* or self-hosted (e.g. a Hono/Express server implementing the Agent Protocol spec).
|
|
6945
7571
|
*
|
|
7572
|
+
* On an Agent Server, the agent is told when its tasks finish, fail or wait for
|
|
7573
|
+
* the user: by checking while it runs, and through a new run when it's idle.
|
|
7574
|
+
*
|
|
7575
|
+
* @experimental Task notifications are experimental and subject to change.
|
|
7576
|
+
*
|
|
6946
7577
|
* @throws {Error} If no async subagents are provided or names are duplicated.
|
|
6947
7578
|
*
|
|
6948
7579
|
* @example
|
|
@@ -6972,9 +7603,15 @@ function createAsyncSubAgentMiddleware(options) {
|
|
|
6972
7603
|
const names = asyncSubAgents.map((a) => a.name);
|
|
6973
7604
|
const duplicates = names.filter((n, i) => names.indexOf(n) !== i);
|
|
6974
7605
|
if (duplicates.length > 0) throw new Error(`Duplicate async subagent names: ${[...new Set(duplicates)].join(", ")}`);
|
|
7606
|
+
for (const spec of asyncSubAgents) {
|
|
7607
|
+
const strategy = spec.updateStrategy ?? "interrupt";
|
|
7608
|
+
if (strategy !== "interrupt" && strategy !== "enqueue") throw new Error(`AsyncSubAgent '${spec.name}' has invalid updateStrategy '${strategy}'; expected 'interrupt' or 'enqueue'`);
|
|
7609
|
+
const mode = spec.mode ?? "isolated";
|
|
7610
|
+
if (mode !== "isolated" && mode !== "fork") throw new Error(`AsyncSubAgent '${spec.name}' has invalid mode '${mode}'; expected 'isolated' or 'fork'`);
|
|
7611
|
+
}
|
|
6975
7612
|
const agentMap = Object.fromEntries(asyncSubAgents.map((a) => [a.name, a]));
|
|
6976
7613
|
const clients = new ClientCache(agentMap);
|
|
6977
|
-
const agentsDescription = asyncSubAgents.map(
|
|
7614
|
+
const agentsDescription = asyncSubAgents.map(describeAsyncSubAgent).join("\n");
|
|
6978
7615
|
const tools = [
|
|
6979
7616
|
buildStartTool(agentMap, clients, ASYNC_TASK_TOOL_DESCRIPTION.replace("{available_agents}", agentsDescription)),
|
|
6980
7617
|
buildCheckTool(clients),
|
|
@@ -6987,6 +7624,41 @@ function createAsyncSubAgentMiddleware(options) {
|
|
|
6987
7624
|
name: "asyncSubAgentMiddleware",
|
|
6988
7625
|
stateSchema: AsyncTaskStateSchema,
|
|
6989
7626
|
tools,
|
|
7627
|
+
beforeAgent: async (state) => {
|
|
7628
|
+
const messages = state.messages ?? [];
|
|
7629
|
+
const tasks = trackedTasks(state);
|
|
7630
|
+
const recorded = recordNotification(messages, tasks);
|
|
7631
|
+
const updates = await pull(clients, {
|
|
7632
|
+
...tasks,
|
|
7633
|
+
...recorded.asyncTasks
|
|
7634
|
+
});
|
|
7635
|
+
const asyncTasks = {
|
|
7636
|
+
...recorded.asyncTasks,
|
|
7637
|
+
...updates.asyncTasks
|
|
7638
|
+
};
|
|
7639
|
+
const notes = [...recorded.messages ?? [], ...updates.messages ?? []];
|
|
7640
|
+
if (Object.keys(asyncTasks).length === 0 && notes.length === 0) return;
|
|
7641
|
+
return {
|
|
7642
|
+
asyncTasks,
|
|
7643
|
+
...notes.length > 0 && { messages: notes }
|
|
7644
|
+
};
|
|
7645
|
+
},
|
|
7646
|
+
beforeModel: async (state) => {
|
|
7647
|
+
const updates = await pull(clients, trackedTasks(state));
|
|
7648
|
+
return Object.keys(updates).length > 0 ? updates : void 0;
|
|
7649
|
+
},
|
|
7650
|
+
afterModel: {
|
|
7651
|
+
canJumpTo: ["model"],
|
|
7652
|
+
hook: async (state) => {
|
|
7653
|
+
if (!isFinalAnswer(state.messages ?? [])) return;
|
|
7654
|
+
const updates = await pull(clients, trackedTasks(state));
|
|
7655
|
+
if (!updates.messages) return Object.keys(updates).length > 0 ? updates : void 0;
|
|
7656
|
+
return {
|
|
7657
|
+
...updates,
|
|
7658
|
+
jumpTo: "model"
|
|
7659
|
+
};
|
|
7660
|
+
}
|
|
7661
|
+
},
|
|
6990
7662
|
wrapModelCall: async (request, handler) => {
|
|
6991
7663
|
if (fullSystemPrompt !== null) return handler({
|
|
6992
7664
|
...request,
|
|
@@ -7047,6 +7719,53 @@ function createCacheBreakpointMiddleware() {
|
|
|
7047
7719
|
});
|
|
7048
7720
|
}
|
|
7049
7721
|
//#endregion
|
|
7722
|
+
//#region src/middleware/parent_notifier.ts
|
|
7723
|
+
/** Whether this is the outermost graph of a task run, not a graph nested in it. */
|
|
7724
|
+
function isTopLevelGraph(config) {
|
|
7725
|
+
const configurable = config.configurable ?? {};
|
|
7726
|
+
return !String(configurable.checkpoint_ns ?? "").includes("|");
|
|
7727
|
+
}
|
|
7728
|
+
/** Whether `error` comes from the run being aborted rather than from the subagent failing. */
|
|
7729
|
+
function wasAborted(error, signal) {
|
|
7730
|
+
return signal?.aborted === true || getConfig()?.signal?.aborted === true || typeof error === "object" && error !== null && error.name === "AbortError";
|
|
7731
|
+
}
|
|
7732
|
+
/**
|
|
7733
|
+
* Wake the agent that started this run with `start_async_task`, when the run ends.
|
|
7734
|
+
*
|
|
7735
|
+
* `createDeepAgent` attaches it to every deep agent. It does nothing unless the
|
|
7736
|
+
* run carries the parent reference, and skips nested runs.
|
|
7737
|
+
*/
|
|
7738
|
+
function createParentNotifierMiddleware() {
|
|
7739
|
+
/**
|
|
7740
|
+
* Notify for this graph's own run that an async subagent tool started.
|
|
7741
|
+
*
|
|
7742
|
+
* The run's context comes from its config: hooks only see the context fields
|
|
7743
|
+
* a middleware's `contextSchema` declares, and this one declares none.
|
|
7744
|
+
*/
|
|
7745
|
+
async function report(status, details) {
|
|
7746
|
+
const config = getConfig();
|
|
7747
|
+
if (!launchingAgent(config) || !isTopLevelGraph(config)) return;
|
|
7748
|
+
if (currentRunId(config) === void 0) return;
|
|
7749
|
+
const metadata = config.metadata ?? {};
|
|
7750
|
+
const configurable = config.configurable ?? {};
|
|
7751
|
+
await notifyParent(config, taskEvent(config, String(metadata.subagent_name ?? metadata.graph_id ?? configurable.graph_id ?? "subagent"), status, details), config.context);
|
|
7752
|
+
}
|
|
7753
|
+
return createMiddleware({
|
|
7754
|
+
name: "parentNotifierMiddleware",
|
|
7755
|
+
afterAgent: async (state) => {
|
|
7756
|
+
await report("success", { result: finalContent(state) });
|
|
7757
|
+
},
|
|
7758
|
+
wrapModelCall: async (request, handler) => {
|
|
7759
|
+
try {
|
|
7760
|
+
return await handler(request);
|
|
7761
|
+
} catch (e) {
|
|
7762
|
+
if (!isGraphBubbleUp(e) && !wasAborted(e, request.runtime.signal)) await report("error", { error: failureText(e) });
|
|
7763
|
+
throw e;
|
|
7764
|
+
}
|
|
7765
|
+
}
|
|
7766
|
+
});
|
|
7767
|
+
}
|
|
7768
|
+
//#endregion
|
|
7050
7769
|
//#region src/middleware/tool_exclusion.ts
|
|
7051
7770
|
function hasToolName(tool) {
|
|
7052
7771
|
return tool !== null && typeof tool === "object" && "name" in tool && typeof tool.name === "string";
|
|
@@ -7952,6 +8671,7 @@ function createDeepAgent(params = {}) {
|
|
|
7952
8671
|
createPatchToolCallsMiddleware()
|
|
7953
8672
|
];
|
|
7954
8673
|
let middleware = mergeMiddlewareStack([
|
|
8674
|
+
createParentNotifierMiddleware(),
|
|
7955
8675
|
fsMiddleware,
|
|
7956
8676
|
subagentMiddleware,
|
|
7957
8677
|
summarizationMiddleware,
|
|
@@ -10103,4 +10823,4 @@ var LangSmithSandbox = class LangSmithSandbox extends BaseSandbox {
|
|
|
10103
10823
|
//#endregion
|
|
10104
10824
|
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
10825
|
|
|
10106
|
-
//# sourceMappingURL=langsmith-
|
|
10826
|
+
//# sourceMappingURL=langsmith-B1pbrx3y.js.map
|