@supatest/cli 0.0.5 → 0.0.7

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 (69) hide show
  1. package/dist/index.js +9512 -157
  2. package/package.json +9 -6
  3. package/dist/commands/login.js +0 -392
  4. package/dist/commands/setup.js +0 -234
  5. package/dist/config.js +0 -29
  6. package/dist/core/agent.js +0 -259
  7. package/dist/modes/headless.js +0 -117
  8. package/dist/modes/interactive.js +0 -418
  9. package/dist/presenters/composite.js +0 -32
  10. package/dist/presenters/console.js +0 -163
  11. package/dist/presenters/react.js +0 -217
  12. package/dist/presenters/types.js +0 -1
  13. package/dist/presenters/web.js +0 -78
  14. package/dist/prompts/builder.js +0 -181
  15. package/dist/prompts/fixer.js +0 -148
  16. package/dist/prompts/index.js +0 -3
  17. package/dist/prompts/planner.js +0 -70
  18. package/dist/services/api-client.js +0 -244
  19. package/dist/services/event-streamer.js +0 -130
  20. package/dist/types.js +0 -1
  21. package/dist/ui/App.js +0 -322
  22. package/dist/ui/components/AuthBanner.js +0 -24
  23. package/dist/ui/components/AuthDialog.js +0 -32
  24. package/dist/ui/components/Banner.js +0 -12
  25. package/dist/ui/components/ExpandableSection.js +0 -17
  26. package/dist/ui/components/Header.js +0 -51
  27. package/dist/ui/components/HelpMenu.js +0 -89
  28. package/dist/ui/components/InputPrompt.js +0 -286
  29. package/dist/ui/components/MessageList.js +0 -42
  30. package/dist/ui/components/QueuedMessageDisplay.js +0 -31
  31. package/dist/ui/components/Scrollable.js +0 -103
  32. package/dist/ui/components/SessionSelector.js +0 -196
  33. package/dist/ui/components/StatusBar.js +0 -34
  34. package/dist/ui/components/messages/AssistantMessage.js +0 -20
  35. package/dist/ui/components/messages/ErrorMessage.js +0 -26
  36. package/dist/ui/components/messages/LoadingMessage.js +0 -28
  37. package/dist/ui/components/messages/ThinkingMessage.js +0 -17
  38. package/dist/ui/components/messages/TodoMessage.js +0 -44
  39. package/dist/ui/components/messages/ToolMessage.js +0 -218
  40. package/dist/ui/components/messages/UserMessage.js +0 -14
  41. package/dist/ui/contexts/KeypressContext.js +0 -527
  42. package/dist/ui/contexts/MouseContext.js +0 -98
  43. package/dist/ui/contexts/SessionContext.js +0 -129
  44. package/dist/ui/hooks/useAnimatedScrollbar.js +0 -83
  45. package/dist/ui/hooks/useBatchedScroll.js +0 -22
  46. package/dist/ui/hooks/useBracketedPaste.js +0 -31
  47. package/dist/ui/hooks/useFocus.js +0 -50
  48. package/dist/ui/hooks/useKeypress.js +0 -26
  49. package/dist/ui/hooks/useModeToggle.js +0 -25
  50. package/dist/ui/types/auth.js +0 -13
  51. package/dist/ui/utils/file-completion.js +0 -56
  52. package/dist/ui/utils/input.js +0 -50
  53. package/dist/ui/utils/markdown.js +0 -376
  54. package/dist/ui/utils/mouse.js +0 -189
  55. package/dist/ui/utils/theme.js +0 -59
  56. package/dist/utils/banner.js +0 -9
  57. package/dist/utils/encryption.js +0 -71
  58. package/dist/utils/events.js +0 -36
  59. package/dist/utils/keychain-storage.js +0 -120
  60. package/dist/utils/logger.js +0 -209
  61. package/dist/utils/node-version.js +0 -89
  62. package/dist/utils/plan-file.js +0 -75
  63. package/dist/utils/project-instructions.js +0 -23
  64. package/dist/utils/rich-logger.js +0 -208
  65. package/dist/utils/stdin.js +0 -25
  66. package/dist/utils/stdio.js +0 -80
  67. package/dist/utils/summary.js +0 -94
  68. package/dist/utils/token-storage.js +0 -242
  69. package/dist/version.js +0 -6
