output-artifacts.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. import { createHash, randomUUID } from 'node:crypto';
  2. import { lstat, mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises';
  3. import { tmpdir } from 'node:os';
  4. import { join } from 'node:path';
  5. import type {
  6. PluginHookCommandHandler,
  7. PluginHookDecision,
  8. PluginHookEventInput,
  9. } from './contracts.js';
  10. const COMPATIBLE_OUTPUT_STRING_LIMIT = 10_000;
  11. const CODEX_DEFAULT_ADDITIONAL_CONTEXT_TOKEN_LIMIT = 2_500;
  12. const MAX_INJECTED_TEXT_CHARS = 64 * 1024;
  13. const ARTIFACT_TTL_MS = 24 * 60 * 60 * 1_000;
  14. const MAX_SESSION_ARTIFACT_BYTES = 8 * 1024 * 1024;
  15. const MAX_SESSION_ARTIFACT_FILES = 64;
  16. const MAX_MANAGED_ARTIFACT_BYTES = 64 * 1024 * 1024;
  17. const MANAGED_OUTPUT_ROOT = join(tmpdir(), 'minimax-plugin-hooks', 'outputs');
  18. const directoryLanes = new Map<string, Promise<void>>();
  19. const activeArtifactDirectories = new Set<string>();
  20. let startupGc: Promise<void> | undefined;
  21. export async function boundHandlerDecision(
  22. handler: PluginHookCommandHandler,
  23. input: PluginHookEventInput,
  24. decision: PluginHookDecision,
  25. ): Promise<PluginHookDecision> {
  26. const limit = handlerOutputLimit(handler);
  27. if (limit === undefined) return decision;
  28. const bound = (value: string | undefined, label: string) =>
  29. value === undefined
  30. ? Promise.resolve(undefined)
  31. : spillOversizedHookText(value, limit, handler, input.sessionId, label);
  32. const [
  33. reason,
  34. additionalContext,
  35. stopReason,
  36. systemMessage,
  37. terminalSequence,
  38. continuePrompt,
  39. postToolFeedback,
  40. ] = await Promise.all([
  41. bound(decision.reason, 'reason'),
  42. bound(decision.additionalContext, 'additional-context'),
  43. bound(decision.stopReason, 'stop-reason'),
  44. bound(decision.systemMessage, 'system-message'),
  45. bound(decision.terminalSequence, 'terminal-sequence'),
  46. bound(decision.continuePrompt, 'continue-prompt'),
  47. bound(decision.postToolFeedback, 'post-tool-feedback'),
  48. ]);
  49. const updatedResult =
  50. handler.sourceFormat === 'CLAUDE' && decision.updatedResult !== undefined
  51. ? await boundHookOutputValue(
  52. decision.updatedResult,
  53. limit,
  54. handler,
  55. input.sessionId,
  56. 'updated-result',
  57. )
  58. : decision.updatedResult;
  59. return {
  60. ...decision,
  61. ...(reason === undefined ? {} : { reason }),
  62. ...(additionalContext === undefined ? {} : { additionalContext }),
  63. ...(stopReason === undefined ? {} : { stopReason }),
  64. ...(systemMessage === undefined ? {} : { systemMessage }),
  65. ...(terminalSequence === undefined ? {} : { terminalSequence }),
  66. ...(continuePrompt === undefined ? {} : { continuePrompt }),
  67. ...(postToolFeedback === undefined ? {} : { postToolFeedback }),
  68. ...(updatedResult === undefined ? {} : { updatedResult }),
  69. };
  70. }
  71. export async function cleanupPluginHookSessionArtifacts(
  72. handlers: readonly PluginHookCommandHandler[],
  73. sessionId: string,
  74. ): Promise<void> {
  75. const directories = new Set(handlers.map((handler) => artifactDirectory(handler, sessionId)));
  76. await withDirectoryLane(MANAGED_OUTPUT_ROOT, async () => {
  77. for (const directory of directories) activeArtifactDirectories.delete(directory);
  78. await Promise.allSettled(
  79. [...directories].map((directory) => rm(directory, { recursive: true, force: true })),
  80. );
  81. });
  82. }
  83. function handlerOutputLimit(
  84. handler: PluginHookCommandHandler,
  85. ): { readonly kind: 'characters' | 'tokens'; readonly value: number } | undefined {
  86. if (handler.sourceFormat === 'CLAUDE') {
  87. return { kind: 'characters', value: COMPATIBLE_OUTPUT_STRING_LIMIT };
  88. }
  89. if (handler.sourceFormat === 'CODEX') {
  90. const value = handler.additionalContextLimit ?? CODEX_DEFAULT_ADDITIONAL_CONTEXT_TOKEN_LIMIT;
  91. return value === 0 ? undefined : { kind: 'tokens', value };
  92. }
  93. return { kind: 'characters', value: MAX_INJECTED_TEXT_CHARS };
  94. }
  95. async function boundHookOutputValue(
  96. value: unknown,
  97. limit: { readonly kind: 'characters' | 'tokens'; readonly value: number },
  98. handler: PluginHookCommandHandler,
  99. sessionId: string,
  100. label: string,
  101. ): Promise<unknown> {
  102. if (typeof value === 'string') {
  103. return spillOversizedHookText(value, limit, handler, sessionId, label);
  104. }
  105. if (Array.isArray(value)) {
  106. const result: unknown[] = [];
  107. for (const [index, item] of value.entries()) {
  108. result.push(await boundHookOutputValue(item, limit, handler, sessionId, `${label}-${index}`));
  109. }
  110. return result;
  111. }
  112. if (!isRecord(value)) return value;
  113. const result: Record<string, unknown> = {};
  114. for (const [key, child] of Object.entries(value)) {
  115. result[key] = await boundHookOutputValue(child, limit, handler, sessionId, `${label}-${key}`);
  116. }
  117. return result;
  118. }
  119. async function spillOversizedHookText(
  120. value: string,
  121. limit: { readonly kind: 'characters' | 'tokens'; readonly value: number },
  122. handler: PluginHookCommandHandler,
  123. sessionId: string,
  124. label: string,
  125. ): Promise<string> {
  126. if (!exceedsTextLimit(value, limit)) return value;
  127. const directory = artifactDirectory(handler, sessionId);
  128. const path = join(directory, `${randomUUID()}-${safeName(label)}.txt`);
  129. const footer = `\n\nFull hook output saved to: ${path}`;
  130. try {
  131. startupGc ??= garbageCollectManagedArtifacts();
  132. await startupGc;
  133. await withDirectoryLane(MANAGED_OUTPUT_ROOT, async () => {
  134. activeArtifactDirectories.add(directory);
  135. await mkdir(directory, { recursive: true, mode: 0o700 });
  136. await enforceManagedRootQuota(Buffer.byteLength(value));
  137. await enforceDirectoryQuota(directory, Buffer.byteLength(value));
  138. await writeFile(path, value, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
  139. });
  140. return previewWithinLimit(value, footer, limit);
  141. } catch {
  142. return previewWithinLimit(value, '', limit);
  143. }
  144. }
  145. function artifactDirectory(handler: PluginHookCommandHandler, sessionId: string): string {
  146. return join(
  147. MANAGED_OUTPUT_ROOT,
  148. stableKey(`${handler.pluginName}\0${handler.pluginRoot}`),
  149. stableKey(sessionId),
  150. );
  151. }
  152. async function withDirectoryLane<T>(directory: string, work: () => Promise<T>): Promise<T> {
  153. const previous = directoryLanes.get(directory) ?? Promise.resolve();
  154. let release: () => void = () => undefined;
  155. const current = new Promise<void>((resolve) => {
  156. release = resolve;
  157. });
  158. const tail = previous.then(() => current);
  159. directoryLanes.set(directory, tail);
  160. await previous;
  161. try {
  162. return await work();
  163. } finally {
  164. release();
  165. if (directoryLanes.get(directory) === tail) directoryLanes.delete(directory);
  166. }
  167. }
  168. async function enforceDirectoryQuota(directory: string, incomingBytes: number): Promise<void> {
  169. const names = await readdir(directory);
  170. const entries = (
  171. await Promise.all(
  172. names.map(async (name) => {
  173. const path = join(directory, name);
  174. try {
  175. const metadata = await stat(path);
  176. return metadata.isFile()
  177. ? { path, size: metadata.size, modifiedAt: metadata.mtimeMs }
  178. : undefined;
  179. } catch {
  180. return undefined;
  181. }
  182. }),
  183. )
  184. )
  185. .filter((entry): entry is NonNullable<typeof entry> => entry !== undefined)
  186. .sort((left, right) => left.modifiedAt - right.modifiedAt);
  187. const bytes = entries.reduce((total, entry) => total + entry.size, 0);
  188. if (
  189. entries.length >= MAX_SESSION_ARTIFACT_FILES ||
  190. bytes + incomingBytes > MAX_SESSION_ARTIFACT_BYTES
  191. ) {
  192. throw new Error('Plugin Hook output exceeds the managed artifact quota.');
  193. }
  194. }
  195. async function enforceManagedRootQuota(incomingBytes: number): Promise<void> {
  196. if (incomingBytes > MAX_MANAGED_ARTIFACT_BYTES) {
  197. throw new Error('Plugin Hook output exceeds the managed artifact root quota.');
  198. }
  199. const directories = await readManagedArtifactDirectories();
  200. let totalBytes = directories.reduce((total, directory) => total + directory.size, 0);
  201. for (const directory of directories.sort((left, right) => left.modifiedAt - right.modifiedAt)) {
  202. if (totalBytes + incomingBytes <= MAX_MANAGED_ARTIFACT_BYTES) break;
  203. if (activeArtifactDirectories.has(directory.path)) continue;
  204. await rm(directory.path, { recursive: true, force: true });
  205. totalBytes -= directory.size;
  206. }
  207. if (totalBytes + incomingBytes > MAX_MANAGED_ARTIFACT_BYTES) {
  208. throw new Error('Plugin Hook output exceeds the managed artifact root quota.');
  209. }
  210. }
  211. async function readManagedArtifactDirectories(): Promise<
  212. Array<{ readonly path: string; readonly size: number; readonly modifiedAt: number }>
  213. > {
  214. let plugins;
  215. try {
  216. plugins = await readdir(MANAGED_OUTPUT_ROOT, { withFileTypes: true });
  217. } catch {
  218. return [];
  219. }
  220. const directories = await Promise.all(
  221. plugins
  222. .filter((plugin) => plugin.isDirectory())
  223. .map(async (plugin) => {
  224. const pluginDirectory = join(MANAGED_OUTPUT_ROOT, plugin.name);
  225. const sessions = await readdir(pluginDirectory, { withFileTypes: true }).catch(() => []);
  226. return Promise.all(
  227. sessions
  228. .filter((session) => session.isDirectory())
  229. .map(async (session) => {
  230. const directory = join(pluginDirectory, session.name);
  231. const files = await readdir(directory, { withFileTypes: true }).catch(() => []);
  232. const metadata = await Promise.all(
  233. files
  234. .filter((file) => file.isFile())
  235. .map((file) => lstat(join(directory, file.name)).catch(() => undefined)),
  236. );
  237. const regularFiles = metadata.filter(
  238. (item): item is NonNullable<typeof item> => item?.isFile() === true,
  239. );
  240. return {
  241. path: directory,
  242. size: regularFiles.reduce((total, item) => total + item.size, 0),
  243. modifiedAt: regularFiles.reduce(
  244. (latest, item) => Math.max(latest, item.mtimeMs),
  245. 0,
  246. ),
  247. };
  248. }),
  249. );
  250. }),
  251. );
  252. return directories.flat();
  253. }
  254. async function garbageCollectManagedArtifacts(): Promise<void> {
  255. const cutoff = Date.now() - ARTIFACT_TTL_MS;
  256. try {
  257. const plugins = await readdir(MANAGED_OUTPUT_ROOT);
  258. await Promise.allSettled(
  259. plugins.map(async (plugin) => {
  260. const pluginDirectory = join(MANAGED_OUTPUT_ROOT, plugin);
  261. const sessions = await readdir(pluginDirectory);
  262. await Promise.allSettled(
  263. sessions.map(async (session) => {
  264. const directory = join(pluginDirectory, session);
  265. if (activeArtifactDirectories.has(directory)) return;
  266. const metadata = await stat(directory);
  267. if (metadata.mtimeMs < cutoff) await rm(directory, { recursive: true, force: true });
  268. }),
  269. );
  270. }),
  271. );
  272. } catch {
  273. // The managed root normally does not exist before the first oversized output.
  274. }
  275. }
  276. function exceedsTextLimit(
  277. value: string,
  278. limit: { readonly kind: 'characters' | 'tokens'; readonly value: number },
  279. ): boolean {
  280. return textCost(value, limit.kind) > textBudget(limit);
  281. }
  282. function previewWithinLimit(
  283. value: string,
  284. footer: string,
  285. limit: { readonly kind: 'characters' | 'tokens'; readonly value: number },
  286. ): string {
  287. const limitBudget = textBudget(limit);
  288. const boundedFooter = textCost(footer, limit.kind) <= limitBudget ? footer : '';
  289. const footerCost = textCost(boundedFooter, limit.kind);
  290. const previewBudget = Math.max(0, limitBudget - footerCost);
  291. if (textCost(value, limit.kind) <= previewBudget) return `${value}${boundedFooter}`;
  292. const fullMarker = '\n... hook output truncated ...\n';
  293. const marker = textCost(fullMarker, limit.kind) <= previewBudget ? fullMarker : '';
  294. const bodyBudget = Math.max(0, previewBudget - textCost(marker, limit.kind));
  295. const points = [...value];
  296. let left = 0;
  297. let right = points.length;
  298. let head = '';
  299. let tail = '';
  300. let headCost = 0;
  301. let tailCost = 0;
  302. while (left < right) {
  303. const fromHead = headCost <= tailCost;
  304. const point = fromHead ? points[left++] : points[--right];
  305. if (point === undefined) break;
  306. const cost = textCost(point, limit.kind);
  307. if (headCost + tailCost + cost > bodyBudget) break;
  308. if (fromHead) {
  309. head += point;
  310. headCost += cost;
  311. } else {
  312. tail = point + tail;
  313. tailCost += cost;
  314. }
  315. }
  316. return `${head}${marker}${tail}${boundedFooter}`;
  317. }
  318. function textCost(value: string, kind: 'characters' | 'tokens'): number {
  319. if (kind === 'characters') return value.length;
  320. let units = 0;
  321. for (const point of value) units += point.charCodeAt(0) <= 0x7f ? 1 : 4;
  322. return units;
  323. }
  324. function textBudget(limit: {
  325. readonly kind: 'characters' | 'tokens';
  326. readonly value: number;
  327. }): number {
  328. return limit.kind === 'characters' ? limit.value : limit.value * 4;
  329. }
  330. function stableKey(value: string): string {
  331. return createHash('sha256').update(value).digest('hex').slice(0, 32);
  332. }
  333. function safeName(value: string): string {
  334. return value.replace(/[^A-Za-z0-9._-]/gu, '_').slice(0, 80) || 'output';
  335. }
  336. function isRecord(value: unknown): value is Record<string, unknown> {
  337. return Boolean(value && typeof value === 'object' && !Array.isArray(value));
  338. }