runner.ts 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348
  1. import { spawn, type ChildProcess } from 'node:child_process';
  2. import { mkdir } from 'node:fs/promises';
  3. import { resolve as resolvePath } from 'node:path';
  4. import type {
  5. PluginHookCommandHandler,
  6. PluginHookDecision,
  7. PluginHookEventInput,
  8. PluginHookLogger,
  9. PluginHookObserver,
  10. PluginHookPermissionUpdate,
  11. PluginHookPermissionUpdateDestination,
  12. PluginHookPermissionUpdateMode,
  13. PluginHookPermissionRuleValue,
  14. PluginHookRunDiagnostic,
  15. PluginHookRunResult,
  16. } from './contracts.js';
  17. import { resolveHookCommandInvocation } from './command-invocation.js';
  18. import { isSafePluginHookMatcher } from './parser.js';
  19. import { boundHandlerDecision } from './output-artifacts.js';
  20. import {
  21. adaptToolIdentity,
  22. hasOnlyKeys,
  23. hasCompatibleJsonShape,
  24. isMcpToolInput,
  25. resolveHookFilePath,
  26. restoreNativeToolInput,
  27. } from './wire-tool-adapter.js';
  28. const MAX_OUTPUT_BYTES = 64 * 1024;
  29. const MAX_INPUT_BYTES = 1024 * 1024;
  30. const MAX_REASON_CHARS = 4_096;
  31. const MAX_INJECTED_TEXT_CHARS = 64 * 1024;
  32. const MAX_OUTPUT_VALUE_DEPTH = 64;
  33. const MAX_OUTPUT_VALUE_NODES = 10_000;
  34. const ORDINARY_EVENT_BUDGET_MS = 15_000;
  35. const SESSION_END_BUDGET_MS = 3_000;
  36. const PROCESS_DRAIN_BUDGET_MS = 500;
  37. export class PluginHookRunner {
  38. private logger?: PluginHookLogger;
  39. private observer?: PluginHookObserver;
  40. private readonly activeChildren = new Set<ChildProcess>();
  41. private readonly disposalController = new AbortController();
  42. private disposed = false;
  43. constructor(logger?: PluginHookLogger, observer?: PluginHookObserver) {
  44. this.logger = logger;
  45. this.observer = observer;
  46. }
  47. configure(input: {
  48. readonly logger?: PluginHookLogger;
  49. readonly observer?: PluginHookObserver;
  50. }): void {
  51. this.logger = input.logger;
  52. this.observer = input.observer;
  53. }
  54. async run(
  55. handlers: readonly PluginHookCommandHandler[],
  56. input: PluginHookEventInput,
  57. signal?: AbortSignal,
  58. ): Promise<PluginHookRunResult> {
  59. const eventStartedAt = Date.now();
  60. const unavailableAdapters = handlers.filter(
  61. (handler) =>
  62. needsPostToolAdapter(handler, input) &&
  63. matches(handler, withPostToolAdapterEvidence(handler, input)) &&
  64. matchesCondition(handler, withPostToolAdapterEvidence(handler, input)),
  65. );
  66. const unavailable = new Set(unavailableAdapters);
  67. const selected = handlers
  68. .filter(
  69. (handler) =>
  70. !unavailable.has(handler) &&
  71. handler.event === input.event &&
  72. isEventSupportedBySource(handler, input) &&
  73. matches(handler, input) &&
  74. matchesCondition(handler, input),
  75. )
  76. .sort(compareHandlers);
  77. const eventBudgetMs =
  78. input.event === 'SessionEnd' ? SESSION_END_BUDGET_MS : ORDINARY_EVENT_BUDGET_MS;
  79. const diagnostics: PluginHookRunDiagnostic[] = unavailableAdapters.map((handler) =>
  80. runDiagnostic(handler, 'HOOK_INVALID_INPUT'),
  81. );
  82. for (const [index, diagnostic] of diagnostics.entries()) {
  83. const handler = unavailableAdapters[index];
  84. if (!handler) continue;
  85. this.logger?.warn(
  86. { ...diagnostic },
  87. 'Plugin hook command skipped because its vendor tool response could not be adapted losslessly',
  88. );
  89. observeHandler(this.observer, {
  90. event: input.event,
  91. format: handler.sourceFormat,
  92. outcome: 'error',
  93. durationMs: 0,
  94. processKilled: false,
  95. });
  96. }
  97. let completionCounter = 0;
  98. const outcomes = await mapWithConcurrency(
  99. selected,
  100. MAX_CONCURRENT_COMMANDS,
  101. async (handler) => {
  102. const handlerStartedAt = Date.now();
  103. const remainingEventBudgetMs = eventStartedAt + eventBudgetMs - handlerStartedAt;
  104. const outcome =
  105. remainingEventBudgetMs <= 0
  106. ? {
  107. diagnostic: runDiagnostic(handler, 'HOOK_TIMEOUT' as const),
  108. processKilled: false,
  109. }
  110. : await this.runCommand(
  111. handler,
  112. input,
  113. Math.min(handler.timeoutMs, remainingEventBudgetMs),
  114. signal,
  115. );
  116. const completionOrder = completionCounter;
  117. completionCounter += 1;
  118. if (outcome.diagnostic) {
  119. this.logger?.warn({ ...outcome.diagnostic }, 'Plugin hook command failed open');
  120. observeHandler(this.observer, {
  121. event: input.event,
  122. format: handler.sourceFormat,
  123. outcome: diagnosticOutcome(outcome.diagnostic.code),
  124. durationMs: Date.now() - handlerStartedAt,
  125. processKilled: outcome.processKilled,
  126. });
  127. } else if (outcome.decision) {
  128. observeHandler(this.observer, {
  129. event: input.event,
  130. format: handler.sourceFormat,
  131. outcome:
  132. outcome.decision.decision === 'deny'
  133. ? 'deny'
  134. : outcome.decision.decision === 'ask' || outcome.decision.decision === 'defer'
  135. ? 'ask'
  136. : 'success',
  137. durationMs: Date.now() - handlerStartedAt,
  138. processKilled: outcome.processKilled,
  139. });
  140. }
  141. return { ...outcome, handler, completionOrder };
  142. },
  143. );
  144. let decision = defaultDecision(input.event);
  145. let firstCodexWinningReason: string | undefined;
  146. let firstCodexStopReason: string | undefined;
  147. for (const outcome of outcomes) {
  148. if (outcome.diagnostic) diagnostics.push(outcome.diagnostic);
  149. if (outcome.decision) {
  150. if (
  151. outcome.handler.sourceFormat === 'CODEX' &&
  152. firstCodexWinningReason === undefined &&
  153. isCodexWinningReason(input.event, outcome.decision)
  154. ) {
  155. firstCodexWinningReason = outcome.decision.reason;
  156. }
  157. if (
  158. outcome.handler.sourceFormat === 'CODEX' &&
  159. firstCodexStopReason === undefined &&
  160. outcome.decision.continue === false
  161. ) {
  162. firstCodexStopReason = outcome.decision.stopReason;
  163. }
  164. decision = mergePluginHookDecisions(decision, outcome.decision);
  165. }
  166. }
  167. if (firstCodexWinningReason !== undefined) {
  168. decision = { ...decision, reason: firstCodexWinningReason };
  169. }
  170. if (firstCodexStopReason !== undefined) {
  171. decision = { ...decision, stopReason: firstCodexStopReason };
  172. }
  173. if (input.event === 'PreToolUse' && decision.decision !== 'deny') {
  174. const latestCompatibleRewrite = outcomes
  175. .filter(
  176. (outcome) =>
  177. outcome.handler.sourceFormat !== 'MINIMAX' &&
  178. outcome.decision?.updatedInput !== undefined,
  179. )
  180. .sort((left, right) => right.completionOrder - left.completionOrder)[0]
  181. ?.decision?.updatedInput;
  182. if (latestCompatibleRewrite !== undefined) {
  183. decision = { ...decision, updatedInput: latestCompatibleRewrite };
  184. }
  185. }
  186. if (input.event === 'PreToolUse' && decision.decision === 'deny' && decision.updatedInput) {
  187. const blockedDecision = { ...decision };
  188. delete blockedDecision.updatedInput;
  189. decision = blockedDecision;
  190. }
  191. observeEvent(this.observer, {
  192. event: input.event,
  193. outcome: eventOutcome(decision, diagnostics),
  194. durationMs: Date.now() - eventStartedAt,
  195. });
  196. return { decision, diagnostics };
  197. }
  198. async dispose(): Promise<void> {
  199. if (this.disposed) return;
  200. this.disposed = true;
  201. this.disposalController.abort('Plugin Hook runner disposed');
  202. await Promise.allSettled([...this.activeChildren].map((child) => terminateAndDrain(child)));
  203. }
  204. private async runCommand(
  205. handler: PluginHookCommandHandler,
  206. input: PluginHookEventInput,
  207. timeoutMs: number,
  208. signal?: AbortSignal,
  209. ): Promise<{
  210. decision?: PluginHookDecision;
  211. diagnostic?: PluginHookRunDiagnostic;
  212. processKilled: boolean;
  213. }> {
  214. if (signal?.aborted || this.disposalController.signal.aborted) {
  215. return { diagnostic: runDiagnostic(handler, 'HOOK_ABORTED'), processKilled: false };
  216. }
  217. const handlerInput = adaptVendorInput(handler, input);
  218. if (!isValidWireInput(handler, handlerInput)) {
  219. return { diagnostic: runDiagnostic(handler, 'HOOK_INVALID_INPUT'), processKilled: false };
  220. }
  221. const serialized = serializeHookInput(handlerInput);
  222. if (!serialized) {
  223. return { diagnostic: runDiagnostic(handler, 'HOOK_INVALID_INPUT'), processKilled: false };
  224. }
  225. let child: ChildProcess;
  226. const pluginDataDir =
  227. handler.pluginDataDir ??
  228. resolvePath(handler.pluginRoot, '..', '.plugin-data', safePluginDataName(handler.pluginName));
  229. try {
  230. await mkdir(pluginDataDir, { recursive: true, mode: 0o700 });
  231. const env = {
  232. ...safeHookEnvironment(),
  233. MINIMAX_PLUGIN_ROOT: handler.pluginRoot,
  234. CLAUDE_PLUGIN_ROOT: handler.pluginRoot,
  235. CODEX_PLUGIN_ROOT: handler.pluginRoot,
  236. PLUGIN_ROOT: handler.pluginRoot,
  237. CLAUDE_PLUGIN_DATA: pluginDataDir,
  238. PLUGIN_DATA: pluginDataDir,
  239. MINIMAX_PROJECT_DIR: input.cwd,
  240. CLAUDE_PROJECT_DIR: input.cwd,
  241. CODEX_PROJECT_DIR: input.cwd,
  242. ...(handler.sourceFormat === 'CLAUDE' && handlerInput.effort
  243. ? { CLAUDE_EFFORT: handlerInput.effort.level }
  244. : {}),
  245. };
  246. const command = expandHookPlaceholders(handler.command, env);
  247. const args = handler.args?.map((value) => expandHookPlaceholders(value, env));
  248. const invocation = resolveHookCommandInvocation({
  249. command,
  250. ...(args ? { args } : {}),
  251. ...(handler.shell ? { shell: handler.shell } : {}),
  252. sourceFormat: handler.sourceFormat,
  253. });
  254. child = spawn(invocation.command, invocation.args, {
  255. cwd: input.cwd,
  256. env,
  257. shell: invocation.shell,
  258. detached: process.platform !== 'win32',
  259. windowsHide: true,
  260. stdio: ['pipe', 'pipe', 'pipe'],
  261. });
  262. } catch {
  263. return { diagnostic: runDiagnostic(handler, 'HOOK_PROCESS_ERROR'), processKilled: false };
  264. }
  265. this.activeChildren.add(child);
  266. const overflowController = new AbortController();
  267. const readOutput = collectOutput(child, () => overflowController.abort());
  268. child.stdin?.on('error', () => undefined);
  269. child.stdin?.end(serialized);
  270. try {
  271. const result = await waitForChild(
  272. child,
  273. timeoutMs,
  274. [...(signal ? [signal] : []), this.disposalController.signal],
  275. overflowController.signal,
  276. );
  277. const captured = readOutput();
  278. if (result.reason === 'aborted') {
  279. return { diagnostic: runDiagnostic(handler, 'HOOK_ABORTED'), processKilled: result.killed };
  280. }
  281. if (result.reason === 'timeout') {
  282. return { diagnostic: runDiagnostic(handler, 'HOOK_TIMEOUT'), processKilled: result.killed };
  283. }
  284. if (result.reason === 'overflow' || captured.overflow) {
  285. return {
  286. diagnostic: runDiagnostic(handler, 'HOOK_INVALID_OUTPUT'),
  287. processKilled: result.killed,
  288. };
  289. }
  290. if (result.reason !== 'exit') {
  291. return { diagnostic: runDiagnostic(handler, 'HOOK_PROCESS_ERROR'), processKilled: true };
  292. }
  293. const killedDescendants = await terminateRemainingProcessGroup(child);
  294. // Codex only interprets structured stdout from a successful command.
  295. // Compatible intentionally parses JSON on every exit code; exit 2 then adds
  296. // the event-specific blocking effect which JSON cannot override.
  297. const parsesStdout =
  298. !(handler.sourceFormat === 'CODEX' && input.event === 'SessionEnd') &&
  299. (handler.sourceFormat !== 'CODEX' || result.code === 0);
  300. const parsed = parsesStdout
  301. ? parseDecision(captured.stdout, handler, input)
  302. : ({ kind: 'empty', decision: defaultDecision(input.event) } as const);
  303. const exitDecision =
  304. result.code === 2 && handler.sourceFormat !== 'MINIMAX'
  305. ? explicitExitTwoDecision(input.event, captured.stderr, handler.sourceFormat)
  306. : undefined;
  307. if (parsed.kind === 'invalid') {
  308. if (exitDecision) {
  309. return {
  310. decision: await boundHandlerDecision(handler, input, exitDecision),
  311. processKilled: killedDescendants,
  312. };
  313. }
  314. return {
  315. ...(parsed.decision
  316. ? { decision: await boundHandlerDecision(handler, input, parsed.decision) }
  317. : {}),
  318. diagnostic: runDiagnostic(handler, 'HOOK_INVALID_OUTPUT'),
  319. processKilled: killedDescendants,
  320. };
  321. }
  322. if (parsed.kind === 'structured') {
  323. const decision = exitDecision
  324. ? mergeExitTwoDecision(
  325. parsed.decision,
  326. exitDecision,
  327. input.event,
  328. handler.sourceFormat,
  329. parsed.hasStructuredBlock,
  330. )
  331. : parsed.decision;
  332. return {
  333. decision: await boundHandlerDecision(handler, input, decision),
  334. processKilled: killedDescendants,
  335. };
  336. }
  337. if (exitDecision)
  338. return {
  339. decision: await boundHandlerDecision(handler, input, exitDecision),
  340. processKilled: killedDescendants,
  341. };
  342. if (result.code !== 0) {
  343. return {
  344. diagnostic: runDiagnostic(handler, 'HOOK_PROCESS_EXITED'),
  345. processKilled: killedDescendants,
  346. };
  347. }
  348. return {
  349. decision: await boundHandlerDecision(handler, input, parsed.decision),
  350. processKilled: killedDescendants,
  351. };
  352. } finally {
  353. this.activeChildren.delete(child);
  354. }
  355. }
  356. }
  357. function safePluginDataName(pluginName: string): string {
  358. const safe = pluginName.replace(/[^A-Za-z0-9._-]/gu, '_').slice(0, 80);
  359. return safe || 'plugin';
  360. }
  361. function diagnosticOutcome(code: PluginHookRunDiagnostic['code']): 'error' | 'timeout' | 'aborted' {
  362. if (code === 'HOOK_TIMEOUT') return 'timeout';
  363. if (code === 'HOOK_ABORTED') return 'aborted';
  364. return 'error';
  365. }
  366. function eventOutcome(
  367. decision: PluginHookDecision,
  368. diagnostics: readonly PluginHookRunDiagnostic[],
  369. ): 'success' | 'deny' | 'ask' | 'degraded' | 'timeout' | 'aborted' {
  370. if (decision.decision === 'deny') return 'deny';
  371. if (decision.decision === 'ask' || decision.decision === 'defer') return 'ask';
  372. if (diagnostics.some((item) => item.code === 'HOOK_ABORTED')) return 'aborted';
  373. if (diagnostics.some((item) => item.code === 'HOOK_TIMEOUT')) return 'timeout';
  374. return diagnostics.length > 0 ? 'degraded' : 'success';
  375. }
  376. function observeHandler(
  377. observer: PluginHookObserver | undefined,
  378. input: Parameters<PluginHookObserver['onHandler']>[0],
  379. ): void {
  380. try {
  381. observer?.onHandler(input);
  382. } catch {
  383. // Observability is best-effort and must never change Hook behavior.
  384. }
  385. }
  386. function observeEvent(
  387. observer: PluginHookObserver | undefined,
  388. input: Parameters<PluginHookObserver['onEvent']>[0],
  389. ): void {
  390. try {
  391. observer?.onEvent(input);
  392. } catch {
  393. // Observability is best-effort and must never change Hook behavior.
  394. }
  395. }
  396. function collectOutput(
  397. child: ChildProcess,
  398. onOverflow: () => void,
  399. ): () => { stdout: string; stderr: string; overflow: boolean } {
  400. let stdout = Buffer.alloc(0);
  401. let stderr = Buffer.alloc(0);
  402. let overflow = false;
  403. child.stdout?.on('data', (chunk: Buffer) => {
  404. if (stdout.length + chunk.length > MAX_OUTPUT_BYTES && !overflow) {
  405. overflow = true;
  406. onOverflow();
  407. }
  408. stdout = Buffer.concat([stdout, chunk]).subarray(0, MAX_OUTPUT_BYTES);
  409. });
  410. child.stderr?.on('data', (chunk: Buffer) => {
  411. if (stderr.length + chunk.length > MAX_OUTPUT_BYTES && !overflow) {
  412. overflow = true;
  413. onOverflow();
  414. }
  415. stderr = Buffer.concat([stderr, chunk]).subarray(0, MAX_OUTPUT_BYTES);
  416. });
  417. return () => ({
  418. stdout: stdout.toString('utf8'),
  419. stderr: stderr.toString('utf8'),
  420. overflow,
  421. });
  422. }
  423. function waitForChild(
  424. child: ChildProcess,
  425. timeoutMs: number,
  426. signals: readonly AbortSignal[],
  427. overflowSignal: AbortSignal,
  428. ): Promise<
  429. | { readonly reason: 'exit'; readonly code: number; readonly killed: false }
  430. | { readonly reason: 'aborted' | 'timeout' | 'overflow'; readonly killed: true }
  431. > {
  432. return new Promise((resolve) => {
  433. let settled = false;
  434. let stopping = false;
  435. let timer: ReturnType<typeof setTimeout> | undefined;
  436. const finish = (
  437. value:
  438. | { readonly reason: 'exit'; readonly code: number; readonly killed: false }
  439. | { readonly reason: 'aborted' | 'timeout' | 'overflow'; readonly killed: true },
  440. ) => {
  441. if (settled) return;
  442. settled = true;
  443. if (timer) clearTimeout(timer);
  444. for (const signal of signals) signal.removeEventListener('abort', abort);
  445. overflowSignal.removeEventListener('abort', overflow);
  446. resolve(value);
  447. };
  448. const stop = async (reason: 'aborted' | 'timeout' | 'overflow') => {
  449. if (stopping || settled) return;
  450. stopping = true;
  451. await terminateAndDrain(child);
  452. finish({ reason, killed: true });
  453. };
  454. const abort = () => void stop('aborted');
  455. const overflow = () => void stop('overflow');
  456. timer = setTimeout(() => void stop('timeout'), timeoutMs);
  457. child.once('error', () => finish({ reason: 'exit', code: 1, killed: false }));
  458. child.once('close', (code) => {
  459. if (!stopping) finish({ reason: 'exit', code: code ?? 1, killed: false });
  460. });
  461. for (const signal of signals) signal.addEventListener('abort', abort, { once: true });
  462. overflowSignal.addEventListener('abort', overflow, { once: true });
  463. if (signals.some((signal) => signal.aborted)) abort();
  464. else if (overflowSignal.aborted) overflow();
  465. });
  466. }
  467. async function terminateAndDrain(child: ChildProcess): Promise<void> {
  468. const closed = new Promise<void>((resolve) => {
  469. if (child.exitCode !== null || child.signalCode !== null) resolve();
  470. else child.once('close', () => resolve());
  471. });
  472. try {
  473. if (process.platform === 'win32' && child.pid) {
  474. const killed = await waitBounded(runTaskkill(child.pid), PROCESS_DRAIN_BUDGET_MS, false);
  475. if (!killed) child.kill('SIGKILL');
  476. } else if (child.pid) {
  477. process.kill(-child.pid, 'SIGKILL');
  478. } else {
  479. child.kill('SIGKILL');
  480. }
  481. } catch {
  482. try {
  483. child.kill('SIGKILL');
  484. } catch {
  485. // The process may already have exited.
  486. }
  487. }
  488. await waitBounded(closed, PROCESS_DRAIN_BUDGET_MS, undefined);
  489. }
  490. async function terminateRemainingProcessGroup(child: ChildProcess): Promise<boolean> {
  491. if (!child.pid) return false;
  492. if (process.platform === 'win32') {
  493. return await waitBounded(runTaskkill(child.pid), PROCESS_DRAIN_BUDGET_MS, false);
  494. }
  495. try {
  496. process.kill(-child.pid, 'SIGKILL');
  497. return true;
  498. } catch {
  499. return false;
  500. }
  501. }
  502. async function runTaskkill(pid: number): Promise<boolean> {
  503. return new Promise<boolean>((resolve) => {
  504. const killer = spawn('taskkill', ['/pid', String(pid), '/T', '/F'], {
  505. windowsHide: true,
  506. stdio: 'ignore',
  507. });
  508. killer.once('error', () => resolve(false));
  509. killer.once('close', (code) => resolve(code === 0));
  510. });
  511. }
  512. async function waitBounded<T>(
  513. operation: Promise<T>,
  514. timeoutMs: number,
  515. timeoutValue: T,
  516. ): Promise<T> {
  517. let timer: ReturnType<typeof setTimeout> | undefined;
  518. try {
  519. return await Promise.race([
  520. operation,
  521. new Promise<T>((resolve) => {
  522. timer = setTimeout(() => resolve(timeoutValue), timeoutMs);
  523. timer.unref?.();
  524. }),
  525. ]);
  526. } finally {
  527. if (timer) clearTimeout(timer);
  528. }
  529. }
  530. type ParsedHookOutput =
  531. | {
  532. readonly kind: 'structured';
  533. readonly decision: PluginHookDecision;
  534. readonly hasStructuredBlock: boolean;
  535. }
  536. | { readonly kind: 'plain'; readonly decision: PluginHookDecision }
  537. | { readonly kind: 'empty'; readonly decision: PluginHookDecision }
  538. | { readonly kind: 'invalid'; readonly decision?: PluginHookDecision };
  539. function parseDecision(
  540. stdout: string,
  541. handler: PluginHookCommandHandler,
  542. input: PluginHookEventInput,
  543. ): ParsedHookOutput {
  544. const event = input.event;
  545. const sourceFormat = handler.sourceFormat;
  546. const output = stdout.trim();
  547. if (!output) return { kind: 'empty', decision: defaultDecision(event) };
  548. const looksLikeStructuredOutput =
  549. output.startsWith('{') || (sourceFormat === 'CODEX' && output.startsWith('['));
  550. if (!looksLikeStructuredOutput) {
  551. return {
  552. kind: 'plain',
  553. decision: supportsPlainTextContext(event, sourceFormat)
  554. ? { ...defaultDecision(event), additionalContext: output }
  555. : defaultDecision(event),
  556. };
  557. }
  558. let value: unknown;
  559. try {
  560. value = JSON.parse(output);
  561. } catch {
  562. if (sourceFormat !== 'CLAUDE') return { kind: 'invalid' };
  563. return {
  564. kind: 'plain',
  565. decision: supportsPlainTextContext(event, sourceFormat)
  566. ? { ...defaultDecision(event), additionalContext: output }
  567. : defaultDecision(event),
  568. };
  569. }
  570. if (!isRecord(value) || !isSafeHookOutputValue(value)) return { kind: 'invalid' };
  571. const decision = parseWireDecision(value, handler, input);
  572. if (decision) {
  573. return {
  574. kind: 'structured',
  575. decision,
  576. hasStructuredBlock: value.decision === 'block' || decision.continue === false,
  577. };
  578. }
  579. const warning = codexUnsupportedControlSystemWarning(value, handler, input);
  580. return warning ? { kind: 'invalid', decision: warning } : { kind: 'invalid' };
  581. }
  582. function parseWireDecision(
  583. value: Record<string, unknown>,
  584. handler: PluginHookCommandHandler,
  585. input: PluginHookEventInput,
  586. ): PluginHookDecision | undefined {
  587. const event = input.event;
  588. const sourceFormat = handler.sourceFormat;
  589. const allowed = allowedWireOutputKeys(event, sourceFormat);
  590. if (Object.keys(value).some((key) => !allowed.has(key))) return undefined;
  591. const universal = parseUniversalOutput(value, event, sourceFormat);
  592. if (!universal) return undefined;
  593. const specificValue = value.hookSpecificOutput;
  594. if (specificValue !== undefined && !isRecord(specificValue)) return undefined;
  595. const specific = isRecord(specificValue) ? specificValue : undefined;
  596. if (specific && specific.hookEventName !== event) return undefined;
  597. const base: PluginHookDecision = { ...defaultDecision(event), ...universal };
  598. if (base.continue === false && !(event === 'PostToolUse' && sourceFormat === 'CODEX')) {
  599. return base;
  600. }
  601. if (event === 'PermissionRequest') {
  602. return parsePermissionRequestOutput(base, specific, handler, input);
  603. }
  604. if (event === 'PreToolUse') {
  605. return parsePreToolUseOutput(base, value, specific, handler, input);
  606. }
  607. const additionalContext = readAdditionalContext(specific);
  608. if (
  609. specific &&
  610. event !== 'PostToolUse' &&
  611. Object.keys(specific).some(
  612. (key) =>
  613. key !== 'hookEventName' &&
  614. key !== 'additionalContext' &&
  615. !isIgnoredCompatibleHookSpecificOutputKey(sourceFormat, event, key),
  616. )
  617. )
  618. return undefined;
  619. if (specific?.additionalContext !== undefined && additionalContext === undefined)
  620. return undefined;
  621. if (event === 'PostToolUse') {
  622. return parsePostToolUseOutput(base, value, specific, handler, input, additionalContext);
  623. }
  624. const topDecision = value.decision;
  625. const reason = readReason(value.reason);
  626. if (value.reason !== undefined && reason === undefined) return undefined;
  627. if (topDecision !== undefined && topDecision !== 'block') return undefined;
  628. if (topDecision === 'block' && !reason) return undefined;
  629. if (topDecision === 'block') {
  630. if (event === 'UserPromptSubmit') {
  631. return { ...base, decision: 'deny', reason };
  632. }
  633. if (event === 'Stop' || event === 'SubagentStop') {
  634. return {
  635. ...base,
  636. continuePrompt: mergePluginHookContext(reason, additionalContext),
  637. };
  638. }
  639. if (event === 'PreCompact' && sourceFormat !== 'CODEX') {
  640. return { ...base, defer: true, reason };
  641. }
  642. return undefined;
  643. }
  644. if (reason !== undefined) return undefined;
  645. if (additionalContext) {
  646. if (
  647. event !== 'SessionStart' &&
  648. event !== 'SubagentStart' &&
  649. event !== 'UserPromptSubmit' &&
  650. event !== 'Stop' &&
  651. event !== 'SubagentStop'
  652. )
  653. return undefined;
  654. if (event === 'Stop' || event === 'SubagentStop') {
  655. return { ...base, continuePrompt: additionalContext };
  656. }
  657. return { ...base, additionalContext };
  658. }
  659. return base;
  660. }
  661. function explicitExitTwoDecision(
  662. event: PluginHookEventInput['event'],
  663. stderr: string,
  664. sourceFormat: PluginHookCommandHandler['sourceFormat'],
  665. ): PluginHookDecision | undefined {
  666. const providedReason = readReason(stderr);
  667. if (sourceFormat === 'CODEX' && !providedReason) return undefined;
  668. const reason = providedReason ?? 'Plugin Hook blocked this operation.';
  669. if (event === 'UserPromptSubmit' || event === 'PreToolUse') {
  670. return { decision: 'deny', reason };
  671. }
  672. if (event === 'PermissionRequest' && sourceFormat === 'CODEX') {
  673. return { decision: 'deny', permissionDecision: 'deny', reason };
  674. }
  675. if (event === 'PostToolUse') {
  676. return sourceFormat === 'CODEX'
  677. ? { decision: 'allow', postToolFeedback: reason }
  678. : { decision: 'allow', additionalContext: reason };
  679. }
  680. if (event === 'Stop' || event === 'SubagentStop') {
  681. return { decision: 'allow', continuePrompt: reason };
  682. }
  683. if (event === 'PreCompact' && sourceFormat === 'CLAUDE') {
  684. return { decision: 'allow', defer: true, reason };
  685. }
  686. return undefined;
  687. }
  688. function mergeExitTwoDecision(
  689. parsed: PluginHookDecision,
  690. exitDecision: PluginHookDecision,
  691. event: PluginHookEventInput['event'],
  692. sourceFormat: PluginHookCommandHandler['sourceFormat'],
  693. hasStructuredBlock: boolean,
  694. ): PluginHookDecision {
  695. if (event === 'PermissionRequest' && sourceFormat === 'CLAUDE') return parsed;
  696. if (sourceFormat === 'CLAUDE' && hasStructuredBlock) {
  697. // Compatible keeps exit-code 2 blocking, but a structured blocking reason wins
  698. // over stderr. `parsed` already carries the event-specific blocking effect.
  699. return parsed;
  700. }
  701. if (event === 'PostToolUse' && sourceFormat === 'CODEX') {
  702. const nonStoppingParsed = withoutStoppingControls(parsed);
  703. return {
  704. ...nonStoppingParsed,
  705. postToolFeedback: mergePluginHookContext(
  706. parsed.postToolFeedback,
  707. exitDecision.postToolFeedback,
  708. ),
  709. };
  710. }
  711. return mergePluginHookDecisions(parsed, exitDecision);
  712. }
  713. function parsePermissionRequestOutput(
  714. base: PluginHookDecision,
  715. specific: Record<string, unknown> | undefined,
  716. handler: PluginHookCommandHandler,
  717. input: PluginHookEventInput,
  718. ): PluginHookDecision | undefined {
  719. const sourceFormat = handler.sourceFormat;
  720. if (!specific) return base;
  721. if (Object.keys(specific).some((key) => key !== 'hookEventName' && key !== 'decision')) {
  722. return undefined;
  723. }
  724. if (specific.decision === undefined) return base;
  725. if (!isRecord(specific.decision)) return undefined;
  726. const decision = specific.decision;
  727. const allowed = new Set([
  728. 'behavior',
  729. 'updatedInput',
  730. 'updatedPermissions',
  731. 'message',
  732. 'interrupt',
  733. ]);
  734. if (Object.keys(decision).some((key) => !allowed.has(key))) return undefined;
  735. if (decision.behavior !== 'allow' && decision.behavior !== 'deny') return undefined;
  736. if (decision.message !== undefined && typeof decision.message !== 'string') return undefined;
  737. if (decision.interrupt !== undefined && typeof decision.interrupt !== 'boolean') return undefined;
  738. if (decision.updatedInput !== undefined && !isRecord(decision.updatedInput)) return undefined;
  739. const restoredUpdatedInput = isRecord(decision.updatedInput)
  740. ? restoreNativeToolInput(decision.updatedInput, handler, input)
  741. : undefined;
  742. if (decision.updatedInput !== undefined && restoredUpdatedInput === undefined) return undefined;
  743. if (decision.updatedPermissions !== undefined && !Array.isArray(decision.updatedPermissions)) {
  744. return undefined;
  745. }
  746. if (
  747. sourceFormat === 'CODEX' &&
  748. (decision.updatedInput !== undefined ||
  749. decision.updatedPermissions !== undefined ||
  750. decision.interrupt === true)
  751. )
  752. return undefined;
  753. if (sourceFormat === 'MINIMAX' && decision.updatedPermissions !== undefined) return undefined;
  754. const updatedPermissions =
  755. sourceFormat === 'CLAUDE' && Array.isArray(decision.updatedPermissions)
  756. ? parseCompatiblePermissionUpdates(decision.updatedPermissions, handler, input)
  757. : undefined;
  758. if (sourceFormat === 'CLAUDE' && decision.updatedPermissions !== undefined && !updatedPermissions)
  759. return undefined;
  760. if (decision.behavior === 'allow') {
  761. if (sourceFormat === 'CLAUDE' && decision.message !== undefined) return undefined;
  762. if (decision.interrupt === true) return undefined;
  763. return {
  764. ...base,
  765. permissionDecision: 'allow',
  766. permissionAutoApproval: sourceFormat === 'CODEX' ? 'any_prompt' : 'ordinary_only',
  767. ...(restoredUpdatedInput ? { updatedInput: restoredUpdatedInput } : {}),
  768. ...(updatedPermissions?.length ? { updatedPermissions } : {}),
  769. };
  770. }
  771. if (decision.updatedInput !== undefined || decision.updatedPermissions !== undefined) {
  772. return undefined;
  773. }
  774. const reason = readReason(decision.message) ?? 'PermissionRequest Hook denied approval.';
  775. return {
  776. ...base,
  777. decision: 'deny',
  778. permissionDecision: 'deny',
  779. reason,
  780. ...(decision.interrupt === true
  781. ? { interrupt: true, continue: false, stopReason: reason }
  782. : {}),
  783. };
  784. }
  785. function parseCompatiblePermissionUpdates(
  786. values: readonly unknown[],
  787. handler: PluginHookCommandHandler,
  788. input: PluginHookEventInput,
  789. ): readonly PluginHookPermissionUpdate[] | undefined {
  790. const parsed: PluginHookPermissionUpdate[] = [];
  791. for (const value of values) {
  792. if (!isRecord(value) || typeof value.type !== 'string') return undefined;
  793. const destination = readPermissionUpdateDestination(value.destination);
  794. if (!destination) return undefined;
  795. if (
  796. value.type === 'addRules' ||
  797. value.type === 'replaceRules' ||
  798. value.type === 'removeRules'
  799. ) {
  800. if (!hasOnlyKeys(value, ['type', 'rules', 'behavior', 'destination'])) return undefined;
  801. if (value.behavior !== 'allow' && value.behavior !== 'deny' && value.behavior !== 'ask') {
  802. return undefined;
  803. }
  804. if (!Array.isArray(value.rules)) return undefined;
  805. const rules = value.rules.map((rule) => parseCompatiblePermissionRule(rule, handler, input));
  806. if (rules.some((rule) => rule === undefined)) return undefined;
  807. parsed.push({
  808. type: value.type,
  809. rules: rules as PluginHookPermissionRuleValue[],
  810. behavior: value.behavior,
  811. destination,
  812. });
  813. continue;
  814. }
  815. if (value.type === 'setMode') {
  816. if (!hasOnlyKeys(value, ['type', 'mode', 'destination'])) return undefined;
  817. const mode = readPermissionUpdateMode(value.mode);
  818. if (!mode) return undefined;
  819. parsed.push({ type: 'setMode', mode, destination });
  820. continue;
  821. }
  822. if (value.type === 'addDirectories' || value.type === 'removeDirectories') {
  823. if (!hasOnlyKeys(value, ['type', 'directories', 'destination'])) return undefined;
  824. if (
  825. !Array.isArray(value.directories) ||
  826. value.directories.some(
  827. (directory) =>
  828. typeof directory !== 'string' ||
  829. !directory.trim() ||
  830. directory.includes('\u0000') ||
  831. directory.length > 16_384,
  832. )
  833. ) {
  834. return undefined;
  835. }
  836. parsed.push({
  837. type: value.type,
  838. directories: value.directories.map((directory) =>
  839. resolveHookFilePath(directory.trim(), input.cwd),
  840. ),
  841. destination,
  842. });
  843. continue;
  844. }
  845. return undefined;
  846. }
  847. return parsed;
  848. }
  849. function parseCompatiblePermissionRule(
  850. value: unknown,
  851. handler: PluginHookCommandHandler,
  852. input: PluginHookEventInput,
  853. ): PluginHookPermissionRuleValue | undefined {
  854. if (!isRecord(value) || !hasOnlyKeys(value, ['toolName', 'ruleContent'])) return undefined;
  855. if (typeof value.toolName !== 'string' || !value.toolName.trim()) return undefined;
  856. if (
  857. value.ruleContent !== undefined &&
  858. (typeof value.ruleContent !== 'string' || value.ruleContent.length > 64 * 1024)
  859. ) {
  860. return undefined;
  861. }
  862. const toolName = restoreNativePermissionRuleToolName(value.toolName.trim(), handler, input);
  863. return {
  864. toolName,
  865. ...(value.ruleContent !== undefined ? { ruleContent: value.ruleContent } : {}),
  866. };
  867. }
  868. function restoreNativePermissionRuleToolName(
  869. value: string,
  870. handler: PluginHookCommandHandler,
  871. input: PluginHookEventInput,
  872. ): string {
  873. if (value === 'Bash' || value === 'PowerShell') return 'bash';
  874. if (value === 'Read') return 'read';
  875. if (value === 'Write') return 'write';
  876. if (value === 'Edit') return 'edit';
  877. if (value === 'Agent') return 'task';
  878. const prefix = `mcp__plugin_${handler.pluginName}_`;
  879. if (value.startsWith(prefix)) return `mcp__${value.slice(prefix.length)}`;
  880. const currentNativeName =
  881. typeof input.payload?.tool_name === 'string' ? input.payload.tool_name : input.matcherValue;
  882. const currentVendorName = adaptToolIdentity(
  883. handler,
  884. input.event,
  885. input.payload ?? {},
  886. input.matcherValue,
  887. input.toolProvenance,
  888. input.cwd,
  889. ).toolName;
  890. return value === currentVendorName && currentNativeName ? currentNativeName : value;
  891. }
  892. function readPermissionUpdateDestination(
  893. value: unknown,
  894. ): PluginHookPermissionUpdateDestination | undefined {
  895. return value === 'session' ||
  896. value === 'localSettings' ||
  897. value === 'projectSettings' ||
  898. value === 'userSettings'
  899. ? value
  900. : undefined;
  901. }
  902. function readPermissionUpdateMode(value: unknown): PluginHookPermissionUpdateMode | undefined {
  903. if (value === 'manual') return 'default';
  904. return value === 'default' ||
  905. value === 'auto' ||
  906. value === 'acceptEdits' ||
  907. value === 'dontAsk' ||
  908. value === 'bypassPermissions' ||
  909. value === 'plan'
  910. ? value
  911. : undefined;
  912. }
  913. function parsePreToolUseOutput(
  914. base: PluginHookDecision,
  915. value: Record<string, unknown>,
  916. specific: Record<string, unknown> | undefined,
  917. handler: PluginHookCommandHandler,
  918. input: PluginHookEventInput,
  919. ): PluginHookDecision | undefined {
  920. const sourceFormat = handler.sourceFormat;
  921. const additionalContext = readAdditionalContext(specific);
  922. if (specific?.additionalContext !== undefined && additionalContext === undefined)
  923. return undefined;
  924. const legacyDecision = value.decision;
  925. const legacyReason = readReason(value.reason);
  926. if (value.reason !== undefined && legacyReason === undefined) return undefined;
  927. const hasSpecificDecision =
  928. specific?.permissionDecision !== undefined ||
  929. specific?.permissionDecisionReason !== undefined ||
  930. specific?.updatedInput !== undefined;
  931. if (!hasSpecificDecision && legacyDecision !== undefined) {
  932. const allowedLegacy = ['approve', 'block'];
  933. if (!allowedLegacy.includes(String(legacyDecision))) return undefined;
  934. if (legacyDecision === 'block') {
  935. return legacyReason
  936. ? {
  937. ...base,
  938. decision: 'deny',
  939. reason: legacyReason,
  940. ...(additionalContext ? { additionalContext } : {}),
  941. }
  942. : undefined;
  943. }
  944. if (legacyReason !== undefined || sourceFormat === 'CODEX') return undefined;
  945. return { ...base, toolPermissionDecision: 'allow' };
  946. }
  947. if (!hasSpecificDecision && legacyReason !== undefined) return undefined;
  948. if (!specific) return base;
  949. const allowed = new Set([
  950. 'hookEventName',
  951. 'permissionDecision',
  952. 'permissionDecisionReason',
  953. 'updatedInput',
  954. 'additionalContext',
  955. ]);
  956. if (Object.keys(specific).some((key) => !allowed.has(key))) return undefined;
  957. const permission = specific.permissionDecision;
  958. const supported =
  959. sourceFormat === 'CODEX' ? ['allow', 'deny'] : ['allow', 'deny', 'ask', 'defer'];
  960. if (permission !== undefined && !supported.includes(String(permission))) return undefined;
  961. const reason = readReason(specific.permissionDecisionReason);
  962. if (specific.permissionDecisionReason !== undefined && reason === undefined) return undefined;
  963. if (permission === undefined && reason !== undefined) return undefined;
  964. if (specific.updatedInput !== undefined && !isRecord(specific.updatedInput)) return undefined;
  965. const restoredUpdatedInput = isRecord(specific.updatedInput)
  966. ? restoreNativeToolInput(specific.updatedInput, handler, input)
  967. : undefined;
  968. if (specific.updatedInput !== undefined && restoredUpdatedInput === undefined) return undefined;
  969. if (sourceFormat === 'CODEX') {
  970. if (permission === 'allow' && specific.updatedInput === undefined) return undefined;
  971. if (permission === 'deny' && !reason) return undefined;
  972. if (specific.updatedInput !== undefined && permission !== 'allow') return undefined;
  973. }
  974. if (permission === 'defer') {
  975. return { ...base, decision: 'defer', toolPermissionDecision: 'defer' };
  976. }
  977. if (permission === 'deny') {
  978. return {
  979. ...base,
  980. decision: 'deny',
  981. ...(sourceFormat === 'CODEX' ? {} : { toolPermissionDecision: 'deny' as const }),
  982. ...(reason ? { reason } : {}),
  983. ...(additionalContext ? { additionalContext } : {}),
  984. };
  985. }
  986. if (permission === 'ask') {
  987. return {
  988. ...base,
  989. decision: 'ask',
  990. toolPermissionDecision: 'ask',
  991. ...(reason ? { reason } : {}),
  992. ...(restoredUpdatedInput ? { updatedInput: restoredUpdatedInput } : {}),
  993. ...(additionalContext ? { additionalContext } : {}),
  994. };
  995. }
  996. return {
  997. ...base,
  998. ...(permission === 'allow' && sourceFormat !== 'CODEX'
  999. ? { toolPermissionDecision: 'allow' as const }
  1000. : {}),
  1001. ...(reason ? { reason } : {}),
  1002. ...(restoredUpdatedInput ? { updatedInput: restoredUpdatedInput } : {}),
  1003. ...(additionalContext ? { additionalContext } : {}),
  1004. };
  1005. }
  1006. function parsePostToolUseOutput(
  1007. base: PluginHookDecision,
  1008. value: Record<string, unknown>,
  1009. specific: Record<string, unknown> | undefined,
  1010. handler: PluginHookCommandHandler,
  1011. input: PluginHookEventInput,
  1012. additionalContext: string | undefined,
  1013. ): PluginHookDecision | undefined {
  1014. const sourceFormat = handler.sourceFormat;
  1015. if (specific) {
  1016. const allowed =
  1017. sourceFormat === 'CLAUDE'
  1018. ? new Set([
  1019. 'hookEventName',
  1020. 'additionalContext',
  1021. 'classifierContext',
  1022. 'updatedToolOutput',
  1023. 'updatedMCPToolOutput',
  1024. ])
  1025. : new Set(['hookEventName', 'additionalContext']);
  1026. if (Object.keys(specific).some((key) => !allowed.has(key))) return undefined;
  1027. }
  1028. const topDecision = value.decision;
  1029. const reason = readReason(value.reason);
  1030. if (value.reason !== undefined && reason === undefined) return undefined;
  1031. if (topDecision !== undefined && topDecision !== 'block') return undefined;
  1032. if (topDecision === 'block' && !reason) return undefined;
  1033. if (topDecision === undefined && reason !== undefined) return undefined;
  1034. const updatedMcpOutput = specific?.updatedMCPToolOutput;
  1035. if (updatedMcpOutput !== undefined && !isMcpToolInput(input)) return undefined;
  1036. if (
  1037. sourceFormat === 'CLAUDE' &&
  1038. specific?.updatedToolOutput !== undefined &&
  1039. !isMcpToolInput(input) &&
  1040. !hasCompatibleJsonShape(input.payload?.compatible_tool_response, specific.updatedToolOutput)
  1041. )
  1042. return undefined;
  1043. const replacement =
  1044. sourceFormat === 'CLAUDE'
  1045. ? firstDefined(specific?.updatedToolOutput, updatedMcpOutput)
  1046. : undefined;
  1047. if (sourceFormat === 'CODEX' && base.continue === false) {
  1048. const stopReason = base.stopReason;
  1049. const nonStoppingBase = withoutStoppingControls(base);
  1050. return {
  1051. ...nonStoppingBase,
  1052. ...(additionalContext ? { additionalContext } : {}),
  1053. postToolFeedback: reason ?? stopReason ?? 'PostToolUse Hook stopped normal processing.',
  1054. };
  1055. }
  1056. if (topDecision === 'block' && reason) {
  1057. return sourceFormat === 'CODEX'
  1058. ? {
  1059. ...base,
  1060. postToolFeedback: reason,
  1061. ...(additionalContext ? { additionalContext } : {}),
  1062. }
  1063. : {
  1064. ...base,
  1065. additionalContext: mergePluginHookContext(additionalContext, reason),
  1066. ...(replacement !== undefined
  1067. ? { updatedResult: replacement, updatedResultFormat: 'CLAUDE' as const }
  1068. : {}),
  1069. };
  1070. }
  1071. return {
  1072. ...base,
  1073. ...(additionalContext ? { additionalContext } : {}),
  1074. ...(replacement !== undefined
  1075. ? { updatedResult: replacement, updatedResultFormat: 'CLAUDE' as const }
  1076. : {}),
  1077. };
  1078. }
  1079. function withoutStoppingControls(decision: PluginHookDecision): PluginHookDecision {
  1080. const result = { ...decision };
  1081. delete result.continue;
  1082. delete result.stopReason;
  1083. return result;
  1084. }
  1085. function parseUniversalOutput(
  1086. value: Record<string, unknown>,
  1087. event: PluginHookEventInput['event'],
  1088. sourceFormat: PluginHookCommandHandler['sourceFormat'],
  1089. ): Omit<PluginHookDecision, 'decision'> | undefined {
  1090. if (value.continue !== undefined && typeof value.continue !== 'boolean') return undefined;
  1091. if (value.stopReason !== undefined && typeof value.stopReason !== 'string') return undefined;
  1092. if (value.suppressOutput !== undefined && typeof value.suppressOutput !== 'boolean')
  1093. return undefined;
  1094. if (value.systemMessage !== undefined && typeof value.systemMessage !== 'string')
  1095. return undefined;
  1096. // Compatible treats terminalSequence as an independent, best-effort side effect.
  1097. // A malformed sequence must not invalidate an otherwise valid policy decision.
  1098. const terminalSequence =
  1099. sourceFormat === 'CLAUDE' &&
  1100. typeof value.terminalSequence === 'string' &&
  1101. isAllowedPluginHookTerminalSequence(value.terminalSequence)
  1102. ? value.terminalSequence
  1103. : undefined;
  1104. if (sourceFormat === 'CLAUDE' && (event === 'PreCompact' || event === 'PostCompact')) {
  1105. return terminalSequence ? { terminalSequence } : {};
  1106. }
  1107. if ((sourceFormat === 'CLAUDE' || sourceFormat === 'CODEX') && event === 'SessionEnd') {
  1108. return terminalSequence ? { terminalSequence } : {};
  1109. }
  1110. if (sourceFormat === 'CODEX') {
  1111. if (
  1112. (event === 'PreToolUse' || event === 'PermissionRequest') &&
  1113. (value.continue === false || value.stopReason !== undefined)
  1114. )
  1115. return undefined;
  1116. if (
  1117. (event === 'PreToolUse' || event === 'PermissionRequest' || event === 'PostToolUse') &&
  1118. value.suppressOutput === true
  1119. )
  1120. return undefined;
  1121. }
  1122. const discardContinue =
  1123. (sourceFormat === 'CODEX' && event === 'SubagentStart') ||
  1124. (sourceFormat === 'CODEX' && event === 'SessionEnd') ||
  1125. (sourceFormat === 'CLAUDE' &&
  1126. (event === 'SessionStart' ||
  1127. event === 'SubagentStart' ||
  1128. event === 'PostCompact' ||
  1129. event === 'SessionEnd'));
  1130. return {
  1131. ...(!discardContinue && value.continue === false ? { continue: false } : {}),
  1132. ...(!discardContinue && value.continue === false && typeof value.stopReason === 'string'
  1133. ? { stopReason: boundedReason(value.stopReason) }
  1134. : {}),
  1135. ...(value.suppressOutput === true ? { suppressOutput: true } : {}),
  1136. ...(typeof value.systemMessage === 'string' ? { systemMessage: value.systemMessage } : {}),
  1137. ...(terminalSequence ? { terminalSequence } : {}),
  1138. };
  1139. }
  1140. /** Compatible permits bare BEL and OSC 0/1/2/9/99/777 terminated by BEL or ST. */
  1141. export function isAllowedPluginHookTerminalSequence(value: string): boolean {
  1142. if (!value || value.length > 10_000) return false;
  1143. let offset = 0;
  1144. while (offset < value.length) {
  1145. if (value.charCodeAt(offset) === 0x07) {
  1146. offset += 1;
  1147. continue;
  1148. }
  1149. if (value.charCodeAt(offset) !== 0x1b || value[offset + 1] !== ']') return false;
  1150. const belTerminator = value.indexOf('\u0007', offset + 2);
  1151. const stTerminator = value.indexOf('\u001b\\', offset + 2);
  1152. const terminator =
  1153. belTerminator < 0
  1154. ? stTerminator
  1155. : stTerminator < 0
  1156. ? belTerminator
  1157. : Math.min(belTerminator, stTerminator);
  1158. if (terminator < 0) return false;
  1159. const payload = value.slice(offset + 2, terminator);
  1160. if (containsTerminalControlCharacter(payload)) return false;
  1161. const separator = payload.indexOf(';');
  1162. const command = separator < 0 ? payload : payload.slice(0, separator);
  1163. if (!new Set(['0', '1', '2', '9', '99', '777']).has(command)) return false;
  1164. offset = terminator + (terminator === stTerminator ? 2 : 1);
  1165. }
  1166. return true;
  1167. }
  1168. function containsTerminalControlCharacter(value: string): boolean {
  1169. for (const character of value) {
  1170. const code = character.codePointAt(0) ?? 0;
  1171. if (code <= 0x1f || code === 0x7f || (code >= 0x80 && code <= 0x9f)) return true;
  1172. }
  1173. return false;
  1174. }
  1175. /**
  1176. * Codex parses a schema-valid warning before it rejects a recognized but unsupported control.
  1177. * Keep that warning, while leaving unknown or malformed wire shapes fully invalid.
  1178. */
  1179. function codexUnsupportedControlSystemWarning(
  1180. value: Record<string, unknown>,
  1181. handler: PluginHookCommandHandler,
  1182. input: PluginHookEventInput,
  1183. ): PluginHookDecision | undefined {
  1184. if (handler.sourceFormat !== 'CODEX' || typeof value.systemMessage !== 'string') return undefined;
  1185. if (
  1186. input.event !== 'PreToolUse' &&
  1187. input.event !== 'PermissionRequest' &&
  1188. input.event !== 'PostToolUse'
  1189. ) {
  1190. return undefined;
  1191. }
  1192. if (!isSchemaValidCodexControlOutput(value, input.event)) return undefined;
  1193. if (!hasUnsupportedCodexControl(value, input.event)) return undefined;
  1194. return { ...defaultDecision(input.event), systemMessage: value.systemMessage };
  1195. }
  1196. function isSchemaValidCodexControlOutput(
  1197. value: Record<string, unknown>,
  1198. event: 'PreToolUse' | 'PermissionRequest' | 'PostToolUse',
  1199. ): boolean {
  1200. if (Object.keys(value).some((key) => !allowedWireOutputKeys(event, 'CODEX').has(key))) {
  1201. return false;
  1202. }
  1203. if (value.continue !== undefined && typeof value.continue !== 'boolean') return false;
  1204. if (!isOptionalString(value.stopReason)) return false;
  1205. if (value.suppressOutput !== undefined && typeof value.suppressOutput !== 'boolean') return false;
  1206. if (!isOptionalString(value.systemMessage)) return false;
  1207. if (value.hookSpecificOutput !== undefined && value.hookSpecificOutput !== null) {
  1208. if (!isRecord(value.hookSpecificOutput)) return false;
  1209. const specific = value.hookSpecificOutput;
  1210. if (specific.hookEventName !== event) return false;
  1211. if (event === 'PreToolUse') {
  1212. if (
  1213. !hasOnlyKeys(specific, [
  1214. 'hookEventName',
  1215. 'additionalContext',
  1216. 'permissionDecision',
  1217. 'permissionDecisionReason',
  1218. 'updatedInput',
  1219. ])
  1220. ) {
  1221. return false;
  1222. }
  1223. if (!isOptionalString(specific.additionalContext)) return false;
  1224. if (!isOptionalString(specific.permissionDecisionReason)) return false;
  1225. if (
  1226. specific.permissionDecision !== undefined &&
  1227. specific.permissionDecision !== null &&
  1228. specific.permissionDecision !== 'allow' &&
  1229. specific.permissionDecision !== 'deny' &&
  1230. specific.permissionDecision !== 'ask'
  1231. ) {
  1232. return false;
  1233. }
  1234. } else if (event === 'PermissionRequest') {
  1235. if (!hasOnlyKeys(specific, ['hookEventName', 'decision'])) return false;
  1236. if (specific.decision !== undefined && specific.decision !== null) {
  1237. if (!isRecord(specific.decision)) return false;
  1238. const decision = specific.decision;
  1239. if (
  1240. !hasOnlyKeys(decision, [
  1241. 'behavior',
  1242. 'updatedInput',
  1243. 'updatedPermissions',
  1244. 'message',
  1245. 'interrupt',
  1246. ])
  1247. ) {
  1248. return false;
  1249. }
  1250. if (decision.behavior !== 'allow' && decision.behavior !== 'deny') return false;
  1251. if (!isOptionalString(decision.message)) return false;
  1252. if (decision.interrupt !== undefined && typeof decision.interrupt !== 'boolean')
  1253. return false;
  1254. }
  1255. } else {
  1256. if (!hasOnlyKeys(specific, ['hookEventName', 'additionalContext', 'updatedMCPToolOutput'])) {
  1257. return false;
  1258. }
  1259. if (!isOptionalString(specific.additionalContext)) return false;
  1260. }
  1261. }
  1262. if (event === 'PermissionRequest') return true;
  1263. if (value.decision !== undefined && value.decision !== null) {
  1264. if (event === 'PreToolUse') {
  1265. if (value.decision !== 'approve' && value.decision !== 'block') return false;
  1266. } else if (value.decision !== 'block') {
  1267. return false;
  1268. }
  1269. }
  1270. return isOptionalString(value.reason);
  1271. }
  1272. function hasUnsupportedCodexControl(
  1273. value: Record<string, unknown>,
  1274. event: 'PreToolUse' | 'PermissionRequest' | 'PostToolUse',
  1275. ): boolean {
  1276. if (event !== 'PostToolUse' && (value.continue === false || hasNonNullValue(value.stopReason))) {
  1277. return true;
  1278. }
  1279. if (value.suppressOutput === true) return true;
  1280. const specific = isRecord(value.hookSpecificOutput) ? value.hookSpecificOutput : undefined;
  1281. if (event === 'PermissionRequest') {
  1282. const decision = isRecord(specific?.decision) ? specific.decision : undefined;
  1283. return Boolean(
  1284. decision &&
  1285. (hasNonNullValue(decision.updatedInput) ||
  1286. hasNonNullValue(decision.updatedPermissions) ||
  1287. decision.interrupt === true),
  1288. );
  1289. }
  1290. if (event === 'PostToolUse') {
  1291. return Boolean(specific && hasNonNullValue(specific.updatedMCPToolOutput));
  1292. }
  1293. const permissionDecision = specific?.permissionDecision;
  1294. const permissionReason = specific?.permissionDecisionReason;
  1295. const updatedInputPresent = hasNonNullValue(specific?.updatedInput);
  1296. const usesSpecificDecision =
  1297. hasNonNullValue(permissionDecision) || hasNonNullValue(permissionReason) || updatedInputPresent;
  1298. if (usesSpecificDecision) {
  1299. if (updatedInputPresent && permissionDecision !== 'allow') return true;
  1300. if (permissionDecision === 'allow') return !updatedInputPresent;
  1301. if (permissionDecision === 'ask') return true;
  1302. if (permissionDecision === 'deny') {
  1303. return typeof permissionReason !== 'string' || !permissionReason.trim();
  1304. }
  1305. return hasNonNullValue(permissionReason);
  1306. }
  1307. if (value.decision === 'approve') return true;
  1308. if (value.decision === 'block') {
  1309. return typeof value.reason !== 'string' || !value.reason.trim();
  1310. }
  1311. return hasNonNullValue(value.reason);
  1312. }
  1313. function isOptionalString(value: unknown): boolean {
  1314. return value === undefined || value === null || typeof value === 'string';
  1315. }
  1316. function hasNonNullValue(value: unknown): boolean {
  1317. return value !== undefined && value !== null;
  1318. }
  1319. function allowedWireOutputKeys(
  1320. event: PluginHookEventInput['event'],
  1321. sourceFormat: PluginHookCommandHandler['sourceFormat'],
  1322. ): ReadonlySet<string> {
  1323. const common = [
  1324. 'continue',
  1325. 'stopReason',
  1326. 'suppressOutput',
  1327. 'systemMessage',
  1328. ...(sourceFormat === 'CLAUDE' ? ['terminalSequence'] : []),
  1329. ];
  1330. switch (event) {
  1331. case 'SessionStart':
  1332. case 'SubagentStart':
  1333. return new Set([...common, 'hookSpecificOutput']);
  1334. case 'UserPromptSubmit':
  1335. return new Set([...common, 'decision', 'reason', 'hookSpecificOutput']);
  1336. case 'PreToolUse':
  1337. return new Set([...common, 'decision', 'reason', 'hookSpecificOutput']);
  1338. case 'PermissionRequest':
  1339. return new Set([...common, 'hookSpecificOutput']);
  1340. case 'PostToolUse':
  1341. return new Set([...common, 'decision', 'reason', 'hookSpecificOutput']);
  1342. case 'Stop':
  1343. case 'SubagentStop':
  1344. return new Set([
  1345. ...common,
  1346. 'decision',
  1347. 'reason',
  1348. ...(sourceFormat === 'CLAUDE' || sourceFormat === 'MINIMAX' ? ['hookSpecificOutput'] : []),
  1349. ]);
  1350. case 'PreCompact':
  1351. return new Set([...common, ...(sourceFormat === 'CODEX' ? [] : ['decision', 'reason'])]);
  1352. case 'PostCompact':
  1353. case 'SessionEnd':
  1354. return new Set(common);
  1355. }
  1356. }
  1357. function readAdditionalContext(value: Record<string, unknown> | undefined): string | undefined {
  1358. if (!value || value.additionalContext === undefined) return undefined;
  1359. return typeof value.additionalContext === 'string' ? value.additionalContext : undefined;
  1360. }
  1361. function isIgnoredCompatibleHookSpecificOutputKey(
  1362. sourceFormat: PluginHookCommandHandler['sourceFormat'],
  1363. event: PluginHookEventInput['event'],
  1364. key: string,
  1365. ): boolean {
  1366. if (sourceFormat !== 'CLAUDE') return false;
  1367. if (event === 'SessionStart') {
  1368. return ['initialUserMessage', 'sessionTitle', 'watchPaths', 'reloadSkills'].includes(key);
  1369. }
  1370. return event === 'UserPromptSubmit' && ['sessionTitle', 'suppressOriginalPrompt'].includes(key);
  1371. }
  1372. function readReason(value: unknown): string | undefined {
  1373. return typeof value === 'string' && value.trim() ? value.trim() : undefined;
  1374. }
  1375. function isCodexWinningReason(
  1376. event: PluginHookEventInput['event'],
  1377. decision: PluginHookDecision,
  1378. ): boolean {
  1379. if (!decision.reason) return false;
  1380. if (event === 'PermissionRequest') return decision.permissionDecision === 'deny';
  1381. return event === 'PreToolUse' && decision.decision === 'deny';
  1382. }
  1383. function supportsPlainTextContext(
  1384. event: PluginHookEventInput['event'],
  1385. sourceFormat: PluginHookCommandHandler['sourceFormat'],
  1386. ): boolean {
  1387. if (event === 'SessionStart' || event === 'UserPromptSubmit') return true;
  1388. return sourceFormat === 'CODEX' && event === 'SubagentStart';
  1389. }
  1390. function defaultDecision(event: PluginHookEventInput['event']): PluginHookDecision {
  1391. return event === 'PermissionRequest'
  1392. ? { decision: 'allow', permissionDecision: 'abstain' }
  1393. : event === 'PreToolUse'
  1394. ? { decision: 'allow', toolPermissionDecision: 'abstain' }
  1395. : { decision: 'allow' };
  1396. }
  1397. function firstDefined(...values: readonly unknown[]): unknown {
  1398. return values.find((value) => value !== undefined);
  1399. }
  1400. export function mergePluginHookDecisions(
  1401. current: PluginHookDecision,
  1402. next: PluginHookDecision,
  1403. ): PluginHookDecision {
  1404. const decision = strongerDecision(current.decision, next.decision);
  1405. const permissionDecision = strongerPermissionDecision(
  1406. current.permissionDecision,
  1407. next.permissionDecision,
  1408. );
  1409. const permissionAutoApproval = strongerPermissionAutoApproval(
  1410. current.permissionAutoApproval,
  1411. next.permissionAutoApproval,
  1412. );
  1413. const toolPermissionDecision = strongerToolPermissionDecision(
  1414. current.toolPermissionDecision,
  1415. next.toolPermissionDecision,
  1416. );
  1417. return {
  1418. decision,
  1419. ...(permissionDecision ? { permissionDecision } : {}),
  1420. ...(permissionAutoApproval ? { permissionAutoApproval } : {}),
  1421. ...(toolPermissionDecision ? { toolPermissionDecision } : {}),
  1422. ...((next.reason ?? current.reason) ? { reason: next.reason ?? current.reason } : {}),
  1423. ...((next.additionalContext ?? current.additionalContext)
  1424. ? {
  1425. additionalContext: mergePluginHookContext(
  1426. current.additionalContext,
  1427. next.additionalContext,
  1428. ),
  1429. }
  1430. : {}),
  1431. ...((next.updatedInput ?? current.updatedInput)
  1432. ? { updatedInput: next.updatedInput ?? current.updatedInput }
  1433. : {}),
  1434. ...(current.updatedPermissions || next.updatedPermissions
  1435. ? {
  1436. updatedPermissions: [
  1437. ...(current.updatedPermissions ?? []),
  1438. ...(next.updatedPermissions ?? []),
  1439. ],
  1440. }
  1441. : {}),
  1442. ...((next.continuePrompt ?? current.continuePrompt)
  1443. ? {
  1444. continuePrompt: mergePluginHookContext(current.continuePrompt, next.continuePrompt),
  1445. }
  1446. : {}),
  1447. ...((next.defer ?? current.defer) ? { defer: next.defer ?? current.defer } : {}),
  1448. ...(current.continue === false || next.continue === false ? { continue: false } : {}),
  1449. ...((next.stopReason ?? current.stopReason)
  1450. ? { stopReason: next.stopReason ?? current.stopReason }
  1451. : {}),
  1452. ...(current.suppressOutput === true || next.suppressOutput === true
  1453. ? { suppressOutput: true }
  1454. : {}),
  1455. ...((next.systemMessage ?? current.systemMessage)
  1456. ? {
  1457. systemMessage: mergePluginHookContext(current.systemMessage, next.systemMessage),
  1458. }
  1459. : {}),
  1460. ...((next.terminalSequence ?? current.terminalSequence)
  1461. ? {
  1462. terminalSequence: `${current.terminalSequence ?? ''}${next.terminalSequence ?? ''}`,
  1463. }
  1464. : {}),
  1465. ...((next.postToolFeedback ?? current.postToolFeedback)
  1466. ? {
  1467. postToolFeedback: mergePluginHookContext(current.postToolFeedback, next.postToolFeedback),
  1468. }
  1469. : {}),
  1470. ...(current.interrupt === true || next.interrupt === true ? { interrupt: true } : {}),
  1471. ...(next.updatedResult !== undefined
  1472. ? {
  1473. updatedResult: next.updatedResult,
  1474. ...(next.updatedResultFormat ? { updatedResultFormat: next.updatedResultFormat } : {}),
  1475. }
  1476. : current.updatedResult !== undefined
  1477. ? {
  1478. updatedResult: current.updatedResult,
  1479. ...(current.updatedResultFormat
  1480. ? { updatedResultFormat: current.updatedResultFormat }
  1481. : {}),
  1482. }
  1483. : {}),
  1484. };
  1485. }
  1486. function strongerDecision(
  1487. left: PluginHookDecision['decision'],
  1488. right: PluginHookDecision['decision'],
  1489. ): PluginHookDecision['decision'] {
  1490. const rank: Record<PluginHookDecision['decision'], number> = {
  1491. allow: 0,
  1492. ask: 1,
  1493. defer: 2,
  1494. deny: 3,
  1495. };
  1496. return rank[right] > rank[left] ? right : left;
  1497. }
  1498. function strongerPermissionDecision(
  1499. left: PluginHookDecision['permissionDecision'],
  1500. right: PluginHookDecision['permissionDecision'],
  1501. ): PluginHookDecision['permissionDecision'] {
  1502. const rank = { abstain: 0, allow: 1, deny: 2 } as const;
  1503. if (!left) return right;
  1504. if (!right) return left;
  1505. return rank[right] > rank[left] ? right : left;
  1506. }
  1507. function strongerPermissionAutoApproval(
  1508. left: PluginHookDecision['permissionAutoApproval'],
  1509. right: PluginHookDecision['permissionAutoApproval'],
  1510. ): PluginHookDecision['permissionAutoApproval'] {
  1511. if (left === 'any_prompt' || right === 'any_prompt') return 'any_prompt';
  1512. return right ?? left;
  1513. }
  1514. function strongerToolPermissionDecision(
  1515. left: PluginHookDecision['toolPermissionDecision'],
  1516. right: PluginHookDecision['toolPermissionDecision'],
  1517. ): PluginHookDecision['toolPermissionDecision'] {
  1518. const rank = { abstain: 0, allow: 1, ask: 2, defer: 3, deny: 4 } as const;
  1519. if (!left) return right;
  1520. if (!right) return left;
  1521. return rank[right] > rank[left] ? right : left;
  1522. }
  1523. export function mergePluginHookContext(
  1524. ...parts: readonly (string | undefined)[]
  1525. ): string | undefined {
  1526. const merged = parts.filter((part): part is string => Boolean(part)).join('\n');
  1527. return merged ? boundedInjectedText(merged) : undefined;
  1528. }
  1529. export function composePluginHookToolResultContent<T>(
  1530. originalContent: readonly T[],
  1531. updatedResult: unknown,
  1532. additionalContext?: string,
  1533. options?: {
  1534. readonly sourceFormat?: PluginHookDecision['updatedResultFormat'];
  1535. readonly toolName?: string;
  1536. },
  1537. ): Array<T | { readonly type: 'text'; readonly text: string }> | undefined {
  1538. const context = additionalContext?.trim();
  1539. if (updatedResult === undefined && !context) return undefined;
  1540. const content: Array<T | { readonly type: 'text'; readonly text: string }> =
  1541. updatedResult === undefined ? [...originalContent] : [];
  1542. if (updatedResult !== undefined) {
  1543. const structuredContent =
  1544. options?.sourceFormat === 'CLAUDE'
  1545. ? readStructuredPluginHookToolContent(updatedResult)
  1546. : undefined;
  1547. if (structuredContent) {
  1548. content.push(...(structuredContent as unknown as readonly T[]));
  1549. } else {
  1550. const text =
  1551. options?.sourceFormat === 'CLAUDE'
  1552. ? serializeCompatibleToolOutput(options.toolName, updatedResult)
  1553. : safeToolResultOverrideText(updatedResult);
  1554. if (text === undefined) content.push(...originalContent);
  1555. else content.push({ type: 'text', text });
  1556. }
  1557. }
  1558. if (context) {
  1559. content.push({
  1560. type: 'text',
  1561. text: `<plugin-hook-context>\n${context}\n</plugin-hook-context>`,
  1562. });
  1563. }
  1564. return content;
  1565. }
  1566. function serializeCompatibleToolOutput(
  1567. toolName: string | undefined,
  1568. value: unknown,
  1569. ): string | undefined {
  1570. if (!isRecord(value)) return undefined;
  1571. if (toolName === 'bash') {
  1572. if (
  1573. typeof value.stdout !== 'string' ||
  1574. typeof value.stderr !== 'string' ||
  1575. typeof value.interrupted !== 'boolean' ||
  1576. value.isImage !== false
  1577. )
  1578. return undefined;
  1579. return [value.stdout, value.stderr, ...(value.interrupted ? ['Command interrupted'] : [])]
  1580. .filter(Boolean)
  1581. .join('\n');
  1582. }
  1583. return undefined;
  1584. }
  1585. /**
  1586. * Preserve the model-facing `content` from an exact structured
  1587. * `updatedToolOutput` (notably Plugin MCP CallToolResult) instead of flattening
  1588. * it to JSON. This is independent of Compatible built-in response adaptation.
  1589. */
  1590. function readStructuredPluginHookToolContent(
  1591. value: unknown,
  1592. ):
  1593. | Array<
  1594. | { readonly type: 'text'; readonly text: string }
  1595. | { readonly type: 'image' | 'video'; readonly data: string; readonly mimeType: string }
  1596. >
  1597. | undefined {
  1598. if (!isRecord(value) || !Array.isArray(value.content)) return undefined;
  1599. const content: Array<
  1600. | { readonly type: 'text'; readonly text: string }
  1601. | { readonly type: 'image' | 'video'; readonly data: string; readonly mimeType: string }
  1602. > = [];
  1603. for (const part of value.content) {
  1604. if (!isRecord(part)) return undefined;
  1605. if (part.type === 'text' && typeof part.text === 'string') {
  1606. content.push({ type: 'text', text: part.text });
  1607. continue;
  1608. }
  1609. if (
  1610. (part.type === 'image' || part.type === 'video') &&
  1611. typeof part.data === 'string' &&
  1612. typeof part.mimeType === 'string'
  1613. ) {
  1614. content.push({ type: part.type, data: part.data, mimeType: part.mimeType });
  1615. continue;
  1616. }
  1617. return undefined;
  1618. }
  1619. return content;
  1620. }
  1621. function boundedInjectedText(value: string): string {
  1622. return value.slice(0, MAX_INJECTED_TEXT_CHARS);
  1623. }
  1624. function serializeHookInput(input: PluginHookEventInput): string | undefined {
  1625. try {
  1626. const serialized = JSON.stringify({
  1627. ...(input.payload ?? {}),
  1628. hook_event_name: input.event,
  1629. session_id: input.sessionId,
  1630. ...(input.turnId ? { turn_id: input.turnId } : {}),
  1631. ...(input.promptId ? { prompt_id: input.promptId } : {}),
  1632. transcript_path: input.transcriptPath ?? null,
  1633. cwd: input.cwd,
  1634. ...(input.model ? { model: input.model } : {}),
  1635. ...(input.permissionMode ? { permission_mode: input.permissionMode } : {}),
  1636. ...(input.effort ? { effort: input.effort } : {}),
  1637. });
  1638. return Buffer.byteLength(serialized) <= MAX_INPUT_BYTES ? serialized : undefined;
  1639. } catch {
  1640. return undefined;
  1641. }
  1642. }
  1643. function isValidWireInput(handler: PluginHookCommandHandler, input: PluginHookEventInput): boolean {
  1644. if (!input.sessionId || !input.cwd) return false;
  1645. if (handler.sourceFormat === 'MINIMAX') return true;
  1646. const payload = input.payload ?? {};
  1647. const has = (key: string) =>
  1648. Object.prototype.hasOwnProperty.call(payload, key) && payload[key] !== undefined;
  1649. const requiresTurn =
  1650. handler.sourceFormat === 'CODEX' &&
  1651. input.event !== 'SessionStart' &&
  1652. input.event !== 'SessionEnd';
  1653. if (requiresTurn && !input.turnId) return false;
  1654. if (handler.sourceFormat === 'CODEX' && input.event !== 'SessionEnd' && !input.model) {
  1655. return false;
  1656. }
  1657. const requiresPermissionMode =
  1658. input.event !== 'SessionEnd' && input.event !== 'PreCompact' && input.event !== 'PostCompact';
  1659. if (handler.sourceFormat === 'CODEX' && requiresPermissionMode && !input.permissionMode) {
  1660. return false;
  1661. }
  1662. if (handler.sourceFormat === 'CLAUDE' && input.transcriptPath == null) return false;
  1663. if (
  1664. handler.sourceFormat === 'CLAUDE' &&
  1665. requiresPermissionMode &&
  1666. input.event !== 'SessionStart' &&
  1667. input.event !== 'SubagentStart' &&
  1668. !input.permissionMode
  1669. )
  1670. return false;
  1671. switch (input.event) {
  1672. case 'SessionStart':
  1673. return has('source');
  1674. case 'SessionEnd':
  1675. return has('reason');
  1676. case 'UserPromptSubmit':
  1677. return has('prompt');
  1678. case 'PreToolUse':
  1679. return has('tool_name') && has('tool_input') && has('tool_use_id');
  1680. case 'PermissionRequest':
  1681. return has('tool_name') && has('tool_input');
  1682. case 'PostToolUse':
  1683. return has('tool_name') && has('tool_input') && has('tool_response') && has('tool_use_id');
  1684. case 'SubagentStart':
  1685. return has('agent_id') && has('agent_type');
  1686. case 'SubagentStop':
  1687. return (
  1688. has('stop_hook_active') &&
  1689. has('agent_id') &&
  1690. has('agent_type') &&
  1691. has('agent_transcript_path') &&
  1692. has('last_assistant_message')
  1693. );
  1694. case 'Stop':
  1695. return has('stop_hook_active') && has('last_assistant_message');
  1696. case 'PreCompact':
  1697. return has('trigger');
  1698. case 'PostCompact':
  1699. return (
  1700. has('trigger') &&
  1701. (handler.sourceFormat !== 'CLAUDE' || typeof payload.compact_summary === 'string')
  1702. );
  1703. }
  1704. }
  1705. function safeHookEnvironment(): NodeJS.ProcessEnv {
  1706. const inherited = [
  1707. 'PATH',
  1708. 'HOME',
  1709. 'LANG',
  1710. 'TERM',
  1711. 'SHELL',
  1712. 'USER',
  1713. 'TMPDIR',
  1714. 'TEMP',
  1715. 'TMP',
  1716. 'PATHEXT',
  1717. 'SystemRoot',
  1718. 'ComSpec',
  1719. 'USERPROFILE',
  1720. 'HOMEDRIVE',
  1721. 'HOMEPATH',
  1722. 'APPDATA',
  1723. 'LOCALAPPDATA',
  1724. ];
  1725. return Object.fromEntries(
  1726. inherited.flatMap((name) => {
  1727. const value = process.env[name];
  1728. return value === undefined ? [] : [[name, value]];
  1729. }),
  1730. );
  1731. }
  1732. function matches(handler: PluginHookCommandHandler, input: PluginHookEventInput): boolean {
  1733. if (input.event === 'UserPromptSubmit' || input.event === 'Stop') return true;
  1734. const pattern = handler.matcher;
  1735. const values = matcherValues(handler, input);
  1736. if (!pattern || pattern === '*') return true;
  1737. if (pattern.length > 256) return false;
  1738. if (values.length === 0 || values.some((value) => value.length > 256)) return false;
  1739. if (handler.sourceFormat === 'CODEX' && /^[A-Za-z0-9_|]+$/u.test(pattern)) {
  1740. const alternatives = pattern.split('|');
  1741. return values.some((value) => alternatives.includes(value));
  1742. }
  1743. if (handler.sourceFormat === 'CLAUDE') {
  1744. const alternatives = pattern.split(/[|,]/u).map((part) => part.trim());
  1745. if (/^[A-Za-z0-9_\- ,|]+$/u.test(pattern)) {
  1746. return values.some((value) => alternatives.includes(value));
  1747. }
  1748. } else if (handler.sourceFormat === 'MINIMAX') {
  1749. const alternatives = pattern.split(/[|,]/u).map((part) => part.trim());
  1750. if (alternatives.every((part) => /^[A-Za-z0-9_.:/-]+$/u.test(part))) {
  1751. return values.some((value) => alternatives.includes(value));
  1752. }
  1753. }
  1754. try {
  1755. if (!isSafePluginHookMatcher(pattern)) return false;
  1756. const regex = new RegExp(pattern, 'u');
  1757. return values.some((value) => regex.test(value));
  1758. } catch {
  1759. return false;
  1760. }
  1761. }
  1762. function matchesCondition(handler: PluginHookCommandHandler, input: PluginHookEventInput): boolean {
  1763. if (!handler.condition) return true;
  1764. const match = /^([A-Za-z0-9_.:/-]+)\(([^\r\n()]*)\)$/u.exec(handler.condition);
  1765. if (!match?.[1] || match[2] === undefined) return false;
  1766. if (!matcherValues(handler, input).includes(match[1])) return false;
  1767. const adapted = adaptVendorInput(handler, input);
  1768. const toolInput = adapted.payload?.tool_input;
  1769. if (!isRecord(toolInput)) return false;
  1770. const candidate = conditionCandidate(match[1], toolInput);
  1771. if (candidate === undefined) return false;
  1772. if (match[1] !== 'Bash') return globMatches(match[2], candidate);
  1773. return bashPermissionRuleMatches(match[2], candidate);
  1774. }
  1775. /**
  1776. * Compatible evaluates Bash permission-rule conditions against each simple
  1777. * subcommand. This intentionally handles only commands that can be split
  1778. * without shell parsing ambiguity; ambiguous input executes the Hook
  1779. * conservatively instead of accidentally skipping a safety Hook.
  1780. */
  1781. function bashPermissionRuleMatches(pattern: string, command: string): boolean {
  1782. if (/['"\\]|\$\{|<<|>>|<\(|>\(/u.test(command)) return true;
  1783. const substitutions = [
  1784. ...[...command.matchAll(/\$\(([^()]*)\)/gu)].map((match) => match[1] ?? ''),
  1785. ...[...command.matchAll(/`([^`]*)`/gu)].map((match) => match[1] ?? ''),
  1786. ];
  1787. const containsDynamicExpansion = substitutions.length > 0 || /\$[A-Za-z_]/u.test(command);
  1788. const subcommands = [command, ...substitutions]
  1789. .flatMap((candidate) => candidate.split(/\s*(?:&&|\|\||;|\n|\|)\s*/u))
  1790. .map((part) => part.trim())
  1791. .map(stripLeadingEnvironmentAssignments)
  1792. .filter(Boolean);
  1793. if (subcommands.length === 0) return true;
  1794. const prefix = pattern.endsWith(':*') ? pattern.slice(0, -2).trim() : undefined;
  1795. if (
  1796. subcommands.some((subcommand) =>
  1797. prefix
  1798. ? subcommand === prefix || subcommand.startsWith(`${prefix} `)
  1799. : globMatches(pattern, subcommand),
  1800. )
  1801. )
  1802. return true;
  1803. const patternWords = pattern.trim().split(/\s+/u);
  1804. return containsDynamicExpansion && patternWords.length > 2;
  1805. }
  1806. function conditionCandidate(
  1807. toolName: string,
  1808. toolInput: Readonly<Record<string, unknown>>,
  1809. ): string | undefined {
  1810. const key =
  1811. toolName === 'Bash' || toolName === 'PowerShell'
  1812. ? 'command'
  1813. : toolName === 'WebFetch'
  1814. ? 'url'
  1815. : toolName === 'WebSearch'
  1816. ? 'query'
  1817. : toolName === 'Agent'
  1818. ? 'subagent_type'
  1819. : 'file_path';
  1820. return typeof toolInput[key] === 'string' ? toolInput[key] : undefined;
  1821. }
  1822. function stripLeadingEnvironmentAssignments(command: string): string {
  1823. return command.replace(/^(?:[A-Za-z_][A-Za-z0-9_]*=(?:[^\s'"`]+|'[^']*'|"[^"]*")\s+)+/u, '');
  1824. }
  1825. function globMatches(pattern: string, value: string): boolean {
  1826. const expression = pattern
  1827. .split('')
  1828. .map((char) => {
  1829. if (char === '*') return '.*';
  1830. if (char === '?') return '.';
  1831. return /[\\^$.*+?()[\]{}|]/u.test(char) ? `\\${char}` : char;
  1832. })
  1833. .join('');
  1834. try {
  1835. return new RegExp(`^${expression}$`, 'u').test(value);
  1836. } catch {
  1837. return false;
  1838. }
  1839. }
  1840. function expandHookPlaceholders(value: string, env: NodeJS.ProcessEnv): string {
  1841. return value.replace(/\$\{([A-Z][A-Z0-9_]*)\}/gu, (placeholder, name: string) => {
  1842. const replacement = env[name];
  1843. return replacement === undefined ? placeholder : replacement;
  1844. });
  1845. }
  1846. function adaptVendorInput(
  1847. handler: PluginHookCommandHandler,
  1848. input: PluginHookEventInput,
  1849. ): PluginHookEventInput {
  1850. const payload = input.payload ?? {};
  1851. const sourceFormat = handler.sourceFormat;
  1852. const common = adaptCommonInputMetadata(input, sourceFormat);
  1853. if (input.event === 'SessionStart') {
  1854. const source = compatibleSessionStartSource(
  1855. input.matcherValue ?? (typeof payload.source === 'string' ? payload.source : undefined),
  1856. sourceFormat,
  1857. );
  1858. return {
  1859. ...common,
  1860. matcherValue: source,
  1861. payload: pickVendorPayload({ ...payload, source }, ['source']),
  1862. };
  1863. }
  1864. if (input.event === 'SessionEnd') {
  1865. const reason = compatibleSessionEndReason(
  1866. input.matcherValue ?? (typeof payload.reason === 'string' ? payload.reason : undefined),
  1867. sourceFormat,
  1868. );
  1869. return {
  1870. ...common,
  1871. matcherValue: reason,
  1872. payload: pickVendorPayload({ ...payload, reason }, ['reason']),
  1873. };
  1874. }
  1875. if (
  1876. input.event === 'PreToolUse' ||
  1877. input.event === 'PermissionRequest' ||
  1878. input.event === 'PostToolUse'
  1879. ) {
  1880. const tool = adaptToolIdentity(
  1881. handler,
  1882. input.event,
  1883. payload,
  1884. input.matcherValue,
  1885. input.toolProvenance,
  1886. input.cwd,
  1887. );
  1888. const subagentFields = ['agent_id', 'agent_type'];
  1889. const keys =
  1890. input.event === 'PermissionRequest'
  1891. ? [
  1892. ...subagentFields,
  1893. 'tool_name',
  1894. 'tool_input',
  1895. ...(sourceFormat === 'CLAUDE' ? ['permission_suggestions'] : []),
  1896. ]
  1897. : input.event === 'PostToolUse'
  1898. ? [
  1899. ...subagentFields,
  1900. 'tool_name',
  1901. 'tool_input',
  1902. 'tool_response',
  1903. 'tool_use_id',
  1904. ...(sourceFormat === 'CLAUDE' ? ['duration_ms'] : []),
  1905. ]
  1906. : [...subagentFields, 'tool_name', 'tool_input', 'tool_use_id'];
  1907. return {
  1908. ...common,
  1909. matcherValue: tool.matcherValue,
  1910. payload: pickVendorPayload(
  1911. {
  1912. ...payload,
  1913. tool_name: tool.toolName,
  1914. tool_input: tool.toolInput,
  1915. permission_suggestions:
  1916. sourceFormat === 'CLAUDE'
  1917. ? compatiblePermissionSuggestions(tool.toolName, payload.permission_rule_contents)
  1918. : undefined,
  1919. tool_response:
  1920. sourceFormat === 'CLAUDE'
  1921. ? payload.compatible_tool_response
  1922. : sourceFormat === 'CODEX'
  1923. ? payload.codex_tool_response
  1924. : (payload.tool_response ?? payload.tool_result),
  1925. },
  1926. keys,
  1927. ),
  1928. };
  1929. }
  1930. if (input.event === 'SubagentStart' || input.event === 'SubagentStop') {
  1931. const agentType =
  1932. typeof payload.agent_type === 'string'
  1933. ? payload.agent_type
  1934. : typeof payload.agent_name === 'string'
  1935. ? payload.agent_name
  1936. : input.matcherValue;
  1937. const keys =
  1938. input.event === 'SubagentStart'
  1939. ? (['agent_id', 'agent_type'] as const)
  1940. : ([
  1941. 'stop_hook_active',
  1942. 'agent_id',
  1943. 'agent_type',
  1944. 'agent_transcript_path',
  1945. 'last_assistant_message',
  1946. ...(sourceFormat === 'CLAUDE' ? ['background_tasks', 'session_crons'] : []),
  1947. ] as const);
  1948. return {
  1949. ...common,
  1950. payload: pickVendorPayload({ ...payload, agent_type: agentType }, keys),
  1951. };
  1952. }
  1953. const vendorPayloadKeys: Partial<Record<PluginHookEventInput['event'], readonly string[]>> = {
  1954. UserPromptSubmit: ['prompt'],
  1955. Stop: [
  1956. 'stop_hook_active',
  1957. 'last_assistant_message',
  1958. ...(sourceFormat === 'CLAUDE' ? ['background_tasks', 'session_crons'] : []),
  1959. ],
  1960. PreCompact: ['trigger', ...(sourceFormat === 'CLAUDE' ? ['custom_instructions'] : [])],
  1961. PostCompact: ['trigger', ...(sourceFormat === 'CLAUDE' ? ['compact_summary'] : [])],
  1962. };
  1963. return {
  1964. ...common,
  1965. payload: pickVendorPayload(
  1966. input.event === 'PreCompact' && sourceFormat === 'CLAUDE'
  1967. ? {
  1968. ...payload,
  1969. custom_instructions:
  1970. typeof payload.custom_instructions === 'string' ? payload.custom_instructions : '',
  1971. }
  1972. : payload,
  1973. vendorPayloadKeys[input.event] ?? [],
  1974. ),
  1975. };
  1976. }
  1977. function compatiblePermissionSuggestions(
  1978. toolName: string | undefined,
  1979. value: unknown,
  1980. ): readonly unknown[] | undefined {
  1981. if (
  1982. !toolName ||
  1983. !Array.isArray(value) ||
  1984. value.length === 0 ||
  1985. !value.every((rule) => typeof rule === 'string' && rule.trim().length > 0)
  1986. ) {
  1987. return undefined;
  1988. }
  1989. return [
  1990. {
  1991. type: 'addRules',
  1992. rules: value.map((ruleContent) => ({ toolName, ruleContent })),
  1993. behavior: 'allow',
  1994. // MiniMax's persisted global permission store is equivalent to Compatible's
  1995. // per-user settings destination. Keep Compatible's public wire vocabulary on
  1996. // the Hook boundary so a suggestion can be echoed as updatedPermissions.
  1997. destination: 'userSettings',
  1998. },
  1999. ];
  2000. }
  2001. function adaptCommonInputMetadata(
  2002. input: PluginHookEventInput,
  2003. sourceFormat: PluginHookCommandHandler['sourceFormat'],
  2004. ): PluginHookEventInput {
  2005. const subagentContext = input.subagentContext;
  2006. const usesParentAgentSession =
  2007. sourceFormat !== 'MINIMAX' &&
  2008. subagentContext !== undefined &&
  2009. (input.event === 'SubagentStart' || input.event === 'SubagentStop');
  2010. const codexTurnScoped = input.event !== 'SessionStart' && input.event !== 'SessionEnd';
  2011. const hasPermissionMode =
  2012. sourceFormat === 'CLAUDE'
  2013. ? input.event === 'UserPromptSubmit' ||
  2014. input.event === 'PreToolUse' ||
  2015. input.event === 'PermissionRequest' ||
  2016. input.event === 'PostToolUse' ||
  2017. input.event === 'Stop' ||
  2018. input.event === 'SubagentStop'
  2019. : input.event !== 'SessionEnd' &&
  2020. input.event !== 'PreCompact' &&
  2021. input.event !== 'PostCompact';
  2022. const hasCompatibleEffort =
  2023. sourceFormat === 'CLAUDE' &&
  2024. (input.event === 'PreToolUse' ||
  2025. input.event === 'PermissionRequest' ||
  2026. input.event === 'PostToolUse' ||
  2027. input.event === 'SubagentStart' ||
  2028. input.event === 'SubagentStop' ||
  2029. input.event === 'Stop');
  2030. return {
  2031. ...input,
  2032. sessionId: usesParentAgentSession ? subagentContext.parentSessionId : input.sessionId,
  2033. transcriptPath:
  2034. sourceFormat === 'CODEX'
  2035. ? usesParentAgentSession
  2036. ? subagentContext.parentCodexTranscriptPath
  2037. : input.codexTranscriptPath
  2038. : usesParentAgentSession
  2039. ? subagentContext.parentTranscriptPath
  2040. : input.transcriptPath,
  2041. turnId:
  2042. sourceFormat === 'CLAUDE'
  2043. ? undefined
  2044. : codexTurnScoped
  2045. ? usesParentAgentSession
  2046. ? subagentContext.parentTurnId
  2047. : input.turnId
  2048. : undefined,
  2049. promptId: sourceFormat === 'CLAUDE' ? input.promptId : undefined,
  2050. model:
  2051. sourceFormat === 'CLAUDE'
  2052. ? input.event === 'SessionStart'
  2053. ? input.model
  2054. : undefined
  2055. : input.event === 'SessionEnd'
  2056. ? undefined
  2057. : input.model,
  2058. permissionMode: hasPermissionMode
  2059. ? compatiblePermissionMode(input.permissionMode, sourceFormat)
  2060. : undefined,
  2061. effort: hasCompatibleEffort ? input.effort : undefined,
  2062. };
  2063. }
  2064. function matcherValues(
  2065. handler: PluginHookCommandHandler,
  2066. input: PluginHookEventInput,
  2067. ): readonly string[] {
  2068. const adapted = adaptVendorInput(handler, input).matcherValue;
  2069. if (!adapted) return [];
  2070. if (handler.sourceFormat !== 'CODEX') return [adapted];
  2071. if (adapted === 'apply_patch') return [adapted, 'Write', 'Edit'];
  2072. if (adapted === 'spawn_agent') return [adapted, 'Agent'];
  2073. return [adapted];
  2074. }
  2075. function compatiblePermissionMode(
  2076. value: string | undefined,
  2077. sourceFormat: PluginHookCommandHandler['sourceFormat'],
  2078. ): string | undefined {
  2079. if (!value) return undefined;
  2080. if (value === 'off') return 'bypassPermissions';
  2081. if (sourceFormat === 'CODEX' && value === 'auto') return 'default';
  2082. const supported =
  2083. sourceFormat === 'CODEX'
  2084. ? new Set(['default', 'acceptEdits', 'plan', 'dontAsk', 'bypassPermissions'])
  2085. : new Set(['default', 'acceptEdits', 'auto', 'plan', 'dontAsk', 'bypassPermissions']);
  2086. return supported.has(value) ? value : 'default';
  2087. }
  2088. function pickVendorPayload(
  2089. payload: Readonly<Record<string, unknown>>,
  2090. keys: readonly string[],
  2091. ): Readonly<Record<string, unknown>> {
  2092. return Object.fromEntries(
  2093. keys.flatMap((key) =>
  2094. Object.prototype.hasOwnProperty.call(payload, key) && payload[key] !== undefined
  2095. ? [[key, payload[key]]]
  2096. : [],
  2097. ),
  2098. );
  2099. }
  2100. function compatibleSessionStartSource(
  2101. value: string | undefined,
  2102. sourceFormat: PluginHookCommandHandler['sourceFormat'],
  2103. ): string | undefined {
  2104. if (value === 'plugin_activation') return 'startup';
  2105. if (sourceFormat === 'CODEX' && value === 'fork') return 'resume';
  2106. return value;
  2107. }
  2108. function compatibleSessionEndReason(
  2109. value: string | undefined,
  2110. sourceFormat: PluginHookCommandHandler['sourceFormat'],
  2111. ): string | undefined {
  2112. if (sourceFormat === 'CODEX') return 'other';
  2113. if (value === 'resume_other') return 'resume';
  2114. if (value === 'archive' || value === 'idle_timeout') return 'other';
  2115. return value;
  2116. }
  2117. function isEventSupportedBySource(
  2118. handler: PluginHookCommandHandler,
  2119. input: PluginHookEventInput,
  2120. ): boolean {
  2121. if (
  2122. input.event === 'PostToolUse' &&
  2123. handler.sourceFormat === 'CODEX' &&
  2124. input.payload?.tool_name === 'bash'
  2125. ) {
  2126. const details = isRecord(input.payload.tool_result)
  2127. ? input.payload.tool_result.details
  2128. : undefined;
  2129. const status = isRecord(details) ? details.status : undefined;
  2130. if (status === 'background_started' || status === 'started') return false;
  2131. }
  2132. if (input.event !== 'PostToolUse' || input.payload?.is_error !== true) return true;
  2133. // Compatible reserves PostToolUse for successful executions and exposes
  2134. // failures through PostToolUseFailure. Codex deliberately sends non-zero
  2135. // Bash results through PostToolUse, so only Compatible is filtered here.
  2136. if (handler.sourceFormat === 'CLAUDE') return false;
  2137. return true;
  2138. }
  2139. const MAX_CONCURRENT_COMMANDS = 8;
  2140. async function mapWithConcurrency<T, R>(
  2141. values: readonly T[],
  2142. concurrency: number,
  2143. operation: (value: T) => Promise<R>,
  2144. ): Promise<R[]> {
  2145. const results = new Array<R>(values.length);
  2146. let cursor = 0;
  2147. await Promise.all(
  2148. Array.from({ length: Math.min(concurrency, values.length) }, async () => {
  2149. while (cursor < values.length) {
  2150. const index = cursor;
  2151. cursor += 1;
  2152. const value = values[index];
  2153. if (value === undefined) continue;
  2154. results[index] = await operation(value);
  2155. }
  2156. }),
  2157. );
  2158. return results;
  2159. }
  2160. function needsPostToolAdapter(
  2161. handler: PluginHookCommandHandler,
  2162. input: PluginHookEventInput,
  2163. ): boolean {
  2164. if (handler.event !== 'PostToolUse' || input.event !== 'PostToolUse') return false;
  2165. if (!isEventSupportedBySource(handler, input)) return false;
  2166. if (handler.sourceFormat === 'CLAUDE') {
  2167. return !isRecord(input.payload?.compatible_tool_response);
  2168. }
  2169. if (handler.sourceFormat === 'CODEX') return input.payload?.codex_tool_response === undefined;
  2170. return false;
  2171. }
  2172. function withPostToolAdapterEvidence(
  2173. handler: PluginHookCommandHandler,
  2174. input: PluginHookEventInput,
  2175. ): PluginHookEventInput {
  2176. const evidence =
  2177. handler.sourceFormat === 'CLAUDE'
  2178. ? { compatible_tool_response: {} }
  2179. : handler.sourceFormat === 'CODEX'
  2180. ? { codex_tool_response: '' }
  2181. : {};
  2182. return {
  2183. ...input,
  2184. payload: { ...(input.payload ?? {}), ...evidence },
  2185. };
  2186. }
  2187. function compareHandlers(left: PluginHookCommandHandler, right: PluginHookCommandHandler): number {
  2188. return (
  2189. left.pluginName.localeCompare(right.pluginName) ||
  2190. left.sourcePath.localeCompare(right.sourcePath) ||
  2191. left.declarationOrder - right.declarationOrder
  2192. );
  2193. }
  2194. function runDiagnostic(
  2195. handler: PluginHookCommandHandler,
  2196. code: PluginHookRunDiagnostic['code'],
  2197. ): PluginHookRunDiagnostic {
  2198. return {
  2199. code,
  2200. pluginName: handler.pluginName,
  2201. sourcePath: handler.sourcePath,
  2202. event: handler.event,
  2203. declarationOrder: handler.declarationOrder,
  2204. };
  2205. }
  2206. export function renderPluginHookRejectionReminder(reason?: string): string {
  2207. const detail = escapeXmlText(
  2208. boundedReason(reason?.trim() || 'A Plugin Hook rejected this queued prompt.'),
  2209. );
  2210. return [
  2211. '<plugin-hook-rejection>',
  2212. 'A Plugin Hook rejected a queued user prompt before it reached the model.',
  2213. `Reason: ${detail}`,
  2214. 'Briefly tell the user that the queued prompt was rejected and why. Do not claim to have processed the rejected prompt.',
  2215. '</plugin-hook-rejection>',
  2216. ].join('\n');
  2217. }
  2218. function boundedReason(value: string): string {
  2219. return value.slice(0, MAX_REASON_CHARS);
  2220. }
  2221. function escapeXmlText(value: string): string {
  2222. return value.split('&').join('&amp;').split('<').join('&lt;').split('>').join('&gt;');
  2223. }
  2224. function isRecord(value: unknown): value is Record<string, unknown> {
  2225. return typeof value === 'object' && value !== null && !Array.isArray(value);
  2226. }
  2227. function isSafeHookOutputValue(value: unknown): boolean {
  2228. const pending: Array<{ readonly value: unknown; readonly depth: number }> = [{ value, depth: 0 }];
  2229. let visited = 0;
  2230. while (pending.length > 0) {
  2231. const current = pending.pop();
  2232. if (!current) break;
  2233. visited += 1;
  2234. if (visited > MAX_OUTPUT_VALUE_NODES || current.depth > MAX_OUTPUT_VALUE_DEPTH) return false;
  2235. if (Array.isArray(current.value)) {
  2236. for (const child of current.value) pending.push({ value: child, depth: current.depth + 1 });
  2237. continue;
  2238. }
  2239. if (!isRecord(current.value)) continue;
  2240. for (const [key, child] of Object.entries(current.value)) {
  2241. if (key === '__proto__' || key === 'prototype' || key === 'constructor') return false;
  2242. pending.push({ value: child, depth: current.depth + 1 });
  2243. }
  2244. }
  2245. return true;
  2246. }
  2247. function safeToolResultOverrideText(value: unknown): string | undefined {
  2248. try {
  2249. const text = typeof value === 'string' ? value : JSON.stringify(value);
  2250. return text !== undefined && text.length <= MAX_INJECTED_TEXT_CHARS ? text : undefined;
  2251. } catch {
  2252. return undefined;
  2253. }
  2254. }