Commit Graph

91 Commits

Author SHA1 Message Date
BrunoMarc
05cd80ebb5 fix: address code review feedback
- Move MAX_EMPTY_RESPONSE_RETRIES to constants.js for consistency
- Handle 429/401/5xx errors properly during retry fetch
- Use proper message ID format (crypto.randomBytes) instead of Date.now()
- Add crypto import for UUID generation

Code review by: Gemini 3 Pro Preview + Claude Opus 4.5

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 18:16:09 -03:00
BrunoMarc
49480847b6 fix: add retry mechanism for empty API responses
When Claude Code sends requests with large thinking_budget values,
the model may spend all tokens on "thinking" and return empty responses,
causing Claude Code to stop mid-conversation.

This commit adds a retry mechanism that:
- Throws EmptyResponseError instead of emitting fake message on empty response
- Retries up to 2 times before giving up
- Emits fallback message only after all retries are exhausted

Changes:
- src/errors.js: Added EmptyResponseError class and isEmptyResponseError()
- src/cloudcode/sse-streamer.js: Throw error instead of yielding fake message
- src/cloudcode/streaming-handler.js: Added retry loop with fallback

Tested for 6+ hours with 1,884 API requests and 88% recovery rate
on empty responses.

Fixes #61

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-07 18:11:03 -03:00
Badri Narayanan S
a7ca710249 fix commands bug in readme - replace anthropic api key to anthropic auth token 2026-01-08 01:21:01 +05:30
Badri Narayanan S
7c047a9578 Updated readme to add MCP CLI Flag 2026-01-08 01:19:47 +05:30
Badri Narayanan S
992fa700d8 Updated readme to use 2.5 flash lite as the default haiku model 2026-01-07 01:55:49 +05:30
Badri Narayanan S
63fa90c04b set cooldown to 10 seconds 2026-01-07 00:33:42 +05:30
Badri Narayanan S
57ba5f9c1c setting cooldown back to 30 seconds 2026-01-07 00:20:22 +05:30
Badri Narayanan S
e686af2e67 added cross model thinking to npm run test tests 2026-01-06 22:24:57 +05:30
Badri Narayanan S
5b70b7703e Changed default cooldown time to 10 seconds 2026-01-06 22:22:32 +05:30
Badri Narayanan S
84166fdefe Update star history link to correct one 2026-01-06 22:12:19 +05:30
Badri Narayanan S
59d0a92b37 Merge pull request #55 from jgor20/fix/oauth-callback-utf8-encoding
fix(oauth): add UTF-8 encoding to callback HTML pages
2026-01-06 21:49:02 +05:30
Badri Narayanan S
27afdf1e79 Merge pull request #54 from jgor20/feature/auto-rebuild-native-modules
feat: Add automatic native module rebuild on Node.js version mismatch
2026-01-06 21:48:28 +05:30
jgor20
df9b935329 fix(auth): add UTF-8 charset to OAuth callback HTML responses
Ensure proper encoding for international characters in error and success pages
by specifying charset=utf-8 in Content-Type headers and adding meta charset tags.
2026-01-05 01:43:15 +00:00
jgor20
e29cd5fa9d refactor(auth): use NativeModuleError for native module load failures
Replace generic Error instances with NativeModuleError in loadDatabaseModule
to provide more structured error information, including rebuild status and
restart requirements. Update getAuthStatus to re-throw NativeModuleError
instances without wrapping.
2026-01-05 01:20:35 +00:00
jgor20
b90eb63f22 feat(errors): add NativeModuleError for native module version mismatches
Add a new error class to handle native module errors, including version mismatches and rebuild requirements. This supports the auto-rebuild functionality by providing structured error information for rebuild success and restart needs.
2026-01-05 01:20:28 +00:00
jgor20
69b7e130a0 refactor(auth): move clearRequireCache to utils and update import
Remove the local clearRequireCache function from database.js and import it from
utils/native-module-helper.js. Update the function call to pass require.cache
as the second parameter for proper cache clearing.
2026-01-05 01:13:55 +00:00
jgor20
2d4693b4c6 refactor(utils): rename and refactor clearModuleCache to recursively clear dependencies
The function has been renamed to clearRequireCache and updated to recursively
clear the require cache for a module and all its dependencies, preventing
cycles with a visited set. This improves reliability after rebuilding native
modules by ensuring complete cache invalidation. Removed unused createRequire
import as it's no longer needed.
2026-01-05 01:13:45 +00:00
jgor20
02ceeb2ff5 feat(utils): enhance rebuildModule error handling and logging
Add detailed stdout/stderr capture and logging for failed npm rebuild commands to improve troubleshooting. Also log successful rebuild output for debugging purposes.
2026-01-05 01:11:13 +00:00
jgor20
ff188f5cf6 fix(utils): fix cross-platform root detection in findPackageRoot
Improve the findPackageRoot function to correctly detect filesystem root on all platforms by checking if dirname returns the same path, replacing the Unix-specific '/' check.
2026-01-05 01:09:00 +00:00
jgor20
e6027ec5a6 feat: auto-rebuild native modules on Node.js version mismatch
When Node.js is updated, native modules like better-sqlite3 can become
   incompatible due to NODE_MODULE_VERSION differences. This change adds
   automatic detection and rebuild capability:

   - Add native-module-helper.js utility for detecting version errors
   - Lazy-load better-sqlite3 to catch import errors at runtime
   - Automatically run npm rebuild when version mismatch is detected
   - Clear require cache and retry loading after successful rebuild
   - Provide clear instructions if automatic rebuild fails

   Fixes the issue where users running via npx encounter module errors
   after updating Node.js.
