headless-invocation.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. import { mkdtemp, mkdir, realpath, rm, symlink, truncate, writeFile } from 'node:fs/promises';
  2. import { tmpdir } from 'node:os';
  3. import { join } from 'node:path';
  4. import { afterEach, describe, expect, it, vi } from 'vitest';
  5. import {
  6. resolveTuiExecInvocation,
  7. type RawTuiExecOptions,
  8. } from '../../src/headless/invocation.js';
  9. const roots: string[] = [];
  10. afterEach(async () => {
  11. await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
  12. });
  13. async function workspace(): Promise<string> {
  14. const root = await mkdtemp(join(tmpdir(), 'mcode-headless-invocation-'));
  15. roots.push(root);
  16. return root;
  17. }
  18. describe('headless invocation', () => {
  19. it('resolves exec review as a fixed local-changes operation without stdin', async () => {
  20. const cwd = await workspace();
  21. const readStdin = vi.fn(async () => 'ignored');
  22. await expect(
  23. resolveTuiExecInvocation(
  24. undefined,
  25. {
  26. review: true,
  27. cwd,
  28. model: 'provider/model',
  29. permission: 'full',
  30. outputFormat: 'json',
  31. },
  32. readStdin,
  33. ),
  34. ).resolves.toMatchObject({
  35. prompt: 'Please review my uncommitted changes.',
  36. workspaceDir: await realpath(cwd),
  37. model: 'provider/model',
  38. permission: 'full',
  39. format: 'json',
  40. attachments: [],
  41. continueSession: false,
  42. reviewRequest: { scope: 'local_changes' },
  43. });
  44. expect(readStdin).not.toHaveBeenCalled();
  45. });
  46. it('carries a trimmed --effort for exec and exec review and rejects a blank level', async () => {
  47. const cwd = await workspace();
  48. const readStdin = vi.fn(async () => 'ignored');
  49. await expect(
  50. resolveTuiExecInvocation('prompt', { cwd, effort: ' xhigh ' }, readStdin),
  51. ).resolves.toMatchObject({ effort: 'xhigh' });
  52. await expect(
  53. resolveTuiExecInvocation(undefined, { review: true, cwd, effort: 'high' }, readStdin),
  54. ).resolves.toMatchObject({ effort: 'high', reviewRequest: { scope: 'local_changes' } });
  55. await expect(resolveTuiExecInvocation('prompt', { cwd }, readStdin)).resolves.not.toHaveProperty(
  56. 'effort',
  57. );
  58. for (const options of [{ cwd, effort: ' ' }, { review: true, cwd, effort: '' }]) {
  59. await expect(
  60. resolveTuiExecInvocation('prompt', options, readStdin),
  61. ).rejects.toMatchObject({ kind: 'invocation', message: '--effort cannot be empty.' });
  62. }
  63. });
  64. it('resolves a diagnostics directory against cwd and rejects empty or file paths', async () => {
  65. const cwd = await workspace();
  66. const invocation = await resolveTuiExecInvocation('review', { cwd, diagnosticsDir: 'evidence' }, async () => '');
  67. expect(invocation.diagnosticsDir).toBe(join(await realpath(cwd), 'evidence'));
  68. await expect(resolveTuiExecInvocation('review', { cwd, diagnosticsDir: '' }, async () => '')).rejects.toThrow('--diagnostics-dir');
  69. await writeFile(join(cwd, 'file'), 'not a directory');
  70. await expect(resolveTuiExecInvocation('review', { cwd, diagnosticsDir: 'file' }, async () => '')).rejects.toThrow('--diagnostics-dir');
  71. });
  72. it('never reads stdin without explicit --input -', async () => {
  73. const cwd = await workspace();
  74. let reads = 0;
  75. await expect(
  76. resolveTuiExecInvocation('prompt', { cwd }, async () => {
  77. reads += 1;
  78. return 'ignored';
  79. }),
  80. ).resolves.toMatchObject({
  81. prompt: 'prompt',
  82. workspaceDir: await realpath(cwd),
  83. });
  84. expect(reads).toBe(0);
  85. });
  86. it('defaults to smart permissions and rejects interactive ask before reading input', async () => {
  87. const cwd = await workspace();
  88. const readStdin = vi.fn(async () => 'ignored');
  89. await expect(
  90. resolveTuiExecInvocation('prompt', { cwd }, readStdin),
  91. ).resolves.toMatchObject({ permission: 'smart' });
  92. await expect(
  93. resolveTuiExecInvocation(undefined, { cwd, input: '-', permission: 'ask' }, readStdin),
  94. ).rejects.toMatchObject({
  95. kind: 'invocation',
  96. message: expect.stringContaining('requires an interactive host'),
  97. });
  98. expect(readStdin).not.toHaveBeenCalled();
  99. });
  100. it('accepts JSON stdin and rejects prompt/source conflicts', async () => {
  101. const cwd = await workspace();
  102. await expect(
  103. resolveTuiExecInvocation(
  104. undefined,
  105. { cwd, input: '-', inputFormat: 'json' },
  106. async () => '{"prompt":"from json"}',
  107. ),
  108. ).resolves.toMatchObject({ prompt: 'from json' });
  109. await expect(
  110. resolveTuiExecInvocation('prompt', { cwd, input: '-' }, async () => 'from stdin'),
  111. ).rejects.toThrow('cannot be combined');
  112. });
  113. it('supports attachment-only input and resolves a symlinked file', async () => {
  114. const cwd = await workspace();
  115. await writeFile(join(cwd, 'actual.txt'), 'hello');
  116. await symlink(join(cwd, 'actual.txt'), join(cwd, 'alias.txt'));
  117. const invocation = await resolveTuiExecInvocation(
  118. undefined,
  119. { cwd, file: ['alias.txt'] },
  120. async () => {
  121. throw new Error('stdin must not be read');
  122. },
  123. );
  124. expect(invocation.prompt).toBe('');
  125. expect(invocation.attachments).toEqual([
  126. expect.objectContaining({
  127. fileName: 'actual.txt',
  128. mimeType: 'text/plain',
  129. sizeBytes: 5,
  130. }),
  131. ]);
  132. });
  133. it('preserves video MIME metadata for model capability selection', async () => {
  134. const cwd = await workspace();
  135. await writeFile(join(cwd, 'demo.mp4'), Buffer.from([0, 1, 2, 3]));
  136. await expect(
  137. resolveTuiExecInvocation('Review this video', { cwd, file: ['demo.mp4'] }, async () => ''),
  138. ).resolves.toMatchObject({
  139. attachments: [
  140. {
  141. type: 'file',
  142. fileName: 'demo.mp4',
  143. mimeType: 'video/mp4',
  144. sizeBytes: 4,
  145. },
  146. ],
  147. });
  148. });
  149. it('rejects missing cwd, missing input, invalid duration, and conflicting session strategies', async () => {
  150. const cwd = await workspace();
  151. await mkdir(join(cwd, 'file-dir'));
  152. const cases: RawTuiExecOptions[] = [
  153. { cwd: join(cwd, 'missing') },
  154. { cwd },
  155. { cwd, timeout: 'forever' },
  156. { cwd, session: 'session-1', continue: true },
  157. ];
  158. for (const options of cases) {
  159. await expect(
  160. resolveTuiExecInvocation(undefined, options, async () => ''),
  161. ).rejects.toThrow();
  162. }
  163. });
  164. it('cancels before reading files or stdin when the invocation signal is aborted', async () => {
  165. const cwd = await workspace();
  166. const controller = new AbortController();
  167. controller.abort('test');
  168. let reads = 0;
  169. await expect(
  170. resolveTuiExecInvocation(
  171. undefined,
  172. { cwd, input: '-' },
  173. async () => {
  174. reads += 1;
  175. return 'ignored';
  176. },
  177. controller.signal,
  178. ),
  179. ).rejects.toMatchObject({ kind: 'cancelled' });
  180. expect(reads).toBe(0);
  181. });
  182. it('accepts binary files and matches the client attachment limits', async () => {
  183. const cwd = await workspace();
  184. await writeFile(join(cwd, 'payload.bin'), Buffer.from([0, 1, 2, 3]));
  185. await writeFile(join(cwd, 'large.bin'), '');
  186. await truncate(join(cwd, 'large.bin'), 100 * 1024 * 1024 + 1);
  187. await expect(
  188. resolveTuiExecInvocation(undefined, { cwd, file: ['payload.bin'] }, async () => ''),
  189. ).resolves.toMatchObject({
  190. attachments: [
  191. {
  192. type: 'file',
  193. fileName: 'payload.bin',
  194. mimeType: 'application/octet-stream',
  195. sizeBytes: 4,
  196. },
  197. ],
  198. });
  199. await expect(
  200. resolveTuiExecInvocation(undefined, { cwd, file: ['missing.bin'] }, async () => ''),
  201. ).rejects.toThrow('Cannot attach missing.bin');
  202. await expect(
  203. resolveTuiExecInvocation(undefined, { cwd, file: ['large.bin'] }, async () => ''),
  204. ).rejects.toThrow('100 MB limit');
  205. const files = Array.from({ length: 11 }, (_, index) => `file-${String(index)}.txt`);
  206. await Promise.all(files.map((file) => writeFile(join(cwd, file), file)));
  207. await expect(
  208. resolveTuiExecInvocation(undefined, { cwd, file: files }, async () => ''),
  209. ).rejects.toThrow('up to 10 files');
  210. });
  211. it('normalizes canonical output flags and parses the result schema', async () => {
  212. const cwd = await workspace();
  213. await expect(
  214. resolveTuiExecInvocation(
  215. 'prompt',
  216. {
  217. cwd,
  218. outputFormat: 'stream-json',
  219. outputSchema: '{"type":"object","required":["type"]}',
  220. },
  221. async () => '',
  222. ),
  223. ).resolves.toMatchObject({
  224. format: 'stream-json',
  225. outputSchema: { type: 'object', required: ['type'] },
  226. });
  227. });
  228. it('loads an output schema file and resolves the last-message target without creating it', async () => {
  229. const cwd = await workspace();
  230. await writeFile(
  231. join(cwd, 'review.schema.json'),
  232. JSON.stringify({ type: 'object', required: ['findings'] }),
  233. );
  234. await expect(
  235. resolveTuiExecInvocation(
  236. 'review',
  237. {
  238. cwd,
  239. outputSchema: 'review.schema.json',
  240. outputLastMessage: 'artifacts/review.json',
  241. },
  242. async () => '',
  243. ),
  244. ).rejects.toThrow('--output-last-message is invalid');
  245. await mkdir(join(cwd, 'artifacts'));
  246. await expect(
  247. resolveTuiExecInvocation(
  248. 'review',
  249. {
  250. cwd,
  251. outputSchema: 'review.schema.json',
  252. outputLastMessage: 'artifacts/review.json',
  253. },
  254. async () => '',
  255. ),
  256. ).resolves.toMatchObject({
  257. outputSchema: { type: 'object', required: ['findings'] },
  258. outputLastMessagePath: join(await realpath(cwd), 'artifacts', 'review.json'),
  259. });
  260. });
  261. it('resolves every optional automation control and trims owner identifiers', async () => {
  262. const cwd = await workspace();
  263. await writeFile(join(cwd, 'mcode.yaml'), 'models: {}\n');
  264. await writeFile(join(cwd, 'image.PNG'), Buffer.from([1, 2, 3]));
  265. await expect(
  266. resolveTuiExecInvocation(
  267. 'prompt',
  268. {
  269. cwd,
  270. file: ['image.PNG'],
  271. model: ' provider/model#fast ',
  272. session: ' session-1 ',
  273. config: 'mcode.yaml',
  274. permission: 'off',
  275. timeout: '2h',
  276. maxSteps: '12',
  277. outputFormat: 'json',
  278. },
  279. async () => '',
  280. ),
  281. ).resolves.toMatchObject({
  282. prompt: 'prompt',
  283. attachments: [
  284. expect.objectContaining({
  285. type: 'image',
  286. fileName: 'image.PNG',
  287. mimeType: 'image/png',
  288. }),
  289. ],
  290. model: 'provider/model#fast',
  291. sessionId: 'session-1',
  292. configPath: await realpath(join(cwd, 'mcode.yaml')),
  293. permission: 'off',
  294. timeoutMs: 7_200_000,
  295. maxSteps: 12,
  296. format: 'json',
  297. });
  298. });
  299. it.each([
  300. [{ input: 'file' }, '--input currently accepts only'],
  301. [{ inputFormat: 'yaml' }, '--input-format must be one of'],
  302. [{ outputFormat: 'xml' }, '--output-format must be one of'],
  303. [{ permission: 'root' }, '--permission must be one of'],
  304. ] as const)('rejects invalid enum-like option %s', async (options, message) => {
  305. const cwd = await workspace();
  306. await expect(
  307. resolveTuiExecInvocation('prompt', { cwd, ...options }, async () => ''),
  308. ).rejects.toThrow(message);
  309. });
  310. it('accepts both JSON prompt shapes and rejects every other JSON input', async () => {
  311. const cwd = await workspace();
  312. await expect(
  313. resolveTuiExecInvocation(
  314. undefined,
  315. { cwd, input: '-', inputFormat: 'json' },
  316. async () => '"string prompt"',
  317. ),
  318. ).resolves.toMatchObject({ prompt: 'string prompt' });
  319. await expect(
  320. resolveTuiExecInvocation(
  321. undefined,
  322. { cwd, input: '-', inputFormat: 'json' },
  323. async () => '{invalid',
  324. ),
  325. ).rejects.toThrow('requires valid JSON');
  326. for (const input of ['[]', '{}', '{"prompt":1}', 'null']) {
  327. await expect(
  328. resolveTuiExecInvocation(
  329. undefined,
  330. { cwd, input: '-', inputFormat: 'json' },
  331. async () => input,
  332. ),
  333. ).rejects.toThrow('JSON string or an object with string prompt');
  334. }
  335. });
  336. it.each([
  337. ['1', 1],
  338. ['500ms', 500],
  339. ['30s', 30_000],
  340. ['2m', 120_000],
  341. ['1H', 3_600_000],
  342. ] as const)('parses timeout %s as %i milliseconds', async (timeout, timeoutMs) => {
  343. const cwd = await workspace();
  344. await expect(
  345. resolveTuiExecInvocation('prompt', { cwd, timeout }, async () => ''),
  346. ).resolves.toMatchObject({ timeoutMs });
  347. });
  348. it.each([
  349. [{ timeout: '0' }, '--timeout must resolve to a positive safe integer'],
  350. [{ timeout: '9007199254740992h' }, '--timeout must resolve to a positive safe integer'],
  351. [{ maxSteps: '0' }, '--max-steps must be a positive safe integer'],
  352. [{ maxSteps: '-1' }, '--max-steps must be a positive integer'],
  353. [{ maxSteps: '1.5' }, '--max-steps must be a positive integer'],
  354. [{ maxSteps: '9007199254740992' }, '--max-steps must be a positive safe integer'],
  355. ] as const)('rejects invalid numeric automation control %s', async (options, message) => {
  356. const cwd = await workspace();
  357. await expect(
  358. resolveTuiExecInvocation('prompt', { cwd, ...options }, async () => ''),
  359. ).rejects.toThrow(message);
  360. });
  361. it.each([
  362. ['null', '--output-schema requires a JSON object'],
  363. ['[]', '--output-schema requires a JSON object'],
  364. ['"text"', '--output-schema requires a JSON object'],
  365. ['{invalid', '--output-schema requires a JSON object'],
  366. ['{"type":42}', '--output-schema requires a JSON object'],
  367. ] as const)('rejects invalid output schema %s', async (outputSchema, message) => {
  368. const cwd = await workspace();
  369. await expect(
  370. resolveTuiExecInvocation('prompt', { cwd, outputSchema }, async () => ''),
  371. ).rejects.toThrow(message);
  372. });
  373. it('rejects non-file attachments, non-directory cwd, invalid config targets, and empty paths', async () => {
  374. const cwd = await workspace();
  375. await mkdir(join(cwd, 'directory'));
  376. await writeFile(join(cwd, 'file.txt'), 'file');
  377. await expect(
  378. resolveTuiExecInvocation('prompt', { cwd, file: ['directory'] }, async () => ''),
  379. ).rejects.toThrow('path is not a file');
  380. await expect(
  381. resolveTuiExecInvocation('prompt', { cwd: join(cwd, 'file.txt') }, async () => ''),
  382. ).rejects.toThrow('--cwd must reference a directory');
  383. await expect(
  384. resolveTuiExecInvocation('prompt', { cwd, config: 'directory' }, async () => ''),
  385. ).rejects.toThrow('--config must reference a file');
  386. await expect(
  387. resolveTuiExecInvocation('prompt', { cwd, config: 'missing' }, async () => ''),
  388. ).rejects.toThrow('--config is invalid');
  389. await expect(
  390. resolveTuiExecInvocation('prompt', { cwd: ' ' }, async () => ''),
  391. ).rejects.toThrow('Path value cannot be empty');
  392. });
  393. it('cancels after an in-flight stdin read before resolving attachments', async () => {
  394. const cwd = await workspace();
  395. const controller = new AbortController();
  396. await expect(
  397. resolveTuiExecInvocation(
  398. undefined,
  399. { cwd, input: '-' },
  400. async () => {
  401. controller.abort('cancelled after read');
  402. return 'prompt';
  403. },
  404. controller.signal,
  405. ),
  406. ).rejects.toMatchObject({ kind: 'cancelled' });
  407. });
  408. });
  409. describe('Prompt mode selection', () => {
  410. it.each([undefined, 'tui', 'coding', 'work'])(
  411. 'resolves %s before runtime startup',
  412. async (promptMode) => {
  413. const invocation = await resolveTuiExecInvocation('hello', { promptMode }, async () => '');
  414. expect(invocation.promptMode).toBe(promptMode ?? 'tui');
  415. },
  416. );
  417. it('rejects unknown modes', async () => {
  418. await expect(
  419. resolveTuiExecInvocation('hello', { promptMode: 'unknown' }, async () => ''),
  420. ).rejects.toThrow('--prompt-mode must be one of');
  421. });
  422. });