run-exec-command.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. import { loadTuiRuntimeConfig } from '../headless/config.js';
  2. import { exitCodeForExecError, TuiExecError } from '../headless/exit-policy.js';
  3. import { formatTuiExecFailure } from '../headless/error-presentation.js';
  4. import { resolveTuiExecInvocation, type RawTuiExecOptions } from '../headless/invocation.js';
  5. import { runTuiExec } from '../headless/runner.js';
  6. import { prepareTuiDataDir } from '../runtime/data-dir.js';
  7. import { createTuiRuntime, shutdownTuiRuntime } from '../runtime/lifecycle.js';
  8. type TuiTerminationSignal = 'SIGINT' | 'SIGTERM' | 'SIGHUP';
  9. interface TuiExecProcess {
  10. exitCode?: number | string;
  11. once(signal: TuiTerminationSignal, listener: () => void): unknown;
  12. off(signal: TuiTerminationSignal, listener: () => void): unknown;
  13. }
  14. export interface RunTuiExecCommandDependencies {
  15. readonly processRef?: TuiExecProcess;
  16. readonly writeError?: (value: string) => void;
  17. readonly resolveInvocation?: typeof resolveTuiExecInvocation;
  18. readonly resolveDataDir?: () => string | Promise<string>;
  19. readonly loadConfig?: typeof loadTuiRuntimeConfig;
  20. readonly createRuntime?: typeof createTuiRuntime;
  21. readonly shutdownRuntime?: typeof shutdownTuiRuntime;
  22. readonly runExec?: typeof runTuiExec;
  23. readonly readStdin?: (signal: AbortSignal) => Promise<string>;
  24. }
  25. export async function runTuiExecCommand(
  26. prompt: string | undefined,
  27. commandOptions: RawTuiExecOptions,
  28. version: string,
  29. dependencies: RunTuiExecCommandDependencies = {},
  30. ): Promise<void> {
  31. const processRef = dependencies.processRef ?? process;
  32. const writeError = dependencies.writeError ?? ((value: string) => process.stderr.write(value));
  33. const resolveInvocation = dependencies.resolveInvocation ?? resolveTuiExecInvocation;
  34. const resolveDataDir = dependencies.resolveDataDir ?? prepareTuiDataDir;
  35. const loadConfig = dependencies.loadConfig ?? loadTuiRuntimeConfig;
  36. const createRuntime = dependencies.createRuntime ?? createTuiRuntime;
  37. const shutdownRuntime = dependencies.shutdownRuntime ?? shutdownTuiRuntime;
  38. const runExec = dependencies.runExec ?? runTuiExec;
  39. const readStdin = dependencies.readStdin ?? readTuiStdinToEnd;
  40. const invocationController = new AbortController();
  41. const cancelInvocation = () => invocationController.abort();
  42. const assertNotCancelled = () => {
  43. if (invocationController.signal.aborted) {
  44. throw new TuiExecError('cancelled', 'Invocation was cancelled.');
  45. }
  46. };
  47. processRef.once('SIGINT', cancelInvocation);
  48. processRef.once('SIGTERM', cancelInvocation);
  49. processRef.once('SIGHUP', cancelInvocation);
  50. try {
  51. const invocation = await resolveInvocation(
  52. prompt,
  53. commandOptions,
  54. () => readStdin(invocationController.signal),
  55. invocationController.signal,
  56. );
  57. assertNotCancelled();
  58. const dataDir = await resolveDataDir();
  59. assertNotCancelled();
  60. const explicitConfig = invocation.configPath
  61. ? await loadConfig(invocation.configPath, { dataDir })
  62. : undefined;
  63. assertNotCancelled();
  64. const runtime = await createRuntime(
  65. {
  66. dataDir,
  67. workspaceDir: invocation.workspaceDir,
  68. version,
  69. ...(invocation.configPath ? { configPath: invocation.configPath } : {}),
  70. surface: 'headless',
  71. promptMode: invocation.promptMode ?? 'tui',
  72. permissionMode: runtimePermissionMode(invocation.permission),
  73. ...(commandOptions.lane ? { lane: commandOptions.lane } : {}),
  74. },
  75. explicitConfig
  76. ? {
  77. getConfig: () => explicitConfig,
  78. configSource: 'explicit',
  79. }
  80. : {},
  81. );
  82. processRef.exitCode = await runExec(
  83. {
  84. prompt: invocation.prompt,
  85. workspaceDir: invocation.workspaceDir,
  86. version,
  87. attachments: invocation.attachments,
  88. format: invocation.format,
  89. ...(invocation.model ? { model: invocation.model } : {}),
  90. ...(invocation.effort ? { effort: invocation.effort } : {}),
  91. ...(invocation.sessionId ? { sessionId: invocation.sessionId } : {}),
  92. continueSession: invocation.continueSession,
  93. permission: invocation.permission,
  94. ...(invocation.diagnosticsDir ? { diagnosticsDir: invocation.diagnosticsDir } : {}),
  95. ...(invocation.timeoutMs !== undefined ? { timeoutMs: invocation.timeoutMs } : {}),
  96. ...(invocation.maxSteps !== undefined ? { maxSteps: invocation.maxSteps } : {}),
  97. ...(invocation.outputSchema === undefined ? {} : { outputSchema: invocation.outputSchema }),
  98. ...(invocation.outputLastMessagePath === undefined
  99. ? {}
  100. : { outputLastMessagePath: invocation.outputLastMessagePath }),
  101. ...(invocation.reviewRequest ? { reviewRequest: invocation.reviewRequest } : {}),
  102. },
  103. {
  104. runtime: runtime.adapter,
  105. signal: invocationController.signal,
  106. shutdown: () => shutdownRuntime(runtime),
  107. },
  108. );
  109. } catch (error) {
  110. const normalized =
  111. error instanceof TuiExecError
  112. ? error
  113. : new TuiExecError('runtime', error instanceof Error ? error.message : String(error), {
  114. cause: error,
  115. });
  116. writeError(`mcode exec failed: ${formatTuiExecFailure(normalized)}\n`);
  117. processRef.exitCode = exitCodeForExecError(normalized);
  118. } finally {
  119. processRef.off('SIGINT', cancelInvocation);
  120. processRef.off('SIGTERM', cancelInvocation);
  121. processRef.off('SIGHUP', cancelInvocation);
  122. }
  123. }
  124. function runtimePermissionMode(
  125. permission: 'smart' | 'full' | 'off',
  126. ): 'auto' | 'bypassPermissions' | 'off' {
  127. switch (permission) {
  128. case 'smart':
  129. return 'auto';
  130. case 'full':
  131. return 'bypassPermissions';
  132. case 'off':
  133. return 'off';
  134. }
  135. }
  136. interface TuiStdinStream {
  137. [Symbol.asyncIterator](): AsyncIterator<Buffer | string>;
  138. }
  139. export async function readTuiStdinToEnd(
  140. signal: AbortSignal,
  141. stream: TuiStdinStream = process.stdin,
  142. ): Promise<string> {
  143. const chunks: Buffer[] = [];
  144. const iterator = stream[Symbol.asyncIterator]();
  145. try {
  146. for (;;) {
  147. const next = await readNextStdinChunk(iterator, signal);
  148. if (next.done) break;
  149. chunks.push(Buffer.isBuffer(next.value) ? next.value : Buffer.from(next.value));
  150. }
  151. } finally {
  152. await iterator.return?.();
  153. }
  154. return Buffer.concat(chunks).toString('utf8');
  155. }
  156. function readNextStdinChunk(
  157. iterator: AsyncIterator<Buffer | string>,
  158. signal: AbortSignal,
  159. ): Promise<IteratorResult<Buffer | string>> {
  160. return new Promise((resolve, reject) => {
  161. const cancel = () => {
  162. reject(new TuiExecError('cancelled', 'stdin input was cancelled.'));
  163. };
  164. if (signal.aborted) {
  165. cancel();
  166. return;
  167. }
  168. signal.addEventListener('abort', cancel, { once: true });
  169. void iterator.next().then(
  170. (next) => {
  171. signal.removeEventListener('abort', cancel);
  172. resolve(next);
  173. },
  174. (error: unknown) => {
  175. signal.removeEventListener('abort', cancel);
  176. reject(error);
  177. },
  178. );
  179. });
  180. }