2026-01-05 00:43:21 +00:00
Badri Narayanan S
ea3d3ca4a4 format readme for headless server account addition 2026-01-04 14:59:29 +05:30
Badri Narayanan S
3c0a4845d6 Merge pull request #50 from badri-s2001/feature/headless-server
feat: add --no-browser OAuth mode for headless servers
2026-01-04 14:53:08 +05:30
Badri Narayanan S
1628696ca1 fix: correct state destructuring and document headless mode
- Fix extractCodeFromInput destructuring: returns { code, state } not
  { code, extractedState }, so state validation was being bypassed
- Add --no-browser hint to CLI banner for discoverability
- Document --no-browser mode in README.md and CLAUDE.md
- Add test:oauth script to package.json
- Add OAuth test to run-all.cjs test suite

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-04 14:51:05 +05:30
Caixiaopig
573ba57db6 feat: add --no-browser OAuth mode for headless servers
## Feature Description

Enables adding Google accounts on remote servers without a desktop
environment (headless Linux, Docker containers, SSH sessions) where
automatic browser opening is not possible. Users can manually copy the
authorization URL to a device with a browser, complete authentication,
and paste the authorization code back.

## Usage

npm run accounts:add -- --no-browser

## Code Architecture

### New Modules

1. oauth.js - extractCodeFromInput()
   - Parses user input (full callback URL or raw authorization code)
   - Extracts code and state parameters
   - Handles OAuth error responses

2. accounts.js - addAccountNoBrowser()
   - Account addition flow for no-browser mode
   - Displays authorization URL for manual copying
   - Waits for user to paste authorization code
   - Calls extractCodeFromInput to parse input
   - Completes OAuth flow and saves account

3. tests/test-oauth-no-browser.cjs
   - 13 unit tests covering valid URLs, raw codes, error handling, edge cases

### Modified Modules

1. accounts.js - interactiveAdd()
   - Added noBrowser parameter
   - Selects addAccount or addAccountNoBrowser based on mode

2. accounts.js - main()
   - Parses --no-browser CLI argument
   - Updated help information

## User Flow

┌─────────────────────────────────────────────────────────────┐
│                   Headless Server Terminal                   │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
            ┌─────────────────────────────────┐
            │ npm run accounts:add -- --no-browser │
            └─────────────────────────────────┘
                              │
                              ▼
            ┌─────────────────────────────────┐
            │   Display Google OAuth URL       │
            │   (manual copy required)         │
            └─────────────────────────────────┘
                              │
         ┌────────────────────┴────────────────────┐
         │                                         │
         ▼                                         ▼
