vendor-tool-response.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import type { ToolResult } from '@mavis/agent-core/tools';
  2. import { parsePatch } from 'diff';
  3. /**
  4. * Non-serializable source-owned channel for exact vendor PostToolUse values.
  5. *
  6. * Tool implementations attach a value only while they still own every field
  7. * required by the vendor schema. The hook bridge must not reconstruct these
  8. * values from model-facing text because that text may be truncated, decorated,
  9. * or otherwise lossy.
  10. */
  11. export const PLUGIN_HOOK_COMPATIBLE_TOOL_RESPONSE = Symbol.for(
  12. 'mavis.pluginHooks.compatibleToolResponse',
  13. );
  14. export const PLUGIN_HOOK_CODEX_TOOL_RESPONSE = Symbol.for('mavis.pluginHooks.codexToolResponse');
  15. interface ToolResultDetailsWithVendorResponse extends Record<string, unknown> {
  16. [PLUGIN_HOOK_COMPATIBLE_TOOL_RESPONSE]?: Readonly<Record<string, unknown>>;
  17. [PLUGIN_HOOK_CODEX_TOOL_RESPONSE]?: unknown;
  18. }
  19. interface HookToolResultView {
  20. readonly details?: unknown;
  21. }
  22. export function withPluginHookCompatibleToolResponse(
  23. result: ToolResult,
  24. response: Readonly<Record<string, unknown>>,
  25. ): ToolResult {
  26. return {
  27. ...result,
  28. details: withPluginHookCompatibleToolResponseDetails(result.details, response),
  29. };
  30. }
  31. export function withPluginHookCompatibleToolResponseDetails(
  32. details: ToolResult['details'],
  33. response: Readonly<Record<string, unknown>>,
  34. ): ToolResultDetailsWithVendorResponse {
  35. return Object.assign(
  36. { ...(details ?? {}) },
  37. { [PLUGIN_HOOK_COMPATIBLE_TOOL_RESPONSE]: response },
  38. );
  39. }
  40. export function readPluginHookCompatibleToolResponse(
  41. result: HookToolResultView,
  42. ): Readonly<Record<string, unknown>> | undefined {
  43. return (result.details as ToolResultDetailsWithVendorResponse | undefined)?.[
  44. PLUGIN_HOOK_COMPATIBLE_TOOL_RESPONSE
  45. ];
  46. }
  47. export function withPluginHookCodexToolResponse(result: ToolResult, response: unknown): ToolResult {
  48. return {
  49. ...result,
  50. details: withPluginHookCodexToolResponseDetails(result.details, response),
  51. };
  52. }
  53. export function withPluginHookCodexToolResponseDetails(
  54. details: ToolResult['details'],
  55. response: unknown,
  56. ): ToolResultDetailsWithVendorResponse {
  57. return Object.assign({ ...(details ?? {}) }, { [PLUGIN_HOOK_CODEX_TOOL_RESPONSE]: response });
  58. }
  59. export function readPluginHookCodexToolResponse(result: HookToolResultView): unknown | undefined {
  60. return (result.details as ToolResultDetailsWithVendorResponse | undefined)?.[
  61. PLUGIN_HOOK_CODEX_TOOL_RESPONSE
  62. ];
  63. }
  64. /** Attach Compatible's BashOutput only from Pi's source-owned split stream facts. */
  65. export function withCompatibleBashToolResponseFromPiDetails(result: ToolResult): ToolResult {
  66. const response = compatibleBashToolResponseFromPiDetails(result.details);
  67. return response ? withPluginHookCompatibleToolResponse(result, response) : result;
  68. }
  69. export function compatibleBashToolResponseFromPiDetails(
  70. details: unknown,
  71. ): Readonly<Record<string, unknown>> | undefined {
  72. const processOutput = nestedRecord(details, 'processOutput');
  73. if (
  74. !processOutput ||
  75. typeof processOutput.stdout !== 'string' ||
  76. typeof processOutput.stderr !== 'string' ||
  77. typeof processOutput.interrupted !== 'boolean' ||
  78. processOutput.stdoutTruncated !== false ||
  79. processOutput.stderrTruncated !== false
  80. ) {
  81. return undefined;
  82. }
  83. const rawOutputPath = optionalString(processOutput.rawOutputPath);
  84. return {
  85. stdout: processOutput.stdout,
  86. stderr: processOutput.stderr,
  87. interrupted: processOutput.interrupted,
  88. ...(rawOutputPath ? { rawOutputPath } : {}),
  89. };
  90. }
  91. /** Build Compatible's FileReadOutput from Pi's undecorated text-file facts. */
  92. export function compatibleReadToolResponseFromPiDetails(
  93. details: unknown,
  94. ): Readonly<Record<string, unknown>> | undefined {
  95. const file = nestedRecord(details, 'textFile');
  96. if (
  97. !file ||
  98. typeof file.path !== 'string' ||
  99. typeof file.content !== 'string' ||
  100. !nonNegativeInteger(file.numLines) ||
  101. !positiveInteger(file.startLine) ||
  102. !positiveInteger(file.totalLines) ||
  103. typeof file.wholeFileAutoTruncated !== 'boolean'
  104. ) {
  105. return undefined;
  106. }
  107. return {
  108. type: 'text',
  109. file: {
  110. filePath: file.path,
  111. content: file.content,
  112. numLines: file.numLines,
  113. startLine: file.startLine,
  114. totalLines: file.totalLines,
  115. ...(file.wholeFileAutoTruncated ? { truncatedByTokenCap: true } : {}),
  116. },
  117. };
  118. }
  119. export function withCompatibleGlobToolResponse(
  120. result: ToolResult,
  121. input: {
  122. readonly durationMs: number;
  123. readonly filenames: readonly string[];
  124. readonly truncated: boolean;
  125. readonly totalMatches: number;
  126. readonly countIsComplete: boolean;
  127. },
  128. ): ToolResult {
  129. return withPluginHookCompatibleToolResponse(result, {
  130. durationMs: input.durationMs,
  131. numFiles: input.filenames.length,
  132. filenames: [...input.filenames],
  133. truncated: input.truncated,
  134. totalMatches: input.totalMatches,
  135. countIsComplete: input.countIsComplete,
  136. });
  137. }
  138. function nestedRecord(value: unknown, key: string): Readonly<Record<string, unknown>> | undefined {
  139. if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
  140. const nested = (value as Readonly<Record<string, unknown>>)[key];
  141. return nested && typeof nested === 'object' && !Array.isArray(nested)
  142. ? (nested as Readonly<Record<string, unknown>>)
  143. : undefined;
  144. }
  145. function optionalString(value: unknown): string | undefined {
  146. return typeof value === 'string' && value.length > 0 ? value : undefined;
  147. }
  148. function nonNegativeInteger(value: unknown): value is number {
  149. return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
  150. }
  151. function positiveInteger(value: unknown): value is number {
  152. return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
  153. }
  154. export function withCompatibleGrepToolResponse(
  155. result: ToolResult,
  156. input: {
  157. readonly mode: 'content' | 'files_with_matches' | 'count';
  158. readonly filenames: readonly string[];
  159. readonly numLines?: number;
  160. readonly numMatches?: number;
  161. readonly totalFiles?: number;
  162. readonly content?: string;
  163. readonly appliedLimit: number;
  164. readonly appliedOffset: number;
  165. },
  166. ): ToolResult {
  167. return withPluginHookCompatibleToolResponse(result, {
  168. mode: input.mode,
  169. numFiles: input.filenames.length,
  170. filenames: [...input.filenames],
  171. ...(input.content !== undefined ? { content: input.content } : {}),
  172. ...(input.numLines !== undefined ? { numLines: input.numLines } : {}),
  173. ...(input.numMatches !== undefined ? { numMatches: input.numMatches } : {}),
  174. ...(input.totalFiles !== undefined ? { totalFiles: input.totalFiles } : {}),
  175. appliedLimit: input.appliedLimit,
  176. appliedOffset: input.appliedOffset,
  177. });
  178. }
  179. export function withCompatibleEditToolResponse(
  180. result: ToolResult,
  181. input: {
  182. readonly filePath: string;
  183. readonly oldString: string;
  184. readonly newString: string;
  185. readonly originalFile: string;
  186. readonly replaceAll: boolean;
  187. readonly userModified: boolean;
  188. },
  189. ): ToolResult {
  190. const patch = typeof result.details?.patch === 'string' ? result.details.patch : undefined;
  191. if (!patch) return result;
  192. let parsed: ReturnType<typeof parsePatch>[number] | undefined;
  193. try {
  194. parsed = parsePatch(patch)[0];
  195. } catch {
  196. // Hook compatibility is an enhancement; malformed vendor metadata must
  197. // never turn a successful edit into a failed tool call.
  198. return result;
  199. }
  200. if (!parsed) return result;
  201. return withPluginHookCompatibleToolResponse(result, {
  202. filePath: input.filePath,
  203. oldString: input.oldString,
  204. newString: input.newString,
  205. originalFile: input.originalFile,
  206. structuredPatch: parsed.hunks.map((hunk) => ({
  207. oldStart: hunk.oldStart,
  208. oldLines: hunk.oldLines,
  209. newStart: hunk.newStart,
  210. newLines: hunk.newLines,
  211. lines: hunk.lines,
  212. })),
  213. userModified: input.userModified,
  214. replaceAll: input.replaceAll,
  215. });
  216. }