Commit Graph
21 Commits
Author SHA1 Message Date
820ac3b56c feat: optimasi boros bandwidth dan CPU (#4)
- Cache layer: LRU cache + TTL untuk non-streaming LLM responses
  (CACHE_TTL, env: CACHE_TTL, CACHE_MAX_SIZE)
- Retries: turunkan default dari pool.size+1 ke 2 (env: MAX_RETRIES)
- Generic stream passthrough: trust content-type, bukan provider name
  (env: STREAM_PASSTHROUGH)
- DSML detection toggle: matikan parsing hot-path kalo gak perlu
  (env: DSML_DETECTION)

All 274 tests pass.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 15:53:42 +07:00
MythEclipseandClaude Opus 4.8 f78f1f5bbf chore: hapus fitur IPv6 source rotation
- Hapus src/lib/ipv6-pool.ts dan test
- Hapus fetchViaCurl() dari fetch-utils.ts
- Hapus parameter ipv6Source dari router, ai-proxy, anthropic-proxy
- Hapus ipv6Only: false dari Bun.serve(), default bind ke 0.0.0.0
- Hapus dokumentasi IPv6 dari CLAUDE.md dan README.md
- SSRF protection untuk IPv6 private/loopback tetap ada

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 12:10:25 +07:00
MythEclipseandClaude Opus 4.8 eec0cd5088 feat: tambah DSML parser untuk konversi tool_calls DeepSeek ke format standar
DeepSeek models mengembalikan tool calls dalam format DSML (DeepSeek
Markup Language) di dalam text content, bukan sebagai JSON structured
tool_calls. Ini menyebabkan tool calling gagal di Claude Code.

Perubahan:
- Buat src/lib/dsml-parser.ts: parser DSML berbasis regex dengan dukungan
  streaming (DSMLAccumulator), deteksi teks sebelum/sesudah DSML, dan
  parsing parameter JSON
- Forward tools/tool_choice dari client ke backend di Anthropic & OpenAI paths
- Konversi DSML ke tool_use content blocks (Anthropic) atau tool_calls array
  (OpenAI) di response non-streaming
- Handle DSML di streaming: buffer text deltas, deteksi di akhir stream,
  emit tool_use/tool_calls events yang sesuai
- Handle tool_result blocks dari Anthropic format di assistant messages
- Tambah 29 tests untuk parser dan 18 tests untuk anthropic-proxy

Fix: #285 tests pass, 0 fail
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 21:25:02 +07:00
Asep Haryana SaputraandGitHub c8ec62c345 fix: unwrap double-nested opencode.ai + handle reasoning_content in Anthropic handler
Two fixes for deepseek-v4-flash-free via Anthropic protocol:

1. **Non-streaming**: Apply config.adaptResponse to unwrap double-nested opencode.ai JSON response before backendToAnthropicResponse
2. **Streaming**: Extract delta.reasoning_content from DeepSeek SSE chunks wrapped in <thinking> tags

All tests pass, verified locally with both streaming and non-streaming.
2026-06-25 01:22:40 +07:00
MythEclipseandClaude Opus 4.8 fc69a0e93c refactor: konsolidasi handler ke router.ts + complexity + test coverage
=== DRY Konsolidasi ===
- handleRelay, requireAuth, handleHealth, handleIndex, getClientIP → 1x di src/lib/router.ts
- api/relay.ts, src/worker.ts, src/index.ts jadi thin wrapper

=== Dead exports ===
- 35 dead exports dibersihkan (dari router.ts, worker.ts, relay.ts)
- Duplikasi simbol dari 12 ke 3 (wajar)

=== Keamanan ===
- Default API key sk-dummy-key dihapus — requireAuth return null saat key kosong
- Semua CORS konsisten via getCorsHeaders()

=== Kompleksitas ===
- handleRequest → pecah ke validateRelayTarget, createJsonErrorResponse, dll
- transformAnthropicStream (170 baris) → 4 sub-fungsi (emitInitEvents, emitDoneEvents, etc)
- handleAnthropicMessages → handleUpstreamError, buildStreamHeaders, buildJsonHeaders
- Fix duplicate stream? field di AnthropicRequest interface

=== Test Coverage ===
- Test naik dari 171 ke 248 (+77 test)
- File baru: src/router.test.ts (requireAuth, getClientIP, CORS, health, index)
- File baru: src/relay-integration.test.ts (filterResponseHeaders, shouldSendBody, buildRelayRequest, classifyFetchError, createRelayResponse, normalizeTargetUrl, SSRF, isPrivateIp)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 23:48:16 +07:00
MythEclipseandClaude Opus 4.8 b69f252f37 fix: remove stray 't' chars causing syntax errors in type definitions
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 21:35:58 +07:00
MythEclipseandClaude Opus 4.8 2171a01974 fix: anthropic messages validation, stream mapping, client error parsing, and add Cloudflare Workers deployment workflow
- Fix type mappings in OpenAIRequest and BackendConfig to handle structured message parts (cache-control).
- Stop adaptRequest crashing when message contents are objects or arrays.
- Forward stream, top_k, and stop_sequences to adaptRequest.
- Forward anthropic-version header to backend endpoints during adaptation.
- Parse structured JSON error payloads from upstream before returning generic "Upstream rejected request" error.
- Create .github/workflows/cloudflare.yml to auto-deploy on master branch pushes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 19:37:23 +07:00
MythEclipse ccb1523692 feat: antropik cache — default anthropic-version, forward cache headers, model features, streaming usage, tests
- Auto-default anthropic-version to 2023-06-01 for prompt caching
- Forward cache headers (x-cache, cf-cache-status, age, etc.) from backend
- Add features: ["prompt_caching"] to /v1/models response
- Extract and report actual usage tokens in streaming message_delta
- Track output char count for token estimation when backend omits it
- Cache-aware usage reporting: cache_creation_input_tokens, cache_read_input_tokens
- Comprehensive tests for cache_control preservation in content blocks & system
2026-06-20 21:38:34 +07:00
MythEclipse 7bb1b443be feat: anthropic cache support — preserve cache_control, forward anthropic-version header, report real usage tokens
- Add anthropicPassthrough flag to BackendConfig for native Anthropic backends
- Preserve cache_control on content blocks and system prompt (keep structured)
- Extract and forward anthropic-version header from client to backend
- Report actual token usage from backend response (input_tokens, output_tokens)
- Support native Anthropic passthrough (no translation) for compatible backends
- Wire anthropic-version through all entry points: index.ts, router.ts, worker.ts
2026-06-20 21:34:31 +07:00
MythEclipse ac19f8f30d perf: stability and performance improvements across proxy
- Add exponential backoff (200ms-2s) between retry attempts
- Fix session retry bug: rotate proxy before retry to avoid same proxy
- Fix ACTIVE_READERS memory leak: release reader on stream done/error
- Make closeAllActiveReaders async with proper await
- WebSocket backpressure: pause upstream forwarding at 512KB buffer
- Optimize rate-limiter pruneTimestamps: avoid array reallocation
- Batch stream chunks (8 per yield) to reduce event loop overhead
- Add periodic cooldown cleanup in ProxyPool (30s interval)
- Extract shared wrapStreamWithCleanup utility to reduce duplication
- Fix fetchViaCurl temp file cleanup with proper unlink()
- Add missing ipv6Source overload to AI proxy handlers
2026-06-20 19:32:23 +07:00
MythEclipse c62de0899a fix: streaming reliability, timeout, memory leaks, and retry improvements
- Fix streaming timeout: use AbortController for connection-only timeout
  instead of AbortSignal.timeout() that kills active SSE streams
- Fix fetchViaCurl: stream body via ReadableStream instead of buffering
  entire response in memory
- Fix JWT/aichat race condition: add Promise dedup to prevent concurrent
  bootstrap calls (10 requests = 1 bootstrap, not 10)
- Fix ACTIVE_READERS memory leak: auto-remove readers on stream completion
- Fix WebSocket backpressure: log warning when client buffer exceeds 1MB
- Add SSE heartbeat/keepalive: send ': keepalive' every 15s to prevent
  LB/proxy timeout during AI thinking
- Fix SSELineBuffer: graceful overflow handling (warn + discard instead
  of throwing error that crashes stream)
- Fix transformStream tight loop: yield to event loop after each chunk
  to prevent starvation
- Fix fetchViaCurl process cleanup: use SIGKILL + proper timeout cleanup
- Add retry on 502/504: retry transient server errors before returning
  to caller (both fetchWithRetry and fetchWithSessionRetry)
2026-06-20 17:13:32 +07:00
MythEclipse 17338a7dca feat: IPv6 outbound rotation via curl --interface
- Add IPv6SourcePool for round-robin IP rotation
- fetchViaCurl: Bun.spawn + curl -6 --interface for source binding
- Auto-fallback to regular fetch when IPv6 connection fails
- Response decompression via --compressed flag
- Docker + GHCR build/deploy workflows
- 8 routable IPv6 addresses on VPS
2026-06-19 19:07:46 +07:00
MythEclipseandClaude 9bd6acddc5 feat: implement session-based sticky proxy pool with auto-failover
Add SessionProxyPool for per-session sticky proxy allocation with
load-balanced least-used selection and auto-rotation on failure.
Introduce fetchWithSessionRetry for transparent retry with proxy
rotation. Wire into AI proxy handlers (OpenAI + Anthropic) with
stream lifecycle cleanup.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-16 23:50:47 +07:00
MythEclipse b09bca8def feat(core): implement robust fetch utilities and stream management
Introduce a centralized `fetch-utils.ts` to handle retry logic with proxy fallback, SSE line buffering to prevent chunk-boundary corruption, and graceful shutdown via active reader tracking.

Key changes:
- Add `fetchWithRetry` for automatic direct-to-proxy failover.
- Implement `SSELineBuffer` to ensure reliable parsing of split SSE chunks.
- Add `createStreamBodyLimiter` to enforce payload limits on streaming requests.
- Refactor `ProxyPool` to decouple failure marking from rotation.
- Standardize CORS handling and environment variable configuration.
- Clean up documentation and remove obsolete skill files.
2026-06-11 03:56:26 +07:00
MythEclipse db065f788d style(anthropic-proxy): update comment formatting and add SSE utility functions
Standardize comment separators and arrow usage in documentation headers.
Additionally, introduce `accumulateSSEText` and `extractTextFromSSE` to
provide robust parsing for various SSE stream formats, including
Claude Code and OpenAI-compatible deltas.
2026-06-11 01:43:23 +07:00
MythEclipse 261f84a96e refactor(anthropic-proxy): improve SSE stream transformation logic
Refactor the backend-to-Anthropic SSE transformation to use a more robust
state machine approach. This replaces manual string building with a
structured phase-based system (`init`, `block`, `done`) to better
manage the Anthropic streaming protocol, including `message_start` and
`content_block_delta` events.

- Extract `formatContentBlockDelta` helper for consistent event formatting
- Implement phase-based state machine in `transformAnthropicStream`
- Delegate `[DONE]` handling to the stream transformer instead of
  manually emitting `message_stop`
- Improve reliability of message ID generation and event sequencing
2026-06-11 01:24:54 +07:00
MythEclipseandClaude Fable 5 2fead57d0f fix: use MODEL_ROUTES directly for Anthropic proxy routing
Remove the ANTHROPIC_MODEL_MAP layer — /v1/messages now uses the
same model names as /v1/chat/completions (deepseek-v4-flash-free,
gpt-5.4-mini-no-login, deepseek/deepseek-v4-flash). This way users
send the original model name and it routes to the correct backend.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 00:42:21 +07:00
MythEclipseandClaude Fable 5 2fca9febe4 fix: pass original model name to backend in Anthropic proxy
Use anthReq.model instead of backendModel so the backend receives
the user-sent model name (e.g. claude-sonnet-4) rather than the
internal mapped name.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 00:20:20 +07:00
MythEclipseandClaude Fable 5 5974d31164 fix: avoid double markFailed in AI proxy retry loop
Response handler already calls markFailed() on non-2xx and network
errors (which rotates the proxy). The preamble at attempt >= 2 was
calling markFailed() again, double-rotating and skipping a proxy.
Changed preamble to use rotate() instead of markFailed().

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 00:02:40 +07:00
MythEclipseandClaude Fable 5 2dfb87eac6 fix: retry AI proxy with next proxy on HTTP errors too
Previously only retried on network errors (fetch exceptions). Now also
rotates to next proxy when upstream returns non-2xx (429 rate limit,
5xx, etc). Applies to both OpenAI and Anthropic endpoints.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 23:57:24 +07:00
MythEclipseandClaude Fable 5 4168a087a0 feat: add Anthropic-compatible AI proxy endpoint
- Create src/lib/anthropic-proxy.ts: accepts Anthropic Messages API
  format (POST /v1/messages) and routes to the same backend providers
- Anthropic model names (claude-sonnet-4, claude-3-haiku, claude-opus-4)
  map to backend models with full request/response translation
- Streaming (SSE) via Anthropic protocol: message_start,
  content_block_delta, message_stop events
- Add /v1/messages route to server with CORS and proxy pool fallback
- Reuses MODEL_ROUTES from ai-proxy.ts for consistent backend routing

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 23:08:32 +07:00