@golba98/codexa 1.0.3 → 1.0.5

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 (125) hide show
  1. package/README.md +17 -18
  2. package/bin/codexa.js +62 -144
  3. package/package.json +4 -3
  4. package/src/app.tsx +642 -303
  5. package/src/commands/handler.ts +7 -18
  6. package/src/config/buildInfo.ts +2 -2
  7. package/src/config/layeredConfig.ts +1 -1
  8. package/src/config/runtimeConfig.ts +1 -1
  9. package/src/config/settings.ts +1 -1
  10. package/src/config/trustStore.ts +1 -1
  11. package/src/core/README.md +52 -0
  12. package/src/core/agent/loop.ts +282 -0
  13. package/src/core/agent/protocol.ts +211 -0
  14. package/src/core/agent/tools.ts +414 -0
  15. package/src/core/{codexExecArgs.ts → codex/codexExecArgs.ts} +2 -2
  16. package/src/core/{codexLaunch.ts → codex/codexLaunch.ts} +3 -3
  17. package/src/core/{codexPrompt.ts → codex/codexPrompt.ts} +3 -3
  18. package/src/core/debug/modelStateDebug.ts +34 -0
  19. package/src/core/executables/antigravityExecutable.ts +48 -0
  20. package/src/core/executables/executableResolver.ts +5 -1
  21. package/src/core/models/codexModelCapabilities.ts +57 -4
  22. package/src/core/models/codexModelsCacheSeed.ts +153 -0
  23. package/src/core/models/providerModelCache.ts +106 -0
  24. package/src/core/perf/renderDebug.ts +10 -6
  25. package/src/core/process/CommandRunner.ts +12 -1
  26. package/src/core/providerLauncher/registry.ts +64 -18
  27. package/src/core/providerLauncher/types.ts +12 -9
  28. package/src/core/providerLauncher/workspaceConfig.ts +41 -26
  29. package/src/core/providerRuntime/anthropic.ts +10 -6
  30. package/src/core/providerRuntime/antigravity.ts +461 -0
  31. package/src/core/providerRuntime/claudeCodeDiscovery.ts +724 -446
  32. package/src/core/providerRuntime/claudeCodeDiscoveryDebug.ts +55 -0
  33. package/src/core/providerRuntime/contextMetadata.ts +12 -24
  34. package/src/core/providerRuntime/local.ts +129 -51
  35. package/src/core/providerRuntime/mistralVibe.ts +663 -0
  36. package/src/core/providerRuntime/models.ts +40 -15
  37. package/src/core/providerRuntime/reasoning.ts +9 -6
  38. package/src/core/providerRuntime/registry.ts +76 -4
  39. package/src/core/providerRuntime/types.ts +20 -14
  40. package/src/core/providers/codexSubprocess.ts +2 -2
  41. package/src/core/providers/types.ts +1 -1
  42. package/src/core/{attachments.ts → shared/attachments.ts} +27 -4
  43. package/src/core/{cleanupFastFail.ts → shared/cleanupFastFail.ts} +1 -1
  44. package/src/core/{hollowResponseFormat.ts → shared/hollowResponseFormat.ts} +1 -1
  45. package/src/core/terminal/clearFrameBoundary.ts +814 -0
  46. package/src/core/terminal/frameLock.ts +109 -0
  47. package/src/core/terminal/inkRenderReset.ts +123 -0
  48. package/src/core/terminal/terminalControl.ts +22 -0
  49. package/src/core/terminal/terminalTitle.ts +16 -102
  50. package/src/core/{channel.ts → version/channel.ts} +1 -1
  51. package/src/core/{updateCheck.ts → version/updateCheck.ts} +10 -5
  52. package/src/core/{launchContext.ts → workspace/launchContext.ts} +9 -16
  53. package/src/core/{planStorage.ts → workspace/planStorage.ts} +2 -2
  54. package/src/core/{workspaceGuard.ts → workspace/workspaceGuard.ts} +97 -13
  55. package/src/headless/execRunner.ts +2 -2
  56. package/src/index.tsx +66 -98
  57. package/src/session/appSession.ts +10 -7
  58. package/src/session/chatLifecycle.ts +1 -1
  59. package/src/session/liveRenderScheduler.ts +1 -1
  60. package/src/session/types.ts +1 -1
  61. package/src/test/runtimeTestUtils.ts +90 -0
  62. package/src/ui/{ActivityBars.tsx → chrome/ActivityBars.tsx} +1 -1
  63. package/src/ui/{ActivityIndicator.tsx → chrome/ActivityIndicator.tsx} +3 -3
  64. package/src/ui/{AnimatedStatusText.tsx → chrome/AnimatedStatusText.tsx} +3 -3
  65. package/src/ui/chrome/AppShell.tsx +672 -0
  66. package/src/ui/{BottomComposer.tsx → chrome/BottomComposer.tsx} +159 -158
  67. package/src/ui/{DashCard.tsx → chrome/DashCard.tsx} +2 -2
  68. package/src/ui/{RunFooter.tsx → chrome/RunFooter.tsx} +3 -3
  69. package/src/ui/chrome/RuntimeStatusBar.tsx +108 -0
  70. package/src/ui/{Spinner.tsx → chrome/Spinner.tsx} +1 -1
  71. package/src/ui/{TopHeader.tsx → chrome/TopHeader.tsx} +54 -38
  72. package/src/ui/{UpdateAvailableCard.tsx → chrome/UpdateAvailableCard.tsx} +5 -5
  73. package/src/ui/{commandNormalize.ts → input/commandNormalize.ts} +1 -1
  74. package/src/ui/{focus.ts → input/focus.ts} +1 -1
  75. package/src/ui/{inputBuffer.ts → input/inputBuffer.ts} +3 -3
  76. package/src/ui/layout.ts +298 -24
  77. package/src/ui/{AttachmentImportPanel.tsx → panels/AttachmentImportPanel.tsx} +3 -3
  78. package/src/ui/{AuthPanel.tsx → panels/AuthPanel.tsx} +5 -5
  79. package/src/ui/{BackendPicker.tsx → panels/BackendPicker.tsx} +2 -2
  80. package/src/ui/{ModePicker.tsx → panels/ModePicker.tsx} +2 -2
  81. package/src/ui/{ModelPicker.tsx → panels/ModelPicker.tsx} +2 -2
  82. package/src/ui/{ModelPickerScreen.tsx → panels/ModelPickerScreen.tsx} +224 -42
  83. package/src/ui/{ModelReasoningPicker.tsx → panels/ModelReasoningPicker.tsx} +5 -5
  84. package/src/ui/{Panel.tsx → panels/Panel.tsx} +1 -1
  85. package/src/ui/{PermissionsPanel.tsx → panels/PermissionsPanel.tsx} +3 -3
  86. package/src/ui/{PlanActionPicker.tsx → panels/PlanActionPicker.tsx} +2 -2
  87. package/src/ui/{PlanReviewPanel.tsx → panels/PlanReviewPanel.tsx} +5 -5
  88. package/src/ui/panels/ProviderPicker.tsx +737 -0
  89. package/src/ui/{ReasoningPicker.tsx → panels/ReasoningPicker.tsx} +3 -3
  90. package/src/ui/{SelectionPanel.tsx → panels/SelectionPanel.tsx} +5 -1
  91. package/src/ui/{SettingsPanel.tsx → panels/SettingsPanel.tsx} +4 -4
  92. package/src/ui/{TextEntryPanel.tsx → panels/TextEntryPanel.tsx} +4 -4
  93. package/src/ui/{ThemePicker.tsx → panels/ThemePicker.tsx} +2 -2
  94. package/src/ui/{UpdatePromptPanel.tsx → panels/UpdatePromptPanel.tsx} +17 -23
  95. package/src/ui/{Markdown.tsx → render/Markdown.tsx} +2 -2
  96. package/src/ui/{diffRenderer.ts → render/diffRenderer.ts} +1 -1
  97. package/src/ui/{logoVariants.ts → render/logoVariants.ts} +4 -8
  98. package/src/ui/{modeDisplay.ts → render/modeDisplay.ts} +2 -2
  99. package/src/ui/{outputPipeline.ts → render/outputPipeline.ts} +2 -2
  100. package/src/ui/{runtimeDisplay.ts → render/runtimeDisplay.ts} +23 -10
  101. package/src/ui/{textLayout.ts → render/textLayout.ts} +15 -4
  102. package/src/ui/{ActionRequiredBlock.tsx → timeline/ActionRequiredBlock.tsx} +3 -3
  103. package/src/ui/{AgentBlock.tsx → timeline/AgentBlock.tsx} +10 -10
  104. package/src/ui/{StaticIntroItem.tsx → timeline/StaticIntroItem.tsx} +2 -2
  105. package/src/ui/{ThinkingBlock.tsx → timeline/ThinkingBlock.tsx} +4 -4
  106. package/src/ui/{Timeline.tsx → timeline/Timeline.tsx} +1620 -1471
  107. package/src/ui/timeline/TranscriptShell.tsx +322 -0
  108. package/src/ui/{TurnGroup.tsx → timeline/TurnGroup.tsx} +15 -15
  109. package/src/ui/timeline/layoutListWindow.ts +145 -0
  110. package/src/ui/{progressEntries.ts → timeline/progressEntries.ts} +3 -3
  111. package/src/ui/{runActivityView.ts → timeline/runActivityView.ts} +1 -1
  112. package/src/ui/{timelineMeasure.ts → timeline/timelineMeasure.ts} +206 -134
  113. package/src/core/codex.ts +0 -124
  114. package/src/ui/AppShell.tsx +0 -706
  115. package/src/ui/ProviderPicker.tsx +0 -321
  116. package/src/ui/StaticTranscriptItem.tsx +0 -56
  117. /package/src/core/{inputDebug.ts → debug/inputDebug.ts} +0 -0
  118. /package/src/core/{clipboard.ts → shared/clipboard.ts} +0 -0
  119. /package/src/core/{githubDiagnostics.ts → shared/githubDiagnostics.ts} +0 -0
  120. /package/src/core/{projectInstructions.ts → workspace/projectInstructions.ts} +0 -0
  121. /package/src/core/{workspaceActivity.ts → workspace/workspaceActivity.ts} +0 -0
  122. /package/src/core/{workspaceRoot.ts → workspace/workspaceRoot.ts} +0 -0
  123. /package/src/ui/{busyStatusAnimation.ts → chrome/busyStatusAnimation.ts} +0 -0
  124. /package/src/ui/{slashCommands.ts → input/slashCommands.ts} +0 -0
  125. /package/src/ui/{terminalAnswerFormat.ts → render/terminalAnswerFormat.ts} +0 -0
