@golba98/codexa 1.0.2 → 1.0.4

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 (206) hide show
  1. package/README.md +396 -100
  2. package/bin/codexa.js +62 -144
  3. package/package.json +14 -8
  4. package/src/app.tsx +596 -306
  5. package/src/commands/handler.ts +6 -6
  6. package/src/config/buildInfo.ts +2 -2
  7. package/src/config/layeredConfig.ts +1 -1
  8. package/src/config/persistence.ts +10 -0
  9. package/src/config/runtimeConfig.ts +1 -1
  10. package/src/config/settings.ts +8 -16
  11. package/src/config/trustStore.ts +1 -1
  12. package/src/config/updateCheckCache.ts +19 -1
  13. package/src/core/README.md +52 -0
  14. package/src/core/agent/loop.ts +282 -0
  15. package/src/core/agent/protocol.ts +211 -0
  16. package/src/core/agent/tools.ts +414 -0
  17. package/src/core/{codexExecArgs.ts → codex/codexExecArgs.ts} +2 -2
  18. package/src/core/{codexLaunch.ts → codex/codexLaunch.ts} +3 -3
  19. package/src/core/{codexPrompt.ts → codex/codexPrompt.ts} +3 -3
  20. package/src/core/debug/modelStateDebug.ts +34 -0
  21. package/src/core/executables/antigravityExecutable.ts +48 -0
  22. package/src/core/executables/codexExecutable.ts +1 -0
  23. package/src/core/executables/executableResolver.ts +65 -43
  24. package/src/core/perf/renderDebug.ts +10 -6
  25. package/src/core/process/processValidation.ts +9 -5
  26. package/src/core/providerLauncher/launcher.ts +59 -42
  27. package/src/core/providerLauncher/registry.ts +30 -14
  28. package/src/core/providerLauncher/types.ts +11 -9
  29. package/src/core/providerLauncher/workspaceConfig.ts +41 -26
  30. package/src/core/providerRuntime/anthropic.ts +7 -1
  31. package/src/core/providerRuntime/antigravity.ts +305 -0
  32. package/src/core/providerRuntime/claudeCodeDiscovery.ts +268 -22
  33. package/src/core/providerRuntime/claudeCodeDiscoveryDebug.ts +55 -0
  34. package/src/core/providerRuntime/contextMetadata.ts +12 -24
  35. package/src/core/providerRuntime/local.ts +129 -51
  36. package/src/core/providerRuntime/models.ts +22 -11
  37. package/src/core/providerRuntime/registry.ts +58 -31
  38. package/src/core/providerRuntime/types.ts +19 -14
  39. package/src/core/providers/codexSubprocess.ts +2 -2
  40. package/src/core/providers/types.ts +1 -1
  41. package/src/core/{attachments.ts → shared/attachments.ts} +27 -4
  42. package/src/core/{cleanupFastFail.ts → shared/cleanupFastFail.ts} +1 -1
  43. package/src/core/{hollowResponseFormat.ts → shared/hollowResponseFormat.ts} +1 -1
  44. package/src/core/terminal/clearFrameBoundary.ts +814 -0
  45. package/src/core/terminal/frameLock.ts +109 -0
  46. package/src/core/terminal/inkRenderReset.ts +123 -0
  47. package/src/core/terminal/terminalControl.ts +22 -0
  48. package/src/core/terminal/terminalTitle.ts +16 -102
  49. package/src/core/version/channel.ts +23 -0
  50. package/src/core/version/updateCheck.ts +193 -0
  51. package/src/core/{launchContext.ts → workspace/launchContext.ts} +32 -39
  52. package/src/core/{planStorage.ts → workspace/planStorage.ts} +2 -2
  53. package/src/core/{workspaceGuard.ts → workspace/workspaceGuard.ts} +97 -13
  54. package/src/headless/execRunner.ts +2 -2
  55. package/src/index.tsx +43 -89
  56. package/src/session/appSession.ts +10 -7
  57. package/src/session/chatLifecycle.ts +1 -1
  58. package/src/session/liveRenderScheduler.ts +1 -1
  59. package/src/session/types.ts +3 -2
  60. package/src/ui/ActionRequiredBlock.tsx +5 -5
  61. package/src/ui/ActivityBars.tsx +3 -3
  62. package/src/ui/ActivityIndicator.tsx +6 -6
  63. package/src/ui/AgentBlock.tsx +6 -6
  64. package/src/ui/AnimatedStatusText.tsx +1 -1
  65. package/src/ui/AppShell.tsx +670 -719
  66. package/src/ui/AttachmentImportPanel.tsx +8 -8
  67. package/src/ui/AuthPanel.tsx +20 -20
  68. package/src/ui/BottomComposer.tsx +158 -118
  69. package/src/ui/DashCard.tsx +3 -3
  70. package/src/ui/Markdown.tsx +17 -17
  71. package/src/ui/ModelPickerScreen.tsx +222 -42
  72. package/src/ui/ModelReasoningPicker.tsx +15 -15
  73. package/src/ui/Panel.tsx +3 -3
  74. package/src/ui/PlanActionPicker.tsx +6 -6
  75. package/src/ui/PlanReviewPanel.tsx +9 -9
  76. package/src/ui/ProviderPicker.tsx +735 -321
  77. package/src/ui/RunFooter.tsx +3 -3
  78. package/src/ui/RuntimeStatusBar.tsx +108 -0
  79. package/src/ui/SelectionPanel.tsx +8 -4
  80. package/src/ui/SettingsPanel.tsx +9 -9
  81. package/src/ui/Spinner.tsx +1 -1
  82. package/src/ui/TextEntryPanel.tsx +11 -11
  83. package/src/ui/ThinkingBlock.tsx +8 -8
  84. package/src/ui/Timeline.tsx +1625 -1472
  85. package/src/ui/TopHeader.tsx +437 -293
  86. package/src/ui/TranscriptShell.tsx +322 -0
  87. package/src/ui/TurnGroup.tsx +33 -33
  88. package/src/ui/UpdateAvailableCard.tsx +41 -0
  89. package/src/ui/UpdatePromptPanel.tsx +197 -0
  90. package/src/ui/focus.ts +3 -0
  91. package/src/ui/layout.ts +299 -25
  92. package/src/ui/layoutListWindow.ts +145 -0
  93. package/src/ui/logoVariants.ts +103 -0
  94. package/src/ui/modeDisplay.ts +12 -12
  95. package/src/ui/runtimeDisplay.ts +112 -0
  96. package/src/ui/textLayout.ts +15 -4
  97. package/src/ui/theme.tsx +274 -395
  98. package/src/ui/timelineMeasure.ts +218 -136
  99. package/scripts/audit-codexa-capabilities.mjs +0 -466
  100. package/scripts/gen-build-info.mjs +0 -33
  101. package/scripts/smoke-terminal-bench.mjs +0 -35
  102. package/src/appRenderStability.test.ts +0 -131
  103. package/src/commands/handler.test.ts +0 -655
  104. package/src/config/launchArgs.test.ts +0 -189
  105. package/src/config/layeredConfig.test.ts +0 -143
  106. package/src/config/persistence.test.ts +0 -114
  107. package/src/config/runtimeConfig.test.ts +0 -218
  108. package/src/config/settings.test.ts +0 -155
  109. package/src/config/trustStore.test.ts +0 -29
  110. package/src/core/attachments.test.ts +0 -155
  111. package/src/core/auth/codexAuth.test.ts +0 -68
  112. package/src/core/cleanupFastFail.test.ts +0 -76
  113. package/src/core/codex.ts +0 -124
  114. package/src/core/codexExecArgs.test.ts +0 -195
  115. package/src/core/codexLaunch.test.ts +0 -205
  116. package/src/core/codexPrompt.test.ts +0 -252
  117. package/src/core/executables/codexExecutable.test.ts +0 -212
  118. package/src/core/executables/executableResolver.test.ts +0 -129
  119. package/src/core/executables/geminiExecutable.test.ts +0 -116
  120. package/src/core/executables/pathSanityScan.test.ts +0 -47
  121. package/src/core/githubDiagnostics.test.ts +0 -92
  122. package/src/core/hollowResponseFormat.test.ts +0 -58
  123. package/src/core/launchContext.test.ts +0 -157
  124. package/src/core/models/codexCapabilities.test.ts +0 -45
  125. package/src/core/models/codexModelCapabilities.test.ts +0 -246
  126. package/src/core/models/modelSpecs.test.ts +0 -283
  127. package/src/core/perf/renderDebug.test.ts +0 -230
  128. package/src/core/planStorage.test.ts +0 -143
  129. package/src/core/process/CommandRunner.test.ts +0 -105
  130. package/src/core/projectInstructions.test.ts +0 -50
  131. package/src/core/providerLauncher/launcher.test.ts +0 -238
  132. package/src/core/providerLauncher/registry.test.ts +0 -324
  133. package/src/core/providerLauncher/workspaceConfig.test.ts +0 -638
  134. package/src/core/providerRuntime/anthropic.test.ts +0 -1120
  135. package/src/core/providerRuntime/capabilityProfile.test.ts +0 -311
  136. package/src/core/providerRuntime/contextMetadata.test.ts +0 -468
  137. package/src/core/providerRuntime/gemini.test.ts +0 -437
  138. package/src/core/providerRuntime/lmstudio.test.ts +0 -168
  139. package/src/core/providerRuntime/local.test.ts +0 -787
  140. package/src/core/providerRuntime/registry.test.ts +0 -233
  141. package/src/core/providers/codexJsonStream.test.ts +0 -148
  142. package/src/core/providers/codexSubprocess.test.ts +0 -68
  143. package/src/core/providers/codexTranscript.test.ts +0 -284
  144. package/src/core/terminal/startupClear.test.ts +0 -55
  145. package/src/core/terminal/terminalCapabilities.test.ts +0 -93
  146. package/src/core/terminal/terminalControl.test.ts +0 -75
  147. package/src/core/terminal/terminalSanitize.test.ts +0 -22
  148. package/src/core/terminal/terminalSelection.test.ts +0 -42
  149. package/src/core/terminal/terminalTitle.test.ts +0 -328
  150. package/src/core/updateCheck.test.ts +0 -194
  151. package/src/core/updateCheck.ts +0 -172
  152. package/src/core/workspaceActivity.test.ts +0 -163
  153. package/src/core/workspaceGuard.test.ts +0 -151
  154. package/src/core/workspaceRoot.test.ts +0 -23
  155. package/src/exec.test.ts +0 -13
  156. package/src/headless/execArgs.test.ts +0 -147
  157. package/src/headless/execRunner.test.ts +0 -436
  158. package/src/index.test.tsx +0 -620
  159. package/src/session/appSession.test.ts +0 -897
  160. package/src/session/chatLifecycle.test.ts +0 -64
  161. package/src/session/liveRenderScheduler.test.ts +0 -201
  162. package/src/session/planFlow.test.ts +0 -103
  163. package/src/session/planTranscript.test.ts +0 -65
  164. package/src/session/promptRunSchedule.test.ts +0 -36
  165. package/src/ui/ActivityIndicator.test.tsx +0 -58
  166. package/src/ui/AgentBlock.test.ts +0 -6
  167. package/src/ui/AnimatedStatusText.test.ts +0 -16
  168. package/src/ui/AppShell.test.tsx +0 -1776
  169. package/src/ui/AttachmentImportPanel.test.tsx +0 -204
  170. package/src/ui/BottomComposer.test.ts +0 -674
  171. package/src/ui/CodexLogo.tsx +0 -55
  172. package/src/ui/Markdown.test.ts +0 -157
  173. package/src/ui/ModelPickerProviderScope.test.tsx +0 -411
  174. package/src/ui/ModelPickerScreen.test.tsx +0 -99
  175. package/src/ui/ModelPickerState.test.tsx +0 -151
  176. package/src/ui/ModelReasoningPicker.test.tsx +0 -447
  177. package/src/ui/PlanReviewPanel.test.tsx +0 -267
  178. package/src/ui/PromptCardBorder.test.tsx +0 -161
  179. package/src/ui/ProviderPicker.test.tsx +0 -289
  180. package/src/ui/ProviderShortcut.test.tsx +0 -143
  181. package/src/ui/SettingsPanel.test.tsx +0 -233
  182. package/src/ui/StaticTranscriptItem.tsx +0 -56
  183. package/src/ui/Timeline.test.ts +0 -2067
  184. package/src/ui/TimelineNavigation.test.tsx +0 -201
  185. package/src/ui/TopHeader.test.tsx +0 -254
  186. package/src/ui/TurnGroup.test.tsx +0 -365
  187. package/src/ui/busyStatusAnimation.test.ts +0 -30
  188. package/src/ui/commandNormalize.test.ts +0 -142
  189. package/src/ui/diffRenderer.test.ts +0 -102
  190. package/src/ui/focusFlow.test.tsx +0 -1098
  191. package/src/ui/inputBuffer.test.ts +0 -151
  192. package/src/ui/layout.test.ts +0 -146
  193. package/src/ui/modeDisplay.test.ts +0 -42
  194. package/src/ui/runActivityView.test.ts +0 -89
  195. package/src/ui/runLifecycleView.test.tsx +0 -237
  196. package/src/ui/statusRenderIsolation.test.tsx +0 -654
  197. package/src/ui/terminalAnswerFormat.test.ts +0 -19
  198. package/src/ui/textLayout.test.ts +0 -18
  199. package/src/ui/themeFlow.test.ts +0 -53
  200. package/src/ui/timelineMeasureCache.test.ts +0 -986
  201. /package/src/core/{inputDebug.ts → debug/inputDebug.ts} +0 -0
  202. /package/src/core/{clipboard.ts → shared/clipboard.ts} +0 -0
  203. /package/src/core/{githubDiagnostics.ts → shared/githubDiagnostics.ts} +0 -0
  204. /package/src/core/{projectInstructions.ts → workspace/projectInstructions.ts} +0 -0
  205. /package/src/core/{workspaceActivity.ts → workspace/workspaceActivity.ts} +0 -0
  206. /package/src/core/{workspaceRoot.ts → workspace/workspaceRoot.ts} +0 -0