@@ -1,259 +0,0 @@
1
- import { createRequire } from "node:module";
2
- import { dirname, join } from "node:path";
3
- import { query } from "@anthropic-ai/claude-agent-sdk";
4
- import { config as envConfig } from "../config";
5
- import { loadProjectInstructions } from "../utils/project-instructions";
6
- export class CoreAgent {
7
- presenter;
8
- abortController = null;
9
- constructor(presenter) {
10
- this.presenter = presenter;
11
- }
12
- /**
13
- * Abort the current query execution.
14
- * This will cancel any running operations including LLM calls and tool executions.
15
- */
16
- abort() {
17
- if (this.abortController) {
18
- this.abortController.abort();
19
- }
20
- }
21
- async run(config) {
22
- // Create a fresh AbortController for this run
23
- this.abortController = new AbortController();
24
- await this.presenter.onStart(config);
25
- // Resolve path to Claude Code executable
26
- const claudeCodePath = await this.resolveClaudeCodePath();
27
- // Build the prompt
28
- let prompt = config.task;
29
- if (config.logs) {
30
- prompt = `${config.task}\n\nHere are the logs to analyze:\n\`\`\`\n${config.logs}\n\`\`\``;
31
- }
32
- // Apply permission mode based on agent mode
33
- // Plan mode uses 'plan' permission which restricts to read-only tools
34
- // Build mode uses 'bypassPermissions' for full tool access
35
- const isPlanMode = config.mode === 'plan';
36
- const cwd = config.cwd || process.cwd();
37
- // Only load system prompt for new sessions - resumed sessions already have it
38
- // This avoids duplicating system prompt tokens on every continuation
39
- const isResumingSession = !!config.providerSessionId;
40
- let systemPromptAppend;
41
- if (!isResumingSession) {
42
- // Load project instructions from SUPATEST.md
43
- const projectInstructions = loadProjectInstructions(cwd);
44
- // Combine system prompts: base prompt + project instructions
45
- systemPromptAppend = [
46
- config.systemPromptAppend,
47
- projectInstructions && `\n\n# Project Instructions (from SUPATEST.md)\n\n${projectInstructions}`,
48
- ].filter(Boolean).join("\n") || undefined;
49
- }
50
- const queryOptions = {
51
- // AbortController for cancellation support
52
- abortController: this.abortController,
53
- maxTurns: config.maxIterations,
54
- cwd,
55
- model: envConfig.anthropicModelName,
56
- permissionMode: isPlanMode ? "plan" : "bypassPermissions",
57
- allowDangerouslySkipPermissions: !isPlanMode,
58
- pathToClaudeCodeExecutable: claudeCodePath,
59
- includePartialMessages: true,
60
- executable: "node",
61
- // MCP servers for enhanced capabilities
62
- mcpServers: {
63
- playwright: {
64
- command: "npx",
65
- args: ["-y", "@playwright/mcp@latest"],
66
- },
67
- },
68
- // Resume from previous session if providerSessionId is provided
69
- // This allows the agent to continue conversations with full context
70
- // Note: Sessions expire after ~30 days due to Anthropic's data retention policy
71
- ...(config.providerSessionId && {
72
- resume: config.providerSessionId,
73
- }),
74
- // Only append system prompt for new sessions - resumed sessions already have context
75
- ...(systemPromptAppend && {
76
- systemPrompt: {
77
- type: "preset",
78
- preset: "claude_code",
79
- append: systemPromptAppend,
80
- },
81
- }),
82
- env: {
83
- ...process.env,
84
- ANTHROPIC_API_KEY: config.supatestApiKey,
85
- ANTHROPIC_BASE_URL: process.env.ANTHROPIC_BASE_URL || "",
86
- ANTHROPIC_AUTH_TOKEN: "",
87
- CLAUDE_CODE_AUTH_TOKEN: "",
88
- },
89
- stderr: (msg) => {
90
- this.presenter.onLog(`[Claude Code stderr] ${msg}`);
91
- },
92
- };
93
- let resultText = "";
94
- let hasError = false;
95
- const errors = [];
96
- let iterations = 0;
97
- const filesModified = new Set();
98
- let wasInterrupted = false;
99
- // Capture the SDK's session_id for future resume capability
100
- let providerSessionId;
101
- // Helper to check if an error indicates an expired/invalid session
102
- const isSessionExpiredError = (errorMsg) => {
103
- const expiredPatterns = [
104
- "no conversation found",
105
- "session not found",
106
- "session expired",
107
- "invalid session",
108
- ];
109
- const lowerError = errorMsg.toLowerCase();
110
- return expiredPatterns.some((pattern) => lowerError.includes(pattern));
111
- };
112
- // Helper to run the query and process messages
113
- const runQuery = async (options) => {
114
- for await (const msg of query({ prompt, options })) {
115
- // Capture session_id from any message that has it
116
- // All SDK messages include session_id which we need for resuming
117
- if ("session_id" in msg && msg.session_id) {
118
- providerSessionId = msg.session_id;
119
- }
120
- if (msg.type === "assistant") {
121
- iterations++;
122
- const content = msg.message.content;
123
- if (Array.isArray(content)) {
124
- for (const block of content) {
125
- if (block.type === "text") {
126
- resultText += block.text + "\n";
127
- await this.presenter.onAssistantText(block.text);
128
- }
129
- else if (block.type === "thinking") {
130
- await this.presenter.onThinking(block.thinking);
131
- }
132
- else if (block.type === "tool_use") {
133
- const toolName = block.name;
134
- const input = block.input;
135
- // Track file modifications
136
- if ((toolName === "Write" || toolName === "Edit") &&
137
- input?.file_path) {
138
- filesModified.add(input.file_path);
139
- }
140
- await this.presenter.onToolUse(toolName, input, block.id);
141
- }
142
- }
143
- }
144
- // Notify presenter that the turn is complete
145
- await this.presenter.onTurnComplete(content);
146
- }
147
- else if (msg.type === "result") {
148
- iterations = msg.num_turns;
149
- if (msg.subtype === "success") {
150
- resultText = msg.result || resultText;
151
- }
152
- else {
153
- hasError = true;
154
- if ("errors" in msg && Array.isArray(msg.errors)) {
155
- errors.push(...msg.errors);
156
- for (const error of msg.errors) {
157
- await this.presenter.onError(error);
158
- }
159
- }
160
- }
161
- }
162
- else if (msg.type === "user") {
163
- // User message contains tool results - end tool timing
164
- const userContent = msg.message?.content;
165
- if (Array.isArray(userContent)) {
166
- for (const block of userContent) {
167
- if (block.type === "tool_result" && block.tool_use_id) {
168
- // Notify presenter of tool result
169
- if (this.presenter.onToolResult) {
170
- const resultContent = Array.isArray(block.content)
171
- ? block.content.map((c) => c.text || "").join("\n")
172
- : typeof block.content === "string"
173
- ? block.content
174
- : "";
175
- await this.presenter.onToolResult(block.tool_use_id, resultContent);
176
- }
177
- }
178
- }
179
- }
180
- }
181
- }
182
- };
183
- try {
184
- await runQuery(queryOptions);
185
- }
186
- catch (error) {
187
- const errorMessage = error instanceof Error ? error.message : String(error);
188
- // Check if this was an abort (user interrupt)
189
- // The SDK may throw AbortError or a message containing "aborted"
190
- const isAbortError = (error instanceof Error && error.name === "AbortError") ||
191
- errorMessage.toLowerCase().includes("aborted");
192
- if (isAbortError) {
193
- wasInterrupted = true;
194
- }
195
- else if (config.providerSessionId && isSessionExpiredError(errorMessage)) {
196
- // If the error indicates an expired session and we were trying to resume,
197
- // show a user-friendly error message
198
- const expiredMessage = "Can't continue conversation older than 30 days. Please start a new session.";
199
- await this.presenter.onError(expiredMessage);
200
- hasError = true;
201
- errors.push(expiredMessage);
202
- }
203
- else {
204
- await this.presenter.onError(errorMessage);
205
- hasError = true;
206
- errors.push(errorMessage);
207
- }
208
- }
209
- const result = {
210
- success: !hasError && errors.length === 0 && !wasInterrupted,
211
- summary: wasInterrupted ? "Interrupted by user" : resultText || "Task completed",
212
- filesModified: Array.from(filesModified),
213
- iterations,
214
- error: wasInterrupted
215
- ? "Interrupted by user"
216
- : errors.length > 0
217
- ? errors.join("; ")
218
- : undefined,
219
- // Include the provider session ID for resume capability
220
- providerSessionId,
221
- };
222
- await this.presenter.onComplete(result);
223
- return result;
224
- }
225
- async resolveClaudeCodePath() {
226
- // Allow override via environment variable
227
- if (envConfig.claudeCodeExecutablePath) {
228
- this.presenter.onLog(`Using CLAUDE_CODE_EXECUTABLE_PATH: ${envConfig.claudeCodeExecutablePath}`);
229
- return envConfig.claudeCodeExecutablePath;
230
- }
231
- // Determine binary directory
232
- const isCompiledBinary = process.execPath && !process.execPath.includes("node");
233
- let claudeCodePath;
234
- if (isCompiledBinary) {
235
- claudeCodePath = join(dirname(process.execPath), "claude-code-cli.js");
236
- this.presenter.onLog(`Production mode: ${claudeCodePath}`);
237
- }
238
- else {
239
- const require = createRequire(import.meta.url);
240
- const sdkPath = require.resolve("@anthropic-ai/claude-agent-sdk/sdk.mjs");
241
- claudeCodePath = join(dirname(sdkPath), "cli.js");
242
- this.presenter.onLog(`Development mode: ${claudeCodePath}`);
243
- }
244
- // Verify the file exists
245
- const fs = await import("node:fs/promises");
246
- try {
247
- await fs.access(claudeCodePath);
248
- this.presenter.onLog(`✓ Claude Code CLI found: ${claudeCodePath}`);
249
- }
250
- catch {
251
- const error = `Claude Code executable not found at: ${claudeCodePath}\n` +
252
- "For compiled binaries, ensure claude-code-cli.js is in the same directory as the binary.\n" +
253
- "Set CLAUDE_CODE_EXECUTABLE_PATH environment variable to override.";
254
- await this.presenter.onError(error);
255
- throw new Error(error);
256
- }
257
- return claudeCodePath;
258
- }
259
- }
@@ -1,117 +0,0 @@
1
- import chalk from "chalk";
2
- import { config as envConfig } from "../config";
3
- import { CoreAgent } from "../core/agent";
4
- import { CompositePresenter } from "../presenters/composite";
5
- import { ConsolePresenter } from "../presenters/console";
6
- import { WebPresenter } from "../presenters/web";
7
- import { ApiClient } from "../services/api-client";
8
- import { logger } from "../utils/logger";
9
- import { CLI_VERSION } from "../version";
10
- export async function runAgent(config) {
11
- // Configure logger
12
- logger.setVerbose(config.verbose);
13
- // --- Metadata Display (CLI only) ---
14
- logger.raw("");
15
- // Get git branch if available
16
- let gitBranch = "";
17
- try {
18
- const { execSync } = await import("node:child_process");
19
- gitBranch = execSync("git rev-parse --abbrev-ref HEAD", {
20
- encoding: "utf8",
21
- stdio: ["pipe", "pipe", "ignore"]
22
- }).trim();
23
- }
24
- catch {
25
- // Not in a git repo or git not available
26
- }
27
- const metadataParts = [
28
- chalk.dim("Supatest AI ") + chalk.cyan(`v${CLI_VERSION}`),
29
- chalk.dim("Model: ") + chalk.cyan(envConfig.anthropicModelName),
30
- ];
31
- if (gitBranch) {
32
- metadataParts.push(chalk.dim("Branch: ") + chalk.cyan(gitBranch));
33
- }
34
- logger.raw(metadataParts.join(chalk.dim(" • ")));
35
- logger.divider();
36
- // --- Session & API Setup ---
37
- const apiUrl = config.supatestApiUrl || "https://code-api.supatest.ai";
38
- const apiClient = new ApiClient(apiUrl, config.supatestApiKey);
39
- let sessionId;
40
- let webUrl;
41
- try {
42
- // Truncate title to 50 characters (backend will auto-generate a better title later)
43
- const truncatedTitle = config.task.length > 50 ? config.task.slice(0, 50) + "..." : config.task;
44
- const session = await apiClient.createSession(truncatedTitle, {
45
- cliVersion: CLI_VERSION,
46
- cwd: config.cwd || process.cwd(),
47
- });
48
- sessionId = session.sessionId;
49
- webUrl = session.webUrl;
50
- logger.raw("");
51
- logger.divider();
52
- logger.raw(chalk.white.bold("View session live: ") +
53
- chalk.cyan.underline(webUrl));
54
- logger.divider();
55
- logger.raw("");
56
- }
57
- catch (error) {
58
- logger.warn(`Failed to create session on backend: ${error.message}`);
59
- logger.warn("Continuing without web streaming...");
60
- }
61
- // --- Environment Setup ---
62
- // Build base URL with session ID embedded for the proxy
63
- let baseUrl = `${apiUrl}/public`;
64
- if (sessionId) {
65
- baseUrl = `${apiUrl}/v1/sessions/${sessionId}/anthropic`;
66
- }
67
- // Set environment variables for the SDK to pick up (via CoreAgent)
68
- process.env.ANTHROPIC_BASE_URL = baseUrl;
69
- process.env.ANTHROPIC_API_KEY = config.supatestApiKey;
70
- // --- Agent Execution ---
71
- const presenters = [];
72
- // 1. Console Presenter (stdout)
73
- presenters.push(new ConsolePresenter({ verbose: config.verbose }));
74
- // 2. Web Presenter (streaming)
75
- if (sessionId) {
76
- presenters.push(new WebPresenter(apiClient, sessionId));
77
- }
78
- const compositePresenter = new CompositePresenter(presenters);
79
- const agent = new CoreAgent(compositePresenter);
80
- try {
81
- const result = await agent.run(config);
82
- // Store the provider session ID for future resume capability
83
- // This allows follow-up messages to continue the conversation with full context
84
- if (sessionId && result.providerSessionId) {
85
- try {
86
- await apiClient.updateSession(sessionId, {
87
- providerSessionId: result.providerSessionId,
88
- });
89
- logger.debug(`Stored provider session ID for resume capability`);
90
- }
91
- catch (updateError) {
92
- // Non-critical - log but don't fail
93
- logger.warn(`Failed to store provider session ID: ${updateError.message}`);
94
- }
95
- }
96
- // Display web URL again at completion
97
- if (webUrl) {
98
- logger.raw("");
99
- logger.divider();
100
- logger.raw(chalk.white.bold("View session: ") +
101
- chalk.cyan.underline(webUrl));
102
- logger.divider();
103
- }
104
- return result;
105
- }
106
- catch (error) {
107
- const errorMessage = error instanceof Error ? error.message : String(error);
108
- // Error is already logged by presenter.onError
109
- return {
110
- success: false,
111
- summary: `Failed: ${errorMessage}`,
112
- filesModified: [],
113
- iterations: 0,
114
- error: errorMessage,
115
- };
116
- }
117
- }