coordinator.ts 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289
  1. import type {
  2. PluginHookCommandHandler,
  3. PluginHookDecision,
  4. PluginHookEventInput,
  5. PluginHookRunResult,
  6. PluginHookLogger,
  7. PluginHookObserver,
  8. PluginHookSessionStartSource,
  9. PluginSubagentRegistration,
  10. } from './contracts.js';
  11. import { cleanupPluginHookSessionArtifacts } from './output-artifacts.js';
  12. import { mergePluginHookDecisions, PluginHookRunner } from './runner.js';
  13. const SESSION_IDLE_MS = 30 * 60 * 1_000;
  14. const SESSION_END_BUDGET_MS = 3_000;
  15. const SESSION_END_REPORT_BUDGET_MS = 1_000;
  16. const SESSION_END_CONCURRENCY = 4;
  17. const SESSION_END_FENCE_RETRY_MS = 1_000;
  18. const SESSION_END_RESUME_DRAIN_BUDGET_MS = 2_000;
  19. const MAX_RESUMABLE_SESSION_MARKERS = 1_024;
  20. type PluginHookSessionEndReason = 'archive' | 'clear' | 'logout' | 'resume_other' | 'idle_timeout';
  21. export interface PluginHookSessionEndFence {
  22. run(input: {
  23. readonly sessionId: string;
  24. readonly reason: PluginHookSessionEndReason;
  25. readonly idleSinceMs?: number;
  26. readonly sessionOwnershipClaim?: string;
  27. readonly operation: (signal?: AbortSignal) => Promise<PluginHookRunResult | undefined>;
  28. }): Promise<
  29. | { readonly status: 'executed'; readonly result?: PluginHookRunResult }
  30. | { readonly status: 'deferred'; readonly latestActivityAtMs?: number }
  31. | { readonly status: 'superseded' }
  32. >;
  33. }
  34. export interface PluginHookAdmissionTransaction {
  35. commit(): Promise<void>;
  36. rollback(): Promise<void>;
  37. }
  38. interface ActivePlugin {
  39. readonly pluginName: string;
  40. readonly handlers: readonly PluginHookCommandHandler[];
  41. readonly cwd: string;
  42. readonly transcriptPath?: string | null;
  43. readonly codexTranscriptPath?: string | null;
  44. readonly model?: string;
  45. readonly permissionMode?: string;
  46. readonly effort?: PluginHookEventInput['effort'];
  47. readonly promptId?: string;
  48. }
  49. interface SessionState {
  50. readonly plugins: Map<string, ActivePlugin>;
  51. sessionOwnershipClaim?: string;
  52. pendingSessionEnd?: {
  53. readonly reason: Exclude<PluginHookSessionEndReason, 'idle_timeout'>;
  54. readonly enabledPluginNames?: ReadonlySet<string>;
  55. };
  56. transcriptCleanup?: () => Promise<void>;
  57. sessionEndCleanup?: () => Promise<void>;
  58. pendingCompactPluginIdentities?: ReadonlySet<string>;
  59. idleSinceMs?: number;
  60. suspendedIdleSinceMs?: number;
  61. turnActive: boolean;
  62. idleTimer?: ReturnType<typeof setTimeout>;
  63. idleEpoch: number;
  64. idleEndController?: AbortController;
  65. }
  66. export interface PluginHookCoordinatorOptions {
  67. /**
  68. * Desktop owns its 30-minute SessionEnd timer in-process. Cloud disables
  69. * this timer and runs SessionEnd from the sandbox idle-release fence so the
  70. * Hook still has a live sandbox in which to execute.
  71. */
  72. readonly automaticIdleSessionEnd?: boolean;
  73. /**
  74. * Best-effort host projection for SessionEnd output. Delivery is awaited
  75. * within a short independent budget so Cloud can persist the warning before
  76. * sandbox release without making Desktop lifecycle actions wait forever.
  77. */
  78. readonly onSessionEndResult?: (input: {
  79. readonly sessionId: string;
  80. readonly result?: PluginHookRunResult;
  81. }) => void | Promise<void>;
  82. }
  83. /**
  84. * Owns Plugin activation and the 30-minute idle SessionEnd rule. Turn callers
  85. * still pass their immutable handler snapshot to every event; this class never
  86. * re-reads mutable Plugin state in the middle of a turn.
  87. */
  88. export class PluginHookCoordinator {
  89. private readonly sessions = new Map<string, SessionState>();
  90. private readonly endedSessions = new Set<string>();
  91. private readonly subagents = new Map<string, PluginSubagentRegistration>();
  92. private readonly idleEndControllers = new Map<string, AbortController>();
  93. private readonly idleEndTasks = new Map<string, Promise<void>>();
  94. private readonly explicitEndControllers = new Map<string, AbortController>();
  95. private readonly explicitEndTasks = new Map<string, Promise<PluginHookRunResult | undefined>>();
  96. private readonly forcedAutomaticCompactions = new Set<string>();
  97. private readonly pendingSessionStartSources = new Map<
  98. string,
  99. Exclude<PluginHookSessionStartSource, 'compact' | 'plugin_activation'>
  100. >();
  101. private readonly automaticIdleSessionEnd: boolean;
  102. private readonly onSessionEndResult?: PluginHookCoordinatorOptions['onSessionEndResult'];
  103. private resolveEnabledPluginNames?: () => ReadonlySet<string>;
  104. private sessionEndFence?: PluginHookSessionEndFence;
  105. constructor(
  106. private readonly runner: PluginHookRunner = new PluginHookRunner(),
  107. options: PluginHookCoordinatorOptions = {},
  108. ) {
  109. this.automaticIdleSessionEnd = options.automaticIdleSessionEnd ?? true;
  110. this.onSessionEndResult = options.onSessionEndResult;
  111. }
  112. configureObservability(input: {
  113. readonly logger?: PluginHookLogger;
  114. readonly observer?: PluginHookObserver;
  115. }): void {
  116. this.runner.configure(input);
  117. }
  118. setEnabledPluginResolver(resolve: (() => ReadonlySet<string>) | undefined): void {
  119. this.resolveEnabledPluginNames = resolve;
  120. }
  121. setSessionEndFence(fence: PluginHookSessionEndFence | undefined): void {
  122. this.sessionEndFence = fence;
  123. }
  124. /** Binds a prepared durable owner before its activation CAS is committed. */
  125. bindSessionOwnershipClaim(sessionId: string, ownershipClaimId: string): string | undefined {
  126. const state = this.sessions.get(sessionId);
  127. if (!state) return undefined;
  128. const previousClaim = state.sessionOwnershipClaim;
  129. state.sessionOwnershipClaim = ownershipClaimId;
  130. return previousClaim;
  131. }
  132. /** Restores the prior owner only when the failed candidate is still bound. */
  133. rollbackSessionOwnershipClaim(
  134. sessionId: string,
  135. failedOwnershipClaimId: string,
  136. previousOwnershipClaimId?: string,
  137. ): void {
  138. const state = this.sessions.get(sessionId);
  139. if (!state || state.sessionOwnershipClaim !== failedOwnershipClaimId) return;
  140. if (previousOwnershipClaimId) state.sessionOwnershipClaim = previousOwnershipClaimId;
  141. else delete state.sessionOwnershipClaim;
  142. }
  143. activeSessionIds(): readonly string[] {
  144. return [...this.sessions.keys()];
  145. }
  146. /** Returns root sessions plus every linked child execution that must be fenced with them. */
  147. activeExecutionSessionIds(rootSessionId?: string): readonly string[] {
  148. if (!rootSessionId) {
  149. return [...new Set([...this.sessions.keys(), ...this.subagents.keys()])];
  150. }
  151. const result = new Set<string>([rootSessionId]);
  152. let changed = true;
  153. while (changed) {
  154. changed = false;
  155. for (const registration of this.subagents.values()) {
  156. if (!result.has(registration.parentSessionId) || result.has(registration.childSessionId)) {
  157. continue;
  158. }
  159. result.add(registration.childSessionId);
  160. changed = true;
  161. }
  162. }
  163. return [...result];
  164. }
  165. hasActiveDescendantExecutions(rootSessionId: string): boolean {
  166. return this.activeExecutionSessionIds(rootSessionId).length > 1;
  167. }
  168. isSubagentSession(sessionId: string): boolean {
  169. return this.subagents.has(sessionId);
  170. }
  171. markNextSessionStart(
  172. sessionId: string,
  173. source: Exclude<PluginHookSessionStartSource, 'compact' | 'plugin_activation'>,
  174. ): void {
  175. this.pendingSessionStartSources.delete(sessionId);
  176. this.pendingSessionStartSources.set(sessionId, source);
  177. if (this.pendingSessionStartSources.size <= MAX_RESUMABLE_SESSION_MARKERS) return;
  178. const oldest = this.pendingSessionStartSources.keys().next().value as string | undefined;
  179. if (oldest) this.pendingSessionStartSources.delete(oldest);
  180. }
  181. deactivatePlugin(pluginName: string): void {
  182. for (const [sessionId, state] of this.sessions) {
  183. const removed = new Set<string>();
  184. for (const [identity, plugin] of state.plugins) {
  185. if (plugin.pluginName === pluginName) {
  186. void cleanupPluginHookSessionArtifacts(plugin.handlers, sessionId);
  187. state.plugins.delete(identity);
  188. removed.add(identity);
  189. }
  190. }
  191. if (state.pendingCompactPluginIdentities && removed.size > 0) {
  192. state.pendingCompactPluginIdentities = new Set(
  193. [...state.pendingCompactPluginIdentities].filter((identity) => !removed.has(identity)),
  194. );
  195. if (state.pendingCompactPluginIdentities.size === 0) {
  196. state.pendingCompactPluginIdentities = undefined;
  197. }
  198. }
  199. }
  200. }
  201. async beginTurn(input: {
  202. readonly handlers: readonly PluginHookCommandHandler[];
  203. readonly sessionId: string;
  204. readonly turnId: string;
  205. readonly cwd: string;
  206. readonly prompt: string;
  207. readonly transcriptPath?: string | null;
  208. readonly codexTranscriptPath?: string | null;
  209. readonly model?: string;
  210. readonly permissionMode?: string;
  211. readonly effort?: PluginHookEventInput['effort'];
  212. readonly promptId?: string;
  213. readonly resumeExistingSession?: boolean;
  214. readonly sessionStartSource?: Exclude<
  215. PluginHookSessionStartSource,
  216. 'compact' | 'plugin_activation'
  217. >;
  218. readonly transcriptCleanup?: () => Promise<void>;
  219. /** Host-owned Session state cleared only after the logical SessionEnd Hook finishes. */
  220. readonly sessionEndCleanup?: () => Promise<void>;
  221. readonly sessionOwnershipClaim?: string;
  222. readonly captureAdmissionTransaction?: (transaction: PluginHookAdmissionTransaction) => void;
  223. readonly signal?: AbortSignal;
  224. }): Promise<PluginHookRunResult> {
  225. await this.drainExplicitSessionEndBeforeTurn(input.sessionId);
  226. const inherited = this.subagents.get(input.sessionId);
  227. if (inherited) return { decision: { decision: 'allow' }, diagnostics: [] };
  228. const idleEnd = this.idleEndTasks.get(input.sessionId);
  229. this.idleEndControllers.get(input.sessionId)?.abort('A new turn superseded idle SessionEnd');
  230. if (idleEnd) await idleEnd;
  231. const previousState = this.sessions.get(input.sessionId);
  232. const previousSnapshot = previousState ? snapshotSessionState(previousState) : undefined;
  233. const previousPendingStartSource = this.pendingSessionStartSources.get(input.sessionId);
  234. const wasEnded = this.endedSessions.has(input.sessionId);
  235. const wasKnownSession = previousState !== undefined;
  236. const isResume = this.endedSessions.delete(input.sessionId);
  237. const state = this.session(input.sessionId);
  238. let removedHandlersForCommit: readonly PluginHookCommandHandler[] = [];
  239. let admissionSettled = false;
  240. input.captureAdmissionTransaction?.({
  241. commit: async () => {
  242. if (admissionSettled) return;
  243. admissionSettled = true;
  244. if (removedHandlersForCommit.length > 0) {
  245. await cleanupPluginHookSessionArtifacts(removedHandlersForCommit, input.sessionId);
  246. }
  247. },
  248. rollback: async () => {
  249. if (admissionSettled) return;
  250. admissionSettled = true;
  251. await this.rollbackTurnAdmission({
  252. sessionId: input.sessionId,
  253. state,
  254. previousSnapshot,
  255. previousPendingStartSource,
  256. wasEnded,
  257. });
  258. },
  259. });
  260. if (input.sessionOwnershipClaim) state.sessionOwnershipClaim = input.sessionOwnershipClaim;
  261. if (input.transcriptCleanup) state.transcriptCleanup = input.transcriptCleanup;
  262. if (input.sessionEndCleanup) state.sessionEndCleanup = input.sessionEndCleanup;
  263. state.idleEpoch += 1;
  264. state.suspendedIdleSinceMs = state.idleSinceMs;
  265. state.idleSinceMs = undefined;
  266. state.turnActive = true;
  267. if (state.idleTimer) clearTimeout(state.idleTimer);
  268. state.idleTimer = undefined;
  269. this.idleEndControllers.delete(input.sessionId);
  270. state.idleEndController?.abort('A new turn superseded idle SessionEnd');
  271. state.idleEndController = undefined;
  272. const currentPlugins = groupByPlugin(input.handlers, input);
  273. const removedHandlers: PluginHookCommandHandler[] = [];
  274. for (const identity of [...state.plugins.keys()]) {
  275. if (currentPlugins.has(identity)) continue;
  276. const removed = state.plugins.get(identity);
  277. if (removed) removedHandlers.push(...removed.handlers);
  278. state.plugins.delete(identity);
  279. }
  280. if (removedHandlers.length > 0 && !input.captureAdmissionTransaction) {
  281. await cleanupPluginHookSessionArtifacts(removedHandlers, input.sessionId);
  282. } else {
  283. removedHandlersForCommit = removedHandlers;
  284. }
  285. const compactIdentities = state.pendingCompactPluginIdentities;
  286. const compacting = compactIdentities
  287. ? [...currentPlugins.entries()].filter(([identity]) => compactIdentities.has(identity))
  288. : [];
  289. const starting = [...currentPlugins.entries()].filter(
  290. ([identity]) => !state.plugins.has(identity) && !compactIdentities?.has(identity),
  291. );
  292. const pendingStartSource = this.pendingSessionStartSources.get(input.sessionId);
  293. this.pendingSessionStartSources.delete(input.sessionId);
  294. const startSource = resolveSessionStartSource(
  295. wasKnownSession,
  296. isResume || input.resumeExistingSession === true,
  297. pendingStartSource ?? (wasKnownSession ? undefined : input.sessionStartSource),
  298. );
  299. const startResults: PluginHookRunResult[] = [];
  300. let compactResult: PluginHookRunResult | undefined;
  301. if (compactIdentities) {
  302. state.pendingCompactPluginIdentities = undefined;
  303. if (compacting.length > 0) {
  304. compactResult = await this.runner.run(
  305. compacting.flatMap(([, plugin]) => plugin.handlers),
  306. eventInput('SessionStart', input, { source: 'compact' }, 'compact'),
  307. input.signal,
  308. );
  309. startResults.push(compactResult);
  310. if (stopsTurnLifecycle(compactResult)) {
  311. return mergeRunResults(startResults);
  312. }
  313. }
  314. }
  315. let activationResult: PluginHookRunResult | undefined;
  316. if (starting.length > 0) {
  317. activationResult = await this.runner.run(
  318. starting.flatMap(([, plugin]) => plugin.handlers),
  319. eventInput('SessionStart', input, { source: startSource }, startSource),
  320. input.signal,
  321. );
  322. startResults.push(activationResult);
  323. }
  324. const compactAborted = compactResult?.diagnostics.some(
  325. (diagnostic) => diagnostic.code === 'HOOK_ABORTED',
  326. );
  327. if (compactAborted && compactIdentities) {
  328. state.pendingCompactPluginIdentities = compactIdentities;
  329. }
  330. const activationAborted = activationResult?.diagnostics.some(
  331. (diagnostic) => diagnostic.code === 'HOOK_ABORTED',
  332. );
  333. for (const [identity, plugin] of currentPlugins) {
  334. if (state.plugins.has(identity) || !activationAborted) state.plugins.set(identity, plugin);
  335. }
  336. if (activationResult && stopsTurnLifecycle(activationResult)) {
  337. return mergeRunResults(startResults);
  338. }
  339. const promptResult = await this.runner.run(
  340. input.handlers,
  341. eventInput('UserPromptSubmit', input, { prompt: input.prompt }),
  342. input.signal,
  343. );
  344. return mergeRunResults([...startResults, promptResult]);
  345. }
  346. runEvent(
  347. handlers: readonly PluginHookCommandHandler[],
  348. input: PluginHookEventInput,
  349. signal?: AbortSignal,
  350. ): Promise<PluginHookRunResult> {
  351. const inherited = this.subagents.get(input.sessionId);
  352. if (!inherited) return this.runner.run(handlers, input, signal);
  353. return this.runner.run(
  354. inherited.handlers,
  355. {
  356. ...input,
  357. promptId: inherited.parentPromptId ?? inherited.parentTurnId,
  358. model: input.model ?? inherited.model,
  359. permissionMode: input.permissionMode ?? inherited.permissionMode,
  360. effort: input.effort ?? inherited.effort,
  361. subagentContext: registrationSubagentContext(inherited),
  362. payload: {
  363. ...(input.payload ?? {}),
  364. agent_id: inherited.agentId,
  365. agent_type: inherited.agentType,
  366. },
  367. },
  368. signal,
  369. );
  370. }
  371. async finishTurn(input: {
  372. readonly handlers: readonly PluginHookCommandHandler[];
  373. readonly sessionId: string;
  374. readonly turnId: string;
  375. readonly cwd: string;
  376. readonly transcriptPath?: string | null;
  377. readonly codexTranscriptPath?: string | null;
  378. readonly model?: string;
  379. readonly permissionMode?: string;
  380. readonly effort?: PluginHookEventInput['effort'];
  381. readonly promptId?: string;
  382. readonly stopHookActive?: boolean;
  383. readonly lastAssistantMessage?: string | null;
  384. readonly signal?: AbortSignal;
  385. }): Promise<PluginHookRunResult> {
  386. const inherited = this.subagents.get(input.sessionId);
  387. const hookInput = inherited
  388. ? {
  389. event: 'SubagentStop' as const,
  390. sessionId: input.sessionId,
  391. turnId: input.turnId,
  392. transcriptPath: inherited.agentTranscriptPath,
  393. codexTranscriptPath: inherited.agentCodexTranscriptPath,
  394. promptId: inherited.parentPromptId ?? inherited.parentTurnId,
  395. subagentContext: registrationSubagentContext(inherited),
  396. cwd: input.cwd,
  397. model: input.model ?? inherited.model,
  398. permissionMode: input.permissionMode ?? inherited.permissionMode,
  399. effort: input.effort ?? inherited.effort,
  400. matcherValue: inherited.agentType,
  401. payload: {
  402. stop_hook_active: input.stopHookActive ?? false,
  403. agent_id: inherited.agentId,
  404. agent_type: inherited.agentType,
  405. agent_transcript_path: inherited.agentTranscriptPath ?? null,
  406. last_assistant_message: input.lastAssistantMessage ?? null,
  407. },
  408. }
  409. : eventInput('Stop', input, {
  410. stop_hook_active: input.stopHookActive ?? false,
  411. last_assistant_message: input.lastAssistantMessage ?? null,
  412. });
  413. const result = await this.runner.run(
  414. inherited?.handlers ?? input.handlers,
  415. hookInput,
  416. input.signal,
  417. );
  418. return result;
  419. }
  420. completeTurn(sessionId: string): void {
  421. if (this.subagents.has(sessionId)) {
  422. this.releaseSubagent(sessionId);
  423. return;
  424. }
  425. const state = this.sessions.get(sessionId);
  426. if (state) {
  427. state.turnActive = false;
  428. state.suspendedIdleSinceMs = undefined;
  429. state.idleSinceMs = Date.now();
  430. const pending = state.pendingSessionEnd;
  431. this.scheduleSessionEnd(
  432. sessionId,
  433. state,
  434. pending ? SESSION_END_FENCE_RETRY_MS : SESSION_IDLE_MS,
  435. pending?.reason ?? 'idle_timeout',
  436. pending?.enabledPluginNames,
  437. );
  438. }
  439. }
  440. /** Suspends idle SessionEnd while a process-local compaction is active. */
  441. beginSessionActivity(sessionId: string, _turnId: string): void {
  442. const state = this.sessions.get(sessionId);
  443. if (!state) return;
  444. state.idleEpoch += 1;
  445. state.suspendedIdleSinceMs = state.idleSinceMs;
  446. state.idleSinceMs = undefined;
  447. state.turnActive = true;
  448. if (state.idleTimer) clearTimeout(state.idleTimer);
  449. state.idleTimer = undefined;
  450. }
  451. completeSessionActivity(sessionId: string): void {
  452. this.completeTurn(sessionId);
  453. }
  454. /** Restores the previous idle anchor after a denied, aborted, or failed turn. */
  455. resumeIdleCountdown(sessionId: string): void {
  456. if (this.subagents.has(sessionId)) return;
  457. const state = this.sessions.get(sessionId);
  458. if (!state) return;
  459. state.turnActive = false;
  460. if (state.idleSinceMs === undefined) {
  461. state.idleSinceMs = state.suspendedIdleSinceMs ?? Date.now();
  462. }
  463. state.suspendedIdleSinceMs = undefined;
  464. if (this.hasActiveDescendantExecutions(sessionId)) return;
  465. const pending = state.pendingSessionEnd;
  466. const remainingMs = pending
  467. ? SESSION_END_FENCE_RETRY_MS
  468. : Math.max(0, state.idleSinceMs + SESSION_IDLE_MS - Date.now());
  469. this.scheduleSessionEnd(
  470. sessionId,
  471. state,
  472. remainingMs,
  473. pending?.reason ?? 'idle_timeout',
  474. pending?.enabledPluginNames,
  475. );
  476. }
  477. markCompacted(sessionId: string, handlers: readonly PluginHookCommandHandler[]): void {
  478. this.session(sessionId).pendingCompactPluginIdentities = new Set(handlers.map(pluginIdentity));
  479. }
  480. admitAutomaticCompaction(sessionId: string, requestedDefer: boolean): boolean {
  481. const forced = this.forcedAutomaticCompactions.delete(sessionId);
  482. if (!requestedDefer) return true;
  483. if (forced) return true;
  484. this.forcedAutomaticCompactions.add(sessionId);
  485. return false;
  486. }
  487. completeAutomaticCompaction(sessionId: string): void {
  488. this.forcedAutomaticCompactions.delete(sessionId);
  489. }
  490. clearAutomaticCompactionDeferral(sessionId: string): void {
  491. this.forcedAutomaticCompactions.delete(sessionId);
  492. }
  493. handlersForTurn(
  494. sessionId: string,
  495. fallback: readonly PluginHookCommandHandler[],
  496. ): readonly PluginHookCommandHandler[] {
  497. return this.subagents.get(sessionId)?.handlers ?? fallback;
  498. }
  499. async startSubagent(
  500. registration: PluginSubagentRegistration,
  501. signal?: AbortSignal,
  502. ): Promise<PluginHookDecision> {
  503. this.subagents.set(registration.childSessionId, registration);
  504. const result = await this.runner.run(
  505. registration.handlers,
  506. {
  507. event: 'SubagentStart',
  508. sessionId: registration.childSessionId,
  509. turnId: registration.childTurnId,
  510. promptId: registration.parentPromptId ?? registration.parentTurnId,
  511. transcriptPath: registration.agentTranscriptPath,
  512. codexTranscriptPath: registration.agentCodexTranscriptPath,
  513. subagentContext: registrationSubagentContext(registration),
  514. cwd: registration.cwd,
  515. model: registration.model,
  516. permissionMode: registration.permissionMode,
  517. effort: registration.effort,
  518. matcherValue: registration.agentType,
  519. payload: {
  520. agent_id: registration.agentId,
  521. agent_type: registration.agentType,
  522. },
  523. },
  524. signal,
  525. );
  526. return result.decision;
  527. }
  528. cancelSubagent(childSessionId: string): void {
  529. this.releaseSubagent(childSessionId);
  530. }
  531. async endSession(
  532. sessionId: string,
  533. reason: PluginHookSessionEndReason,
  534. signal?: AbortSignal,
  535. enabledPluginNames?: ReadonlySet<string>,
  536. ): Promise<PluginHookRunResult | undefined> {
  537. if (reason !== 'idle_timeout') {
  538. const current = this.explicitEndTasks.get(sessionId);
  539. if (current) return current;
  540. const controller = new AbortController();
  541. this.explicitEndControllers.set(sessionId, controller);
  542. const task = this.performSessionEnd(
  543. sessionId,
  544. reason,
  545. combineAbortSignals(signal, controller.signal),
  546. enabledPluginNames,
  547. ).finally(() => {
  548. if (this.explicitEndTasks.get(sessionId) === task) {
  549. this.explicitEndTasks.delete(sessionId);
  550. }
  551. if (this.explicitEndControllers.get(sessionId) === controller) {
  552. this.explicitEndControllers.delete(sessionId);
  553. }
  554. });
  555. this.explicitEndTasks.set(sessionId, task);
  556. return task;
  557. }
  558. return this.performSessionEnd(sessionId, reason, signal, enabledPluginNames);
  559. }
  560. private async performSessionEnd(
  561. sessionId: string,
  562. reason: PluginHookSessionEndReason,
  563. signal?: AbortSignal,
  564. enabledPluginNames?: ReadonlySet<string>,
  565. ): Promise<PluginHookRunResult | undefined> {
  566. const state = this.sessions.get(sessionId);
  567. if (!state) return;
  568. if (reason !== 'idle_timeout' && !state.pendingSessionEnd) {
  569. state.pendingSessionEnd = {
  570. reason,
  571. ...(enabledPluginNames ? { enabledPluginNames: new Set(enabledPluginNames) } : {}),
  572. };
  573. }
  574. const pending = state.pendingSessionEnd;
  575. const effectiveReason = pending?.reason ?? reason;
  576. const effectiveEnabledPluginNames = pending?.enabledPluginNames ?? enabledPluginNames;
  577. // An explicit lifecycle action is allowed to return before an active Turn
  578. // drains, but SessionEnd itself must not run concurrently with that Turn.
  579. // Keep retrying the request; completeTurn/resumeIdleCountdown will also
  580. // promptly re-arm it when the local Turn actually releases.
  581. if (
  582. effectiveReason !== 'idle_timeout' &&
  583. (state.turnActive || this.hasActiveDescendantExecutions(sessionId))
  584. ) {
  585. this.scheduleSessionEnd(
  586. sessionId,
  587. state,
  588. SESSION_END_FENCE_RETRY_MS,
  589. effectiveReason,
  590. effectiveEnabledPluginNames,
  591. );
  592. return undefined;
  593. }
  594. const operation = (fenceSignal?: AbortSignal) =>
  595. this.finishSessionEnd(
  596. sessionId,
  597. state,
  598. effectiveReason,
  599. combineAbortSignals(signal, fenceSignal),
  600. effectiveEnabledPluginNames,
  601. );
  602. if (!this.sessionEndFence) return operation();
  603. let outcome: Awaited<ReturnType<PluginHookSessionEndFence['run']>>;
  604. try {
  605. outcome = await this.sessionEndFence.run({
  606. sessionId,
  607. reason: effectiveReason,
  608. ...(state.idleSinceMs !== undefined ? { idleSinceMs: state.idleSinceMs } : {}),
  609. ...(state.sessionOwnershipClaim
  610. ? { sessionOwnershipClaim: state.sessionOwnershipClaim }
  611. : {}),
  612. operation,
  613. });
  614. } catch {
  615. outcome = { status: 'deferred' };
  616. }
  617. if (outcome.status === 'executed') return outcome.result;
  618. if (outcome.status === 'superseded') {
  619. await this.abandonSupersededSession(sessionId, state);
  620. return undefined;
  621. }
  622. if (this.sessions.get(sessionId) === state) {
  623. if (outcome.latestActivityAtMs !== undefined) {
  624. state.idleSinceMs = Math.max(state.idleSinceMs ?? 0, outcome.latestActivityAtMs);
  625. }
  626. const delayMs =
  627. effectiveReason === 'idle_timeout' && state.idleSinceMs !== undefined
  628. ? Math.max(SESSION_END_FENCE_RETRY_MS, state.idleSinceMs + SESSION_IDLE_MS - Date.now())
  629. : SESSION_END_FENCE_RETRY_MS;
  630. if (effectiveReason !== 'idle_timeout' || !state.turnActive) {
  631. this.scheduleSessionEnd(
  632. sessionId,
  633. state,
  634. delayMs,
  635. effectiveReason,
  636. effectiveEnabledPluginNames,
  637. );
  638. }
  639. }
  640. return undefined;
  641. }
  642. private async finishSessionEnd(
  643. sessionId: string,
  644. state: SessionState,
  645. reason: PluginHookSessionEndReason,
  646. signal: AbortSignal | undefined,
  647. enabledPluginNames: ReadonlySet<string> | undefined,
  648. ): Promise<PluginHookRunResult | undefined> {
  649. if (this.sessions.get(sessionId) !== state) return undefined;
  650. this.sessions.delete(sessionId);
  651. this.forcedAutomaticCompactions.delete(sessionId);
  652. this.markEnded(sessionId);
  653. if (state.idleTimer) clearTimeout(state.idleTimer);
  654. if (reason !== 'idle_timeout' && state.idleEndController) {
  655. state.idleEndController.abort('Session ended explicitly');
  656. }
  657. state.idleSinceMs = undefined;
  658. const enabled = enabledPluginNames ?? this.resolveEnabledPluginNames?.();
  659. const plugins = [...state.plugins.values()].filter(
  660. (plugin) => !enabled || enabled.has(plugin.pluginName),
  661. );
  662. const firstPlugin = plugins[0];
  663. let result: PluginHookRunResult | undefined;
  664. try {
  665. if (firstPlugin) {
  666. result = await this.runner.run(
  667. plugins.flatMap((plugin) => plugin.handlers),
  668. {
  669. event: 'SessionEnd',
  670. sessionId,
  671. transcriptPath: firstPlugin.transcriptPath,
  672. codexTranscriptPath: firstPlugin.codexTranscriptPath,
  673. cwd: firstPlugin.cwd,
  674. model: firstPlugin.model,
  675. permissionMode: firstPlugin.permissionMode,
  676. effort: firstPlugin.effort,
  677. promptId: firstPlugin.promptId,
  678. matcherValue: reason,
  679. payload: { reason },
  680. },
  681. signal,
  682. );
  683. }
  684. } finally {
  685. await this.reportSessionEndResult(sessionId, result);
  686. await cleanupSessionResources(state, sessionId);
  687. const idleController = this.idleEndControllers.get(sessionId);
  688. if (idleController?.signal === signal) this.idleEndControllers.delete(sessionId);
  689. }
  690. return result;
  691. }
  692. private async abandonSupersededSession(sessionId: string, state: SessionState): Promise<void> {
  693. if (this.sessions.get(sessionId) !== state) return;
  694. this.sessions.delete(sessionId);
  695. this.forcedAutomaticCompactions.delete(sessionId);
  696. this.markEnded(sessionId);
  697. if (state.idleTimer) clearTimeout(state.idleTimer);
  698. // The newer owner owns the logical SessionEnd command, but it cannot clear
  699. // Session-scoped permissions held in this stale process.
  700. await this.reportSessionEndResult(sessionId, undefined);
  701. await cleanupSessionResources(state, sessionId);
  702. }
  703. /**
  704. * Runs an idle SessionEnd as a cancellable admission fence. A new turn for
  705. * the same session aborts and drains this task before SessionStart, avoiding
  706. * overlapping old-session cleanup with a resumed turn.
  707. */
  708. async endIdleSession(
  709. sessionId: string,
  710. signal?: AbortSignal,
  711. enabledPluginNames?: ReadonlySet<string>,
  712. ): Promise<void> {
  713. const current = this.idleEndTasks.get(sessionId);
  714. if (current) return current;
  715. const state = this.sessions.get(sessionId);
  716. if (!state || state.turnActive || this.hasActiveDescendantExecutions(sessionId)) return;
  717. const controller = new AbortController();
  718. const abort = () => controller.abort(signal?.reason);
  719. if (signal?.aborted) abort();
  720. else signal?.addEventListener('abort', abort, { once: true });
  721. state.idleEndController = controller;
  722. this.idleEndControllers.set(sessionId, controller);
  723. const task = this.endSession(
  724. sessionId,
  725. 'idle_timeout',
  726. controller.signal,
  727. enabledPluginNames,
  728. ).then(() => undefined);
  729. this.idleEndTasks.set(sessionId, task);
  730. try {
  731. await task;
  732. } finally {
  733. signal?.removeEventListener('abort', abort);
  734. if (this.idleEndTasks.get(sessionId) === task) this.idleEndTasks.delete(sessionId);
  735. if (this.idleEndControllers.get(sessionId) === controller) {
  736. this.idleEndControllers.delete(sessionId);
  737. }
  738. }
  739. }
  740. /**
  741. * Ends the idle sessions owned by one sandbox release fence without
  742. * creating an unbounded burst of Hook processes. The shared deadline is a
  743. * release budget, not a per-session extension: remaining sessions are left
  744. * for the sandbox teardown once the budget expires.
  745. */
  746. async endIdleSessions(
  747. sessionIds: readonly string[],
  748. signal?: AbortSignal,
  749. enabledPluginNames?: ReadonlySet<string>,
  750. ): Promise<void> {
  751. const pendingSessions = [...new Set(sessionIds)].flatMap((sessionId) => {
  752. const state = this.sessions.get(sessionId);
  753. return state ? [{ sessionId, state, idleEpoch: state.idleEpoch }] : [];
  754. });
  755. const controller = new AbortController();
  756. const abort = () => controller.abort(signal?.reason);
  757. if (signal?.aborted) abort();
  758. else signal?.addEventListener('abort', abort, { once: true });
  759. const timer = setTimeout(
  760. () => controller.abort('Plugin SessionEnd release deadline exceeded'),
  761. SESSION_END_BUDGET_MS,
  762. );
  763. let cursor = 0;
  764. try {
  765. await Promise.all(
  766. Array.from(
  767. { length: Math.min(SESSION_END_CONCURRENCY, pendingSessions.length) },
  768. async () => {
  769. while (cursor < pendingSessions.length && !controller.signal.aborted) {
  770. const candidate = pendingSessions[cursor];
  771. cursor += 1;
  772. if (!candidate) continue;
  773. const current = this.sessions.get(candidate.sessionId);
  774. if (
  775. current !== candidate.state ||
  776. current.idleEpoch !== candidate.idleEpoch ||
  777. current.turnActive ||
  778. this.hasActiveDescendantExecutions(candidate.sessionId)
  779. ) {
  780. continue;
  781. }
  782. await this.endIdleSession(candidate.sessionId, controller.signal, enabledPluginNames);
  783. }
  784. },
  785. ),
  786. );
  787. } finally {
  788. clearTimeout(timer);
  789. signal?.removeEventListener('abort', abort);
  790. }
  791. }
  792. async endAllSessions(
  793. reason: 'logout',
  794. signal?: AbortSignal,
  795. enabledPluginNames?: ReadonlySet<string>,
  796. ): Promise<void> {
  797. const sessionIds = [...this.sessions.keys()];
  798. const controller = new AbortController();
  799. const abort = () => controller.abort(signal?.reason);
  800. signal?.addEventListener('abort', abort, { once: true });
  801. if (signal?.aborted) abort();
  802. const timer = setTimeout(
  803. () => controller.abort('Plugin SessionEnd total deadline exceeded'),
  804. SESSION_END_BUDGET_MS,
  805. );
  806. let cursor = 0;
  807. try {
  808. await Promise.all(
  809. Array.from({ length: Math.min(SESSION_END_CONCURRENCY, sessionIds.length) }, async () => {
  810. while (cursor < sessionIds.length && !controller.signal.aborted) {
  811. const sessionId = sessionIds[cursor];
  812. cursor += 1;
  813. if (sessionId) {
  814. await this.endSession(sessionId, reason, controller.signal, enabledPluginNames);
  815. }
  816. }
  817. }),
  818. );
  819. } finally {
  820. clearTimeout(timer);
  821. signal?.removeEventListener('abort', abort);
  822. this.pruneSubagentsWithoutActiveRoot();
  823. // The foreground logout sweep has a fixed UX budget. Every session still
  824. // present (active, deferred, or not reached by a worker) must retry in
  825. // the background with its original explicit reason; deleting it would
  826. // skip both SessionEnd and session-permission cleanup.
  827. for (const sessionId of sessionIds) {
  828. const state = this.sessions.get(sessionId);
  829. if (!state) continue;
  830. if (!state.pendingSessionEnd) {
  831. state.pendingSessionEnd = {
  832. reason,
  833. ...(enabledPluginNames ? { enabledPluginNames: new Set(enabledPluginNames) } : {}),
  834. };
  835. }
  836. this.scheduleSessionEnd(
  837. sessionId,
  838. state,
  839. SESSION_END_FENCE_RETRY_MS,
  840. state.pendingSessionEnd.reason,
  841. state.pendingSessionEnd.enabledPluginNames,
  842. );
  843. }
  844. }
  845. }
  846. async dispose(): Promise<void> {
  847. const sessionStates = [...this.sessions].map(([sessionId, state]) => ({ sessionId, state }));
  848. for (const state of this.sessions.values()) if (state.idleTimer) clearTimeout(state.idleTimer);
  849. for (const state of this.sessions.values()) state.idleEndController?.abort('disposed');
  850. for (const controller of this.idleEndControllers.values()) controller.abort('disposed');
  851. for (const controller of this.explicitEndControllers.values()) controller.abort('disposed');
  852. await Promise.allSettled([...this.idleEndTasks.values(), ...this.explicitEndTasks.values()]);
  853. this.sessions.clear();
  854. this.endedSessions.clear();
  855. this.subagents.clear();
  856. this.idleEndControllers.clear();
  857. this.idleEndTasks.clear();
  858. this.explicitEndControllers.clear();
  859. this.explicitEndTasks.clear();
  860. this.forcedAutomaticCompactions.clear();
  861. this.pendingSessionStartSources.clear();
  862. this.resolveEnabledPluginNames = undefined;
  863. this.sessionEndFence = undefined;
  864. await Promise.allSettled(
  865. sessionStates.map((state) => cleanupSessionResources(state.state, state.sessionId)),
  866. );
  867. await this.runner.dispose();
  868. }
  869. private session(sessionId: string): SessionState {
  870. const current = this.sessions.get(sessionId);
  871. if (current) return current;
  872. const created: SessionState = { plugins: new Map(), idleEpoch: 0, turnActive: false };
  873. this.sessions.set(sessionId, created);
  874. return created;
  875. }
  876. private async drainExplicitSessionEndBeforeTurn(sessionId: string): Promise<void> {
  877. const current = this.explicitEndTasks.get(sessionId);
  878. if (current) {
  879. this.explicitEndControllers
  880. .get(sessionId)
  881. ?.abort('A new turn is waiting for explicit SessionEnd cleanup');
  882. const drained = await settlesWithin(current, SESSION_END_RESUME_DRAIN_BUDGET_MS);
  883. if (!drained) {
  884. throw new Error(`Previous Plugin SessionEnd is still finalizing: ${sessionId}`);
  885. }
  886. }
  887. if (this.sessions.get(sessionId)?.pendingSessionEnd) {
  888. // A prior explicit request was deferred while its Turn drained. Its retry
  889. // owns SessionEnd; admitting a replacement Turn here could starve that
  890. // retry and overlap old Session cleanup with the new session generation.
  891. throw new Error(`Previous Plugin SessionEnd is pending: ${sessionId}`);
  892. }
  893. }
  894. private async rollbackTurnAdmission(input: {
  895. readonly sessionId: string;
  896. readonly state: SessionState;
  897. readonly previousSnapshot?: SessionState;
  898. readonly previousPendingStartSource?: Exclude<
  899. PluginHookSessionStartSource,
  900. 'compact' | 'plugin_activation'
  901. >;
  902. readonly wasEnded: boolean;
  903. }): Promise<void> {
  904. if (this.sessions.get(input.sessionId) !== input.state) return;
  905. if (input.state.idleTimer) clearTimeout(input.state.idleTimer);
  906. input.state.idleEndController?.abort('Plugin Hook admission rolled back');
  907. this.idleEndControllers.get(input.sessionId)?.abort('Plugin Hook admission rolled back');
  908. this.idleEndControllers.delete(input.sessionId);
  909. const currentHandlers = [...input.state.plugins.entries()]
  910. .filter(([identity]) => !input.previousSnapshot?.plugins.has(identity))
  911. .flatMap(([, plugin]) => plugin.handlers);
  912. const currentTranscriptCleanup = input.state.transcriptCleanup;
  913. const previousTranscriptCleanup = input.previousSnapshot?.transcriptCleanup;
  914. await Promise.allSettled([
  915. ...(currentTranscriptCleanup && currentTranscriptCleanup !== previousTranscriptCleanup
  916. ? [Promise.resolve().then(currentTranscriptCleanup)]
  917. : []),
  918. ...(currentHandlers.length > 0
  919. ? [cleanupPluginHookSessionArtifacts(currentHandlers, input.sessionId)]
  920. : []),
  921. ]);
  922. if (input.previousSnapshot) {
  923. const pendingSessionEnd =
  924. input.state.pendingSessionEnd ?? input.previousSnapshot.pendingSessionEnd;
  925. const restored = snapshotSessionState(input.previousSnapshot);
  926. restored.idleTimer = undefined;
  927. restored.idleEndController = undefined;
  928. if (pendingSessionEnd) restored.pendingSessionEnd = pendingSessionEnd;
  929. this.sessions.set(input.sessionId, restored);
  930. } else {
  931. this.sessions.delete(input.sessionId);
  932. }
  933. if (!this.pendingSessionStartSources.has(input.sessionId) && input.previousPendingStartSource) {
  934. this.pendingSessionStartSources.set(input.sessionId, input.previousPendingStartSource);
  935. }
  936. if (input.wasEnded) this.markEnded(input.sessionId);
  937. else this.endedSessions.delete(input.sessionId);
  938. }
  939. private pruneSubagentsWithoutActiveRoot(): void {
  940. for (const childSessionId of this.subagents.keys()) {
  941. let registration = this.subagents.get(childSessionId);
  942. const visited = new Set<string>([childSessionId]);
  943. let retained = false;
  944. while (registration) {
  945. if (this.sessions.has(registration.parentSessionId)) {
  946. retained = true;
  947. break;
  948. }
  949. if (visited.has(registration.parentSessionId)) break;
  950. visited.add(registration.parentSessionId);
  951. registration = this.subagents.get(registration.parentSessionId);
  952. }
  953. if (!retained) this.subagents.delete(childSessionId);
  954. }
  955. }
  956. private markEnded(sessionId: string): void {
  957. this.endedSessions.delete(sessionId);
  958. this.endedSessions.add(sessionId);
  959. if (this.endedSessions.size <= MAX_RESUMABLE_SESSION_MARKERS) return;
  960. const oldest = this.endedSessions.values().next().value as string | undefined;
  961. if (oldest) this.endedSessions.delete(oldest);
  962. }
  963. private releaseSubagent(childSessionId: string): void {
  964. const registration = this.subagents.get(childSessionId);
  965. if (!registration) return;
  966. this.subagents.delete(childSessionId);
  967. for (const [descendantId, descendant] of this.subagents) {
  968. if (descendant.parentSessionId !== childSessionId) continue;
  969. this.subagents.set(descendantId, {
  970. ...descendant,
  971. parentSessionId: registration.parentSessionId,
  972. parentTurnId: registration.parentTurnId,
  973. });
  974. }
  975. const parent = this.sessions.get(registration.parentSessionId);
  976. if (!parent || parent.turnActive || parent.idleSinceMs === undefined) return;
  977. const pending = parent.pendingSessionEnd;
  978. const remainingMs = pending
  979. ? SESSION_END_FENCE_RETRY_MS
  980. : Math.max(0, parent.idleSinceMs + SESSION_IDLE_MS - Date.now());
  981. this.scheduleSessionEnd(
  982. registration.parentSessionId,
  983. parent,
  984. remainingMs,
  985. pending?.reason ?? 'idle_timeout',
  986. pending?.enabledPluginNames,
  987. );
  988. }
  989. private scheduleSessionEnd(
  990. sessionId: string,
  991. state: SessionState,
  992. delayMs: number,
  993. reason: PluginHookSessionEndReason,
  994. enabledPluginNames?: ReadonlySet<string>,
  995. ): void {
  996. if (state.idleTimer) clearTimeout(state.idleTimer);
  997. if (!this.automaticIdleSessionEnd && reason === 'idle_timeout') {
  998. state.idleTimer = undefined;
  999. return;
  1000. }
  1001. if ([...this.subagents.values()].some((child) => child.parentSessionId === sessionId)) {
  1002. state.idleTimer = undefined;
  1003. return;
  1004. }
  1005. const epoch = ++state.idleEpoch;
  1006. state.idleTimer = setTimeout(() => {
  1007. if (this.sessions.get(sessionId) !== state || state.idleEpoch !== epoch) return;
  1008. void (reason === 'idle_timeout'
  1009. ? this.endIdleSession(
  1010. sessionId,
  1011. undefined,
  1012. enabledPluginNames ?? this.resolveEnabledPluginNames?.(),
  1013. )
  1014. : this.endSession(
  1015. sessionId,
  1016. reason,
  1017. undefined,
  1018. enabledPluginNames ?? this.resolveEnabledPluginNames?.(),
  1019. ));
  1020. }, delayMs);
  1021. state.idleTimer.unref?.();
  1022. }
  1023. private async reportSessionEndResult(
  1024. sessionId: string,
  1025. result: PluginHookRunResult | undefined,
  1026. ): Promise<void> {
  1027. if (!this.onSessionEndResult) return;
  1028. try {
  1029. await settleWithin(
  1030. Promise.resolve(this.onSessionEndResult({ sessionId, ...(result ? { result } : {}) })),
  1031. SESSION_END_REPORT_BUDGET_MS,
  1032. );
  1033. } catch {
  1034. // User-visible diagnostics are best-effort and must never fail teardown.
  1035. }
  1036. }
  1037. }
  1038. function combineAbortSignals(
  1039. caller: AbortSignal | undefined,
  1040. fence: AbortSignal | undefined,
  1041. ): AbortSignal | undefined {
  1042. if (!caller) return fence;
  1043. if (!fence) return caller;
  1044. return AbortSignal.any([caller, fence]);
  1045. }
  1046. async function settleWithin(value: Promise<unknown>, timeoutMs: number): Promise<void> {
  1047. let timer: ReturnType<typeof setTimeout> | undefined;
  1048. await Promise.race([
  1049. value.then(
  1050. () => undefined,
  1051. () => undefined,
  1052. ),
  1053. new Promise<void>((resolve) => {
  1054. timer = setTimeout(resolve, timeoutMs);
  1055. timer.unref?.();
  1056. }),
  1057. ]);
  1058. if (timer) clearTimeout(timer);
  1059. }
  1060. async function settlesWithin(value: Promise<unknown>, timeoutMs: number): Promise<boolean> {
  1061. let timer: ReturnType<typeof setTimeout> | undefined;
  1062. try {
  1063. return await Promise.race([
  1064. value.then(
  1065. () => true,
  1066. () => true,
  1067. ),
  1068. new Promise<boolean>((resolve) => {
  1069. timer = setTimeout(() => resolve(false), timeoutMs);
  1070. timer.unref?.();
  1071. }),
  1072. ]);
  1073. } finally {
  1074. if (timer) clearTimeout(timer);
  1075. }
  1076. }
  1077. async function cleanupSessionResources(state: SessionState, sessionId: string): Promise<void> {
  1078. const cleanup = state.transcriptCleanup;
  1079. state.transcriptCleanup = undefined;
  1080. const sessionEndCleanup = state.sessionEndCleanup;
  1081. state.sessionEndCleanup = undefined;
  1082. const handlers = [...state.plugins.values()].flatMap((plugin) => plugin.handlers);
  1083. await Promise.allSettled([
  1084. ...(cleanup ? [Promise.resolve().then(cleanup)] : []),
  1085. ...(sessionEndCleanup ? [Promise.resolve().then(sessionEndCleanup)] : []),
  1086. cleanupPluginHookSessionArtifacts(handlers, sessionId),
  1087. ]);
  1088. }
  1089. function snapshotSessionState(state: SessionState): SessionState {
  1090. return {
  1091. plugins: new Map(state.plugins),
  1092. ...(state.sessionOwnershipClaim ? { sessionOwnershipClaim: state.sessionOwnershipClaim } : {}),
  1093. ...(state.pendingSessionEnd
  1094. ? {
  1095. pendingSessionEnd: {
  1096. reason: state.pendingSessionEnd.reason,
  1097. ...(state.pendingSessionEnd.enabledPluginNames
  1098. ? { enabledPluginNames: new Set(state.pendingSessionEnd.enabledPluginNames) }
  1099. : {}),
  1100. },
  1101. }
  1102. : {}),
  1103. ...(state.transcriptCleanup ? { transcriptCleanup: state.transcriptCleanup } : {}),
  1104. ...(state.sessionEndCleanup ? { sessionEndCleanup: state.sessionEndCleanup } : {}),
  1105. ...(state.pendingCompactPluginIdentities
  1106. ? { pendingCompactPluginIdentities: new Set(state.pendingCompactPluginIdentities) }
  1107. : {}),
  1108. ...(state.idleSinceMs !== undefined ? { idleSinceMs: state.idleSinceMs } : {}),
  1109. ...(state.suspendedIdleSinceMs !== undefined
  1110. ? { suspendedIdleSinceMs: state.suspendedIdleSinceMs }
  1111. : {}),
  1112. turnActive: state.turnActive,
  1113. ...(state.idleTimer ? { idleTimer: state.idleTimer } : {}),
  1114. idleEpoch: state.idleEpoch,
  1115. ...(state.idleEndController ? { idleEndController: state.idleEndController } : {}),
  1116. };
  1117. }
  1118. function registrationSubagentContext(
  1119. registration: PluginSubagentRegistration,
  1120. ): NonNullable<PluginHookEventInput['subagentContext']> {
  1121. return {
  1122. parentSessionId: registration.parentSessionId,
  1123. parentTurnId: registration.parentTurnId,
  1124. parentTranscriptPath: registration.parentTranscriptPath,
  1125. parentCodexTranscriptPath: registration.parentCodexTranscriptPath,
  1126. childSessionId: registration.childSessionId,
  1127. childTranscriptPath: registration.agentTranscriptPath,
  1128. childCodexTranscriptPath: registration.agentCodexTranscriptPath,
  1129. };
  1130. }
  1131. function stopsTurnLifecycle(result: PluginHookRunResult): boolean {
  1132. return result.decision.continue === false || result.decision.decision === 'deny';
  1133. }
  1134. function resolveSessionStartSource(
  1135. wasKnownSession: boolean,
  1136. isResume: boolean,
  1137. explicitSource?: Exclude<PluginHookSessionStartSource, 'compact' | 'plugin_activation'>,
  1138. ): PluginHookSessionStartSource {
  1139. if (explicitSource) return explicitSource;
  1140. if (wasKnownSession) return 'plugin_activation';
  1141. return isResume ? 'resume' : 'startup';
  1142. }
  1143. function groupByPlugin(
  1144. handlers: readonly PluginHookCommandHandler[],
  1145. runtime: {
  1146. readonly cwd: string;
  1147. readonly transcriptPath?: string | null;
  1148. readonly codexTranscriptPath?: string | null;
  1149. readonly model?: string;
  1150. readonly permissionMode?: string;
  1151. readonly effort?: PluginHookEventInput['effort'];
  1152. readonly promptId?: string;
  1153. },
  1154. ): Map<string, ActivePlugin> {
  1155. const grouped = new Map<string, PluginHookCommandHandler[]>();
  1156. for (const handler of handlers) {
  1157. const identity = pluginIdentity(handler);
  1158. const values = grouped.get(identity) ?? [];
  1159. values.push(handler);
  1160. grouped.set(identity, values);
  1161. }
  1162. const result = new Map<string, ActivePlugin>();
  1163. for (const [identity, values] of grouped) {
  1164. const first = values[0];
  1165. if (first) {
  1166. result.set(identity, {
  1167. pluginName: first.pluginName,
  1168. handlers: values,
  1169. cwd: runtime.cwd,
  1170. transcriptPath: runtime.transcriptPath,
  1171. codexTranscriptPath: runtime.codexTranscriptPath,
  1172. model: runtime.model,
  1173. permissionMode: runtime.permissionMode,
  1174. effort: runtime.effort,
  1175. promptId: runtime.promptId,
  1176. });
  1177. }
  1178. }
  1179. return result;
  1180. }
  1181. function pluginIdentity(handler: PluginHookCommandHandler): string {
  1182. return JSON.stringify([handler.pluginName, handler.pluginRoot, handler.activationKey ?? '']);
  1183. }
  1184. function mergeRunResults(results: readonly PluginHookRunResult[]): PluginHookRunResult {
  1185. const decision = results.reduce(
  1186. (current, result) => mergePluginHookDecisions(current, result.decision),
  1187. { decision: 'allow' } as PluginHookDecision,
  1188. );
  1189. return {
  1190. decision,
  1191. diagnostics: results.flatMap((result) => result.diagnostics),
  1192. };
  1193. }
  1194. function eventInput(
  1195. event: PluginHookEventInput['event'],
  1196. input: {
  1197. readonly sessionId: string;
  1198. readonly turnId: string;
  1199. readonly cwd: string;
  1200. readonly transcriptPath?: string | null;
  1201. readonly codexTranscriptPath?: string | null;
  1202. readonly model?: string;
  1203. readonly permissionMode?: string;
  1204. readonly effort?: PluginHookEventInput['effort'];
  1205. readonly promptId?: string;
  1206. },
  1207. payload: Readonly<Record<string, unknown>>,
  1208. matcherValue?: string,
  1209. ): PluginHookEventInput {
  1210. return {
  1211. event,
  1212. sessionId: input.sessionId,
  1213. turnId: input.turnId,
  1214. transcriptPath: input.transcriptPath,
  1215. codexTranscriptPath: input.codexTranscriptPath,
  1216. cwd: input.cwd,
  1217. model: input.model,
  1218. permissionMode: input.permissionMode,
  1219. effort: input.effort,
  1220. promptId: input.promptId,
  1221. ...(matcherValue ? { matcherValue } : {}),
  1222. payload,
  1223. };
  1224. }