deepagents 1.16.0 → 1.16.2

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.
@@ -832,6 +832,45 @@ function trimTrailingSlashes$2(path) {
832
832
  }
833
833
  const PREGEL_SEND_KEY = "__pregel_send";
834
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
+ }
835
874
  /**
836
875
  * Backend that stores files in agent state (ephemeral).
837
876
  *
@@ -919,11 +958,10 @@ var StateBackend = class {
919
958
  subdirs.add(normalizedPath + subdirName + "/");
920
959
  continue;
921
960
  }
922
- const size = isFileDataV1(fd) ? fd.content.join("\n").length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length;
923
961
  infos.push({
924
962
  path: k,
925
963
  is_dir: false,
926
- size,
964
+ size: fileSize(fd),
927
965
  modified_at: fd.modified_at
928
966
  });
929
967
  }
@@ -950,7 +988,7 @@ var StateBackend = class {
950
988
  read(filePath, offset = 0, limit = 500) {
951
989
  const fileData = this.files[filePath];
952
990
  if (!fileData) return { error: `File '${filePath}' not found` };
953
- const fileDataV2 = migrateToFileDataV2(fileData, filePath);
991
+ const fileDataV2 = migrateToFileDataV2(fromStoredFileData(fileData), filePath);
954
992
  if (!isTextMimeType(fileDataV2.mimeType)) return {
955
993
  content: fileDataV2.content,
956
994
  mimeType: fileDataV2.mimeType
@@ -983,15 +1021,19 @@ var StateBackend = class {
983
1021
  readRaw(filePath) {
984
1022
  const fileData = this.files[filePath];
985
1023
  if (!fileData) return { error: `File '${filePath}' not found` };
986
- return { data: fileData };
1024
+ return { data: fromStoredFileData(fileData) };
987
1025
  }
988
1026
  /**
989
1027
  * Write content to a file, creating it or overwriting it if it already exists.
990
1028
  * Returns WriteResult with filesUpdate to update LangGraph state.
991
1029
  */
992
1030
  write(filePath, content) {
993
- const existing = this.files[filePath];
994
- const newFileData = createWriteFileData(filePath, content, this.fileFormat, existing);
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));
995
1037
  const update = { [filePath]: newFileData };