@@ -0,0 +1,414 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import type { ResolvedRuntimeConfig } from "../../config/runtimeConfig.js";
5
+ import { runShellCommand, summarizeCommandResult } from "../process/CommandRunner.js";
6
+ import { sanitizeTerminalOutput } from "../terminal/terminalSanitize.js";
7
+ import {
8
+ getShellWorkspaceGuardMessage,
9
+ isPathInsideAllowedRoots,
10
+ resolveWorkspacePath,
11
+ } from "../workspace/workspaceGuard.js";
12
+ import type { AgentToolName } from "./protocol.js";
13
+
14
+ export interface AgentToolContext {
15
+ workspaceRoot: string;
16
+ runtime: ResolvedRuntimeConfig;
17
+ signal?: AbortSignal;
18
+ }
19
+
20
+ export interface AgentToolResult {
21
+ success: boolean;
22
+ tool: AgentToolName;
23
+ path?: string;
24
+ command?: string;
25
+ paths?: string[];
26
+ output?: string;
27
+ stdout?: string;
28
+ stderr?: string;
29
+ exitCode?: number | null;
30
+ durationMs?: number;
31
+ summary?: string;
32
+ error?: string;
33
+ }
34
+
35
+ const MAX_FILE_BYTES = 128 * 1024;
36
+ const MAX_OUTPUT_CHARS = 4_000;
37
+ const MAX_OUTPUT_LINES = 80;
38
+ const SHELL_TIMEOUT_MS = 30_000;
39
+
40
+ const DANGEROUS_SHELL_PATTERNS: RegExp[] = [
41
+ /\brm\s+-[^\n;|&]*r[f]?\b/i,
42
+ /\bsudo\b/i,
43
+ /\bdoas\b/i,
44
+ /\bdd\s+.*\bof=/i,
45
+ /\bmkfs(?:\.[a-z0-9]+)?\b/i,
46
+ /\bshutdown\b/i,
47
+ /\breboot\b/i,
48
+ /\bpoweroff\b/i,
49
+ /\bchmod\s+-R\s+777\b/i,
50
+ /:\(\)\s*\{\s*:\|:\s*&\s*\}\s*;/,
51
+ />\s*\/dev\/(?:sd|hd|nvme|disk)/i,
52
+ ];
53
+
54
+ function preview(text: string, maxChars = MAX_OUTPUT_CHARS): string {
55
+ const sanitized = sanitizeTerminalOutput(text);
56
+ return sanitized.length > maxChars ? `${sanitized.slice(0, maxChars)}\n...[truncated]` : sanitized;
57
+ }
58
+
59
+ function trimOutputLines(text: string, preferTail: boolean): string {
60
+ const sanitized = sanitizeTerminalOutput(text).replace(/\r\n/g, "\n").replace(/\r/g, "\n");
61
+ const lines = sanitized.split("\n");
62
+ if (lines.at(-1) === "") lines.pop();
63
+ if (lines.length <= MAX_OUTPUT_LINES) return sanitized;
64
+ const visible = preferTail ? lines.slice(-MAX_OUTPUT_LINES) : lines.slice(0, MAX_OUTPUT_LINES);
65
+ const hidden = lines.length - visible.length;
66
+ const marker = `[...${hidden} line${hidden === 1 ? "" : "s"} truncated; showing ${preferTail ? "last" : "first"} ${MAX_OUTPUT_LINES} lines...]`;
67
+ return preferTail
68
+ ? [marker, ...visible].join("\n")
69
+ : [...visible, marker].join("\n");
70
+ }
71
+
72
+ function stringArg(args: Record<string, unknown>, key: string): string | null {
73
+ const value = args[key];
74
+ return typeof value === "string" && value.trim() ? value : null;
75
+ }
76
+
77
+ function isReadOnly(runtime: ResolvedRuntimeConfig): boolean {
78
+ return runtime.policy.sandboxMode === "read-only";
79
+ }
80
+
81
+ function canWrite(runtime: ResolvedRuntimeConfig): boolean {
82
+ return runtime.policy.sandboxMode === "workspace-write"
83
+ || runtime.policy.sandboxMode === "danger-full-access";
84
+ }
85
+
86
+ function relativeDisplay(workspaceRoot: string, absolutePath: string): string {
87
+ const relative = path.relative(workspaceRoot, absolutePath).split(path.sep).join("/");
88
+ return relative || ".";
89
+ }
90
+
91
+ function hasCargoManifest(workspaceRoot: string): boolean {
92
+ return existsSync(path.join(workspaceRoot, "Cargo.toml"));
93
+ }
94
+
95
+ function rustCommandGuard(command: string, context: AgentToolContext): string | null {
96
+ if (!hasCargoManifest(context.workspaceRoot)) return null;
97
+ const normalized = command.trim().replace(/\s+/g, " ");
98
+ const rustcMatch = /^rustc(?:\s+--?[^\s]+)*\s+([^\s]+\.rs)\b/.exec(normalized);
99
+ if (!rustcMatch) return null;
100
+ const target = rustcMatch[1]!;
101
+ const resolved = path.resolve(context.workspaceRoot, target);
102
+ const rootMain = path.join(context.workspaceRoot, "main.rs");
103
+ if (resolved !== rootMain || !existsSync(rootMain)) {
104
+ return "This workspace has Cargo.toml. Use `cargo check` to validate or `cargo run` to run instead of compiling a Rust source file directly with rustc.";
105
+ }
106
+ return null;
107
+ }
108
+
109
+ function resolveAllowedPath(rawPath: string, context: AgentToolContext): { ok: true; absolutePath: string; relativePath: string } | { ok: false; error: string } {
110
+ if (!isPathInsideAllowedRoots(rawPath, context.workspaceRoot, context.runtime.policy.writableRoots)) {
111
+ return { ok: false, error: `Path is outside the workspace: ${rawPath}` };
112
+ }
113
+ const absolutePath = resolveWorkspacePath(rawPath, context.workspaceRoot);
114
+ return {
115
+ ok: true,
116
+ absolutePath,
117
+ relativePath: relativeDisplay(context.workspaceRoot, absolutePath),
118
+ };
119
+ }
120
+
121
+ async function listFiles(args: Record<string, unknown>, context: AgentToolContext): Promise<AgentToolResult> {
122
+ const rawPath = stringArg(args, "path") ?? ".";
123
+ const resolved = resolveAllowedPath(rawPath, context);
124
+ if (!resolved.ok) return { success: false, tool: "list_files", path: rawPath, error: resolved.error };
125
+
126
+ const entries = await readdir(resolved.absolutePath, { withFileTypes: true });
127
+ const names = entries
128
+ .filter((entry) => ![".git", "node_modules", "dist", "build", "coverage"].includes(entry.name))
129
+ .map((entry) => `${entry.name}${entry.isDirectory() ? "/" : ""}`)
130
+ .sort();
131
+ return {
132
+ success: true,
133
+ tool: "list_files",
134
+ path: resolved.relativePath,
135
+ output: names.slice(0, 200).join("\n"),
136
+ summary: `Listed ${names.length} item${names.length === 1 ? "" : "s"}.`,
137
+ };
138
+ }
139
+
140
+ async function readFileTool(args: Record<string, unknown>, context: AgentToolContext): Promise<AgentToolResult> {
141
+ const rawPath = stringArg(args, "path");
142
+ if (!rawPath) return { success: false, tool: "read_file", error: "Missing path." };
143
+ const resolved = resolveAllowedPath(rawPath, context);
144
+ if (!resolved.ok) return { success: false, tool: "read_file", path: rawPath, error: resolved.error };
145
+
146
+ const fileStat = await stat(resolved.absolutePath);
147
+ if (fileStat.size > MAX_FILE_BYTES) {
148
+ return { success: false, tool: "read_file", path: resolved.relativePath, error: "File is too large to read through the agent tool." };
149
+ }
150
+ const content = await readFile(resolved.absolutePath, "utf8");
151
+ return {
152
+ success: true,
153
+ tool: "read_file",
154
+ path: resolved.relativePath,
155
+ output: content,
156
+ summary: `Read ${resolved.relativePath}.`,
157
+ };
158
+ }
159
+
160
+ async function writeFileTool(args: Record<string, unknown>, context: AgentToolContext): Promise<AgentToolResult> {
161
+ if (!canWrite(context.runtime)) {
162
+ return { success: false, tool: "write_file", error: "write_file is blocked by read-only runtime policy." };
163
+ }
164
+ const rawPath = stringArg(args, "path");
165
+ const content = stringArg(args, "content");
166
+ if (!rawPath) return { success: false, tool: "write_file", error: "Missing path." };
167
+ if (content === null) return { success: false, tool: "write_file", path: rawPath, error: "Missing content." };
168
+ const resolved = resolveAllowedPath(rawPath, context);
169
+ if (!resolved.ok) return { success: false, tool: "write_file", path: rawPath, error: resolved.error };
170
+
171
+ await mkdir(path.dirname(resolved.absolutePath), { recursive: true });
172
+ await writeFile(resolved.absolutePath, content, "utf8");
173
+ return {
174
+ success: true,
175
+ tool: "write_file",
176
+ path: resolved.relativePath,
177
+ paths: [resolved.relativePath],
178
+ summary: `Wrote ${resolved.relativePath}.`,
179
+ };
180
+ }
181
+
182
+ function parseApplyPatchPaths(patch: string): string[] {
183
+ const paths: string[] = [];
184
+ for (const line of patch.split(/\r?\n/)) {
185
+ const marker = /^(?:\*\*\* (?:Add|Update|Delete) File:|--- a\/|\+\+\+ b\/)\s*(.+)$/.exec(line);
186
+ if (marker?.[1] && marker[1] !== "/dev/null") {
187
+ paths.push(marker[1].trim());
188
+ }
189
+ }
190
+ return [...new Set(paths)];
191
+ }
192
+
193
+ function applyPatchFormatToContent(before: string, patchLines: string[]): string {
194
+ let contentLines = before.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n");
195
+ if (contentLines.at(-1) === "") contentLines = contentLines.slice(0, -1);
196
+ let cursor = 0;
197
+ let index = 0;
198
+
199
+ while (index < patchLines.length) {
200
+ if (!patchLines[index]?.startsWith("@@")) {
201
+ index += 1;
202
+ continue;
203
+ }
204
+ index += 1;
205
+ const oldLines: string[] = [];
206
+ const newLines: string[] = [];
207
+ while (index < patchLines.length && !patchLines[index]?.startsWith("@@") && !patchLines[index]?.startsWith("*** ")) {
208
+ const line = patchLines[index] ?? "";
209
+ if (line.startsWith(" ")) {
210
+ oldLines.push(line.slice(1));
211
+ newLines.push(line.slice(1));
212
+ } else if (line.startsWith("-")) {
213
+ oldLines.push(line.slice(1));
214
+ } else if (line.startsWith("+")) {
215
+ newLines.push(line.slice(1));
216
+ }
217
+ index += 1;
218
+ }
219
+
220
+ let matchAt = -1;
221
+ for (let candidate = cursor; candidate <= contentLines.length - oldLines.length; candidate += 1) {
222
+ const matches = oldLines.every((line, offset) => contentLines[candidate + offset] === line);
223
+ if (matches) {
224
+ matchAt = candidate;
225
+ break;
226
+ }
227
+ }
228
+ if (matchAt < 0) {
229
+ throw new Error("Patch context did not match the target file.");
230
+ }
231
+ contentLines.splice(matchAt, oldLines.length, ...newLines);
232
+ cursor = matchAt + newLines.length;
233
+ }
234
+
235
+ return `${contentLines.join("\n")}\n`;
236
+ }
237
+
238
+ async function applyPatchFormat(patch: string, context: AgentToolContext): Promise<AgentToolResult> {
239
+ const lines = patch.split(/\r?\n/);
240
+ const changedPaths: string[] = [];
241
+ let index = 0;
242
+
243
+ while (index < lines.length) {
244
+ const add = /^\*\*\* Add File:\s*(.+)$/.exec(lines[index] ?? "");
245
+ const update = /^\*\*\* Update File:\s*(.+)$/.exec(lines[index] ?? "");
246
+ const del = /^\*\*\* Delete File:\s*(.+)$/.exec(lines[index] ?? "");
247
+
248
+ if (add) {
249
+ const resolved = resolveAllowedPath(add[1]!, context);
250
+ if (!resolved.ok) return { success: false, tool: "apply_patch", path: add[1], error: resolved.error };
251
+ index += 1;
252
+ const content: string[] = [];
253
+ while (index < lines.length && !lines[index]?.startsWith("*** ")) {
254
+ const line = lines[index] ?? "";
255
+ if (line.startsWith("+")) content.push(line.slice(1));
256
+ index += 1;
257
+ }
258
+ await mkdir(path.dirname(resolved.absolutePath), { recursive: true });
259
+ await writeFile(resolved.absolutePath, `${content.join("\n")}\n`, "utf8");
260
+ changedPaths.push(resolved.relativePath);
261
+ continue;
262
+ }
263
+
264
+ if (update) {
265
+ const resolved = resolveAllowedPath(update[1]!, context);
266
+ if (!resolved.ok) return { success: false, tool: "apply_patch", path: update[1], error: resolved.error };
267
+ index += 1;
268
+ const patchLines: string[] = [];
269
+ while (index < lines.length && !/^\*\*\* (?:Add|Update|Delete|End)/.test(lines[index] ?? "")) {
270
+ patchLines.push(lines[index] ?? "");
271
+ index += 1;
272
+ }
273
+ const before = await readFile(resolved.absolutePath, "utf8");
274
+ await writeFile(resolved.absolutePath, applyPatchFormatToContent(before, patchLines), "utf8");
275
+ changedPaths.push(resolved.relativePath);
276
+ continue;
277
+ }
278
+
279
+ if (del) {
280
+ const resolved = resolveAllowedPath(del[1]!, context);
281
+ if (!resolved.ok) return { success: false, tool: "apply_patch", path: del[1], error: resolved.error };
282
+ await rm(resolved.absolutePath, { force: true });
283
+ changedPaths.push(resolved.relativePath);
284
+ index += 1;
285
+ continue;
286
+ }
287
+
288
+ index += 1;
289
+ }
290
+
291
+ if (changedPaths.length === 0) {
292
+ return { success: false, tool: "apply_patch", error: "No supported patch operations were found." };
293
+ }
294
+
295
+ return {
296
+ success: true,
297
+ tool: "apply_patch",
298
+ paths: changedPaths,
299
+ summary: `Patched ${changedPaths.join(", ")}.`,
300
+ };
301
+ }
302
+
303
+ async function applyPatchTool(args: Record<string, unknown>, context: AgentToolContext): Promise<AgentToolResult> {
304
+ if (!canWrite(context.runtime)) {
305
+ return { success: false, tool: "apply_patch", error: "apply_patch is blocked by read-only runtime policy." };
306
+ }
307
+ const patch = stringArg(args, "patch");
308
+ if (!patch) return { success: false, tool: "apply_patch", error: "Missing patch." };
309
+
310
+ const explicitPath = stringArg(args, "path");
311
+ const paths = explicitPath ? [explicitPath] : parseApplyPatchPaths(patch);
312
+ for (const patchPath of paths) {
313
+ const resolved = resolveAllowedPath(patchPath, context);
314
+ if (!resolved.ok) return { success: false, tool: "apply_patch", path: patchPath, error: resolved.error };
315
+ }
316
+
317
+ if (!patch.trimStart().startsWith("*** Begin Patch")) {
318
+ return { success: false, tool: "apply_patch", error: "Only *** Begin Patch format is supported by this agent tool." };
319
+ }
320
+
321
+ return applyPatchFormat(patch, context);
322
+ }
323
+
324
+ async function runShellTool(args: Record<string, unknown>, context: AgentToolContext): Promise<AgentToolResult> {
325
+ if (!canWrite(context.runtime) || isReadOnly(context.runtime)) {
326
+ return { success: false, tool: "run_shell", error: "run_shell is blocked by read-only runtime policy." };
327
+ }
328
+ const command = stringArg(args, "command");
329
+ if (!command) return { success: false, tool: "run_shell", error: "Missing command." };
330
+
331
+ if (DANGEROUS_SHELL_PATTERNS.some((pattern) => pattern.test(command))) {
332
+ return { success: false, tool: "run_shell", command, error: "Shell command blocked as dangerous." };
333
+ }
334
+ const rustGuard = rustCommandGuard(command, context);
335
+ if (rustGuard) {
336
+ return { success: false, tool: "run_shell", command, exitCode: null, durationMs: 0, stdout: "", stderr: "", error: rustGuard };
337
+ }
338
+ const workspaceGuard = getShellWorkspaceGuardMessage(command, context.workspaceRoot, context.runtime.policy.writableRoots);
339
+ if (workspaceGuard) {
340
+ return { success: false, tool: "run_shell", command, error: workspaceGuard };
341
+ }
342
+
343
+ const runner = runShellCommand(command, {
344
+ cwd: context.workspaceRoot,
345
+ timeoutMs: SHELL_TIMEOUT_MS,
346
+ });
347
+ const cancel = () => runner.cancel();
348
+ context.signal?.addEventListener("abort", cancel, { once: true });
349
+ try {
350
+ const result = await runner.result;
351
+ const success = result.status === "completed" && result.exitCode === 0;
352
+ const stdout = trimOutputLines(result.stdout, !success);
353
+ const stderr = trimOutputLines(result.stderr, !success);
354
+ const output = preview([stdout, stderr].filter(Boolean).join("\n"));
355
+ return {
356
+ success,
357
+ tool: "run_shell",
358
+ command,
359
+ exitCode: result.exitCode,
360
+ durationMs: result.durationMs,
361
+ stdout,
362
+ stderr,
363
+ output,
364
+ summary: summarizeCommandResult(command, result),
365
+ error: success ? undefined : result.userMessage,
366
+ };
367
+ } finally {
368
+ context.signal?.removeEventListener("abort", cancel);
369
+ }
370
+ }
371
+
372
+ async function getWorkspaceInfo(context: AgentToolContext): Promise<AgentToolResult> {
373
+ return {
374
+ success: true,
375
+ tool: "get_workspace_info",
376
+ path: ".",
377
+ output: JSON.stringify({
378
+ workspaceRoot: context.workspaceRoot,
379
+ sandboxMode: context.runtime.policy.sandboxMode,
380
+ writableRoots: context.runtime.policy.writableRoots,
381
+ packageJson: existsSync(path.join(context.workspaceRoot, "package.json")),
382
+ }),
383
+ summary: "Returned workspace info.",
384
+ };
385
+ }
386
+
387
+ export async function executeAgentTool(
388
+ name: AgentToolName,
389
+ args: Record<string, unknown>,
390
+ context: AgentToolContext,
391
+ ): Promise<AgentToolResult> {
392
+ try {
393
+ switch (name) {
394
+ case "list_files":
395
+ return await listFiles(args, context);
396
+ case "read_file":
397
+ return await readFileTool(args, context);
398
+ case "write_file":
399
+ return await writeFileTool(args, context);
400
+ case "apply_patch":
401
+ return await applyPatchTool(args, context);
402
+ case "run_shell":
403
+ return await runShellTool(args, context);
404
+ case "get_workspace_info":
405
+ return await getWorkspaceInfo(context);
406
+ }
407
+ } catch (error) {
408
+ return {
409
+ success: false,
410
+ tool: name,
411
+ error: error instanceof Error ? error.message : String(error),
412
+ };
413
+ }
414
+ }
@@ -1,5 +1,5 @@
1
- import type { ResolvedRuntimeConfig } from "../config/runtimeConfig.js";
2
- import type { CodexCliCapabilities } from "./models/codexCapabilities.js";
1
+ import type { ResolvedRuntimeConfig } from "../../config/runtimeConfig.js";
2
+ import type { CodexCliCapabilities } from "../models/codexCapabilities.js";
3
3
 
