popeye-cli 1.0.0 → 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.
Files changed (171) hide show
  1. package/README.md +521 -125
  2. package/dist/adapters/claude.d.ts +16 -4
  3. package/dist/adapters/claude.d.ts.map +1 -1
  4. package/dist/adapters/claude.js +679 -33
  5. package/dist/adapters/claude.js.map +1 -1
  6. package/dist/adapters/gemini.d.ts +55 -0
  7. package/dist/adapters/gemini.d.ts.map +1 -0
  8. package/dist/adapters/gemini.js +318 -0
  9. package/dist/adapters/gemini.js.map +1 -0
  10. package/dist/adapters/openai.d.ts.map +1 -1
  11. package/dist/adapters/openai.js +41 -7
  12. package/dist/adapters/openai.js.map +1 -1
  13. package/dist/auth/claude.d.ts +11 -9
  14. package/dist/auth/claude.d.ts.map +1 -1
  15. package/dist/auth/claude.js +107 -71
  16. package/dist/auth/claude.js.map +1 -1
  17. package/dist/auth/gemini.d.ts +58 -0
  18. package/dist/auth/gemini.d.ts.map +1 -0
  19. package/dist/auth/gemini.js +172 -0
  20. package/dist/auth/gemini.js.map +1 -0
  21. package/dist/auth/index.d.ts +11 -7
  22. package/dist/auth/index.d.ts.map +1 -1
  23. package/dist/auth/index.js +23 -5
  24. package/dist/auth/index.js.map +1 -1
  25. package/dist/auth/keychain.d.ts +20 -7
  26. package/dist/auth/keychain.d.ts.map +1 -1
  27. package/dist/auth/keychain.js +85 -29
  28. package/dist/auth/keychain.js.map +1 -1
  29. package/dist/auth/openai.d.ts +2 -2
  30. package/dist/auth/openai.d.ts.map +1 -1
  31. package/dist/auth/openai.js +30 -32
  32. package/dist/auth/openai.js.map +1 -1
  33. package/dist/cli/index.d.ts.map +1 -1
  34. package/dist/cli/index.js +4 -7
  35. package/dist/cli/index.js.map +1 -1
  36. package/dist/cli/interactive.d.ts +2 -2
  37. package/dist/cli/interactive.d.ts.map +1 -1
  38. package/dist/cli/interactive.js +1380 -183
  39. package/dist/cli/interactive.js.map +1 -1
  40. package/dist/config/defaults.d.ts +6 -1
  41. package/dist/config/defaults.d.ts.map +1 -1
  42. package/dist/config/defaults.js +10 -2
  43. package/dist/config/defaults.js.map +1 -1
  44. package/dist/config/index.d.ts +10 -0
  45. package/dist/config/index.d.ts.map +1 -1
  46. package/dist/config/index.js +19 -0
  47. package/dist/config/index.js.map +1 -1
  48. package/dist/config/schema.d.ts +20 -0
  49. package/dist/config/schema.d.ts.map +1 -1
  50. package/dist/config/schema.js +7 -0
  51. package/dist/config/schema.js.map +1 -1
  52. package/dist/generators/python.d.ts.map +1 -1
  53. package/dist/generators/python.js +1 -0
  54. package/dist/generators/python.js.map +1 -1
  55. package/dist/generators/typescript.d.ts.map +1 -1
  56. package/dist/generators/typescript.js +1 -0
  57. package/dist/generators/typescript.js.map +1 -1
  58. package/dist/state/index.d.ts +108 -0
  59. package/dist/state/index.d.ts.map +1 -1
  60. package/dist/state/index.js +551 -4
  61. package/dist/state/index.js.map +1 -1
  62. package/dist/state/registry.d.ts +52 -0
  63. package/dist/state/registry.d.ts.map +1 -0
  64. package/dist/state/registry.js +215 -0
  65. package/dist/state/registry.js.map +1 -0
  66. package/dist/types/cli.d.ts +4 -0
  67. package/dist/types/cli.d.ts.map +1 -1
  68. package/dist/types/cli.js.map +1 -1
  69. package/dist/types/consensus.d.ts +69 -4
  70. package/dist/types/consensus.d.ts.map +1 -1
  71. package/dist/types/consensus.js +24 -3
  72. package/dist/types/consensus.js.map +1 -1
  73. package/dist/types/workflow.d.ts +55 -0
  74. package/dist/types/workflow.d.ts.map +1 -1
  75. package/dist/types/workflow.js +16 -0
  76. package/dist/types/workflow.js.map +1 -1
  77. package/dist/workflow/auto-fix.d.ts +45 -0
  78. package/dist/workflow/auto-fix.d.ts.map +1 -0
  79. package/dist/workflow/auto-fix.js +274 -0
  80. package/dist/workflow/auto-fix.js.map +1 -0
  81. package/dist/workflow/consensus.d.ts +44 -2
  82. package/dist/workflow/consensus.d.ts.map +1 -1
  83. package/dist/workflow/consensus.js +565 -17
  84. package/dist/workflow/consensus.js.map +1 -1
  85. package/dist/workflow/execution-mode.d.ts +10 -4
  86. package/dist/workflow/execution-mode.d.ts.map +1 -1
  87. package/dist/workflow/execution-mode.js +547 -58
  88. package/dist/workflow/execution-mode.js.map +1 -1
  89. package/dist/workflow/index.d.ts +14 -2
  90. package/dist/workflow/index.d.ts.map +1 -1
  91. package/dist/workflow/index.js +69 -6
  92. package/dist/workflow/index.js.map +1 -1
  93. package/dist/workflow/milestone-workflow.d.ts +34 -0
  94. package/dist/workflow/milestone-workflow.d.ts.map +1 -0
  95. package/dist/workflow/milestone-workflow.js +414 -0
  96. package/dist/workflow/milestone-workflow.js.map +1 -0
  97. package/dist/workflow/plan-mode.d.ts +14 -1
  98. package/dist/workflow/plan-mode.d.ts.map +1 -1
  99. package/dist/workflow/plan-mode.js +589 -47
  100. package/dist/workflow/plan-mode.js.map +1 -1
  101. package/dist/workflow/plan-storage.d.ts +142 -0
  102. package/dist/workflow/plan-storage.d.ts.map +1 -0
  103. package/dist/workflow/plan-storage.js +331 -0
  104. package/dist/workflow/plan-storage.js.map +1 -0
  105. package/dist/workflow/project-verification.d.ts +37 -0
  106. package/dist/workflow/project-verification.d.ts.map +1 -0
  107. package/dist/workflow/project-verification.js +381 -0
  108. package/dist/workflow/project-verification.js.map +1 -0
  109. package/dist/workflow/task-workflow.d.ts +37 -0
  110. package/dist/workflow/task-workflow.d.ts.map +1 -0
  111. package/dist/workflow/task-workflow.js +383 -0
  112. package/dist/workflow/task-workflow.js.map +1 -0
  113. package/dist/workflow/test-runner.d.ts +1 -0
  114. package/dist/workflow/test-runner.d.ts.map +1 -1
  115. package/dist/workflow/test-runner.js +9 -5
  116. package/dist/workflow/test-runner.js.map +1 -1
  117. package/dist/workflow/ui-designer.d.ts +82 -0
  118. package/dist/workflow/ui-designer.d.ts.map +1 -0
  119. package/dist/workflow/ui-designer.js +234 -0
  120. package/dist/workflow/ui-designer.js.map +1 -0
  121. package/dist/workflow/ui-setup.d.ts +58 -0
  122. package/dist/workflow/ui-setup.d.ts.map +1 -0
  123. package/dist/workflow/ui-setup.js +685 -0
  124. package/dist/workflow/ui-setup.js.map +1 -0
  125. package/dist/workflow/ui-verification.d.ts +114 -0
  126. package/dist/workflow/ui-verification.d.ts.map +1 -0
  127. package/dist/workflow/ui-verification.js +258 -0
  128. package/dist/workflow/ui-verification.js.map +1 -0
  129. package/dist/workflow/workflow-logger.d.ts +110 -0
  130. package/dist/workflow/workflow-logger.d.ts.map +1 -0
  131. package/dist/workflow/workflow-logger.js +267 -0
  132. package/dist/workflow/workflow-logger.js.map +1 -0
  133. package/package.json +2 -2
  134. package/src/adapters/claude.ts +815 -34
  135. package/src/adapters/gemini.ts +373 -0
  136. package/src/adapters/openai.ts +40 -7
  137. package/src/auth/claude.ts +120 -78
  138. package/src/auth/gemini.ts +207 -0
  139. package/src/auth/index.ts +28 -8
  140. package/src/auth/keychain.ts +95 -28
  141. package/src/auth/openai.ts +29 -36
  142. package/src/cli/index.ts +4 -7
  143. package/src/cli/interactive.ts +1641 -216
  144. package/src/config/defaults.ts +10 -2
  145. package/src/config/index.ts +21 -0
  146. package/src/config/schema.ts +7 -0
  147. package/src/generators/python.ts +1 -0
  148. package/src/generators/typescript.ts +1 -0
  149. package/src/state/index.ts +713 -4
  150. package/src/state/registry.ts +278 -0
  151. package/src/types/cli.ts +4 -0
  152. package/src/types/consensus.ts +65 -6
  153. package/src/types/workflow.ts +35 -0
  154. package/src/workflow/auto-fix.ts +340 -0
  155. package/src/workflow/consensus.ts +750 -16
  156. package/src/workflow/execution-mode.ts +673 -74
  157. package/src/workflow/index.ts +95 -6
  158. package/src/workflow/milestone-workflow.ts +576 -0
  159. package/src/workflow/plan-mode.ts +696 -50
  160. package/src/workflow/plan-storage.ts +482 -0
  161. package/src/workflow/project-verification.ts +471 -0
  162. package/src/workflow/task-workflow.ts +525 -0
  163. package/src/workflow/test-runner.ts +10 -5
  164. package/src/workflow/ui-designer.ts +337 -0
  165. package/src/workflow/ui-setup.ts +797 -0
  166. package/src/workflow/ui-verification.ts +357 -0
  167. package/src/workflow/workflow-logger.ts +353 -0
  168. package/tests/config/config.test.ts +1 -1
  169. package/tests/types/consensus.test.ts +3 -3
  170. package/tests/workflow/plan-mode.test.ts +213 -0
  171. package/tests/workflow/test-runner.test.ts +5 -3
