tool-output-budget.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import type { AgentExtension, AfterToolCallHandler, TurnAssemblyCtx } from '@mavis/agent-runtime';
  2. import { isSourceReferenceMarkerBlock } from './source-reference-marker.js';
  3. type TextBlock = { readonly type: 'text'; readonly text: string };
  4. export interface ToolOutputArtifactInput {
  5. readonly sessionId: string;
  6. readonly turnId: string;
  7. readonly agentName: string;
  8. readonly workspaceDir: string;
  9. readonly toolCallId: string;
  10. readonly toolName: string;
  11. readonly args: unknown;
  12. readonly text: string;
  13. readonly originalBytes: number;
  14. readonly sensitive: boolean;
  15. }
  16. export interface ToolOutputArtifact {
  17. readonly reference: string;
  18. readonly metadata?: Readonly<Record<string, unknown>>;
  19. }
  20. export interface ToolOutputBudgetExtensionOptions {
  21. readonly maxInlineBytes: number;
  22. /** Live host-owned override. Missing, invalid or throwing values keep maxInlineBytes. */
  23. readonly getMaxInlineBytes?: () => number | undefined;
  24. /** Head/tail bytes retained only when artifact persistence fails. */
  25. readonly fallbackPreviewBytes?: number;
  26. readonly perToolMaxInlineBytes?: Readonly<Record<string, number>>;
  27. readonly sensitiveTools?: readonly string[];
  28. readonly writeArtifact: (
  29. input: ToolOutputArtifactInput,
  30. ) => ToolOutputArtifact | Promise<ToolOutputArtifact>;
  31. readonly onArtifactError?: (
  32. error: unknown,
  33. input: ToolOutputArtifactInput,
  34. ) => void | Promise<void>;
  35. readonly id?: string;
  36. readonly description?: string;
  37. }
  38. /**
  39. * Externalizes oversized textual tool output while leaving media blocks in
  40. * the model-visible result. Artifact storage, access control, retention and
  41. * cleanup stay behind the injected writer owned by the host.
  42. */
  43. export function toolOutputBudgetExtension(
  44. options: ToolOutputBudgetExtensionOptions,
  45. ): AgentExtension {
  46. const defaultMaxInlineBytes = positiveInteger(options.maxInlineBytes, 'maxInlineBytes');
  47. const fallbackPreviewBytes = positiveInteger(
  48. options.fallbackPreviewBytes ?? Math.min(defaultMaxInlineBytes, 2_048),
  49. 'fallbackPreviewBytes',
  50. );
  51. const perTool = normalizePerToolLimits(options.perToolMaxInlineBytes);
  52. const sensitiveTools = new Set(options.sensitiveTools ?? []);
  53. const afterToolCall: AfterToolCallHandler = async (toolContext, _signal, turnCtx) => {
  54. // A receipt is only a safe replacement when this exact turn can recover
  55. // the archived result. Keep the original ToolResult otherwise.
  56. if (!toolContext.context.tools?.some((tool) => tool.name === 'read')) return undefined;
  57. const textBlocks = toolContext.result.content.filter(
  58. (block): block is Extract<(typeof toolContext.result.content)[number], { type: 'text' }> =>
  59. block.type === 'text',
  60. );
  61. if (textBlocks.length === 0) return undefined;
  62. // Count every text byte, including host-generated markers.
  63. const text = textBlocks.map((block) => block.text).join('\n');
  64. const originalBytes = Buffer.byteLength(text);
  65. const toolName = toolContext.toolCall.name;
  66. const limit =
  67. perTool.get(toolName) ??
  68. readLiveMaxInlineBytes(options.getMaxInlineBytes, defaultMaxInlineBytes);
  69. if (originalBytes <= limit) return undefined;
  70. const sourceMarkerBlocks = boundedSourceReferenceMarkers(textBlocks, Math.min(limit, 4_096));
  71. const retainedMarkers = new Set(sourceMarkerBlocks);
  72. // Keep original structured payloads parseable. Bounded host hints stay in
  73. // context; every other block (including oversized hints) is archived.
  74. const artifactText = textBlocks
  75. .filter((block) => !retainedMarkers.has(block))
  76. .map((block) => block.text)
  77. .join('\n');
  78. const artifactInput = buildArtifactInput(
  79. turnCtx,
  80. toolContext.toolCall.id,
  81. toolName,
  82. toolContext.args,
  83. artifactText,
  84. originalBytes,
  85. sensitiveTools.has(toolName),
  86. );
  87. const mediaBlocks = toolContext.result.content.filter((block) => block.type !== 'text');
  88. try {
  89. const artifact = await options.writeArtifact(artifactInput);
  90. const receipt = buildExternalizedReceipt({
  91. artifact,
  92. toolName,
  93. args: toolContext.args,
  94. isError: toolContext.isError,
  95. });
  96. return {
  97. // Preserve only bounded, host-created citation hints after archiving.
  98. content: [{ type: 'text', text: receipt }, ...sourceMarkerBlocks, ...mediaBlocks],
  99. details: mergeBudgetDetails(toolContext.result.details, {
  100. externalized: true,
  101. fallback: false,
  102. original_bytes: originalBytes,
  103. reference: artifact.reference,
  104. ...(artifact.metadata ?? {}),
  105. }),
  106. };
  107. } catch (error) {
  108. await notifyArtifactError(options.onArtifactError, error, artifactInput);
  109. const notice = `\n\n[tool output truncated: ${originalBytes} bytes; artifact persistence failed]\n\n`;
  110. return {
  111. content: [
  112. { type: 'text', text: headTailPreview(text, fallbackPreviewBytes, notice) },
  113. ...mediaBlocks,
  114. ],
  115. details: mergeBudgetDetails(toolContext.result.details, {
  116. externalized: false,
  117. fallback: true,
  118. original_bytes: originalBytes,
  119. }),
  120. };
  121. }
  122. };
  123. return {
  124. id: options.id ?? 'tool-output-budget',
  125. description:
  126. options.description ??
  127. 'Externalize oversized textual tool results and replace them with a recovery receipt.',
  128. init(pi) {
  129. pi.on('after_tool_call', afterToolCall);
  130. },
  131. };
  132. }
  133. function boundedSourceReferenceMarkers(
  134. textBlocks: readonly TextBlock[],
  135. limit: number,
  136. ): TextBlock[] {
  137. const sourceMarkerBlocks: TextBlock[] = [];
  138. let remainingBytes = limit;
  139. textBlocks.forEach((block) => {
  140. if (!isSourceReferenceMarkerBlock(block)) return;
  141. const bytes = Buffer.byteLength(block.text) + 1;
  142. if (bytes > remainingBytes) return;
  143. remainingBytes -= bytes;
  144. sourceMarkerBlocks.push(block);
  145. });
  146. return sourceMarkerBlocks;
  147. }
  148. function buildArtifactInput(
  149. ctx: TurnAssemblyCtx,
  150. toolCallId: string,
  151. toolName: string,
  152. args: unknown,
  153. text: string,
  154. originalBytes: number,
  155. sensitive: boolean,
  156. ): ToolOutputArtifactInput {
  157. return {
  158. sessionId: ctx.sessionId,
  159. turnId: ctx.turnId,
  160. agentName: ctx.agentName,
  161. workspaceDir: ctx.workspaceDir,
  162. toolCallId,
  163. toolName,
  164. args,
  165. text,
  166. originalBytes,
  167. sensitive,
  168. };
  169. }
  170. function positiveInteger(value: number, field: string): number {
  171. if (!Number.isSafeInteger(value) || value <= 0) {
  172. throw new Error(`toolOutputBudgetExtension: ${field} must be a positive integer`);
  173. }
  174. return value;
  175. }
  176. function readLiveMaxInlineBytes(
  177. getMaxInlineBytes: (() => number | undefined) | undefined,
  178. fallback: number,
  179. ): number {
  180. try {
  181. const value = getMaxInlineBytes?.();
  182. return value !== undefined && Number.isSafeInteger(value) && value > 0 ? value : fallback;
  183. } catch {
  184. return fallback;
  185. }
  186. }
  187. function normalizePerToolLimits(
  188. limits: Readonly<Record<string, number>> | undefined,
  189. ): ReadonlyMap<string, number> {
  190. const normalized = new Map<string, number>();
  191. for (const [toolName, value] of Object.entries(limits ?? {})) {
  192. normalized.set(toolName, positiveInteger(value, `perToolMaxInlineBytes.${toolName}`));
  193. }
  194. return normalized;
  195. }
  196. function headTailPreview(text: string, budgetBytes: number, notice: string): string {
  197. const headBytes = Math.ceil(budgetBytes / 2);
  198. const tailBytes = Math.floor(budgetBytes / 2);
  199. return `${takeUtf8Start(text, headBytes)}${notice}${takeUtf8End(text, tailBytes)}`;
  200. }
  201. function takeUtf8Start(text: string, budgetBytes: number): string {
  202. let used = 0;
  203. let result = '';
  204. for (const char of text) {
  205. const bytes = Buffer.byteLength(char);
  206. if (used + bytes > budgetBytes) break;
  207. result += char;
  208. used += bytes;
  209. }
  210. return result;
  211. }
  212. function takeUtf8End(text: string, budgetBytes: number): string {
  213. let used = 0;
  214. let start = text.length;
  215. let cursor = text.length;
  216. while (cursor > 0) {
  217. const end = cursor;
  218. cursor -= 1;
  219. if (
  220. isLowSurrogate(text.charCodeAt(cursor)) &&
  221. cursor > 0 &&
  222. isHighSurrogate(text.charCodeAt(cursor - 1))
  223. ) {
  224. cursor -= 1;
  225. }
  226. const bytes = Buffer.byteLength(text.slice(cursor, end));
  227. if (used + bytes > budgetBytes) break;
  228. start = cursor;
  229. used += bytes;
  230. }
  231. return text.slice(start);
  232. }
  233. function isHighSurrogate(codeUnit: number): boolean {
  234. return codeUnit >= 0xd800 && codeUnit <= 0xdbff;
  235. }
  236. function isLowSurrogate(codeUnit: number): boolean {
  237. return codeUnit >= 0xdc00 && codeUnit <= 0xdfff;
  238. }
  239. function buildExternalizedReceipt(input: {
  240. readonly artifact: ToolOutputArtifact;
  241. readonly toolName: string;
  242. readonly args: unknown;
  243. readonly isError: boolean;
  244. }): string {
  245. const toolName = truncateUtf8(normalizeReceiptText(input.toolName), 64) || 'tool';
  246. const source = readReceiptSource(input.toolName, input.args);
  247. const sourceLine = source ? `Source: ${truncateUtf8(source, 256)}\n` : '';
  248. const errorLine = input.isError ? 'Result: error\n' : '';
  249. const chunkedInstruction =
  250. input.artifact.metadata?.read_format === 'chunked_jsonl_v1'
  251. ? "\nArtifact format: chunked JSONL; concatenate each chunk row's text field in index order."
  252. : '';
  253. return `[Tool output externalized
  254. Tool: ${toolName}
  255. ${sourceLine}${errorLine}Artifact: ${input.artifact.reference}${chunkedInstruction}
  256. Recover the needed facts from this artifact now, before answering, inferring, or searching another source.
  257. Search this artifact first with bounded rg/grep when available, then read the relevant ranges with read(path, offset, limit).
  258. If artifact search is unavailable, use bounded read directly.
  259. Do not read or print the entire artifact in a single call.
  260. When complete content is required, continue with bounded reads until all of it has been read.
  261. Do not treat this receipt as evidence.]`;
  262. }
  263. function readReceiptSource(toolName: string, args: unknown): string | undefined {
  264. if (!isRecord(args)) return undefined;
  265. const canonicalToolName = normalizeReceiptText(toolName).toLowerCase();
  266. if (canonicalToolName === 'grep') {
  267. const pattern = readReceiptSourceField(args, 'pattern');
  268. const path = readReceiptSourceField(args, 'path') ?? readReceiptSourceField(args, 'file_path');
  269. const source = [pattern, path].filter((field): field is string => Boolean(field)).join('; ');
  270. if (source) return source;
  271. }
  272. for (const key of ['query', 'url', 'pattern', 'path', 'file_path'] as const) {
  273. const source = readReceiptSourceField(args, key);
  274. if (source) return source;
  275. }
  276. return undefined;
  277. }
  278. function readReceiptSourceField(
  279. args: Readonly<Record<string, unknown>>,
  280. key: string,
  281. ): string | undefined {
  282. const value = args[key];
  283. if (typeof value !== 'string') return undefined;
  284. // Source is only a receipt anchor. Bound it before whitespace normalization
  285. // so a huge tool argument cannot add another full-string scan here.
  286. const normalized = normalizeReceiptText(takeUtf8Start(value, 512));
  287. return normalized ? `${key}=${JSON.stringify(normalized)}` : undefined;
  288. }
  289. function normalizeReceiptText(value: string): string {
  290. return value.replaceAll(/\s+/gu, ' ').trim();
  291. }
  292. function truncateUtf8(value: string, maxBytes: number): string {
  293. if (Buffer.byteLength(value) <= maxBytes) return value;
  294. const ellipsis = '…';
  295. const ellipsisBytes = Buffer.byteLength(ellipsis);
  296. if (maxBytes <= ellipsisBytes) return '';
  297. return takeUtf8Start(value, maxBytes - ellipsisBytes) + ellipsis;
  298. }
  299. function mergeBudgetDetails(
  300. details: unknown,
  301. budget: Readonly<Record<string, unknown>>,
  302. ): Record<string, unknown> {
  303. const base = isRecord(details)
  304. ? details
  305. : details === undefined
  306. ? {}
  307. : { original_details: details };
  308. return { ...base, tool_output_budget: budget };
  309. }
  310. function isRecord(value: unknown): value is Record<string, unknown> {
  311. return typeof value === 'object' && value !== null && !Array.isArray(value);
  312. }
  313. async function notifyArtifactError(
  314. observer: ToolOutputBudgetExtensionOptions['onArtifactError'],
  315. error: unknown,
  316. input: ToolOutputArtifactInput,
  317. ): Promise<void> {
  318. if (!observer) return;
  319. try {
  320. await observer(error, input);
  321. } catch {
  322. // Observability must not replace the bounded fallback result.
  323. }
  324. }