source-reference-files.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import nodePath from 'node:path';
  2. import { shellSourceStages } from '@mavis/agent-runtime';
  3. import type { ToolSourceAdapterInput, ToolSourceReference } from './source-reference.js';
  4. interface GeneratedFileReferenceState {
  5. readonly references: Map<string, ToolSourceReference>;
  6. readonly evidence: Map<string, string>;
  7. readonly generatedFilePaths: Set<string>;
  8. }
  9. export function generatedFilePathsForToolCall(input: ToolSourceAdapterInput): string[] {
  10. const toolName = normalizeToolName(input.toolName);
  11. const args = readRecord(input.args);
  12. if (['write', 'write_file', 'create', 'create_file'].includes(toolName)) {
  13. const target =
  14. readNonEmptyString(args?.path) ??
  15. readNonEmptyString(args?.file_path) ??
  16. readNonEmptyString(args?.filePath);
  17. return target ? [resolveGeneratedFilePath(target, input.turn.workspaceDir)] : [];
  18. }
  19. if (toolName !== 'bash') return [];
  20. const command = readNonEmptyString(args?.command);
  21. if (!command) return [];
  22. const stages = shellSourceStages(command, input.turn.workspaceDir, resolveShellPath);
  23. return Array.from(
  24. new Set(
  25. stages.flatMap(({ command: stageCommand, directory }) =>
  26. Array.from(
  27. stageCommand.matchAll(
  28. /(?:^|[ \t])(?:\d+)?>{1,2}[ \t]*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|([^\s;&|]+))/gmu,
  29. ),
  30. (match) => match[1] ?? match[2] ?? match[3] ?? '',
  31. )
  32. .map((target) => target.trim())
  33. .filter((target) => target && !target.startsWith('&'))
  34. .flatMap((target) => resolveShellPath(target, directory) ?? [])
  35. .filter((target) => !isTemporaryOrInternalFilePath(target)),
  36. ),
  37. ),
  38. );
  39. }
  40. function resolveShellPath(value: string, directory: string | undefined): string | undefined {
  41. if (!directory && !nodePath.posix.isAbsolute(value) && !nodePath.win32.isAbsolute(value))
  42. return undefined;
  43. return resolveGeneratedFilePath(value, directory ?? '');
  44. }
  45. function resolveGeneratedFilePath(value: string, workingDirectory: string): string {
  46. if (nodePath.posix.isAbsolute(value) || nodePath.win32.isAbsolute(value)) {
  47. return normalizeFilePath(value);
  48. }
  49. const pathApi = nodePath.win32.isAbsolute(workingDirectory) ? nodePath.win32 : nodePath.posix;
  50. return normalizeFilePath(pathApi.resolve(workingDirectory, value));
  51. }
  52. function generatedFilePathKey(value: string): string {
  53. const normalized = normalizeFilePath(value).replace(/:\d+(?::\d+)?$/u, '');
  54. return /^[A-Za-z]:\//u.test(normalized) ? normalized.toLowerCase() : normalized;
  55. }
  56. export function isGeneratedFileReference(
  57. reference: ToolSourceReference,
  58. generatedFilePaths: ReadonlySet<string>,
  59. ): boolean {
  60. return (
  61. reference.type === 'file' &&
  62. Boolean(reference.path) &&
  63. generatedFilePaths.has(generatedFilePathKey(reference.path ?? ''))
  64. );
  65. }
  66. export function recordGeneratedFilePaths(
  67. state: GeneratedFileReferenceState,
  68. paths: readonly string[],
  69. ): void {
  70. if (paths.length === 0) return;
  71. paths.forEach((generatedPath) =>
  72. state.generatedFilePaths.add(generatedFilePathKey(generatedPath)),
  73. );
  74. for (const [citationId, reference] of state.references) {
  75. if (!isGeneratedFileReference(reference, state.generatedFilePaths)) continue;
  76. state.references.delete(citationId);
  77. state.evidence.delete(citationId);
  78. }
  79. }
  80. /**
  81. * Office/PDF and other binary attachments are commonly inspected by skill
  82. * scripts through `bash` because the native read tool cannot decode them. The
  83. * default adapter accepts only dated v2 asset paths. A local host may also
  84. * resolve absolute shell paths against its Session-owned attachment registry
  85. * or workspace boundary; unresolved operands and internal temporary artifacts
  86. * stay excluded.
  87. */
  88. export function registeredAssetPathsFromShellCommand(command: string): string[] {
  89. return Array.from(
  90. command.matchAll(
  91. /(?:[A-Za-z]:[\\/]|\/)[^"'`\r\n]*?[\\/]v2[\\/]assets[\\/]\d{4}[\\/]\d{2}[\\/]\d{2}[\\/][^"'`\r\n]*?\.[A-Za-z0-9]{1,16}/gu,
  92. ),
  93. (match) => match[0],
  94. );
  95. }
  96. export function absoluteFilePathsFromShellCommand(command: string): string[] {
  97. const quoted = Array.from(
  98. command.matchAll(/(["'])((?:[A-Za-z]:[\\/]|\/)[^"'`\r\n]+?\.[A-Za-z0-9]{1,16})\1/gu),
  99. (match) => match[2] ?? '',
  100. );
  101. const unquoted = Array.from(
  102. command.matchAll(
  103. /(?:^|[\s;&|<>])((?:[A-Za-z]:[\\/]|\/)[^\s"'`;&|<>]+?\.[A-Za-z0-9]{1,16})(?=$|[\s;&|<>])/gmu,
  104. ),
  105. (match) => match[1] ?? '',
  106. );
  107. return Array.from(new Set([...quoted, ...unquoted].filter(Boolean)));
  108. }
  109. export function workspaceFilePathsFromShellCommand(
  110. command: string,
  111. workspaceDir: string,
  112. ): string[] {
  113. return Array.from(
  114. new Set(
  115. shellSourceStages(command, workspaceDir, resolveShellPath).flatMap(
  116. ({ command: stageCommand, directory }) =>
  117. shellFilePathOperands(stageCommand)
  118. .filter(
  119. (operand) =>
  120. nodePath.posix.isAbsolute(operand) ||
  121. nodePath.win32.isAbsolute(operand) ||
  122. normalizeFilePath(operand).includes('/'),
  123. )
  124. .flatMap((operand) => resolveShellPath(operand, directory) ?? []),
  125. ),
  126. ),
  127. );
  128. }
  129. /**
  130. * A later shell call often reuses a validated workspace File by basename after
  131. * changing into the workspace (for example `unzip -p 'report.pptx'`). Match
  132. * exact resolved identities only; a unique basename is not evidence of identity.
  133. */
  134. export function knownFileReferencesUsedByShellCommand(
  135. input: ToolSourceAdapterInput,
  136. references: Iterable<ToolSourceReference>,
  137. ): ToolSourceReference[] {
  138. if (normalizeToolName(input.toolName) !== 'bash') return [];
  139. const command = readNonEmptyString(readRecord(input.args)?.command);
  140. if (!command) return [];
  141. const knownFiles = Array.from(references).filter(
  142. (reference): reference is ToolSourceReference & { readonly path: string } =>
  143. reference.type === 'file' && Boolean(reference.path),
  144. );
  145. if (knownFiles.length === 0) return [];
  146. const operands = shellSourceStages(command, input.turn.workspaceDir, resolveShellPath).flatMap(
  147. ({ command: stageCommand, directory }) =>
  148. shellFilePathOperands(stageCommand).flatMap(
  149. (operand) => resolveShellPath(operand, directory) ?? [],
  150. ),
  151. );
  152. const resolved = operands.flatMap((operand) => {
  153. const matches = knownFiles.filter(
  154. (reference) => generatedFilePathKey(operand) === generatedFilePathKey(reference.path),
  155. );
  156. if (matches.length !== 1 || !matches[0]) return [];
  157. return [
  158. {
  159. ...matches[0],
  160. tool_call_id: input.toolCallId,
  161. tool_name: input.toolName,
  162. result_path: '$',
  163. },
  164. ];
  165. });
  166. return Array.from(
  167. new Map(resolved.map((reference) => [reference.source_id, reference] as const)).values(),
  168. );
  169. }
  170. function shellFilePathOperands(command: string): string[] {
  171. const quoted = Array.from(
  172. command.matchAll(/(["'])((?:\.{0,2}[\\/])?[^"'`\r\n]*?\.[A-Za-z0-9]{1,16})\1/gu),
  173. (match) => match[2] ?? '',
  174. );
  175. const unquoted = Array.from(
  176. command.matchAll(
  177. /(?:^|[\s;&|<>])((?:\.{0,2}[\\/])?[^\s"'`;&|<>]+?\.[A-Za-z0-9]{1,16})(?=$|[\s;&|<>])/gmu,
  178. ),
  179. (match) => match[1] ?? '',
  180. );
  181. return Array.from(
  182. new Set(
  183. [...quoted, ...unquoted]
  184. .map((value) => value.trim())
  185. .filter(
  186. (value) =>
  187. value && !['*', '?', '[', ']', '{', '}', '$'].some((marker) => value.includes(marker)),
  188. ),
  189. ),
  190. );
  191. }
  192. export function normalizeFilePath(value: string): string {
  193. return value.trim().replaceAll('\\', '/').replace(/^\.\//u, '').replace(/\/+$/u, '');
  194. }
  195. export function isTemporaryOrInternalFilePath(value: string): boolean {
  196. const path = normalizeFilePath(value);
  197. if (/[/\\]v2[/\\]assets[/\\]\d{4}[/\\]\d{2}[/\\]\d{2}[/\\][^/\\]+$/u.test(value)) {
  198. return false;
  199. }
  200. return (
  201. /(?:^|\/)\.(?:minimax|mavis)(?:-[^/]*)?(?:\/|$)/iu.test(path) ||
  202. /(?:^|\/)reports\/tool-outputs(?:\/|$)/iu.test(path) ||
  203. /(?:^|\/)(?:\.tmp|tmp|temp)(?:\/|$)/iu.test(path) ||
  204. /^\/?(?:private\/)?var\/folders\/[^/]+\/[^/]+\/T(?:\/|$)/iu.test(path) ||
  205. /(?:^|\/)AppData\/Local\/Temp(?:\/|$)/iu.test(path) ||
  206. /\.readable\.v\d+\.jsonl$/iu.test(path)
  207. );
  208. }
  209. export function filePathsMatch(left: string, right: string): boolean {
  210. const normalizedLeft = normalizeFilePath(left).replace(/:\d+(?::\d+)?$/u, '');
  211. const normalizedRight = normalizeFilePath(right).replace(/:\d+(?::\d+)?$/u, '');
  212. return (
  213. normalizedLeft === normalizedRight ||
  214. normalizedLeft.endsWith(`/${normalizedRight}`) ||
  215. normalizedRight.endsWith(`/${normalizedLeft}`)
  216. );
  217. }
  218. function normalizeToolName(value: string): string {
  219. return value
  220. .trim()
  221. .toLowerCase()
  222. .replace(/[\s-]+/gu, '_');
  223. }
  224. function readRecord(value: unknown): Record<string, unknown> | undefined {
  225. return typeof value === 'object' && value !== null && !Array.isArray(value)
  226. ? (value as Record<string, unknown>)
  227. : undefined;
  228. }
  229. function readNonEmptyString(value: unknown): string | undefined {
  230. return typeof value === 'string' && value.trim() ? value.trim() : undefined;
  231. }