@@ -2,7 +2,227 @@
2
2
  * Claude Agent SDK adapter
3
3
  * Wraps the Claude Agent SDK for code execution and generation
4
4
  */
5
+ import { promises as fs } from 'node:fs';
6
+ import path from 'node:path';
7
+ import { homedir } from 'os';
5
8
  import { query } from '@anthropic-ai/claude-agent-sdk';
9
+ /**
10
+ * Log directory for debug information
11
+ */
12
+ const LOG_DIR = path.join(homedir(), '.popeye', 'logs');
13
+ const DEFAULT_RATE_LIMIT_CONFIG = {
14
+ maxRetries: 5,
15
+ baseWaitMs: 5 * 60_000, // 5 minutes
16
+ maxWaitMs: 2 * 60 * 60_000, // 2 hours
17
+ };
18
+ /**
19
+ * Parse rate limit reset time from error message
20
+ * Messages like: "You've hit your limit · resets 3pm (Asia/Jerusalem)"
21
+ */
22
+ function parseRateLimitResetTime(message) {
23
+ // Try to parse time like "3pm", "3:30pm", "15:00"
24
+ const timePatterns = [
25
+ /resets?\s+(\d{1,2}):?(\d{2})?\s*(am|pm)?/i,
26
+ /until\s+(\d{1,2}):?(\d{2})?\s*(am|pm)?/i,
27
+ /wait\s+until\s+(\d{1,2}):?(\d{2})?\s*(am|pm)?/i,
28
+ ];
29
+ for (const pattern of timePatterns) {
30
+ const match = message.match(pattern);
31
+ if (match) {
32
+ let hours = parseInt(match[1], 10);
33
+ const minutes = match[2] ? parseInt(match[2], 10) : 0;
34
+ const ampm = match[3]?.toLowerCase();
35
+ if (ampm === 'pm' && hours < 12)
36
+ hours += 12;
37
+ if (ampm === 'am' && hours === 12)
38
+ hours = 0;
39
+ const resetTime = new Date();
40
+ resetTime.setHours(hours, minutes, 0, 0);
41
+ // If the time has passed today, assume tomorrow
42
+ if (resetTime.getTime() <= Date.now()) {
43
+ resetTime.setDate(resetTime.getDate() + 1);
44
+ }
45
+ return resetTime;
46
+ }
47
+ }
48
+ // Try to parse duration like "30 minutes", "1 hour"
49
+ const durationPatterns = [
50
+ /(\d+)\s*minutes?/i,
51
+ /(\d+)\s*hours?/i,
52
+ ];
53
+ for (let i = 0; i < durationPatterns.length; i++) {
54
+ const match = message.match(durationPatterns[i]);
55
+ if (match) {
56
+ const value = parseInt(match[1], 10);
57
+ const multiplier = i === 0 ? 60_000 : 60 * 60_000; // minutes or hours
58
+ return new Date(Date.now() + value * multiplier);
59
+ }
60
+ }
61
+ return null;
62
+ }
63
+ /**
64
+ * Format wait time for display
65
+ */
66
+ function formatWaitTime(ms) {
67
+ if (ms < 60_000) {
68
+ return `${Math.ceil(ms / 1000)} seconds`;
69
+ }
70
+ else if (ms < 60 * 60_000) {
71
+ const minutes = Math.ceil(ms / 60_000);
72
+ return `${minutes} minute${minutes > 1 ? 's' : ''}`;
73
+ }
74
+ else {
75
+ const hours = Math.floor(ms / (60 * 60_000));
76
+ const minutes = Math.ceil((ms % (60 * 60_000)) / 60_000);
77
+ return `${hours} hour${hours > 1 ? 's' : ''}${minutes > 0 ? ` ${minutes} minute${minutes > 1 ? 's' : ''}` : ''}`;
78
+ }
79
+ }
80
+ /**
81
+ * Sleep for a specified duration with progress updates
82
+ */
83
+ async function sleepWithProgress(ms, onProgress) {
84
+ const startTime = Date.now();
85
+ const endTime = startTime + ms;
86
+ const updateInterval = Math.min(ms / 10, 60_000); // Update every 10% or minute, whichever is smaller
87
+ while (Date.now() < endTime) {
88
+ const remaining = endTime - Date.now();
89
+ if (remaining <= 0)
90
+ break;
91
+ onProgress?.(`Rate limit: waiting ${formatWaitTime(remaining)} before retry...`);
92
+ const sleepTime = Math.min(updateInterval, remaining);
93
+ await new Promise(resolve => setTimeout(resolve, sleepTime));
94
+ }
95
+ }
96
+ /**
97
+ * Extract just the rate limit message from a larger string
98
+ * e.g., "Some content... You've hit your limit · resets 3pm (Asia/Jerusalem)" -> "You've hit your limit · resets 3pm (Asia/Jerusalem)"
99
+ */
100
+ function extractRateLimitMessage(content) {
101
+ // Look for specific rate limit error message patterns
102
+ // These patterns are designed to match actual error messages, not plan content
103
+ const patterns = [
104
+ // "You've hit your limit" patterns - common Claude error
105
+ /You['']ve hit your limit[^.\n]*(?:\.[\s]*(?:resets?|try again)[^.\n]*)?/i,
106
+ // "Rate limit exceeded" - explicit error message
107
+ /rate limit exceeded[^.\n]*/i,
108
+ // "rate limited" as verb - "you have been rate limited"
109
+ /(?:you\s+(?:have\s+)?(?:been\s+)?)?rate\s+limited[^.\n]*/i,
110
+ // "too many requests" - HTTP 429 style
111
+ /too many requests[^.\n]*/i,
112
+ // "quota exceeded" - usage limit
113
+ /quota exceeded[^.\n]*/i,
114
+ // "API rate limit" - specific to API errors
115
+ /api\s+rate\s+limit[^.\n]*/i,
116
+ // "request limit" patterns
117
+ /request\s+limit[^.\n]*(?:reached|exceeded|hit)[^.\n]*/i,
118
+ // "usage limit" patterns
119
+ /usage\s+limit[^.\n]*(?:reached|exceeded|hit)[^.\n]*/i,
120
+ ];
121
+ for (const pattern of patterns) {
122
+ const match = content.match(pattern);
123
+ if (match) {
124
+ // Limit matched content to 200 chars to prevent capturing run-on text
125
+ const matched = match[0].trim();
126
+ return matched.length > 200 ? matched.slice(0, 197) + '...' : matched;
127
+ }
128
+ }
129
+ // If no pattern matches, try to find the first line that looks like an error
130
+ const lines = content.split('\n').filter(line => line.trim());
131
+ for (const line of lines.slice(0, 5)) {
132
+ const trimmedLine = line.trim();
133
+ // Look for lines that start with error indicators
134
+ if (/^(error|failed|limit|exceeded|denied)/i.test(trimmedLine)) {
135
+ return trimmedLine.length > 200 ? trimmedLine.slice(0, 197) + '...' : trimmedLine;
136
+ }
137
+ }
138
+ // If content is short, return it (but cap at 200 chars)
139
+ if (content.length < 200) {
140
+ return content;
141
+ }
142
+ // Otherwise return a generic message - don't include potentially huge content
143
+ return 'Rate limit detected (details unavailable)';
144
+ }
145
+ /**
146
+ * Check if an error indicates a rate limit
147
+ * Uses specific patterns to avoid false positives from plan content mentioning rate limiting
148
+ */
149
+ function isRateLimitError(error, message) {
150
+ // Patterns that indicate actual rate limit errors (not just mentions of rate limiting)
151
+ // These are more specific than just "rate limit" to avoid matching plan content
152
+ const rateLimitPatterns = [
153
+ /you['']ve hit your limit/i,
154
+ /rate_limit_exceeded/i,
155
+ /rate limit exceeded/i,
156
+ /you have been rate limited/i,
157
+ /too many requests/i,
158
+ /quota exceeded/i,
159
+ /\b429\b/, // HTTP 429 status code
160
+ /rate limited/i, // "rate limited" as a verb phrase
161
+ /api rate limit/i,
162
+ /request limit reached/i,
163
+ /usage limit exceeded/i,
164
+ /limit reached.*try again/i,
165
+ /exceeded.*limit.*retry/i,
166
+ ];
167
+ const checkString = (str) => {
168
+ return rateLimitPatterns.some(pattern => pattern.test(str));
169
+ };
170
+ if (message && checkString(message))
171
+ return true;
172
+ if (error instanceof Error) {
173
+ if (checkString(error.message))
174
+ return true;
175
+ if ('code' in error && typeof error.code === 'string' && checkString(error.code))
176
+ return true;
177
+ }
178
+ if (typeof error === 'object' && error !== null) {
179
+ const obj = error;
180
+ if (typeof obj.error === 'string' && checkString(obj.error))
181
+ return true;
182
+ if (typeof obj.code === 'string' && checkString(obj.code))
183
+ return true;
184
+ if (typeof obj.message === 'string' && checkString(obj.message))
185
+ return true;
186
+ }
187
+ return false;
188
+ }
189
+ /**
190
+ * Write error details to a log file for debugging
191
+ */
192
+ async function logErrorDetails(error, context) {
193
+ try {
194
+ await fs.mkdir(LOG_DIR, { recursive: true });
195
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
196
+ const logFile = path.join(LOG_DIR, `claude-error-${timestamp}.log`);
197
+ const errorDetails = [
198
+ '='.repeat(80),
199
+ `CLAUDE ERROR LOG - ${new Date().toISOString()}`,
200
+ '='.repeat(80),
201
+ '',
202
+ '## Error Details',
203
+ `Type: ${error instanceof Error ? error.constructor.name : typeof error}`,
204
+ `Message: ${error instanceof Error ? error.message : String(error)}`,
205
+ '',
206
+ ];
207
+ if (error instanceof Error && error.stack) {
208
+ errorDetails.push('## Stack Trace', error.stack, '');
209
+ }
210
+ if (context.prompt) {
211
+ errorDetails.push('## Prompt (truncated)', context.prompt.slice(0, 2000), '');
212
+ }
213
+ if (context.response) {
214
+ errorDetails.push('## Response Before Error (truncated)', context.response.slice(-2000), '');
215
+ }
216
+ if (context.lastMessages && context.lastMessages.length > 0) {
217
+ errorDetails.push('## Last Messages', JSON.stringify(context.lastMessages.slice(-5), null, 2), '');
218
+ }
219
+ await fs.writeFile(logFile, errorDetails.join('\n'), 'utf-8');
220
+ return logFile;
221
+ }
222
+ catch {
223
+ return '';
224
+ }
225
+ }
6
226
  /**
7
227
  * Default allowed tools for autonomous operation
8
228
  */
