wire-tool-adapter.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. import { homedir } from 'node:os';
  2. import { resolve as resolvePath } from 'node:path';
  3. import type { PluginHookCommandHandler, PluginHookEventInput } from './contracts.js';
  4. export function adaptToolIdentity(
  5. handler: PluginHookCommandHandler,
  6. event: PluginHookEventInput['event'],
  7. payload: Readonly<Record<string, unknown>>,
  8. matcherValue: string | undefined,
  9. provenance: PluginHookEventInput['toolProvenance'],
  10. cwd: string,
  11. ): {
  12. readonly toolName: string | undefined;
  13. readonly toolInput: unknown;
  14. readonly matcherValue: string | undefined;
  15. } {
  16. const nativeName = typeof payload.tool_name === 'string' ? payload.tool_name : matcherValue;
  17. const sourceFormat = handler.sourceFormat;
  18. const canUseCompatibleIdentity =
  19. sourceFormat === 'CLAUDE' &&
  20. (event !== 'PostToolUse' || isRecord(payload.compatible_tool_response)) &&
  21. isLosslesslyAdaptableCompatibleToolInput(nativeName, payload.tool_input);
  22. const canUseCodexPatchIdentity =
  23. sourceFormat === 'CODEX' &&
  24. (nativeName === 'write' || nativeName === 'edit') &&
  25. codexApplyPatchCommand(payload.tool_input, nativeName, cwd) !== undefined;
  26. let toolName = nativeName;
  27. if (nativeName === 'bash' && (canUseCompatibleIdentity || sourceFormat === 'CODEX'))
  28. toolName = sourceFormat === 'CLAUDE' && process.platform === 'win32' ? 'PowerShell' : 'Bash';
  29. else if (nativeName === 'read' && canUseCompatibleIdentity) toolName = 'Read';
  30. else if (nativeName === 'write' && canUseCompatibleIdentity) toolName = 'Write';
  31. else if (nativeName === 'edit' && canUseCompatibleIdentity) toolName = 'Edit';
  32. else if (nativeName === 'task' && canUseCompatibleIdentity) toolName = 'Agent';
  33. else if (canUseCodexPatchIdentity) toolName = 'apply_patch';
  34. else if (
  35. sourceFormat === 'CLAUDE' &&
  36. canUseCompatibleIdentity &&
  37. nativeName?.startsWith('mcp__') &&
  38. provenance?.kind === 'plugin_mcp'
  39. ) {
  40. toolName = compatiblePluginMcpToolName(provenance.pluginName, nativeName);
  41. }
  42. return {
  43. toolName,
  44. matcherValue: toolName,
  45. toolInput: adaptToolInput(payload.tool_input, nativeName, sourceFormat, cwd),
  46. };
  47. }
  48. export function restoreNativeToolInput(
  49. value: Readonly<Record<string, unknown>>,
  50. handler: PluginHookCommandHandler,
  51. input: PluginHookEventInput,
  52. ): Readonly<Record<string, unknown>> | undefined {
  53. const nativeName =
  54. typeof input.payload?.tool_name === 'string' ? input.payload.tool_name : input.matcherValue;
  55. if (handler.sourceFormat === 'CODEX') {
  56. if (nativeName === 'write' || nativeName === 'edit') {
  57. const original = input.payload?.tool_input;
  58. const originalCommand = codexApplyPatchCommand(original, nativeName, input.cwd);
  59. if (!originalCommand || !isCommandOnlyBashHookInput(value)) return undefined;
  60. if (value.command === originalCommand) return isRecord(original) ? original : undefined;
  61. return restoreCodexApplyPatchInput(value.command, nativeName);
  62. }
  63. if (nativeName !== 'bash') return value;
  64. const original = input.payload?.tool_input;
  65. if (!isRecord(original) || !isCommandOnlyBashHookInput(value)) return undefined;
  66. return { ...original, command: value.command };
  67. }
  68. if (handler.sourceFormat !== 'CLAUDE') return value;
  69. if (!isLosslesslyAdaptableCompatibleToolInput(nativeName, input.payload?.tool_input))
  70. return value;
  71. if ((nativeName === 'read' || nativeName === 'write') && typeof value.file_path === 'string') {
  72. if (!isValidCompatibleFileToolInput(nativeName, value)) return undefined;
  73. const { file_path, ...rest } = value;
  74. return { path: file_path, ...rest };
  75. }
  76. if (nativeName === 'edit')
  77. return isValidCompatibleFileToolInput(nativeName, value) ? value : undefined;
  78. if (nativeName === 'bash') {
  79. if (!isValidCompatibleBashInput(value)) return undefined;
  80. return value.timeout === undefined
  81. ? value
  82. : { ...value, timeout: (value.timeout as number) / 1_000 };
  83. }
  84. if (nativeName === 'task') {
  85. const original = input.payload?.tool_input;
  86. if (!isRecord(original) || !isValidCompatibleAgentInput(value)) return undefined;
  87. if (typeof original.agent_name === 'string') {
  88. const { subagent_type, ...rest } = value;
  89. return { ...rest, agent_name: subagent_type };
  90. }
  91. if (typeof original.subagent_type === 'string') return value;
  92. return undefined;
  93. }
  94. return value;
  95. }
  96. export function isMcpToolInput(input: PluginHookEventInput): boolean {
  97. const name =
  98. typeof input.payload?.tool_name === 'string' ? input.payload.tool_name : input.matcherValue;
  99. return input.toolProvenance?.kind === 'plugin_mcp' || name?.startsWith('mcp__') === true;
  100. }
  101. export function hasCompatibleJsonShape(original: unknown, replacement: unknown): boolean {
  102. if (original === null || replacement === null) return original === replacement;
  103. if (Array.isArray(original) || Array.isArray(replacement)) {
  104. return Array.isArray(original) && Array.isArray(replacement);
  105. }
  106. if (isRecord(original) || isRecord(replacement)) {
  107. if (!isRecord(original) || !isRecord(replacement)) return false;
  108. const originalKeys = Object.keys(original).sort();
  109. const replacementKeys = Object.keys(replacement).sort();
  110. return (
  111. originalKeys.length === replacementKeys.length &&
  112. originalKeys.every(
  113. (key, index) =>
  114. key === replacementKeys[index] && hasCompatibleJsonShape(original[key], replacement[key]),
  115. )
  116. );
  117. }
  118. return typeof original === typeof replacement;
  119. }
  120. function adaptToolInput(
  121. value: unknown,
  122. nativeName: string | undefined,
  123. sourceFormat: PluginHookCommandHandler['sourceFormat'],
  124. cwd: string,
  125. ): unknown {
  126. if (!isRecord(value)) return value;
  127. if (sourceFormat === 'CODEX') {
  128. if (nativeName === 'bash' && typeof value.command === 'string') {
  129. return { command: value.command };
  130. }
  131. const command = codexApplyPatchCommand(value, nativeName, cwd);
  132. return command ? { command } : value;
  133. }
  134. if (sourceFormat === 'MINIMAX') return value;
  135. if (sourceFormat === 'CLAUDE' && !isLosslesslyAdaptableCompatibleToolInput(nativeName, value))
  136. return value;
  137. if (nativeName === 'bash' && sourceFormat === 'CLAUDE') {
  138. if (value.timeout !== undefined && !isFiniteNumber(value.timeout)) return value;
  139. return value.timeout === undefined ? value : { ...value, timeout: value.timeout * 1_000 };
  140. }
  141. if ((nativeName === 'read' || nativeName === 'write') && typeof value.path === 'string') {
  142. const { path, ...rest } = value;
  143. return { file_path: resolveHookFilePath(path, cwd), ...rest };
  144. }
  145. if (nativeName === 'edit' && typeof value.file_path === 'string') {
  146. return { ...value, file_path: resolveHookFilePath(value.file_path, cwd) };
  147. }
  148. if (nativeName === 'task' && isLosslesslyAdaptableCompatibleToolInput(nativeName, value)) {
  149. if (typeof value.subagent_type === 'string') return value;
  150. const { agent_name, ...rest } = value;
  151. return {
  152. ...rest,
  153. ...(typeof agent_name === 'string' ? { subagent_type: agent_name } : {}),
  154. };
  155. }
  156. return value;
  157. }
  158. function codexApplyPatchCommand(
  159. value: unknown,
  160. nativeName: string | undefined,
  161. cwd: string,
  162. ): string | undefined {
  163. if (!isRecord(value)) return undefined;
  164. if (nativeName === 'write' && isValidNativeWriteInput(value)) {
  165. const path = resolveHookFilePath(value.path as string, cwd);
  166. const content = value.content as string;
  167. return [
  168. '*** Begin Patch',
  169. `*** Add File: ${path}`,
  170. ...content.split('\n').map((line) => `+${line}`),
  171. '*** End Patch',
  172. ].join('\n');
  173. }
  174. if (nativeName === 'edit' && isValidCompatibleFileToolInput(nativeName, value)) {
  175. const path = resolveHookFilePath(value.file_path as string, cwd);
  176. const oldString = value.old_string as string;
  177. const newString = value.new_string as string;
  178. return [
  179. '*** Begin Patch',
  180. `*** Update File: ${path}`,
  181. '@@',
  182. ...oldString.split('\n').map((line) => `-${line}`),
  183. ...newString.split('\n').map((line) => `+${line}`),
  184. '*** End Patch',
  185. ].join('\n');
  186. }
  187. return undefined;
  188. }
  189. function restoreCodexApplyPatchInput(
  190. command: string,
  191. nativeName: 'write' | 'edit',
  192. ): Readonly<Record<string, unknown>> | undefined {
  193. const lines = command.split('\n');
  194. if (lines[0] !== '*** Begin Patch' || lines.at(-1) !== '*** End Patch') return undefined;
  195. const body = lines.slice(1, -1);
  196. const prefix = nativeName === 'write' ? '*** Add File: ' : '*** Update File: ';
  197. const path = body[0]?.startsWith(prefix) ? body[0].slice(prefix.length) : undefined;
  198. if (!path || path.includes('\u0000') || path.includes('\n')) return undefined;
  199. if (nativeName === 'write') {
  200. const contentLines = body.slice(1);
  201. if (contentLines.length === 0 || contentLines.some((line) => !line.startsWith('+'))) {
  202. return undefined;
  203. }
  204. return { path, content: contentLines.map((line) => line.slice(1)).join('\n') };
  205. }
  206. if (body[1] !== '@@') return undefined;
  207. const changed = body.slice(2);
  208. const firstAdded = changed.findIndex((line) => line.startsWith('+'));
  209. if (firstAdded < 0) return undefined;
  210. const removed = changed.slice(0, firstAdded);
  211. const added = changed.slice(firstAdded);
  212. if (
  213. removed.length === 0 ||
  214. removed.some((line) => !line.startsWith('-')) ||
  215. added.some((line) => !line.startsWith('+'))
  216. ) {
  217. return undefined;
  218. }
  219. return {
  220. file_path: path,
  221. old_string: removed.map((line) => line.slice(1)).join('\n'),
  222. new_string: added.map((line) => line.slice(1)).join('\n'),
  223. };
  224. }
  225. function isCommandOnlyBashHookInput(
  226. value: Readonly<Record<string, unknown>>,
  227. ): value is Readonly<{ command: string }> {
  228. return Object.keys(value).length === 1 && typeof value.command === 'string';
  229. }
  230. function isLosslesslyAdaptableCompatibleToolInput(
  231. nativeName: string | undefined,
  232. value: unknown,
  233. ): boolean {
  234. if (!isRecord(value)) return false;
  235. if (nativeName === 'bash') return isValidNativeBashInput(value);
  236. if (nativeName === 'read') return isValidNativeReadInput(value);
  237. if (nativeName === 'write') return isValidNativeWriteInput(value);
  238. if (nativeName === 'edit') return isValidCompatibleFileToolInput(nativeName, value);
  239. if (nativeName !== 'task') return true;
  240. const desktop = typeof value.agent_name === 'string';
  241. const cloud = typeof value.subagent_type === 'string';
  242. if (desktop === cloud) return false;
  243. const allowed = desktop
  244. ? new Set(['description', 'prompt', 'agent_name', 'run_in_background'])
  245. : new Set(['description', 'prompt', 'subagent_type', 'run_in_background']);
  246. return Object.keys(value).every((key) => allowed.has(key));
  247. }
  248. function isValidNativeBashInput(value: Readonly<Record<string, unknown>>): boolean {
  249. return (
  250. hasOnlyKeys(value, ['command', 'timeout', 'run_in_background']) &&
  251. typeof value.command === 'string' &&
  252. (value.timeout === undefined || isFiniteNumber(value.timeout)) &&
  253. (value.run_in_background === undefined || typeof value.run_in_background === 'boolean')
  254. );
  255. }
  256. function isValidCompatibleBashInput(value: Readonly<Record<string, unknown>>): boolean {
  257. return isValidNativeBashInput(value);
  258. }
  259. function isValidNativeReadInput(value: Readonly<Record<string, unknown>>): boolean {
  260. return (
  261. hasOnlyKeys(value, ['path', 'offset', 'limit']) &&
  262. typeof value.path === 'string' &&
  263. (value.offset === undefined || isFiniteNumber(value.offset)) &&
  264. (value.limit === undefined || isFiniteNumber(value.limit))
  265. );
  266. }
  267. function isValidNativeWriteInput(value: Readonly<Record<string, unknown>>): boolean {
  268. return (
  269. hasOnlyKeys(value, ['path', 'content']) &&
  270. typeof value.path === 'string' &&
  271. typeof value.content === 'string'
  272. );
  273. }
  274. function isValidCompatibleFileToolInput(
  275. nativeName: string,
  276. value: Readonly<Record<string, unknown>>,
  277. ): boolean {
  278. if (nativeName === 'read') {
  279. return (
  280. hasOnlyKeys(value, ['file_path', 'offset', 'limit']) &&
  281. typeof value.file_path === 'string' &&
  282. (value.offset === undefined || isFiniteNumber(value.offset)) &&
  283. (value.limit === undefined || isFiniteNumber(value.limit))
  284. );
  285. }
  286. if (nativeName === 'write') {
  287. return (
  288. hasOnlyKeys(value, ['file_path', 'content']) &&
  289. typeof value.file_path === 'string' &&
  290. typeof value.content === 'string'
  291. );
  292. }
  293. return (
  294. nativeName === 'edit' &&
  295. hasOnlyKeys(value, ['file_path', 'old_string', 'new_string', 'replace_all']) &&
  296. typeof value.file_path === 'string' &&
  297. typeof value.old_string === 'string' &&
  298. typeof value.new_string === 'string' &&
  299. (value.replace_all === undefined || typeof value.replace_all === 'boolean')
  300. );
  301. }
  302. export function hasOnlyKeys(
  303. value: Readonly<Record<string, unknown>>,
  304. keys: readonly string[],
  305. ): boolean {
  306. const allowed = new Set(keys);
  307. return Object.keys(value).every((key) => allowed.has(key));
  308. }
  309. function isValidCompatibleAgentInput(value: Readonly<Record<string, unknown>>): boolean {
  310. const allowed = new Set(['description', 'prompt', 'subagent_type', 'run_in_background']);
  311. return (
  312. Object.keys(value).every((key) => allowed.has(key)) &&
  313. typeof value.description === 'string' &&
  314. typeof value.prompt === 'string' &&
  315. typeof value.subagent_type === 'string' &&
  316. (value.run_in_background === undefined || typeof value.run_in_background === 'boolean')
  317. );
  318. }
  319. function isFiniteNumber(value: unknown): value is number {
  320. return typeof value === 'number' && Number.isFinite(value);
  321. }
  322. export function resolveHookFilePath(value: string, cwd: string): string {
  323. if (value === '~') return homedir();
  324. if (value.startsWith('~/') || value.startsWith('~\\')) {
  325. return resolvePath(homedir(), value.slice(2));
  326. }
  327. if (value.startsWith('/') || /^[A-Za-z]:[\\/]/u.test(value) || value.startsWith('\\\\')) {
  328. return value;
  329. }
  330. return resolvePath(cwd, value);
  331. }
  332. function compatiblePluginMcpToolName(pluginName: string, nativeName: string): string {
  333. const suffix = nativeName.slice('mcp__'.length);
  334. return `mcp__plugin_${pluginName}_${suffix}`;
  335. }
  336. function isRecord(value: unknown): value is Record<string, unknown> {
  337. return typeof value === 'object' && value !== null && !Array.isArray(value);
  338. }