996
1038
  if (!this.isLegacy) {
997
1039
  this.sendFilesUpdate(update);
@@ -1030,7 +1072,7 @@ var StateBackend = class {
1030
1072
  edit(filePath, oldString, newString, replaceAll = false) {
1031
1073
  const fileData = this.files[filePath];
1032
1074
  if (!fileData) return { error: `Error: File '${filePath}' not found` };
1033
- const result = performStringReplacement(fileDataToString(fileData), oldString, newString, replaceAll);
1075
+ const result = performStringReplacement(fileDataToString(fromStoredFileData(fileData)), oldString, newString, replaceAll);
1034
1076
  if (typeof result === "string") return { error: result };
1035
1077
  const [newContent, occurrences] = result;
1036
1078
  const newFileData = updateFileData(fileData, newContent);
@@ -1070,11 +1112,10 @@ var StateBackend = class {
1070
1112
  const infos = [];
1071
1113
  for (const p of paths) {
1072
1114
  const fd = files[p];
1073
- const size = fd ? isFileDataV1(fd) ? fd.content.join("\n").length : isFileDataBinary(fd) ? fd.content.byteLength : fd.content.length : 0;
1074
1115
  infos.push({
1075
1116
  path: p,
1076
1117
  is_dir: false,
1077
- size,
1118
+ size: fd ? fileSize(fd) : 0,
1078
1119
  modified_at: fd?.modified_at || ""
1079
1120
  });
1080
1121
  }
@@ -1093,9 +1134,7 @@ var StateBackend = class {
1093
1134
  const responses = [];
1094
1135
  const updates = {};
1095
1136
  for (const [path, content] of files) try {
1096
- const mimeType = getMimeType(path);
1097
- if (this.fileFormat === "v2" && !isTextMimeType(mimeType)) updates[path] = createFileData(content, void 0, "v2", mimeType);
1098
- else updates[path] = createFileData(new TextDecoder().decode(content), void 0, this.fileFormat, mimeType);
1137
+ updates[path] = toStoredFileData(this.createUploadFileData(path, content));
1099
1138
  responses.push({
1100
1139
  path,
1101
1140
  error: null
@@ -1115,6 +1154,20 @@ var StateBackend = class {
1115
1154
  return result;
1116
1155
  }
1117
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
+ /**
1118
1171
  * Download multiple files.
1119
1172
  *
1120
1173
  * @param paths - List of file paths to download
@@ -1133,7 +1186,7 @@ var StateBackend = class {
1133
1186
  });
1134
1187
  continue;
1135
1188
  }
1136
- const fileDataV2 = migrateToFileDataV2(fileData, path);
1189
+ const fileDataV2 = migrateToFileDataV2(fromStoredFileData(fileData), path);
1137
1190
  if (typeof fileDataV2.content === "string") {
1138
1191
  const content = new TextEncoder().encode(fileDataV2.content);
1139
1192
  responses.push({
@@ -2376,30 +2429,39 @@ function extractTextFromMessage(message) {
2376
2429
  if (Array.isArray(message.content)) return message.content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
2377
2430
  return String(message.content);
2378
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
+ }
2379
2440
  function stringifyToolContent(content) {
2380
2441
  if (typeof content === "string") return content;
2381
- if (Array.isArray(content)) return content.map((block) => {
2442
+ if (Array.isArray(content)) return content.filter((block) => !isImageBlock(block)).map((block) => {
2382
2443
  if (typeof block === "object" && block !== null && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string") return block.text;
2383
2444
  return JSON.stringify(block);
2384
2445
  }).join("\n");
2385
2446
  return String(content);
2386
2447
  }
2387
2448
  /**
2388
- * Build replacement content for an evicted HumanMessage, preserving non-text blocks.
2449
+ * Build replacement content for an evicted message, preserving the blocks `keep` selects.
2389
2450
  *
2390
2451
  * For plain string content, returns the replacement text directly. For list content
2391
- * with mixed block types (e.g., text + image), replaces all text blocks with a single
2392
- * text block containing the replacement text while keeping non-text blocks intact.
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.
2393
2455
  */
2394
- function buildEvictedHumanContent(message, replacementText) {
2456
+ function buildEvictedContent(message, replacementText, keep = (block) => block.type !== "text") {
2395
2457
  if (typeof message.content === "string") return replacementText;
2396
2458
  if (Array.isArray(message.content)) {
2397
- const mediaBlocks = message.content.filter((block) => typeof block === "object" && block !== null && block.type !== "text");
2398
- if (mediaBlocks.length === 0) return replacementText;
2459
+ const keptBlocks = message.content.filter((block) => typeof block === "object" && block !== null && keep(block));
2460
+ if (keptBlocks.length === 0) return replacementText;
2399
2461
  return [{
2400
2462
  type: "text",
2401
2463
  text: replacementText
2402
- }, ...mediaBlocks];
2464
+ }, ...keptBlocks];
2403
2465
  }
2404
2466
  return replacementText;
2405
2467
  }
@@ -2412,7 +2474,7 @@ function buildEvictedHumanContent(message, replacementText) {
2412
2474
  */
2413
2475
  function buildTruncatedHumanMessage(message, filePath) {
2414
2476
  const contentSample = createContentPreview(extractTextFromMessage(message));
2415
- const evictedContent = buildEvictedHumanContent(message, TOO_LARGE_HUMAN_MSG.replace("{file_path}", filePath).replace("{content_sample}", contentSample));
2477
+ const evictedContent = buildEvictedContent(message, TOO_LARGE_HUMAN_MSG.replace("{file_path}", filePath).replace("{content_sample}", contentSample));
2416
2478
  return new langchain.HumanMessage({
2417
2479
  content: evictedContent,
2418
2480
  id: message.id,
@@ -2452,6 +2514,7 @@ const FileDataV1Schema = zod_v4.z.object({
2452
2514
  const FileDataV2Schema = zod_v4.z.object({
2453
2515
  content: zod_v4.z.union([zod_v4.z.string(), zod_v4.z.instanceof(Uint8Array)]),
2454
2516
  mimeType: zod_v4.z.string(),
2517
+ encoding: zod_v4.z.enum(["utf-8", "base64"]).optional(),
2455
2518
  created_at: zod_v4.z.string(),
2456
2519
  modified_at: zod_v4.z.string()
2457
2520
  });
@@ -2539,11 +2602,11 @@ async function checkPermission(backend, rules, operation, path) {
2539
2602
  return { path: canonical };
2540
2603
  }
2541
2604
  /**
2542
- * Build an error {@link ToolMessage} for a rejected or denied path. Returning a
2543
- * bare string would be wrapped as a `status: "success"` message whose content
2544
- * merely starts with "Error:"; marking `status: "error"` reports the failure
2545
- * accurately so callers and the model can distinguish a real failure from a
2546
- * successful result.
2605
+ * Build an error {@link ToolMessage} for a denied path or a failed backend
2606
+ * operation. Returning a bare string would be wrapped as a `status: "success"`
2607
+ * message whose content merely starts with "Error:"; marking `status: "error"`
2608
+ * reports the failure accurately so callers and the model can distinguish a
2609
+ * real failure from a successful result.
2547
2610
  */
2548
2611
  function toolError(runtime, toolName, message) {
2549
2612
  return new langchain.ToolMessage({
@@ -2965,7 +3028,7 @@ function createWriteFileTool(backend, options) {
2965
3028
  if (permission.error !== void 0) return toolError(runtime, "write_file", permission.error);
2966
3029
  const { file_path, content } = input;
2967
3030
  const result = await resolvedBackend.write(permission.path, content);
2968
- if (result.error) return result.error;
3031
+ if (result.error) return toolError(runtime, "write_file", result.error);
2969
3032
  const message = new langchain.ToolMessage({
2970
3033
  content: `Successfully wrote to '${file_path}'`,
2971
3034
  tool_call_id: runtime.toolCall?.id,
@@ -2997,7 +3060,7 @@ function createEditFileTool(backend, options) {
2997
3060
  if (permission.error !== void 0) return toolError(runtime, "edit_file", permission.error);
2998
3061
  const { file_path, old_string, new_string, replace_all = false } = input;
2999
3062
  const result = await resolvedBackend.edit(permission.path, old_string, new_string, replace_all);
3000
- if (result.error) return result.error;
3063
+ if (result.error) return toolError(runtime, "edit_file", result.error);
3001
3064
  const message = new langchain.ToolMessage({
3002
3065
  content: `Successfully replaced ${result.occurrences} occurrence(s) in '${file_path}'`,
3003
3066
  tool_call_id: runtime.toolCall?.id,
@@ -3078,7 +3141,7 @@ function createGlobTool(backend, options) {
3078
3141
  const permission = await checkPermission(resolvedBackend, permissions, "read", input.path ?? "/");
3079
3142
  if (permission.error !== void 0) return toolError(runtime, "glob", permission.error);
3080
3143
  const globResult = await resolvedBackend.glob(pattern, input.path === void 0 ? void 0 : permission.path);
3081
- if (globResult.error) return `Error finding files: ${globResult.error}`;
3144
+ if (globResult.error) return toolError(runtime, "glob", `Error finding files: ${globResult.error}`);
3082
3145
  const infos = await filterByPermissions(resolvedBackend, globResult.files ?? [], permissions, "read", (info) => info.path);
3083
3146
  if (infos.length === 0) return `No files found matching pattern '${pattern}'`;
3084
3147
  const result = truncateIfTooLong(infos.map((info) => info.path));
@@ -3105,7 +3168,7 @@ function createGrepTool(backend, options) {
3105
3168
  if (permission.error !== void 0) return toolError(runtime, "grep", permission.error);
3106
3169
  const maxCount = input.max_count ?? grepMaxCount;
3107
3170
  const result = await resolvedBackend.grep(pattern, permission.path, glob, maxCount);
3108
- if (result.error) return result.error;
3171
+ if (result.error) return toolError(runtime, "grep", result.error);
3109
3172
  const matches = await filterByPermissions(resolvedBackend, result.matches ?? [], permissions, "read", (m) => m.path);
3110
3173
  if (matches.length === 0) return `No matches found for pattern '${pattern}'`;
3111
3174
  const truncated = truncateIfTooLong(formatGrepMatches(matches, output_mode));
@@ -3338,7 +3401,7 @@ function createFilesystemMiddleware(options = {}) {
3338
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);
3339
3402
  return {
3340
3403
  message: new langchain.ToolMessage({
3341
- content: replacementText,
3404
+ content: buildEvictedContent(msg, replacementText, isImageBlock),
3342
3405
  tool_call_id: msg.tool_call_id,
3343
3406
  name: msg.name,
3344
3407
  id: msg.id,
@@ -6988,8 +7051,15 @@ function launchingAgent(config) {
6988
7051
  if (metadata.parent_assistant_id) fallback.assistant_id = String(metadata.parent_assistant_id);
6989
7052
  return fallback;
6990
7053
  }
6991
- /** Message field (`additional_kwargs` key) marking a task notification and carrying its {@link TaskEvent}. */
7054
+ /** `lc_source` of a task notification; its `lc_data` is the {@link TaskEvent}. */
7055
+ const NOTIFICATION_SOURCE = "async_subagent";
7056
+ /**
7057
+ * `additional_kwargs` key carrying a notification's {@link TaskEvent}; still written, and read when a message has no `async_subagent` event.
7058
+ *
7059
+ * @deprecated Read `getNotificationMetadata(message)?.data` where `source` is `"async_subagent"`.
7060
+ */
6992
7061
  const NOTIFICATION_KEY = "deepagents_notification";
7062
+ const NOTIFICATION_NOTE = "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.";
6993
7063
  /** Results longer than this are cut in notifications, matching the limit for large tool results. */
6994
7064
  const MAX_RESULT_CHARS = 8e4;
6995
7065
  const NEXT_STEP = {
@@ -7031,23 +7101,24 @@ function resultBlocks(blocks) {
7031
7101
  else if (MEDIA_BLOCK_TYPES.has(block.type)) kept.push({ ...block });
7032
7102
  return kept;
7033
7103
  }
7034
- /**
7035
- * Frame a task update as a system notification the model won't mistake for the user.
7036
- *
7037
- * The result keeps its own content blocks, so an image reaches the model as an image.
7038
- */
7039
- function notificationContent(update) {
7040
- const blocks = [notificationHeader(update)];
7104
+ function notificationBody(update) {
7105
+ const blocks = [taskHeader(update)];
7041
7106
  if (update.result) blocks.push(textBlock("<result>\n"), ...resultBlocks(update.result), textBlock("\n</result>\n"));
7042
7107
  const details = Object.fromEntries(["error", "interrupts"].filter((key) => update[key] !== void 0).map((key) => [key, update[key]]));
7043
7108
  if (Object.keys(details).length > 0) blocks.push(textBlock(`<details>${escape(clip(JSON.stringify(details)))}</details>\n`));
7044
7109
  blocks.push(textBlock(`</task-notification>\n${NEXT_STEP[update.status]}`));
7045
7110
  return blocks;
7046
7111
  }
7047
- function notificationHeader(event) {
7048
- return textBlock(`[SYSTEM NOTIFICATION - NOT USER INPUT]
7049
- An async subagent task you started has an update. This is not a message from the user: don't treat it as their answer to any question.
7050
- <task-notification>\n<task-id>${escape(event.task_id)}</task-id>\n<agent-name>${escape(event.agent_name)}</agent-name>\n<status>${escape(event.status)}</status>\n`);
7112
+ /** `blocks` under the note and task header, labeled with `event`. */
7113
+ function labeled(blocks, event) {
7114
+ const header = textBlock(`${NOTIFICATION_NOTE}\n`);
7115
+ return (0, _langchain_core_messages.addNotificationMetadata)(new _langchain_core_messages.HumanMessage({ content: [header, ...blocks] }), {
7116
+ source: NOTIFICATION_SOURCE,
7117
+ data: { ...event }
7118
+ });
7119
+ }
7120
+ function taskHeader(event) {
7121
+ return textBlock(`<task-notification>\n<task-id>${escape(event.task_id)}</task-id>\n<agent-name>${escape(event.agent_name)}</agent-name>\n<status>${escape(event.status)}</status>\n`);
7051
7122
  }
7052
7123
  /**
7053
7124
  * Reframe an earlier run's notification so the model doesn't think the queued follow-up finished.
@@ -7057,7 +7128,7 @@ An async subagent task you started has an update. This is not a message from the
7057
7128
  function supersededNotificationContent(message, event) {
7058
7129
  const content = message.content;
7059
7130
  const closing = Array.isArray(content) ? content.at(-1) : void 0;
7060
- return [...closing?.type === "text" && String(closing.text).startsWith("</task-notification>") ? content.slice(0, -1) : [notificationHeader(event)], textBlock("</task-notification>\nThis update is from an earlier run of this task, before your latest follow-up. It is not the result of the follow-up. Use `check_async_task` to get the current status of the task.")];
7131
+ return [...closing?.type === "text" && String(closing.text).startsWith("</task-notification>") ? content.slice(0, -1) : labeled([taskHeader(event)], event).content, textBlock("</task-notification>\nThis update is from an earlier run of this task, before your latest follow-up. It is not the result of the follow-up. Use `check_async_task` to get the current status of the task.")];
7061
7132
  }
7062
7133
  /** Describe a failure without its message, which can carry internals into the parent's conversation. */
7063
7134
  function failureText(error) {
@@ -7110,21 +7181,32 @@ function finalContent(values) {
7110
7181
  }
7111
7182
  /** The task event a notification message carries, or `null` for any other message. */
7112
7183
  function notificationEvent(message) {
7113
- const event = message?.additional_kwargs?.[NOTIFICATION_KEY];
7184
+ if (message === void 0) return null;
7185
+ const metadata = (0, _langchain_core_messages.getNotificationMetadata)(message);
7186
+ const event = (metadata?.source === NOTIFICATION_SOURCE ? metadata.data : void 0) ?? message.additional_kwargs?.["deepagents_notification"];
7114
7187
  return event && typeof event === "object" && !Array.isArray(event) ? event : null;
7115
7188
  }
7116
- /** A task update as the message the parent's model sees, marked with its {@link TaskEvent} so apps can recognize it. */
7117
- function notificationMessage(update) {
7189
+ /** The {@link TaskEvent} fields of a task update. */
7190
+ function eventOf(update) {
7118
7191
  const event = {
7119
7192
  task_id: update.task_id,
7120
7193
  agent_name: update.agent_name,
7121
7194
  status: update.status
7122
7195
  };
7123
7196
  if (update.run_id) event.run_id = update.run_id;
7197
+ return event;
7198
+ }
7199
+ /** A task update as the message the parent's model sees, labeled with its {@link TaskEvent}. */
7200
+ function notificationMessage(update) {
7201
+ const event = eventOf(update);
7202
+ const message = labeled(notificationBody(update), event);
7124
7203
  return {
7125
7204
  role: "user",
7126
- content: notificationContent(update),
7127
- additional_kwargs: { [NOTIFICATION_KEY]: event }
7205
+ content: message.content,
7206
+ additional_kwargs: {
7207
+ ...message.additional_kwargs,
7208
+ [NOTIFICATION_KEY]: event
7209
+ }
7128
7210
  };
7129
7211
  }
7130
7212
  /** Parent thread statuses a notification run can start on: neither running nor waiting for a human. */
@@ -11143,4 +11225,4 @@ Object.defineProperty(exports, "skillsMetadataValue", {
11143
11225
  }
11144
11226
  });
11145
11227
 
11146
- //# sourceMappingURL=langsmith-Bf4pcnIO.cjs.map
11228
+ //# sourceMappingURL=langsmith-9ilIzQAp.cjs.map