┌─────────────────┐                    ┌─────────────────────┐
│  Local Browser  │                    │  Phone/Other Device │
│  Open URL       │                    │  Open URL           │
│  Google Sign-in │                    │  Google Sign-in     │
│  Authorize App  │                    │  Authorize App      │
└─────────────────┘                    └─────────────────────┘
         │                                         │
         └────────────────────┬────────────────────┘
                              │
                              ▼
            ┌─────────────────────────────────┐
            │ Browser redirects to localhost   │
            │ (page won't load - this is OK)   │
            │ Copy full URL or code parameter  │
            └─────────────────────────────────┘
                              │
                              ▼
            ┌─────────────────────────────────┐
            │ Return to server terminal        │
            │ Paste URL or authorization code  │
            └─────────────────────────────────┘
                              │
                              ▼
            ┌─────────────────────────────────┐
            │ ✓ Account added successfully     │
            └─────────────────────────────────┘

## Security Considerations

- Supports state parameter validation (when user pastes full URL)
- Warns on state mismatch but allows continuation (manual mode tolerance)
- Authorization code length validation to prevent incorrect input

## Compatibility

- Does not affect existing automatic browser OAuth flow
- All changes are additive, no modifications to upstream logic
- Easy to merge future upstream updates
2026-01-04 14:46:16 +05:30
Badri Narayanan S
d03c79cc39 Merge pull request #41 from badri-s2001/feature/model-fallback
Feature/model fallback
2026-01-04 02:32:32 +05:30
Badri Narayanan S
e0b3f90777 docs: update CLAUDE.md with model fallback and cross-model features
- Add --fallback and --debug startup flags to commands section
- Add test:crossmodel script for cross-model thinking tests
- Document fallback-config.js module in directory structure
- Add Model Fallback section explaining fallback behavior
- Add Cross-Model Thinking Signatures section explaining compatibility
- Update constants section with MODEL_FALLBACK_MAP

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-04 00:19:35 +05:30
Badri Narayanan S
141558dd62 Improve cross-model thinking handling and add gemini-3-flash fallback
- Add gemini-3-flash to MODEL_FALLBACK_MAP for completeness
- Add hasGeminiHistory() to detect Gemini→Claude cross-model switch
- Trigger recovery for Claude only when Gemini history detected
- Remove unnecessary thinking block filtering for Claude-only conversations
- Add comments explaining '.' placeholder usage
- Remove unused filterUnsignedThinkingFromMessages function

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-04 00:11:14 +05:30
Badri Narayanan S
53f8d7f6cc Add debug logging when stripping thinking blocks
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-03 23:29:21 +05:30
Badri Narayanan S
12e427e9d5 Fix needsThinkingRecovery to require tool loop context
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-03 23:24:52 +05:30
Badri Narayanan S
dc65499c49 Preserve valid thinking blocks during recovery
Instead of stripping all thinking blocks during thinking recovery,
now only strips invalid or incompatible blocks. Uses signature cache
to validate family compatibility for cross-model fallback scenarios.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-03 23:17:38 +05:30
Badri Narayanan S
668c7aef26 correct els if condition for state.inToolLoop 2026-01-03 22:38:46 +05:30
Badri Narayanan S
b7286059ee remove targetFamily from analyzeConversationState 2026-01-03 22:13:35 +05:30
Badri Narayanan S
602d6ca0f8 move fallback map to constants 2026-01-03 22:05:16 +05:30
Badri Narayanan S
ac9ec6b358 Signature handling for fallback 2026-01-03 22:01:57 +05:30
Badri Narayanan S
df6625b531 fallback changes from PR #35 2026-01-03 18:01:21 +05:30
Badri Narayanan S
9c4a712a9a Selective fixes from PR #35: Model-specific rate limits & robustness improvements (#37)
* feat: apply local user changes and fixes

* ;D

* Implement OpenAI support, model-specific rate limiting, and robustness fixes

* docs: update pr title

* feat: ensure unique openai models endpoint

* fix: startup banner alignment and removed duplicates

* feat: add model fallback system with --fallback flag

* fix: accounts cli hanging after completion

* feat: add exit option to accounts cli menu

* fix: remove circular dependency warning for fallback flag

* feat: show active modes in banner and hide their flags

* Remove OpenAI compatibility and fallback features from PR #35

Cherry-picked selective fixes from PR #35 while removing:
- OpenAI-compatible API endpoints (/openai/v1/*)
- Model fallback system (fallback-config.js)
- Thinking block skip for Gemini models
- Unnecessary files (pullrequest.md, test-fix.js, test-openai.js)

Retained improvements:
- Network error handling with retry logic
- Model-specific rate limiting
- Enhanced health check with quota info
- CLI fixes (exit option, process.exit)
- Startup banner alignment (debug mode only)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* banner alignment fix

* Refactor: Model-specific rate limits and cleanup deprecated code

- Remove global rate limit fields (isRateLimited, rateLimitResetTime) in favor of model-specific limits (modelRateLimits[modelId])
- Remove deprecated wrapper functions (is429Error, isAuthInvalidError) from handlers
- Filter fetchAvailableModels to only return Claude and Gemini models
- Fix getCurrentStickyAccount() to pass model param after waiting
- Update /account-limits endpoint to show model-specific limits
- Remove multi-account OAuth flow to avoid state mismatch errors

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix: show (x/y) limited status in account-limits table

- Status is now "ok" only when all models are available
- Shows "(x/y) limited" when x out of y models are exhausted
- Provides better visibility into partial rate limiting

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* docs: update CLAUDE.md with model-specific rate limiting

- Document modelRateLimits[modelId] for per-model rate tracking
- Add isNetworkError() helper to utilities section

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: M1noa <minoa@minoa.cat>
Co-authored-by: Minoa <altgithub@minoa.cat>
Co-authored-by: Claude <noreply@anthropic.com>
2026-01-03 15:33:49 +05:30
Badri Narayanan S
2d05dd5b62 Fix: Reset invalid accounts on startup and improve project discovery logging
Fixes #33 - Accounts marked as invalid were permanently stuck because
the isInvalid flag was persisted to disk but never reset on startup.

Changes:
- Reset isInvalid flag for all accounts on server startup, giving them
  a fresh chance to refresh their OAuth tokens
- Add logging for project discovery failures (was silently failing)
- Add success logging when project is discovered
- Add warning message when falling back to default project

Bug introduced in 01cda83 (2025-12-25) when isInvalid persistence was
added without corresponding reset logic on load.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-02 12:34:35 +05:30
Badri Narayanan S
77089e0360 Fix issue where Antigravity auth is not working 2026-01-02 11:47:54 +05:30
Badri Narayanan S
8e4c4bdfd4 Fix accounts cli path 2026-01-02 00:03:43 +05:30
Badri Narayanan S
f02364d4ef refactor: Reorganize src/ into modular folder structure
Split large monolithic files into focused modules:
- cloudcode-client.js (1,107 lines) → src/cloudcode/ (9 files)
- account-manager.js (639 lines) → src/account-manager/ (5 files)
- Move auth files to src/auth/ (oauth, token-extractor, database)
- Move CLI to src/cli/accounts.js

Update all import paths and documentation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-01 15:13:43 +05:30
Badri Narayanan S
1d91bc0d30 Improve logging, rate limiting, and error handling (#29)
* feat: apply local user changes and fixes

* ;D

* Clean up PR #28: Remove duplicate code lines and unnecessary file

- Remove pullrequest.md (PR notes file not needed in repo)
- Fix duplicate lines in account-manager.js:
  - rateLimitResetTime assignment
  - saveToDisk() calls in markRateLimited and markInvalid
  - invalidReason/invalidAt assignments
  - double return statement in discoverProject

Original PR by M2noa: fix sticky accs, 500s, logging updates, and rate limit handling

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: M2noa <226494568+M2noa@users.noreply.github.com>
Co-Authored-By: Claude <noreply@anthropic.com>

* chore: replace console.log with logger methods for consistency

- Replace all console.log calls with logger.warn/debug in:
  - src/cloudcode-client.js (4 places)
  - src/format/thinking-utils.js (7 places)

This ensures consistent logging behavior with the new logger utility,
respecting --debug mode for verbose output.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: M1noa <minoa@minoa.cat>
Co-authored-by: M2noa <226494568+M2noa@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-01-01 14:35:06 +05:30
Badri Narayanan S
d05fb64e29 Fix: Add Windows support for SQLite database access (Issue #23)
Replace CLI-based sqlite3 extraction with better-sqlite3 library:
- Create shared src/db/database.js module for cross-platform SQLite access
- Remove duplicate extractTokenFromDB functions from token-extractor.js and account-manager.js
- Add better-sqlite3 dependency with prebuilt Windows/Mac/Linux binaries
- Improve error handling with specific messages for common issues

Fixes #23

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-30 18:47:05 +05:30
Badri Narayanan S
ead7632eec Fix: Read Image tool not working 2025-12-30 17:01:01 +05:30
Badri Narayanan S
1bf2362e98 chore: remove unused node-fetch dependency from lockfile
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-30 12:12:27 +05:30
Badri Narayanan S
f3f7189cba Updated readme to set hasCompletedOnboarding to true 2025-12-29 17:26:31 +05:30
Badri Narayanan S
2247df24df updated instructions to load environment variables 2025-12-29 14:46:11 +05:30
Badri Narayanan S
17e7cebef1 Merge pull request #13 from jroth1111/split/count-tokens
Add count_tokens stub
2025-12-29 14:18:26 +05:30
gwizz
306a8891c8 Add count_tokens stub endpoint 2025-12-29 10:57:47 +11:00
Badri Narayanan S
426acc494a Implement Gemini signature caching and thinking recovery
- Add in-memory signature cache to restore thoughtSignatures stripped by Claude Code
- Implement thinking recovery logic to handle interrupted tool loops for Gemini
- Enhance schema sanitizer to preserve constraints and enums as description hints
- Update CLAUDE.md with new architecture details

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-28 14:34:03 +05:30
Badri Narayanan S
1eb2329f7c Gemini schema fix and modularize format converter 2025-12-28 03:28:05 +05:30