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
|
@@ -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
|
|
@@ -831,6 +832,45 @@ function trimTrailingSlashes$2(path) {
|
|
|
831
832
|
}
|
|
832
833
|
const PREGEL_SEND_KEY = "__pregel_send";
|
|
833
834
|
const PREGEL_READ_KEY = "__pregel_read";
|
|
835
|
+
function isBase64Encoded(data) {
|
|
836
|
+
return !isFileDataV1(data) && data.encoding === "base64" && typeof data.content === "string";
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* Store binary content as base64 text. State is checkpointed as JSON, which
|
|
840
|
+
* turns a Uint8Array into an object of numeric keys that fails the files
|
|
841
|
+
* schema on the next run.
|
|
842
|
+
*/
|
|
843
|
+
function toStoredFileData(data) {
|
|
844
|
+
if (!isFileDataBinary(data)) return data;
|
|
845
|
+
return {
|
|
846
|
+
...data,
|
|
847
|
+
content: Buffer.from(data.content).toString("base64"),
|
|
848
|
+
encoding: "base64"
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
/** Decode base64-stored content so readers keep getting Uint8Array bytes. */
|
|
852
|
+
function fromStoredFileData(data) {
|
|
853
|
+
if (!isBase64Encoded(data)) return data;
|
|
854
|
+
return {
|
|
855
|
+
content: new Uint8Array(Buffer.from(data.content, "base64")),
|
|
856
|
+
mimeType: data.mimeType,
|
|
857
|
+
created_at: data.created_at,
|
|
858
|
+
modified_at: data.modified_at
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
function fileSize(data) {
|
|
862
|
+
if (isFileDataV1(data)) return data.content.join("\n").length;
|
|
863
|
+
if (typeof data.content !== "string") return data.content.byteLength;
|
|
864
|
+
return data.encoding === "base64" ? Buffer.byteLength(data.content, "base64") : data.content.length;
|
|
865
|
+
}
|
|
866
|
+
/** Strict UTF-8 decode; undefined when the bytes are not valid UTF-8. */
|
|
867
|
+
function decodeUtf8(bytes) {
|
|
868
|
+
try {
|
|
869
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
870
|
+
} catch {
|
|
871
|
+
return;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
834
874
|
/**
|
|
835
875
|
* Backend that stores files in agent state (ephemeral).
|
|
836
876
|
*
|
|
@@ -918,11 +958,10 @@ var StateBackend = class {
|
|
|
918
958
|
subdirs.add(normalizedPath + subdirName + "/");
|
|
919
959
|
continue;
|
|
920
960
|
}
|
|
921
|
-
const size = isFileDataV1(fd) ? fd.content.join("\n").length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length;
|
|
922
961
|
infos.push({
|
|
923
962
|
path: k,
|
|
924
963
|
is_dir: false,
|
|
925
|
-
size,
|
|
964
|
+
size: fileSize(fd),
|
|
926
965
|
modified_at: fd.modified_at
|
|
927
966
|
});
|
|
928
967
|
}
|
|
@@ -949,7 +988,7 @@ var StateBackend = class {
|
|
|
949
988
|
read(filePath, offset = 0, limit = 500) {
|
|
950
989
|
const fileData = this.files[filePath];
|
|
951
990
|
if (!fileData) return { error: `File '${filePath}' not found` };
|
|
952
|
-
const fileDataV2 = migrateToFileDataV2(fileData, filePath);
|
|
991
|
+
const fileDataV2 = migrateToFileDataV2(fromStoredFileData(fileData), filePath);
|
|
953
992
|
if (!isTextMimeType(fileDataV2.mimeType)) return {
|
|
954
993
|
content: fileDataV2.content,
|
|
955
994
|
mimeType: fileDataV2.mimeType
|
|
@@ -982,15 +1021,19 @@ var StateBackend = class {
|
|
|
982
1021
|
readRaw(filePath) {
|
|
983
1022
|
const fileData = this.files[filePath];
|
|
984
1023
|
if (!fileData) return { error: `File '${filePath}' not found` };
|
|
985
|
-
return { data: fileData };
|
|
1024
|
+
return { data: fromStoredFileData(fileData) };
|
|
986
1025
|
}
|
|
987
1026
|
/**
|
|
988
1027
|
* Write content to a file, creating it or overwriting it if it already exists.
|
|
989
1028
|
* Returns WriteResult with filesUpdate to update LangGraph state.
|
|
990
1029
|
*/
|
|
991
1030
|
write(filePath, content) {
|
|
992
|
-
const
|
|
993
|
-
const
|
|
1031
|
+
const stored = this.files[filePath];
|
|
1032
|
+
const existing = stored && isBase64Encoded(stored) ? {
|
|
1033
|
+
...stored,
|
|
1034
|
+
mimeType: getMimeType(filePath)
|
|
1035
|
+
} : stored;
|
|
1036
|
+
const newFileData = toStoredFileData(createWriteFileData(filePath, content, this.fileFormat, existing));
|
|
994
1037
|
const update = { [filePath]: newFileData };
|
|
995
1038
|
if (!this.isLegacy) {
|
|
996
1039
|
this.sendFilesUpdate(update);
|
|
@@ -1029,7 +1072,7 @@ var StateBackend = class {
|
|
|
1029
1072
|
edit(filePath, oldString, newString, replaceAll = false) {
|
|
1030
1073
|
const fileData = this.files[filePath];
|
|
1031
1074
|
if (!fileData) return { error: `Error: File '${filePath}' not found` };
|
|
1032
|
-
const result = performStringReplacement(fileDataToString(fileData), oldString, newString, replaceAll);
|
|
1075
|
+
const result = performStringReplacement(fileDataToString(fromStoredFileData(fileData)), oldString, newString, replaceAll);
|
|
1033
1076
|
if (typeof result === "string") return { error: result };
|
|
1034
1077
|
const [newContent, occurrences] = result;
|
|
1035
1078
|
const newFileData = updateFileData(fileData, newContent);
|
|
@@ -1069,11 +1112,10 @@ var StateBackend = class {
|
|
|
1069
1112
|
const infos = [];
|
|
1070
1113
|
for (const p of paths) {
|
|
1071
1114
|
const fd = files[p];
|
|
1072
|
-
const size = fd ? isFileDataV1(fd) ? fd.content.join("\n").length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length : 0;
|
|
1073
1115
|
infos.push({
|
|
1074
1116
|
path: p,
|
|
1075
1117
|
is_dir: false,
|
|
1076
|
-
size,
|
|
1118
|
+
size: fd ? fileSize(fd) : 0,
|
|
1077
1119
|
modified_at: fd?.modified_at || ""
|
|
1078
1120
|
});
|
|
1079
1121
|
}
|
|
@@ -1092,9 +1134,7 @@ var StateBackend = class {
|
|
|
1092
1134
|
const responses = [];
|
|
1093
1135
|
const updates = {};
|
|
1094
1136
|
for (const [path, content] of files) try {
|
|
1095
|
-
|
|
1096
|
-
if (this.fileFormat === "v2" && !isTextMimeType(mimeType)) updates[path] = createFileData(content, void 0, "v2", mimeType);
|
|
1097
|
-
else updates[path] = createFileData(new TextDecoder().decode(content), void 0, this.fileFormat, mimeType);
|
|
1137
|
+
updates[path] = toStoredFileData(this.createUploadFileData(path, content));
|
|
1098
1138
|
responses.push({
|
|
1099
1139
|
path,
|
|
1100
1140
|
error: null
|
|
@@ -1114,6 +1154,20 @@ var StateBackend = class {
|
|
|
1114
1154
|
return result;
|
|
1115
1155
|
}
|
|
1116
1156
|
/**
|
|
1157
|
+
* Build FileData for an uploaded file.
|
|
1158
|
+
*
|
|
1159
|
+
* In v2, bytes at a binary MIME type stay binary, and bytes at a text MIME
|
|
1160
|
+
* type that are not valid UTF-8 are kept as application/octet-stream rather
|
|
1161
|
+
* than lossily decoded. v1 cannot hold binary, so it always decodes as text.
|
|
1162
|
+
*/
|
|
1163
|
+
createUploadFileData(path, content) {
|
|
1164
|
+
const mimeType = getMimeType(path);
|
|
1165
|
+
if (this.fileFormat === "v1") return createFileData(new TextDecoder().decode(content), void 0, "v1", mimeType);
|
|
1166
|
+
if (!isTextMimeType(mimeType)) return createFileData(content, void 0, "v2", mimeType);
|
|
1167
|
+
const text = decodeUtf8(content);
|
|
1168
|
+
return text === void 0 ? createFileData(content, void 0, "v2", "application/octet-stream") : createFileData(text, void 0, "v2", mimeType);
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1117
1171
|
* Download multiple files.
|
|
1118
1172
|
*
|
|
1119
1173
|
* @param paths - List of file paths to download
|
|
@@ -1132,7 +1186,7 @@ var StateBackend = class {
|
|
|
1132
1186
|
});
|
|
1133
1187
|
continue;
|
|
1134
1188
|
}
|
|
1135
|
-
const fileDataV2 = migrateToFileDataV2(fileData, path);
|
|
1189
|
+
const fileDataV2 = migrateToFileDataV2(fromStoredFileData(fileData), path);
|
|
1136
1190
|
if (typeof fileDataV2.content === "string") {
|
|
1137
1191
|
const content = new TextEncoder().encode(fileDataV2.content);
|
|
1138
1192
|
responses.push({
|
|
@@ -1468,6 +1522,14 @@ async function hydrateMessages(messages, backend, prefix, cache) {
|
|
|
1468
1522
|
}
|
|
1469
1523
|
return restorePayloads(messages, payloads);
|
|
1470
1524
|
}
|
|
1525
|
+
/**
|
|
1526
|
+
* Replace each blob reference in `messages` with a notice that the content is
|
|
1527
|
+
* unavailable, for an agent that can't load blobs, so the model still accepts
|
|
1528
|
+
* the request.
|
|
1529
|
+
*/
|
|
1530
|
+
function withoutBlobRefs(messages) {
|
|
1531
|
+
return messages.some(messageHasRefs) ? restorePayloads(messages, /* @__PURE__ */ new Map()) : messages;
|
|
1532
|
+
}
|
|
1471
1533
|
//#endregion
|
|
1472
1534
|
//#region src/middleware/unsupportedContent.ts
|
|
1473
1535
|
const PDF_MIME_TYPE = "application/pdf";
|
|
@@ -2367,30 +2429,39 @@ function extractTextFromMessage(message) {
|
|
|
2367
2429
|
if (Array.isArray(message.content)) return message.content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
|
|
2368
2430
|
return String(message.content);
|
|
2369
2431
|
}
|
|
2432
|
+
/**
|
|
2433
|
+
* Whether a content block is an image. Tool-result eviction skips images when
|
|
2434
|
+
* sizing a result and keeps them when evicting it: base64 length says little
|
|
2435
|
+
* about what a provider charges for an image.
|
|
2436
|
+
*/
|
|
2437
|
+
function isImageBlock(block) {
|
|
2438
|
+
return typeof block === "object" && block !== null && "type" in block && (block.type === "image" || block.type === "image_url");
|
|
2439
|
+
}
|
|
2370
2440
|
function stringifyToolContent(content) {
|
|
2371
2441
|
if (typeof content === "string") return content;
|
|
2372
|
-
if (Array.isArray(content)) return content.map((block) => {
|
|
2442
|
+
if (Array.isArray(content)) return content.filter((block) => !isImageBlock(block)).map((block) => {
|
|
2373
2443
|
if (typeof block === "object" && block !== null && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string") return block.text;
|
|
2374
2444
|
return JSON.stringify(block);
|
|
2375
2445
|
}).join("\n");
|
|
2376
2446
|
return String(content);
|
|
2377
2447
|
}
|
|
2378
2448
|
/**
|
|
2379
|
-
* Build replacement content for an evicted
|
|
2449
|
+
* Build replacement content for an evicted message, preserving the blocks `keep` selects.
|
|
2380
2450
|
*
|
|
2381
2451
|
* For plain string content, returns the replacement text directly. For list content
|
|
2382
|
-
* with mixed block types (e.g., text + image), replaces
|
|
2383
|
-
* text block containing the replacement text while keeping
|
|
2452
|
+
* with mixed block types (e.g., text + image), replaces the other blocks with a single
|
|
2453
|
+
* text block containing the replacement text while keeping the selected blocks intact.
|
|
2454
|
+
* By default every non-text block is kept.
|
|
2384
2455
|
*/
|
|
2385
|
-
function
|
|
2456
|
+
function buildEvictedContent(message, replacementText, keep = (block) => block.type !== "text") {
|
|
2386
2457
|
if (typeof message.content === "string") return replacementText;
|
|
2387
2458
|
if (Array.isArray(message.content)) {
|
|
2388
|
-
const
|
|
2389
|
-
if (
|
|
2459
|
+
const keptBlocks = message.content.filter((block) => typeof block === "object" && block !== null && keep(block));
|
|
2460
|
+
if (keptBlocks.length === 0) return replacementText;
|
|
2390
2461
|
return [{
|
|
2391
2462
|
type: "text",
|
|
2392
2463
|
text: replacementText
|
|
2393
|
-
}, ...
|
|
2464
|
+
}, ...keptBlocks];
|
|
2394
2465
|
}
|
|
2395
2466
|
return replacementText;
|
|
2396
2467
|
}
|
|
@@ -2403,7 +2474,7 @@ function buildEvictedHumanContent(message, replacementText) {
|
|
|
2403
2474
|
*/
|
|
2404
2475
|
function buildTruncatedHumanMessage(message, filePath) {
|
|
2405
2476
|
const contentSample = createContentPreview(extractTextFromMessage(message));
|
|
2406
|
-
const evictedContent =
|
|
2477
|
+
const evictedContent = buildEvictedContent(message, TOO_LARGE_HUMAN_MSG.replace("{file_path}", filePath).replace("{content_sample}", contentSample));
|
|
2407
2478
|
return new langchain.HumanMessage({
|
|
2408
2479
|
content: evictedContent,
|
|
2409
2480
|
id: message.id,
|
|
@@ -2443,6 +2514,7 @@ const FileDataV1Schema = zod_v4.z.object({
|
|
|
2443
2514
|
const FileDataV2Schema = zod_v4.z.object({
|
|
2444
2515
|
content: zod_v4.z.union([zod_v4.z.string(), zod_v4.z.instanceof(Uint8Array)]),
|
|
2445
2516
|
mimeType: zod_v4.z.string(),
|
|
2517
|
+
encoding: zod_v4.z.enum(["utf-8", "base64"]).optional(),
|
|
2446
2518
|
created_at: zod_v4.z.string(),
|
|
2447
2519
|
modified_at: zod_v4.z.string()
|
|
2448
2520
|
});
|
|
@@ -3329,7 +3401,7 @@ function createFilesystemMiddleware(options = {}) {
|
|
|
3329
3401
|
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);
|
|
3330
3402
|
return {
|
|
3331
3403
|
message: new langchain.ToolMessage({
|
|
3332
|
-
content: replacementText,
|
|
3404
|
+
content: buildEvictedContent(msg, replacementText, isImageBlock),
|
|
3333
3405
|
tool_call_id: msg.tool_call_id,
|
|
3334
3406
|
name: msg.name,
|
|
3335
3407
|
id: msg.id,
|
|
@@ -3396,7 +3468,7 @@ function createFilesystemMiddleware(options = {}) {
|
|
|
3396
3468
|
pending: []
|
|
3397
3469
|
}, resolvedBackend, BLOBS_PREFIX, blobCache);
|
|
3398
3470
|
messages = await hydrateMessages(messages, resolvedBackend, BLOBS_PREFIX, blobCache);
|
|
3399
|
-
}
|
|
3471
|
+
} else if (messages) messages = withoutBlobRefs(messages);
|
|
3400
3472
|
const finalRequest = {
|
|
3401
3473
|
...request,
|
|
3402
3474
|
tools,
|
|
@@ -6263,6 +6335,9 @@ function createSkillsMiddleware(options) {
|
|
|
6263
6335
|
*
|
|
6264
6336
|
* @experimental - this middleware is experimental and may change in future releases.
|
|
6265
6337
|
*
|
|
6338
|
+
* @deprecated `createDeepAgent` now notifies the launching agent on its own;
|
|
6339
|
+
* adding this middleware too sends the parent two notifications per task.
|
|
6340
|
+
*
|
|
6266
6341
|
* This middleware sends a notification to a callback thread when a subagent
|
|
6267
6342
|
* completes successfully or raises an error. The callback agent can then
|
|
6268
6343
|
* process that notification instead of relying only on polling via
|
|
@@ -6371,7 +6446,7 @@ function resolveHeaders(headers) {
|
|
|
6371
6446
|
* @param message - The message content to send.
|
|
6372
6447
|
* @param options - Optional url and headers for the callback server.
|
|
6373
6448
|
*/
|
|
6374
|
-
async function notifyParent(callbackGraphId, callbackThreadId, message, options) {
|
|
6449
|
+
async function notifyParent$1(callbackGraphId, callbackThreadId, message, options) {
|
|
6375
6450
|
try {
|
|
6376
6451
|
await new _langchain_langgraph_sdk.Client({
|
|
6377
6452
|
apiUrl: options?.url ?? void 0,
|
|
@@ -6422,6 +6497,9 @@ function extractLastMessage(state, taskId) {
|
|
|
6422
6497
|
* If `callbackThreadId` is not present in state, the middleware does
|
|
6423
6498
|
* nothing.
|
|
6424
6499
|
*
|
|
6500
|
+
* @deprecated `createDeepAgent` now notifies the launching agent on its own;
|
|
6501
|
+
* adding this middleware too sends the parent two notifications per task.
|
|
6502
|
+
*
|
|
6425
6503
|
* @param options - Configuration options.
|
|
6426
6504
|
* @returns An `AgentMiddleware` instance.
|
|
6427
6505
|
*
|
|
@@ -6445,7 +6523,7 @@ function createCompletionCallbackMiddleware(options) {
|
|
|
6445
6523
|
* Send a notification to the callback destination.
|
|
6446
6524
|
*/
|
|
6447
6525
|
async function sendNotification(callbackThreadId, message) {
|
|
6448
|
-
await notifyParent(callbackGraphId, callbackThreadId, message, {
|
|
6526
|
+
await notifyParent$1(callbackGraphId, callbackThreadId, message, {
|
|
6449
6527
|
url,
|
|
6450
6528
|
headers
|
|
6451
6529
|
});
|
|
@@ -6515,6 +6593,7 @@ const AsyncTaskSchema = zod_v4.z.object({
|
|
|
6515
6593
|
agentName: zod_v4.z.string(),
|
|
6516
6594
|
threadId: zod_v4.z.string(),
|
|
6517
6595
|
runId: zod_v4.z.string(),
|
|
6596
|
+
supersededRunIds: zod_v4.z.array(zod_v4.z.string()).optional(),
|
|
6518
6597
|
status: zod_v4.z.string(),
|
|
6519
6598
|
createdAt: zod_v4.z.string(),
|
|
6520
6599
|
description: zod_v4.z.string().optional(),
|
|
@@ -6562,16 +6641,11 @@ Available async agent types:
|
|
|
6562
6641
|
|
|
6563
6642
|
## Usage notes:
|
|
6564
6643
|
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.
|
|
6644
|
+
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
6645
|
3. Use \`update_async_task\` to send new instructions to a running task.
|
|
6567
6646
|
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
|
-
*/
|
|
6647
|
+
5. The subagent runs on a remote server, so it has its own tools and capabilities.
|
|
6648
|
+
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
6649
|
/**
|
|
6576
6650
|
* Names of the tools added by the async subagent middleware.
|
|
6577
6651
|
*
|
|
@@ -6585,6 +6659,7 @@ const ASYNC_TASK_TOOL_NAMES = [
|
|
|
6585
6659
|
"cancel_async_task",
|
|
6586
6660
|
"list_async_tasks"
|
|
6587
6661
|
];
|
|
6662
|
+
/** Task statuses that never change, so live-status fetches can be skipped; `waiting` can still resume. */
|
|
6588
6663
|
const TERMINAL_STATUSES = /* @__PURE__ */ new Set([
|
|
6589
6664
|
"cancelled",
|
|
6590
6665
|
"success",
|
|
@@ -6604,32 +6679,141 @@ function resolveTrackedTask(taskId, state) {
|
|
|
6604
6679
|
if (!tracked) return `No tracked task found for taskId: '${taskId}'`;
|
|
6605
6680
|
return tracked;
|
|
6606
6681
|
}
|
|
6682
|
+
/** Guidance for a task whose latest run hasn't started. */
|
|
6683
|
+
const PENDING_NOTE = "The latest run hasn't started yet. If it is a queued follow-up, an earlier run may still be working.";
|
|
6684
|
+
/** Task status implied by the thread when the tracked run finished but the thread moved on. */
|
|
6685
|
+
const THREAD_TO_TASK_STATUS = {
|
|
6686
|
+
interrupted: "waiting",
|
|
6687
|
+
busy: "running",
|
|
6688
|
+
error: "error"
|
|
6689
|
+
};
|
|
6607
6690
|
/**
|
|
6608
|
-
*
|
|
6691
|
+
* Return a task's status from its latest run, reading the thread to spot pauses.
|
|
6609
6692
|
*
|
|
6610
|
-
*
|
|
6611
|
-
*
|
|
6693
|
+
* A run that hits `interrupt()` ends as `success`; only its thread shows the pause.
|
|
6694
|
+
* A run cancelled on the server ends `interrupted`, which a task reports as `cancelled`.
|
|
6695
|
+
*/
|
|
6696
|
+
function taskStatus(run, thread) {
|
|
6697
|
+
if (run.status === "interrupted") return "cancelled";
|
|
6698
|
+
if (run.status !== "success" || thread === null) return run.status;
|
|
6699
|
+
return THREAD_TO_TASK_STATUS[thread.status] ?? "success";
|
|
6700
|
+
}
|
|
6701
|
+
/** Whether a newer run exists than the tracked one, e.g. after a resume from another client. */
|
|
6702
|
+
function needsLatestRun(run, thread) {
|
|
6703
|
+
return run.status === "success" && thread !== null && (thread.status === "busy" || thread.status === "error");
|
|
6704
|
+
}
|
|
6705
|
+
/**
|
|
6706
|
+
* Fetch a task's latest run and, when that run finished, its thread (else `null`).
|
|
6612
6707
|
*
|
|
6613
|
-
*
|
|
6614
|
-
*
|
|
6615
|
-
*
|
|
6708
|
+
* Throws if the thread can't be read, since a paused run also ends as `success`.
|
|
6709
|
+
* A run replaced by another client's run hands over to the newest one, except for
|
|
6710
|
+
* a task the parent cancelled.
|
|
6616
6711
|
*/
|
|
6617
|
-
function
|
|
6712
|
+
async function observeTaskRun(client, task, signal) {
|
|
6713
|
+
let run = await client.runs.get(task.threadId, task.runId, { signal });
|
|
6714
|
+
if (run.status === "interrupted" && task.status !== "cancelled") {
|
|
6715
|
+
const [latest] = await client.runs.list(task.threadId, {
|
|
6716
|
+
limit: 1,
|
|
6717
|
+
signal
|
|
6718
|
+
});
|
|
6719
|
+
run = latest ?? run;
|
|
6720
|
+
}
|
|
6721
|
+
if (run.status !== "success") return [run, null];
|
|
6722
|
+
const thread = await client.threads.get(task.threadId, { signal });
|
|
6723
|
+
if (needsLatestRun(run, thread)) {
|
|
6724
|
+
const [latest] = await client.runs.list(task.threadId, {
|
|
6725
|
+
limit: 1,
|
|
6726
|
+
signal
|
|
6727
|
+
});
|
|
6728
|
+
run = latest ?? run;
|
|
6729
|
+
}
|
|
6730
|
+
return [run, thread];
|
|
6731
|
+
}
|
|
6732
|
+
/** Flatten a thread's pending interrupts, including ones raised inside subgraphs. */
|
|
6733
|
+
function pendingInterrupts(thread) {
|
|
6734
|
+
if (!thread?.interrupts) return [];
|
|
6735
|
+
return Object.values(thread.interrupts).flat();
|
|
6736
|
+
}
|
|
6737
|
+
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.";
|
|
6738
|
+
/** The thread's messages, if its values hold any. */
|
|
6739
|
+
function threadMessages(values) {
|
|
6740
|
+
if (values === null || typeof values !== "object" || Array.isArray(values)) return [];
|
|
6741
|
+
const messages = values.messages;
|
|
6742
|
+
return Array.isArray(messages) ? messages : [];
|
|
6743
|
+
}
|
|
6744
|
+
/** A thread message's content as text, whatever shape the server sent it in. */
|
|
6745
|
+
function messageText(message) {
|
|
6746
|
+
if (_langchain_core_messages.BaseMessage.isInstance(message)) return message.text;
|
|
6747
|
+
const content = typeof message === "object" && message !== null && "content" in message ? message.content : message;
|
|
6748
|
+
return typeof content === "string" ? content : JSON.stringify(content);
|
|
6749
|
+
}
|
|
6750
|
+
/**
|
|
6751
|
+
* Build a check result from a task's latest run and its thread.
|
|
6752
|
+
*
|
|
6753
|
+
* @param run - The task's latest run.
|
|
6754
|
+
* @param threadId - The task's thread ID.
|
|
6755
|
+
* @param thread - The task's thread, when its run finished.
|
|
6756
|
+
*/
|
|
6757
|
+
function buildCheckResult(run, threadId, thread) {
|
|
6758
|
+
const status = taskStatus(run, thread);
|
|
6618
6759
|
const checkResult = {
|
|
6619
|
-
status
|
|
6760
|
+
status,
|
|
6620
6761
|
threadId
|
|
6621
6762
|
};
|
|
6622
|
-
if (
|
|
6623
|
-
|
|
6624
|
-
|
|
6625
|
-
|
|
6626
|
-
|
|
6627
|
-
|
|
6628
|
-
|
|
6629
|
-
|
|
6763
|
+
if (status === "pending") checkResult.note = PENDING_NOTE;
|
|
6764
|
+
else if (status === "success") checkResult.result = finalContent(thread?.values);
|
|
6765
|
+
else if (status === "error") checkResult.error = "The async subagent encountered an error.";
|
|
6766
|
+
else if (status === "waiting") {
|
|
6767
|
+
checkResult.interrupts = pendingInterrupts(thread).map((item) => ({
|
|
6768
|
+
id: item.id ?? "",
|
|
6769
|
+
value: item.value
|
|
6770
|
+
}));
|
|
6771
|
+
checkResult.note = WAITING_NOTE;
|
|
6772
|
+
}
|
|
6630
6773
|
return checkResult;
|
|
6631
6774
|
}
|
|
6632
6775
|
/**
|
|
6776
|
+
* A check result as tool output: JSON, with a text-only answer's text in `result`.
|
|
6777
|
+
*
|
|
6778
|
+
* An answer with media follows the JSON as its own blocks, in order. Reasoning and
|
|
6779
|
+
* tool-call blocks are dropped; the text isn't cut.
|
|
6780
|
+
*/
|
|
6781
|
+
function checkOutput(result) {
|
|
6782
|
+
const blocks = result.result;
|
|
6783
|
+
if (!blocks) return JSON.stringify(result);
|
|
6784
|
+
const text = (block) => String(block.text);
|
|
6785
|
+
if (!blocks.some((block) => MEDIA_BLOCK_TYPES.has(block.type))) {
|
|
6786
|
+
const answer = blocks.filter((block) => block.type === "text").map(text);
|
|
6787
|
+
return JSON.stringify({
|
|
6788
|
+
...result,
|
|
6789
|
+
result: answer.join("")
|
|
6790
|
+
});
|
|
6791
|
+
}
|
|
6792
|
+
const { result: _answer, ...status } = result;
|
|
6793
|
+
const answer = blocks.filter((block) => block.type === "text" || MEDIA_BLOCK_TYPES.has(block.type)).map((block) => block.type === "text" ? textBlock(text(block)) : { ...block });
|
|
6794
|
+
return [textBlock(JSON.stringify(status)), ...answer];
|
|
6795
|
+
}
|
|
6796
|
+
/** Keep a task cancelled while paused as cancelled; its thread still shows the old pause. */
|
|
6797
|
+
function keepCancelled(task, result) {
|
|
6798
|
+
if (task.status === "cancelled" && result.status === "waiting") return {
|
|
6799
|
+
status: "cancelled",
|
|
6800
|
+
threadId: result.threadId
|
|
6801
|
+
};
|
|
6802
|
+
return result;
|
|
6803
|
+
}
|
|
6804
|
+
/** `task` updated to what a check found. */
|
|
6805
|
+
function observed(task, status, runId) {
|
|
6806
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
6807
|
+
const changed = status !== task.status || runId !== task.runId;
|
|
6808
|
+
return {
|
|
6809
|
+
...task,
|
|
6810
|
+
runId,
|
|
6811
|
+
status,
|
|
6812
|
+
updatedAt: changed ? now : task.updatedAt,
|
|
6813
|
+
checkedAt: now
|
|
6814
|
+
};
|
|
6815
|
+
}
|
|
6816
|
+
/**
|
|
6633
6817
|
* Filter tasks by cached status from agent state.
|
|
6634
6818
|
*
|
|
6635
6819
|
* Filtering uses the cached status, not live server status. Live statuses
|
|
@@ -6644,17 +6828,17 @@ function filterTasks(tasks, statusFilter) {
|
|
|
6644
6828
|
return Object.values(tasks).filter((task) => task.status === statusFilter);
|
|
6645
6829
|
}
|
|
6646
6830
|
/**
|
|
6647
|
-
* Fetch
|
|
6831
|
+
* Fetch a task's current status and run ID.
|
|
6648
6832
|
*
|
|
6649
|
-
* Returns the cached
|
|
6650
|
-
* unnecessary API calls). Falls back to the cached status on SDK errors.
|
|
6833
|
+
* Returns the cached values for terminal tasks and on SDK errors.
|
|
6651
6834
|
*/
|
|
6652
6835
|
async function fetchLiveTaskStatus(clients, task) {
|
|
6653
|
-
if (TERMINAL_STATUSES.has(task.status)) return task.status;
|
|
6836
|
+
if (TERMINAL_STATUSES.has(task.status)) return [task.status, task.runId];
|
|
6654
6837
|
try {
|
|
6655
|
-
|
|
6838
|
+
const [run, thread] = await observeTaskRun(clients.getClient(task.agentName), task);
|
|
6839
|
+
return [taskStatus(run, thread), run.run_id];
|
|
6656
6840
|
} catch {
|
|
6657
|
-
return task.status;
|
|
6841
|
+
return [task.status, task.runId];
|
|
6658
6842
|
}
|
|
6659
6843
|
}
|
|
6660
6844
|
/**
|
|
@@ -6697,9 +6881,18 @@ var ClientCache = class {
|
|
|
6697
6881
|
}
|
|
6698
6882
|
/**
|
|
6699
6883
|
* Get or create a `Client` for the named agent.
|
|
6884
|
+
*
|
|
6885
|
+
* With `extraHeaders` (such as one launch's trace headers), returns a new, uncached client.
|
|
6700
6886
|
*/
|
|
6701
|
-
getClient(name) {
|
|
6887
|
+
getClient(name, extraHeaders = {}) {
|
|
6702
6888
|
const spec = this.agents[name];
|
|
6889
|
+
if (Object.keys(extraHeaders).length > 0) return new _langchain_langgraph_sdk.Client({
|
|
6890
|
+
apiUrl: spec.url,
|
|
6891
|
+
defaultHeaders: {
|
|
6892
|
+
...this.resolveHeaders(spec),
|
|
6893
|
+
...extraHeaders
|
|
6894
|
+
}
|
|
6895
|
+
});
|
|
6703
6896
|
const key = this.cacheKey(spec);
|
|
6704
6897
|
const existing = this.clients.get(key);
|
|
6705
6898
|
if (existing) return existing;
|
|
@@ -6713,6 +6906,318 @@ var ClientCache = class {
|
|
|
6713
6906
|
}
|
|
6714
6907
|
};
|
|
6715
6908
|
/**
|
|
6909
|
+
* Baggage metadata key (JSON `true`) marking trace headers as a parent to nest under.
|
|
6910
|
+
*
|
|
6911
|
+
* Receivers that adopt the trace check for it, so keep the name stable.
|
|
6912
|
+
*/
|
|
6913
|
+
const NEST_UNDER_PARENT = "ls_nest_under_parent";
|
|
6914
|
+
/**
|
|
6915
|
+
* Build LangSmith headers pointing at the current span, or `{}` when tracing is off.
|
|
6916
|
+
*
|
|
6917
|
+
* Only sent to subagents on this deployment (no `url`). The baggage carries the
|
|
6918
|
+
* project and `NEST_UNDER_PARENT`, not the caller's run metadata. Any `baggage`
|
|
6919
|
+
* in the spec's headers is kept.
|
|
6920
|
+
*/
|
|
6921
|
+
function traceHeaders(spec) {
|
|
6922
|
+
if (spec.url) return {};
|
|
6923
|
+
const runTree = (0, langsmith_traceable.getCurrentRunTree)(true);
|
|
6924
|
+
if (!runTree?.tracingEnabled || !runTree.trace_id || !runTree.dotted_order) return {};
|
|
6925
|
+
const baggage = Object.entries(spec.headers ?? {}).filter(([key, value]) => key.toLowerCase() === "baggage" && value).map(([, value]) => value);
|
|
6926
|
+
baggage.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify({ [NEST_UNDER_PARENT]: true }))}`);
|
|
6927
|
+
if (runTree.project_name) baggage.push(`langsmith-project=${encodeURIComponent(runTree.project_name)}`);
|
|
6928
|
+
return {
|
|
6929
|
+
"langsmith-trace": runTree.dotted_order,
|
|
6930
|
+
baggage: baggage.join(",")
|
|
6931
|
+
};
|
|
6932
|
+
}
|
|
6933
|
+
/**
|
|
6934
|
+
* `configurable` key carrying the launching agent's reference to an async subagent's run.
|
|
6935
|
+
*
|
|
6936
|
+
* Apps read it directly, and Python deep agents use the same key, so keep the key and shape stable.
|
|
6937
|
+
*/
|
|
6938
|
+
const PARENT_KEY = "deepagents_parent";
|
|
6939
|
+
/** Describe the running agent so the async subagent it launches can find it. */
|
|
6940
|
+
function parentReference(config) {
|
|
6941
|
+
const reference = {};
|
|
6942
|
+
const configurable = config?.configurable ?? {};
|
|
6943
|
+
const metadata = config?.metadata ?? {};
|
|
6944
|
+
if (configurable.thread_id) reference.thread_id = String(configurable.thread_id);
|
|
6945
|
+
const assistantId = metadata.assistant_id || configurable.assistant_id;
|
|
6946
|
+
if (assistantId) reference.assistant_id = String(assistantId);
|
|
6947
|
+
return reference;
|
|
6948
|
+
}
|
|
6949
|
+
/**
|
|
6950
|
+
* The parent reference sent to `spec`'s runs.
|
|
6951
|
+
*
|
|
6952
|
+
* A subagent on another server (`url`) or with `notifyParent: false` gets only the
|
|
6953
|
+
* parent's thread: the assistant is for waking the parent, which it can't do.
|
|
6954
|
+
*/
|
|
6955
|
+
function referenceFor(spec, config) {
|
|
6956
|
+
const { thread_id, assistant_id } = parentReference(config);
|
|
6957
|
+
const wakesParent = !spec.url && spec.notifyParent !== false;
|
|
6958
|
+
return {
|
|
6959
|
+
...thread_id && { thread_id },
|
|
6960
|
+
...wakesParent && assistant_id && { assistant_id }
|
|
6961
|
+
};
|
|
6962
|
+
}
|
|
6963
|
+
/**
|
|
6964
|
+
* Metadata for a task's thread, so apps can find a parent's subagent threads with `threads.search`.
|
|
6965
|
+
*
|
|
6966
|
+
* It names the subagent as the parent knows it, and for subagents on this deployment
|
|
6967
|
+
* keeps the parent's assistant, so other runs on the thread (such as the user
|
|
6968
|
+
* answering the subagent) can still notify the parent.
|
|
6969
|
+
*/
|
|
6970
|
+
function threadMetadata(spec, config) {
|
|
6971
|
+
const reference = referenceFor(spec, config);
|
|
6972
|
+
const metadata = { subagent_name: spec.name };
|
|
6973
|
+
if (reference.thread_id) metadata.parent_thread_id = reference.thread_id;
|
|
6974
|
+
if (reference.assistant_id) metadata.parent_assistant_id = reference.assistant_id;
|
|
6975
|
+
return metadata;
|
|
6976
|
+
}
|
|
6977
|
+
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";
|
|
6978
|
+
/** A message as portable input for another run, without parent-local eviction tags. */
|
|
6979
|
+
function serializeForkMessage(message) {
|
|
6980
|
+
const { lc_evicted_to: _evicted, ...additionalKwargs } = message.additional_kwargs ?? {};
|
|
6981
|
+
const serialized = {
|
|
6982
|
+
type: message.type,
|
|
6983
|
+
content: message.content,
|
|
6984
|
+
additional_kwargs: additionalKwargs
|
|
6985
|
+
};
|
|
6986
|
+
if (message.id) serialized.id = message.id;
|
|
6987
|
+
if (message.name) serialized.name = message.name;
|
|
6988
|
+
if (_langchain_core_messages.AIMessage.isInstance(message)) serialized.tool_calls = message.tool_calls;
|
|
6989
|
+
if (_langchain_core_messages.ToolMessage.isInstance(message)) {
|
|
6990
|
+
serialized.tool_call_id = message.tool_call_id;
|
|
6991
|
+
serialized.status = message.status;
|
|
6992
|
+
}
|
|
6993
|
+
return serialized;
|
|
6994
|
+
}
|
|
6995
|
+
/**
|
|
6996
|
+
* The task's input messages: the parent's effective conversation for forks, or only the task.
|
|
6997
|
+
*
|
|
6998
|
+
* A fork keeps references to the parent's offloaded media; a subagent sharing the
|
|
6999
|
+
* parent's backend loads them, and any other sees that the content is unavailable.
|
|
7000
|
+
*/
|
|
7001
|
+
function startTaskMessages(spec, state, description) {
|
|
7002
|
+
if (spec.mode !== "fork") return [{
|
|
7003
|
+
role: "user",
|
|
7004
|
+
content: description
|
|
7005
|
+
}];
|
|
7006
|
+
return [...getEffectiveMessages(stripInFlightAIMessage(state.messages ?? []), state), new _langchain_core_messages.HumanMessage({ content: ASYNC_FORK_TASK_PREAMBLE + description })].map(serializeForkMessage);
|
|
7007
|
+
}
|
|
7008
|
+
/** Describe a subagent's context inheritance without promising shared tools. */
|
|
7009
|
+
function describeAsyncSubAgent(spec) {
|
|
7010
|
+
const suffix = spec.mode === "fork" ? " (inherits your conversation at launch; uses its own system prompt and tools)" : "";
|
|
7011
|
+
return `- ${spec.name}: ${spec.description}${suffix}`;
|
|
7012
|
+
}
|
|
7013
|
+
/**
|
|
7014
|
+
* The `runs.create` options that link a run to this agent and set the subagent's webhook.
|
|
7015
|
+
*
|
|
7016
|
+
* A subagent on this deployment runs with this agent's context. The Agent Server
|
|
7017
|
+
* takes `context` or `configurable`, not both, so the parent reference then goes
|
|
7018
|
+
* through the thread's metadata.
|
|
7019
|
+
*/
|
|
7020
|
+
function runOptions(spec, runtime) {
|
|
7021
|
+
const webhook = spec.webhook ? { webhook: spec.webhook } : {};
|
|
7022
|
+
const context = spec.url ? void 0 : forwardedContext(runtime.context);
|
|
7023
|
+
if (context) return {
|
|
7024
|
+
...webhook,
|
|
7025
|
+
context
|
|
7026
|
+
};
|
|
7027
|
+
const reference = referenceFor(spec, runtime.config);
|
|
7028
|
+
return Object.keys(reference).length > 0 ? {
|
|
7029
|
+
...webhook,
|
|
7030
|
+
config: { configurable: { [PARENT_KEY]: reference } }
|
|
7031
|
+
} : webhook;
|
|
7032
|
+
}
|
|
7033
|
+
/** A run context as JSON data for another run, without deepagents' parent reference. */
|
|
7034
|
+
function forwardedContext(context) {
|
|
7035
|
+
if (!context || typeof context !== "object" || Array.isArray(context)) return;
|
|
7036
|
+
const entries = Object.entries(context).filter(([key]) => key !== PARENT_KEY);
|
|
7037
|
+
return entries.length > 0 ? Object.fromEntries(entries) : void 0;
|
|
7038
|
+
}
|
|
7039
|
+
/**
|
|
7040
|
+
* The agent that launched this run's task, or `null` if no async subagent tool did.
|
|
7041
|
+
*
|
|
7042
|
+
* Read from the run's config, or else from the task thread's metadata, which the
|
|
7043
|
+
* Agent Server copies into every run on the thread (such as the user's answer).
|
|
7044
|
+
*/
|
|
7045
|
+
function launchingAgent(config) {
|
|
7046
|
+
const reference = (config?.configurable ?? {})[PARENT_KEY];
|
|
7047
|
+
if (reference && typeof reference === "object" && !Array.isArray(reference)) return reference;
|
|
7048
|
+
const metadata = config?.metadata ?? {};
|
|
7049
|
+
if (!metadata.parent_thread_id) return null;
|
|
7050
|
+
const fallback = { thread_id: String(metadata.parent_thread_id) };
|
|
7051
|
+
if (metadata.parent_assistant_id) fallback.assistant_id = String(metadata.parent_assistant_id);
|
|
7052
|
+
return fallback;
|
|
7053
|
+
}
|
|
7054
|
+
/** Message field (`additional_kwargs` key) marking a task notification and carrying its {@link TaskEvent}. */
|
|
7055
|
+
const NOTIFICATION_KEY = "deepagents_notification";
|
|
7056
|
+
/** Results longer than this are cut in notifications, matching the limit for large tool results. */
|
|
7057
|
+
const MAX_RESULT_CHARS = 8e4;
|
|
7058
|
+
const NEXT_STEP = {
|
|
7059
|
+
success: "Use the result to continue; report back to the user if they're waiting on it.",
|
|
7060
|
+
error: "Use `check_async_task` for details, then decide whether to retry, try another approach, or tell the user.",
|
|
7061
|
+
timeout: "The task ran too long and was stopped. Decide whether to retry with a smaller task, or tell the user.",
|
|
7062
|
+
cancelled: "The task's run was cancelled before it finished, outside your tools. Decide whether to start it again, or tell the user.",
|
|
7063
|
+
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."
|
|
7064
|
+
};
|
|
7065
|
+
function textBlock(text) {
|
|
7066
|
+
return {
|
|
7067
|
+
type: "text",
|
|
7068
|
+
text
|
|
7069
|
+
};
|
|
7070
|
+
}
|
|
7071
|
+
/** Escape subagent-controlled text so it can't close the notification's tags and pose as the system. */
|
|
7072
|
+
function escape(text) {
|
|
7073
|
+
return text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
7074
|
+
}
|
|
7075
|
+
function clip(text) {
|
|
7076
|
+
if (text.length <= MAX_RESULT_CHARS) return text;
|
|
7077
|
+
return `${text.slice(0, MAX_RESULT_CHARS)}\n... [cut off; use \`check_async_task\` for the full details]`;
|
|
7078
|
+
}
|
|
7079
|
+
/** Standard content blocks passed on as they are; a notification is a user message, where providers reject the rest. */
|
|
7080
|
+
const MEDIA_BLOCK_TYPES = /* @__PURE__ */ new Set([
|
|
7081
|
+
"image",
|
|
7082
|
+
"audio",
|
|
7083
|
+
"video",
|
|
7084
|
+
"file"
|
|
7085
|
+
]);
|
|
7086
|
+
/**
|
|
7087
|
+
* The subagent's answer as user content: text escaped and cut when very long, media as it is.
|
|
7088
|
+
*
|
|
7089
|
+
* Reasoning, tool calls and blocks LangChain doesn't recognize are dropped.
|
|
7090
|
+
*/
|
|
7091
|
+
function resultBlocks(blocks) {
|
|
7092
|
+
const kept = [];
|
|
7093
|
+
for (const block of blocks) if (block.type === "text") kept.push(textBlock(escape(clip(String(block.text)))));
|
|
7094
|
+
else if (MEDIA_BLOCK_TYPES.has(block.type)) kept.push({ ...block });
|
|
7095
|
+
return kept;
|
|
7096
|
+
}
|
|
7097
|
+
/**
|
|
7098
|
+
* Frame a task update as a system notification the model won't mistake for the user.
|
|
7099
|
+
*
|
|
7100
|
+
* The result keeps its own content blocks, so an image reaches the model as an image.
|
|
7101
|
+
*/
|
|
7102
|
+
function notificationContent(update) {
|
|
7103
|
+
const blocks = [notificationHeader(update)];
|
|
7104
|
+
if (update.result) blocks.push(textBlock("<result>\n"), ...resultBlocks(update.result), textBlock("\n</result>\n"));
|
|
7105
|
+
const details = Object.fromEntries(["error", "interrupts"].filter((key) => update[key] !== void 0).map((key) => [key, update[key]]));
|
|
7106
|
+
if (Object.keys(details).length > 0) blocks.push(textBlock(`<details>${escape(clip(JSON.stringify(details)))}</details>\n`));
|
|
7107
|
+
blocks.push(textBlock(`</task-notification>\n${NEXT_STEP[update.status]}`));
|
|
7108
|
+
return blocks;
|
|
7109
|
+
}
|
|
7110
|
+
function notificationHeader(event) {
|
|
7111
|
+
return textBlock(`[SYSTEM NOTIFICATION - NOT USER INPUT]
|
|
7112
|
+
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.
|
|
7113
|
+
<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`);
|
|
7114
|
+
}
|
|
7115
|
+
/**
|
|
7116
|
+
* Reframe an earlier run's notification so the model doesn't think the queued follow-up finished.
|
|
7117
|
+
*
|
|
7118
|
+
* Only the closing next step changes; the earlier run's result and details stay.
|
|
7119
|
+
*/
|
|
7120
|
+
function supersededNotificationContent(message, event) {
|
|
7121
|
+
const content = message.content;
|
|
7122
|
+
const closing = Array.isArray(content) ? content.at(-1) : void 0;
|
|
7123
|
+
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.")];
|
|
7124
|
+
}
|
|
7125
|
+
/** Describe a failure without its message, which can carry internals into the parent's conversation. */
|
|
7126
|
+
function failureText(error) {
|
|
7127
|
+
return `The subagent failed (${typeof error === "object" && error !== null && "name" in error ? String(error.name) : typeof error}).`;
|
|
7128
|
+
}
|
|
7129
|
+
/** The ID of the run this config belongs to, when the Agent Server set it. */
|
|
7130
|
+
function currentRunId(config) {
|
|
7131
|
+
const metadata = config?.metadata ?? {};
|
|
7132
|
+
const configurable = config?.configurable ?? {};
|
|
7133
|
+
const runId = metadata.run_id ?? configurable.run_id;
|
|
7134
|
+
return runId ? String(runId) : void 0;
|
|
7135
|
+
}
|
|
7136
|
+
/** Build a task update; `details` are the status's `result`, `error` or `interrupts`. */
|
|
7137
|
+
function taskUpdate(event, details = {}) {
|
|
7138
|
+
const update = {
|
|
7139
|
+
task_id: event.task_id,
|
|
7140
|
+
agent_name: event.agent_name,
|
|
7141
|
+
status: event.status,
|
|
7142
|
+
...details
|
|
7143
|
+
};
|
|
7144
|
+
if (event.run_id) update.run_id = event.run_id;
|
|
7145
|
+
return update;
|
|
7146
|
+
}
|
|
7147
|
+
/** Describe how this run's task ended. */
|
|
7148
|
+
function taskEvent(config, agentName, status, details = {}) {
|
|
7149
|
+
const configurable = config?.configurable ?? {};
|
|
7150
|
+
return taskUpdate({
|
|
7151
|
+
task_id: String(configurable.thread_id ?? ""),
|
|
7152
|
+
agent_name: agentName,
|
|
7153
|
+
status,
|
|
7154
|
+
run_id: currentRunId(config)
|
|
7155
|
+
}, details);
|
|
7156
|
+
}
|
|
7157
|
+
/** The subagent's last message as standard content blocks, the task's result; it may hold images. */
|
|
7158
|
+
function finalContent(values) {
|
|
7159
|
+
const messages = threadMessages(values);
|
|
7160
|
+
if (messages.length === 0) return [{
|
|
7161
|
+
type: "text",
|
|
7162
|
+
text: "(completed with no output messages)"
|
|
7163
|
+
}];
|
|
7164
|
+
const last = messages[messages.length - 1];
|
|
7165
|
+
try {
|
|
7166
|
+
return (0, _langchain_core_messages.coerceMessageLikeToMessage)(last).contentBlocks;
|
|
7167
|
+
} catch {
|
|
7168
|
+
return [{
|
|
7169
|
+
type: "text",
|
|
7170
|
+
text: messageText(last)
|
|
7171
|
+
}];
|
|
7172
|
+
}
|
|
7173
|
+
}
|
|
7174
|
+
/** The task event a notification message carries, or `null` for any other message. */
|
|
7175
|
+
function notificationEvent(message) {
|
|
7176
|
+
const event = message?.additional_kwargs?.[NOTIFICATION_KEY];
|
|
7177
|
+
return event && typeof event === "object" && !Array.isArray(event) ? event : null;
|
|
7178
|
+
}
|
|
7179
|
+
/** A task update as the message the parent's model sees, marked with its {@link TaskEvent} so apps can recognize it. */
|
|
7180
|
+
function notificationMessage(update) {
|
|
7181
|
+
const event = {
|
|
7182
|
+
task_id: update.task_id,
|
|
7183
|
+
agent_name: update.agent_name,
|
|
7184
|
+
status: update.status
|
|
7185
|
+
};
|
|
7186
|
+
if (update.run_id) event.run_id = update.run_id;
|
|
7187
|
+
return {
|
|
7188
|
+
role: "user",
|
|
7189
|
+
content: notificationContent(update),
|
|
7190
|
+
additional_kwargs: { [NOTIFICATION_KEY]: event }
|
|
7191
|
+
};
|
|
7192
|
+
}
|
|
7193
|
+
/** Parent thread statuses a notification run can start on: neither running nor waiting for a human. */
|
|
7194
|
+
const DELIVERABLE_THREAD_STATUSES = /* @__PURE__ */ new Set(["idle", "error"]);
|
|
7195
|
+
/**
|
|
7196
|
+
* Start a notification run on the parent's thread only while it's idle (or its last run failed).
|
|
7197
|
+
*
|
|
7198
|
+
* A run on a thread waiting for a human would cancel that approval. Never throws.
|
|
7199
|
+
*/
|
|
7200
|
+
async function awakeParent(parentThreadId, assistantId, update, context) {
|
|
7201
|
+
const client = new _langchain_langgraph_sdk.Client();
|
|
7202
|
+
try {
|
|
7203
|
+
const thread = await client.threads.get(parentThreadId);
|
|
7204
|
+
if (!DELIVERABLE_THREAD_STATUSES.has(thread.status)) return;
|
|
7205
|
+
await client.runs.create(parentThreadId, assistantId, {
|
|
7206
|
+
input: { messages: [notificationMessage(update)] },
|
|
7207
|
+
multitaskStrategy: "reject",
|
|
7208
|
+
...context ? { context } : {}
|
|
7209
|
+
});
|
|
7210
|
+
} catch {}
|
|
7211
|
+
}
|
|
7212
|
+
/**
|
|
7213
|
+
* Wake the parent if it's idle, with this run's context; otherwise it finds out
|
|
7214
|
+
* on its own. Never throws.
|
|
7215
|
+
*/
|
|
7216
|
+
async function notifyParent(config, update, context) {
|
|
7217
|
+
const parent = launchingAgent(config);
|
|
7218
|
+
if (parent?.thread_id && parent.assistant_id) await awakeParent(parent.thread_id, parent.assistant_id, update, forwardedContext(context));
|
|
7219
|
+
}
|
|
7220
|
+
/**
|
|
6716
7221
|
* Extract the callback thread ID from the tool runtime.
|
|
6717
7222
|
*
|
|
6718
7223
|
* The thread ID is included in the subagent's input state so the subagent
|
|
@@ -6741,15 +7246,14 @@ function buildStartTool(agentMap, clients, toolDescription) {
|
|
|
6741
7246
|
const spec = agentMap[input.agentName];
|
|
6742
7247
|
const callbackContext = extractCallbackContext(runtime);
|
|
6743
7248
|
try {
|
|
6744
|
-
const
|
|
6745
|
-
const
|
|
6746
|
-
|
|
6747
|
-
|
|
6748
|
-
|
|
6749
|
-
|
|
6750
|
-
|
|
6751
|
-
|
|
6752
|
-
} });
|
|
7249
|
+
const thread = await clients.getClient(input.agentName).threads.create({ metadata: threadMetadata(spec, runtime.config) });
|
|
7250
|
+
const run = await clients.getClient(input.agentName, traceHeaders(spec)).runs.create(thread.thread_id, spec.graphId, {
|
|
7251
|
+
input: {
|
|
7252
|
+
messages: startTaskMessages(spec, runtime.state, input.description),
|
|
7253
|
+
...callbackContext
|
|
7254
|
+
},
|
|
7255
|
+
...runOptions(spec, runtime)
|
|
7256
|
+
});
|
|
6753
7257
|
const taskId = thread.thread_id;
|
|
6754
7258
|
const task = {
|
|
6755
7259
|
taskId,
|
|
@@ -6789,86 +7293,111 @@ function buildCheckTool(clients) {
|
|
|
6789
7293
|
return (0, langchain.tool)(async (input, runtime) => {
|
|
6790
7294
|
const task = resolveTrackedTask(input.taskId, runtime.state);
|
|
6791
7295
|
if (typeof task === "string") return task;
|
|
6792
|
-
const client = clients.getClient(task.agentName);
|
|
6793
7296
|
let run;
|
|
7297
|
+
let thread;
|
|
6794
7298
|
try {
|
|
6795
|
-
run = await
|
|
7299
|
+
[run, thread] = await observeTaskRun(clients.getClient(task.agentName), task);
|
|
6796
7300
|
} catch (e) {
|
|
6797
7301
|
return `Failed to get run status: ${e}`;
|
|
6798
7302
|
}
|
|
6799
|
-
|
|
6800
|
-
|
|
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
|
-
};
|
|
7303
|
+
const result = keepCancelled(task, buildCheckResult(run, task.threadId, thread));
|
|
7304
|
+
const updatedTask = observed(task, result.status, run.run_id);
|
|
6814
7305
|
return new _langchain_langgraph.Command({ update: {
|
|
6815
7306
|
messages: [new langchain.ToolMessage({
|
|
6816
|
-
content:
|
|
7307
|
+
content: checkOutput(result),
|
|
6817
7308
|
tool_call_id: toolCallIdFromRuntime(runtime)
|
|
6818
7309
|
})],
|
|
6819
7310
|
asyncTasks: { [task.taskId]: updatedTask }
|
|
6820
7311
|
} });
|
|
6821
7312
|
}, {
|
|
6822
7313
|
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.",
|
|
7314
|
+
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
7315
|
schema: zod_v4.z.object({ taskId: zod_v4.z.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim.") })
|
|
6825
7316
|
});
|
|
6826
7317
|
}
|
|
7318
|
+
/** Confirm an update: queued behind an active run, or started, noting when it dropped a waiting human request. */
|
|
7319
|
+
function updateMessage(tracked, strategy) {
|
|
7320
|
+
if (strategy === "enqueue" && (tracked.status === "running" || tracked.status === "pending")) return `Queued follow-up to async subagent without interrupting its current run. taskId: ${tracked.taskId}`;
|
|
7321
|
+
const msg = `Updated async subagent. taskId: ${tracked.taskId}`;
|
|
7322
|
+
return tracked.status === "waiting" ? `${msg}. It was waiting for a human; that request was dropped.` : msg;
|
|
7323
|
+
}
|
|
7324
|
+
/**
|
|
7325
|
+
* Refuse every queued follow-up to a task after the first in one model turn.
|
|
7326
|
+
*
|
|
7327
|
+
* Parallel calls read the same state, so the task would lose track of all but one.
|
|
7328
|
+
*/
|
|
7329
|
+
function parallelUpdateError(taskId, runtime) {
|
|
7330
|
+
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;
|
|
7331
|
+
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.`;
|
|
7332
|
+
}
|
|
7333
|
+
/**
|
|
7334
|
+
* The runs a queued follow-up leaves behind it.
|
|
7335
|
+
*
|
|
7336
|
+
* The list grows while the task is unfinished, and otherwise restarts with the tracked run.
|
|
7337
|
+
*/
|
|
7338
|
+
function supersededAfterUpdate(tracked) {
|
|
7339
|
+
return [...UNFINISHED_STATUSES.has(tracked.status) ? tracked.supersededRunIds ?? [] : [], tracked.runId];
|
|
7340
|
+
}
|
|
7341
|
+
/** The tracked task after a follow-up created `run`, which may still be queued. */
|
|
7342
|
+
function updatedTask(tracked, run, strategy, message) {
|
|
7343
|
+
const task = {
|
|
7344
|
+
...tracked,
|
|
7345
|
+
runId: run.run_id,
|
|
7346
|
+
status: "running",
|
|
7347
|
+
description: message,
|
|
7348
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
7349
|
+
};
|
|
7350
|
+
if (strategy === "enqueue") {
|
|
7351
|
+
task.status = run.status;
|
|
7352
|
+
task.supersededRunIds = supersededAfterUpdate(tracked);
|
|
7353
|
+
}
|
|
7354
|
+
return task;
|
|
7355
|
+
}
|
|
7356
|
+
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.";
|
|
7357
|
+
/** The update tool's description, naming the subagents whose follow-ups queue instead. */
|
|
7358
|
+
function updateToolDescription(agentMap) {
|
|
7359
|
+
const queued = Object.values(agentMap).filter((spec) => spec.updateStrategy === "enqueue").map((spec) => `\`${spec.name}\``);
|
|
7360
|
+
if (queued.length === 0) return UPDATE_TOOL_DESCRIPTION;
|
|
7361
|
+
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.`;
|
|
7362
|
+
}
|
|
6827
7363
|
/**
|
|
6828
7364
|
* Build the `update_async_task` tool.
|
|
6829
7365
|
*
|
|
6830
|
-
* Sends a follow-up message to
|
|
6831
|
-
*
|
|
6832
|
-
*
|
|
6833
|
-
*
|
|
7366
|
+
* Sends a follow-up message to an async subagent by creating a new run on the
|
|
7367
|
+
* same thread. The subagent sees the full conversation history plus the new
|
|
7368
|
+
* message. The `taskId` remains the same. The subagent's `updateStrategy`
|
|
7369
|
+
* decides whether the new run interrupts the current run or queues behind it.
|
|
6834
7370
|
*/
|
|
6835
7371
|
function buildUpdateTool(agentMap, clients) {
|
|
6836
7372
|
return (0, langchain.tool)(async (input, runtime) => {
|
|
6837
7373
|
const tracked = resolveTrackedTask(input.taskId, runtime.state);
|
|
6838
7374
|
if (typeof tracked === "string") return tracked;
|
|
6839
7375
|
const spec = agentMap[tracked.agentName];
|
|
7376
|
+
const strategy = spec.updateStrategy ?? "interrupt";
|
|
7377
|
+
const refused = strategy === "enqueue" && parallelUpdateError(tracked.taskId, runtime);
|
|
7378
|
+
if (refused) return refused;
|
|
6840
7379
|
try {
|
|
6841
|
-
const run = await clients.getClient(tracked.agentName).runs.create(tracked.threadId, spec.graphId, {
|
|
7380
|
+
const run = await clients.getClient(tracked.agentName, traceHeaders(spec)).runs.create(tracked.threadId, spec.graphId, {
|
|
6842
7381
|
input: { messages: [{
|
|
6843
7382
|
role: "user",
|
|
6844
7383
|
content: input.message
|
|
6845
7384
|
}] },
|
|
6846
|
-
multitaskStrategy:
|
|
7385
|
+
multitaskStrategy: strategy,
|
|
7386
|
+
...runOptions(spec, runtime)
|
|
6847
7387
|
});
|
|
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
7388
|
return new _langchain_langgraph.Command({ update: {
|
|
6860
7389
|
messages: [new langchain.ToolMessage({
|
|
6861
|
-
content:
|
|
7390
|
+
content: updateMessage(tracked, strategy),
|
|
6862
7391
|
tool_call_id: toolCallIdFromRuntime(runtime)
|
|
6863
7392
|
})],
|
|
6864
|
-
asyncTasks: { [tracked.taskId]:
|
|
7393
|
+
asyncTasks: { [tracked.taskId]: updatedTask(tracked, run, strategy, input.message) }
|
|
6865
7394
|
} });
|
|
6866
7395
|
} catch (e) {
|
|
6867
7396
|
return `Failed to update async subagent: ${e}`;
|
|
6868
7397
|
}
|
|
6869
7398
|
}, {
|
|
6870
7399
|
name: "update_async_task",
|
|
6871
|
-
description:
|
|
7400
|
+
description: updateToolDescription(agentMap),
|
|
6872
7401
|
schema: zod_v4.z.object({
|
|
6873
7402
|
taskId: zod_v4.z.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim."),
|
|
6874
7403
|
message: zod_v4.z.string().describe("Follow-up instructions or context to send to the subagent")
|
|
@@ -6876,6 +7405,20 @@ function buildUpdateTool(agentMap, clients) {
|
|
|
6876
7405
|
});
|
|
6877
7406
|
}
|
|
6878
7407
|
/**
|
|
7408
|
+
* Cancel earlier runs that are still pending or running, newest first.
|
|
7409
|
+
*
|
|
7410
|
+
* Newest first, so a queued run doesn't start when the run ahead of it is cancelled.
|
|
7411
|
+
* A run that can't be read or cancelled is skipped.
|
|
7412
|
+
*/
|
|
7413
|
+
async function cancelEarlierRuns(client, task) {
|
|
7414
|
+
for (const runId of [...task.supersededRunIds ?? []].reverse()) try {
|
|
7415
|
+
const run = await client.runs.get(task.threadId, runId);
|
|
7416
|
+
if (run.status === "running" || run.status === "pending") await client.runs.cancel(task.threadId, runId);
|
|
7417
|
+
} catch (e) {
|
|
7418
|
+
console.warn(`Failed to cancel earlier run ${runId} of task ${task.taskId}:`, e);
|
|
7419
|
+
}
|
|
7420
|
+
}
|
|
7421
|
+
/**
|
|
6879
7422
|
* Build the `cancel_async_task` tool.
|
|
6880
7423
|
*
|
|
6881
7424
|
* Cancels the current run on the remote server and updates the task's
|
|
@@ -6885,21 +7428,17 @@ function buildCancelTool(clients) {
|
|
|
6885
7428
|
return (0, langchain.tool)(async (input, runtime) => {
|
|
6886
7429
|
const tracked = resolveTrackedTask(input.taskId, runtime.state);
|
|
6887
7430
|
if (typeof tracked === "string") return tracked;
|
|
6888
|
-
|
|
6889
|
-
|
|
7431
|
+
if (tracked.status !== "waiting") try {
|
|
7432
|
+
const client = clients.getClient(tracked.agentName);
|
|
6890
7433
|
await client.runs.cancel(tracked.threadId, tracked.runId);
|
|
7434
|
+
await cancelEarlierRuns(client, tracked);
|
|
6891
7435
|
} catch (e) {
|
|
6892
7436
|
return `Failed to cancel run: ${e}`;
|
|
6893
7437
|
}
|
|
6894
7438
|
const updated = {
|
|
6895
|
-
|
|
6896
|
-
agentName: tracked.agentName,
|
|
6897
|
-
threadId: tracked.threadId,
|
|
6898
|
-
runId: tracked.runId,
|
|
7439
|
+
...tracked,
|
|
6899
7440
|
status: "cancelled",
|
|
6900
|
-
|
|
6901
|
-
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
6902
|
-
checkedAt: tracked.checkedAt
|
|
7441
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
6903
7442
|
};
|
|
6904
7443
|
return new _langchain_langgraph.Command({ update: {
|
|
6905
7444
|
messages: [new langchain.ToolMessage({
|
|
@@ -6910,7 +7449,7 @@ function buildCancelTool(clients) {
|
|
|
6910
7449
|
} });
|
|
6911
7450
|
}, {
|
|
6912
7451
|
name: "cancel_async_task",
|
|
6913
|
-
description: "Cancel a running async subagent task. Use this to stop a task that is no longer needed.",
|
|
7452
|
+
description: "Cancel a running, pending, or waiting async subagent task. Use this to stop a task that is no longer needed.",
|
|
6914
7453
|
schema: zod_v4.z.object({ taskId: zod_v4.z.string().describe("The exact taskId string returned by start_async_task. Pass it verbatim.") })
|
|
6915
7454
|
});
|
|
6916
7455
|
}
|
|
@@ -6924,24 +7463,14 @@ function buildListTool(clients) {
|
|
|
6924
7463
|
return (0, langchain.tool)(async (input, runtime) => {
|
|
6925
7464
|
const filtered = filterTasks(runtime.state.asyncTasks ?? {}, input.statusFilter ?? void 0);
|
|
6926
7465
|
if (filtered.length === 0) return "No async subagent tasks tracked";
|
|
6927
|
-
const
|
|
7466
|
+
const live = await Promise.all(filtered.map((task) => fetchLiveTaskStatus(clients, task)));
|
|
6928
7467
|
const updatedTasks = {};
|
|
6929
7468
|
const entries = [];
|
|
6930
7469
|
for (let idx = 0; idx < filtered.length; idx++) {
|
|
6931
7470
|
const task = filtered[idx];
|
|
6932
|
-
const status =
|
|
6933
|
-
|
|
6934
|
-
|
|
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
|
-
};
|
|
7471
|
+
const [status, runId] = live[idx];
|
|
7472
|
+
entries.push(formatTaskEntry(task, status));
|
|
7473
|
+
updatedTasks[task.taskId] = observed(task, status, runId);
|
|
6945
7474
|
}
|
|
6946
7475
|
return new _langchain_langgraph.Command({ update: {
|
|
6947
7476
|
messages: [new langchain.ToolMessage({
|
|
@@ -6952,10 +7481,107 @@ function buildListTool(clients) {
|
|
|
6952
7481
|
} });
|
|
6953
7482
|
}, {
|
|
6954
7483
|
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'.") })
|
|
7484
|
+
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.",
|
|
7485
|
+
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
7486
|
});
|
|
6958
7487
|
}
|
|
7488
|
+
/** The notification for a task outcome a check found, or `null` for outcomes not worth waking for. */
|
|
7489
|
+
function checkEvent(task, run, thread, status) {
|
|
7490
|
+
if (!NOTIFIED_STATUSES.has(status)) return null;
|
|
7491
|
+
const result = buildCheckResult(run, task.threadId, thread);
|
|
7492
|
+
const details = {};
|
|
7493
|
+
if (result.interrupts) details.interrupts = result.interrupts;
|
|
7494
|
+
if (status === "success") details.result = result.result;
|
|
7495
|
+
if (status === "error") details.error = "The subagent failed.";
|
|
7496
|
+
return taskUpdate({
|
|
7497
|
+
task_id: task.taskId,
|
|
7498
|
+
agent_name: task.agentName,
|
|
7499
|
+
status,
|
|
7500
|
+
run_id: run.run_id ?? task.runId
|
|
7501
|
+
}, details);
|
|
7502
|
+
}
|
|
7503
|
+
/** Task outcomes that notify the parent. */
|
|
7504
|
+
const NOTIFIED_STATUSES = /* @__PURE__ */ new Set([
|
|
7505
|
+
"success",
|
|
7506
|
+
"error",
|
|
7507
|
+
"timeout",
|
|
7508
|
+
"cancelled",
|
|
7509
|
+
"waiting"
|
|
7510
|
+
]);
|
|
7511
|
+
/** How long the parent waits on one task's status before skipping it until the next check. */
|
|
7512
|
+
const PULL_TIMEOUT_MS = 5e3;
|
|
7513
|
+
/** Tracked task statuses that can still change, so the parent checks them for status updates. */
|
|
7514
|
+
const UNFINISHED_STATUSES = /* @__PURE__ */ new Set([
|
|
7515
|
+
"running",
|
|
7516
|
+
"pending",
|
|
7517
|
+
"waiting"
|
|
7518
|
+
]);
|
|
7519
|
+
/** Observe a task, or `null` when it can't be checked in time; it's checked again next time. */
|
|
7520
|
+
async function observeTask(clients, task) {
|
|
7521
|
+
try {
|
|
7522
|
+
return await observeTaskRun(clients.getClient(task.agentName), task, AbortSignal.timeout(PULL_TIMEOUT_MS));
|
|
7523
|
+
} catch (e) {
|
|
7524
|
+
console.warn(`Failed to check task ${task.taskId}:`, e);
|
|
7525
|
+
return null;
|
|
7526
|
+
}
|
|
7527
|
+
}
|
|
7528
|
+
/**
|
|
7529
|
+
* Check unfinished tasks; return their updated records and a notification per new outcome.
|
|
7530
|
+
*
|
|
7531
|
+
* Outcomes the agent already saw aren't reported again; a task that can't be
|
|
7532
|
+
* checked is skipped until the next check.
|
|
7533
|
+
*/
|
|
7534
|
+
async function pull(clients, tasks) {
|
|
7535
|
+
const unfinished = Object.values(tasks).filter((task) => UNFINISHED_STATUSES.has(task.status));
|
|
7536
|
+
const found = await Promise.all(unfinished.map((task) => observeTask(clients, task)));
|
|
7537
|
+
const records = {};
|
|
7538
|
+
const messages = [];
|
|
7539
|
+
unfinished.forEach((task, idx) => {
|
|
7540
|
+
if (found[idx] === null) return;
|
|
7541
|
+
const [run, thread] = found[idx];
|
|
7542
|
+
const status = taskStatus(run, thread);
|
|
7543
|
+
if (status === task.status && run.run_id === task.runId) return;
|
|
7544
|
+
records[task.taskId] = observed(task, status, run.run_id);
|
|
7545
|
+
const event = status !== task.status ? checkEvent(task, run, thread, status) : null;
|
|
7546
|
+
if (event) messages.push((0, _langchain_core_messages.coerceMessageLikeToMessage)(notificationMessage(event)));
|
|
7547
|
+
});
|
|
7548
|
+
const update = {};
|
|
7549
|
+
if (Object.keys(records).length > 0) update.asyncTasks = records;
|
|
7550
|
+
if (messages.length > 0) update.messages = messages;
|
|
7551
|
+
return update;
|
|
7552
|
+
}
|
|
7553
|
+
/**
|
|
7554
|
+
* When a task notification started this run, record the task's outcome so checks don't report it again.
|
|
7555
|
+
*
|
|
7556
|
+
* A notification from an earlier run that a queued follow-up replaced is rewritten
|
|
7557
|
+
* instead, so the model doesn't take it as the task's outcome.
|
|
7558
|
+
*/
|
|
7559
|
+
function recordNotification(messages, tasks) {
|
|
7560
|
+
const last = messages[messages.length - 1];
|
|
7561
|
+
const event = notificationEvent(last);
|
|
7562
|
+
const task = event ? tasks[event.task_id] : void 0;
|
|
7563
|
+
if (!event || !task || task.status === "cancelled") return {};
|
|
7564
|
+
const runId = event.run_id ?? task.runId;
|
|
7565
|
+
if (task.supersededRunIds?.includes(runId)) {
|
|
7566
|
+
const content = supersededNotificationContent(last, event);
|
|
7567
|
+
return { messages: [new _langchain_core_messages.HumanMessage({
|
|
7568
|
+
id: last.id,
|
|
7569
|
+
content,
|
|
7570
|
+
additional_kwargs: last.additional_kwargs
|
|
7571
|
+
})] };
|
|
7572
|
+
}
|
|
7573
|
+
if (runId !== task.runId && !UNFINISHED_STATUSES.has(task.status)) return {};
|
|
7574
|
+
return { asyncTasks: { [task.taskId]: observed(task, event.status, runId) } };
|
|
7575
|
+
}
|
|
7576
|
+
/** The tasks tracked in state; the state schema stores `status` as a plain string. */
|
|
7577
|
+
function trackedTasks(state) {
|
|
7578
|
+
return state.asyncTasks ?? {};
|
|
7579
|
+
}
|
|
7580
|
+
/** Whether the last message is a final answer: an AI message with no tool calls. */
|
|
7581
|
+
function isFinalAnswer(messages) {
|
|
7582
|
+
const last = messages[messages.length - 1];
|
|
7583
|
+
return last !== void 0 && !last.tool_calls?.length;
|
|
7584
|
+
}
|
|
6959
7585
|
/**
|
|
6960
7586
|
* Create middleware that adds async subagent tools to an agent.
|
|
6961
7587
|
*
|
|
@@ -6967,6 +7593,11 @@ function buildListTool(clients) {
|
|
|
6967
7593
|
* Works with any Agent Protocol-compliant server — LangGraph Platform (managed)
|
|
6968
7594
|
* or self-hosted (e.g. a Hono/Express server implementing the Agent Protocol spec).
|
|
6969
7595
|
*
|
|
7596
|
+
* On an Agent Server, the agent is told when its tasks finish, fail or wait for
|
|
7597
|
+
* the user: by checking while it runs, and through a new run when it's idle.
|
|
7598
|
+
*
|
|
7599
|
+
* @experimental Task notifications are experimental and subject to change.
|
|
7600
|
+
*
|
|
6970
7601
|
* @throws {Error} If no async subagents are provided or names are duplicated.
|
|
6971
7602
|
*
|
|
6972
7603
|
* @example
|
|
@@ -6996,9 +7627,15 @@ function createAsyncSubAgentMiddleware(options) {
|
|
|
6996
7627
|
const names = asyncSubAgents.map((a) => a.name);
|
|
6997
7628
|
const duplicates = names.filter((n, i) => names.indexOf(n) !== i);
|
|
6998
7629
|
if (duplicates.length > 0) throw new Error(`Duplicate async subagent names: ${[...new Set(duplicates)].join(", ")}`);
|
|
7630
|
+
for (const spec of asyncSubAgents) {
|
|
7631
|
+
const strategy = spec.updateStrategy ?? "interrupt";
|
|
7632
|
+
if (strategy !== "interrupt" && strategy !== "enqueue") throw new Error(`AsyncSubAgent '${spec.name}' has invalid updateStrategy '${strategy}'; expected 'interrupt' or 'enqueue'`);
|
|
7633
|
+
const mode = spec.mode ?? "isolated";
|
|
7634
|
+
if (mode !== "isolated" && mode !== "fork") throw new Error(`AsyncSubAgent '${spec.name}' has invalid mode '${mode}'; expected 'isolated' or 'fork'`);
|
|
7635
|
+
}
|
|
6999
7636
|
const agentMap = Object.fromEntries(asyncSubAgents.map((a) => [a.name, a]));
|
|
7000
7637
|
const clients = new ClientCache(agentMap);
|
|
7001
|
-
const agentsDescription = asyncSubAgents.map(
|
|
7638
|
+
const agentsDescription = asyncSubAgents.map(describeAsyncSubAgent).join("\n");
|
|
7002
7639
|
const tools = [
|
|
7003
7640
|
buildStartTool(agentMap, clients, ASYNC_TASK_TOOL_DESCRIPTION.replace("{available_agents}", agentsDescription)),
|
|
7004
7641
|
buildCheckTool(clients),
|
|
@@ -7011,6 +7648,41 @@ function createAsyncSubAgentMiddleware(options) {
|
|
|
7011
7648
|
name: "asyncSubAgentMiddleware",
|
|
7012
7649
|
stateSchema: AsyncTaskStateSchema,
|
|
7013
7650
|
tools,
|
|
7651
|
+
beforeAgent: async (state) => {
|
|
7652
|
+
const messages = state.messages ?? [];
|
|
7653
|
+
const tasks = trackedTasks(state);
|
|
7654
|
+
const recorded = recordNotification(messages, tasks);
|
|
7655
|
+
const updates = await pull(clients, {
|
|
7656
|
+
...tasks,
|
|
7657
|
+
...recorded.asyncTasks
|
|
7658
|
+
});
|
|
7659
|
+
const asyncTasks = {
|
|
7660
|
+
...recorded.asyncTasks,
|
|
7661
|
+
...updates.asyncTasks
|
|
7662
|
+
};
|
|
7663
|
+
const notes = [...recorded.messages ?? [], ...updates.messages ?? []];
|
|
7664
|
+
if (Object.keys(asyncTasks).length === 0 && notes.length === 0) return;
|
|
7665
|
+
return {
|
|
7666
|
+
asyncTasks,
|
|
7667
|
+
...notes.length > 0 && { messages: notes }
|
|
7668
|
+
};
|
|
7669
|
+
},
|
|
7670
|
+
beforeModel: async (state) => {
|
|
7671
|
+
const updates = await pull(clients, trackedTasks(state));
|
|
7672
|
+
return Object.keys(updates).length > 0 ? updates : void 0;
|
|
7673
|
+
},
|
|
7674
|
+
afterModel: {
|
|
7675
|
+
canJumpTo: ["model"],
|
|
7676
|
+
hook: async (state) => {
|
|
7677
|
+
if (!isFinalAnswer(state.messages ?? [])) return;
|
|
7678
|
+
const updates = await pull(clients, trackedTasks(state));
|
|
7679
|
+
if (!updates.messages) return Object.keys(updates).length > 0 ? updates : void 0;
|
|
7680
|
+
return {
|
|
7681
|
+
...updates,
|
|
7682
|
+
jumpTo: "model"
|
|
7683
|
+
};
|
|
7684
|
+
}
|
|
7685
|
+
},
|
|
7014
7686
|
wrapModelCall: async (request, handler) => {
|
|
7015
7687
|
if (fullSystemPrompt !== null) return handler({
|
|
7016
7688
|
...request,
|
|
@@ -7071,6 +7743,53 @@ function createCacheBreakpointMiddleware() {
|
|
|
7071
7743
|
});
|
|
7072
7744
|
}
|
|
7073
7745
|
//#endregion
|
|
7746
|
+
//#region src/middleware/parent_notifier.ts
|
|
7747
|
+
/** Whether this is the outermost graph of a task run, not a graph nested in it. */
|
|
7748
|
+
function isTopLevelGraph(config) {
|
|
7749
|
+
const configurable = config.configurable ?? {};
|
|
7750
|
+
return !String(configurable.checkpoint_ns ?? "").includes("|");
|
|
7751
|
+
}
|
|
7752
|
+
/** Whether `error` comes from the run being aborted rather than from the subagent failing. */
|
|
7753
|
+
function wasAborted(error, signal) {
|
|
7754
|
+
return signal?.aborted === true || (0, _langchain_langgraph.getConfig)()?.signal?.aborted === true || typeof error === "object" && error !== null && error.name === "AbortError";
|
|
7755
|
+
}
|
|
7756
|
+
/**
|
|
7757
|
+
* Wake the agent that started this run with `start_async_task`, when the run ends.
|
|
7758
|
+
*
|
|
7759
|
+
* `createDeepAgent` attaches it to every deep agent. It does nothing unless the
|
|
7760
|
+
* run carries the parent reference, and skips nested runs.
|
|
7761
|
+
*/
|
|
7762
|
+
function createParentNotifierMiddleware() {
|
|
7763
|
+
/**
|
|
7764
|
+
* Notify for this graph's own run that an async subagent tool started.
|
|
7765
|
+
*
|
|
7766
|
+
* The run's context comes from its config: hooks only see the context fields
|
|
7767
|
+
* a middleware's `contextSchema` declares, and this one declares none.
|
|
7768
|
+
*/
|
|
7769
|
+
async function report(status, details) {
|
|
7770
|
+
const config = (0, _langchain_langgraph.getConfig)();
|
|
7771
|
+
if (!launchingAgent(config) || !isTopLevelGraph(config)) return;
|
|
7772
|
+
if (currentRunId(config) === void 0) return;
|
|
7773
|
+
const metadata = config.metadata ?? {};
|
|
7774
|
+
const configurable = config.configurable ?? {};
|
|
7775
|
+
await notifyParent(config, taskEvent(config, String(metadata.subagent_name ?? metadata.graph_id ?? configurable.graph_id ?? "subagent"), status, details), config.context);
|
|
7776
|
+
}
|
|
7777
|
+
return (0, langchain.createMiddleware)({
|
|
7778
|
+
name: "parentNotifierMiddleware",
|
|
7779
|
+
afterAgent: async (state) => {
|
|
7780
|
+
await report("success", { result: finalContent(state) });
|
|
7781
|
+
},
|
|
7782
|
+
wrapModelCall: async (request, handler) => {
|
|
7783
|
+
try {
|
|
7784
|
+
return await handler(request);
|
|
7785
|
+
} catch (e) {
|
|
7786
|
+
if (!(0, _langchain_langgraph.isGraphBubbleUp)(e) && !wasAborted(e, request.runtime.signal)) await report("error", { error: failureText(e) });
|
|
7787
|
+
throw e;
|
|
7788
|
+
}
|
|
7789
|
+
}
|
|
7790
|
+
});
|
|
7791
|
+
}
|
|
7792
|
+
//#endregion
|
|
7074
7793
|
//#region src/middleware/tool_exclusion.ts
|
|
7075
7794
|
function hasToolName(tool) {
|
|
7076
7795
|
return tool !== null && typeof tool === "object" && "name" in tool && typeof tool.name === "string";
|
|
@@ -7976,6 +8695,7 @@ function createDeepAgent(params = {}) {
|
|
|
7976
8695
|
createPatchToolCallsMiddleware()
|
|
7977
8696
|
];
|
|
7978
8697
|
let middleware = mergeMiddlewareStack([
|
|
8698
|
+
createParentNotifierMiddleware(),
|
|
7979
8699
|
fsMiddleware,
|
|
7980
8700
|
subagentMiddleware,
|
|
7981
8701
|
summarizationMiddleware,
|
|
@@ -10486,4 +11206,4 @@ Object.defineProperty(exports, "skillsMetadataValue", {
|
|
|
10486
11206
|
}
|
|
10487
11207
|
});
|
|
10488
11208
|
|
|
10489
|
-
//# sourceMappingURL=langsmith-
|
|
11209
|
+
//# sourceMappingURL=langsmith-aH3Gwzii.cjs.map
|