@golba98/codexa 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/README.md +320 -0
  2. package/bin/codexa.js +445 -0
  3. package/package.json +45 -0
  4. package/scripts/audit-codexa-capabilities.mjs +466 -0
  5. package/scripts/smoke-terminal-bench.mjs +35 -0
  6. package/src/app.tsx +4561 -0
  7. package/src/appRenderStability.test.ts +131 -0
  8. package/src/commands/handler.test.ts +643 -0
  9. package/src/commands/handler.ts +875 -0
  10. package/src/config/launchArgs.test.ts +158 -0
  11. package/src/config/launchArgs.ts +186 -0
  12. package/src/config/layeredConfig.test.ts +143 -0
  13. package/src/config/layeredConfig.ts +836 -0
  14. package/src/config/persistence.test.ts +110 -0
  15. package/src/config/persistence.ts +311 -0
  16. package/src/config/runtimeConfig.test.ts +218 -0
  17. package/src/config/runtimeConfig.ts +554 -0
  18. package/src/config/settings.test.ts +155 -0
  19. package/src/config/settings.ts +401 -0
  20. package/src/config/toml-serialize.ts +98 -0
  21. package/src/config/trustStore.test.ts +29 -0
  22. package/src/config/trustStore.ts +68 -0
  23. package/src/core/attachments.test.ts +155 -0
  24. package/src/core/attachments.ts +71 -0
  25. package/src/core/auth/codexAuth.test.ts +68 -0
  26. package/src/core/auth/codexAuth.ts +359 -0
  27. package/src/core/cleanupFastFail.test.ts +76 -0
  28. package/src/core/cleanupFastFail.ts +67 -0
  29. package/src/core/clipboard.ts +24 -0
  30. package/src/core/codex.ts +124 -0
  31. package/src/core/codexExecArgs.test.ts +195 -0
  32. package/src/core/codexExecArgs.ts +152 -0
  33. package/src/core/codexLaunch.test.ts +205 -0
  34. package/src/core/codexLaunch.ts +162 -0
  35. package/src/core/codexPrompt.test.ts +252 -0
  36. package/src/core/codexPrompt.ts +428 -0
  37. package/src/core/executables/claudeExecutable.ts +63 -0
  38. package/src/core/executables/codexExecutable.test.ts +212 -0
  39. package/src/core/executables/codexExecutable.ts +159 -0
  40. package/src/core/executables/executableResolver.test.ts +129 -0
  41. package/src/core/executables/executableResolver.ts +138 -0
  42. package/src/core/executables/geminiExecutable.test.ts +116 -0
  43. package/src/core/executables/geminiExecutable.ts +78 -0
  44. package/src/core/executables/pathSanityScan.test.ts +47 -0
  45. package/src/core/githubDiagnostics.test.ts +92 -0
  46. package/src/core/githubDiagnostics.ts +222 -0
  47. package/src/core/hollowResponseFormat.test.ts +58 -0
  48. package/src/core/hollowResponseFormat.ts +39 -0
  49. package/src/core/inputDebug.ts +51 -0
  50. package/src/core/launchContext.test.ts +157 -0
  51. package/src/core/launchContext.ts +266 -0
  52. package/src/core/models/codexCapabilities.test.ts +45 -0
  53. package/src/core/models/codexCapabilities.ts +95 -0
  54. package/src/core/models/codexModelCapabilities.test.ts +246 -0
  55. package/src/core/models/codexModelCapabilities.ts +571 -0
  56. package/src/core/models/modelSpecs.test.ts +283 -0
  57. package/src/core/models/modelSpecs.ts +300 -0
  58. package/src/core/perf/profiler.ts +125 -0
  59. package/src/core/perf/renderDebug.test.ts +230 -0
  60. package/src/core/perf/renderDebug.ts +373 -0
  61. package/src/core/planStorage.test.ts +143 -0
  62. package/src/core/planStorage.ts +141 -0
  63. package/src/core/process/CommandRunner.test.ts +105 -0
  64. package/src/core/process/CommandRunner.ts +269 -0
  65. package/src/core/process/processValidation.ts +101 -0
  66. package/src/core/projectInstructions.test.ts +50 -0
  67. package/src/core/projectInstructions.ts +54 -0
  68. package/src/core/providerLauncher/launcher.test.ts +238 -0
  69. package/src/core/providerLauncher/launcher.ts +203 -0
  70. package/src/core/providerLauncher/registry.test.ts +324 -0
  71. package/src/core/providerLauncher/registry.ts +253 -0
  72. package/src/core/providerLauncher/types.ts +84 -0
  73. package/src/core/providerLauncher/workspaceConfig.test.ts +638 -0
  74. package/src/core/providerLauncher/workspaceConfig.ts +407 -0
  75. package/src/core/providerRuntime/anthropic.test.ts +1120 -0
  76. package/src/core/providerRuntime/anthropic.ts +576 -0
  77. package/src/core/providerRuntime/capabilityProfile.test.ts +311 -0
  78. package/src/core/providerRuntime/capabilityProfile.ts +288 -0
  79. package/src/core/providerRuntime/claudeCodeDiscovery.ts +446 -0
  80. package/src/core/providerRuntime/contextMetadata.test.ts +468 -0
  81. package/src/core/providerRuntime/contextMetadata.ts +409 -0
  82. package/src/core/providerRuntime/gemini.test.ts +437 -0
  83. package/src/core/providerRuntime/gemini.ts +784 -0
  84. package/src/core/providerRuntime/lmstudio.test.ts +168 -0
  85. package/src/core/providerRuntime/lmstudio.ts +118 -0
  86. package/src/core/providerRuntime/local.test.ts +787 -0
  87. package/src/core/providerRuntime/local.ts +754 -0
  88. package/src/core/providerRuntime/models.ts +150 -0
  89. package/src/core/providerRuntime/reasoning.ts +17 -0
  90. package/src/core/providerRuntime/registry.test.ts +233 -0
  91. package/src/core/providerRuntime/registry.ts +203 -0
  92. package/src/core/providerRuntime/types.ts +103 -0
  93. package/src/core/providers/codexJsonStream.test.ts +148 -0
  94. package/src/core/providers/codexJsonStream.ts +305 -0
  95. package/src/core/providers/codexSubprocess.test.ts +68 -0
  96. package/src/core/providers/codexSubprocess.ts +372 -0
  97. package/src/core/providers/codexTranscript.test.ts +284 -0
  98. package/src/core/providers/codexTranscript.ts +695 -0
  99. package/src/core/providers/openaiNative.ts +13 -0
  100. package/src/core/providers/registry.ts +21 -0
  101. package/src/core/providers/types.ts +59 -0
  102. package/src/core/terminal/terminalCapabilities.test.ts +93 -0
  103. package/src/core/terminal/terminalCapabilities.ts +100 -0
  104. package/src/core/terminal/terminalControl.test.ts +75 -0
  105. package/src/core/terminal/terminalControl.ts +147 -0
  106. package/src/core/terminal/terminalSanitize.test.ts +22 -0
  107. package/src/core/terminal/terminalSanitize.ts +147 -0
  108. package/src/core/terminal/terminalSelection.test.ts +42 -0
  109. package/src/core/terminal/terminalSelection.ts +66 -0
  110. package/src/core/terminal/terminalTitle.test.ts +328 -0
  111. package/src/core/terminal/terminalTitle.ts +483 -0
  112. package/src/core/workspaceActivity.test.ts +163 -0
  113. package/src/core/workspaceActivity.ts +380 -0
  114. package/src/core/workspaceGuard.test.ts +151 -0
  115. package/src/core/workspaceGuard.ts +288 -0
  116. package/src/core/workspaceRoot.test.ts +23 -0
  117. package/src/core/workspaceRoot.ts +47 -0
  118. package/src/exec.test.ts +13 -0
  119. package/src/exec.ts +72 -0
  120. package/src/headless/execArgs.test.ts +147 -0
  121. package/src/headless/execArgs.ts +294 -0
  122. package/src/headless/execRunner.test.ts +434 -0
  123. package/src/headless/execRunner.ts +304 -0
  124. package/src/index.test.tsx +618 -0
  125. package/src/index.tsx +296 -0
  126. package/src/session/appSession.test.ts +897 -0
  127. package/src/session/appSession.ts +761 -0
  128. package/src/session/chatLifecycle.test.ts +64 -0
  129. package/src/session/chatLifecycle.ts +951 -0
  130. package/src/session/liveRenderScheduler.test.ts +201 -0
  131. package/src/session/liveRenderScheduler.ts +214 -0
  132. package/src/session/planFlow.test.ts +103 -0
  133. package/src/session/planFlow.ts +149 -0
  134. package/src/session/planTranscript.test.ts +65 -0
  135. package/src/session/planTranscript.ts +15 -0
  136. package/src/session/promptRunSchedule.test.ts +36 -0
  137. package/src/session/promptRunSchedule.ts +26 -0
  138. package/src/session/types.ts +228 -0
  139. package/src/test/runtimeTestUtils.ts +14 -0
  140. package/src/types/react-dom.d.ts +3 -0
  141. package/src/ui/ActionRequiredBlock.tsx +38 -0
  142. package/src/ui/ActivityBars.tsx +68 -0
  143. package/src/ui/ActivityIndicator.test.tsx +58 -0
  144. package/src/ui/ActivityIndicator.tsx +58 -0
  145. package/src/ui/AgentBlock.test.ts +6 -0
  146. package/src/ui/AgentBlock.tsx +130 -0
  147. package/src/ui/AnimatedStatusText.test.ts +16 -0
  148. package/src/ui/AnimatedStatusText.tsx +69 -0
  149. package/src/ui/AppShell.test.tsx +1739 -0
  150. package/src/ui/AppShell.tsx +698 -0
  151. package/src/ui/AttachmentImportPanel.test.tsx +204 -0
  152. package/src/ui/AttachmentImportPanel.tsx +98 -0
  153. package/src/ui/AuthPanel.tsx +113 -0
  154. package/src/ui/BackendPicker.tsx +28 -0
  155. package/src/ui/BottomComposer.test.ts +674 -0
  156. package/src/ui/BottomComposer.tsx +1028 -0
  157. package/src/ui/CodexLogo.tsx +55 -0
  158. package/src/ui/DashCard.tsx +82 -0
  159. package/src/ui/Markdown.test.ts +157 -0
  160. package/src/ui/Markdown.tsx +310 -0
  161. package/src/ui/ModePicker.tsx +27 -0
  162. package/src/ui/ModelPicker.tsx +31 -0
  163. package/src/ui/ModelPickerProviderScope.test.tsx +411 -0
  164. package/src/ui/ModelPickerScreen.test.tsx +99 -0
  165. package/src/ui/ModelPickerScreen.tsx +416 -0
  166. package/src/ui/ModelPickerState.test.tsx +151 -0
  167. package/src/ui/ModelReasoningPicker.test.tsx +447 -0
  168. package/src/ui/ModelReasoningPicker.tsx +458 -0
  169. package/src/ui/Panel.tsx +51 -0
  170. package/src/ui/PermissionsPanel.tsx +78 -0
  171. package/src/ui/PlanActionPicker.tsx +119 -0
  172. package/src/ui/PlanReviewPanel.test.tsx +267 -0
  173. package/src/ui/PlanReviewPanel.tsx +212 -0
  174. package/src/ui/PromptCardBorder.test.tsx +161 -0
  175. package/src/ui/ProviderPicker.test.tsx +289 -0
  176. package/src/ui/ProviderPicker.tsx +321 -0
  177. package/src/ui/ProviderShortcut.test.tsx +143 -0
  178. package/src/ui/ReasoningPicker.tsx +46 -0
  179. package/src/ui/RunFooter.tsx +65 -0
  180. package/src/ui/SelectionPanel.tsx +67 -0
  181. package/src/ui/SettingsPanel.test.tsx +233 -0
  182. package/src/ui/SettingsPanel.tsx +156 -0
  183. package/src/ui/Spinner.tsx +25 -0
  184. package/src/ui/StaticIntroItem.tsx +54 -0
  185. package/src/ui/StaticTranscriptItem.tsx +56 -0
  186. package/src/ui/TextEntryPanel.tsx +139 -0
  187. package/src/ui/ThemePicker.tsx +31 -0
  188. package/src/ui/ThinkingBlock.tsx +100 -0
  189. package/src/ui/Timeline.test.ts +2067 -0
  190. package/src/ui/Timeline.tsx +1472 -0
  191. package/src/ui/TimelineNavigation.test.tsx +201 -0
  192. package/src/ui/TopHeader.test.tsx +239 -0
  193. package/src/ui/TopHeader.tsx +257 -0
  194. package/src/ui/TurnGroup.test.tsx +365 -0
  195. package/src/ui/TurnGroup.tsx +657 -0
  196. package/src/ui/busyStatusAnimation.test.ts +30 -0
  197. package/src/ui/busyStatusAnimation.ts +11 -0
  198. package/src/ui/commandNormalize.test.ts +142 -0
  199. package/src/ui/commandNormalize.ts +66 -0
  200. package/src/ui/diffRenderer.test.ts +102 -0
  201. package/src/ui/diffRenderer.ts +116 -0
  202. package/src/ui/focus.ts +61 -0
  203. package/src/ui/focusFlow.test.tsx +1098 -0
  204. package/src/ui/inputBuffer.test.ts +151 -0
  205. package/src/ui/inputBuffer.ts +203 -0
  206. package/src/ui/layout.test.ts +145 -0
  207. package/src/ui/layout.ts +287 -0
  208. package/src/ui/modeDisplay.test.ts +42 -0
  209. package/src/ui/modeDisplay.ts +52 -0
  210. package/src/ui/outputPipeline.ts +64 -0
  211. package/src/ui/progressEntries.ts +156 -0
  212. package/src/ui/runActivityView.test.ts +89 -0
  213. package/src/ui/runActivityView.ts +37 -0
  214. package/src/ui/runLifecycleView.test.tsx +237 -0
  215. package/src/ui/slashCommands.ts +41 -0
  216. package/src/ui/statusRenderIsolation.test.tsx +654 -0
  217. package/src/ui/terminalAnswerFormat.test.ts +19 -0
  218. package/src/ui/terminalAnswerFormat.ts +128 -0
  219. package/src/ui/textLayout.test.ts +18 -0
  220. package/src/ui/textLayout.ts +338 -0
  221. package/src/ui/theme.tsx +395 -0
  222. package/src/ui/themeFlow.test.ts +53 -0
  223. package/src/ui/themeFlow.ts +41 -0
  224. package/src/ui/timelineMeasure.ts +3088 -0
  225. package/src/ui/timelineMeasureCache.test.ts +986 -0
  226. package/src/ui/useThrottledValue.ts +31 -0