@@ -0,0 +1,211 @@
1
+ export type AgentToolName =
2
+ | "list_files"
3
+ | "read_file"
4
+ | "write_file"
5
+ | "apply_patch"
6
+ | "run_shell"
7
+ | "get_workspace_info";
8
+
9
+ export interface ParsedAgentToolCall {
10
+ kind: "tool_call";
11
+ name: AgentToolName;
12
+ arguments: Record<string, unknown>;
13
+ raw: string;
14
+ }
15
+
16
+ export interface NormalizedAgentToolCall {
17
+ name: AgentToolName;
18
+ arguments: Record<string, unknown>;
19
+ }
20
+
21
+ export interface MalformedAgentToolCall {
22
+ kind: "malformed_tool_call";
23
+ raw: string;
24
+ error: string;
25
+ }
26
+
27
+ export type AgentToolParseResult =
28
+ | { kind: "final"; text: string }
29
+ | ParsedAgentToolCall
30
+ | MalformedAgentToolCall;
31
+
32
+ const TOOL_CALL_PATTERN = /<tool_call>([\s\S]*?)<\/tool_call>/i;
33
+ const TOOL_CALL_OPEN_PATTERN = /<tool_call\b[^>]*>/i;
34
+
35
+ const TOOL_NAMES = new Set<AgentToolName>([
36
+ "list_files",
37
+ "read_file",
38
+ "write_file",
39
+ "apply_patch",
40
+ "run_shell",
41
+ "get_workspace_info",
42
+ ]);
43
+
44
+ function isRecord(value: unknown): value is Record<string, unknown> {
45
+ return typeof value === "object" && value !== null && !Array.isArray(value);
46
+ }
47
+
48
+ function parseJsonMaybeWithExtraBrace(raw: string): unknown {
49
+ try {
50
+ return JSON.parse(raw) as unknown;
51
+ } catch (firstError) {
52
+ const trimmed = raw.trim();
53
+ if (trimmed.endsWith("}")) {
54
+ try {
55
+ return JSON.parse(trimmed.slice(0, -1)) as unknown;
56
+ } catch {
57
+ // Return the original parse error below.
58
+ }
59
+ }
60
+ throw firstError;
61
+ }
62
+ }
63
+
64
+ function parseArguments(value: unknown): Record<string, unknown> | null {
65
+ if (value === undefined || value === null) return {};
66
+ if (isRecord(value)) return value;
67
+ if (typeof value === "string") {
68
+ try {
69
+ const parsed = JSON.parse(value) as unknown;
70
+ return isRecord(parsed) ? parsed : null;
71
+ } catch {
72
+ return null;
73
+ }
74
+ }
75
+ return null;
76
+ }
77
+
78
+ export function normalizeAgentToolCall(value: unknown): NormalizedAgentToolCall | null {
79
+ if (!isRecord(value)) return null;
80
+
81
+ const functionCall = isRecord(value.function) ? value.function : null;
82
+ const rawName = functionCall?.name ?? value.name ?? value.tool;
83
+ if (typeof rawName !== "string" || !TOOL_NAMES.has(rawName as AgentToolName)) {
84
+ return null;
85
+ }
86
+
87
+ const args = parseArguments(functionCall?.arguments ?? value.arguments ?? value.args);
88
+ if (!args) return null;
89
+
90
+ return {
91
+ name: rawName as AgentToolName,
92
+ arguments: args,
93
+ };
94
+ }
95
+
96
+ export function parseOpenAiToolCalls(value: unknown): NormalizedAgentToolCall[] {
97
+ if (!Array.isArray(value)) return [];
98
+ return value
99
+ .map((item) => normalizeAgentToolCall(item))
100
+ .filter((item): item is NormalizedAgentToolCall => Boolean(item));
101
+ }
102
+
103
+ function extractJsonObjectAfterToolCall(text: string): string | null {
104
+ const open = TOOL_CALL_OPEN_PATTERN.exec(text);
105
+ if (!open) return null;
106
+
107
+ const startSearch = open.index + open[0].length;
108
+ const firstBrace = text.indexOf("{", startSearch);
109
+ if (firstBrace < 0) return text.slice(startSearch).trim();
110
+
111
+ let depth = 0;
112
+ let inString = false;
113
+ let escaped = false;
114
+ for (let index = firstBrace; index < text.length; index += 1) {
115
+ const char = text[index];
116
+ if (escaped) {
117
+ escaped = false;
118
+ continue;
119
+ }
120
+ if (char === "\\") {
121
+ escaped = inString;
122
+ continue;
123
+ }
124
+ if (char === "\"") {
125
+ inString = !inString;
126
+ continue;
127
+ }
128
+ if (inString) continue;
129
+ if (char === "{") depth += 1;
130
+ if (char === "}") {
131
+ depth -= 1;
132
+ if (depth === 0) {
133
+ return text.slice(firstBrace, index + 1).trim();
134
+ }
135
+ }
136
+ }
137
+
138
+ return text.slice(firstBrace).replace(/<\/tool_call>.*/is, "").trim();
139
+ }
140
+
141
+ function parseToolCallPayload(raw: string): AgentToolParseResult {
142
+ try {
143
+ const parsed = parseJsonMaybeWithExtraBrace(raw);
144
+ const fromToolCalls = isRecord(parsed) ? parseOpenAiToolCalls(parsed.tool_calls) : [];
145
+ const normalized = fromToolCalls[0] ?? normalizeAgentToolCall(parsed);
146
+ if (!normalized) {
147
+ return { kind: "malformed_tool_call", raw, error: "Tool call JSON did not contain a supported tool call." };
148
+ }
149
+
150
+ return {
151
+ kind: "tool_call",
152
+ ...normalized,
153
+ raw,
154
+ };
155
+ } catch (error) {
156
+ return {
157
+ kind: "malformed_tool_call",
158
+ raw,
159
+ error: error instanceof Error ? error.message : String(error),
160
+ };
161
+ }
162
+ }
163
+
164
+ export function parseAgentToolCall(text: string): AgentToolParseResult {
165
+ const closedMatch = TOOL_CALL_PATTERN.exec(text);
166
+ const raw = closedMatch?.[1]?.trim() ?? extractJsonObjectAfterToolCall(text);
167
+ if (!raw) {
168
+ return TOOL_CALL_OPEN_PATTERN.test(text)
169
+ ? { kind: "malformed_tool_call", raw: "", error: "Tool call block did not contain JSON." }
170
+ : { kind: "final", text };
171
+ }
172
+
173
+ return parseToolCallPayload(raw);
174
+ }
175
+
176
+ function scalar(value: unknown): string {
177
+ if (value === undefined || value === null) return "";
178
+ if (typeof value === "string") return value;
179
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
180
+ return JSON.stringify(value);
181
+ }
182
+
183
+ function blockField(name: string, value: unknown): string[] {
184
+ return [`${name}:`, scalar(value)];
185
+ }
186
+
187
+ export function serializeToolResult(result: unknown): string {
188
+ const record = isRecord(result) ? result : {};
189
+ const tool = typeof record.tool === "string" ? record.tool : "unknown";
190
+ const lines: string[] = [`<tool_result name="${tool}">`];
191
+
192
+ lines.push(`success: ${scalar(record.success)}`);
193
+ if (record.command !== undefined) lines.push(`command: ${scalar(record.command)}`);
194
+ if (record.path !== undefined) lines.push(`path: ${scalar(record.path)}`);
195
+ if (record.paths !== undefined) lines.push(`paths: ${Array.isArray(record.paths) ? record.paths.join(", ") : scalar(record.paths)}`);
196
+ if (record.exitCode !== undefined) lines.push(`exit_code: ${scalar(record.exitCode)}`);
197
+ if (record.durationMs !== undefined) lines.push(`duration_ms: ${scalar(record.durationMs)}`);
198
+ if (record.summary !== undefined) lines.push(...blockField("summary", record.summary));
199
+ if (record.error !== undefined) lines.push(...blockField("error", record.error));
200
+
201
+ if (tool === "run_shell") {
202
+ lines.push(...blockField("stdout", record.stdout ?? record.output ?? ""));
203
+ lines.push(...blockField("stderr", record.stderr ?? ""));
204
+ } else if (record.output !== undefined) {
205
+ lines.push(...blockField("output", record.output));
206
+ }
207
+
208
+ if (record.raw !== undefined) lines.push(...blockField("raw", record.raw));
209
+ lines.push("</tool_result>");
210
+ return lines.join("\n");
211
+ }
@@ -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
+ }