4
4
  export interface BuildCodexExecArgsOptions {
5
5
  runtime: ResolvedRuntimeConfig;
@@ -1,8 +1,8 @@
1
1
  import { fileURLToPath } from "url";
2
2
  import { buildCodexExecArgs, type BuildCodexExecArgsOptions, type BuildCodexExecArgsResult } from "./codexExecArgs.js";
3
- import { getCodexCliCapabilities, type CodexCliCapabilities } from "./models/codexCapabilities.js";
4
- import { resolveCodexExecutable } from "./executables/codexExecutable.js";
5
- import * as perf from "./perf/profiler.js";
3
+ import { getCodexCliCapabilities, type CodexCliCapabilities } from "../models/codexCapabilities.js";
4
+ import { resolveCodexExecutable } from "../executables/codexExecutable.js";
5
+ import * as perf from "../perf/profiler.js";
6
6
 
7
7
  // Assumed capability set when probeCapabilities is false — avoids a slow help-output probe on every run.
8
8
  const MODERN_CODEX_CLI_CAPABILITIES: CodexCliCapabilities = {
@@ -1,6 +1,6 @@
1
- import type { AvailableMode } from "../config/settings.js";
2
- import type { ResolvedRuntimeConfig } from "../config/runtimeConfig.js";
3
- import type { ProjectInstructions } from "./projectInstructions.js";
1
+ import type { AvailableMode } from "../../config/settings.js";
2
+ import type { ResolvedRuntimeConfig } from "../../config/runtimeConfig.js";
3
+ import type { ProjectInstructions } from "../workspace/projectInstructions.js";
4
4
 
5
5
  // ─── Write-intent detection ───────────────────────────────────────────────────
6
6
 
@@ -0,0 +1,34 @@
1
+ import { appendFileSync, mkdirSync } from "fs";
2
+ import { dirname, join } from "path";
3
+
4
+ type ModelStateDebugDetails = Record<string, unknown>;
5
+
6
+ let sequence = 0;
7
+
8
+ export function isModelStateDebugEnabled(): boolean {
9
+ return process.env.CODEXA_RENDER_DEBUG === "1" || process.env.CODEXA_DEBUG_MODEL_STATE === "1";
10
+ }
11
+
12
+ export function getModelStateDebugLogPath(): string {
13
+ return process.env.CODEXA_RENDER_DEBUG_FILE?.trim()
14
+ || process.env.CODEXA_DEBUG_MODEL_STATE_LOG?.trim()
15
+ || join(process.cwd(), ".codexa", "debug", "render-status.log");
16
+ }
17
+
18
+ export function traceModelStateDebug(event: string, details: ModelStateDebugDetails = {}): void {
19
+ if (!isModelStateDebugEnabled()) return;
20
+
21
+ try {
22
+ const entry = {
23
+ ts: new Date().toISOString(),
24
+ seq: ++sequence,
25
+ event,
26
+ ...details,
27
+ };
28
+ const logPath = getModelStateDebugLogPath();
29
+ mkdirSync(dirname(logPath), { recursive: true });
30
+ appendFileSync(logPath, `${JSON.stringify(entry)}\n`, "utf8");
31
+ } catch {
32
+ // Debug logging must never affect the TUI.
33
+ }
34
+ }
@@ -0,0 +1,48 @@
1
+ import { runCommand } from "../process/CommandRunner.js";
2
+ import { resolveExecutable } from "./executableResolver.js";
3
+
4
+ type CommandRunner = typeof runCommand;
5
+
6
+ let cachedExecutable: string | null = null;
7
+
8
+ export function resetAgyExecutableCacheForTests(): void {
9
+ cachedExecutable = null;
10
+ }
11
+
12
+ /**
13
+ * Returns the resolved Antigravity CLI executable (full path or bare name).
14
+ *
15
+ * Priority:
16
+ * 1. Configured path override (antigravityCommandPath)
17
+ * 2. AGY_EXECUTABLE env var
18
+ * 3. Windows PATH lookup for real files: agy.exe, agy.cmd, agy.bat, agy
19
+ * 4. Bare name fallback "agy" (Unix PATH resolution)
20
+ */
21
+ export async function resolveAgyExecutable(options?: {
22
+ runCommandImpl?: CommandRunner;
23
+ cwd?: string;
24
+ configuredPath?: string | null;
25
+ }): Promise<string> {
26
+ if (!options?.configuredPath && !options?.runCommandImpl && cachedExecutable !== null) {
27
+ return cachedExecutable;
28
+ }
29
+
30
+ const result = await resolveExecutable({
31
+ runCommandImpl: options?.runCommandImpl,
32
+ cwd: options?.cwd,
33
+ configuredPath: options?.configuredPath,
34
+ envOverrides: ["AGY_EXECUTABLE"],
35
+ commandNames: process.platform === "win32"
36
+ ? ["agy.exe", "agy.cmd", "agy.bat", "agy"]
37
+ : ["agy"],
38
+ knownPathDirectories: [],
39
+ knownFilePaths: [],
40
+ label: "antigravity",
41
+ allowBareFallback: true,
42
+ });
43
+
44
+ if (!options?.configuredPath && !options?.runCommandImpl) {
45
+ cachedExecutable = result;
46
+ }
47
+ return result;
48
+ }
@@ -139,13 +139,17 @@ export async function resolveExecutable(options: ExecutableResolverOptions): Pro
139
139
  /**
140
140
  * Builds the spawn spec for a resolved executable.
141
141
  * .cmd and .bat files must be invoked via `cmd.exe /d /s /c` on Windows.
142
+ *
143
+ * `platform` defaults to the host platform; it is injectable so the Windows
144
+ * wrapping branch can be unit-tested from any OS.
142
145
  */
143
146
  export function buildSpawnSpec(
144
147
  executable: string,
145
148
  args: string[],
149
+ platform: NodeJS.Platform = process.platform,
146
150
  ): { executable: string; args: string[] } {
147
151
  const validatedExecutable = validateResolvedExecutable(executable, "Executable", process.cwd());
148
- if (process.platform === "win32") {
152
+ if (platform === "win32") {
149
153
  const lower = validatedExecutable.toLowerCase();
150
154
  if (lower.endsWith(".cmd") || lower.endsWith(".bat")) {
151
155
  validateWindowsBatchExecutableForCmd(validatedExecutable, "Windows batch executable");
@@ -1,6 +1,9 @@
1
1
  import { type ChildProcess } from "child_process";
2
2
  import { APP_NAME, APP_VERSION, DEFAULT_MODEL, LEGACY_FALLBACK_MODELS, formatReasoningLabel } from "../../config/settings.js";
3
3
  import { resolveCodexExecutable, spawnCodexProcess } from "../executables/codexExecutable.js";
4
+ import { loadSeededCodexCapabilities } from "./codexModelsCacheSeed.js";
5
+ import { saveCachedProviderModels } from "./providerModelCache.js";
6
+ import type { ProviderModel } from "../providerRuntime/types.js";
4
7
 
5
8
  export type ModelCapabilitySource = "runtime" | "fallback";
6
9
  export type ModelCapabilityStatus = "ready" | "fallback";
@@ -47,6 +50,8 @@ export interface GetCodexModelCapabilitiesOptions extends DiscoverCodexModelCapa
47
50
  ttlMs?: number;
48
51
  resolveExecutable?: typeof resolveCodexExecutable;
49
52
  discover?: typeof discoverCodexModelCapabilities;
53
+ seed?: typeof loadSeededCodexCapabilities;
54
+ persist?: typeof persistCodexModelCapabilities;
50
55
  }
51
56
 
52
57
  interface JsonRpcResponse {
@@ -439,14 +444,36 @@ export async function discoverCodexModelCapabilities(
439
444
  });
440
445
  }
441
446
 
442
- // Cache chain: TTL-based in-memory cache live discovery fallback model list on error.
443
- // Failed discoveries are evicted from the cache so retries are possible.
447
+ // Persist a successful live discovery so the next launch can seed the model
448
+ // picker without spawning the codex app-server. Best-effort by design.
449
+ export function persistCodexModelCapabilities(capabilities: CodexModelCapabilities): void {
450
+ const models: ProviderModel[] = capabilities.models
451
+ .filter((capability) => !capability.hidden)
452
+ .map((capability) => ({
453
+ id: capability.id,
454
+ modelId: capability.model,
455
+ label: capability.label,
456
+ description: capability.description,
457
+ defaultReasoningLevel: capability.defaultReasoningLevel,
458
+ supportedReasoningLevels: capability.supportedReasoningLevels,
459
+ source: "discovered",
460
+ }));
461
+ saveCachedProviderModels("openai", { discoveredAt: capabilities.discoveredAt, models });
462
+ }
463
+
464
+ // Cache chain: TTL-based in-memory cache → live discovery → seeded local caches
465
+ // (codex's own models_cache.json / Codexa's last-good discovery) → static
466
+ // fallback model list. Failed discoveries are evicted from the in-memory cache
467
+ // so retries are possible even when a seed satisfied the request.
444
468
  export async function getCodexModelCapabilities(
445
469
  options: GetCodexModelCapabilitiesOptions = {},
446
470
  ): Promise<CodexModelCapabilities> {
447
471
  const now = options.now?.() ?? Date.now();
448
472
  const ttlMs = options.ttlMs ?? DEFAULT_CACHE_TTL_MS;
473
+ const seed = options.seed ?? loadSeededCodexCapabilities;
474
+ const persist = options.persist ?? persistCodexModelCapabilities;
449
475
  let executable: string | null = null;
476
+ let liveDiscoverySucceeded = false;
450
477
 
451
478
  try {
452
479
  executable = options.executable ?? await (options.resolveExecutable ?? resolveCodexExecutable)();
@@ -462,7 +489,25 @@ export async function getCodexModelCapabilities(
462
489
  includeHidden: options.includeHidden,
463
490
  timeoutMs: options.timeoutMs,
464
491
  now: () => now,
465
- }).catch((error) => createFallbackModelCapabilities(error, { discoveredAt: now, executable }));
492
+ }).then((discovered) => {
493
+ liveDiscoverySucceeded = true;
494
+ try {
495
+ persist(discovered);
496
+ } catch {
497
+ // Persistence must never fail a successful discovery.
498
+ }
499
+ return discovered;
500
+ }).catch((error) => {
501
+ try {
502
+ const seeded = seed();
503
+ if (seeded) {
504
+ return seeded;
505
+ }
506
+ } catch {
507
+ // Seed read failures fall through to the static list.
508
+ }
509
+ return createFallbackModelCapabilities(error, { discoveredAt: now, executable });
510
+ });
466
511
 
467
512
  capabilityCache.set(cacheKey, {
468
513
  expiresAt: now + ttlMs,
@@ -470,12 +515,20 @@ export async function getCodexModelCapabilities(
470
515
  });
471
516
 
472
517
  const result = await promise;
473
- if (result.status === "fallback") {
518
+ if (!liveDiscoverySucceeded) {
474
519
  capabilityCache.delete(cacheKey);
475
520
  }
476
521
 
477
522
  return result;
478
523
  } catch (error) {
524
+ try {
525
+ const seeded = seed();
526
+ if (seeded) {
527
+ return seeded;
528
+ }
529
+ } catch {
530
+ // Seed read failures fall through to the static list.
531
+ }
479
532
  return createFallbackModelCapabilities(error, { discoveredAt: now, executable });
480
533
  }
481
534
  }