@@ -0,0 +1,101 @@
1
+ import { existsSync } from "fs";
2
+ import { isAbsolute, resolve } from "path";
3
+
4
+ const CONTROL_CHARACTER_PATTERN = /[\u0000-\u001f\u007f]/;
5
+ const BARE_EXECUTABLE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
6
+ const SHELL_METACHARACTER_PATTERN = /[;&|<>`$]/;
7
+ const WINDOWS_BATCH_METACHARACTER_PATTERN = /[;&|<>`$^%!]/;
8
+
9
+ export interface ExecutableValidationOptions {
10
+ label: string;
11
+ cwd?: string;
12
+ requireExistingPath?: boolean;
13
+ allowBareExecutable?: boolean;
14
+ }
15
+
16
+ function stripBalancedWrappingQuotes(value: string): string {
17
+ if (value.length < 2) return value;
18
+ const first = value[0];
19
+ const last = value[value.length - 1];
20
+ if ((first === `"` && last === `"`) || (first === `'` && last === `'`)) {
21
+ return value.slice(1, -1).trim();
22
+ }
23
+ return value;
24
+ }
25
+
26
+ function looksLikePath(value: string): boolean {
27
+ return /[\\/]/.test(value) || /^[A-Za-z]:/.test(value);
28
+ }
29
+
30
+ function hasWindowsBatchExtension(value: string): boolean {
31
+ return /\.(?:cmd|bat)$/i.test(value);
32
+ }
33
+
34
+ function validateCommonExecutableSyntax(value: string, label: string): void {
35
+ if (!value) {
36
+ throw new Error(`${label} is empty.`);
37
+ }
38
+ if (CONTROL_CHARACTER_PATTERN.test(value)) {
39
+ throw new Error(`${label} contains control characters and cannot be used as an executable.`);
40
+ }
41
+ if (value.includes(`"`) || value.includes(`'`)) {
42
+ throw new Error(`${label} must be a command/path only, without embedded quotes.`);
43
+ }
44
+ if (SHELL_METACHARACTER_PATTERN.test(value)) {
45
+ throw new Error(`${label} contains shell metacharacters and cannot be used as an executable.`);
46
+ }
47
+ }
48
+
49
+ export function normalizeExecutableValue(
50
+ rawValue: string,
51
+ options: ExecutableValidationOptions,
52
+ ): string {
53
+ const allowBareExecutable = options.allowBareExecutable ?? true;
54
+ const requireExistingPath = options.requireExistingPath ?? false;
55
+ const cwd = options.cwd ?? process.cwd();
56
+ const trimmed = stripBalancedWrappingQuotes(rawValue.trim());
57
+
58
+ validateCommonExecutableSyntax(trimmed, options.label);
59
+
60
+ if (!looksLikePath(trimmed)) {
61
+ if (!allowBareExecutable) {
62
+ throw new Error(`${options.label} must be an executable path.`);
63
+ }
64
+ if (!BARE_EXECUTABLE_PATTERN.test(trimmed)) {
65
+ throw new Error(`${options.label} must be a single executable name without arguments.`);
66
+ }
67
+ return trimmed;
68
+ }
69
+
70
+ const normalized = isAbsolute(trimmed) ? resolve(trimmed) : resolve(cwd, trimmed);
71
+ validateCommonExecutableSyntax(normalized, options.label);
72
+
73
+ if (requireExistingPath && !existsSync(normalized)) {
74
+ throw new Error(
75
+ `${options.label} path does not exist: "${normalized}"\n` +
76
+ `Check the path is correct and the file is accessible, or unset ${options.label}.`,
77
+ );
78
+ }
79
+
80
+ return normalized;
81
+ }
82
+
83
+ export function validateExecutableForSpawn(
84
+ executable: string,
85
+ options: ExecutableValidationOptions,
86
+ ): string {
87
+ return normalizeExecutableValue(executable, {
88
+ ...options,
89
+ requireExistingPath: options.requireExistingPath ?? false,
90
+ });
91
+ }
92
+
93
+ export function validateWindowsBatchExecutableForCmd(
94
+ executable: string,
95
+ label: string,
96
+ ): void {
97
+ if (!hasWindowsBatchExtension(executable)) return;
98
+ if (WINDOWS_BATCH_METACHARACTER_PATTERN.test(executable)) {
99
+ throw new Error(`${label} contains characters that are unsafe for cmd.exe batch launch.`);
100
+ }
101
+ }
@@ -0,0 +1,50 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import test from "node:test";
6
+ import { loadProjectInstructions } from "./projectInstructions.js";
7
+
8
+ function withTempWorkspace(run: (workspaceRoot: string) => void) {
9
+ const workspaceRoot = mkdtempSync(join(tmpdir(), "codexa-instructions-"));
10
+ try {
11
+ run(workspaceRoot);
12
+ } finally {
13
+ rmSync(workspaceRoot, { recursive: true, force: true });
14
+ }
15
+ }
16
+
17
+ test("loads AGENTS.md from the workspace root first", () => {
18
+ withTempWorkspace((workspaceRoot) => {
19
+ mkdirSync(join(workspaceRoot, ".codex"), { recursive: true });
20
+ writeFileSync(join(workspaceRoot, "AGENTS.md"), "root instructions\n", "utf8");
21
+ writeFileSync(join(workspaceRoot, ".codex", "AGENTS.md"), "nested instructions\n", "utf8");
22
+
23
+ const result = loadProjectInstructions(workspaceRoot);
24
+
25
+ assert.equal(result.status, "loaded");
26
+ if (result.status !== "loaded") return;
27
+ assert.equal(result.instructions.content, "root instructions");
28
+ assert.match(result.instructions.path, /AGENTS\.md$/);
29
+ });
30
+ });
31
+
32
+ test("falls back to .codex/AGENTS.md", () => {
33
+ withTempWorkspace((workspaceRoot) => {
34
+ mkdirSync(join(workspaceRoot, ".codex"), { recursive: true });
35
+ writeFileSync(join(workspaceRoot, ".codex", "AGENTS.md"), "project instructions\n", "utf8");
36
+
37
+ const result = loadProjectInstructions(workspaceRoot);
38
+
39
+ assert.equal(result.status, "loaded");
40
+ if (result.status !== "loaded") return;
41
+ assert.equal(result.instructions.content, "project instructions");
42
+ assert.match(result.instructions.path, /\.codex[\\/]AGENTS\.md$/);
43
+ });
44
+ });
45
+
46
+ test("treats missing instruction files as non-fatal", () => {
47
+ withTempWorkspace((workspaceRoot) => {
48
+ assert.deepEqual(loadProjectInstructions(workspaceRoot), { status: "missing" });
49
+ });
50
+ });
@@ -0,0 +1,54 @@
1
+ import { existsSync, readFileSync } from "fs";
2
+ import { join } from "path";
3
+
4
+ export interface ProjectInstructions {
5
+ path: string;
6
+ content: string;
7
+ }
8
+
9
+ export type ProjectInstructionsLoadResult =
10
+ | { status: "loaded"; instructions: ProjectInstructions }
11
+ | { status: "missing" }
12
+ | { status: "error"; path: string; message: string };
13
+
14
+ const PROJECT_INSTRUCTION_CANDIDATES = [
15
+ "AGENTS.md",
16
+ join(".codex", "AGENTS.md"),
17
+ ] as const;
18
+
19
+ export function loadProjectInstructions(workspaceRoot: string): ProjectInstructionsLoadResult {
20
+ let firstError: Extract<ProjectInstructionsLoadResult, { status: "error" }> | null = null;
21
+
22
+ for (const relativePath of PROJECT_INSTRUCTION_CANDIDATES) {
23
+ const candidatePath = join(workspaceRoot, relativePath);
24
+ if (!existsSync(candidatePath)) {
25
+ continue;
26
+ }
27
+
28
+ try {
29
+ const content = readFileSync(candidatePath, "utf8").trim();
30
+ if (!content) {
31
+ continue;
32
+ }
33
+ return {
34
+ status: "loaded",
35
+ instructions: {
36
+ path: candidatePath,
37
+ content,
38
+ },
39
+ };
40
+ } catch (error) {
41
+ firstError ??= {
42
+ status: "error",
43
+ path: candidatePath,
44
+ message: error instanceof Error ? error.message : String(error),
45
+ };
46
+ }
47
+ }
48
+
49
+ if (firstError) {
50
+ return firstError;
51
+ }
52
+
53
+ return { status: "missing" };
54
+ }
@@ -0,0 +1,238 @@
1
+ import assert from "node:assert/strict";
2
+ import { EventEmitter } from "events";
3
+ import test from "node:test";
4
+ import { buildProviderLaunchSpec, launchProviderCli } from "./launcher.js";
5
+ import type { ProviderConfig } from "./types.js";
6
+
7
+ function makeProvider(overrides: Partial<ProviderConfig> = {}): ProviderConfig {
8
+ return {
9
+ id: "openai",
10
+ displayName: "OpenAI",
11
+ currentModel: "gpt-5.4",
12
+ backendType: "codex-cli-auth",
13
+ routeMode: "in-codexa",
14
+ enabled: true,
15
+ statusLabel: "Enabled",
16
+ launchCommand: { executable: "codex", args: [] },
17
+ isDefault: true,
18
+ isActiveRoute: true,
19
+ routeUnavailableReason: null,
20
+ ...overrides,
21
+ };
22
+ }
23
+
24
+ test("builds launch specs for enabled providers", () => {
25
+ const spec = buildProviderLaunchSpec(makeProvider({
26
+ launchCommand: { executable: "claude", args: ["--resume"] },
27
+ }), "C:\\Workspace");
28
+
29
+ assert.equal("status" in spec, false);
30
+ if ("status" in spec) return;
31
+ assert.equal(spec.executable, "claude");
32
+ assert.deepEqual(spec.args, ["--resume"]);
33
+ assert.equal(spec.cwd, "C:\\Workspace");
34
+ });
35
+
36
+ test("disabled providers fail before spawning", () => {
37
+ const result = buildProviderLaunchSpec(makeProvider({
38
+ id: "local",
39
+ displayName: "Local",
40
+ backendType: "local-openai-compatible",
41
+ enabled: false,
42
+ statusLabel: "Disabled",
43
+ launchCommand: null,
44
+ isDefault: false,
45
+ }), "C:\\Workspace");
46
+
47
+ assert.equal("status" in result, true);
48
+ assert.equal("status" in result ? result.status : "", "disabled");
49
+ assert.match("status" in result ? result.message : "", /Configure a command/i);
50
+ });
51
+
52
+ test("unsafe configured launch commands fail before spawning", () => {
53
+ const result = buildProviderLaunchSpec(makeProvider({
54
+ launchCommand: { executable: "codex & calc", args: [] },
55
+ }), "C:\\Workspace");
56
+
57
+ assert.equal("status" in result, true);
58
+ assert.equal("status" in result ? result.status : "", "spawn-error");
59
+ assert.match("status" in result ? result.message : "", /unsafe launch command/i);
60
+ });
61
+
62
+ test("missing command spawn errors become friendly launch results", async () => {
63
+ const child = new EventEmitter();
64
+ const spawnImpl = (() => {
65
+ queueMicrotask(() => {
66
+ const error = new Error("not found") as NodeJS.ErrnoException;
67
+ error.code = "ENOENT";
68
+ child.emit("error", error);
69
+ });
70
+ return child;
71
+ }) as unknown as typeof import("child_process").spawn;
72
+
73
+ const result = await launchProviderCli(makeProvider(), {
74
+ cwd: "C:\\Workspace",
75
+ commandExists: () => true,
76
+ spawnImpl,
77
+ });
78
+
79
+ assert.equal(result.status, "missing-command");
80
+ assert.match(result.message, /codex.*PATH/i);
81
+ });
82
+
83
+ test("missing command preflight fails before suspending raw mode", async () => {
84
+ const rawModes: boolean[] = [];
85
+ let didSpawn = false;
86
+
87
+ const result = await launchProviderCli(makeProvider(), {
88
+ cwd: "C:\\Workspace",
89
+ stdin: {
90
+ isRaw: true,
91
+ setRawMode(enabled) {
92
+ rawModes.push(enabled);
93
+ },
94
+ },
95
+ commandExists: () => false,
96
+ spawnImpl: (() => {
97
+ didSpawn = true;
98
+ return new EventEmitter();
99
+ }) as unknown as typeof import("child_process").spawn,
100
+ });
101
+
102
+ assert.equal(result.status, "missing-command");
103
+ assert.equal(didSpawn, false);
104
+ assert.deepEqual(rawModes, []);
105
+ });
106
+
107
+ test("launch restores raw mode after child exits", async () => {
108
+ const child = new EventEmitter();
109
+ const rawModes: boolean[] = [];
110
+ const spawnImpl = (() => {
111
+ queueMicrotask(() => child.emit("close", 0, null));
112
+ return child;
113
+ }) as unknown as typeof import("child_process").spawn;
114
+
115
+ const result = await launchProviderCli(makeProvider(), {
116
+ cwd: "C:\\Workspace",
117
+ stdin: {
118
+ isRaw: true,
119
+ setRawMode(enabled) {
120
+ rawModes.push(enabled);
121
+ },
122
+ },
123
+ commandExists: () => true,
124
+ spawnImpl,
125
+ });
126
+
127
+ assert.equal(result.status, "completed");
128
+ assert.deepEqual(rawModes, [false, true]);
129
+ });
130
+
131
+ test("launch passes the workspace root as the child cwd", async () => {
132
+ const child = new EventEmitter();
133
+ let observedCwd = "";
134
+ let observedShell: boolean | undefined = undefined;
135
+ const spawnImpl = ((_executable: string, _args: string[], options: { cwd?: string; shell?: boolean }) => {
136
+ observedCwd = options.cwd ?? "";
137
+ observedShell = options.shell;
138
+ queueMicrotask(() => child.emit("close", 0, null));
139
+ return child;
140
+ }) as unknown as typeof import("child_process").spawn;
141
+
142
+ const result = await launchProviderCli(makeProvider(), {
143
+ cwd: "C:\\Workspace\\Project",
144
+ commandExists: () => true,
145
+ spawnImpl,
146
+ });
147
+
148
+ assert.equal(result.status, "completed");
149
+ assert.equal(observedCwd, "C:\\Workspace\\Project");
150
+ assert.equal(observedShell, false);
151
+ });
152
+
153
+ test("launch wraps Windows batch commands without enabling shell mode", async () => {
154
+ if (process.platform !== "win32") return;
155
+
156
+ const child = new EventEmitter();
157
+ let observedExecutable = "";
158
+ let observedArgs: string[] = [];
159
+ let observedShell: boolean | undefined = undefined;
160
+ const spawnImpl = ((executable: string, args: string[], options: { shell?: boolean }) => {
161
+ observedExecutable = executable;
162
+ observedArgs = args;
163
+ observedShell = options.shell;
164
+ queueMicrotask(() => child.emit("close", 0, null));
165
+ return child;
166
+ }) as unknown as typeof import("child_process").spawn;
167
+
168
+ const result = await launchProviderCli(makeProvider({
169
+ launchCommand: { executable: "codex.cmd", args: ["--resume"] },
170
+ }), {
171
+ cwd: "C:\\Workspace",
172
+ commandExists: () => true,
173
+ spawnImpl,
174
+ });
175
+
176
+ assert.equal(result.status, "completed");
177
+ assert.equal(observedExecutable, "cmd.exe");
178
+ assert.deepEqual(observedArgs, ["/d", "/s", "/c", "call", "codex.cmd", "--resume"]);
179
+ assert.equal(observedShell, false);
180
+ });
181
+
182
+ test("launch runs suspend and resume hooks around raw mode changes", async () => {
183
+ const child = new EventEmitter();
184
+ const events: string[] = [];
185
+ const spawnImpl = (() => {
186
+ events.push("spawn");
187
+ queueMicrotask(() => child.emit("close", 0, null));
188
+ return child;
189
+ }) as unknown as typeof import("child_process").spawn;
190
+
191
+ const result = await launchProviderCli(makeProvider(), {
192
+ cwd: "C:\\Workspace",
193
+ stdin: {
194
+ isRaw: true,
195
+ setRawMode(enabled) {
196
+ events.push(enabled ? "raw-on" : "raw-off");
197
+ },
198
+ },
199
+ beforeLaunch: () => events.push("before"),
200
+ afterLaunch: () => events.push("after"),
201
+ commandExists: () => true,
202
+ spawnImpl,
203
+ });
204
+
205
+ assert.equal(result.status, "completed");
206
+ assert.deepEqual(events, ["before", "raw-off", "spawn", "raw-on", "after"]);
207
+ });
208
+
209
+ test("launch restores terminal state after child spawn error", async () => {
210
+ const child = new EventEmitter();
211
+ const events: string[] = [];
212
+ const spawnImpl = (() => {
213
+ events.push("spawn");
214
+ queueMicrotask(() => {
215
+ const error = new Error("blocked") as NodeJS.ErrnoException;
216
+ error.code = "EPERM";
217
+ child.emit("error", error);
218
+ });
219
+ return child;
220
+ }) as unknown as typeof import("child_process").spawn;
221
+
222
+ const result = await launchProviderCli(makeProvider(), {
223
+ cwd: "C:\\Workspace",
224
+ stdin: {
225
+ isRaw: true,
226
+ setRawMode(enabled) {
227
+ events.push(enabled ? "raw-on" : "raw-off");
228
+ },
229
+ },
230
+ beforeLaunch: () => events.push("before"),
231
+ afterLaunch: () => events.push("after"),
232
+ commandExists: () => true,
233
+ spawnImpl,
234
+ });
235
+
236
+ assert.equal(result.status, "spawn-error");
237
+ assert.deepEqual(events, ["before", "raw-off", "spawn", "raw-on", "after"]);
238
+ });
@@ -0,0 +1,203 @@
1
+ import { spawn, type ChildProcess } from "child_process";
2
+ import { existsSync } from "fs";
3
+ import { buildSpawnSpec } from "../executables/executableResolver.js";
4
+ import { normalizeExecutableValue } from "../process/processValidation.js";
5
+ import type { ProviderConfig, ProviderLaunchCommand } from "./types.js";
6
+
7
+ export interface ProviderLaunchSpec {
8
+ executable: string;
9
+ args: string[];
10
+ cwd: string;
11
+ }
12
+
13
+ export type ProviderLaunchResult =
14
+ | { status: "completed"; exitCode: number | null; signal: NodeJS.Signals | null; message: string }
15
+ | { status: "disabled"; message: string }
16
+ | { status: "missing-command"; message: string }
17
+ | { status: "spawn-error"; message: string; errorCode?: string };
18
+
19
+ interface RawModeStream {
20
+ isRaw?: boolean;
21
+ setRawMode?: (enabled: boolean) => unknown;
22
+ }
23
+
24
+ export interface LaunchProviderCliOptions {
25
+ cwd: string;
26
+ stdin?: RawModeStream | null;
27
+ beforeLaunch?: () => void;
28
+ afterLaunch?: () => void;
29
+ spawnImpl?: typeof spawn;
30
+ commandExists?: (executable: string) => Promise<boolean> | boolean;
31
+ }
32
+
33
+ function formatCommand(command: ProviderLaunchCommand): string {
34
+ return [command.executable, ...command.args].join(" ");
35
+ }
36
+
37
+ export function buildProviderLaunchSpec(provider: ProviderConfig, cwd: string): ProviderLaunchSpec | ProviderLaunchResult {
38
+ if (!provider.enabled) {
39
+ return {
40
+ status: "disabled",
41
+ message: `${provider.displayName} is disabled. Configure a command in .codexa/providers.json before launching it.`,
42
+ };
43
+ }
44
+
45
+ if (!provider.launchCommand?.executable.trim()) {
46
+ return {
47
+ status: "missing-command",
48
+ message: `${provider.displayName} does not have a launch command configured.`,
49
+ };
50
+ }
51
+
52
+ try {
53
+ return {
54
+ executable: normalizeExecutableValue(provider.launchCommand.executable, {
55
+ label: `${provider.displayName} launch command`,
56
+ cwd,
57
+ }),
58
+ args: provider.launchCommand.args,
59
+ cwd,
60
+ };
61
+ } catch (error) {
62
+ const message = error instanceof Error ? error.message : "Invalid launch command.";
63
+ return {
64
+ status: "spawn-error",
65
+ message: `${provider.displayName} has an unsafe launch command. ${message}`,
66
+ };
67
+ }
68
+ }
69
+
70
+ function setRawMode(stdin: RawModeStream | null | undefined, enabled: boolean): void {
71
+ try {
72
+ stdin?.setRawMode?.(enabled);
73
+ } catch {
74
+ // Some test streams and redirected terminals do not support raw-mode changes.
75
+ }
76
+ }
77
+
78
+ function executableLooksLikePath(executable: string): boolean {
79
+ return /[\\/]/.test(executable) || /^[A-Za-z]:/.test(executable);
80
+ }
81
+
82
+ // Probe-spawns the executable to check if it exits cleanly — used instead of `which`/`where`
83
+ // because path-lookup alone doesn't verify the file is actually runnable.
84
+ function captureProcessExit(executable: string, args: string[]): Promise<boolean> {
85
+ return new Promise((resolve) => {
86
+ let child: ChildProcess;
87
+ try {
88
+ child = spawn(executable, args, {
89
+ stdio: "ignore",
90
+ shell: false,
91
+ });
92
+ } catch {
93
+ resolve(false);
94
+ return;
95
+ }
96
+
97
+ child.once("error", () => resolve(false));
98
+ child.once("close", (exitCode) => resolve(exitCode === 0));
99
+ });
100
+ }
101
+
102
+ export async function commandExistsOnPath(executable: string): Promise<boolean> {
103
+ const trimmed = executable.trim();
104
+ if (!trimmed) return false;
105
+ if (executableLooksLikePath(trimmed)) {
106
+ return existsSync(trimmed);
107
+ }
108
+
109
+ if (process.platform === "win32") {
110
+ return captureProcessExit("where.exe", [trimmed]);
111
+ }
112
+
113
+ return captureProcessExit("sh", ["-c", `command -v "$1" >/dev/null 2>&1`, "sh", trimmed]);
114
+ }
115
+
116
+ function formatSpawnError(provider: ProviderConfig, executable: string, error: NodeJS.ErrnoException): ProviderLaunchResult {
117
+ if (error.code === "ENOENT") {
118
+ return {
119
+ status: "missing-command",
120
+ message: `${provider.displayName} could not be launched because \`${executable}\` is not installed or not available on PATH.`,
121
+ };
122
+ }
123
+
124
+ if (error.code === "EACCES" || error.code === "EPERM") {
125
+ return {
126
+ status: "spawn-error",
127
+ errorCode: error.code,
128
+ message: `${provider.displayName} could not be launched because permission was denied for \`${executable}\`.`,
129
+ };
130
+ }
131
+
132
+ return {
133
+ status: "spawn-error",
134
+ errorCode: error.code,
135
+ message: `${provider.displayName} could not be launched. ${error.message}`,
136
+ };
137
+ }
138
+
139
+ export async function launchProviderCli(
140
+ provider: ProviderConfig,
141
+ options: LaunchProviderCliOptions,
142
+ ): Promise<ProviderLaunchResult> {
143
+ const spec = buildProviderLaunchSpec(provider, options.cwd);
144
+ if ("status" in spec) return spec;
145
+
146
+ const spawnImpl = options.spawnImpl ?? spawn;
147
+ const commandExists = options.commandExists ?? commandExistsOnPath;
148
+ const available = await commandExists(spec.executable);
149
+ if (!available) {
150
+ return {
151
+ status: "missing-command",
152
+ message: `${provider.displayName} could not be launched because \`${spec.executable}\` is not installed or not available on PATH.`,
153
+ };
154
+ }
155
+
156
+ const wasRaw = Boolean(options.stdin?.isRaw);
157
+ options.beforeLaunch?.();
158
+ setRawMode(options.stdin, false);
159
+
160
+ try {
161
+ return await new Promise<ProviderLaunchResult>((resolve) => {
162
+ let child: ChildProcess;
163
+ try {
164
+ const spawnSpec = buildSpawnSpec(spec.executable, spec.args);
165
+ child = spawnImpl(spawnSpec.executable, spawnSpec.args, {
166
+ cwd: spec.cwd,
167
+ shell: false,
168
+ stdio: "inherit",
169
+ });
170
+ } catch (error) {
171
+ resolve(formatSpawnError(provider, spec.executable, error as NodeJS.ErrnoException));
172
+ return;
173
+ }
174
+
175
+ child.once("error", (error: NodeJS.ErrnoException) => {
176
+ resolve(formatSpawnError(provider, spec.executable, error));
177
+ });
178
+
179
+ child.once("close", (exitCode, signal) => {
180
+ resolve({
181
+ status: "completed",
182
+ exitCode,
183
+ signal,
184
+ message: `${provider.displayName} launch finished${exitCode === null ? "" : ` with exit code ${exitCode}`}.`,
185
+ });
186
+ });
187
+ });
188
+ } finally {
189
+ if (wasRaw) {
190
+ setRawMode(options.stdin, true);
191
+ }
192
+ options.afterLaunch?.();
193
+ }
194
+ }
195
+
196
+ export function describeProviderLaunch(provider: ProviderConfig): string {
197
+ if (!provider.enabled) {
198
+ return `${provider.displayName} is disabled.`;
199
+ }
200
+ return provider.launchCommand
201
+ ? `${provider.displayName}: ${formatCommand(provider.launchCommand)}`
202
+ : `${provider.displayName} has no launch command configured.`;
203
+ }