popeye-cli 1.0.1 → 1.1.0
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.
- package/README.md +521 -125
- package/dist/adapters/claude.d.ts +16 -4
- package/dist/adapters/claude.d.ts.map +1 -1
- package/dist/adapters/claude.js +679 -33
- package/dist/adapters/claude.js.map +1 -1
- package/dist/adapters/gemini.d.ts +55 -0
- package/dist/adapters/gemini.d.ts.map +1 -0
- package/dist/adapters/gemini.js +318 -0
- package/dist/adapters/gemini.js.map +1 -0
- package/dist/adapters/openai.d.ts.map +1 -1
- package/dist/adapters/openai.js +41 -7
- package/dist/adapters/openai.js.map +1 -1
- package/dist/auth/claude.d.ts +11 -9
- package/dist/auth/claude.d.ts.map +1 -1
- package/dist/auth/claude.js +107 -71
- package/dist/auth/claude.js.map +1 -1
- package/dist/auth/gemini.d.ts +58 -0
- package/dist/auth/gemini.d.ts.map +1 -0
- package/dist/auth/gemini.js +172 -0
- package/dist/auth/gemini.js.map +1 -0
- package/dist/auth/index.d.ts +11 -7
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/index.js +23 -5
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/keychain.d.ts +20 -7
- package/dist/auth/keychain.d.ts.map +1 -1
- package/dist/auth/keychain.js +85 -29
- package/dist/auth/keychain.js.map +1 -1
- package/dist/auth/openai.d.ts +2 -2
- package/dist/auth/openai.d.ts.map +1 -1
- package/dist/auth/openai.js +30 -32
- package/dist/auth/openai.js.map +1 -1
- package/dist/cli/interactive.d.ts.map +1 -1
- package/dist/cli/interactive.js +1151 -110
- package/dist/cli/interactive.js.map +1 -1
- package/dist/config/defaults.d.ts +6 -1
- package/dist/config/defaults.d.ts.map +1 -1
- package/dist/config/defaults.js +10 -2
- package/dist/config/defaults.js.map +1 -1
- package/dist/config/index.d.ts +10 -0
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/index.js +19 -0
- package/dist/config/index.js.map +1 -1
- package/dist/config/schema.d.ts +20 -0
- package/dist/config/schema.d.ts.map +1 -1
- package/dist/config/schema.js +7 -0
- package/dist/config/schema.js.map +1 -1
- package/dist/generators/python.d.ts.map +1 -1
- package/dist/generators/python.js +1 -0
- package/dist/generators/python.js.map +1 -1
- package/dist/generators/typescript.d.ts.map +1 -1
- package/dist/generators/typescript.js +1 -0
- package/dist/generators/typescript.js.map +1 -1
- package/dist/state/index.d.ts +108 -0
- package/dist/state/index.d.ts.map +1 -1
- package/dist/state/index.js +551 -4
- package/dist/state/index.js.map +1 -1
- package/dist/state/registry.d.ts +52 -0
- package/dist/state/registry.d.ts.map +1 -0
- package/dist/state/registry.js +215 -0
- package/dist/state/registry.js.map +1 -0
- package/dist/types/cli.d.ts +4 -0
- package/dist/types/cli.d.ts.map +1 -1
- package/dist/types/cli.js.map +1 -1
- package/dist/types/consensus.d.ts +69 -4
- package/dist/types/consensus.d.ts.map +1 -1
- package/dist/types/consensus.js +24 -3
- package/dist/types/consensus.js.map +1 -1
- package/dist/types/workflow.d.ts +55 -0
- package/dist/types/workflow.d.ts.map +1 -1
- package/dist/types/workflow.js +16 -0
- package/dist/types/workflow.js.map +1 -1
- package/dist/workflow/auto-fix.d.ts +45 -0
- package/dist/workflow/auto-fix.d.ts.map +1 -0
- package/dist/workflow/auto-fix.js +274 -0
- package/dist/workflow/auto-fix.js.map +1 -0
- package/dist/workflow/consensus.d.ts +44 -2
- package/dist/workflow/consensus.d.ts.map +1 -1
- package/dist/workflow/consensus.js +565 -17
- package/dist/workflow/consensus.js.map +1 -1
- package/dist/workflow/execution-mode.d.ts +10 -4
- package/dist/workflow/execution-mode.d.ts.map +1 -1
- package/dist/workflow/execution-mode.js +547 -58
- package/dist/workflow/execution-mode.js.map +1 -1
- package/dist/workflow/index.d.ts +14 -2
- package/dist/workflow/index.d.ts.map +1 -1
- package/dist/workflow/index.js +69 -6
- package/dist/workflow/index.js.map +1 -1
- package/dist/workflow/milestone-workflow.d.ts +34 -0
- package/dist/workflow/milestone-workflow.d.ts.map +1 -0
- package/dist/workflow/milestone-workflow.js +414 -0
- package/dist/workflow/milestone-workflow.js.map +1 -0
- package/dist/workflow/plan-mode.d.ts +14 -1
- package/dist/workflow/plan-mode.d.ts.map +1 -1
- package/dist/workflow/plan-mode.js +589 -47
- package/dist/workflow/plan-mode.js.map +1 -1
- package/dist/workflow/plan-storage.d.ts +142 -0
- package/dist/workflow/plan-storage.d.ts.map +1 -0
- package/dist/workflow/plan-storage.js +331 -0
- package/dist/workflow/plan-storage.js.map +1 -0
- package/dist/workflow/project-verification.d.ts +37 -0
- package/dist/workflow/project-verification.d.ts.map +1 -0
- package/dist/workflow/project-verification.js +381 -0
- package/dist/workflow/project-verification.js.map +1 -0
- package/dist/workflow/task-workflow.d.ts +37 -0
- package/dist/workflow/task-workflow.d.ts.map +1 -0
- package/dist/workflow/task-workflow.js +383 -0
- package/dist/workflow/task-workflow.js.map +1 -0
- package/dist/workflow/test-runner.d.ts +1 -0
- package/dist/workflow/test-runner.d.ts.map +1 -1
- package/dist/workflow/test-runner.js +9 -5
- package/dist/workflow/test-runner.js.map +1 -1
- package/dist/workflow/ui-designer.d.ts +82 -0
- package/dist/workflow/ui-designer.d.ts.map +1 -0
- package/dist/workflow/ui-designer.js +234 -0
- package/dist/workflow/ui-designer.js.map +1 -0
- package/dist/workflow/ui-setup.d.ts +58 -0
- package/dist/workflow/ui-setup.d.ts.map +1 -0
- package/dist/workflow/ui-setup.js +685 -0
- package/dist/workflow/ui-setup.js.map +1 -0
- package/dist/workflow/ui-verification.d.ts +114 -0
- package/dist/workflow/ui-verification.d.ts.map +1 -0
- package/dist/workflow/ui-verification.js +258 -0
- package/dist/workflow/ui-verification.js.map +1 -0
- package/dist/workflow/workflow-logger.d.ts +110 -0
- package/dist/workflow/workflow-logger.d.ts.map +1 -0
- package/dist/workflow/workflow-logger.js +267 -0
- package/dist/workflow/workflow-logger.js.map +1 -0
- package/package.json +2 -2
- package/src/adapters/claude.ts +815 -34
- package/src/adapters/gemini.ts +373 -0
- package/src/adapters/openai.ts +40 -7
- package/src/auth/claude.ts +120 -78
- package/src/auth/gemini.ts +207 -0
- package/src/auth/index.ts +28 -8
- package/src/auth/keychain.ts +95 -28
- package/src/auth/openai.ts +29 -36
- package/src/cli/interactive.ts +1357 -115
- package/src/config/defaults.ts +10 -2
- package/src/config/index.ts +21 -0
- package/src/config/schema.ts +7 -0
- package/src/generators/python.ts +1 -0
- package/src/generators/typescript.ts +1 -0
- package/src/state/index.ts +713 -4
- package/src/state/registry.ts +278 -0
- package/src/types/cli.ts +4 -0
- package/src/types/consensus.ts +65 -6
- package/src/types/workflow.ts +35 -0
- package/src/workflow/auto-fix.ts +340 -0
- package/src/workflow/consensus.ts +750 -16
- package/src/workflow/execution-mode.ts +673 -74
- package/src/workflow/index.ts +95 -6
- package/src/workflow/milestone-workflow.ts +576 -0
- package/src/workflow/plan-mode.ts +696 -50
- package/src/workflow/plan-storage.ts +482 -0
- package/src/workflow/project-verification.ts +471 -0
- package/src/workflow/task-workflow.ts +525 -0
- package/src/workflow/test-runner.ts +10 -5
- package/src/workflow/ui-designer.ts +337 -0
- package/src/workflow/ui-setup.ts +797 -0
- package/src/workflow/ui-verification.ts +357 -0
- package/src/workflow/workflow-logger.ts +353 -0
- package/tests/config/config.test.ts +1 -1
- package/tests/types/consensus.test.ts +3 -3
- package/tests/workflow/plan-mode.test.ts +213 -0
- package/tests/workflow/test-runner.test.ts +5 -3
package/src/adapters/claude.ts
CHANGED
|
@@ -3,6 +3,9 @@
|
|
|
3
3
|
* Wraps the Claude Agent SDK for code execution and generation
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
+
import { promises as fs } from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { homedir } from 'os';
|
|
6
9
|
import { query, type SDKMessage } from '@anthropic-ai/claude-agent-sdk';
|
|
7
10
|
|
|
8
11
|
/**
|
|
@@ -15,6 +18,287 @@ export interface ClaudeExecuteOptions {
|
|
|
15
18
|
systemPrompt?: string;
|
|
16
19
|
timeout?: number;
|
|
17
20
|
onMessage?: (message: SDKMessage) => void;
|
|
21
|
+
onProgress?: (message: string) => void;
|
|
22
|
+
/**
|
|
23
|
+
* Rate limit handling configuration
|
|
24
|
+
* Set to false to disable rate limit retries
|
|
25
|
+
*/
|
|
26
|
+
rateLimitConfig?: {
|
|
27
|
+
maxRetries?: number;
|
|
28
|
+
baseWaitMs?: number;
|
|
29
|
+
maxWaitMs?: number;
|
|
30
|
+
} | false;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Log directory for debug information
|
|
35
|
+
*/
|
|
36
|
+
const LOG_DIR = path.join(homedir(), '.popeye', 'logs');
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Rate limit handling configuration
|
|
40
|
+
*/
|
|
41
|
+
interface RateLimitConfig {
|
|
42
|
+
maxRetries: number;
|
|
43
|
+
baseWaitMs: number;
|
|
44
|
+
maxWaitMs: number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const DEFAULT_RATE_LIMIT_CONFIG: RateLimitConfig = {
|
|
48
|
+
maxRetries: 5,
|
|
49
|
+
baseWaitMs: 5 * 60_000, // 5 minutes
|
|
50
|
+
maxWaitMs: 2 * 60 * 60_000, // 2 hours
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Parse rate limit reset time from error message
|
|
55
|
+
* Messages like: "You've hit your limit · resets 3pm (Asia/Jerusalem)"
|
|
56
|
+
*/
|
|
57
|
+
function parseRateLimitResetTime(message: string): Date | null {
|
|
58
|
+
// Try to parse time like "3pm", "3:30pm", "15:00"
|
|
59
|
+
const timePatterns = [
|
|
60
|
+
/resets?\s+(\d{1,2}):?(\d{2})?\s*(am|pm)?/i,
|
|
61
|
+
/until\s+(\d{1,2}):?(\d{2})?\s*(am|pm)?/i,
|
|
62
|
+
/wait\s+until\s+(\d{1,2}):?(\d{2})?\s*(am|pm)?/i,
|
|
63
|
+
];
|
|
64
|
+
|
|
65
|
+
for (const pattern of timePatterns) {
|
|
66
|
+
const match = message.match(pattern);
|
|
67
|
+
if (match) {
|
|
68
|
+
let hours = parseInt(match[1], 10);
|
|
69
|
+
const minutes = match[2] ? parseInt(match[2], 10) : 0;
|
|
70
|
+
const ampm = match[3]?.toLowerCase();
|
|
71
|
+
|
|
72
|
+
if (ampm === 'pm' && hours < 12) hours += 12;
|
|
73
|
+
if (ampm === 'am' && hours === 12) hours = 0;
|
|
74
|
+
|
|
75
|
+
const resetTime = new Date();
|
|
76
|
+
resetTime.setHours(hours, minutes, 0, 0);
|
|
77
|
+
|
|
78
|
+
// If the time has passed today, assume tomorrow
|
|
79
|
+
if (resetTime.getTime() <= Date.now()) {
|
|
80
|
+
resetTime.setDate(resetTime.getDate() + 1);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return resetTime;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Try to parse duration like "30 minutes", "1 hour"
|
|
88
|
+
const durationPatterns = [
|
|
89
|
+
/(\d+)\s*minutes?/i,
|
|
90
|
+
/(\d+)\s*hours?/i,
|
|
91
|
+
];
|
|
92
|
+
|
|
93
|
+
for (let i = 0; i < durationPatterns.length; i++) {
|
|
94
|
+
const match = message.match(durationPatterns[i]);
|
|
95
|
+
if (match) {
|
|
96
|
+
const value = parseInt(match[1], 10);
|
|
97
|
+
const multiplier = i === 0 ? 60_000 : 60 * 60_000; // minutes or hours
|
|
98
|
+
return new Date(Date.now() + value * multiplier);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Format wait time for display
|
|
107
|
+
*/
|
|
108
|
+
function formatWaitTime(ms: number): string {
|
|
109
|
+
if (ms < 60_000) {
|
|
110
|
+
return `${Math.ceil(ms / 1000)} seconds`;
|
|
111
|
+
} else if (ms < 60 * 60_000) {
|
|
112
|
+
const minutes = Math.ceil(ms / 60_000);
|
|
113
|
+
return `${minutes} minute${minutes > 1 ? 's' : ''}`;
|
|
114
|
+
} else {
|
|
115
|
+
const hours = Math.floor(ms / (60 * 60_000));
|
|
116
|
+
const minutes = Math.ceil((ms % (60 * 60_000)) / 60_000);
|
|
117
|
+
return `${hours} hour${hours > 1 ? 's' : ''}${minutes > 0 ? ` ${minutes} minute${minutes > 1 ? 's' : ''}` : ''}`;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Sleep for a specified duration with progress updates
|
|
123
|
+
*/
|
|
124
|
+
async function sleepWithProgress(
|
|
125
|
+
ms: number,
|
|
126
|
+
onProgress?: (message: string) => void
|
|
127
|
+
): Promise<void> {
|
|
128
|
+
const startTime = Date.now();
|
|
129
|
+
const endTime = startTime + ms;
|
|
130
|
+
const updateInterval = Math.min(ms / 10, 60_000); // Update every 10% or minute, whichever is smaller
|
|
131
|
+
|
|
132
|
+
while (Date.now() < endTime) {
|
|
133
|
+
const remaining = endTime - Date.now();
|
|
134
|
+
if (remaining <= 0) break;
|
|
135
|
+
|
|
136
|
+
onProgress?.(`Rate limit: waiting ${formatWaitTime(remaining)} before retry...`);
|
|
137
|
+
|
|
138
|
+
const sleepTime = Math.min(updateInterval, remaining);
|
|
139
|
+
await new Promise(resolve => setTimeout(resolve, sleepTime));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Extract just the rate limit message from a larger string
|
|
145
|
+
* e.g., "Some content... You've hit your limit · resets 3pm (Asia/Jerusalem)" -> "You've hit your limit · resets 3pm (Asia/Jerusalem)"
|
|
146
|
+
*/
|
|
147
|
+
function extractRateLimitMessage(content: string): string {
|
|
148
|
+
// Look for specific rate limit error message patterns
|
|
149
|
+
// These patterns are designed to match actual error messages, not plan content
|
|
150
|
+
const patterns = [
|
|
151
|
+
// "You've hit your limit" patterns - common Claude error
|
|
152
|
+
/You['']ve hit your limit[^.\n]*(?:\.[\s]*(?:resets?|try again)[^.\n]*)?/i,
|
|
153
|
+
// "Rate limit exceeded" - explicit error message
|
|
154
|
+
/rate limit exceeded[^.\n]*/i,
|
|
155
|
+
// "rate limited" as verb - "you have been rate limited"
|
|
156
|
+
/(?:you\s+(?:have\s+)?(?:been\s+)?)?rate\s+limited[^.\n]*/i,
|
|
157
|
+
// "too many requests" - HTTP 429 style
|
|
158
|
+
/too many requests[^.\n]*/i,
|
|
159
|
+
// "quota exceeded" - usage limit
|
|
160
|
+
/quota exceeded[^.\n]*/i,
|
|
161
|
+
// "API rate limit" - specific to API errors
|
|
162
|
+
/api\s+rate\s+limit[^.\n]*/i,
|
|
163
|
+
// "request limit" patterns
|
|
164
|
+
/request\s+limit[^.\n]*(?:reached|exceeded|hit)[^.\n]*/i,
|
|
165
|
+
// "usage limit" patterns
|
|
166
|
+
/usage\s+limit[^.\n]*(?:reached|exceeded|hit)[^.\n]*/i,
|
|
167
|
+
];
|
|
168
|
+
|
|
169
|
+
for (const pattern of patterns) {
|
|
170
|
+
const match = content.match(pattern);
|
|
171
|
+
if (match) {
|
|
172
|
+
// Limit matched content to 200 chars to prevent capturing run-on text
|
|
173
|
+
const matched = match[0].trim();
|
|
174
|
+
return matched.length > 200 ? matched.slice(0, 197) + '...' : matched;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// If no pattern matches, try to find the first line that looks like an error
|
|
179
|
+
const lines = content.split('\n').filter(line => line.trim());
|
|
180
|
+
for (const line of lines.slice(0, 5)) {
|
|
181
|
+
const trimmedLine = line.trim();
|
|
182
|
+
// Look for lines that start with error indicators
|
|
183
|
+
if (/^(error|failed|limit|exceeded|denied)/i.test(trimmedLine)) {
|
|
184
|
+
return trimmedLine.length > 200 ? trimmedLine.slice(0, 197) + '...' : trimmedLine;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// If content is short, return it (but cap at 200 chars)
|
|
189
|
+
if (content.length < 200) {
|
|
190
|
+
return content;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Otherwise return a generic message - don't include potentially huge content
|
|
194
|
+
return 'Rate limit detected (details unavailable)';
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Check if an error indicates a rate limit
|
|
199
|
+
* Uses specific patterns to avoid false positives from plan content mentioning rate limiting
|
|
200
|
+
*/
|
|
201
|
+
function isRateLimitError(error: unknown, message?: string): boolean {
|
|
202
|
+
// Patterns that indicate actual rate limit errors (not just mentions of rate limiting)
|
|
203
|
+
// These are more specific than just "rate limit" to avoid matching plan content
|
|
204
|
+
const rateLimitPatterns = [
|
|
205
|
+
/you['']ve hit your limit/i,
|
|
206
|
+
/rate_limit_exceeded/i,
|
|
207
|
+
/rate limit exceeded/i,
|
|
208
|
+
/you have been rate limited/i,
|
|
209
|
+
/too many requests/i,
|
|
210
|
+
/quota exceeded/i,
|
|
211
|
+
/\b429\b/, // HTTP 429 status code
|
|
212
|
+
/rate limited/i, // "rate limited" as a verb phrase
|
|
213
|
+
/api rate limit/i,
|
|
214
|
+
/request limit reached/i,
|
|
215
|
+
/usage limit exceeded/i,
|
|
216
|
+
/limit reached.*try again/i,
|
|
217
|
+
/exceeded.*limit.*retry/i,
|
|
218
|
+
];
|
|
219
|
+
|
|
220
|
+
const checkString = (str: string): boolean => {
|
|
221
|
+
return rateLimitPatterns.some(pattern => pattern.test(str));
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
if (message && checkString(message)) return true;
|
|
225
|
+
|
|
226
|
+
if (error instanceof Error) {
|
|
227
|
+
if (checkString(error.message)) return true;
|
|
228
|
+
if ('code' in error && typeof error.code === 'string' && checkString(error.code)) return true;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (typeof error === 'object' && error !== null) {
|
|
232
|
+
const obj = error as Record<string, unknown>;
|
|
233
|
+
if (typeof obj.error === 'string' && checkString(obj.error)) return true;
|
|
234
|
+
if (typeof obj.code === 'string' && checkString(obj.code)) return true;
|
|
235
|
+
if (typeof obj.message === 'string' && checkString(obj.message)) return true;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
return false;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Write error details to a log file for debugging
|
|
243
|
+
*/
|
|
244
|
+
async function logErrorDetails(
|
|
245
|
+
error: unknown,
|
|
246
|
+
context: {
|
|
247
|
+
prompt?: string;
|
|
248
|
+
lastMessages?: SDKMessage[];
|
|
249
|
+
response?: string;
|
|
250
|
+
}
|
|
251
|
+
): Promise<string> {
|
|
252
|
+
try {
|
|
253
|
+
await fs.mkdir(LOG_DIR, { recursive: true });
|
|
254
|
+
|
|
255
|
+
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
256
|
+
const logFile = path.join(LOG_DIR, `claude-error-${timestamp}.log`);
|
|
257
|
+
|
|
258
|
+
const errorDetails = [
|
|
259
|
+
'='.repeat(80),
|
|
260
|
+
`CLAUDE ERROR LOG - ${new Date().toISOString()}`,
|
|
261
|
+
'='.repeat(80),
|
|
262
|
+
'',
|
|
263
|
+
'## Error Details',
|
|
264
|
+
`Type: ${error instanceof Error ? error.constructor.name : typeof error}`,
|
|
265
|
+
`Message: ${error instanceof Error ? error.message : String(error)}`,
|
|
266
|
+
'',
|
|
267
|
+
];
|
|
268
|
+
|
|
269
|
+
if (error instanceof Error && error.stack) {
|
|
270
|
+
errorDetails.push('## Stack Trace', error.stack, '');
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (context.prompt) {
|
|
274
|
+
errorDetails.push(
|
|
275
|
+
'## Prompt (truncated)',
|
|
276
|
+
context.prompt.slice(0, 2000),
|
|
277
|
+
''
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
if (context.response) {
|
|
282
|
+
errorDetails.push(
|
|
283
|
+
'## Response Before Error (truncated)',
|
|
284
|
+
context.response.slice(-2000),
|
|
285
|
+
''
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (context.lastMessages && context.lastMessages.length > 0) {
|
|
290
|
+
errorDetails.push(
|
|
291
|
+
'## Last Messages',
|
|
292
|
+
JSON.stringify(context.lastMessages.slice(-5), null, 2),
|
|
293
|
+
''
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
await fs.writeFile(logFile, errorDetails.join('\n'), 'utf-8');
|
|
298
|
+
return logFile;
|
|
299
|
+
} catch {
|
|
300
|
+
return '';
|
|
301
|
+
}
|
|
18
302
|
}
|
|
19
303
|
|
|
20
304
|
/**
|
|
@@ -53,29 +337,31 @@ export const DEFAULT_ALLOWED_TOOLS = [
|
|
|
53
337
|
];
|
|
54
338
|
|
|
55
339
|
/**
|
|
56
|
-
* Execute a prompt through the Claude Agent SDK
|
|
57
|
-
*
|
|
58
|
-
* @param prompt - The prompt to execute
|
|
59
|
-
* @param options - Execution options
|
|
60
|
-
* @returns The execution result
|
|
340
|
+
* Execute a prompt through the Claude Agent SDK (internal implementation)
|
|
61
341
|
*/
|
|
62
|
-
|
|
342
|
+
async function executePromptInternal(
|
|
63
343
|
prompt: string,
|
|
64
344
|
options: ClaudeExecuteOptions = {}
|
|
65
|
-
): Promise<ClaudeExecuteResult> {
|
|
345
|
+
): Promise<ClaudeExecuteResult & { rateLimitInfo?: { isRateLimit: boolean; resetTime?: Date; message?: string } }> {
|
|
66
346
|
const {
|
|
67
347
|
cwd,
|
|
68
348
|
allowedTools = DEFAULT_ALLOWED_TOOLS,
|
|
69
349
|
permissionMode = 'bypassPermissions',
|
|
70
350
|
systemPrompt,
|
|
71
351
|
onMessage,
|
|
352
|
+
onProgress,
|
|
72
353
|
} = options;
|
|
73
354
|
|
|
74
355
|
const toolCalls: ToolCallRecord[] = [];
|
|
356
|
+
const recentMessages: SDKMessage[] = [];
|
|
75
357
|
let response = '';
|
|
76
358
|
let error: string | undefined;
|
|
359
|
+
let rateLimitInfo: { isRateLimit: boolean; resetTime?: Date; message?: string } | undefined;
|
|
360
|
+
let lastProgressTime = Date.now();
|
|
77
361
|
|
|
78
362
|
try {
|
|
363
|
+
onProgress?.('Connecting to Claude...');
|
|
364
|
+
|
|
79
365
|
const result = query({
|
|
80
366
|
prompt,
|
|
81
367
|
options: {
|
|
@@ -86,49 +372,306 @@ export async function executePrompt(
|
|
|
86
372
|
},
|
|
87
373
|
});
|
|
88
374
|
|
|
375
|
+
onProgress?.('Claude is thinking...');
|
|
376
|
+
|
|
89
377
|
for await (const message of result) {
|
|
378
|
+
// Keep track of recent messages for error logging
|
|
379
|
+
recentMessages.push(message);
|
|
380
|
+
if (recentMessages.length > 10) {
|
|
381
|
+
recentMessages.shift();
|
|
382
|
+
}
|
|
383
|
+
|
|
90
384
|
// Call the message handler if provided
|
|
91
385
|
if (onMessage) {
|
|
92
386
|
onMessage(message);
|
|
93
387
|
}
|
|
94
388
|
|
|
389
|
+
// Report progress based on message type
|
|
390
|
+
const now = Date.now();
|
|
391
|
+
if (now - lastProgressTime > 2000) {
|
|
392
|
+
// Report progress every 2 seconds
|
|
393
|
+
lastProgressTime = now;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// Check for rate limit in message error field
|
|
397
|
+
const messageWithError = message as { error?: string | { message?: string; code?: string }; message?: { content?: Array<{ text?: string }> } };
|
|
398
|
+
if (messageWithError.error) {
|
|
399
|
+
const errorStr = typeof messageWithError.error === 'string'
|
|
400
|
+
? messageWithError.error
|
|
401
|
+
: messageWithError.error.message || '';
|
|
402
|
+
|
|
403
|
+
if (isRateLimitError(null, errorStr)) {
|
|
404
|
+
// Extract rate limit message from response content
|
|
405
|
+
let rateLimitMessage = errorStr;
|
|
406
|
+
if (messageWithError.message?.content) {
|
|
407
|
+
const textContent = messageWithError.message.content.find(c => c.text);
|
|
408
|
+
if (textContent?.text) {
|
|
409
|
+
rateLimitMessage = textContent.text;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const extractedMessage = extractRateLimitMessage(rateLimitMessage);
|
|
414
|
+
rateLimitInfo = {
|
|
415
|
+
isRateLimit: true,
|
|
416
|
+
resetTime: parseRateLimitResetTime(rateLimitMessage) ?? undefined,
|
|
417
|
+
message: extractedMessage,
|
|
418
|
+
};
|
|
419
|
+
error = `Rate limit exceeded: ${extractedMessage}`;
|
|
420
|
+
onProgress?.(`Rate limit hit: ${rateLimitMessage}`);
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
95
425
|
// Process different message types
|
|
96
426
|
if (message.type === 'assistant') {
|
|
97
427
|
const assistantMessage = message as { type: 'assistant'; message: { content: string | Array<{ type: string; text?: string }> } };
|
|
98
428
|
if (typeof assistantMessage.message.content === 'string') {
|
|
99
429
|
response += assistantMessage.message.content;
|
|
430
|
+
|
|
431
|
+
// Check for rate limit in text response
|
|
432
|
+
if (isRateLimitError(null, assistantMessage.message.content)) {
|
|
433
|
+
const extractedMsg = extractRateLimitMessage(assistantMessage.message.content);
|
|
434
|
+
rateLimitInfo = {
|
|
435
|
+
isRateLimit: true,
|
|
436
|
+
resetTime: parseRateLimitResetTime(assistantMessage.message.content) ?? undefined,
|
|
437
|
+
message: extractedMsg,
|
|
438
|
+
};
|
|
439
|
+
error = `Rate limit exceeded: ${extractedMsg}`;
|
|
440
|
+
onProgress?.(`Rate limit hit: ${assistantMessage.message.content}`);
|
|
441
|
+
} else {
|
|
442
|
+
onProgress?.('Claude is writing...');
|
|
443
|
+
}
|
|
100
444
|
} else if (Array.isArray(assistantMessage.message.content)) {
|
|
101
445
|
for (const block of assistantMessage.message.content) {
|
|
102
446
|
if (block.type === 'text' && block.text) {
|
|
103
447
|
response += block.text;
|
|
448
|
+
|
|
449
|
+
// Check for rate limit in text block
|
|
450
|
+
if (isRateLimitError(null, block.text)) {
|
|
451
|
+
const extractedBlockMsg = extractRateLimitMessage(block.text);
|
|
452
|
+
rateLimitInfo = {
|
|
453
|
+
isRateLimit: true,
|
|
454
|
+
resetTime: parseRateLimitResetTime(block.text) ?? undefined,
|
|
455
|
+
message: extractedBlockMsg,
|
|
456
|
+
};
|
|
457
|
+
error = `Rate limit exceeded: ${extractedBlockMsg}`;
|
|
458
|
+
onProgress?.(`Rate limit hit: ${block.text}`);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
if (block.type === 'tool_use') {
|
|
462
|
+
const toolBlock = block as { type: 'tool_use'; name?: string };
|
|
463
|
+
onProgress?.(`Using tool: ${toolBlock.name || 'unknown'}...`);
|
|
104
464
|
}
|
|
105
465
|
}
|
|
106
466
|
}
|
|
107
467
|
} else if (message.type === 'result') {
|
|
108
|
-
// Handle result messages which may contain tool information
|
|
109
|
-
const resultMessage = message as {
|
|
110
|
-
|
|
111
|
-
|
|
468
|
+
// Handle result messages which may contain tool information or errors
|
|
469
|
+
const resultMessage = message as {
|
|
470
|
+
type: 'result';
|
|
471
|
+
result?: string;
|
|
472
|
+
error?: { message?: string; code?: string };
|
|
473
|
+
subtype?: string;
|
|
474
|
+
};
|
|
475
|
+
if (resultMessage.error && !rateLimitInfo) {
|
|
476
|
+
const errMsg = resultMessage.error.message || 'Unknown error';
|
|
477
|
+
const errCode = resultMessage.error.code || 'ERROR';
|
|
478
|
+
error = `${errCode}: ${errMsg}`;
|
|
479
|
+
onProgress?.(`Claude returned error: ${error}`);
|
|
112
480
|
}
|
|
113
481
|
}
|
|
482
|
+
|
|
483
|
+
// Check for any error property on the message (handles various error formats)
|
|
484
|
+
if (messageWithError.error && !error && !rateLimitInfo) {
|
|
485
|
+
const errMsg = typeof messageWithError.error === 'string'
|
|
486
|
+
? messageWithError.error
|
|
487
|
+
: messageWithError.error.message || 'Unknown error';
|
|
488
|
+
const errCode = typeof messageWithError.error === 'object'
|
|
489
|
+
? messageWithError.error.code || 'ERROR'
|
|
490
|
+
: 'ERROR';
|
|
491
|
+
error = `${errCode}: ${errMsg}`;
|
|
492
|
+
onProgress?.(`Error detected: ${error}`);
|
|
493
|
+
}
|
|
114
494
|
}
|
|
115
495
|
|
|
496
|
+
onProgress?.('Claude finished');
|
|
497
|
+
|
|
116
498
|
return {
|
|
117
499
|
success: !error,
|
|
118
500
|
response: response.trim(),
|
|
119
501
|
toolCalls,
|
|
120
502
|
error,
|
|
503
|
+
rateLimitInfo,
|
|
121
504
|
};
|
|
122
505
|
} catch (err) {
|
|
506
|
+
// First, check if we already detected a rate limit during message processing
|
|
507
|
+
// This happens when rate limit is detected in the stream but process still exits with code 1
|
|
508
|
+
if (rateLimitInfo?.isRateLimit) {
|
|
509
|
+
onProgress?.(`Rate limit detected (process exited): ${rateLimitInfo.message || 'Unknown'}`);
|
|
510
|
+
return {
|
|
511
|
+
success: false,
|
|
512
|
+
response: response.trim(),
|
|
513
|
+
toolCalls,
|
|
514
|
+
error: `Rate limit exceeded: ${rateLimitInfo.message || 'Rate limit hit'}`,
|
|
515
|
+
rateLimitInfo,
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// Check if the exception itself indicates a rate limit
|
|
520
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
521
|
+
|
|
522
|
+
if (isRateLimitError(err, errMsg) || isRateLimitError(null, response)) {
|
|
523
|
+
const combinedMessage = response || errMsg;
|
|
524
|
+
const extractedRateLimitMsg = extractRateLimitMessage(combinedMessage);
|
|
525
|
+
return {
|
|
526
|
+
success: false,
|
|
527
|
+
response: response.trim(),
|
|
528
|
+
toolCalls,
|
|
529
|
+
error: `Rate limit exceeded: ${extractedRateLimitMsg}`,
|
|
530
|
+
rateLimitInfo: {
|
|
531
|
+
isRateLimit: true,
|
|
532
|
+
resetTime: parseRateLimitResetTime(combinedMessage) ?? undefined,
|
|
533
|
+
message: extractedRateLimitMsg,
|
|
534
|
+
},
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// Log detailed error information for debugging
|
|
539
|
+
const logFile = await logErrorDetails(err, {
|
|
540
|
+
prompt: prompt.slice(0, 5000),
|
|
541
|
+
lastMessages: recentMessages,
|
|
542
|
+
response: response.slice(-3000),
|
|
543
|
+
});
|
|
544
|
+
|
|
545
|
+
// Build a detailed error message
|
|
546
|
+
let errorMsg = err instanceof Error ? err.message : 'Unknown error executing prompt';
|
|
547
|
+
|
|
548
|
+
// Check for common error patterns and provide helpful messages
|
|
549
|
+
if (errorMsg.includes('exited with code 1')) {
|
|
550
|
+
errorMsg = `Claude Code process failed (exit code 1). `;
|
|
551
|
+
if (response) {
|
|
552
|
+
// Try to extract any error indicators from the response
|
|
553
|
+
const lastLines = response.split('\n').slice(-10).join('\n');
|
|
554
|
+
if (lastLines.includes('error') || lastLines.includes('Error') || lastLines.includes('failed')) {
|
|
555
|
+
errorMsg += `Last output: ${lastLines.slice(0, 500)}`;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
if (logFile) {
|
|
559
|
+
errorMsg += ` Debug log: ${logFile}`;
|
|
560
|
+
}
|
|
561
|
+
} else if (errorMsg.includes('ECONNREFUSED') || errorMsg.includes('ENOTFOUND')) {
|
|
562
|
+
errorMsg = 'Cannot connect to Claude Code CLI. Is it installed and running?';
|
|
563
|
+
} else if (errorMsg.includes('timeout') || errorMsg.includes('ETIMEDOUT')) {
|
|
564
|
+
errorMsg = 'Claude Code request timed out. The task may be too complex.';
|
|
565
|
+
} else if (errorMsg.includes('permission') || errorMsg.includes('Permission')) {
|
|
566
|
+
errorMsg = `Permission error: ${errorMsg}. Check tool permissions.`;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
onProgress?.(`Error: ${errorMsg}`);
|
|
570
|
+
|
|
123
571
|
return {
|
|
124
572
|
success: false,
|
|
125
|
-
response:
|
|
573
|
+
response: response.trim(),
|
|
126
574
|
toolCalls,
|
|
127
|
-
error:
|
|
575
|
+
error: errorMsg,
|
|
128
576
|
};
|
|
129
577
|
}
|
|
130
578
|
}
|
|
131
579
|
|
|
580
|
+
/**
|
|
581
|
+
* Execute a prompt through the Claude Agent SDK with rate limit retry handling
|
|
582
|
+
*
|
|
583
|
+
* @param prompt - The prompt to execute
|
|
584
|
+
* @param options - Execution options
|
|
585
|
+
* @returns The execution result
|
|
586
|
+
*/
|
|
587
|
+
export async function executePrompt(
|
|
588
|
+
prompt: string,
|
|
589
|
+
options: ClaudeExecuteOptions = {}
|
|
590
|
+
): Promise<ClaudeExecuteResult> {
|
|
591
|
+
const { onProgress, rateLimitConfig: userRateLimitConfig } = options;
|
|
592
|
+
|
|
593
|
+
// If rate limit handling is disabled, run once without retry
|
|
594
|
+
if (userRateLimitConfig === false) {
|
|
595
|
+
const result = await executePromptInternal(prompt, options);
|
|
596
|
+
return {
|
|
597
|
+
success: result.success,
|
|
598
|
+
response: result.response,
|
|
599
|
+
toolCalls: result.toolCalls,
|
|
600
|
+
error: result.error,
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
// Merge user config with defaults
|
|
605
|
+
const rateLimitConfig: RateLimitConfig = {
|
|
606
|
+
...DEFAULT_RATE_LIMIT_CONFIG,
|
|
607
|
+
...userRateLimitConfig,
|
|
608
|
+
};
|
|
609
|
+
|
|
610
|
+
let attempt = 0;
|
|
611
|
+
|
|
612
|
+
while (attempt < rateLimitConfig.maxRetries) {
|
|
613
|
+
const result = await executePromptInternal(prompt, options);
|
|
614
|
+
|
|
615
|
+
// If no rate limit, return the result
|
|
616
|
+
if (!result.rateLimitInfo?.isRateLimit) {
|
|
617
|
+
return {
|
|
618
|
+
success: result.success,
|
|
619
|
+
response: result.response,
|
|
620
|
+
toolCalls: result.toolCalls,
|
|
621
|
+
error: result.error,
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// Rate limit detected - calculate wait time
|
|
626
|
+
attempt++;
|
|
627
|
+
|
|
628
|
+
if (attempt >= rateLimitConfig.maxRetries) {
|
|
629
|
+
onProgress?.(`Rate limit: max retries (${rateLimitConfig.maxRetries}) exceeded`);
|
|
630
|
+
return {
|
|
631
|
+
success: false,
|
|
632
|
+
response: result.response,
|
|
633
|
+
toolCalls: result.toolCalls,
|
|
634
|
+
error: `Rate limit exceeded after ${attempt} retries. ${result.rateLimitInfo.message || ''}`,
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// Calculate wait time
|
|
639
|
+
let waitMs: number;
|
|
640
|
+
|
|
641
|
+
if (result.rateLimitInfo.resetTime) {
|
|
642
|
+
// Use parsed reset time
|
|
643
|
+
waitMs = result.rateLimitInfo.resetTime.getTime() - Date.now();
|
|
644
|
+
// Add a small buffer
|
|
645
|
+
waitMs += 30_000;
|
|
646
|
+
} else {
|
|
647
|
+
// Use exponential backoff
|
|
648
|
+
waitMs = Math.min(
|
|
649
|
+
rateLimitConfig.baseWaitMs * Math.pow(2, attempt - 1),
|
|
650
|
+
rateLimitConfig.maxWaitMs
|
|
651
|
+
);
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
// Ensure minimum wait time
|
|
655
|
+
waitMs = Math.max(waitMs, 30_000);
|
|
656
|
+
|
|
657
|
+
onProgress?.(`Rate limit hit (attempt ${attempt}/${rateLimitConfig.maxRetries}). ${result.rateLimitInfo.message || ''}`);
|
|
658
|
+
onProgress?.(`Waiting ${formatWaitTime(waitMs)} before retry...`);
|
|
659
|
+
|
|
660
|
+
// Wait with progress updates
|
|
661
|
+
await sleepWithProgress(waitMs, onProgress);
|
|
662
|
+
|
|
663
|
+
onProgress?.(`Retrying after rate limit (attempt ${attempt + 1}/${rateLimitConfig.maxRetries})...`);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// Should not reach here, but just in case
|
|
667
|
+
return {
|
|
668
|
+
success: false,
|
|
669
|
+
response: '',
|
|
670
|
+
toolCalls: [],
|
|
671
|
+
error: 'Rate limit handling failed unexpectedly',
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
|
|
132
675
|
/**
|
|
133
676
|
* Execute code generation for a specific task
|
|
134
677
|
*
|
|
@@ -202,8 +745,12 @@ After running the tests:
|
|
|
202
745
|
* Analyze codebase to understand structure and patterns
|
|
203
746
|
*
|
|
204
747
|
* @param cwd - Working directory of the project
|
|
748
|
+
* @param onProgress - Progress callback
|
|
205
749
|
*/
|
|
206
|
-
export async function analyzeCodebase(
|
|
750
|
+
export async function analyzeCodebase(
|
|
751
|
+
cwd: string,
|
|
752
|
+
onProgress?: (message: string) => void
|
|
753
|
+
): Promise<ClaudeExecuteResult> {
|
|
207
754
|
const prompt = `
|
|
208
755
|
Analyze this codebase and provide:
|
|
209
756
|
|
|
@@ -221,43 +768,208 @@ Be concise but thorough in your analysis.
|
|
|
221
768
|
cwd,
|
|
222
769
|
allowedTools: ['Read', 'Glob', 'Grep', 'LS'],
|
|
223
770
|
permissionMode: 'default', // Read-only analysis
|
|
771
|
+
onProgress,
|
|
224
772
|
});
|
|
225
773
|
}
|
|
226
774
|
|
|
775
|
+
/**
|
|
776
|
+
* Extract plan file path from Claude's response
|
|
777
|
+
* Claude sometimes saves the plan to a file and responds with a summary
|
|
778
|
+
*/
|
|
779
|
+
function extractPlanFilePath(response: string): string | null {
|
|
780
|
+
// Look for plan file paths like /Users/.../.claude/plans/...
|
|
781
|
+
const patterns = [
|
|
782
|
+
/`([^`]*\.claude\/plans\/[^`]+\.md)`/i,
|
|
783
|
+
/saved to\s+`?([^\s`]+\.claude\/plans\/[^\s`]+\.md)`?/i,
|
|
784
|
+
/created at\s+`?([^\s`]+\.claude\/plans\/[^\s`]+\.md)`?/i,
|
|
785
|
+
/plan.*at\s+`?([^\s`]+\.claude\/plans\/[^\s`]+\.md)`?/i,
|
|
786
|
+
/(\/[^\s]+\.claude\/plans\/[^\s]+\.md)/i,
|
|
787
|
+
];
|
|
788
|
+
|
|
789
|
+
for (const pattern of patterns) {
|
|
790
|
+
const match = response.match(pattern);
|
|
791
|
+
if (match && match[1]) {
|
|
792
|
+
return match[1];
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
return null;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* Check if response is Claude's thinking/conversation instead of actual plan
|
|
801
|
+
*/
|
|
802
|
+
function isConversationalResponse(response: string): boolean {
|
|
803
|
+
const conversationalPhrases = [
|
|
804
|
+
'let me ',
|
|
805
|
+
'i will ',
|
|
806
|
+
'i\'ll ',
|
|
807
|
+
'now i have',
|
|
808
|
+
'i now have',
|
|
809
|
+
'let me launch',
|
|
810
|
+
'let me create',
|
|
811
|
+
'i\'ve created',
|
|
812
|
+
'i\'ve analyzed',
|
|
813
|
+
'has been created',
|
|
814
|
+
'has been saved',
|
|
815
|
+
'the plan is structured',
|
|
816
|
+
];
|
|
817
|
+
|
|
818
|
+
const responseLower = response.toLowerCase();
|
|
819
|
+
return conversationalPhrases.some(phrase => responseLower.includes(phrase));
|
|
820
|
+
}
|
|
821
|
+
|
|
227
822
|
/**
|
|
228
823
|
* Create a development plan from a specification
|
|
229
824
|
*
|
|
230
825
|
* @param specification - The project specification
|
|
231
826
|
* @param context - Additional context (existing code, etc.)
|
|
827
|
+
* @param onProgress - Progress callback
|
|
232
828
|
*/
|
|
233
829
|
export async function createPlan(
|
|
234
830
|
specification: string,
|
|
235
|
-
context: string = ''
|
|
831
|
+
context: string = '',
|
|
832
|
+
onProgress?: (message: string) => void
|
|
236
833
|
): Promise<ClaudeExecuteResult> {
|
|
237
834
|
const prompt = `
|
|
238
|
-
Create a detailed development plan
|
|
835
|
+
You are a software architect. Create a detailed, actionable development plan.
|
|
836
|
+
|
|
837
|
+
CRITICAL INSTRUCTION: You must output the COMPLETE plan content directly in your response as markdown.
|
|
838
|
+
Do NOT use tools to save the plan to a file.
|
|
839
|
+
Do NOT just describe what the plan contains - output the ACTUAL plan with all milestones and tasks.
|
|
840
|
+
Do NOT say "Let me...", "I will...", "I've created...", or any conversational text.
|
|
841
|
+
|
|
842
|
+
Start your response with "# Development Plan:" and include the FULL plan content.
|
|
239
843
|
|
|
240
844
|
## Specification
|
|
241
845
|
${specification}
|
|
242
846
|
|
|
243
847
|
${context ? `## Additional Context\n${context}` : ''}
|
|
244
848
|
|
|
245
|
-
## Required Plan
|
|
849
|
+
## Required Plan Format
|
|
850
|
+
|
|
851
|
+
Your response MUST be the complete plan in this EXACT format:
|
|
852
|
+
|
|
853
|
+
# Development Plan: [Project Name]
|
|
854
|
+
|
|
855
|
+
## Overview
|
|
856
|
+
[2-3 sentence summary of what will be built]
|
|
857
|
+
|
|
858
|
+
## Milestone 1: [Name]
|
|
859
|
+
**Description**: [What this milestone achieves]
|
|
860
|
+
**Estimated Duration**: [X days/weeks]
|
|
861
|
+
|
|
862
|
+
### Task 1.1: [Actionable task name starting with verb]
|
|
863
|
+
**Description**: [What this task accomplishes]
|
|
864
|
+
**Files to create/modify**: [List specific files]
|
|
865
|
+
**Acceptance Criteria**:
|
|
866
|
+
- [Specific, testable criterion]
|
|
867
|
+
- [Another criterion]
|
|
868
|
+
|
|
869
|
+
### Task 1.2: [Another actionable task]
|
|
870
|
+
...
|
|
871
|
+
|
|
872
|
+
## Milestone 2: [Name]
|
|
873
|
+
...
|
|
874
|
+
|
|
875
|
+
## Test Plan
|
|
876
|
+
[How to verify the implementation works]
|
|
877
|
+
|
|
878
|
+
## Risks & Mitigations
|
|
879
|
+
[Potential issues and how to address them]
|
|
246
880
|
|
|
247
|
-
|
|
248
|
-
2. **Goals & Objectives**: List measurable objectives
|
|
249
|
-
3. **Milestones**: Break down into major phases
|
|
250
|
-
4. **Tasks**: Detail specific tasks for each milestone
|
|
251
|
-
5. **Test Plan**: Define tests for each task
|
|
252
|
-
6. **Risks & Mitigations**: Identify potential issues
|
|
881
|
+
## Requirements for Tasks
|
|
253
882
|
|
|
254
|
-
|
|
883
|
+
1. Each task MUST start with an action verb: Implement, Create, Build, Add, Configure, Set up, Write, Design, etc.
|
|
884
|
+
2. Each task MUST be specific and implementable (not vague like "handle errors" - instead "Implement error handling middleware with custom error classes")
|
|
885
|
+
3. Each milestone MUST have at least 3-5 specific tasks
|
|
886
|
+
4. The plan MUST have at least 3 milestones for any non-trivial project
|
|
887
|
+
5. Files to create/modify MUST be listed for each task
|
|
888
|
+
6. Acceptance criteria MUST be testable
|
|
889
|
+
|
|
890
|
+
IMPORTANT: Output the COMPLETE plan now. Start with "# Development Plan:" on the first line.
|
|
255
891
|
`.trim();
|
|
256
892
|
|
|
257
|
-
|
|
893
|
+
const result = await executePrompt(prompt, {
|
|
258
894
|
allowedTools: ['Read', 'Glob'],
|
|
259
895
|
permissionMode: 'plan',
|
|
896
|
+
onProgress,
|
|
260
897
|
});
|
|
898
|
+
|
|
899
|
+
// If Claude's response is conversational (describes the plan but doesn't contain it),
|
|
900
|
+
// try to extract the plan from the file it may have created
|
|
901
|
+
if (result.success && isConversationalResponse(result.response)) {
|
|
902
|
+
onProgress?.('Detected conversational response, looking for plan file...');
|
|
903
|
+
|
|
904
|
+
// Try to find and read the plan file
|
|
905
|
+
const planFilePath = extractPlanFilePath(result.response);
|
|
906
|
+
|
|
907
|
+
if (planFilePath) {
|
|
908
|
+
try {
|
|
909
|
+
onProgress?.(`Found plan file reference: ${planFilePath}`);
|
|
910
|
+
const planContent = await fs.readFile(planFilePath, 'utf-8');
|
|
911
|
+
|
|
912
|
+
// Verify the plan content is actually a plan
|
|
913
|
+
if (planContent.includes('# Development Plan') ||
|
|
914
|
+
planContent.includes('## Milestone') ||
|
|
915
|
+
planContent.includes('### Task')) {
|
|
916
|
+
onProgress?.('Successfully extracted plan from file');
|
|
917
|
+
return {
|
|
918
|
+
...result,
|
|
919
|
+
response: planContent,
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
} catch (readError) {
|
|
923
|
+
onProgress?.(`Could not read plan file: ${readError instanceof Error ? readError.message : 'Unknown error'}`);
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
// Also try to find any recent .claude/plans files
|
|
928
|
+
try {
|
|
929
|
+
const claudePlansDir = path.join(homedir(), '.claude', 'plans');
|
|
930
|
+
const files = await fs.readdir(claudePlansDir);
|
|
931
|
+
const mdFiles = files.filter(f => f.endsWith('.md'));
|
|
932
|
+
|
|
933
|
+
if (mdFiles.length > 0) {
|
|
934
|
+
// Sort by modification time (most recent first)
|
|
935
|
+
const fileStats = await Promise.all(
|
|
936
|
+
mdFiles.map(async f => {
|
|
937
|
+
const filePath = path.join(claudePlansDir, f);
|
|
938
|
+
const stat = await fs.stat(filePath);
|
|
939
|
+
return { name: f, path: filePath, mtime: stat.mtime };
|
|
940
|
+
})
|
|
941
|
+
);
|
|
942
|
+
|
|
943
|
+
fileStats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
|
|
944
|
+
|
|
945
|
+
// Check the most recent file (created in the last 5 minutes)
|
|
946
|
+
const recentFile = fileStats[0];
|
|
947
|
+
const fiveMinutesAgo = Date.now() - 5 * 60 * 1000;
|
|
948
|
+
|
|
949
|
+
if (recentFile.mtime.getTime() > fiveMinutesAgo) {
|
|
950
|
+
onProgress?.(`Found recent plan file: ${recentFile.name}`);
|
|
951
|
+
const planContent = await fs.readFile(recentFile.path, 'utf-8');
|
|
952
|
+
|
|
953
|
+
if (planContent.includes('# Development Plan') ||
|
|
954
|
+
planContent.includes('## Milestone') ||
|
|
955
|
+
planContent.includes('### Task')) {
|
|
956
|
+
onProgress?.('Successfully extracted plan from recent file');
|
|
957
|
+
return {
|
|
958
|
+
...result,
|
|
959
|
+
response: planContent,
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
} catch {
|
|
965
|
+
// Could not access .claude/plans directory
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
// Log warning that we couldn't extract the plan
|
|
969
|
+
onProgress?.('WARNING: Could not extract actual plan content from file');
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
return result;
|
|
261
973
|
}
|
|
262
974
|
|
|
263
975
|
/**
|
|
@@ -270,29 +982,98 @@ Format the plan as markdown with clear sections and bullet points.
|
|
|
270
982
|
export async function revisePlan(
|
|
271
983
|
originalPlan: string,
|
|
272
984
|
feedback: string,
|
|
273
|
-
concerns: string[]
|
|
985
|
+
concerns: string[],
|
|
986
|
+
onProgress?: (message: string) => void
|
|
274
987
|
): Promise<ClaudeExecuteResult> {
|
|
275
988
|
const prompt = `
|
|
276
|
-
|
|
989
|
+
CRITICAL: You must output the COMPLETE revised plan in your response.
|
|
990
|
+
Do NOT describe what you changed - output the FULL plan with all changes incorporated.
|
|
991
|
+
Do NOT say "Let me...", "I will...", "I've revised...", or any conversational text.
|
|
992
|
+
Start your response directly with "# Development Plan:" and include the ENTIRE revised plan.
|
|
277
993
|
|
|
278
|
-
## Original Plan
|
|
994
|
+
## Original Plan to Revise
|
|
279
995
|
${originalPlan}
|
|
280
996
|
|
|
281
|
-
## Feedback
|
|
997
|
+
## Feedback to Address
|
|
282
998
|
${feedback}
|
|
283
999
|
|
|
284
1000
|
## Specific Concerns to Address
|
|
285
1001
|
${concerns.map((c, i) => `${i + 1}. ${c}`).join('\n')}
|
|
286
1002
|
|
|
287
1003
|
## Instructions
|
|
288
|
-
1. Address each concern
|
|
289
|
-
2. Maintain the same plan structure
|
|
290
|
-
3.
|
|
291
|
-
4.
|
|
1004
|
+
1. Address each concern by incorporating changes into the plan
|
|
1005
|
+
2. Maintain the same plan structure (Overview, Milestones, Tasks, Test Plan, Risks)
|
|
1006
|
+
3. Output the COMPLETE revised plan - not just the changes
|
|
1007
|
+
4. Start with "# Development Plan:" and include ALL milestones and tasks
|
|
1008
|
+
|
|
1009
|
+
OUTPUT THE COMPLETE REVISED PLAN NOW:
|
|
292
1010
|
`.trim();
|
|
293
1011
|
|
|
294
|
-
|
|
1012
|
+
onProgress?.('Claude is revising the plan...');
|
|
1013
|
+
|
|
1014
|
+
const result = await executePrompt(prompt, {
|
|
295
1015
|
allowedTools: [],
|
|
296
1016
|
permissionMode: 'plan',
|
|
1017
|
+
onProgress,
|
|
297
1018
|
});
|
|
1019
|
+
|
|
1020
|
+
// Check if response is conversational and try to extract actual plan
|
|
1021
|
+
if (result.success && isConversationalResponse(result.response)) {
|
|
1022
|
+
// Try to find the plan file
|
|
1023
|
+
const planFilePath = extractPlanFilePath(result.response);
|
|
1024
|
+
|
|
1025
|
+
if (planFilePath) {
|
|
1026
|
+
try {
|
|
1027
|
+
const planContent = await fs.readFile(planFilePath, 'utf-8');
|
|
1028
|
+
if (planContent.includes('# Development Plan') ||
|
|
1029
|
+
planContent.includes('## Milestone') ||
|
|
1030
|
+
planContent.includes('### Task')) {
|
|
1031
|
+
return {
|
|
1032
|
+
...result,
|
|
1033
|
+
response: planContent,
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
} catch {
|
|
1037
|
+
// Could not read file, fall through
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
// Try recent .claude/plans files
|
|
1042
|
+
try {
|
|
1043
|
+
const claudePlansDir = path.join(homedir(), '.claude', 'plans');
|
|
1044
|
+
const files = await fs.readdir(claudePlansDir);
|
|
1045
|
+
const mdFiles = files.filter(f => f.endsWith('.md'));
|
|
1046
|
+
|
|
1047
|
+
if (mdFiles.length > 0) {
|
|
1048
|
+
const fileStats = await Promise.all(
|
|
1049
|
+
mdFiles.map(async f => {
|
|
1050
|
+
const filePath = path.join(claudePlansDir, f);
|
|
1051
|
+
const stat = await fs.stat(filePath);
|
|
1052
|
+
return { name: f, path: filePath, mtime: stat.mtime };
|
|
1053
|
+
})
|
|
1054
|
+
);
|
|
1055
|
+
|
|
1056
|
+
fileStats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
|
|
1057
|
+
|
|
1058
|
+
const recentFile = fileStats[0];
|
|
1059
|
+
const twoMinutesAgo = Date.now() - 2 * 60 * 1000;
|
|
1060
|
+
|
|
1061
|
+
if (recentFile.mtime.getTime() > twoMinutesAgo) {
|
|
1062
|
+
const planContent = await fs.readFile(recentFile.path, 'utf-8');
|
|
1063
|
+
if (planContent.includes('# Development Plan') ||
|
|
1064
|
+
planContent.includes('## Milestone') ||
|
|
1065
|
+
planContent.includes('### Task')) {
|
|
1066
|
+
return {
|
|
1067
|
+
...result,
|
|
1068
|
+
response: planContent,
|
|
1069
|
+
};
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
} catch {
|
|
1074
|
+
// Could not access .claude/plans directory
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
return result;
|
|
298
1079
|
}
|