@@ -19,18 +239,18 @@ export const DEFAULT_ALLOWED_TOOLS = [
19
239
  'TodoWrite',
20
240
  ];
21
241
  /**
22
- * Execute a prompt through the Claude Agent SDK
23
- *
24
- * @param prompt - The prompt to execute
25
- * @param options - Execution options
26
- * @returns The execution result
242
+ * Execute a prompt through the Claude Agent SDK (internal implementation)
27
243
  */
28
- export async function executePrompt(prompt, options = {}) {
29
- const { cwd, allowedTools = DEFAULT_ALLOWED_TOOLS, permissionMode = 'bypassPermissions', systemPrompt, onMessage, } = options;
244
+ async function executePromptInternal(prompt, options = {}) {
245
+ const { cwd, allowedTools = DEFAULT_ALLOWED_TOOLS, permissionMode = 'bypassPermissions', systemPrompt, onMessage, onProgress, } = options;
30
246
  const toolCalls = [];
247
+ const recentMessages = [];
31
248
  let response = '';
32
249
  let error;
250
+ let rateLimitInfo;
251
+ let lastProgressTime = Date.now();
33
252
  try {
253
+ onProgress?.('Connecting to Claude...');
34
254
  const result = query({
35
255
  prompt,
36
256
  options: {
@@ -40,48 +260,267 @@ export async function executePrompt(prompt, options = {}) {
40
260
  systemPrompt: systemPrompt || { type: 'preset', preset: 'claude_code' },
41
261
  },
42
262
  });
263
+ onProgress?.('Claude is thinking...');
43
264
  for await (const message of result) {
265
+ // Keep track of recent messages for error logging
266
+ recentMessages.push(message);
267
+ if (recentMessages.length > 10) {
268
+ recentMessages.shift();
269
+ }
44
270
  // Call the message handler if provided
45
271
  if (onMessage) {
46
272
  onMessage(message);
47
273
  }
274
+ // Report progress based on message type
275
+ const now = Date.now();
276
+ if (now - lastProgressTime > 2000) {
277
+ // Report progress every 2 seconds
278
+ lastProgressTime = now;
279
+ }
280
+ // Check for rate limit in message error field
281
+ const messageWithError = message;
282
+ if (messageWithError.error) {
283
+ const errorStr = typeof messageWithError.error === 'string'
284
+ ? messageWithError.error
285
+ : messageWithError.error.message || '';
286
+ if (isRateLimitError(null, errorStr)) {
287
+ // Extract rate limit message from response content
288
+ let rateLimitMessage = errorStr;
289
+ if (messageWithError.message?.content) {
290
+ const textContent = messageWithError.message.content.find(c => c.text);
291
+ if (textContent?.text) {
292
+ rateLimitMessage = textContent.text;
293
+ }
294
+ }
295
+ const extractedMessage = extractRateLimitMessage(rateLimitMessage);
296
+ rateLimitInfo = {
297
+ isRateLimit: true,
298
+ resetTime: parseRateLimitResetTime(rateLimitMessage) ?? undefined,
299
+ message: extractedMessage,
300
+ };
301
+ error = `Rate limit exceeded: ${extractedMessage}`;
302
+ onProgress?.(`Rate limit hit: ${rateLimitMessage}`);
303
+ continue;
304
+ }
305
+ }
48
306
  // Process different message types
49
307
  if (message.type === 'assistant') {
50
308
  const assistantMessage = message;
51
309
  if (typeof assistantMessage.message.content === 'string') {
52
310
  response += assistantMessage.message.content;
311
+ // Check for rate limit in text response
312
+ if (isRateLimitError(null, assistantMessage.message.content)) {
313
+ const extractedMsg = extractRateLimitMessage(assistantMessage.message.content);
314
+ rateLimitInfo = {
315
+ isRateLimit: true,
316
+ resetTime: parseRateLimitResetTime(assistantMessage.message.content) ?? undefined,
317
+ message: extractedMsg,
318
+ };
319
+ error = `Rate limit exceeded: ${extractedMsg}`;
320
+ onProgress?.(`Rate limit hit: ${assistantMessage.message.content}`);
321
+ }
322
+ else {
323
+ onProgress?.('Claude is writing...');
324
+ }
53
325
  }
54
326
  else if (Array.isArray(assistantMessage.message.content)) {
55
327
  for (const block of assistantMessage.message.content) {
56
328
  if (block.type === 'text' && block.text) {
57
329
  response += block.text;
330
+ // Check for rate limit in text block
331
+ if (isRateLimitError(null, block.text)) {
332
+ const extractedBlockMsg = extractRateLimitMessage(block.text);
333
+ rateLimitInfo = {
334
+ isRateLimit: true,
335
+ resetTime: parseRateLimitResetTime(block.text) ?? undefined,
336
+ message: extractedBlockMsg,
337
+ };
338
+ error = `Rate limit exceeded: ${extractedBlockMsg}`;
339
+ onProgress?.(`Rate limit hit: ${block.text}`);
340
+ }
341
+ }
342
+ if (block.type === 'tool_use') {
343
+ const toolBlock = block;
344
+ onProgress?.(`Using tool: ${toolBlock.name || 'unknown'}...`);
58
345
  }
59
346
  }
60
347
  }
61
348
  }
62
349
  else if (message.type === 'result') {
63
- // Handle result messages which may contain tool information
350
+ // Handle result messages which may contain tool information or errors
64
351
  const resultMessage = message;
65
- if (resultMessage.error) {
66
- error = resultMessage.error.message;
352
+ if (resultMessage.error && !rateLimitInfo) {
353
+ const errMsg = resultMessage.error.message || 'Unknown error';
354
+ const errCode = resultMessage.error.code || 'ERROR';
355
+ error = `${errCode}: ${errMsg}`;
356
+ onProgress?.(`Claude returned error: ${error}`);
67
357
  }
68
358
  }
359
+ // Check for any error property on the message (handles various error formats)
360
+ if (messageWithError.error && !error && !rateLimitInfo) {
361
+ const errMsg = typeof messageWithError.error === 'string'
362
+ ? messageWithError.error
363
+ : messageWithError.error.message || 'Unknown error';
364
+ const errCode = typeof messageWithError.error === 'object'
365
+ ? messageWithError.error.code || 'ERROR'
366
+ : 'ERROR';
367
+ error = `${errCode}: ${errMsg}`;
368
+ onProgress?.(`Error detected: ${error}`);
369
+ }
69
370
  }
371
+ onProgress?.('Claude finished');
70
372
  return {
71
373
  success: !error,
72
374
  response: response.trim(),
73
375
  toolCalls,
74
376
  error,
377
+ rateLimitInfo,
75
378
  };
76
379
  }
77
380
  catch (err) {
381
+ // First, check if we already detected a rate limit during message processing
382
+ // This happens when rate limit is detected in the stream but process still exits with code 1
383
+ if (rateLimitInfo?.isRateLimit) {
384
+ onProgress?.(`Rate limit detected (process exited): ${rateLimitInfo.message || 'Unknown'}`);
385
+ return {
386
+ success: false,
387
+ response: response.trim(),
388
+ toolCalls,
389
+ error: `Rate limit exceeded: ${rateLimitInfo.message || 'Rate limit hit'}`,
390
+ rateLimitInfo,
391
+ };
392
+ }
393
+ // Check if the exception itself indicates a rate limit
394
+ const errMsg = err instanceof Error ? err.message : String(err);
395
+ if (isRateLimitError(err, errMsg) || isRateLimitError(null, response)) {
396
+ const combinedMessage = response || errMsg;
397
+ const extractedRateLimitMsg = extractRateLimitMessage(combinedMessage);
398
+ return {
399
+ success: false,
400
+ response: response.trim(),
401
+ toolCalls,
402
+ error: `Rate limit exceeded: ${extractedRateLimitMsg}`,
403
+ rateLimitInfo: {
404
+ isRateLimit: true,
405
+ resetTime: parseRateLimitResetTime(combinedMessage) ?? undefined,
406
+ message: extractedRateLimitMsg,
407
+ },
408
+ };
409
+ }
410
+ // Log detailed error information for debugging
411
+ const logFile = await logErrorDetails(err, {
412
+ prompt: prompt.slice(0, 5000),
413
+ lastMessages: recentMessages,
414
+ response: response.slice(-3000),
415
+ });
416
+ // Build a detailed error message
417
+ let errorMsg = err instanceof Error ? err.message : 'Unknown error executing prompt';
418
+ // Check for common error patterns and provide helpful messages
419
+ if (errorMsg.includes('exited with code 1')) {
420
+ errorMsg = `Claude Code process failed (exit code 1). `;
421
+ if (response) {
422
+ // Try to extract any error indicators from the response
423
+ const lastLines = response.split('\n').slice(-10).join('\n');
424
+ if (lastLines.includes('error') || lastLines.includes('Error') || lastLines.includes('failed')) {
425
+ errorMsg += `Last output: ${lastLines.slice(0, 500)}`;
426
+ }
427
+ }
428
+ if (logFile) {
429
+ errorMsg += ` Debug log: ${logFile}`;
430
+ }
431
+ }
432
+ else if (errorMsg.includes('ECONNREFUSED') || errorMsg.includes('ENOTFOUND')) {
433
+ errorMsg = 'Cannot connect to Claude Code CLI. Is it installed and running?';
434
+ }
435
+ else if (errorMsg.includes('timeout') || errorMsg.includes('ETIMEDOUT')) {
436
+ errorMsg = 'Claude Code request timed out. The task may be too complex.';
437
+ }
438
+ else if (errorMsg.includes('permission') || errorMsg.includes('Permission')) {
439
+ errorMsg = `Permission error: ${errorMsg}. Check tool permissions.`;
440
+ }
441
+ onProgress?.(`Error: ${errorMsg}`);
78
442
  return {
79
443
  success: false,
80
- response: '',
444
+ response: response.trim(),
81
445
  toolCalls,
82
- error: err instanceof Error ? err.message : 'Unknown error executing prompt',
446
+ error: errorMsg,
447
+ };
448
+ }
449
+ }
450
+ /**
451
+ * Execute a prompt through the Claude Agent SDK with rate limit retry handling
452
+ *
453
+ * @param prompt - The prompt to execute
454
+ * @param options - Execution options
455
+ * @returns The execution result
456
+ */
457
+ export async function executePrompt(prompt, options = {}) {
458
+ const { onProgress, rateLimitConfig: userRateLimitConfig } = options;
459
+ // If rate limit handling is disabled, run once without retry
460
+ if (userRateLimitConfig === false) {
461
+ const result = await executePromptInternal(prompt, options);
462
+ return {
463
+ success: result.success,
464
+ response: result.response,
465
+ toolCalls: result.toolCalls,
466
+ error: result.error,
83
467
  };
84
468
  }
469
+ // Merge user config with defaults
470
+ const rateLimitConfig = {
471
+ ...DEFAULT_RATE_LIMIT_CONFIG,
472
+ ...userRateLimitConfig,
473
+ };
474
+ let attempt = 0;
475
+ while (attempt < rateLimitConfig.maxRetries) {
476
+ const result = await executePromptInternal(prompt, options);
477
+ // If no rate limit, return the result
478
+ if (!result.rateLimitInfo?.isRateLimit) {
479
+ return {
480
+ success: result.success,
481
+ response: result.response,
482
+ toolCalls: result.toolCalls,
483
+ error: result.error,
484
+ };
485
+ }
486
+ // Rate limit detected - calculate wait time
487
+ attempt++;
488
+ if (attempt >= rateLimitConfig.maxRetries) {
489
+ onProgress?.(`Rate limit: max retries (${rateLimitConfig.maxRetries}) exceeded`);
490
+ return {
491
+ success: false,
492
+ response: result.response,
493
+ toolCalls: result.toolCalls,
494
+ error: `Rate limit exceeded after ${attempt} retries. ${result.rateLimitInfo.message || ''}`,
495
+ };
496
+ }
497
+ // Calculate wait time
498
+ let waitMs;
499
+ if (result.rateLimitInfo.resetTime) {
500
+ // Use parsed reset time
501
+ waitMs = result.rateLimitInfo.resetTime.getTime() - Date.now();
502
+ // Add a small buffer
503
+ waitMs += 30_000;
504
+ }
505
+ else {
506
+ // Use exponential backoff
507
+ waitMs = Math.min(rateLimitConfig.baseWaitMs * Math.pow(2, attempt - 1), rateLimitConfig.maxWaitMs);
508
+ }
509
+ // Ensure minimum wait time
510
+ waitMs = Math.max(waitMs, 30_000);
511
+ onProgress?.(`Rate limit hit (attempt ${attempt}/${rateLimitConfig.maxRetries}). ${result.rateLimitInfo.message || ''}`);
512
+ onProgress?.(`Waiting ${formatWaitTime(waitMs)} before retry...`);
513
+ // Wait with progress updates
514
+ await sleepWithProgress(waitMs, onProgress);
515
+ onProgress?.(`Retrying after rate limit (attempt ${attempt + 1}/${rateLimitConfig.maxRetries})...`);
516
+ }
517
+ // Should not reach here, but just in case
518
+ return {
519
+ success: false,
520
+ response: '',
521
+ toolCalls: [],
522
+ error: 'Rate limit handling failed unexpectedly',
523
+ };
85
524
  }
86
525
  /**
87
526
  * Execute code generation for a specific task
@@ -145,8 +584,9 @@ After running the tests:
145
584
  * Analyze codebase to understand structure and patterns
146
585
  *
147
586
  * @param cwd - Working directory of the project
587
+ * @param onProgress - Progress callback
148
588
  */
149
- export async function analyzeCodebase(cwd) {
589
+ export async function analyzeCodebase(cwd, onProgress) {
150
590
  const prompt = `
151
591
  Analyze this codebase and provide:
152
592
 
@@ -163,38 +603,185 @@ Be concise but thorough in your analysis.
163
603
  cwd,
164
604
  allowedTools: ['Read', 'Glob', 'Grep', 'LS'],
165
605
  permissionMode: 'default', // Read-only analysis
606
+ onProgress,
166
607
  });
167
608
  }
609
+ /**
610
+ * Extract plan file path from Claude's response
611
+ * Claude sometimes saves the plan to a file and responds with a summary
612
+ */
613
+ function extractPlanFilePath(response) {
614
+ // Look for plan file paths like /Users/.../.claude/plans/...
615
+ const patterns = [
616
+ /`([^`]*\.claude\/plans\/[^`]+\.md)`/i,
617
+ /saved to\s+`?([^\s`]+\.claude\/plans\/[^\s`]+\.md)`?/i,
618
+ /created at\s+`?([^\s`]+\.claude\/plans\/[^\s`]+\.md)`?/i,
619
+ /plan.*at\s+`?([^\s`]+\.claude\/plans\/[^\s`]+\.md)`?/i,
620
+ /(\/[^\s]+\.claude\/plans\/[^\s]+\.md)/i,
621
+ ];
622
+ for (const pattern of patterns) {
623
+ const match = response.match(pattern);
624
+ if (match && match[1]) {
625
+ return match[1];
626
+ }
627
+ }
628
+ return null;
629
+ }
630
+ /**
631
+ * Check if response is Claude's thinking/conversation instead of actual plan
632
+ */
633
+ function isConversationalResponse(response) {
634
+ const conversationalPhrases = [
635
+ 'let me ',
636
+ 'i will ',
637
+ 'i\'ll ',
638
+ 'now i have',
639
+ 'i now have',
640
+ 'let me launch',
641
+ 'let me create',
642
+ 'i\'ve created',
643
+ 'i\'ve analyzed',
644
+ 'has been created',
645
+ 'has been saved',
646
+ 'the plan is structured',
647
+ ];
648
+ const responseLower = response.toLowerCase();
649
+ return conversationalPhrases.some(phrase => responseLower.includes(phrase));
650
+ }
168
651
  /**
169
652
  * Create a development plan from a specification
170
653
  *
171
654
  * @param specification - The project specification
172
655
  * @param context - Additional context (existing code, etc.)
656
+ * @param onProgress - Progress callback
173
657
  */
174
- export async function createPlan(specification, context = '') {
658
+ export async function createPlan(specification, context = '', onProgress) {
175
659
  const prompt = `
176
- Create a detailed development plan for the following specification:
660
+ You are a software architect. Create a detailed, actionable development plan.
661
+
662
+ CRITICAL INSTRUCTION: You must output the COMPLETE plan content directly in your response as markdown.
663
+ Do NOT use tools to save the plan to a file.
664
+ Do NOT just describe what the plan contains - output the ACTUAL plan with all milestones and tasks.
665
+ Do NOT say "Let me...", "I will...", "I've created...", or any conversational text.
666
+
667
+ Start your response with "# Development Plan:" and include the FULL plan content.
177
668
 
178
669
  ## Specification
179
670
  ${specification}
180
671
 
181
672
  ${context ? `## Additional Context\n${context}` : ''}
182
673
 
183
- ## Required Plan Sections
674
+ ## Required Plan Format
675
+
676
+ Your response MUST be the complete plan in this EXACT format:
184
677
 
185
- 1. **Background & Context**: Summarize the project requirements
186
- 2. **Goals & Objectives**: List measurable objectives
187
- 3. **Milestones**: Break down into major phases
188
- 4. **Tasks**: Detail specific tasks for each milestone
189
- 5. **Test Plan**: Define tests for each task
190
- 6. **Risks & Mitigations**: Identify potential issues
678
+ # Development Plan: [Project Name]
191
679
 
192
- Format the plan as markdown with clear sections and bullet points.
680
+ ## Overview
681
+ [2-3 sentence summary of what will be built]
682
+
683
+ ## Milestone 1: [Name]
684
+ **Description**: [What this milestone achieves]
685
+ **Estimated Duration**: [X days/weeks]
686
+
687
+ ### Task 1.1: [Actionable task name starting with verb]
688
+ **Description**: [What this task accomplishes]
689
+ **Files to create/modify**: [List specific files]
690
+ **Acceptance Criteria**:
691
+ - [Specific, testable criterion]
692
+ - [Another criterion]
693
+
694
+ ### Task 1.2: [Another actionable task]
695
+ ...
696
+
697
+ ## Milestone 2: [Name]
698
+ ...
699
+
700
+ ## Test Plan
701
+ [How to verify the implementation works]
702
+
703
+ ## Risks & Mitigations
704
+ [Potential issues and how to address them]
705
+
706
+ ## Requirements for Tasks
707
+
708
+ 1. Each task MUST start with an action verb: Implement, Create, Build, Add, Configure, Set up, Write, Design, etc.
709
+ 2. Each task MUST be specific and implementable (not vague like "handle errors" - instead "Implement error handling middleware with custom error classes")
710
+ 3. Each milestone MUST have at least 3-5 specific tasks
711
+ 4. The plan MUST have at least 3 milestones for any non-trivial project
712
+ 5. Files to create/modify MUST be listed for each task
713
+ 6. Acceptance criteria MUST be testable
714
+
715
+ IMPORTANT: Output the COMPLETE plan now. Start with "# Development Plan:" on the first line.
193
716
  `.trim();
194
- return executePrompt(prompt, {
717
+ const result = await executePrompt(prompt, {
195
718
  allowedTools: ['Read', 'Glob'],
196
719
  permissionMode: 'plan',
720
+ onProgress,
197
721
  });
722
+ // If Claude's response is conversational (describes the plan but doesn't contain it),
723
+ // try to extract the plan from the file it may have created
724
+ if (result.success && isConversationalResponse(result.response)) {
725
+ onProgress?.('Detected conversational response, looking for plan file...');
726
+ // Try to find and read the plan file
727
+ const planFilePath = extractPlanFilePath(result.response);
728
+ if (planFilePath) {
729
+ try {
730
+ onProgress?.(`Found plan file reference: ${planFilePath}`);
731
+ const planContent = await fs.readFile(planFilePath, 'utf-8');
732
+ // Verify the plan content is actually a plan
733
+ if (planContent.includes('# Development Plan') ||
734
+ planContent.includes('## Milestone') ||
735
+ planContent.includes('### Task')) {
736
+ onProgress?.('Successfully extracted plan from file');
737
+ return {
738
+ ...result,
739
+ response: planContent,
740
+ };
741
+ }
742
+ }
743
+ catch (readError) {
744
+ onProgress?.(`Could not read plan file: ${readError instanceof Error ? readError.message : 'Unknown error'}`);
745
+ }
746
+ }
747
+ // Also try to find any recent .claude/plans files
748
+ try {
749
+ const claudePlansDir = path.join(homedir(), '.claude', 'plans');
750
+ const files = await fs.readdir(claudePlansDir);
751
+ const mdFiles = files.filter(f => f.endsWith('.md'));
752
+ if (mdFiles.length > 0) {
753
+ // Sort by modification time (most recent first)
754
+ const fileStats = await Promise.all(mdFiles.map(async (f) => {
755
+ const filePath = path.join(claudePlansDir, f);
756
+ const stat = await fs.stat(filePath);
757
+ return { name: f, path: filePath, mtime: stat.mtime };
758
+ }));
759
+ fileStats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
760
+ // Check the most recent file (created in the last 5 minutes)
761
+ const recentFile = fileStats[0];
762
+ const fiveMinutesAgo = Date.now() - 5 * 60 * 1000;
763
+ if (recentFile.mtime.getTime() > fiveMinutesAgo) {
764
+ onProgress?.(`Found recent plan file: ${recentFile.name}`);
765
+ const planContent = await fs.readFile(recentFile.path, 'utf-8');
766
+ if (planContent.includes('# Development Plan') ||
767
+ planContent.includes('## Milestone') ||
768
+ planContent.includes('### Task')) {
769
+ onProgress?.('Successfully extracted plan from recent file');
770
+ return {
771
+ ...result,
772
+ response: planContent,
773
+ };
774
+ }
775
+ }
776
+ }
777
+ }
778
+ catch {
779
+ // Could not access .claude/plans directory
780
+ }
781
+ // Log warning that we couldn't extract the plan
782
+ onProgress?.('WARNING: Could not extract actual plan content from file');
783
+ }
784
+ return result;
198
785
  }
199
786
  /**
200
787
  * Revise a plan based on feedback
@@ -203,28 +790,87 @@ Format the plan as markdown with clear sections and bullet points.
203
790
  * @param feedback - Feedback to incorporate
204
791
  * @param concerns - Specific concerns to address
205
792
  */
206
- export async function revisePlan(originalPlan, feedback, concerns) {
793
+ export async function revisePlan(originalPlan, feedback, concerns, onProgress) {
207
794
  const prompt = `
208
- Revise the following plan based on the feedback provided:
795
+ CRITICAL: You must output the COMPLETE revised plan in your response.
796
+ Do NOT describe what you changed - output the FULL plan with all changes incorporated.
797
+ Do NOT say "Let me...", "I will...", "I've revised...", or any conversational text.
798
+ Start your response directly with "# Development Plan:" and include the ENTIRE revised plan.
209
799
 
210
- ## Original Plan
800
+ ## Original Plan to Revise
211
801
  ${originalPlan}
212
802
 
213
- ## Feedback
803
+ ## Feedback to Address
214
804
  ${feedback}
215
805
 
216
806
  ## Specific Concerns to Address
217
807
  ${concerns.map((c, i) => `${i + 1}. ${c}`).join('\n')}
218
808
 
219
809
  ## Instructions
220
- 1. Address each concern specifically
221
- 2. Maintain the same plan structure
222
- 3. Note what changed from the original
223
- 4. Ensure the revised plan is complete and actionable
810
+ 1. Address each concern by incorporating changes into the plan
811
+ 2. Maintain the same plan structure (Overview, Milestones, Tasks, Test Plan, Risks)
812
+ 3. Output the COMPLETE revised plan - not just the changes
813
+ 4. Start with "# Development Plan:" and include ALL milestones and tasks
814
+
815
+ OUTPUT THE COMPLETE REVISED PLAN NOW:
224
816
  `.trim();
225
- return executePrompt(prompt, {
817
+ onProgress?.('Claude is revising the plan...');
818
+ const result = await executePrompt(prompt, {
226
819
  allowedTools: [],
227
820
  permissionMode: 'plan',
821
+ onProgress,
228
822
  });
823
+ // Check if response is conversational and try to extract actual plan
824
+ if (result.success && isConversationalResponse(result.response)) {
825
+ // Try to find the plan file
826
+ const planFilePath = extractPlanFilePath(result.response);
827
+ if (planFilePath) {
828
+ try {
829
+ const planContent = await fs.readFile(planFilePath, 'utf-8');
830
+ if (planContent.includes('# Development Plan') ||
831
+ planContent.includes('## Milestone') ||
832
+ planContent.includes('### Task')) {
833
+ return {
834
+ ...result,
835
+ response: planContent,
836
+ };
837
+ }
838
+ }
839
+ catch {
840
+ // Could not read file, fall through
841
+ }
842
+ }
843
+ // Try recent .claude/plans files
844
+ try {
845
+ const claudePlansDir = path.join(homedir(), '.claude', 'plans');
846
+ const files = await fs.readdir(claudePlansDir);
847
+ const mdFiles = files.filter(f => f.endsWith('.md'));
848
+ if (mdFiles.length > 0) {
849
+ const fileStats = await Promise.all(mdFiles.map(async (f) => {
850
+ const filePath = path.join(claudePlansDir, f);
851
+ const stat = await fs.stat(filePath);
852
+ return { name: f, path: filePath, mtime: stat.mtime };
853
+ }));
854
+ fileStats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
855
+ const recentFile = fileStats[0];
856
+ const twoMinutesAgo = Date.now() - 2 * 60 * 1000;
857
+ if (recentFile.mtime.getTime() > twoMinutesAgo) {
858
+ const planContent = await fs.readFile(recentFile.path, 'utf-8');
859
+ if (planContent.includes('# Development Plan') ||
860
+ planContent.includes('## Milestone') ||
861
+ planContent.includes('### Task')) {
862
+ return {
863
+ ...result,
864
+ response: planContent,
865
+ };
866
+ }
867
+ }
868
+ }
869
+ }
870
+ catch {
871
+ // Could not access .claude/plans directory
872
+ }
873
+ }
874
+ return result;
229
875
  }
230
876
  //# sourceMappingURL=claude.js.map