Spaces:
Running
Running
Commit ·
2e7b8ca
1
Parent(s): f7872b8
sync: upstream 8dfff832 (v6.18.5) + custom addons (KeyRotator, 401/403 rotation, sol/terra/luna, ScannerTrap, health, Py3.12 compat)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- pyproject.toml +19 -15
- src/free_claude_code/api/admin_routes.py +61 -1
- src/free_claude_code/api/admin_static/admin.css +10 -5
- src/free_claude_code/api/admin_static/admin.js +167 -36
- src/free_claude_code/api/admin_static/code_sessions.js +86 -43
- src/free_claude_code/api/admin_static/index.html +27 -0
- src/free_claude_code/api/admin_static/session_ui.js +10 -1
- src/free_claude_code/api/app.py +35 -7
- src/free_claude_code/api/command_utils.py +0 -165
- src/free_claude_code/api/dependencies.py +29 -0
- src/free_claude_code/api/detection.py +1 -141
- src/free_claude_code/api/generation_paths.py +16 -0
- src/free_claude_code/api/handlers/gemini.py +123 -0
- src/free_claude_code/api/handlers/messages.py +11 -56
- src/free_claude_code/api/optimization_handlers.py +0 -163
- src/free_claude_code/api/ports.py +6 -0
- src/free_claude_code/api/request_errors.py +7 -1
- src/free_claude_code/api/request_ids.py +3 -1
- src/free_claude_code/api/request_lifetime.py +7 -2
- src/free_claude_code/api/request_outcomes.py +14 -6
- src/free_claude_code/api/response_streams.py +38 -1
- src/free_claude_code/api/routes.py +78 -2
- src/free_claude_code/api/stream_delivery.py +18 -12
- src/free_claude_code/api/stream_frames.py +1 -11
- src/free_claude_code/api/tool_call_buffer.py +4 -1
- src/free_claude_code/application/code_sessions/service.py +2 -2
- src/free_claude_code/application/execution.py +62 -3
- src/free_claude_code/application/model_metadata.py +2 -1
- src/free_claude_code/application/ports.py +17 -1
- src/free_claude_code/application/reasoning.py +15 -3
- src/free_claude_code/application/routing.py +33 -1
- src/free_claude_code/cli/desktop_entrypoint.py +10 -0
- src/free_claude_code/cli/doctor.py +21 -2
- src/free_claude_code/cli/launchers/agy.py +95 -0
- src/free_claude_code/cli/launchers/opencode_config.py +3 -0
- src/free_claude_code/cli/macos_app.py +148 -0
- src/free_claude_code/cli/uvicorn_server.py +28 -0
- src/free_claude_code/config/admin/manifest.py +0 -40
- src/free_claude_code/config/admin/provider_manifest.py +4 -2
- src/free_claude_code/config/constants.py +1 -1
- src/free_claude_code/config/env_migrations.py +1 -3
- src/free_claude_code/config/loader.py +2 -4
- src/free_claude_code/config/model_refs.py +38 -6
- src/free_claude_code/config/nim.py +0 -122
- src/free_claude_code/config/settings.py +1 -28
- src/free_claude_code/core/anthropic/tokens.py +6 -3
- src/free_claude_code/core/async_rwlock.py +3 -3
- src/free_claude_code/core/continuation_overlap.py +32 -19
- src/free_claude_code/core/continuation_stream.py +17 -0
- src/free_claude_code/core/delivered_response.py +61 -16
pyproject.toml
CHANGED
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
| 4 |
|
| 5 |
[project]
|
| 6 |
name = "free-claude-code"
|
| 7 |
-
version = "6.
|
| 8 |
description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"
|
| 9 |
readme = "README.md"
|
| 10 |
license = "AGPL-3.0-only"
|
|
@@ -17,28 +17,28 @@ dependencies = [
|
|
| 17 |
"httpx[socks]>=0.28.1",
|
| 18 |
"httpx2[socks]>=2.7.0,<3",
|
| 19 |
"markdown-it-py>=4.2.0",
|
| 20 |
-
"pydantic>=2.
|
| 21 |
"python-dotenv>=1.2.4",
|
| 22 |
"tiktoken>=0.13.0",
|
| 23 |
"python-telegram-bot>=22.8",
|
| 24 |
"discord.py>=2.7.1",
|
| 25 |
-
"openai>=3.
|
| 26 |
"loguru>=0.7.0",
|
| 27 |
-
"aiohttp>=3.14.
|
| 28 |
"jsonschema>=4.25.0",
|
| 29 |
-
"json5>=0.
|
| 30 |
-
"tomlkit>=0.
|
| 31 |
"google-auth[requests]>=2.56.3",
|
| 32 |
"requests[socks]>=2.34.2",
|
| 33 |
"pystray>=0.19.5; sys_platform == 'win32' or sys_platform == 'darwin'",
|
| 34 |
-
"Pillow>=
|
| 35 |
-
"github-copilot-sdk>=1.0.
|
| 36 |
"simplejson>=4.2.0",
|
| 37 |
-
"grpcio>=1.84.
|
| 38 |
"grpcio-tools>=1.81.1",
|
| 39 |
"nvidia-riva-client>=2.26.0",
|
| 40 |
"pyperclip>=1.11.0",
|
| 41 |
-
"sqlalchemy>=2.1.
|
| 42 |
"ruamel-yaml>=0.19.1",
|
| 43 |
]
|
| 44 |
|
|
@@ -55,6 +55,7 @@ fcc-hermes = "free_claude_code.cli.launchers.hermes:launch"
|
|
| 55 |
fcc-dsh = "free_claude_code.cli.launchers.dsh:launch"
|
| 56 |
fcc-grok = "free_claude_code.cli.launchers.grok:launch"
|
| 57 |
fcc-muse = "free_claude_code.cli.launchers.muse:launch"
|
|
|
|
| 58 |
fcc-aider = "free_claude_code.cli.launchers.aider:launch"
|
| 59 |
|
| 60 |
[project.gui-scripts]
|
|
@@ -63,11 +64,14 @@ fcc-desktop = "free_claude_code.cli.desktop_entrypoint:launch"
|
|
| 63 |
[project.optional-dependencies]
|
| 64 |
voice_local = [
|
| 65 |
"torch>=2.14.1",
|
| 66 |
-
"transformers>=5.
|
| 67 |
"accelerate>=1.15.0",
|
| 68 |
"librosa>=1.0.0",
|
| 69 |
]
|
| 70 |
|
|
|
|
|
|
|
|
|
|
| 71 |
[tool.hatch.build.targets.wheel]
|
| 72 |
packages = ["src/free_claude_code"]
|
| 73 |
|
|
@@ -76,7 +80,7 @@ packages = ["src/free_claude_code"]
|
|
| 76 |
"scripts/update/fcc-update.cmd" = "fcc-update.cmd"
|
| 77 |
|
| 78 |
[tool.uv]
|
| 79 |
-
required-version = ">=0.
|
| 80 |
cache-keys = [{ file = "pyproject.toml" }, { git = { commit = true, tags = true } }]
|
| 81 |
|
| 82 |
[tool.uv.sources]
|
|
@@ -92,10 +96,10 @@ dev = [
|
|
| 92 |
"pytest>=9.1.1",
|
| 93 |
"pytest-asyncio>=1.4.0",
|
| 94 |
"pytest-cov>=7.1.0",
|
| 95 |
-
"ty>=0.0.
|
| 96 |
-
"ruff>=0.
|
| 97 |
"pytest-xdist>=3.8.0",
|
| 98 |
-
"pytest-playwright>=0.
|
| 99 |
"pyyaml>=6.0.3",
|
| 100 |
"pytest-split>=0.11.0",
|
| 101 |
]
|
|
|
|
| 4 |
|
| 5 |
[project]
|
| 6 |
name = "free-claude-code"
|
| 7 |
+
version = "6.18.5"
|
| 8 |
description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"
|
| 9 |
readme = "README.md"
|
| 10 |
license = "AGPL-3.0-only"
|
|
|
|
| 17 |
"httpx[socks]>=0.28.1",
|
| 18 |
"httpx2[socks]>=2.7.0,<3",
|
| 19 |
"markdown-it-py>=4.2.0",
|
| 20 |
+
"pydantic>=2.14.1",
|
| 21 |
"python-dotenv>=1.2.4",
|
| 22 |
"tiktoken>=0.13.0",
|
| 23 |
"python-telegram-bot>=22.8",
|
| 24 |
"discord.py>=2.7.1",
|
| 25 |
+
"openai>=3.37.0",
|
| 26 |
"loguru>=0.7.0",
|
| 27 |
+
"aiohttp>=3.14.5",
|
| 28 |
"jsonschema>=4.25.0",
|
| 29 |
+
"json5>=0.17.3",
|
| 30 |
+
"tomlkit>=0.15.2",
|
| 31 |
"google-auth[requests]>=2.56.3",
|
| 32 |
"requests[socks]>=2.34.2",
|
| 33 |
"pystray>=0.19.5; sys_platform == 'win32' or sys_platform == 'darwin'",
|
| 34 |
+
"Pillow>=13.0.0; sys_platform == 'win32' or sys_platform == 'darwin'",
|
| 35 |
+
"github-copilot-sdk>=1.0.26",
|
| 36 |
"simplejson>=4.2.0",
|
| 37 |
+
"grpcio>=1.84.1",
|
| 38 |
"grpcio-tools>=1.81.1",
|
| 39 |
"nvidia-riva-client>=2.26.0",
|
| 40 |
"pyperclip>=1.11.0",
|
| 41 |
+
"sqlalchemy>=2.1.6",
|
| 42 |
"ruamel-yaml>=0.19.1",
|
| 43 |
]
|
| 44 |
|
|
|
|
| 55 |
fcc-dsh = "free_claude_code.cli.launchers.dsh:launch"
|
| 56 |
fcc-grok = "free_claude_code.cli.launchers.grok:launch"
|
| 57 |
fcc-muse = "free_claude_code.cli.launchers.muse:launch"
|
| 58 |
+
fcc-agy = "free_claude_code.cli.launchers.agy:launch"
|
| 59 |
fcc-aider = "free_claude_code.cli.launchers.aider:launch"
|
| 60 |
|
| 61 |
[project.gui-scripts]
|
|
|
|
| 64 |
[project.optional-dependencies]
|
| 65 |
voice_local = [
|
| 66 |
"torch>=2.14.1",
|
| 67 |
+
"transformers>=5.20.2",
|
| 68 |
"accelerate>=1.15.0",
|
| 69 |
"librosa>=1.0.0",
|
| 70 |
]
|
| 71 |
|
| 72 |
+
[tool.hatch.build]
|
| 73 |
+
artifacts = ["src/free_claude_code/assets/macos/fcc-desktop-*"]
|
| 74 |
+
|
| 75 |
[tool.hatch.build.targets.wheel]
|
| 76 |
packages = ["src/free_claude_code"]
|
| 77 |
|
|
|
|
| 80 |
"scripts/update/fcc-update.cmd" = "fcc-update.cmd"
|
| 81 |
|
| 82 |
[tool.uv]
|
| 83 |
+
required-version = ">=0.13.6"
|
| 84 |
cache-keys = [{ file = "pyproject.toml" }, { git = { commit = true, tags = true } }]
|
| 85 |
|
| 86 |
[tool.uv.sources]
|
|
|
|
| 96 |
"pytest>=9.1.1",
|
| 97 |
"pytest-asyncio>=1.4.0",
|
| 98 |
"pytest-cov>=7.1.0",
|
| 99 |
+
"ty>=0.0.91",
|
| 100 |
+
"ruff>=0.17.2",
|
| 101 |
"pytest-xdist>=3.8.0",
|
| 102 |
+
"pytest-playwright>=0.10.0",
|
| 103 |
"pyyaml>=6.0.3",
|
| 104 |
"pytest-split>=0.11.0",
|
| 105 |
]
|
src/free_claude_code/api/admin_routes.py
CHANGED
|
@@ -3,6 +3,7 @@ from __future__ import annotations
|
|
| 3 |
|
| 4 |
from collections.abc import Awaitable, Callable, Mapping
|
| 5 |
from pathlib import Path
|
|
|
|
| 6 |
|
| 7 |
import httpx
|
| 8 |
from fastapi import (
|
|
@@ -300,6 +301,33 @@ async def vscode_chat_status(
|
|
| 300 |
return await _integration_response(services.admin.vscode_chat_status)
|
| 301 |
|
| 302 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
@router.post("/admin/api/integrations/vscode-chat/connect")
|
| 304 |
async def connect_vscode_chat(
|
| 305 |
request: Request,
|
|
@@ -551,9 +579,13 @@ async def _check_local_provider(
|
|
| 551 |
"status": "missing_url",
|
| 552 |
"label": "Missing URL",
|
| 553 |
"base_url": base_url,
|
|
|
|
|
|
|
|
|
|
| 554 |
}
|
| 555 |
|
| 556 |
url = f"{clean_url}{path}"
|
|
|
|
| 557 |
try:
|
| 558 |
async with httpx.AsyncClient(timeout=1.5) as client:
|
| 559 |
response = await client.get(url)
|
|
@@ -564,6 +596,9 @@ async def _check_local_provider(
|
|
| 564 |
"label": "Reachable" if ok else "Offline",
|
| 565 |
"base_url": base_url,
|
| 566 |
"status_code": response.status_code,
|
|
|
|
|
|
|
|
|
|
| 567 |
}
|
| 568 |
except Exception as exc:
|
| 569 |
logger.debug(
|
|
@@ -571,15 +606,40 @@ async def _check_local_provider(
|
|
| 571 |
provider_id,
|
| 572 |
type(exc).__name__,
|
| 573 |
)
|
|
|
|
| 574 |
return {
|
| 575 |
"provider_id": provider_id,
|
| 576 |
"status": "offline",
|
| 577 |
"label": "Offline",
|
| 578 |
"base_url": base_url,
|
| 579 |
-
"message":
|
|
|
|
|
|
|
|
|
|
| 580 |
}
|
| 581 |
|
| 582 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 583 |
def _require_connected_account_provider(provider_id: str) -> None:
|
| 584 |
descriptor = PROVIDER_CATALOG.get(provider_id)
|
| 585 |
if (
|
|
|
|
| 3 |
|
| 4 |
from collections.abc import Awaitable, Callable, Mapping
|
| 5 |
from pathlib import Path
|
| 6 |
+
from time import perf_counter
|
| 7 |
|
| 8 |
import httpx
|
| 9 |
from fastapi import (
|
|
|
|
| 301 |
return await _integration_response(services.admin.vscode_chat_status)
|
| 302 |
|
| 303 |
|
| 304 |
+
@router.get("/admin/api/integrations/antigravity")
|
| 305 |
+
async def antigravity_status(
|
| 306 |
+
request: Request,
|
| 307 |
+
services: ApiServices = Depends(get_services),
|
| 308 |
+
):
|
| 309 |
+
require_loopback_admin(request)
|
| 310 |
+
return await _integration_response(services.admin.antigravity_status)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
@router.post("/admin/api/integrations/antigravity/connect")
|
| 314 |
+
async def connect_antigravity(
|
| 315 |
+
request: Request,
|
| 316 |
+
services: ApiServices = Depends(get_services),
|
| 317 |
+
):
|
| 318 |
+
require_loopback_admin(request)
|
| 319 |
+
return await _integration_response(services.admin.connect_antigravity)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
@router.post("/admin/api/integrations/antigravity/disconnect")
|
| 323 |
+
async def disconnect_antigravity(
|
| 324 |
+
request: Request,
|
| 325 |
+
services: ApiServices = Depends(get_services),
|
| 326 |
+
):
|
| 327 |
+
require_loopback_admin(request)
|
| 328 |
+
return await _integration_response(services.admin.disconnect_antigravity)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
@router.post("/admin/api/integrations/vscode-chat/connect")
|
| 332 |
async def connect_vscode_chat(
|
| 333 |
request: Request,
|
|
|
|
| 579 |
"status": "missing_url",
|
| 580 |
"label": "Missing URL",
|
| 581 |
"base_url": base_url,
|
| 582 |
+
"probe_path": path,
|
| 583 |
+
"latency_ms": None,
|
| 584 |
+
"error_type": None,
|
| 585 |
}
|
| 586 |
|
| 587 |
url = f"{clean_url}{path}"
|
| 588 |
+
started = perf_counter()
|
| 589 |
try:
|
| 590 |
async with httpx.AsyncClient(timeout=1.5) as client:
|
| 591 |
response = await client.get(url)
|
|
|
|
| 596 |
"label": "Reachable" if ok else "Offline",
|
| 597 |
"base_url": base_url,
|
| 598 |
"status_code": response.status_code,
|
| 599 |
+
"probe_path": path,
|
| 600 |
+
"latency_ms": round((perf_counter() - started) * 1000, 2),
|
| 601 |
+
"error_type": None if ok else "http_error",
|
| 602 |
}
|
| 603 |
except Exception as exc:
|
| 604 |
logger.debug(
|
|
|
|
| 606 |
provider_id,
|
| 607 |
type(exc).__name__,
|
| 608 |
)
|
| 609 |
+
error_type, message = _local_provider_failure(exc)
|
| 610 |
return {
|
| 611 |
"provider_id": provider_id,
|
| 612 |
"status": "offline",
|
| 613 |
"label": "Offline",
|
| 614 |
"base_url": base_url,
|
| 615 |
+
"message": message,
|
| 616 |
+
"probe_path": path,
|
| 617 |
+
"latency_ms": round((perf_counter() - started) * 1000, 2),
|
| 618 |
+
"error_type": error_type,
|
| 619 |
}
|
| 620 |
|
| 621 |
|
| 622 |
+
def _local_provider_failure(exc: Exception) -> tuple[str, str]:
|
| 623 |
+
if isinstance(exc, httpx.TimeoutException):
|
| 624 |
+
return (
|
| 625 |
+
"timeout",
|
| 626 |
+
"The local provider availability check timed out. Check that its server is responsive and retry.",
|
| 627 |
+
)
|
| 628 |
+
if isinstance(exc, (httpx.ConnectError, httpx.ProxyError)):
|
| 629 |
+
return "connection_error", _LOCAL_PROVIDER_CHECK_FAILURE_MESSAGE
|
| 630 |
+
if isinstance(exc, (httpx.InvalidURL, httpx.UnsupportedProtocol)):
|
| 631 |
+
return (
|
| 632 |
+
"invalid_url",
|
| 633 |
+
"Check the local provider's HTTP or HTTPS base URL and port.",
|
| 634 |
+
)
|
| 635 |
+
if isinstance(exc, httpx.RequestError):
|
| 636 |
+
return (
|
| 637 |
+
"transport_error",
|
| 638 |
+
"The connection ended before the availability check completed. Retry and check the local server logs.",
|
| 639 |
+
)
|
| 640 |
+
return "unexpected_error", _LOCAL_PROVIDER_CHECK_FAILURE_MESSAGE
|
| 641 |
+
|
| 642 |
+
|
| 643 |
def _require_connected_account_provider(provider_id: str) -> None:
|
| 644 |
descriptor = PROVIDER_CATALOG.get(provider_id)
|
| 645 |
if (
|
src/free_claude_code/api/admin_static/admin.css
CHANGED
|
@@ -361,7 +361,8 @@ button.startup-busy::before,
|
|
| 361 |
.provider-dialog .field-grid { grid-template-columns: minmax(0, 1fr); }
|
| 362 |
.provider-dialog .field.advanced-field { display: flex; }
|
| 363 |
.provider-dialog .provider-actions:not(:empty),
|
| 364 |
-
.provider-dialog .provider-check-result:not([hidden])
|
|
|
|
| 365 |
.provider-dialog .message-area:empty { display: none; }
|
| 366 |
.provider-dialog-footer { display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px; }
|
| 367 |
|
|
@@ -411,24 +412,28 @@ button.startup-busy::before,
|
|
| 411 |
overflow-wrap: anywhere;
|
| 412 |
}
|
| 413 |
|
| 414 |
-
.provider-check-result
|
|
|
|
| 415 |
color: var(--muted);
|
| 416 |
font-size: 12px;
|
| 417 |
line-height: 1.4;
|
| 418 |
overflow-wrap: anywhere;
|
| 419 |
}
|
| 420 |
|
| 421 |
-
.provider-check-result.ok
|
|
|
|
| 422 |
color: var(--ok);
|
| 423 |
}
|
| 424 |
|
| 425 |
-
.provider-check-result.error
|
|
|
|
| 426 |
color: var(--error);
|
| 427 |
}
|
| 428 |
|
| 429 |
.provider-meta.error { color: var(--error); }
|
| 430 |
|
| 431 |
-
.provider-check-result.checking
|
|
|
|
| 432 |
color: var(--info);
|
| 433 |
}
|
| 434 |
|
|
|
|
| 361 |
.provider-dialog .field-grid { grid-template-columns: minmax(0, 1fr); }
|
| 362 |
.provider-dialog .field.advanced-field { display: flex; }
|
| 363 |
.provider-dialog .provider-actions:not(:empty),
|
| 364 |
+
.provider-dialog .provider-check-result:not([hidden]),
|
| 365 |
+
.provider-dialog .provider-availability-result:not([hidden]) { margin-bottom: 20px; }
|
| 366 |
.provider-dialog .message-area:empty { display: none; }
|
| 367 |
.provider-dialog-footer { display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px; }
|
| 368 |
|
|
|
|
| 412 |
overflow-wrap: anywhere;
|
| 413 |
}
|
| 414 |
|
| 415 |
+
.provider-check-result,
|
| 416 |
+
.provider-availability-result {
|
| 417 |
color: var(--muted);
|
| 418 |
font-size: 12px;
|
| 419 |
line-height: 1.4;
|
| 420 |
overflow-wrap: anywhere;
|
| 421 |
}
|
| 422 |
|
| 423 |
+
.provider-check-result.ok,
|
| 424 |
+
.provider-availability-result.ok {
|
| 425 |
color: var(--ok);
|
| 426 |
}
|
| 427 |
|
| 428 |
+
.provider-check-result.error,
|
| 429 |
+
.provider-availability-result.error {
|
| 430 |
color: var(--error);
|
| 431 |
}
|
| 432 |
|
| 433 |
.provider-meta.error { color: var(--error); }
|
| 434 |
|
| 435 |
+
.provider-check-result.checking,
|
| 436 |
+
.provider-availability-result.checking {
|
| 437 |
color: var(--info);
|
| 438 |
}
|
| 439 |
|
src/free_claude_code/api/admin_static/admin.js
CHANGED
|
@@ -19,7 +19,7 @@ const state = {
|
|
| 19 |
startupRequest: null,
|
| 20 |
startupTimer: null,
|
| 21 |
startupAgain: false,
|
| 22 |
-
|
| 23 |
modelOptionsRequest: 0,
|
| 24 |
activeView: viewFromLocation(),
|
| 25 |
};
|
|
@@ -142,6 +142,7 @@ function renderStartup() {
|
|
| 142 |
renderProviderCheckResult(provider.provider_id);
|
| 143 |
});
|
| 144 |
renderClaudeIntegration();
|
|
|
|
| 145 |
renderVSCodeChatIntegration();
|
| 146 |
renderJetBrainsIntegration();
|
| 147 |
renderCodexIntegration();
|
|
@@ -177,8 +178,8 @@ async function refreshStartup() {
|
|
| 177 |
const changed = !previous || previous.instance_id !== result.instance_id ||
|
| 178 |
JSON.stringify(previous.startup) !== JSON.stringify(current);
|
| 179 |
if (changed) void hydrateModelOptions();
|
| 180 |
-
if (changed
|
| 181 |
-
pending =
|
| 182 |
current.code?.state === "starting" || current.messaging?.state === "starting" ||
|
| 183 |
Object.values(current.integrations || {}).some((update) => update.state === "starting") ||
|
| 184 |
Object.values(current.providers || {}).includes("starting");
|
|
@@ -209,11 +210,13 @@ window.addEventListener("pagehide", () => {
|
|
| 209 |
});
|
| 210 |
|
| 211 |
async function load({ providersOnly = false } = {}) {
|
|
|
|
| 212 |
state.localStatusRequest = null;
|
| 213 |
state.startupRequest?.controller.abort();
|
| 214 |
state.startupRequest = null;
|
| 215 |
showMessage("Loading admin config");
|
| 216 |
const config = await api("/admin/api/config");
|
|
|
|
| 217 |
config.custom_providers ||= [];
|
| 218 |
config.provider_status.push(...config.custom_providers.map((provider) => ({ ...provider, kind: "custom", status: "configured", settings_keys: [], missing_configuration_keys: [] })));
|
| 219 |
state.config = config;
|
|
@@ -229,11 +232,10 @@ async function load({ providersOnly = false } = {}) {
|
|
| 229 |
byId("configPath").textContent = config.paths.managed;
|
| 230 |
void refreshLocalStatus(config);
|
| 231 |
void refreshStartup();
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
]);
|
| 237 |
if (state.config !== config) return;
|
| 238 |
updateDirtyState();
|
| 239 |
showMessage("");
|
|
@@ -265,7 +267,7 @@ function setActiveView(viewId, { scroll = false } = {}) {
|
|
| 265 |
state.activeView = activeView.id;
|
| 266 |
byId("pageTitle").textContent = activeView.title;
|
| 267 |
renderStartup();
|
| 268 |
-
if (activeView.id === "code")
|
| 269 |
void refreshStartup();
|
| 270 |
const sessionActive = activeView.id === "code";
|
| 271 |
document.querySelector(".app-shell").classList.toggle("session-active", sessionActive);
|
|
@@ -295,6 +297,7 @@ function setActiveView(viewId, { scroll = false } = {}) {
|
|
| 295 |
if (activeView.id === "code") window.CodeSessions.activate(window.location.pathname);
|
| 296 |
else window.CodeSessions.deactivate();
|
| 297 |
if (activeView.id === "integrations") {
|
|
|
|
| 298 |
refreshClaudeIntegration();
|
| 299 |
refreshClaudeOnboarding();
|
| 300 |
refreshVSCodeChatIntegration();
|
|
@@ -407,6 +410,10 @@ function updateProviderCard(provider) {
|
|
| 407 |
result.className = "provider-check-result";
|
| 408 |
result.dataset.providerCheckResult = provider.provider_id;
|
| 409 |
result.hidden = true;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
const actions = document.createElement("div");
|
| 411 |
actions.className = "provider-actions";
|
| 412 |
if (oauth) populateConnectedAccountActions(provider, status, actions);
|
|
@@ -418,7 +425,7 @@ function updateProviderCard(provider) {
|
|
| 418 |
settings.setAttribute("aria-controls", "providerDialog");
|
| 419 |
actions.appendChild(settings);
|
| 420 |
}
|
| 421 |
-
card.replaceChildren(title, meta, result, actions);
|
| 422 |
const next = [...grid.children].find((other) => other !== card &&
|
| 423 |
connectedAccountName(provider).localeCompare(providerDisplayName(other.dataset.provider), "en", { sensitivity: "base" }) < 0);
|
| 424 |
if (card.parentElement !== grid || card.nextElementSibling !== (next || null)) grid.insertBefore(card, next || null);
|
|
@@ -489,6 +496,7 @@ async function openCustomProviderDialog(providerId = null) {
|
|
| 489 |
byId("providerDialogTitle").textContent = providerId ? provider.display_name : "Add provider";
|
| 490 |
byId("providerMessage").textContent = "";
|
| 491 |
byId("providerDialogCheck").hidden = true;
|
|
|
|
| 492 |
const fields = byId("providerFields");
|
| 493 |
fields.replaceChildren();
|
| 494 |
const formats = (state.config.custom_reasoning_formats || {})[provider.api_format] || ["provider_default"];
|
|
@@ -553,10 +561,8 @@ function renderProviderDialogActions(provider) {
|
|
| 553 |
actions.appendChild(button);
|
| 554 |
}
|
| 555 |
const check = oauth ? null : providerCheckResult(provider.provider_id);
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
result.textContent = check?.message || "";
|
| 559 |
-
result.hidden = !check?.message;
|
| 560 |
byId("saveProvider").hidden = !provider.settings_keys?.length;
|
| 561 |
renderStartup();
|
| 562 |
}
|
|
@@ -779,14 +785,22 @@ function providerCheckResult(providerId) {
|
|
| 779 |
// An explicit check takes precedence over background discovery and reachability.
|
| 780 |
if (check?.source === "manual") return check;
|
| 781 |
const discovery = state.startup?.startup?.providers?.[providerId];
|
| 782 |
-
|
| 783 |
-
if (discovery === "
|
| 784 |
-
|
| 785 |
-
}
|
| 786 |
-
|
| 787 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 788 |
}
|
| 789 |
-
|
|
|
|
| 790 |
}
|
| 791 |
|
| 792 |
function updateProviderCheckResult(providerId, status, message, source = "manual") {
|
|
@@ -794,8 +808,17 @@ function updateProviderCheckResult(providerId, status, message, source = "manual
|
|
| 794 |
renderProviderCheckResult(providerId);
|
| 795 |
}
|
| 796 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 797 |
function renderProviderCheckResult(providerId) {
|
| 798 |
-
const
|
|
|
|
| 799 |
const card = document.querySelector(`[data-provider="${providerId}"]`);
|
| 800 |
if (!card) return;
|
| 801 |
const provider = connectedAccountDescriptor(providerId);
|
|
@@ -810,15 +833,11 @@ function renderProviderCheckResult(providerId) {
|
|
| 810 |
if (account?.state === "error") meta.classList.add("error");
|
| 811 |
return;
|
| 812 |
}
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
result.textContent = message;
|
| 816 |
-
result.hidden = !message;
|
| 817 |
if (state.providerId === providerId) {
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
modalResult.textContent = message;
|
| 821 |
-
modalResult.hidden = !message;
|
| 822 |
}
|
| 823 |
}
|
| 824 |
|
|
@@ -1544,7 +1563,7 @@ async function showRestartNotice() {
|
|
| 1544 |
async function restoreSavedProvider(providerId, checks) {
|
| 1545 |
if (!connectedAccountDescriptor(providerId)) return;
|
| 1546 |
await openProviderDialog(providerId);
|
| 1547 |
-
showCredentialErrors(checks);
|
| 1548 |
byId("providerMessage").textContent = "Saved. Some keys could not be verified.";
|
| 1549 |
byId("providerMessage").className = "message-area warn";
|
| 1550 |
}
|
|
@@ -1598,7 +1617,7 @@ async function apply(providerId = null, customAction = null) {
|
|
| 1598 |
applied = true;
|
| 1599 |
const warningChecks = checks.filter((check) => check.status === "unverified");
|
| 1600 |
const warnings = warningChecks.map((check) =>
|
| 1601 |
-
`${state.fields.get(check.key)?.label || "API keys"}, Key ${check.index + 1}: ${check.message}`
|
| 1602 |
);
|
| 1603 |
const savedProviderId = warnings.length && providerId && mutation?.action !== "delete" ? result.custom_provider_id || providerId : null;
|
| 1604 |
if (providerId && !savedProviderId) byId("providerDialog").close();
|
|
@@ -1653,8 +1672,14 @@ async function refreshLocalStatus(config) {
|
|
| 1653 |
const provider = await api(`/admin/api/providers/${providerId}/local-status`);
|
| 1654 |
if (state.localStatusRequest !== request || !request.providerIds.has(providerId)) return;
|
| 1655 |
if (provider.status === "missing_url") return;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1656 |
if (provider.status === "reachable") {
|
| 1657 |
-
updateProviderCheckResult(providerId, "ok", `Reachable: ${provider.base_url}`, "availability");
|
| 1658 |
return;
|
| 1659 |
}
|
| 1660 |
const detail = provider.message
|
|
@@ -1662,7 +1687,7 @@ async function refreshLocalStatus(config) {
|
|
| 1662 |
: provider.status_code
|
| 1663 |
? `${provider.base_url} returned HTTP ${provider.status_code}`
|
| 1664 |
: "The local provider did not respond.";
|
| 1665 |
-
updateProviderCheckResult(providerId, "error", `Unavailable: ${detail}`, "availability");
|
| 1666 |
} catch {
|
| 1667 |
if (state.localStatusRequest !== request || !request.providerIds.has(providerId)) return;
|
| 1668 |
updateProviderCheckResult(providerId, "error", "Availability check failed. Use Test to retry.", "availability");
|
|
@@ -1693,7 +1718,7 @@ async function testProvider(providerId, button) {
|
|
| 1693 |
"ok",
|
| 1694 |
modelCountMessage(result.models.length),
|
| 1695 |
);
|
| 1696 |
-
|
| 1697 |
} else {
|
| 1698 |
updateProviderCheckResult(
|
| 1699 |
providerId,
|
|
@@ -1733,7 +1758,7 @@ async function loadModelOptions(refresh = false) {
|
|
| 1733 |
method: refresh ? "POST" : "GET",
|
| 1734 |
});
|
| 1735 |
if (request === state.modelOptionsRequest && config === state.config) { state.modelLabels = new Map(Object.entries(result.model_labels || {})); setModelOptions(result.models); }
|
| 1736 |
-
if (refresh && window.CodeSessions)
|
| 1737 |
return result;
|
| 1738 |
}
|
| 1739 |
|
|
@@ -2077,6 +2102,112 @@ claudeIntegrationDialog.addEventListener("click", (event) => {
|
|
| 2077 |
}
|
| 2078 |
});
|
| 2079 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2080 |
const vscodeChatIntegrationDialog = byId("vscodeChatIntegrationDialog");
|
| 2081 |
const vscodeChatIntegration = { connected: null, busy: false, paths: null, update: null };
|
| 2082 |
const vscodeChatIntegrationPath = "/admin/api/integrations/vscode-chat";
|
|
|
|
| 19 |
startupRequest: null,
|
| 20 |
startupTimer: null,
|
| 21 |
startupAgain: false,
|
| 22 |
+
configRequest: 0,
|
| 23 |
modelOptionsRequest: 0,
|
| 24 |
activeView: viewFromLocation(),
|
| 25 |
};
|
|
|
|
| 142 |
renderProviderCheckResult(provider.provider_id);
|
| 143 |
});
|
| 144 |
renderClaudeIntegration();
|
| 145 |
+
renderAntigravityIntegration();
|
| 146 |
renderVSCodeChatIntegration();
|
| 147 |
renderJetBrainsIntegration();
|
| 148 |
renderCodexIntegration();
|
|
|
|
| 178 |
const changed = !previous || previous.instance_id !== result.instance_id ||
|
| 179 |
JSON.stringify(previous.startup) !== JSON.stringify(current);
|
| 180 |
if (changed) void hydrateModelOptions();
|
| 181 |
+
if (changed) void window.CodeSessions?.refresh(result);
|
| 182 |
+
pending = current.catalog === "starting" || current.catalog_file === "starting" ||
|
| 183 |
current.code?.state === "starting" || current.messaging?.state === "starting" ||
|
| 184 |
Object.values(current.integrations || {}).some((update) => update.state === "starting") ||
|
| 185 |
Object.values(current.providers || {}).includes("starting");
|
|
|
|
| 210 |
});
|
| 211 |
|
| 212 |
async function load({ providersOnly = false } = {}) {
|
| 213 |
+
const request = ++state.configRequest;
|
| 214 |
state.localStatusRequest = null;
|
| 215 |
state.startupRequest?.controller.abort();
|
| 216 |
state.startupRequest = null;
|
| 217 |
showMessage("Loading admin config");
|
| 218 |
const config = await api("/admin/api/config");
|
| 219 |
+
if (request !== state.configRequest) return;
|
| 220 |
config.custom_providers ||= [];
|
| 221 |
config.provider_status.push(...config.custom_providers.map((provider) => ({ ...provider, kind: "custom", status: "configured", settings_keys: [], missing_configuration_keys: [] })));
|
| 222 |
state.config = config;
|
|
|
|
| 232 |
byId("configPath").textContent = config.paths.managed;
|
| 233 |
void refreshLocalStatus(config);
|
| 234 |
void refreshStartup();
|
| 235 |
+
void refreshConnectedAccounts();
|
| 236 |
+
void hydrateModelOptions();
|
| 237 |
+
if (providersOnly) void window.CodeSessions.refresh();
|
| 238 |
+
else window.CodeSessions.initialize(api);
|
|
|
|
| 239 |
if (state.config !== config) return;
|
| 240 |
updateDirtyState();
|
| 241 |
showMessage("");
|
|
|
|
| 267 |
state.activeView = activeView.id;
|
| 268 |
byId("pageTitle").textContent = activeView.title;
|
| 269 |
renderStartup();
|
| 270 |
+
if (activeView.id === "code") void window.CodeSessions.refresh();
|
| 271 |
void refreshStartup();
|
| 272 |
const sessionActive = activeView.id === "code";
|
| 273 |
document.querySelector(".app-shell").classList.toggle("session-active", sessionActive);
|
|
|
|
| 297 |
if (activeView.id === "code") window.CodeSessions.activate(window.location.pathname);
|
| 298 |
else window.CodeSessions.deactivate();
|
| 299 |
if (activeView.id === "integrations") {
|
| 300 |
+
refreshAntigravityIntegration();
|
| 301 |
refreshClaudeIntegration();
|
| 302 |
refreshClaudeOnboarding();
|
| 303 |
refreshVSCodeChatIntegration();
|
|
|
|
| 410 |
result.className = "provider-check-result";
|
| 411 |
result.dataset.providerCheckResult = provider.provider_id;
|
| 412 |
result.hidden = true;
|
| 413 |
+
const availability = document.createElement("span");
|
| 414 |
+
availability.className = "provider-availability-result";
|
| 415 |
+
availability.dataset.providerAvailabilityResult = provider.provider_id;
|
| 416 |
+
availability.hidden = true;
|
| 417 |
const actions = document.createElement("div");
|
| 418 |
actions.className = "provider-actions";
|
| 419 |
if (oauth) populateConnectedAccountActions(provider, status, actions);
|
|
|
|
| 425 |
settings.setAttribute("aria-controls", "providerDialog");
|
| 426 |
actions.appendChild(settings);
|
| 427 |
}
|
| 428 |
+
card.replaceChildren(title, meta, result, availability, actions);
|
| 429 |
const next = [...grid.children].find((other) => other !== card &&
|
| 430 |
connectedAccountName(provider).localeCompare(providerDisplayName(other.dataset.provider), "en", { sensitivity: "base" }) < 0);
|
| 431 |
if (card.parentElement !== grid || card.nextElementSibling !== (next || null)) grid.insertBefore(card, next || null);
|
|
|
|
| 496 |
byId("providerDialogTitle").textContent = providerId ? provider.display_name : "Add provider";
|
| 497 |
byId("providerMessage").textContent = "";
|
| 498 |
byId("providerDialogCheck").hidden = true;
|
| 499 |
+
renderProviderCheckMessage(byId("providerDialogAvailability"), null);
|
| 500 |
const fields = byId("providerFields");
|
| 501 |
fields.replaceChildren();
|
| 502 |
const formats = (state.config.custom_reasoning_formats || {})[provider.api_format] || ["provider_default"];
|
|
|
|
| 561 |
actions.appendChild(button);
|
| 562 |
}
|
| 563 |
const check = oauth ? null : providerCheckResult(provider.provider_id);
|
| 564 |
+
renderProviderCheckMessage(byId("providerDialogCheck"), check);
|
| 565 |
+
renderProviderCheckMessage(byId("providerDialogAvailability"), check?.availability);
|
|
|
|
|
|
|
| 566 |
byId("saveProvider").hidden = !provider.settings_keys?.length;
|
| 567 |
renderStartup();
|
| 568 |
}
|
|
|
|
| 785 |
// An explicit check takes precedence over background discovery and reachability.
|
| 786 |
if (check?.source === "manual") return check;
|
| 787 |
const discovery = state.startup?.startup?.providers?.[providerId];
|
| 788 |
+
let result;
|
| 789 |
+
if (discovery === "starting") {
|
| 790 |
+
result = { status: "checking", message: "Checking models…" };
|
| 791 |
+
} else if (discovery === "failed") {
|
| 792 |
+
result = { status: "error", message: state.startup.startup.provider_errors?.[providerId] || "Could not load models. Check the provider's settings and retry." };
|
| 793 |
+
} else if (discovery === "ready") {
|
| 794 |
+
result = { status: "ok", message: modelCountMessage(state.startup.cached_models[providerId]?.length || 0) };
|
| 795 |
+
} else if (discovery === "unavailable") {
|
| 796 |
+
return {
|
| 797 |
+
status: "",
|
| 798 |
+
message: "Local server unavailable",
|
| 799 |
+
availability: check ? { ...check, status: "" } : undefined,
|
| 800 |
+
};
|
| 801 |
}
|
| 802 |
+
// Model discovery and endpoint reachability are separate observations.
|
| 803 |
+
return result ? { ...result, availability: check } : check;
|
| 804 |
}
|
| 805 |
|
| 806 |
function updateProviderCheckResult(providerId, status, message, source = "manual") {
|
|
|
|
| 808 |
renderProviderCheckResult(providerId);
|
| 809 |
}
|
| 810 |
|
| 811 |
+
function renderProviderCheckMessage(element, check) {
|
| 812 |
+
for (const status of ["ok", "error", "checking"]) {
|
| 813 |
+
element.classList.toggle(status, check?.status === status);
|
| 814 |
+
}
|
| 815 |
+
element.textContent = check?.message || "";
|
| 816 |
+
element.hidden = !check?.message;
|
| 817 |
+
}
|
| 818 |
+
|
| 819 |
function renderProviderCheckResult(providerId) {
|
| 820 |
+
const check = providerCheckResult(providerId);
|
| 821 |
+
const { status = "" } = check || {};
|
| 822 |
const card = document.querySelector(`[data-provider="${providerId}"]`);
|
| 823 |
if (!card) return;
|
| 824 |
const provider = connectedAccountDescriptor(providerId);
|
|
|
|
| 833 |
if (account?.state === "error") meta.classList.add("error");
|
| 834 |
return;
|
| 835 |
}
|
| 836 |
+
renderProviderCheckMessage(card.querySelector(".provider-check-result"), check);
|
| 837 |
+
renderProviderCheckMessage(card.querySelector(".provider-availability-result"), check?.availability);
|
|
|
|
|
|
|
| 838 |
if (state.providerId === providerId) {
|
| 839 |
+
renderProviderCheckMessage(byId("providerDialogCheck"), check);
|
| 840 |
+
renderProviderCheckMessage(byId("providerDialogAvailability"), check?.availability);
|
|
|
|
|
|
|
| 841 |
}
|
| 842 |
}
|
| 843 |
|
|
|
|
| 1563 |
async function restoreSavedProvider(providerId, checks) {
|
| 1564 |
if (!connectedAccountDescriptor(providerId)) return;
|
| 1565 |
await openProviderDialog(providerId);
|
| 1566 |
+
showCredentialErrors(checks.map((check) => ({ ...check, message: `Key saved. ${check.message}` })));
|
| 1567 |
byId("providerMessage").textContent = "Saved. Some keys could not be verified.";
|
| 1568 |
byId("providerMessage").className = "message-area warn";
|
| 1569 |
}
|
|
|
|
| 1617 |
applied = true;
|
| 1618 |
const warningChecks = checks.filter((check) => check.status === "unverified");
|
| 1619 |
const warnings = warningChecks.map((check) =>
|
| 1620 |
+
`${state.fields.get(check.key)?.label || "API keys"}, Key ${check.index + 1}: Key saved. ${check.message}`
|
| 1621 |
);
|
| 1622 |
const savedProviderId = warnings.length && providerId && mutation?.action !== "delete" ? result.custom_provider_id || providerId : null;
|
| 1623 |
if (providerId && !savedProviderId) byId("providerDialog").close();
|
|
|
|
| 1672 |
const provider = await api(`/admin/api/providers/${providerId}/local-status`);
|
| 1673 |
if (state.localStatusRequest !== request || !request.providerIds.has(providerId)) return;
|
| 1674 |
if (provider.status === "missing_url") return;
|
| 1675 |
+
const diagnostics = [];
|
| 1676 |
+
if (provider.probe_path) diagnostics.push(`GET ${provider.probe_path}`);
|
| 1677 |
+
if (typeof provider.latency_ms === "number" && Number.isFinite(provider.latency_ms)) {
|
| 1678 |
+
diagnostics.push(`${provider.latency_ms} ms`);
|
| 1679 |
+
}
|
| 1680 |
+
const suffix = diagnostics.length ? ` (${diagnostics.join(", ")})` : "";
|
| 1681 |
if (provider.status === "reachable") {
|
| 1682 |
+
updateProviderCheckResult(providerId, "ok", `Reachable: ${provider.base_url}${suffix}`, "availability");
|
| 1683 |
return;
|
| 1684 |
}
|
| 1685 |
const detail = provider.message
|
|
|
|
| 1687 |
: provider.status_code
|
| 1688 |
? `${provider.base_url} returned HTTP ${provider.status_code}`
|
| 1689 |
: "The local provider did not respond.";
|
| 1690 |
+
updateProviderCheckResult(providerId, "error", `Unavailable: ${detail}${suffix}`, "availability");
|
| 1691 |
} catch {
|
| 1692 |
if (state.localStatusRequest !== request || !request.providerIds.has(providerId)) return;
|
| 1693 |
updateProviderCheckResult(providerId, "error", "Availability check failed. Use Test to retry.", "availability");
|
|
|
|
| 1718 |
"ok",
|
| 1719 |
modelCountMessage(result.models.length),
|
| 1720 |
);
|
| 1721 |
+
void hydrateModelOptions();
|
| 1722 |
} else {
|
| 1723 |
updateProviderCheckResult(
|
| 1724 |
providerId,
|
|
|
|
| 1758 |
method: refresh ? "POST" : "GET",
|
| 1759 |
});
|
| 1760 |
if (request === state.modelOptionsRequest && config === state.config) { state.modelLabels = new Map(Object.entries(result.model_labels || {})); setModelOptions(result.models); }
|
| 1761 |
+
if (refresh && window.CodeSessions) void window.CodeSessions.refresh();
|
| 1762 |
return result;
|
| 1763 |
}
|
| 1764 |
|
|
|
|
| 2102 |
}
|
| 2103 |
});
|
| 2104 |
|
| 2105 |
+
const antigravityIntegrationDialog = byId("antigravityIntegrationDialog");
|
| 2106 |
+
const antigravityIntegration = { connected: null, canDisconnect: false, disconnecting: false, busy: false, paths: null };
|
| 2107 |
+
const antigravityIntegrationPath = "/admin/api/integrations/antigravity";
|
| 2108 |
+
|
| 2109 |
+
function renderAntigravityIntegration() {
|
| 2110 |
+
const { connected, canDisconnect, disconnecting, busy, paths } = antigravityIntegration;
|
| 2111 |
+
const action = connected ? "Disconnect" : "Connect";
|
| 2112 |
+
byId("openAntigravityIntegration").textContent = busy ? "Loading…" : connected === null ? "Retry" : action;
|
| 2113 |
+
byId("openAntigravityIntegration").disabled = busy;
|
| 2114 |
+
byId("openAntigravityIntegration").setAttribute("aria-busy", String(busy));
|
| 2115 |
+
byId("openAntigravityIntegration").className = connected && !busy ? "danger-button" : "primary-button";
|
| 2116 |
+
byId("disconnectAntigravityIntegration").hidden = connected !== false || !canDisconnect;
|
| 2117 |
+
byId("disconnectAntigravityIntegration").disabled = busy;
|
| 2118 |
+
byId("confirmAntigravityIntegration").textContent = busy ? "Saving…" : disconnecting ? "Disconnect" : "Connect";
|
| 2119 |
+
byId("confirmAntigravityIntegration").disabled = busy || connected === null;
|
| 2120 |
+
byId("confirmAntigravityIntegration").className = disconnecting ? "danger-button" : "primary-button";
|
| 2121 |
+
byId("antigravityIntegrationDescription").textContent = disconnecting
|
| 2122 |
+
? connected
|
| 2123 |
+
? "Restore Antigravity CLI's previous provider and remove FCC's models. Running sessions can continue. Connect again before your next fcc-agy launch."
|
| 2124 |
+
: "Remove FCC's saved connection and models. Keep your current Antigravity CLI provider."
|
| 2125 |
+
: "Switch Antigravity CLI to the Gemini API provider and add FCC's models. Then launch with fcc-agy.";
|
| 2126 |
+
const files = byId("antigravityIntegrationFiles");
|
| 2127 |
+
files.replaceChildren();
|
| 2128 |
+
for (const path of Object.values(paths || {})) {
|
| 2129 |
+
const item = document.createElement("li");
|
| 2130 |
+
const code = document.createElement("code");
|
| 2131 |
+
code.textContent = path;
|
| 2132 |
+
item.appendChild(code);
|
| 2133 |
+
files.appendChild(item);
|
| 2134 |
+
}
|
| 2135 |
+
}
|
| 2136 |
+
|
| 2137 |
+
async function refreshAntigravityIntegration() {
|
| 2138 |
+
const request = beginIntegrationCheck(antigravityIntegration);
|
| 2139 |
+
if (!request) return;
|
| 2140 |
+
integrationMessage("antigravityIntegrationMessage", "");
|
| 2141 |
+
renderAntigravityIntegration();
|
| 2142 |
+
try {
|
| 2143 |
+
const result = await api(antigravityIntegrationPath);
|
| 2144 |
+
if (!currentIntegrationCheck(antigravityIntegration, request)) return;
|
| 2145 |
+
antigravityIntegration.connected = result.connected;
|
| 2146 |
+
antigravityIntegration.canDisconnect = result.can_disconnect;
|
| 2147 |
+
antigravityIntegration.paths = result.paths;
|
| 2148 |
+
} catch (error) {
|
| 2149 |
+
if (!currentIntegrationCheck(antigravityIntegration, request)) return;
|
| 2150 |
+
antigravityIntegration.connected = null;
|
| 2151 |
+
integrationMessage("antigravityIntegrationMessage", error.message, true);
|
| 2152 |
+
} finally {
|
| 2153 |
+
finishIntegrationCheck(antigravityIntegration, request, renderAntigravityIntegration);
|
| 2154 |
+
}
|
| 2155 |
+
}
|
| 2156 |
+
|
| 2157 |
+
function openAntigravityIntegration(disconnect) {
|
| 2158 |
+
antigravityIntegration.disconnecting = disconnect;
|
| 2159 |
+
renderAntigravityIntegration();
|
| 2160 |
+
integrationMessage("antigravityIntegrationDialogMessage", "");
|
| 2161 |
+
antigravityIntegrationDialog.showModal();
|
| 2162 |
+
}
|
| 2163 |
+
|
| 2164 |
+
byId("openAntigravityIntegration").addEventListener("click", () => {
|
| 2165 |
+
if (antigravityIntegration.connected === null) {
|
| 2166 |
+
void refreshAntigravityIntegration();
|
| 2167 |
+
return;
|
| 2168 |
+
}
|
| 2169 |
+
openAntigravityIntegration(antigravityIntegration.connected);
|
| 2170 |
+
});
|
| 2171 |
+
byId("disconnectAntigravityIntegration").addEventListener("click", () => openAntigravityIntegration(true));
|
| 2172 |
+
byId("confirmAntigravityIntegration").addEventListener("click", async () => {
|
| 2173 |
+
if (byId("confirmAntigravityIntegration").disabled) return;
|
| 2174 |
+
const disconnect = antigravityIntegration.disconnecting;
|
| 2175 |
+
const config = state.config;
|
| 2176 |
+
let failed = false;
|
| 2177 |
+
antigravityIntegration.busy = true;
|
| 2178 |
+
renderAntigravityIntegration();
|
| 2179 |
+
integrationMessage("antigravityIntegrationDialogMessage", "");
|
| 2180 |
+
integrationMessage("antigravityIntegrationMessage", "");
|
| 2181 |
+
try {
|
| 2182 |
+
const result = await api(`${antigravityIntegrationPath}/${disconnect ? "disconnect" : "connect"}`, { method: "POST" });
|
| 2183 |
+
if (config !== state.config) return;
|
| 2184 |
+
antigravityIntegration.connected = result.connected;
|
| 2185 |
+
antigravityIntegration.canDisconnect = result.can_disconnect;
|
| 2186 |
+
antigravityIntegration.paths = result.paths;
|
| 2187 |
+
antigravityIntegrationDialog.close();
|
| 2188 |
+
integrationMessage("antigravityIntegrationMessage", disconnect
|
| 2189 |
+
? "Disconnected. FCC's connection removed."
|
| 2190 |
+
: "Connected. Launch Antigravity CLI with fcc-agy.");
|
| 2191 |
+
} catch (error) {
|
| 2192 |
+
if (config !== state.config) return;
|
| 2193 |
+
failed = true;
|
| 2194 |
+
integrationMessage("antigravityIntegrationDialogMessage", error.message, true);
|
| 2195 |
+
integrationMessage("antigravityIntegrationMessage", error.message, true);
|
| 2196 |
+
} finally {
|
| 2197 |
+
antigravityIntegration.busy = false;
|
| 2198 |
+
renderAntigravityIntegration();
|
| 2199 |
+
if (failed || config !== state.config) void refreshAntigravityIntegration();
|
| 2200 |
+
}
|
| 2201 |
+
});
|
| 2202 |
+
byId("closeAntigravityIntegration").addEventListener("click", () => antigravityIntegrationDialog.close());
|
| 2203 |
+
antigravityIntegrationDialog.addEventListener("click", (event) => {
|
| 2204 |
+
if (event.target !== antigravityIntegrationDialog) return;
|
| 2205 |
+
const bounds = antigravityIntegrationDialog.getBoundingClientRect();
|
| 2206 |
+
if (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom) {
|
| 2207 |
+
antigravityIntegrationDialog.close();
|
| 2208 |
+
}
|
| 2209 |
+
});
|
| 2210 |
+
|
| 2211 |
const vscodeChatIntegrationDialog = byId("vscodeChatIntegrationDialog");
|
| 2212 |
const vscodeChatIntegration = { connected: null, busy: false, paths: null, update: null };
|
| 2213 |
const vscodeChatIntegrationPath = "/admin/api/integrations/vscode-chat";
|
src/free_claude_code/api/admin_static/code_sessions.js
CHANGED
|
@@ -14,9 +14,15 @@
|
|
| 14 |
catalogLoaded = false,
|
| 15 |
catalogPhase = "starting",
|
| 16 |
catalogVersion = null,
|
|
|
|
|
|
|
| 17 |
catalogInstance = null,
|
| 18 |
catalogRequest = 0,
|
| 19 |
settingsPending = false;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
let visibleIds = [],
|
| 21 |
query = "",
|
| 22 |
libraryToken = 0,
|
|
@@ -364,32 +370,60 @@
|
|
| 364 |
record.nextBefore = data.next_before;
|
| 365 |
render(!before && outputChanged);
|
| 366 |
}
|
| 367 |
-
function olderCatalog(candidate) {
|
| 368 |
-
return candidate &&
|
| 369 |
-
(candidate.generation_id ===
|
| 370 |
}
|
| 371 |
-
async function
|
| 372 |
const token = syncToken;
|
| 373 |
const request = ++catalogRequest;
|
|
|
|
|
|
|
| 374 |
try {
|
| 375 |
-
const data = await api(`${base}/bootstrap`);
|
| 376 |
-
if (request !== catalogRequest || token !== syncToken || (epoch && data.epoch !== epoch) || olderCatalog(data.startup)) return false;
|
| 377 |
if (data.startup) catalogVersion = data.startup;
|
| 378 |
available = data.available;
|
| 379 |
catalogPhase = data.startup?.catalog || "ready";
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
if (catalogPhase === "ready") catalogLoaded = true;
|
| 385 |
availabilityNotice = data.message || "";
|
| 386 |
return true;
|
| 387 |
} catch (error) {
|
| 388 |
-
if (request === catalogRequest && token === syncToken) {
|
| 389 |
availabilityNotice = error.message;
|
| 390 |
if (!catalogLoaded) catalogPhase = "failed";
|
| 391 |
}
|
| 392 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 393 |
}
|
| 394 |
}
|
| 395 |
|
|
@@ -402,6 +436,7 @@
|
|
| 402 |
if (epoch !== readyData.epoch) {
|
| 403 |
if (epoch) {
|
| 404 |
catalogVersion = null;
|
|
|
|
| 405 |
catalogLoaded = false;
|
| 406 |
catalogPhase = "starting";
|
| 407 |
}
|
|
@@ -429,7 +464,7 @@
|
|
| 429 |
for (const summary of readyData.sessions)
|
| 430 |
merge({ ...summary, cursor: readyData.cursor });
|
| 431 |
render();
|
| 432 |
-
void bootstrap()
|
| 433 |
try {
|
| 434 |
const results = await Promise.allSettled([
|
| 435 |
list(),
|
|
@@ -479,17 +514,12 @@
|
|
| 479 |
source.addEventListener(type, (event) => {
|
| 480 |
if (feed === source) receive(type, event);
|
| 481 |
});
|
| 482 |
-
const disconnected =
|
| 483 |
if (feed !== source) return;
|
| 484 |
restart();
|
| 485 |
// A stopped store cannot open its event feed. Read its availability
|
| 486 |
// so that the retry screen can explain why it is unavailable.
|
| 487 |
-
|
| 488 |
-
await bootstrap();
|
| 489 |
-
render();
|
| 490 |
-
} catch {
|
| 491 |
-
/* The scheduled connection retries the reads. */
|
| 492 |
-
}
|
| 493 |
};
|
| 494 |
source.addEventListener("feed.resync_required", disconnected);
|
| 495 |
source.onerror = disconnected;
|
|
@@ -591,11 +621,7 @@
|
|
| 591 |
if (selected === id) notice = error.message;
|
| 592 |
}
|
| 593 |
if (error.status === 400 || error.status === 409) {
|
| 594 |
-
|
| 595 |
-
await bootstrap();
|
| 596 |
-
} catch (failure) {
|
| 597 |
-
restart(failure.message);
|
| 598 |
-
}
|
| 599 |
}
|
| 600 |
} finally {
|
| 601 |
sends.delete(id);
|
|
@@ -837,7 +863,9 @@
|
|
| 837 |
if (providerDraft) return "Choose a model for the selected provider.";
|
| 838 |
if (!catalogLoaded) return catalogPhase === "starting" ? "Models are loading…" : "Model list unavailable.";
|
| 839 |
const model = catalog.find((model) => model.id === record.session.model);
|
| 840 |
-
if (!model) return
|
|
|
|
|
|
|
| 841 |
if (
|
| 842 |
record.session.reasoning_effort &&
|
| 843 |
!model.reasoning_efforts.includes(record.session.reasoning_effort)
|
|
@@ -846,6 +874,12 @@
|
|
| 846 |
return "";
|
| 847 |
}
|
| 848 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 849 |
function remove() {
|
| 850 |
const record = records.get(selected),
|
| 851 |
id = selected,
|
|
@@ -1241,8 +1275,8 @@
|
|
| 1241 |
stop.hidden = !isBusy;
|
| 1242 |
stop.disabled = !connected || record?.run?.stop_requested;
|
| 1243 |
send.textContent = saved(selected).pending ? "Retry Send" : "Send";
|
| 1244 |
-
send.classList.toggle("startup-busy",
|
| 1245 |
-
send.setAttribute("aria-busy", String(
|
| 1246 |
send.disabled =
|
| 1247 |
!ready(record) ||
|
| 1248 |
!available ||
|
|
@@ -1268,12 +1302,12 @@
|
|
| 1268 |
record.session?.status === "deleting" ||
|
| 1269 |
isBusy ||
|
| 1270 |
pending(record);
|
| 1271 |
-
const
|
| 1272 |
!ready(record) ||
|
| 1273 |
isBusy ||
|
| 1274 |
pending(record) ||
|
| 1275 |
-
settingsPending
|
| 1276 |
-
|
| 1277 |
const provider =
|
| 1278 |
providerDraft?.provider || record?.session?.provider_id || "";
|
| 1279 |
if (modelControl.group.dataset.provider !== provider) {
|
|
@@ -1298,7 +1332,7 @@
|
|
| 1298 |
);
|
| 1299 |
harnessControl.select.disabled = true;
|
| 1300 |
modeControl.select.value = record?.session?.mode || "config";
|
| 1301 |
-
modeControl.select.disabled =
|
| 1302 |
const model = catalog.find((model) => model.id === record?.session?.model),
|
| 1303 |
effort =
|
| 1304 |
record?.session?.reasoning_effort ||
|
|
@@ -1661,6 +1695,18 @@
|
|
| 1661 |
dismissDialog();
|
| 1662 |
}
|
| 1663 |
window.addEventListener("pagehide", deactivate);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1664 |
window.CodeSessions = {
|
| 1665 |
setProviderNames(providers) {
|
| 1666 |
providerNames = new Map(providers.map((provider) => [provider.provider_id, provider.display_name]));
|
|
@@ -1675,18 +1721,15 @@
|
|
| 1675 |
async refresh(status) {
|
| 1676 |
if (!api) return false;
|
| 1677 |
if (status?.startup) {
|
| 1678 |
-
if (catalogInstance !== status.instance_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1679 |
catalogInstance = status.instance_id;
|
| 1680 |
-
if (!olderCatalog(status.startup))
|
| 1681 |
-
}
|
| 1682 |
-
try {
|
| 1683 |
-
const refreshed = await bootstrap();
|
| 1684 |
-
render();
|
| 1685 |
-
return refreshed;
|
| 1686 |
-
} catch {
|
| 1687 |
-
render();
|
| 1688 |
-
return false;
|
| 1689 |
}
|
|
|
|
| 1690 |
},
|
| 1691 |
};
|
| 1692 |
document.addEventListener("pointerdown", (event) => {
|
|
|
|
| 14 |
catalogLoaded = false,
|
| 15 |
catalogPhase = "starting",
|
| 16 |
catalogVersion = null,
|
| 17 |
+
catalogTarget = null,
|
| 18 |
+
catalogProviders = {},
|
| 19 |
catalogInstance = null,
|
| 20 |
catalogRequest = 0,
|
| 21 |
settingsPending = false;
|
| 22 |
+
let catalogFlight = null,
|
| 23 |
+
catalogAgain = false,
|
| 24 |
+
catalogRetryTimer = null,
|
| 25 |
+
catalogController = null;
|
| 26 |
let visibleIds = [],
|
| 27 |
query = "",
|
| 28 |
libraryToken = 0,
|
|
|
|
| 370 |
record.nextBefore = data.next_before;
|
| 371 |
render(!before && outputChanged);
|
| 372 |
}
|
| 373 |
+
function olderCatalog(candidate, version = catalogTarget) {
|
| 374 |
+
return candidate && version && (candidate.generation_id < version.generation_id ||
|
| 375 |
+
(candidate.generation_id === version.generation_id && candidate.catalog_revision < version.catalog_revision));
|
| 376 |
}
|
| 377 |
+
async function readBootstrap() {
|
| 378 |
const token = syncToken;
|
| 379 |
const request = ++catalogRequest;
|
| 380 |
+
const controller = new AbortController();
|
| 381 |
+
catalogController = controller;
|
| 382 |
try {
|
| 383 |
+
const data = await api(`${base}/bootstrap`, { signal: controller.signal });
|
| 384 |
+
if (request !== catalogRequest || token !== syncToken || (epoch && data.epoch !== epoch) || olderCatalog(data.startup) || olderCatalog(data.startup, catalogVersion)) return false;
|
| 385 |
if (data.startup) catalogVersion = data.startup;
|
| 386 |
available = data.available;
|
| 387 |
catalogPhase = data.startup?.catalog || "ready";
|
| 388 |
+
catalogProviders = data.startup?.providers || {};
|
| 389 |
+
catalog = data.models;
|
| 390 |
+
harnesses = data.harnesses;
|
| 391 |
+
catalogLoaded = true;
|
|
|
|
| 392 |
availabilityNotice = data.message || "";
|
| 393 |
return true;
|
| 394 |
} catch (error) {
|
| 395 |
+
if (error.name !== "AbortError" && request === catalogRequest && token === syncToken) {
|
| 396 |
availabilityNotice = error.message;
|
| 397 |
if (!catalogLoaded) catalogPhase = "failed";
|
| 398 |
}
|
| 399 |
+
return false;
|
| 400 |
+
} finally {
|
| 401 |
+
if (catalogController === controller) catalogController = null;
|
| 402 |
+
}
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
async function bootstrap() {
|
| 406 |
+
if (!api || document.hidden) return false;
|
| 407 |
+
catalogAgain = true;
|
| 408 |
+
clearTimeout(catalogRetryTimer);
|
| 409 |
+
catalogRetryTimer = null;
|
| 410 |
+
if (catalogFlight) return catalogFlight;
|
| 411 |
+
catalogFlight = (async () => {
|
| 412 |
+
while (catalogAgain && !document.hidden) {
|
| 413 |
+
catalogAgain = false;
|
| 414 |
+
const refreshed = await readBootstrap();
|
| 415 |
+
render();
|
| 416 |
+
if (!refreshed && !catalogAgain) {
|
| 417 |
+
if (!document.hidden) catalogRetryTimer = setTimeout(() => void bootstrap(), 500);
|
| 418 |
+
return false;
|
| 419 |
+
}
|
| 420 |
+
}
|
| 421 |
+
return true;
|
| 422 |
+
})();
|
| 423 |
+
try {
|
| 424 |
+
return await catalogFlight;
|
| 425 |
+
} finally {
|
| 426 |
+
catalogFlight = null;
|
| 427 |
}
|
| 428 |
}
|
| 429 |
|
|
|
|
| 436 |
if (epoch !== readyData.epoch) {
|
| 437 |
if (epoch) {
|
| 438 |
catalogVersion = null;
|
| 439 |
+
catalogTarget = null;
|
| 440 |
catalogLoaded = false;
|
| 441 |
catalogPhase = "starting";
|
| 442 |
}
|
|
|
|
| 464 |
for (const summary of readyData.sessions)
|
| 465 |
merge({ ...summary, cursor: readyData.cursor });
|
| 466 |
render();
|
| 467 |
+
void bootstrap();
|
| 468 |
try {
|
| 469 |
const results = await Promise.allSettled([
|
| 470 |
list(),
|
|
|
|
| 514 |
source.addEventListener(type, (event) => {
|
| 515 |
if (feed === source) receive(type, event);
|
| 516 |
});
|
| 517 |
+
const disconnected = () => {
|
| 518 |
if (feed !== source) return;
|
| 519 |
restart();
|
| 520 |
// A stopped store cannot open its event feed. Read its availability
|
| 521 |
// so that the retry screen can explain why it is unavailable.
|
| 522 |
+
void bootstrap();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 523 |
};
|
| 524 |
source.addEventListener("feed.resync_required", disconnected);
|
| 525 |
source.onerror = disconnected;
|
|
|
|
| 621 |
if (selected === id) notice = error.message;
|
| 622 |
}
|
| 623 |
if (error.status === 400 || error.status === 409) {
|
| 624 |
+
await bootstrap();
|
|
|
|
|
|
|
|
|
|
|
|
|
| 625 |
}
|
| 626 |
} finally {
|
| 627 |
sends.delete(id);
|
|
|
|
| 863 |
if (providerDraft) return "Choose a model for the selected provider.";
|
| 864 |
if (!catalogLoaded) return catalogPhase === "starting" ? "Models are loading…" : "Model list unavailable.";
|
| 865 |
const model = catalog.find((model) => model.id === record.session.model);
|
| 866 |
+
if (!model) return catalogProviders[record.session.provider_id] === "starting"
|
| 867 |
+
? "Models for the selected provider are loading…"
|
| 868 |
+
: "Selected model is unavailable. Choose another model.";
|
| 869 |
if (
|
| 870 |
record.session.reasoning_effort &&
|
| 871 |
!model.reasoning_efforts.includes(record.session.reasoning_effort)
|
|
|
|
| 874 |
return "";
|
| 875 |
}
|
| 876 |
|
| 877 |
+
function selectionLoading(record) {
|
| 878 |
+
if (!catalogLoaded) return catalogPhase === "starting";
|
| 879 |
+
return !!record?.session && !catalog.some((model) => model.id === record.session.model) &&
|
| 880 |
+
catalogProviders[record.session.provider_id] === "starting";
|
| 881 |
+
}
|
| 882 |
+
|
| 883 |
function remove() {
|
| 884 |
const record = records.get(selected),
|
| 885 |
id = selected,
|
|
|
|
| 1275 |
stop.hidden = !isBusy;
|
| 1276 |
stop.disabled = !connected || record?.run?.stop_requested;
|
| 1277 |
send.textContent = saved(selected).pending ? "Retry Send" : "Send";
|
| 1278 |
+
send.classList.toggle("startup-busy", selectionLoading(record));
|
| 1279 |
+
send.setAttribute("aria-busy", String(selectionLoading(record)));
|
| 1280 |
send.disabled =
|
| 1281 |
!ready(record) ||
|
| 1282 |
!available ||
|
|
|
|
| 1302 |
record.session?.status === "deleting" ||
|
| 1303 |
isBusy ||
|
| 1304 |
pending(record);
|
| 1305 |
+
const sessionDisabled =
|
| 1306 |
!ready(record) ||
|
| 1307 |
isBusy ||
|
| 1308 |
pending(record) ||
|
| 1309 |
+
settingsPending;
|
| 1310 |
+
const disabled = sessionDisabled || !catalogLoaded || !catalog.length;
|
| 1311 |
const provider =
|
| 1312 |
providerDraft?.provider || record?.session?.provider_id || "";
|
| 1313 |
if (modelControl.group.dataset.provider !== provider) {
|
|
|
|
| 1332 |
);
|
| 1333 |
harnessControl.select.disabled = true;
|
| 1334 |
modeControl.select.value = record?.session?.mode || "config";
|
| 1335 |
+
modeControl.select.disabled = sessionDisabled;
|
| 1336 |
const model = catalog.find((model) => model.id === record?.session?.model),
|
| 1337 |
effort =
|
| 1338 |
record?.session?.reasoning_effort ||
|
|
|
|
| 1695 |
dismissDialog();
|
| 1696 |
}
|
| 1697 |
window.addEventListener("pagehide", deactivate);
|
| 1698 |
+
function pauseCatalog() {
|
| 1699 |
+
clearTimeout(catalogRetryTimer);
|
| 1700 |
+
catalogRetryTimer = null;
|
| 1701 |
+
catalogAgain = false;
|
| 1702 |
+
++catalogRequest;
|
| 1703 |
+
catalogController?.abort();
|
| 1704 |
+
}
|
| 1705 |
+
window.addEventListener("pagehide", pauseCatalog);
|
| 1706 |
+
document.addEventListener("visibilitychange", () => {
|
| 1707 |
+
if (document.hidden) pauseCatalog();
|
| 1708 |
+
else void bootstrap();
|
| 1709 |
+
});
|
| 1710 |
window.CodeSessions = {
|
| 1711 |
setProviderNames(providers) {
|
| 1712 |
providerNames = new Map(providers.map((provider) => [provider.provider_id, provider.display_name]));
|
|
|
|
| 1721 |
async refresh(status) {
|
| 1722 |
if (!api) return false;
|
| 1723 |
if (status?.startup) {
|
| 1724 |
+
if (catalogInstance !== status.instance_id) {
|
| 1725 |
+
catalogTarget = null;
|
| 1726 |
+
catalogVersion = null;
|
| 1727 |
+
++catalogRequest;
|
| 1728 |
+
}
|
| 1729 |
catalogInstance = status.instance_id;
|
| 1730 |
+
if (!olderCatalog(status.startup)) catalogTarget = status.startup;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1731 |
}
|
| 1732 |
+
return bootstrap();
|
| 1733 |
},
|
| 1734 |
};
|
| 1735 |
document.addEventListener("pointerdown", (event) => {
|
src/free_claude_code/api/admin_static/index.html
CHANGED
|
@@ -65,6 +65,32 @@
|
|
| 65 |
</section>
|
| 66 |
|
| 67 |
<section id="view-integrations" class="admin-view provider-grid" data-view="integrations" hidden>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
<article class="provider-strip integration-card">
|
| 69 |
<div class="section-heading">
|
| 70 |
<div>
|
|
@@ -259,6 +285,7 @@
|
|
| 259 |
<div id="providerDialogBody">
|
| 260 |
<div id="providerDialogActions" class="provider-actions"></div>
|
| 261 |
<div id="providerDialogCheck" class="provider-check-result" role="status" hidden></div>
|
|
|
|
| 262 |
<div id="providerFields" class="field-grid"></div>
|
| 263 |
</div>
|
| 264 |
<div id="providerMessage" class="message-area" role="status"></div>
|
|
|
|
| 65 |
</section>
|
| 66 |
|
| 67 |
<section id="view-integrations" class="admin-view provider-grid" data-view="integrations" hidden>
|
| 68 |
+
<article class="provider-strip integration-card">
|
| 69 |
+
<div class="section-heading">
|
| 70 |
+
<div>
|
| 71 |
+
<h3>Antigravity CLI</h3>
|
| 72 |
+
<p>Connect Antigravity CLI to use FCC's models with fcc-agy.</p>
|
| 73 |
+
</div>
|
| 74 |
+
</div>
|
| 75 |
+
<p id="antigravityIntegrationMessage" class="message-area" role="status" hidden></p>
|
| 76 |
+
<div class="integration-actions">
|
| 77 |
+
<button id="openAntigravityIntegration" class="primary-button" type="button" aria-busy="true" disabled>Loading…</button>
|
| 78 |
+
<button id="disconnectAntigravityIntegration" class="danger-button" type="button" hidden>Disconnect</button>
|
| 79 |
+
</div>
|
| 80 |
+
</article>
|
| 81 |
+
<dialog id="antigravityIntegrationDialog" class="integration-dialog" aria-labelledby="antigravityIntegrationTitle" aria-describedby="antigravityIntegrationDescription">
|
| 82 |
+
<div class="section-heading">
|
| 83 |
+
<h3 id="antigravityIntegrationTitle">Antigravity CLI</h3>
|
| 84 |
+
<button id="closeAntigravityIntegration" class="ghost-button" type="button" aria-label="Close" autofocus>×</button>
|
| 85 |
+
</div>
|
| 86 |
+
<p id="antigravityIntegrationDescription">Switch Antigravity CLI to the Gemini API provider and add FCC's models. Then launch with fcc-agy.</p>
|
| 87 |
+
<div class="integration-files">
|
| 88 |
+
<strong>Files to modify</strong>
|
| 89 |
+
<ul id="antigravityIntegrationFiles"></ul>
|
| 90 |
+
</div>
|
| 91 |
+
<button id="confirmAntigravityIntegration" class="primary-button" type="button">Connect</button>
|
| 92 |
+
<p id="antigravityIntegrationDialogMessage" class="message-area error" role="alert" hidden></p>
|
| 93 |
+
</dialog>
|
| 94 |
<article class="provider-strip integration-card">
|
| 95 |
<div class="section-heading">
|
| 96 |
<div>
|
|
|
|
| 285 |
<div id="providerDialogBody">
|
| 286 |
<div id="providerDialogActions" class="provider-actions"></div>
|
| 287 |
<div id="providerDialogCheck" class="provider-check-result" role="status" hidden></div>
|
| 288 |
+
<div id="providerDialogAvailability" class="provider-availability-result" role="status" hidden></div>
|
| 289 |
<div id="providerFields" class="field-grid"></div>
|
| 290 |
</div>
|
| 291 |
<div id="providerMessage" class="message-area" role="status"></div>
|
src/free_claude_code/api/admin_static/session_ui.js
CHANGED
|
@@ -87,7 +87,8 @@
|
|
| 87 |
input.autocomplete = "off";
|
| 88 |
input.value = value;
|
| 89 |
input.setAttribute("aria-label", "Selected model");
|
| 90 |
-
let committed = value
|
|
|
|
| 91 |
const combobox = new window.FccModelCombobox(input, {
|
| 92 |
listboxId: `${id}-options`,
|
| 93 |
label: "model",
|
|
@@ -114,6 +115,14 @@
|
|
| 114 |
input.disabled = disabled;
|
| 115 |
combobox.toggle.disabled = disabled;
|
| 116 |
if (disabled) combobox.close();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
},
|
| 118 |
};
|
| 119 |
}
|
|
|
|
| 87 |
input.autocomplete = "off";
|
| 88 |
input.value = value;
|
| 89 |
input.setAttribute("aria-label", "Selected model");
|
| 90 |
+
let committed = value,
|
| 91 |
+
optionsSignature = JSON.stringify(values());
|
| 92 |
const combobox = new window.FccModelCombobox(input, {
|
| 93 |
listboxId: `${id}-options`,
|
| 94 |
label: "model",
|
|
|
|
| 115 |
input.disabled = disabled;
|
| 116 |
combobox.toggle.disabled = disabled;
|
| 117 |
if (disabled) combobox.close();
|
| 118 |
+
const signature = JSON.stringify(values());
|
| 119 |
+
if (combobox.isOpen && signature !== optionsSignature) {
|
| 120 |
+
const active = combobox.visibleOptions[combobox.activeIndex]?.dataset.value;
|
| 121 |
+
combobox.render(combobox.query);
|
| 122 |
+
const index = combobox.visibleOptions.findIndex((option) => option.dataset.value === active);
|
| 123 |
+
if (index >= 0) combobox.setActive(index, false);
|
| 124 |
+
}
|
| 125 |
+
optionsSignature = signature;
|
| 126 |
},
|
| 127 |
};
|
| 128 |
}
|
src/free_claude_code/api/app.py
CHANGED
|
@@ -2,11 +2,15 @@ from __future__ import annotations
|
|
| 2 |
"""Pure FastAPI application factory."""
|
| 3 |
|
| 4 |
from fastapi import FastAPI, Request
|
| 5 |
-
from fastapi.exception_handlers import
|
|
|
|
|
|
|
|
|
|
| 6 |
from fastapi.exceptions import RequestValidationError
|
| 7 |
from fastapi.responses import JSONResponse, Response
|
| 8 |
-
from starlette.middleware.base import BaseHTTPMiddleware
|
| 9 |
from loguru import logger
|
|
|
|
|
|
|
| 10 |
|
| 11 |
from free_claude_code.application.code_sessions import (
|
| 12 |
CodeConflictError,
|
|
@@ -21,6 +25,7 @@ from free_claude_code.core.diagnostics import (
|
|
| 21 |
redacted_exception_traceback,
|
| 22 |
safe_exception_message,
|
| 23 |
)
|
|
|
|
| 24 |
from free_claude_code.core.openai_responses import openai_error_payload
|
| 25 |
from free_claude_code.core.trace import (
|
| 26 |
extract_claude_session_id_from_headers,
|
|
@@ -31,6 +36,7 @@ from free_claude_code.core.version import package_version
|
|
| 31 |
from .admin_cache import AdminNoStoreMiddleware, attach_admin_no_store
|
| 32 |
from .admin_routes import router as admin_router
|
| 33 |
from .code_sessions_routes import router as code_router
|
|
|
|
| 34 |
from .ports import ApiServices
|
| 35 |
from .request_errors import ordinary_application_error_response
|
| 36 |
from .request_ids import (
|
|
@@ -44,6 +50,7 @@ from .routes import router
|
|
| 44 |
from .validation_log import summarize_request_validation_body
|
| 45 |
|
| 46 |
|
|
|
|
| 47 |
class ScannerTrapMiddleware(BaseHTTPMiddleware):
|
| 48 |
"""Intercept common automated scanner probes and return 200 OK."""
|
| 49 |
|
|
@@ -68,6 +75,16 @@ def create_app(services: ApiServices) -> FastAPI:
|
|
| 68 |
app.include_router(code_router)
|
| 69 |
app.include_router(router)
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
@app.exception_handler(CodeError)
|
| 72 |
async def code_error_handler(request: Request, exc: CodeError):
|
| 73 |
if isinstance(exc, CodeNotFoundError):
|
|
@@ -102,12 +119,23 @@ def create_app(services: ApiServices) -> FastAPI:
|
|
| 102 |
event="server.request.validation_failed",
|
| 103 |
source="api",
|
| 104 |
path=request.url.path,
|
| 105 |
-
query=
|
|
|
|
|
|
|
|
|
|
| 106 |
error_locs=[list(error.get("loc", ())) for error in exc.errors()],
|
| 107 |
error_types=[str(error.get("type", "")) for error in exc.errors()],
|
| 108 |
message_summary=message_summary,
|
| 109 |
tool_names=tool_names,
|
| 110 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
if request.url.path == "/admin/api/config/apply":
|
| 112 |
return JSONResponse(
|
| 113 |
status_code=422,
|
|
@@ -125,9 +153,7 @@ def create_app(services: ApiServices) -> FastAPI:
|
|
| 125 |
"""Serialize defensive application failures in the selected wire protocol."""
|
| 126 |
return ordinary_application_error_response(
|
| 127 |
exc,
|
| 128 |
-
wire_api=(
|
| 129 |
-
"responses" if request.url.path == "/v1/responses" else "messages"
|
| 130 |
-
),
|
| 131 |
request_id=get_request_id(request),
|
| 132 |
)
|
| 133 |
|
|
@@ -154,7 +180,9 @@ def create_app(services: ApiServices) -> FastAPI:
|
|
| 154 |
type(exc).__name__,
|
| 155 |
)
|
| 156 |
message = safe_exception_message(exc)
|
| 157 |
-
if request.url.path == "
|
|
|
|
|
|
|
| 158 |
content = openai_error_payload(message=message, error_type="api_error")
|
| 159 |
else:
|
| 160 |
content = anthropic_error_payload(
|
|
|
|
| 2 |
"""Pure FastAPI application factory."""
|
| 3 |
|
| 4 |
from fastapi import FastAPI, Request
|
| 5 |
+
from fastapi.exception_handlers import (
|
| 6 |
+
http_exception_handler,
|
| 7 |
+
request_validation_exception_handler,
|
| 8 |
+
)
|
| 9 |
from fastapi.exceptions import RequestValidationError
|
| 10 |
from fastapi.responses import JSONResponse, Response
|
|
|
|
| 11 |
from loguru import logger
|
| 12 |
+
from starlette.exceptions import HTTPException
|
| 13 |
+
from starlette.middleware.base import BaseHTTPMiddleware
|
| 14 |
|
| 15 |
from free_claude_code.application.code_sessions import (
|
| 16 |
CodeConflictError,
|
|
|
|
| 25 |
redacted_exception_traceback,
|
| 26 |
safe_exception_message,
|
| 27 |
)
|
| 28 |
+
from free_claude_code.core.gemini import gemini_error_payload
|
| 29 |
from free_claude_code.core.openai_responses import openai_error_payload
|
| 30 |
from free_claude_code.core.trace import (
|
| 31 |
extract_claude_session_id_from_headers,
|
|
|
|
| 36 |
from .admin_cache import AdminNoStoreMiddleware, attach_admin_no_store
|
| 37 |
from .admin_routes import router as admin_router
|
| 38 |
from .code_sessions_routes import router as code_router
|
| 39 |
+
from .generation_paths import generation_api
|
| 40 |
from .ports import ApiServices
|
| 41 |
from .request_errors import ordinary_application_error_response
|
| 42 |
from .request_ids import (
|
|
|
|
| 50 |
from .validation_log import summarize_request_validation_body
|
| 51 |
|
| 52 |
|
| 53 |
+
|
| 54 |
class ScannerTrapMiddleware(BaseHTTPMiddleware):
|
| 55 |
"""Intercept common automated scanner probes and return 200 OK."""
|
| 56 |
|
|
|
|
| 75 |
app.include_router(code_router)
|
| 76 |
app.include_router(router)
|
| 77 |
|
| 78 |
+
@app.exception_handler(HTTPException)
|
| 79 |
+
async def public_http_error_handler(request: Request, exc: HTTPException):
|
| 80 |
+
if generation_api(request.url.path) == "gemini":
|
| 81 |
+
return JSONResponse(
|
| 82 |
+
status_code=exc.status_code,
|
| 83 |
+
content=gemini_error_payload(exc.status_code, str(exc.detail)),
|
| 84 |
+
headers=exc.headers,
|
| 85 |
+
)
|
| 86 |
+
return await http_exception_handler(request, exc)
|
| 87 |
+
|
| 88 |
@app.exception_handler(CodeError)
|
| 89 |
async def code_error_handler(request: Request, exc: CodeError):
|
| 90 |
if isinstance(exc, CodeNotFoundError):
|
|
|
|
| 119 |
event="server.request.validation_failed",
|
| 120 |
source="api",
|
| 121 |
path=request.url.path,
|
| 122 |
+
query={
|
| 123 |
+
key: "[REDACTED]" if key == "key" else value
|
| 124 |
+
for key, value in request.query_params.items()
|
| 125 |
+
},
|
| 126 |
error_locs=[list(error.get("loc", ())) for error in exc.errors()],
|
| 127 |
error_types=[str(error.get("type", "")) for error in exc.errors()],
|
| 128 |
message_summary=message_summary,
|
| 129 |
tool_names=tool_names,
|
| 130 |
)
|
| 131 |
+
if generation_api(request.url.path) == "gemini":
|
| 132 |
+
message = "; ".join(
|
| 133 |
+
f"{'.'.join(map(str, error['loc']))}: {error['msg']}"
|
| 134 |
+
for error in exc.errors()
|
| 135 |
+
)
|
| 136 |
+
return JSONResponse(
|
| 137 |
+
status_code=400, content=gemini_error_payload(400, message)
|
| 138 |
+
)
|
| 139 |
if request.url.path == "/admin/api/config/apply":
|
| 140 |
return JSONResponse(
|
| 141 |
status_code=422,
|
|
|
|
| 153 |
"""Serialize defensive application failures in the selected wire protocol."""
|
| 154 |
return ordinary_application_error_response(
|
| 155 |
exc,
|
| 156 |
+
wire_api=generation_api(request.url.path) or "messages",
|
|
|
|
|
|
|
| 157 |
request_id=get_request_id(request),
|
| 158 |
)
|
| 159 |
|
|
|
|
| 180 |
type(exc).__name__,
|
| 181 |
)
|
| 182 |
message = safe_exception_message(exc)
|
| 183 |
+
if generation_api(request.url.path) == "gemini":
|
| 184 |
+
content = gemini_error_payload(500, message)
|
| 185 |
+
elif request.url.path == "/v1/responses":
|
| 186 |
content = openai_error_payload(message=message, error_type="api_error")
|
| 187 |
else:
|
| 188 |
content = anthropic_error_payload(
|
src/free_claude_code/api/command_utils.py
DELETED
|
@@ -1,165 +0,0 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
"""Command parsing utilities for API optimizations."""
|
| 3 |
-
|
| 4 |
-
import re
|
| 5 |
-
import shlex
|
| 6 |
-
|
| 7 |
-
_ENV_ASSIGNMENT_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=.*$")
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
def _is_env_assignment(part: str) -> bool:
|
| 11 |
-
"""Return True when a token is a shell-style env assignment."""
|
| 12 |
-
return bool(_ENV_ASSIGNMENT_RE.match(part))
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def _strip_env_assignments(parts: list[str]) -> list[str]:
|
| 16 |
-
"""Return command parts after leading shell-style env assignments."""
|
| 17 |
-
cmd_start = 0
|
| 18 |
-
for i, part in enumerate(parts):
|
| 19 |
-
if _is_env_assignment(part):
|
| 20 |
-
cmd_start = i + 1
|
| 21 |
-
else:
|
| 22 |
-
break
|
| 23 |
-
return parts[cmd_start:]
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
def extract_command_prefix(command: str) -> str:
|
| 27 |
-
"""Extract the command prefix for fast prefix detection.
|
| 28 |
-
|
| 29 |
-
Parses a shell command safely, handling environment variables and
|
| 30 |
-
command injection attempts. Returns the command prefix suitable
|
| 31 |
-
for quick identification.
|
| 32 |
-
|
| 33 |
-
Returns:
|
| 34 |
-
Command prefix (e.g., "git", "git commit", "npm install")
|
| 35 |
-
or "none" if no valid command found
|
| 36 |
-
"""
|
| 37 |
-
if "`" in command or "$(" in command:
|
| 38 |
-
return "command_injection_detected"
|
| 39 |
-
|
| 40 |
-
try:
|
| 41 |
-
parts = shlex.split(command, posix=False)
|
| 42 |
-
if not parts:
|
| 43 |
-
return "none"
|
| 44 |
-
|
| 45 |
-
env_prefix = []
|
| 46 |
-
cmd_start = 0
|
| 47 |
-
for i, part in enumerate(parts):
|
| 48 |
-
if _is_env_assignment(part):
|
| 49 |
-
env_prefix.append(part)
|
| 50 |
-
cmd_start = i + 1
|
| 51 |
-
else:
|
| 52 |
-
break
|
| 53 |
-
|
| 54 |
-
if cmd_start >= len(parts):
|
| 55 |
-
return "none"
|
| 56 |
-
|
| 57 |
-
cmd_parts = parts[cmd_start:]
|
| 58 |
-
if not cmd_parts:
|
| 59 |
-
return "none"
|
| 60 |
-
|
| 61 |
-
first_word = cmd_parts[0]
|
| 62 |
-
two_word_commands = {
|
| 63 |
-
"git",
|
| 64 |
-
"npm",
|
| 65 |
-
"docker",
|
| 66 |
-
"kubectl",
|
| 67 |
-
"cargo",
|
| 68 |
-
"go",
|
| 69 |
-
"pip",
|
| 70 |
-
"yarn",
|
| 71 |
-
}
|
| 72 |
-
|
| 73 |
-
if first_word in two_word_commands and len(cmd_parts) > 1:
|
| 74 |
-
second_word = cmd_parts[1]
|
| 75 |
-
if not second_word.startswith("-"):
|
| 76 |
-
return f"{first_word} {second_word}"
|
| 77 |
-
return first_word
|
| 78 |
-
return first_word if not env_prefix else " ".join(env_prefix) + " " + first_word
|
| 79 |
-
|
| 80 |
-
except ValueError:
|
| 81 |
-
parts = command.split()
|
| 82 |
-
if not parts:
|
| 83 |
-
return "none"
|
| 84 |
-
cmd_parts = _strip_env_assignments(parts)
|
| 85 |
-
return cmd_parts[0] if cmd_parts else "none"
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
def extract_filepaths_from_command(command: str, output: str) -> str:
|
| 89 |
-
"""Extract file paths from a command locally without API call.
|
| 90 |
-
|
| 91 |
-
Determines if the command reads file contents and extracts paths accordingly.
|
| 92 |
-
Commands like ls/dir/find just list files, so return empty.
|
| 93 |
-
Commands like cat/head/tail actually read contents, so extract the file path.
|
| 94 |
-
|
| 95 |
-
Returns:
|
| 96 |
-
Filepath extraction result in <filepaths> format
|
| 97 |
-
"""
|
| 98 |
-
listing_commands = {
|
| 99 |
-
"ls",
|
| 100 |
-
"dir",
|
| 101 |
-
"find",
|
| 102 |
-
"tree",
|
| 103 |
-
"pwd",
|
| 104 |
-
"cd",
|
| 105 |
-
"mkdir",
|
| 106 |
-
"rmdir",
|
| 107 |
-
"rm",
|
| 108 |
-
}
|
| 109 |
-
|
| 110 |
-
reading_commands = {"cat", "head", "tail", "less", "more", "bat", "type"}
|
| 111 |
-
|
| 112 |
-
try:
|
| 113 |
-
parts = shlex.split(command, posix=False)
|
| 114 |
-
if not parts:
|
| 115 |
-
return "<filepaths>\n</filepaths>"
|
| 116 |
-
|
| 117 |
-
cmd_parts = _strip_env_assignments(parts)
|
| 118 |
-
if not cmd_parts:
|
| 119 |
-
return "<filepaths>\n</filepaths>"
|
| 120 |
-
|
| 121 |
-
base_cmd = cmd_parts[0].split("/")[-1].split("\\")[-1].lower()
|
| 122 |
-
|
| 123 |
-
if base_cmd in listing_commands:
|
| 124 |
-
return "<filepaths>\n</filepaths>"
|
| 125 |
-
|
| 126 |
-
if base_cmd in reading_commands:
|
| 127 |
-
filepaths = []
|
| 128 |
-
for part in cmd_parts[1:]:
|
| 129 |
-
if part.startswith("-"):
|
| 130 |
-
continue
|
| 131 |
-
filepaths.append(part)
|
| 132 |
-
|
| 133 |
-
if filepaths:
|
| 134 |
-
paths_str = "\n".join(filepaths)
|
| 135 |
-
return f"<filepaths>\n{paths_str}\n</filepaths>"
|
| 136 |
-
return "<filepaths>\n</filepaths>"
|
| 137 |
-
|
| 138 |
-
if base_cmd == "grep":
|
| 139 |
-
flags_with_args = {"-e", "-f", "-m", "-A", "-B", "-C"}
|
| 140 |
-
pattern_provided_via_flag = False
|
| 141 |
-
positional = []
|
| 142 |
-
|
| 143 |
-
skip_next = False
|
| 144 |
-
for part in cmd_parts[1:]:
|
| 145 |
-
if skip_next:
|
| 146 |
-
skip_next = False
|
| 147 |
-
continue
|
| 148 |
-
if part.startswith("-"):
|
| 149 |
-
if part in flags_with_args:
|
| 150 |
-
if part in {"-e", "-f"}:
|
| 151 |
-
pattern_provided_via_flag = True
|
| 152 |
-
skip_next = True
|
| 153 |
-
continue
|
| 154 |
-
positional.append(part)
|
| 155 |
-
|
| 156 |
-
filepaths = positional if pattern_provided_via_flag else positional[1:]
|
| 157 |
-
if filepaths:
|
| 158 |
-
paths_str = "\n".join(filepaths)
|
| 159 |
-
return f"<filepaths>\n{paths_str}\n</filepaths>"
|
| 160 |
-
return "<filepaths>\n</filepaths>"
|
| 161 |
-
|
| 162 |
-
return "<filepaths>\n</filepaths>"
|
| 163 |
-
|
| 164 |
-
except ValueError:
|
| 165 |
-
return "<filepaths>\n</filepaths>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/free_claude_code/api/dependencies.py
CHANGED
|
@@ -120,6 +120,35 @@ def require_anthropic_proxy_auth(
|
|
| 120 |
)
|
| 121 |
|
| 122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
def _proxy_token_matches(
|
| 124 |
credential: str,
|
| 125 |
configured_token: str,
|
|
|
|
| 120 |
)
|
| 121 |
|
| 122 |
|
| 123 |
+
def require_gemini_proxy_auth(
|
| 124 |
+
request: Request,
|
| 125 |
+
settings: Settings = Depends(get_settings),
|
| 126 |
+
) -> None:
|
| 127 |
+
keys = request.query_params.getlist("key")
|
| 128 |
+
if len(keys) > 1:
|
| 129 |
+
raise HTTPException(
|
| 130 |
+
status_code=400, detail="Repeated key query credentials are unsupported"
|
| 131 |
+
)
|
| 132 |
+
if not settings.proxy_auth_enabled:
|
| 133 |
+
return
|
| 134 |
+
credential = request.headers.get("authorization")
|
| 135 |
+
bearer = credential is not None
|
| 136 |
+
if credential is None:
|
| 137 |
+
credential = request.headers.get("x-goog-api-key")
|
| 138 |
+
if credential is None:
|
| 139 |
+
credential = keys[0] if keys else None
|
| 140 |
+
if credential is None:
|
| 141 |
+
raise HTTPException(
|
| 142 |
+
status_code=401, detail="Missing proxy authentication token"
|
| 143 |
+
)
|
| 144 |
+
if not _proxy_token_matches(
|
| 145 |
+
credential, settings.proxy_auth_token, require_bearer=bearer
|
| 146 |
+
):
|
| 147 |
+
raise HTTPException(
|
| 148 |
+
status_code=401, detail="Invalid proxy authentication token"
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
def _proxy_token_matches(
|
| 153 |
credential: str,
|
| 154 |
configured_token: str,
|
src/free_claude_code/api/detection.py
CHANGED
|
@@ -1,29 +1,12 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
-
"""
|
| 3 |
-
|
| 4 |
-
Detects quota checks, title generation, prefix detection, safety classifier,
|
| 5 |
-
suggestion mode, and filepath extraction requests to enable targeted handling.
|
| 6 |
-
"""
|
| 7 |
|
| 8 |
from free_claude_code.core.anthropic import (
|
| 9 |
-
Message,
|
| 10 |
MessagesRequest,
|
| 11 |
extract_text_from_content,
|
| 12 |
)
|
| 13 |
|
| 14 |
|
| 15 |
-
def _single_user_turn(request_data: MessagesRequest) -> Message | None:
|
| 16 |
-
"""Return the sole conversational user turn, ignoring system context."""
|
| 17 |
-
user_turn: Message | None = None
|
| 18 |
-
for message in request_data.messages:
|
| 19 |
-
if message.role == "system":
|
| 20 |
-
continue
|
| 21 |
-
if message.role != "user" or user_turn is not None:
|
| 22 |
-
return None
|
| 23 |
-
user_turn = message
|
| 24 |
-
return user_turn
|
| 25 |
-
|
| 26 |
-
|
| 27 |
def _request_system_text(request_data: MessagesRequest) -> str:
|
| 28 |
"""Return top-level and inline system text for request-shape detection."""
|
| 29 |
parts: list[str] = []
|
|
@@ -40,65 +23,6 @@ def _request_system_text(request_data: MessagesRequest) -> str:
|
|
| 40 |
return "\n".join(parts)
|
| 41 |
|
| 42 |
|
| 43 |
-
def is_quota_check_request(request_data: MessagesRequest) -> bool:
|
| 44 |
-
"""Check if this is a quota probe request.
|
| 45 |
-
|
| 46 |
-
Quota checks are typically simple requests with max_tokens=1
|
| 47 |
-
and a single message containing the word "quota".
|
| 48 |
-
"""
|
| 49 |
-
message = _single_user_turn(request_data)
|
| 50 |
-
if request_data.max_tokens != 1 or message is None:
|
| 51 |
-
return False
|
| 52 |
-
text = extract_text_from_content(message.content)
|
| 53 |
-
return "quota" in text.lower()
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
def is_title_generation_request(request_data: MessagesRequest) -> bool:
|
| 57 |
-
"""Check if this is a conversation title generation request.
|
| 58 |
-
|
| 59 |
-
Title generation requests are detected by a system prompt containing
|
| 60 |
-
title extraction instructions, no tools, and a single user message.
|
| 61 |
-
|
| 62 |
-
Matches Claude Code session title prompts (sentence-case title, JSON
|
| 63 |
-
\"title\" field, etc.).
|
| 64 |
-
"""
|
| 65 |
-
if request_data.tools:
|
| 66 |
-
return False
|
| 67 |
-
system_text = _request_system_text(request_data).lower()
|
| 68 |
-
if "title" not in system_text:
|
| 69 |
-
return False
|
| 70 |
-
return "sentence-case title" in system_text or (
|
| 71 |
-
"return json" in system_text
|
| 72 |
-
and "field" in system_text
|
| 73 |
-
and ("coding session" in system_text or "this session" in system_text)
|
| 74 |
-
)
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def is_prefix_detection_request(request_data: MessagesRequest) -> tuple[bool, str]:
|
| 78 |
-
"""Check if this is a fast prefix detection request.
|
| 79 |
-
|
| 80 |
-
Prefix detection requests contain a policy_spec block and
|
| 81 |
-
a Command: section for extracting shell command prefixes.
|
| 82 |
-
|
| 83 |
-
Returns:
|
| 84 |
-
Tuple of (is_prefix_request, command_string)
|
| 85 |
-
"""
|
| 86 |
-
message = _single_user_turn(request_data)
|
| 87 |
-
if message is None:
|
| 88 |
-
return False, ""
|
| 89 |
-
|
| 90 |
-
content = extract_text_from_content(message.content)
|
| 91 |
-
|
| 92 |
-
if "<policy_spec>" in content and "Command:" in content:
|
| 93 |
-
try:
|
| 94 |
-
cmd_start = content.rfind("Command:") + len("Command:")
|
| 95 |
-
return True, content[cmd_start:].strip()
|
| 96 |
-
except TypeError:
|
| 97 |
-
return False, ""
|
| 98 |
-
|
| 99 |
-
return False, ""
|
| 100 |
-
|
| 101 |
-
|
| 102 |
def detect_safety_classifier_stop_sequence(
|
| 103 |
request_data: MessagesRequest,
|
| 104 |
) -> str | None:
|
|
@@ -120,67 +44,3 @@ def detect_safety_classifier_stop_sequence(
|
|
| 120 |
if "yes</block>" in system_text or "no</block>" in system_text:
|
| 121 |
return "</block>"
|
| 122 |
return None
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
def is_suggestion_mode_request(request_data: MessagesRequest) -> bool:
|
| 126 |
-
"""Check if this is a suggestion mode request.
|
| 127 |
-
|
| 128 |
-
Suggestion mode requests contain "[SUGGESTION MODE:" in the user's message,
|
| 129 |
-
used for auto-suggesting what the user might type next.
|
| 130 |
-
"""
|
| 131 |
-
for msg in request_data.messages:
|
| 132 |
-
if msg.role == "user":
|
| 133 |
-
text = extract_text_from_content(msg.content)
|
| 134 |
-
if "[SUGGESTION MODE:" in text:
|
| 135 |
-
return True
|
| 136 |
-
return False
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
def is_filepath_extraction_request(
|
| 140 |
-
request_data: MessagesRequest,
|
| 141 |
-
) -> tuple[bool, str, str]:
|
| 142 |
-
"""Check if this is a filepath extraction request.
|
| 143 |
-
|
| 144 |
-
Filepath extraction requests have a single user message with
|
| 145 |
-
"Command:" and "Output:" sections, asking to extract file paths
|
| 146 |
-
from command output.
|
| 147 |
-
|
| 148 |
-
Returns:
|
| 149 |
-
Tuple of (is_filepath_request, command, output)
|
| 150 |
-
"""
|
| 151 |
-
message = _single_user_turn(request_data)
|
| 152 |
-
if message is None:
|
| 153 |
-
return False, "", ""
|
| 154 |
-
if request_data.tools:
|
| 155 |
-
return False, "", ""
|
| 156 |
-
|
| 157 |
-
content = extract_text_from_content(message.content)
|
| 158 |
-
|
| 159 |
-
if "Command:" not in content or "Output:" not in content:
|
| 160 |
-
return False, "", ""
|
| 161 |
-
|
| 162 |
-
# Match if user content OR system block indicates filepath extraction
|
| 163 |
-
user_has_filepaths = (
|
| 164 |
-
"filepaths" in content.lower() or "<filepaths>" in content.lower()
|
| 165 |
-
)
|
| 166 |
-
system_text = _request_system_text(request_data)
|
| 167 |
-
system_has_extract = (
|
| 168 |
-
"extract any file paths" in system_text.lower()
|
| 169 |
-
or "file paths that this command" in system_text.lower()
|
| 170 |
-
)
|
| 171 |
-
if not user_has_filepaths and not system_has_extract:
|
| 172 |
-
return False, "", ""
|
| 173 |
-
|
| 174 |
-
cmd_start = content.find("Command:") + len("Command:")
|
| 175 |
-
output_marker = content.find("Output:", cmd_start)
|
| 176 |
-
if output_marker == -1:
|
| 177 |
-
return False, "", ""
|
| 178 |
-
|
| 179 |
-
command = content[cmd_start:output_marker].strip()
|
| 180 |
-
output = content[output_marker + len("Output:") :].strip()
|
| 181 |
-
|
| 182 |
-
for marker in ["<", "\n\n"]:
|
| 183 |
-
if marker in output:
|
| 184 |
-
output = output.split(marker)[0].strip()
|
| 185 |
-
|
| 186 |
-
return True, command, output
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
+
"""Detect known Claude auto-mode classifier requests."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
from free_claude_code.core.anthropic import (
|
|
|
|
| 5 |
MessagesRequest,
|
| 6 |
extract_text_from_content,
|
| 7 |
)
|
| 8 |
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
def _request_system_text(request_data: MessagesRequest) -> str:
|
| 11 |
"""Return top-level and inline system text for request-shape detection."""
|
| 12 |
parts: list[str] = []
|
|
|
|
| 23 |
return "\n".join(parts)
|
| 24 |
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
def detect_safety_classifier_stop_sequence(
|
| 27 |
request_data: MessagesRequest,
|
| 28 |
) -> str | None:
|
|
|
|
| 44 |
if "yes</block>" in system_text or "no</block>" in system_text:
|
| 45 |
return "</block>"
|
| 46 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/free_claude_code/api/generation_paths.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
"""Public generation route classification shared by HTTP boundaries."""
|
| 3 |
+
|
| 4 |
+
from typing import Literal
|
| 5 |
+
|
| 6 |
+
type WireApi = Literal["messages", "responses", "gemini"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def generation_api(path: str) -> WireApi | None:
|
| 10 |
+
if path == "/v1/messages":
|
| 11 |
+
return "messages"
|
| 12 |
+
if path == "/v1/responses":
|
| 13 |
+
return "responses"
|
| 14 |
+
if path.startswith("/v1beta/models/"):
|
| 15 |
+
return "gemini"
|
| 16 |
+
return None
|
src/free_claude_code/api/handlers/gemini.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
"""Gemini JSON and SSE execution through the shared provider application."""
|
| 3 |
+
|
| 4 |
+
from collections.abc import Mapping
|
| 5 |
+
|
| 6 |
+
from fastapi.responses import JSONResponse, Response
|
| 7 |
+
|
| 8 |
+
from free_claude_code.api.request_errors import (
|
| 9 |
+
log_unexpected_api_exception,
|
| 10 |
+
ordinary_application_error_response,
|
| 11 |
+
)
|
| 12 |
+
from free_claude_code.api.response_streams import (
|
| 13 |
+
ManagedStreamingResponse,
|
| 14 |
+
gemini_sse_streaming_response,
|
| 15 |
+
terminal_execution_error_response,
|
| 16 |
+
trace_terminal_execution_error,
|
| 17 |
+
)
|
| 18 |
+
from free_claude_code.application.errors import ApplicationError
|
| 19 |
+
from free_claude_code.application.execution import ProviderExecutor
|
| 20 |
+
from free_claude_code.application.ports import ModelInfoLookup, ProviderResolver
|
| 21 |
+
from free_claude_code.application.routing import ModelRouter
|
| 22 |
+
from free_claude_code.config.settings import Settings
|
| 23 |
+
from free_claude_code.core.anthropic.streaming.decoder import AnthropicSSEDecoder
|
| 24 |
+
from free_claude_code.core.diagnostics import safe_exception_message
|
| 25 |
+
from free_claude_code.core.failures import find_execution_failure
|
| 26 |
+
from free_claude_code.core.gemini import (
|
| 27 |
+
GeminiConversionError,
|
| 28 |
+
GeminiRequest,
|
| 29 |
+
gemini_error_payload,
|
| 30 |
+
)
|
| 31 |
+
from free_claude_code.core.gemini.response import GeminiResponseAccumulator
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class GeminiHandler:
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
settings: Settings,
|
| 38 |
+
provider_resolver: ProviderResolver,
|
| 39 |
+
*,
|
| 40 |
+
generation_id: int | None = None,
|
| 41 |
+
request_headers: Mapping[str, str] | None = None,
|
| 42 |
+
model_info_lookup: ModelInfoLookup | None = None,
|
| 43 |
+
) -> None:
|
| 44 |
+
self._settings = settings
|
| 45 |
+
self._router = ModelRouter(settings)
|
| 46 |
+
self._executor = ProviderExecutor(
|
| 47 |
+
provider_resolver,
|
| 48 |
+
progress_timeout_seconds=settings.provider_progress_timeout,
|
| 49 |
+
generation_id=generation_id,
|
| 50 |
+
request_headers=request_headers,
|
| 51 |
+
model_info_lookup=model_info_lookup,
|
| 52 |
+
log_raw_payloads=settings.log_raw_api_payloads,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
async def create(
|
| 56 |
+
self, request: GeminiRequest, *, streaming: bool, request_id: str
|
| 57 |
+
) -> Response:
|
| 58 |
+
try:
|
| 59 |
+
routed = self._router.resolve_gemini_request(request)
|
| 60 |
+
body = self._executor.stream_gemini(
|
| 61 |
+
routed,
|
| 62 |
+
request_id=request_id,
|
| 63 |
+
raw_log_payload=lambda: request.model_dump(
|
| 64 |
+
mode="json", by_alias=True, exclude_none=True
|
| 65 |
+
),
|
| 66 |
+
)
|
| 67 |
+
response = await gemini_sse_streaming_response(
|
| 68 |
+
body,
|
| 69 |
+
request_id=request_id,
|
| 70 |
+
pre_start_error_response=lambda error: self._error(error, request_id),
|
| 71 |
+
)
|
| 72 |
+
if streaming or not isinstance(response, ManagedStreamingResponse):
|
| 73 |
+
return response
|
| 74 |
+
aggregate = GeminiResponseAccumulator()
|
| 75 |
+
decoder = AnthropicSSEDecoder()
|
| 76 |
+
try:
|
| 77 |
+
async for chunk in response.body_iterator:
|
| 78 |
+
text = (
|
| 79 |
+
chunk
|
| 80 |
+
if isinstance(chunk, str)
|
| 81 |
+
else bytes(chunk).decode("utf-8")
|
| 82 |
+
)
|
| 83 |
+
for event in decoder.feed(text):
|
| 84 |
+
aggregate.feed(event.data)
|
| 85 |
+
for event in decoder.finish():
|
| 86 |
+
aggregate.feed(event.data)
|
| 87 |
+
return JSONResponse(content=aggregate.result())
|
| 88 |
+
finally:
|
| 89 |
+
await response.aclose()
|
| 90 |
+
except (Exception, BaseExceptionGroup) as error:
|
| 91 |
+
return self._error(error, request_id)
|
| 92 |
+
|
| 93 |
+
def _error(self, error: BaseException, request_id: str) -> JSONResponse:
|
| 94 |
+
if isinstance(error, ApplicationError):
|
| 95 |
+
return ordinary_application_error_response(
|
| 96 |
+
error, wire_api="gemini", request_id=request_id
|
| 97 |
+
)
|
| 98 |
+
if isinstance(error, GeminiConversionError):
|
| 99 |
+
return JSONResponse(
|
| 100 |
+
status_code=400, content=gemini_error_payload(400, str(error))
|
| 101 |
+
)
|
| 102 |
+
failure = find_execution_failure(error)
|
| 103 |
+
status = failure.status_code if failure is not None else 500
|
| 104 |
+
if failure is None:
|
| 105 |
+
log_unexpected_api_exception(
|
| 106 |
+
self._settings,
|
| 107 |
+
error,
|
| 108 |
+
context="CREATE_GEMINI_ERROR",
|
| 109 |
+
request_id=request_id,
|
| 110 |
+
)
|
| 111 |
+
trace_terminal_execution_error(
|
| 112 |
+
wire_api="gemini",
|
| 113 |
+
request_id=request_id,
|
| 114 |
+
status_code=status,
|
| 115 |
+
error_type=failure.kind.value if failure else "api_error",
|
| 116 |
+
error=error,
|
| 117 |
+
)
|
| 118 |
+
return terminal_execution_error_response(
|
| 119 |
+
status_code=status,
|
| 120 |
+
content=gemini_error_payload(
|
| 121 |
+
status, safe_exception_message(failure or error)
|
| 122 |
+
),
|
| 123 |
+
)
|
src/free_claude_code/api/handlers/messages.py
CHANGED
|
@@ -4,13 +4,11 @@ from __future__ import annotations
|
|
| 4 |
import asyncio
|
| 5 |
import sys
|
| 6 |
from collections.abc import AsyncIterator, Mapping
|
| 7 |
-
from dataclasses import
|
| 8 |
|
| 9 |
from fastapi.responses import JSONResponse, Response
|
| 10 |
-
from loguru import logger
|
| 11 |
|
| 12 |
from free_claude_code.api.detection import detect_safety_classifier_stop_sequence
|
| 13 |
-
from free_claude_code.api.optimization_handlers import try_optimizations
|
| 14 |
from free_claude_code.api.request_errors import (
|
| 15 |
http_status_for_unexpected_api_exception,
|
| 16 |
log_unexpected_api_exception,
|
|
@@ -54,19 +52,6 @@ from free_claude_code.core.trace import close_stream_input, trace_event
|
|
| 54 |
from .classifier_response import classifier_response
|
| 55 |
|
| 56 |
|
| 57 |
-
@dataclass(frozen=True)
|
| 58 |
-
class _MessagesStreamResult:
|
| 59 |
-
body: AsyncIterator[str]
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
@dataclass(frozen=True)
|
| 63 |
-
class _MessagesCompleteResult:
|
| 64 |
-
response: object
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
_MessagesResult = _MessagesStreamResult | _MessagesCompleteResult
|
| 68 |
-
|
| 69 |
-
|
| 70 |
class MessagesHandler:
|
| 71 |
"""Handle Anthropic-compatible Messages requests."""
|
| 72 |
|
|
@@ -141,25 +126,15 @@ class MessagesHandler:
|
|
| 141 |
routed.resolved.primary.provider_id,
|
| 142 |
routed.resolved.primary.provider_model,
|
| 143 |
)
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
else self._intercept_local_optimization(routed)
|
| 151 |
-
)
|
| 152 |
-
if result is None:
|
| 153 |
-
logger.debug("No optimization matched, routing to provider")
|
| 154 |
-
result = _MessagesStreamResult(
|
| 155 |
-
self._provider_executor.stream_messages(
|
| 156 |
-
routed,
|
| 157 |
-
raw_log_payload=routed.request.model_dump,
|
| 158 |
-
request_id=request_id,
|
| 159 |
-
)
|
| 160 |
)
|
| 161 |
return await self._to_public_response(
|
| 162 |
-
|
| 163 |
stream=request_data.stream,
|
| 164 |
request_id=request_id,
|
| 165 |
hide_reasoning=routed.reasoning.control is ReasoningControl.PREFER_OFF,
|
|
@@ -178,21 +153,19 @@ class MessagesHandler:
|
|
| 178 |
|
| 179 |
async def _to_public_response(
|
| 180 |
self,
|
| 181 |
-
|
| 182 |
*,
|
| 183 |
stream: bool,
|
| 184 |
request_id: str,
|
| 185 |
hide_reasoning: bool = False,
|
| 186 |
) -> object:
|
| 187 |
-
if isinstance(result, _MessagesCompleteResult):
|
| 188 |
-
return result.response
|
| 189 |
if not stream:
|
| 190 |
# Non-streaming clients (e.g. Claude Code utility calls) need a
|
| 191 |
# complete JSON Message; the internal pipeline is always SSE, so
|
| 192 |
# serving that raw here breaks the client SDK's response parse.
|
| 193 |
try:
|
| 194 |
message, error, _complete = await aggregate_anthropic_sse_to_message(
|
| 195 |
-
classifier_response(
|
| 196 |
)
|
| 197 |
except GeneratorExit:
|
| 198 |
raise
|
|
@@ -238,7 +211,7 @@ class MessagesHandler:
|
|
| 238 |
)
|
| 239 |
return JSONResponse(content=message)
|
| 240 |
return await anthropic_sse_streaming_response(
|
| 241 |
-
|
| 242 |
pre_start_error_response=lambda exc: self._pre_start_error_response(
|
| 243 |
exc, request_id=request_id
|
| 244 |
),
|
|
@@ -361,24 +334,6 @@ class MessagesHandler:
|
|
| 361 |
),
|
| 362 |
)
|
| 363 |
|
| 364 |
-
def _intercept_local_optimization(
|
| 365 |
-
self, routed: RoutedMessagesRequest
|
| 366 |
-
) -> _MessagesResult | None:
|
| 367 |
-
optimized = try_optimizations(
|
| 368 |
-
routed.request,
|
| 369 |
-
self._settings,
|
| 370 |
-
response_model=routed.resolved.original_model,
|
| 371 |
-
)
|
| 372 |
-
if optimized is None:
|
| 373 |
-
return None
|
| 374 |
-
trace_event(
|
| 375 |
-
stage="routing",
|
| 376 |
-
event="free_claude_code.api.optimization.short_circuit",
|
| 377 |
-
source="api",
|
| 378 |
-
model=routed.resolved.original_model,
|
| 379 |
-
)
|
| 380 |
-
return _MessagesCompleteResult(optimized)
|
| 381 |
-
|
| 382 |
|
| 383 |
def _stream_error_fields(error: dict[str, object]) -> tuple[str, str]:
|
| 384 |
raw_type = error.get("type")
|
|
|
|
| 4 |
import asyncio
|
| 5 |
import sys
|
| 6 |
from collections.abc import AsyncIterator, Mapping
|
| 7 |
+
from dataclasses import replace
|
| 8 |
|
| 9 |
from fastapi.responses import JSONResponse, Response
|
|
|
|
| 10 |
|
| 11 |
from free_claude_code.api.detection import detect_safety_classifier_stop_sequence
|
|
|
|
| 12 |
from free_claude_code.api.request_errors import (
|
| 13 |
http_status_for_unexpected_api_exception,
|
| 14 |
log_unexpected_api_exception,
|
|
|
|
| 52 |
from .classifier_response import classifier_response
|
| 53 |
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
class MessagesHandler:
|
| 56 |
"""Handle Anthropic-compatible Messages requests."""
|
| 57 |
|
|
|
|
| 126 |
routed.resolved.primary.provider_id,
|
| 127 |
routed.resolved.primary.provider_model,
|
| 128 |
)
|
| 129 |
+
body = self._web_tools.try_stream_messages(routed, request_id=request_id)
|
| 130 |
+
if body is None:
|
| 131 |
+
body = self._provider_executor.stream_messages(
|
| 132 |
+
routed,
|
| 133 |
+
raw_log_payload=routed.request.model_dump,
|
| 134 |
+
request_id=request_id,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
)
|
| 136 |
return await self._to_public_response(
|
| 137 |
+
body,
|
| 138 |
stream=request_data.stream,
|
| 139 |
request_id=request_id,
|
| 140 |
hide_reasoning=routed.reasoning.control is ReasoningControl.PREFER_OFF,
|
|
|
|
| 153 |
|
| 154 |
async def _to_public_response(
|
| 155 |
self,
|
| 156 |
+
body: AsyncIterator[str],
|
| 157 |
*,
|
| 158 |
stream: bool,
|
| 159 |
request_id: str,
|
| 160 |
hide_reasoning: bool = False,
|
| 161 |
) -> object:
|
|
|
|
|
|
|
| 162 |
if not stream:
|
| 163 |
# Non-streaming clients (e.g. Claude Code utility calls) need a
|
| 164 |
# complete JSON Message; the internal pipeline is always SSE, so
|
| 165 |
# serving that raw here breaks the client SDK's response parse.
|
| 166 |
try:
|
| 167 |
message, error, _complete = await aggregate_anthropic_sse_to_message(
|
| 168 |
+
classifier_response(body) if hide_reasoning else body
|
| 169 |
)
|
| 170 |
except GeneratorExit:
|
| 171 |
raise
|
|
|
|
| 211 |
)
|
| 212 |
return JSONResponse(content=message)
|
| 213 |
return await anthropic_sse_streaming_response(
|
| 214 |
+
body,
|
| 215 |
pre_start_error_response=lambda exc: self._pre_start_error_response(
|
| 216 |
exc, request_id=request_id
|
| 217 |
),
|
|
|
|
| 334 |
),
|
| 335 |
)
|
| 336 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
|
| 338 |
def _stream_error_fields(error: dict[str, object]) -> tuple[str, str]:
|
| 339 |
raw_type = error.get("type")
|
src/free_claude_code/api/optimization_handlers.py
DELETED
|
@@ -1,163 +0,0 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
"""Optimization handlers for fast-path API responses.
|
| 3 |
-
|
| 4 |
-
Each handler returns a MessagesResponse if the request matches and the
|
| 5 |
-
optimization is enabled, otherwise None.
|
| 6 |
-
"""
|
| 7 |
-
|
| 8 |
-
import uuid
|
| 9 |
-
|
| 10 |
-
from loguru import logger
|
| 11 |
-
|
| 12 |
-
from free_claude_code.config.settings import Settings
|
| 13 |
-
from free_claude_code.core.anthropic import (
|
| 14 |
-
MessagesRequest,
|
| 15 |
-
MessagesResponse,
|
| 16 |
-
Usage,
|
| 17 |
-
)
|
| 18 |
-
|
| 19 |
-
from .command_utils import extract_command_prefix, extract_filepaths_from_command
|
| 20 |
-
from .detection import (
|
| 21 |
-
is_filepath_extraction_request,
|
| 22 |
-
is_prefix_detection_request,
|
| 23 |
-
is_quota_check_request,
|
| 24 |
-
is_suggestion_mode_request,
|
| 25 |
-
is_title_generation_request,
|
| 26 |
-
)
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def _text_response(
|
| 30 |
-
request_data: MessagesRequest,
|
| 31 |
-
text: str,
|
| 32 |
-
*,
|
| 33 |
-
input_tokens: int,
|
| 34 |
-
output_tokens: int,
|
| 35 |
-
) -> MessagesResponse:
|
| 36 |
-
return MessagesResponse(
|
| 37 |
-
id=f"msg_{uuid.uuid4()}",
|
| 38 |
-
model=request_data.model,
|
| 39 |
-
content=[{"type": "text", "text": text}],
|
| 40 |
-
stop_reason="end_turn",
|
| 41 |
-
usage=Usage(input_tokens=input_tokens, output_tokens=output_tokens),
|
| 42 |
-
)
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
def try_prefix_detection(
|
| 46 |
-
request_data: MessagesRequest, settings: Settings
|
| 47 |
-
) -> MessagesResponse | None:
|
| 48 |
-
"""Fast prefix detection - return command prefix without API call."""
|
| 49 |
-
if not settings.fast_prefix_detection:
|
| 50 |
-
return None
|
| 51 |
-
|
| 52 |
-
is_prefix_req, command = is_prefix_detection_request(request_data)
|
| 53 |
-
if not is_prefix_req:
|
| 54 |
-
return None
|
| 55 |
-
|
| 56 |
-
logger.info("Optimization: Fast prefix detection request")
|
| 57 |
-
return _text_response(
|
| 58 |
-
request_data,
|
| 59 |
-
extract_command_prefix(command),
|
| 60 |
-
input_tokens=100,
|
| 61 |
-
output_tokens=5,
|
| 62 |
-
)
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
def try_quota_mock(
|
| 66 |
-
request_data: MessagesRequest, settings: Settings
|
| 67 |
-
) -> MessagesResponse | None:
|
| 68 |
-
"""Mock quota probe requests."""
|
| 69 |
-
if not settings.enable_network_probe_mock:
|
| 70 |
-
return None
|
| 71 |
-
if not is_quota_check_request(request_data):
|
| 72 |
-
return None
|
| 73 |
-
|
| 74 |
-
logger.info("Optimization: Intercepted and mocked quota probe")
|
| 75 |
-
return _text_response(
|
| 76 |
-
request_data,
|
| 77 |
-
"Quota check passed.",
|
| 78 |
-
input_tokens=10,
|
| 79 |
-
output_tokens=5,
|
| 80 |
-
)
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
def try_title_skip(
|
| 84 |
-
request_data: MessagesRequest, settings: Settings
|
| 85 |
-
) -> MessagesResponse | None:
|
| 86 |
-
"""Skip title generation requests."""
|
| 87 |
-
if not settings.enable_title_generation_skip:
|
| 88 |
-
return None
|
| 89 |
-
if not is_title_generation_request(request_data):
|
| 90 |
-
return None
|
| 91 |
-
|
| 92 |
-
logger.info("Optimization: Skipped title generation request")
|
| 93 |
-
return _text_response(
|
| 94 |
-
request_data,
|
| 95 |
-
"Conversation",
|
| 96 |
-
input_tokens=100,
|
| 97 |
-
output_tokens=5,
|
| 98 |
-
)
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
def try_suggestion_skip(
|
| 102 |
-
request_data: MessagesRequest, settings: Settings
|
| 103 |
-
) -> MessagesResponse | None:
|
| 104 |
-
"""Skip suggestion mode requests."""
|
| 105 |
-
if not settings.enable_suggestion_mode_skip:
|
| 106 |
-
return None
|
| 107 |
-
if not is_suggestion_mode_request(request_data):
|
| 108 |
-
return None
|
| 109 |
-
|
| 110 |
-
logger.info("Optimization: Skipped suggestion mode request")
|
| 111 |
-
return _text_response(
|
| 112 |
-
request_data,
|
| 113 |
-
"",
|
| 114 |
-
input_tokens=100,
|
| 115 |
-
output_tokens=1,
|
| 116 |
-
)
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
def try_filepath_mock(
|
| 120 |
-
request_data: MessagesRequest, settings: Settings
|
| 121 |
-
) -> MessagesResponse | None:
|
| 122 |
-
"""Mock filepath extraction requests."""
|
| 123 |
-
if not settings.enable_filepath_extraction_mock:
|
| 124 |
-
return None
|
| 125 |
-
|
| 126 |
-
is_fp, cmd, output = is_filepath_extraction_request(request_data)
|
| 127 |
-
if not is_fp:
|
| 128 |
-
return None
|
| 129 |
-
|
| 130 |
-
filepaths = extract_filepaths_from_command(cmd, output)
|
| 131 |
-
logger.info("Optimization: Mocked filepath extraction")
|
| 132 |
-
return _text_response(
|
| 133 |
-
request_data,
|
| 134 |
-
filepaths,
|
| 135 |
-
input_tokens=100,
|
| 136 |
-
output_tokens=10,
|
| 137 |
-
)
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
# Cheapest/most common optimizations first for faster short-circuit.
|
| 141 |
-
OPTIMIZATION_HANDLERS = [
|
| 142 |
-
try_quota_mock,
|
| 143 |
-
try_prefix_detection,
|
| 144 |
-
try_title_skip,
|
| 145 |
-
try_suggestion_skip,
|
| 146 |
-
try_filepath_mock,
|
| 147 |
-
]
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
def try_optimizations(
|
| 151 |
-
request_data: MessagesRequest,
|
| 152 |
-
settings: Settings,
|
| 153 |
-
*,
|
| 154 |
-
response_model: str | None = None,
|
| 155 |
-
) -> MessagesResponse | None:
|
| 156 |
-
"""Run optimization handlers in order. Returns first match or None."""
|
| 157 |
-
for handler in OPTIMIZATION_HANDLERS:
|
| 158 |
-
result = handler(request_data, settings)
|
| 159 |
-
if result is not None:
|
| 160 |
-
if response_model is None:
|
| 161 |
-
return result
|
| 162 |
-
return result.model_copy(update={"model": response_model})
|
| 163 |
-
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/free_claude_code/api/ports.py
CHANGED
|
@@ -53,6 +53,12 @@ class AdminRuntimePort(Protocol):
|
|
| 53 |
|
| 54 |
async def refresh_claude_vscode(self) -> JsonObject: ...
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
async def dsh_desktop_status(self) -> JsonObject: ...
|
| 57 |
|
| 58 |
async def connect_dsh_desktop(self) -> JsonObject: ...
|
|
|
|
| 53 |
|
| 54 |
async def refresh_claude_vscode(self) -> JsonObject: ...
|
| 55 |
|
| 56 |
+
async def antigravity_status(self) -> JsonObject: ...
|
| 57 |
+
|
| 58 |
+
async def connect_antigravity(self) -> JsonObject: ...
|
| 59 |
+
|
| 60 |
+
async def disconnect_antigravity(self) -> JsonObject: ...
|
| 61 |
+
|
| 62 |
async def dsh_desktop_status(self) -> JsonObject: ...
|
| 63 |
|
| 64 |
async def connect_dsh_desktop(self) -> JsonObject: ...
|
src/free_claude_code/api/request_errors.py
CHANGED
|
@@ -18,6 +18,7 @@ from free_claude_code.core.diagnostics import (
|
|
| 18 |
redacted_exception_traceback,
|
| 19 |
safe_exception_message,
|
| 20 |
)
|
|
|
|
| 21 |
from free_claude_code.core.openai_responses import (
|
| 22 |
openai_error_payload,
|
| 23 |
openai_error_type_for_failure,
|
|
@@ -27,7 +28,7 @@ from free_claude_code.core.request_outcomes import (
|
|
| 27 |
record_request_failure,
|
| 28 |
)
|
| 29 |
|
| 30 |
-
WireApi = Literal["messages", "responses"]
|
| 31 |
|
| 32 |
|
| 33 |
def require_non_empty_messages(messages: Sequence[object]) -> None:
|
|
@@ -43,6 +44,11 @@ def ordinary_application_error_response(
|
|
| 43 |
) -> JSONResponse:
|
| 44 |
"""Serialize a deterministic application error without terminal headers."""
|
| 45 |
record_request_failure(error.kind.value)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
if wire_api == "responses":
|
| 47 |
return JSONResponse(
|
| 48 |
status_code=error.status_code,
|
|
|
|
| 18 |
redacted_exception_traceback,
|
| 19 |
safe_exception_message,
|
| 20 |
)
|
| 21 |
+
from free_claude_code.core.gemini import gemini_error_payload
|
| 22 |
from free_claude_code.core.openai_responses import (
|
| 23 |
openai_error_payload,
|
| 24 |
openai_error_type_for_failure,
|
|
|
|
| 28 |
record_request_failure,
|
| 29 |
)
|
| 30 |
|
| 31 |
+
WireApi = Literal["messages", "responses", "gemini"]
|
| 32 |
|
| 33 |
|
| 34 |
def require_non_empty_messages(messages: Sequence[object]) -> None:
|
|
|
|
| 44 |
) -> JSONResponse:
|
| 45 |
"""Serialize a deterministic application error without terminal headers."""
|
| 46 |
record_request_failure(error.kind.value)
|
| 47 |
+
if wire_api == "gemini":
|
| 48 |
+
return JSONResponse(
|
| 49 |
+
status_code=error.status_code,
|
| 50 |
+
content=gemini_error_payload(error.status_code, error.message),
|
| 51 |
+
)
|
| 52 |
if wire_api == "responses":
|
| 53 |
return JSONResponse(
|
| 54 |
status_code=error.status_code,
|
src/free_claude_code/api/request_ids.py
CHANGED
|
@@ -10,6 +10,8 @@ from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
|
| 10 |
|
| 11 |
from free_claude_code.core.trace import extract_claude_session_id_from_headers
|
| 12 |
|
|
|
|
|
|
|
| 13 |
REQUEST_ID_HEADER = "request-id"
|
| 14 |
OPENAI_REQUEST_ID_HEADER = "x-request-id"
|
| 15 |
_REQUEST_ID_STATE_ATTRIBUTE = "fcc_request_id"
|
|
@@ -97,5 +99,5 @@ def _set_request_id_headers(
|
|
| 97 |
path: str,
|
| 98 |
) -> None:
|
| 99 |
headers[REQUEST_ID_HEADER] = request_id
|
| 100 |
-
if path in _OPENAI_REQUEST_ID_PATHS:
|
| 101 |
headers[OPENAI_REQUEST_ID_HEADER] = request_id
|
|
|
|
| 10 |
|
| 11 |
from free_claude_code.core.trace import extract_claude_session_id_from_headers
|
| 12 |
|
| 13 |
+
from .generation_paths import generation_api
|
| 14 |
+
|
| 15 |
REQUEST_ID_HEADER = "request-id"
|
| 16 |
OPENAI_REQUEST_ID_HEADER = "x-request-id"
|
| 17 |
_REQUEST_ID_STATE_ATTRIBUTE = "fcc_request_id"
|
|
|
|
| 99 |
path: str,
|
| 100 |
) -> None:
|
| 101 |
headers[REQUEST_ID_HEADER] = request_id
|
| 102 |
+
if path in _OPENAI_REQUEST_ID_PATHS or generation_api(path) == "gemini":
|
| 103 |
headers[OPENAI_REQUEST_ID_HEADER] = request_id
|
src/free_claude_code/api/request_lifetime.py
CHANGED
|
@@ -5,6 +5,8 @@ import asyncio
|
|
| 5 |
|
| 6 |
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
| 7 |
|
|
|
|
|
|
|
| 8 |
_CLIENT_OWNED_PATHS = frozenset(
|
| 9 |
{
|
| 10 |
"/v1/messages",
|
|
@@ -85,9 +87,12 @@ class ClientRequestLifetimeMiddleware:
|
|
| 85 |
|
| 86 |
|
| 87 |
def _owns_client_lifetime(scope: Scope) -> bool:
|
| 88 |
-
path = scope.get("path")
|
| 89 |
return scope["type"] == "http" and (
|
| 90 |
-
(
|
|
|
|
|
|
|
|
|
|
| 91 |
or (
|
| 92 |
scope.get("method") == "GET" and path in {"/v1/models", "/muse-code/models"}
|
| 93 |
)
|
|
|
|
| 5 |
|
| 6 |
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
| 7 |
|
| 8 |
+
from .generation_paths import generation_api
|
| 9 |
+
|
| 10 |
_CLIENT_OWNED_PATHS = frozenset(
|
| 11 |
{
|
| 12 |
"/v1/messages",
|
|
|
|
| 87 |
|
| 88 |
|
| 89 |
def _owns_client_lifetime(scope: Scope) -> bool:
|
| 90 |
+
path = scope.get("path", "")
|
| 91 |
return scope["type"] == "http" and (
|
| 92 |
+
(
|
| 93 |
+
scope.get("method") == "POST"
|
| 94 |
+
and (path in _CLIENT_OWNED_PATHS or generation_api(path) is not None)
|
| 95 |
+
)
|
| 96 |
or (
|
| 97 |
scope.get("method") == "GET" and path in {"/v1/models", "/muse-code/models"}
|
| 98 |
)
|
src/free_claude_code/api/request_outcomes.py
CHANGED
|
@@ -18,11 +18,17 @@ from free_claude_code.core.request_outcomes import (
|
|
| 18 |
record_request_failure,
|
| 19 |
)
|
| 20 |
|
|
|
|
|
|
|
| 21 |
_FAILURE_EVENTS = frozenset({"error", "response.error", "response.failed"})
|
| 22 |
|
| 23 |
|
| 24 |
def _observe_event(event: SSEEvent) -> None:
|
| 25 |
-
kind =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
if not isinstance(kind, str) or kind not in _FAILURE_EVENTS:
|
| 27 |
return
|
| 28 |
response = event.data.get("response")
|
|
@@ -43,7 +49,7 @@ class RequestOutcomeMiddleware:
|
|
| 43 |
if (
|
| 44 |
scope["type"] != "http"
|
| 45 |
or scope.get("method") != "POST"
|
| 46 |
-
or scope.get("path"
|
| 47 |
):
|
| 48 |
await self._app(scope, receive, send)
|
| 49 |
return
|
|
@@ -76,7 +82,11 @@ class RequestOutcomeMiddleware:
|
|
| 76 |
.get("content-type", "")
|
| 77 |
.startswith("text/event-stream")
|
| 78 |
):
|
| 79 |
-
decoder = AnthropicSSEDecoder(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
elif message["type"] == "http.response.body":
|
| 81 |
completed = not message.get("more_body", False)
|
| 82 |
if decoder is not None:
|
|
@@ -115,9 +125,7 @@ class RequestOutcomeMiddleware:
|
|
| 115 |
result = "success"
|
| 116 |
logger.bind(
|
| 117 |
event="request.completed",
|
| 118 |
-
wire_api="
|
| 119 |
-
if scope["path"] == "/v1/responses"
|
| 120 |
-
else "messages",
|
| 121 |
provider_id=outcome.provider_id,
|
| 122 |
model=outcome.model,
|
| 123 |
status_code=status_code,
|
|
|
|
| 18 |
record_request_failure,
|
| 19 |
)
|
| 20 |
|
| 21 |
+
from .generation_paths import generation_api
|
| 22 |
+
|
| 23 |
_FAILURE_EVENTS = frozenset({"error", "response.error", "response.failed"})
|
| 24 |
|
| 25 |
|
| 26 |
def _observe_event(event: SSEEvent) -> None:
|
| 27 |
+
kind = (
|
| 28 |
+
event.event
|
| 29 |
+
or event.data.get("type")
|
| 30 |
+
or ("error" if "error" in event.data else None)
|
| 31 |
+
)
|
| 32 |
if not isinstance(kind, str) or kind not in _FAILURE_EVENTS:
|
| 33 |
return
|
| 34 |
response = event.data.get("response")
|
|
|
|
| 49 |
if (
|
| 50 |
scope["type"] != "http"
|
| 51 |
or scope.get("method") != "POST"
|
| 52 |
+
or generation_api(scope.get("path", "")) is None
|
| 53 |
):
|
| 54 |
await self._app(scope, receive, send)
|
| 55 |
return
|
|
|
|
| 82 |
.get("content-type", "")
|
| 83 |
.startswith("text/event-stream")
|
| 84 |
):
|
| 85 |
+
decoder = AnthropicSSEDecoder(
|
| 86 |
+
event_names=None
|
| 87 |
+
if generation_api(scope["path"]) == "gemini"
|
| 88 |
+
else _FAILURE_EVENTS
|
| 89 |
+
)
|
| 90 |
elif message["type"] == "http.response.body":
|
| 91 |
completed = not message.get("more_body", False)
|
| 92 |
if decoder is not None:
|
|
|
|
| 125 |
result = "success"
|
| 126 |
logger.bind(
|
| 127 |
event="request.completed",
|
| 128 |
+
wire_api=generation_api(scope["path"]),
|
|
|
|
|
|
|
| 129 |
provider_id=outcome.provider_id,
|
| 130 |
model=outcome.model,
|
| 131 |
status_code=status_code,
|
src/free_claude_code/api/response_streams.py
CHANGED
|
@@ -25,6 +25,8 @@ from free_claude_code.core.anthropic.streaming import (
|
|
| 25 |
from free_claude_code.core.async_iterators import try_close_async_iterator
|
| 26 |
from free_claude_code.core.diagnostics import safe_exception_message
|
| 27 |
from free_claude_code.core.failures import find_execution_failure
|
|
|
|
|
|
|
| 28 |
from free_claude_code.core.json_types import JsonObject
|
| 29 |
from free_claude_code.core.openai_responses import (
|
| 30 |
committed_response_failure_frame,
|
|
@@ -45,7 +47,7 @@ PreStartErrorResponse = Callable[[BaseException], Response]
|
|
| 45 |
TerminalFrameEmitter = Callable[[str, str, BaseException], str]
|
| 46 |
TerminalFailureObserver = Callable[[BaseException], None]
|
| 47 |
ReleaseResponseResource = Callable[[], Awaitable[None]]
|
| 48 |
-
WireApi = Literal["messages", "responses"]
|
| 49 |
|
| 50 |
|
| 51 |
class EmptyStreamError(RuntimeError):
|
|
@@ -394,6 +396,41 @@ async def openai_responses_sse_streaming_response(
|
|
| 394 |
)
|
| 395 |
|
| 396 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
def _trace_responses_terminal_failure(
|
| 398 |
exc: BaseException,
|
| 399 |
*,
|
|
|
|
| 25 |
from free_claude_code.core.async_iterators import try_close_async_iterator
|
| 26 |
from free_claude_code.core.diagnostics import safe_exception_message
|
| 27 |
from free_claude_code.core.failures import find_execution_failure
|
| 28 |
+
from free_claude_code.core.gemini import gemini_error_payload
|
| 29 |
+
from free_claude_code.core.gemini.response import gemini_frame
|
| 30 |
from free_claude_code.core.json_types import JsonObject
|
| 31 |
from free_claude_code.core.openai_responses import (
|
| 32 |
committed_response_failure_frame,
|
|
|
|
| 47 |
TerminalFrameEmitter = Callable[[str, str, BaseException], str]
|
| 48 |
TerminalFailureObserver = Callable[[BaseException], None]
|
| 49 |
ReleaseResponseResource = Callable[[], Awaitable[None]]
|
| 50 |
+
WireApi = Literal["messages", "responses", "gemini"]
|
| 51 |
|
| 52 |
|
| 53 |
class EmptyStreamError(RuntimeError):
|
|
|
|
| 396 |
)
|
| 397 |
|
| 398 |
|
| 399 |
+
async def gemini_sse_streaming_response(
|
| 400 |
+
body: AsyncIterator[str],
|
| 401 |
+
*,
|
| 402 |
+
pre_start_error_response: PreStartErrorResponse,
|
| 403 |
+
request_id: str,
|
| 404 |
+
) -> Response:
|
| 405 |
+
def terminal_frame(_first: str, _latest: str, error: BaseException) -> str:
|
| 406 |
+
failure = find_execution_failure(error)
|
| 407 |
+
return gemini_frame(
|
| 408 |
+
gemini_error_payload(
|
| 409 |
+
failure.status_code if failure else 500,
|
| 410 |
+
safe_exception_message(failure or error),
|
| 411 |
+
)
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
def terminal_observer(error: BaseException) -> None:
|
| 415 |
+
failure = find_execution_failure(error)
|
| 416 |
+
trace_terminal_execution_error(
|
| 417 |
+
wire_api="gemini",
|
| 418 |
+
request_id=request_id,
|
| 419 |
+
status_code=failure.status_code if failure else 500,
|
| 420 |
+
error_type=failure.kind.value if failure else "api_error",
|
| 421 |
+
error=error,
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
return await _first_chunk_streaming_response(
|
| 425 |
+
body,
|
| 426 |
+
wire_api="gemini",
|
| 427 |
+
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
| 428 |
+
pre_start_error_response=pre_start_error_response,
|
| 429 |
+
terminal_frame=terminal_frame,
|
| 430 |
+
terminal_failure_observer=terminal_observer,
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
def _trace_responses_terminal_failure(
|
| 435 |
exc: BaseException,
|
| 436 |
*,
|
src/free_claude_code/api/routes.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
"""FastAPI route handlers."""
|
| 3 |
|
|
|
|
| 4 |
from collections.abc import Mapping
|
| 5 |
from typing import Annotated, Any, cast
|
| 6 |
|
|
@@ -25,6 +26,7 @@ from free_claude_code.core.anthropic.native import (
|
|
| 25 |
validate_messages_json,
|
| 26 |
)
|
| 27 |
from free_claude_code.core.anthropic.passthrough import NativeMessagesRequest
|
|
|
|
| 28 |
from free_claude_code.core.json_types import JsonObject
|
| 29 |
from free_claude_code.core.openai_responses import OpenAIResponsesRequest
|
| 30 |
from free_claude_code.core.trace import trace_event
|
|
@@ -33,10 +35,12 @@ from .dependencies import (
|
|
| 33 |
get_services,
|
| 34 |
get_settings,
|
| 35 |
require_anthropic_proxy_auth,
|
|
|
|
| 36 |
require_proxy_auth,
|
| 37 |
resolve_provider,
|
| 38 |
)
|
| 39 |
from .handlers import MessagesHandler, ResponsesHandler, TokenCountHandler
|
|
|
|
| 40 |
from .model_catalog import (
|
| 41 |
ModelCatalogView,
|
| 42 |
ModelsListResponse,
|
|
@@ -51,6 +55,78 @@ from .response_streams import bind_response_lifetime
|
|
| 51 |
router = APIRouter()
|
| 52 |
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
def _provider_resolver(lease: RequestRuntimeLease) -> ProviderResolver:
|
| 55 |
return lambda provider_type, api_key_number: resolve_provider(
|
| 56 |
provider_type, api_key_number, lease=lease
|
|
@@ -320,7 +396,7 @@ async def list_models(
|
|
| 320 |
):
|
| 321 |
"""List the model ids this proxy advertises to compatible clients."""
|
| 322 |
trace_event(stage="ingress", event="free_claude_code.api.models.list", source="api")
|
| 323 |
-
snapshot =
|
| 324 |
return build_models_list_response(
|
| 325 |
snapshot.settings,
|
| 326 |
snapshot,
|
|
@@ -339,7 +415,7 @@ async def list_muse_models(
|
|
| 339 |
):
|
| 340 |
"""List the direct Responses models expected by Muse Code."""
|
| 341 |
trace_event(stage="ingress", event="free_claude_code.api.models.list", source="api")
|
| 342 |
-
snapshot =
|
| 343 |
return build_muse_models_list_response(snapshot.settings, snapshot)
|
| 344 |
|
| 345 |
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
"""FastAPI route handlers."""
|
| 3 |
|
| 4 |
+
import json
|
| 5 |
from collections.abc import Mapping
|
| 6 |
from typing import Annotated, Any, cast
|
| 7 |
|
|
|
|
| 26 |
validate_messages_json,
|
| 27 |
)
|
| 28 |
from free_claude_code.core.anthropic.passthrough import NativeMessagesRequest
|
| 29 |
+
from free_claude_code.core.gemini import GeminiRequest
|
| 30 |
from free_claude_code.core.json_types import JsonObject
|
| 31 |
from free_claude_code.core.openai_responses import OpenAIResponsesRequest
|
| 32 |
from free_claude_code.core.trace import trace_event
|
|
|
|
| 35 |
get_services,
|
| 36 |
get_settings,
|
| 37 |
require_anthropic_proxy_auth,
|
| 38 |
+
require_gemini_proxy_auth,
|
| 39 |
require_proxy_auth,
|
| 40 |
resolve_provider,
|
| 41 |
)
|
| 42 |
from .handlers import MessagesHandler, ResponsesHandler, TokenCountHandler
|
| 43 |
+
from .handlers.gemini import GeminiHandler
|
| 44 |
from .model_catalog import (
|
| 45 |
ModelCatalogView,
|
| 46 |
ModelsListResponse,
|
|
|
|
| 55 |
router = APIRouter()
|
| 56 |
|
| 57 |
|
| 58 |
+
def _unique_json_fields(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
| 59 |
+
result: dict[str, Any] = {}
|
| 60 |
+
for key, value in pairs:
|
| 61 |
+
if key in result:
|
| 62 |
+
raise ValueError(f"Duplicate JSON field: {key}")
|
| 63 |
+
result[key] = value
|
| 64 |
+
return result
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@router.post("/v1beta/models/{resource:path}")
|
| 68 |
+
async def create_gemini_response(
|
| 69 |
+
resource: str,
|
| 70 |
+
request: Request,
|
| 71 |
+
request_data: Annotated[dict[str, Any], Body()],
|
| 72 |
+
services: ApiServices = Depends(get_services),
|
| 73 |
+
_auth=Depends(require_gemini_proxy_auth),
|
| 74 |
+
):
|
| 75 |
+
try:
|
| 76 |
+
json.loads(await request.body(), object_pairs_hook=_unique_json_fields)
|
| 77 |
+
except ValueError as error:
|
| 78 |
+
raise HTTPException(status_code=400, detail=str(error)) from error
|
| 79 |
+
model, separator, action = resource.rpartition(":")
|
| 80 |
+
if not separator or action not in {"generateContent", "streamGenerateContent"}:
|
| 81 |
+
raise HTTPException(status_code=404, detail="Unknown Gemini generation method")
|
| 82 |
+
if not model.strip() or any(
|
| 83 |
+
not segment or segment in {".", ".."} or any(char.isspace() for char in segment)
|
| 84 |
+
for segment in model.split("/")
|
| 85 |
+
):
|
| 86 |
+
raise HTTPException(status_code=400, detail="Invalid model resource")
|
| 87 |
+
streaming = action == "streamGenerateContent"
|
| 88 |
+
alt = request.query_params.getlist("alt")
|
| 89 |
+
if (
|
| 90 |
+
len(alt) > 1
|
| 91 |
+
or (streaming and alt != ["sse"])
|
| 92 |
+
or (not streaming and alt not in ([], ["json"]))
|
| 93 |
+
):
|
| 94 |
+
raise HTTPException(
|
| 95 |
+
status_code=400,
|
| 96 |
+
detail="Streaming requires alt=sse; JSON generation accepts alt=json",
|
| 97 |
+
)
|
| 98 |
+
if "model" in request_data:
|
| 99 |
+
raise HTTPException(status_code=400, detail="Specify the model in the URL only")
|
| 100 |
+
try:
|
| 101 |
+
data = GeminiRequest.model_validate({**request_data, "model": model})
|
| 102 |
+
except ValidationError as error:
|
| 103 |
+
raise RequestValidationError(
|
| 104 |
+
[{**item, "loc": ("body", *item["loc"])} for item in error.errors()],
|
| 105 |
+
body=request_data,
|
| 106 |
+
) from error
|
| 107 |
+
lease = await services.requests.acquire()
|
| 108 |
+
try:
|
| 109 |
+
await lease.wait_for_token_estimation()
|
| 110 |
+
handler = GeminiHandler(
|
| 111 |
+
lease.settings,
|
| 112 |
+
_provider_resolver(lease),
|
| 113 |
+
generation_id=lease.generation_id,
|
| 114 |
+
request_headers={
|
| 115 |
+
key: value
|
| 116 |
+
for key, value in request.headers.items()
|
| 117 |
+
if key.lower() not in {"authorization", "x-api-key", "x-goog-api-key"}
|
| 118 |
+
},
|
| 119 |
+
model_info_lookup=lease.model_info,
|
| 120 |
+
)
|
| 121 |
+
response = await handler.create(
|
| 122 |
+
data, streaming=streaming, request_id=get_request_id(request)
|
| 123 |
+
)
|
| 124 |
+
except BaseException:
|
| 125 |
+
await lease.release()
|
| 126 |
+
raise
|
| 127 |
+
return await bind_response_lifetime(response, lease.release)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
def _provider_resolver(lease: RequestRuntimeLease) -> ProviderResolver:
|
| 131 |
return lambda provider_type, api_key_number: resolve_provider(
|
| 132 |
provider_type, api_key_number, lease=lease
|
|
|
|
| 396 |
):
|
| 397 |
"""List the model ids this proxy advertises to compatible clients."""
|
| 398 |
trace_event(stage="ingress", event="free_claude_code.api.models.list", source="api")
|
| 399 |
+
snapshot = services.requests.catalog_snapshot()
|
| 400 |
return build_models_list_response(
|
| 401 |
snapshot.settings,
|
| 402 |
snapshot,
|
|
|
|
| 415 |
):
|
| 416 |
"""List the direct Responses models expected by Muse Code."""
|
| 417 |
trace_event(stage="ingress", event="free_claude_code.api.models.list", source="api")
|
| 418 |
+
snapshot = services.requests.catalog_snapshot()
|
| 419 |
return build_muse_models_list_response(snapshot.settings, snapshot)
|
| 420 |
|
| 421 |
|
src/free_claude_code/api/stream_delivery.py
CHANGED
|
@@ -9,23 +9,14 @@ from typing import Any, Literal
|
|
| 9 |
try:
|
| 10 |
import simplejson
|
| 11 |
except ImportError:
|
| 12 |
-
import json
|
| 13 |
-
class _SimpleJsonFallback:
|
| 14 |
-
@staticmethod
|
| 15 |
-
def dumps(obj, *args, **kwargs):
|
| 16 |
-
kwargs.pop('use_decimal', None)
|
| 17 |
-
return json.dumps(obj, *args, **kwargs)
|
| 18 |
-
@staticmethod
|
| 19 |
-
def loads(s, *args, **kwargs):
|
| 20 |
-
kwargs.pop('use_decimal', None)
|
| 21 |
-
return json.loads(s, *args, **kwargs)
|
| 22 |
-
simplejson = _SimpleJsonFallback()
|
| 23 |
|
| 24 |
from free_claude_code.core.anthropic.streaming.decoder import AnthropicSSEDecoder
|
| 25 |
from free_claude_code.core.async_iterators import try_close_async_iterator
|
| 26 |
from free_claude_code.core.continuation_stream import ContinuationStream
|
| 27 |
from free_claude_code.core.delivered_response import DeliveredResponse
|
| 28 |
from free_claude_code.core.failures import find_execution_failure
|
|
|
|
| 29 |
from free_claude_code.core.stream_delivery import (
|
| 30 |
StreamDeliveryState,
|
| 31 |
bind_stream_delivery,
|
|
@@ -65,7 +56,7 @@ class PublicResponseStream(AsyncIterator[str]):
|
|
| 65 |
body: AsyncIterator[str],
|
| 66 |
state: StreamDeliveryState,
|
| 67 |
*,
|
| 68 |
-
wire_api: Literal["messages", "responses"],
|
| 69 |
first_chunk: str,
|
| 70 |
terminal_frame: Callable[[str, str, BaseException], str] | None,
|
| 71 |
terminal_failure_observer: Callable[[BaseException], None] | None,
|
|
@@ -239,6 +230,8 @@ class PublicResponseStream(AsyncIterator[str]):
|
|
| 239 |
|
| 240 |
@staticmethod
|
| 241 |
def _format(payload: dict[str, Any]) -> str:
|
|
|
|
|
|
|
| 242 |
return f"event: {payload['type']}\ndata: {simplejson.dumps(payload, use_decimal=True)}\n\n"
|
| 243 |
|
| 244 |
async def aclose(self) -> None:
|
|
@@ -289,6 +282,13 @@ class PublicResponseStream(AsyncIterator[str]):
|
|
| 289 |
return frame
|
| 290 |
|
| 291 |
raw_kind = payload.get("type")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
kind = raw_kind if isinstance(raw_kind, str) else ""
|
| 293 |
metadata = self._metadata(kind, payload)
|
| 294 |
if self._wire_api == "messages":
|
|
@@ -358,6 +358,12 @@ class PublicResponseStream(AsyncIterator[str]):
|
|
| 358 |
return self._release_content(frame, synthetic=synthetic)
|
| 359 |
|
| 360 |
def _metadata(self, kind: str, payload: dict[str, Any]) -> bool:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
if kind == "ping":
|
| 362 |
return True
|
| 363 |
if self._wire_api == "messages" and kind == "message_start":
|
|
|
|
| 9 |
try:
|
| 10 |
import simplejson
|
| 11 |
except ImportError:
|
| 12 |
+
import json as simplejson
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
from free_claude_code.core.anthropic.streaming.decoder import AnthropicSSEDecoder
|
| 15 |
from free_claude_code.core.async_iterators import try_close_async_iterator
|
| 16 |
from free_claude_code.core.continuation_stream import ContinuationStream
|
| 17 |
from free_claude_code.core.delivered_response import DeliveredResponse
|
| 18 |
from free_claude_code.core.failures import find_execution_failure
|
| 19 |
+
from free_claude_code.core.gemini.response import gemini_finished, gemini_parts
|
| 20 |
from free_claude_code.core.stream_delivery import (
|
| 21 |
StreamDeliveryState,
|
| 22 |
bind_stream_delivery,
|
|
|
|
| 56 |
body: AsyncIterator[str],
|
| 57 |
state: StreamDeliveryState,
|
| 58 |
*,
|
| 59 |
+
wire_api: Literal["messages", "responses", "gemini"],
|
| 60 |
first_chunk: str,
|
| 61 |
terminal_frame: Callable[[str, str, BaseException], str] | None,
|
| 62 |
terminal_failure_observer: Callable[[BaseException], None] | None,
|
|
|
|
| 230 |
|
| 231 |
@staticmethod
|
| 232 |
def _format(payload: dict[str, Any]) -> str:
|
| 233 |
+
if "type" not in payload:
|
| 234 |
+
return f"data: {simplejson.dumps(payload, use_decimal=True)}\n\n"
|
| 235 |
return f"event: {payload['type']}\ndata: {simplejson.dumps(payload, use_decimal=True)}\n\n"
|
| 236 |
|
| 237 |
async def aclose(self) -> None:
|
|
|
|
| 282 |
return frame
|
| 283 |
|
| 284 |
raw_kind = payload.get("type")
|
| 285 |
+
if self._wire_api == "gemini":
|
| 286 |
+
if self._public_id is None and isinstance(payload.get("responseId"), str):
|
| 287 |
+
self._public_id = payload["responseId"]
|
| 288 |
+
self.start_frame = frame
|
| 289 |
+
elif self._public_id is not None and "responseId" in payload:
|
| 290 |
+
payload["responseId"] = self._public_id
|
| 291 |
+
frame = replace_frame_data(frame, payload)
|
| 292 |
kind = raw_kind if isinstance(raw_kind, str) else ""
|
| 293 |
metadata = self._metadata(kind, payload)
|
| 294 |
if self._wire_api == "messages":
|
|
|
|
| 358 |
return self._release_content(frame, synthetic=synthetic)
|
| 359 |
|
| 360 |
def _metadata(self, kind: str, payload: dict[str, Any]) -> bool:
|
| 361 |
+
if self._wire_api == "gemini":
|
| 362 |
+
return (
|
| 363 |
+
not gemini_parts(payload)
|
| 364 |
+
and not gemini_finished(payload)
|
| 365 |
+
and "error" not in payload
|
| 366 |
+
)
|
| 367 |
if kind == "ping":
|
| 368 |
return True
|
| 369 |
if self._wire_api == "messages" and kind == "message_start":
|
src/free_claude_code/api/stream_frames.py
CHANGED
|
@@ -8,17 +8,7 @@ from typing import Any
|
|
| 8 |
try:
|
| 9 |
import simplejson
|
| 10 |
except ImportError:
|
| 11 |
-
import json
|
| 12 |
-
class _SimpleJsonFallback:
|
| 13 |
-
@staticmethod
|
| 14 |
-
def dumps(obj, *args, **kwargs):
|
| 15 |
-
kwargs.pop('use_decimal', None)
|
| 16 |
-
return json.dumps(obj, *args, **kwargs)
|
| 17 |
-
@staticmethod
|
| 18 |
-
def loads(s, *args, **kwargs):
|
| 19 |
-
kwargs.pop('use_decimal', None)
|
| 20 |
-
return json.loads(s, *args, **kwargs)
|
| 21 |
-
simplejson = _SimpleJsonFallback()
|
| 22 |
|
| 23 |
|
| 24 |
def frame_data(frame: str) -> dict[str, Any] | None:
|
|
|
|
| 8 |
try:
|
| 9 |
import simplejson
|
| 10 |
except ImportError:
|
| 11 |
+
import json as simplejson
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
def frame_data(frame: str) -> dict[str, Any] | None:
|
src/free_claude_code/api/tool_call_buffer.py
CHANGED
|
@@ -48,7 +48,7 @@ def _client_call(item: Mapping[str, object]) -> bool:
|
|
| 48 |
class ToolCallBuffer:
|
| 49 |
"""Select complete groups in source order, without owning public delivery."""
|
| 50 |
|
| 51 |
-
def __init__(self, wire_api: Literal["messages", "responses"]) -> None:
|
| 52 |
self._wire_api = wire_api
|
| 53 |
self._frames: list[str] = []
|
| 54 |
self._calls: set[CallKey] = set()
|
|
@@ -59,6 +59,9 @@ class ToolCallBuffer:
|
|
| 59 |
self._indices: dict[int, CallKey] = {}
|
| 60 |
|
| 61 |
def feed(self, frame: str) -> list[str]:
|
|
|
|
|
|
|
|
|
|
| 62 |
events = parse_sse_text(frame)
|
| 63 |
if not events:
|
| 64 |
return self._publish(frame)
|
|
|
|
| 48 |
class ToolCallBuffer:
|
| 49 |
"""Select complete groups in source order, without owning public delivery."""
|
| 50 |
|
| 51 |
+
def __init__(self, wire_api: Literal["messages", "responses", "gemini"]) -> None:
|
| 52 |
self._wire_api = wire_api
|
| 53 |
self._frames: list[str] = []
|
| 54 |
self._calls: set[CallKey] = set()
|
|
|
|
| 59 |
self._indices: dict[int, CallKey] = {}
|
| 60 |
|
| 61 |
def feed(self, frame: str) -> list[str]:
|
| 62 |
+
if self._wire_api == "gemini":
|
| 63 |
+
# Gemini presenters release only complete, object-valued calls.
|
| 64 |
+
return [frame]
|
| 65 |
events = parse_sse_text(frame)
|
| 66 |
if not events:
|
| 67 |
return self._publish(frame)
|
src/free_claude_code/application/code_sessions/service.py
CHANGED
|
@@ -3,7 +3,7 @@ from __future__ import annotations
|
|
| 3 |
|
| 4 |
import asyncio
|
| 5 |
import uuid
|
| 6 |
-
from collections.abc import
|
| 7 |
from contextlib import asynccontextmanager
|
| 8 |
from dataclasses import dataclass, field
|
| 9 |
from pathlib import Path
|
|
@@ -252,7 +252,7 @@ class CodeService:
|
|
| 252 |
del self._gates[session_id]
|
| 253 |
|
| 254 |
@asynccontextmanager
|
| 255 |
-
async def _locked(self, owner: _SessionRuntime) ->
|
| 256 |
async with owner.lock:
|
| 257 |
try:
|
| 258 |
yield
|
|
|
|
| 3 |
|
| 4 |
import asyncio
|
| 5 |
import uuid
|
| 6 |
+
from collections.abc import AsyncGenerator, Callable, Coroutine, Sequence
|
| 7 |
from contextlib import asynccontextmanager
|
| 8 |
from dataclasses import dataclass, field
|
| 9 |
from pathlib import Path
|
|
|
|
| 252 |
del self._gates[session_id]
|
| 253 |
|
| 254 |
@asynccontextmanager
|
| 255 |
+
async def _locked(self, owner: _SessionRuntime) -> AsyncGenerator[None]:
|
| 256 |
async with owner.lock:
|
| 257 |
try:
|
| 258 |
yield
|
src/free_claude_code/application/execution.py
CHANGED
|
@@ -18,6 +18,7 @@ from free_claude_code.core.anthropic import (
|
|
| 18 |
)
|
| 19 |
from free_claude_code.core.anthropic.tokens import TokenCounter
|
| 20 |
from free_claude_code.core.failures import ExecutionFailure, FailureKind
|
|
|
|
| 21 |
from free_claude_code.core.openai_responses import (
|
| 22 |
OpenAIResponsesRequest,
|
| 23 |
estimate_responses_input_tokens,
|
|
@@ -47,13 +48,14 @@ from .routing import (
|
|
| 47 |
ProviderModelCandidate,
|
| 48 |
ProviderModelTarget,
|
| 49 |
ResolvedModelRoute,
|
|
|
|
| 50 |
RoutedMessagesRequest,
|
| 51 |
RoutedNativeMessagesRequest,
|
| 52 |
RoutedResponsesRequest,
|
| 53 |
)
|
| 54 |
|
| 55 |
ResponsesTokenCounter = Callable[[OpenAIResponsesRequest], int]
|
| 56 |
-
WireApi = Literal["messages", "responses"]
|
| 57 |
CandidateStreamOpener = Callable[
|
| 58 |
[int, ProviderModelCandidate, ContinuationSeed | None],
|
| 59 |
Awaitable[AsyncIterator[str]],
|
|
@@ -371,6 +373,63 @@ class ProviderExecutor:
|
|
| 371 |
open_candidate=open_candidate,
|
| 372 |
)
|
| 373 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
def _stream_candidates(
|
| 375 |
self,
|
| 376 |
*,
|
|
@@ -406,8 +465,8 @@ class ProviderExecutor:
|
|
| 406 |
),
|
| 407 |
"reasoning_budget_tokens": reasoning.budget_tokens,
|
| 408 |
}
|
| 409 |
-
if wire_api =
|
| 410 |
-
route_trace["wire_api"] =
|
| 411 |
if self._generation_id is not None:
|
| 412 |
route_trace["generation_id"] = self._generation_id
|
| 413 |
trace_event(**route_trace)
|
|
|
|
| 18 |
)
|
| 19 |
from free_claude_code.core.anthropic.tokens import TokenCounter
|
| 20 |
from free_claude_code.core.failures import ExecutionFailure, FailureKind
|
| 21 |
+
from free_claude_code.core.gemini.tokens import estimate_gemini_input_tokens
|
| 22 |
from free_claude_code.core.openai_responses import (
|
| 23 |
OpenAIResponsesRequest,
|
| 24 |
estimate_responses_input_tokens,
|
|
|
|
| 48 |
ProviderModelCandidate,
|
| 49 |
ProviderModelTarget,
|
| 50 |
ResolvedModelRoute,
|
| 51 |
+
RoutedGeminiRequest,
|
| 52 |
RoutedMessagesRequest,
|
| 53 |
RoutedNativeMessagesRequest,
|
| 54 |
RoutedResponsesRequest,
|
| 55 |
)
|
| 56 |
|
| 57 |
ResponsesTokenCounter = Callable[[OpenAIResponsesRequest], int]
|
| 58 |
+
WireApi = Literal["messages", "responses", "gemini"]
|
| 59 |
CandidateStreamOpener = Callable[
|
| 60 |
[int, ProviderModelCandidate, ContinuationSeed | None],
|
| 61 |
Awaitable[AsyncIterator[str]],
|
|
|
|
| 373 |
open_candidate=open_candidate,
|
| 374 |
)
|
| 375 |
|
| 376 |
+
def stream_gemini(
|
| 377 |
+
self,
|
| 378 |
+
routed: RoutedGeminiRequest,
|
| 379 |
+
*,
|
| 380 |
+
raw_log_payload: Callable[[], object],
|
| 381 |
+
request_id: str,
|
| 382 |
+
) -> AsyncIterator[str]:
|
| 383 |
+
client_reasoning = routed.request.reasoning_policy()
|
| 384 |
+
input_tokens = estimate_gemini_input_tokens(routed.request)
|
| 385 |
+
|
| 386 |
+
async def open_candidate(
|
| 387 |
+
index: int,
|
| 388 |
+
candidate: ProviderModelCandidate,
|
| 389 |
+
continuation: ContinuationSeed | None,
|
| 390 |
+
) -> AsyncIterator[str]:
|
| 391 |
+
target = candidate.target
|
| 392 |
+
provider = await self._provider_resolver(
|
| 393 |
+
target.provider_id, target.api_key_number
|
| 394 |
+
)
|
| 395 |
+
request = prepare_fallback_request(
|
| 396 |
+
routed.request,
|
| 397 |
+
model=target.provider_model,
|
| 398 |
+
preference=candidate.reasoning_preference,
|
| 399 |
+
)
|
| 400 |
+
return provider.stream_gemini(
|
| 401 |
+
request,
|
| 402 |
+
input_tokens=input_tokens,
|
| 403 |
+
request_id=request_id,
|
| 404 |
+
response_model=routed.resolved.original_model,
|
| 405 |
+
reasoning=resolve_fallback_reasoning(
|
| 406 |
+
routed.reasoning,
|
| 407 |
+
candidate.reasoning_preference,
|
| 408 |
+
client=client_reasoning,
|
| 409 |
+
),
|
| 410 |
+
request_headers=self._request_headers,
|
| 411 |
+
continuation=continuation,
|
| 412 |
+
model_info=self._model_info_lookup(
|
| 413 |
+
target.provider_id, target.provider_model
|
| 414 |
+
),
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
return self._stream_candidates(
|
| 418 |
+
resolved=routed.resolved,
|
| 419 |
+
reasoning=routed.reasoning,
|
| 420 |
+
wire_api="gemini",
|
| 421 |
+
raw_log_label="FULL_GEMINI_PAYLOAD",
|
| 422 |
+
raw_log_payload=raw_log_payload,
|
| 423 |
+
request_snapshot=lambda: {
|
| 424 |
+
"model": routed.request.model,
|
| 425 |
+
"content_count": len(routed.request.contents),
|
| 426 |
+
},
|
| 427 |
+
ingress_count_name="content_count",
|
| 428 |
+
ingress_count=len(routed.request.contents),
|
| 429 |
+
request_id=request_id,
|
| 430 |
+
open_candidate=open_candidate,
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
def _stream_candidates(
|
| 434 |
self,
|
| 435 |
*,
|
|
|
|
| 465 |
),
|
| 466 |
"reasoning_budget_tokens": reasoning.budget_tokens,
|
| 467 |
}
|
| 468 |
+
if wire_api != "messages":
|
| 469 |
+
route_trace["wire_api"] = wire_api
|
| 470 |
if self._generation_id is not None:
|
| 471 |
route_trace["generation_id"] = self._generation_id
|
| 472 |
trace_event(**route_trace)
|
src/free_claude_code/application/model_metadata.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
"""Application-owned model metadata."""
|
| 3 |
|
| 4 |
-
from dataclasses import dataclass
|
| 5 |
|
| 6 |
from free_claude_code.core.model_capabilities import ModelInputModality
|
| 7 |
from free_claude_code.core.reasoning import ReasoningCapability
|
|
@@ -25,3 +25,4 @@ class ProviderModelRefreshResult:
|
|
| 25 |
|
| 26 |
refreshed_provider_ids: tuple[str, ...] = ()
|
| 27 |
failed_provider_ids: tuple[str, ...] = ()
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
"""Application-owned model metadata."""
|
| 3 |
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
|
| 6 |
from free_claude_code.core.model_capabilities import ModelInputModality
|
| 7 |
from free_claude_code.core.reasoning import ReasoningCapability
|
|
|
|
| 25 |
|
| 26 |
refreshed_provider_ids: tuple[str, ...] = ()
|
| 27 |
failed_provider_ids: tuple[str, ...] = ()
|
| 28 |
+
failure_messages: dict[str, str] = field(default_factory=dict)
|
src/free_claude_code/application/ports.py
CHANGED
|
@@ -8,6 +8,7 @@ from typing import Protocol
|
|
| 8 |
from free_claude_code.config.settings import Settings
|
| 9 |
from free_claude_code.core.anthropic import MessagesRequest
|
| 10 |
from free_claude_code.core.anthropic.passthrough import NativeMessagesRequest
|
|
|
|
| 11 |
from free_claude_code.core.json_types import JsonObject
|
| 12 |
from free_claude_code.core.openai_responses import OpenAIResponsesRequest
|
| 13 |
from free_claude_code.core.reasoning import ReasoningPolicy
|
|
@@ -19,6 +20,19 @@ from .model_metadata import ProviderModelInfo
|
|
| 19 |
class ProviderPort(Protocol):
|
| 20 |
"""Minimal provider capability required to execute one request."""
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
def stream_native_messages(
|
| 23 |
self,
|
| 24 |
request: NativeMessagesRequest,
|
|
@@ -127,7 +141,9 @@ class RequestRuntimePort(ModelCatalogPort, Protocol):
|
|
| 127 |
|
| 128 |
async def acquire(self) -> RequestRuntimeLease: ...
|
| 129 |
|
| 130 |
-
|
|
|
|
|
|
|
| 131 |
|
| 132 |
def catalog_status(self) -> JsonObject: ...
|
| 133 |
|
|
|
|
| 8 |
from free_claude_code.config.settings import Settings
|
| 9 |
from free_claude_code.core.anthropic import MessagesRequest
|
| 10 |
from free_claude_code.core.anthropic.passthrough import NativeMessagesRequest
|
| 11 |
+
from free_claude_code.core.gemini import GeminiRequest
|
| 12 |
from free_claude_code.core.json_types import JsonObject
|
| 13 |
from free_claude_code.core.openai_responses import OpenAIResponsesRequest
|
| 14 |
from free_claude_code.core.reasoning import ReasoningPolicy
|
|
|
|
| 20 |
class ProviderPort(Protocol):
|
| 21 |
"""Minimal provider capability required to execute one request."""
|
| 22 |
|
| 23 |
+
def stream_gemini(
|
| 24 |
+
self,
|
| 25 |
+
request: GeminiRequest,
|
| 26 |
+
*,
|
| 27 |
+
input_tokens: int,
|
| 28 |
+
request_id: str,
|
| 29 |
+
response_model: str,
|
| 30 |
+
reasoning: ReasoningPolicy,
|
| 31 |
+
request_headers: Mapping[str, str] | None = None,
|
| 32 |
+
model_info: ProviderModelInfo | None = None,
|
| 33 |
+
continuation: ContinuationSeed | None = None,
|
| 34 |
+
) -> AsyncIterator[str]: ...
|
| 35 |
+
|
| 36 |
def stream_native_messages(
|
| 37 |
self,
|
| 38 |
request: NativeMessagesRequest,
|
|
|
|
| 141 |
|
| 142 |
async def acquire(self) -> RequestRuntimeLease: ...
|
| 143 |
|
| 144 |
+
def catalog_snapshot(self) -> ModelCatalogSnapshot: ...
|
| 145 |
+
|
| 146 |
+
async def wait_for_model_catalog(self, model: str) -> ModelCatalogSnapshot: ...
|
| 147 |
|
| 148 |
def catalog_status(self) -> JsonObject: ...
|
| 149 |
|
src/free_claude_code/application/reasoning.py
CHANGED
|
@@ -5,6 +5,7 @@ from collections.abc import Mapping
|
|
| 5 |
|
| 6 |
from free_claude_code.config.reasoning import ReasoningPreference
|
| 7 |
from free_claude_code.core.anthropic.models import MessagesRequest, ThinkingConfig
|
|
|
|
| 8 |
from free_claude_code.core.openai_responses import (
|
| 9 |
OpenAIResponsesRequest,
|
| 10 |
responses_reasoning_policy,
|
|
@@ -58,9 +59,16 @@ def resolve_fallback_reasoning(
|
|
| 58 |
return _apply_reasoning_preference(original, preference)
|
| 59 |
|
| 60 |
|
| 61 |
-
def
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
"""Copy a candidate and remove computation controls replaced by its policy."""
|
| 65 |
|
| 66 |
request = original.model_copy(update={"model": model}, deep=True)
|
|
@@ -76,6 +84,10 @@ def prepare_fallback_request[T: MessagesRequest | OpenAIResponsesRequest](
|
|
| 76 |
)
|
| 77 |
if request.output_config is not None:
|
| 78 |
request.output_config.pop("effort", None)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
elif request.reasoning is not None:
|
| 80 |
request.reasoning.pop("effort", None)
|
| 81 |
return request
|
|
|
|
| 5 |
|
| 6 |
from free_claude_code.config.reasoning import ReasoningPreference
|
| 7 |
from free_claude_code.core.anthropic.models import MessagesRequest, ThinkingConfig
|
| 8 |
+
from free_claude_code.core.gemini import GeminiRequest
|
| 9 |
from free_claude_code.core.openai_responses import (
|
| 10 |
OpenAIResponsesRequest,
|
| 11 |
responses_reasoning_policy,
|
|
|
|
| 59 |
return _apply_reasoning_preference(original, preference)
|
| 60 |
|
| 61 |
|
| 62 |
+
def resolve_gemini_reasoning_policy(
|
| 63 |
+
request: GeminiRequest,
|
| 64 |
+
preference: ReasoningPreference,
|
| 65 |
+
) -> ReasoningPolicy:
|
| 66 |
+
return _apply_reasoning_preference(request.reasoning_policy(), preference)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def prepare_fallback_request[
|
| 70 |
+
T: MessagesRequest | OpenAIResponsesRequest | GeminiRequest
|
| 71 |
+
](original: T, *, model: str, preference: ReasoningPreference) -> T:
|
| 72 |
"""Copy a candidate and remove computation controls replaced by its policy."""
|
| 73 |
|
| 74 |
request = original.model_copy(update={"model": model}, deep=True)
|
|
|
|
| 84 |
)
|
| 85 |
if request.output_config is not None:
|
| 86 |
request.output_config.pop("effort", None)
|
| 87 |
+
elif isinstance(request, GeminiRequest):
|
| 88 |
+
thinking = request.generation_config.thinking_config
|
| 89 |
+
thinking.thinking_budget = None
|
| 90 |
+
thinking.thinking_level = None
|
| 91 |
elif request.reasoning is not None:
|
| 92 |
request.reasoning.pop("effort", None)
|
| 93 |
return request
|
src/free_claude_code/application/routing.py
CHANGED
|
@@ -13,6 +13,7 @@ from free_claude_code.config.model_refs import (
|
|
| 13 |
is_retired_model_ref,
|
| 14 |
parse_model_name,
|
| 15 |
parse_provider_type,
|
|
|
|
| 16 |
)
|
| 17 |
from free_claude_code.config.provider_catalog import PROVIDER_CATALOG
|
| 18 |
from free_claude_code.config.reasoning import ReasoningPreference
|
|
@@ -28,11 +29,16 @@ from free_claude_code.core.gateway_model_ids import (
|
|
| 28 |
DESKTOP_NO_THINKING_PREFIX,
|
| 29 |
decode_gateway_model_id,
|
| 30 |
)
|
|
|
|
| 31 |
from free_claude_code.core.openai_responses import OpenAIResponsesRequest
|
| 32 |
from free_claude_code.core.reasoning import ReasoningPolicy
|
| 33 |
from free_claude_code.core.trace import trace_event
|
| 34 |
|
| 35 |
-
from .reasoning import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
_ROUTE_SETTINGS = (
|
| 38 |
("fable", "model_fable", "reasoning_fable"),
|
|
@@ -98,6 +104,13 @@ class RoutedResponsesRequest:
|
|
| 98 |
reasoning: ReasoningPolicy
|
| 99 |
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
@dataclass(frozen=True, slots=True)
|
| 102 |
class RoutedTokenCountRequest:
|
| 103 |
request: TokenCountRequest | NativeTokenCountRequest
|
|
@@ -211,6 +224,13 @@ class ModelRouter:
|
|
| 211 |
parse_model_name(self._settings.model),
|
| 212 |
decoded.force_reasoning_off if decoded is not None else False,
|
| 213 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
if decoded is not None:
|
| 215 |
if decoded.provider_id not in self._settings.provider_ids:
|
| 216 |
if decoded.provider_id.startswith("custom_") or model_name.partition(
|
|
@@ -362,3 +382,15 @@ class ModelRouter:
|
|
| 362 |
resolved.reasoning_preference,
|
| 363 |
),
|
| 364 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
is_retired_model_ref,
|
| 14 |
parse_model_name,
|
| 15 |
parse_provider_type,
|
| 16 |
+
replace_retired_model_ref,
|
| 17 |
)
|
| 18 |
from free_claude_code.config.provider_catalog import PROVIDER_CATALOG
|
| 19 |
from free_claude_code.config.reasoning import ReasoningPreference
|
|
|
|
| 29 |
DESKTOP_NO_THINKING_PREFIX,
|
| 30 |
decode_gateway_model_id,
|
| 31 |
)
|
| 32 |
+
from free_claude_code.core.gemini import GeminiRequest
|
| 33 |
from free_claude_code.core.openai_responses import OpenAIResponsesRequest
|
| 34 |
from free_claude_code.core.reasoning import ReasoningPolicy
|
| 35 |
from free_claude_code.core.trace import trace_event
|
| 36 |
|
| 37 |
+
from .reasoning import (
|
| 38 |
+
resolve_gemini_reasoning_policy,
|
| 39 |
+
resolve_reasoning_policy,
|
| 40 |
+
resolve_responses_reasoning_policy,
|
| 41 |
+
)
|
| 42 |
|
| 43 |
_ROUTE_SETTINGS = (
|
| 44 |
("fable", "model_fable", "reasoning_fable"),
|
|
|
|
| 104 |
reasoning: ReasoningPolicy
|
| 105 |
|
| 106 |
|
| 107 |
+
@dataclass(frozen=True, slots=True)
|
| 108 |
+
class RoutedGeminiRequest:
|
| 109 |
+
request: GeminiRequest
|
| 110 |
+
resolved: ResolvedModelRoute
|
| 111 |
+
reasoning: ReasoningPolicy
|
| 112 |
+
|
| 113 |
+
|
| 114 |
@dataclass(frozen=True, slots=True)
|
| 115 |
class RoutedTokenCountRequest:
|
| 116 |
request: TokenCountRequest | NativeTokenCountRequest
|
|
|
|
| 224 |
parse_model_name(self._settings.model),
|
| 225 |
decoded.force_reasoning_off if decoded is not None else False,
|
| 226 |
)
|
| 227 |
+
replacement = replace_retired_model_ref(candidate)
|
| 228 |
+
if replacement != candidate:
|
| 229 |
+
return (
|
| 230 |
+
parse_provider_type(replacement),
|
| 231 |
+
parse_model_name(replacement),
|
| 232 |
+
decoded.force_reasoning_off if decoded is not None else False,
|
| 233 |
+
)
|
| 234 |
if decoded is not None:
|
| 235 |
if decoded.provider_id not in self._settings.provider_ids:
|
| 236 |
if decoded.provider_id.startswith("custom_") or model_name.partition(
|
|
|
|
| 382 |
resolved.reasoning_preference,
|
| 383 |
),
|
| 384 |
)
|
| 385 |
+
|
| 386 |
+
def resolve_gemini_request(self, request: GeminiRequest) -> RoutedGeminiRequest:
|
| 387 |
+
resolved = self.resolve(request.model)
|
| 388 |
+
return RoutedGeminiRequest(
|
| 389 |
+
request=request.model_copy(
|
| 390 |
+
update={"model": resolved.primary.provider_model}, deep=True
|
| 391 |
+
),
|
| 392 |
+
resolved=resolved,
|
| 393 |
+
reasoning=resolve_gemini_reasoning_policy(
|
| 394 |
+
request, resolved.reasoning_preference
|
| 395 |
+
),
|
| 396 |
+
)
|
src/free_claude_code/cli/desktop_entrypoint.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
"""Lightweight entrypoint for the optional FCC desktop shell."""
|
| 3 |
|
|
|
|
| 4 |
import sys
|
| 5 |
from collections.abc import Sequence
|
| 6 |
from pathlib import Path
|
|
@@ -16,6 +17,15 @@ def launch(argv: Sequence[str] | None = None) -> None:
|
|
| 16 |
if len(args) == 2 and args[0] == "--export-icon":
|
| 17 |
export_app_icon(Path(args[1]))
|
| 18 |
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
auto_started = args == ("--auto-started",)
|
| 20 |
if args and not auto_started:
|
| 21 |
print("Usage: fcc-desktop [--export-icon PATH]", file=sys.stderr)
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
"""Lightweight entrypoint for the optional FCC desktop shell."""
|
| 3 |
|
| 4 |
+
import subprocess
|
| 5 |
import sys
|
| 6 |
from collections.abc import Sequence
|
| 7 |
from pathlib import Path
|
|
|
|
| 17 |
if len(args) == 2 and args[0] == "--export-icon":
|
| 18 |
export_app_icon(Path(args[1]))
|
| 19 |
return
|
| 20 |
+
if args == ("--install-macos-app",) and sys.platform == "darwin":
|
| 21 |
+
from free_claude_code.cli.macos_app import install
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
install()
|
| 25 |
+
except (OSError, ValueError, subprocess.CalledProcessError) as error:
|
| 26 |
+
print(f"Could not install the macOS app: {error}", file=sys.stderr)
|
| 27 |
+
raise SystemExit(1) from error
|
| 28 |
+
return
|
| 29 |
auto_started = args == ("--auto-started",)
|
| 30 |
if args and not auto_started:
|
| 31 |
print("Usage: fcc-desktop [--export-icon PATH]", file=sys.stderr)
|
src/free_claude_code/cli/doctor.py
CHANGED
|
@@ -12,10 +12,29 @@ from .clipboard import ClipboardUnavailable, copy_text
|
|
| 12 |
|
| 13 |
|
| 14 |
def main(argv: Sequence[str] | None = None) -> None:
|
| 15 |
-
argparse.ArgumentParser(
|
| 16 |
prog="fcc-doctor",
|
| 17 |
description="Print and copy FCC diagnostics for a bug report.",
|
| 18 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
text = json.dumps(collect_report(), indent=2, ensure_ascii=False) + "\n"
|
| 20 |
sys.stdout.write(text)
|
| 21 |
try:
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
def main(argv: Sequence[str] | None = None) -> None:
|
| 15 |
+
parser = argparse.ArgumentParser(
|
| 16 |
prog="fcc-doctor",
|
| 17 |
description="Print and copy FCC diagnostics for a bug report.",
|
| 18 |
+
)
|
| 19 |
+
parser.add_argument(
|
| 20 |
+
"--disconnect-integrations",
|
| 21 |
+
action="store_true",
|
| 22 |
+
help="Disconnect recognized FCC editor/app integrations before uninstalling.",
|
| 23 |
+
)
|
| 24 |
+
args = parser.parse_args(argv)
|
| 25 |
+
if args.disconnect_integrations:
|
| 26 |
+
from free_claude_code.harnesses.integration_cleanup import (
|
| 27 |
+
IntegrationCleanupError,
|
| 28 |
+
disconnect_integrations,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
disconnect_integrations()
|
| 33 |
+
except IntegrationCleanupError as exc:
|
| 34 |
+
print(str(exc), file=sys.stderr)
|
| 35 |
+
raise SystemExit(1) from None
|
| 36 |
+
print("Disconnected recognized FCC editor/app integrations.")
|
| 37 |
+
return
|
| 38 |
text = json.dumps(collect_report(), indent=2, ensure_ascii=False) + "\n"
|
| 39 |
sys.stdout.write(text)
|
| 40 |
try:
|
src/free_claude_code/cli/launchers/agy.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
"""Installed Antigravity CLI launcher with an explicit native FCC connection."""
|
| 3 |
+
|
| 4 |
+
import re
|
| 5 |
+
import sys
|
| 6 |
+
from collections.abc import Sequence
|
| 7 |
+
|
| 8 |
+
from free_claude_code.config.loader import get_settings
|
| 9 |
+
from free_claude_code.config.server_urls import local_admin_url
|
| 10 |
+
from free_claude_code.harnesses import antigravity_integration
|
| 11 |
+
from free_claude_code.harnesses.environment import client_environment
|
| 12 |
+
from free_claude_code.harnesses.launch import NativeCheck, PreparedLaunch
|
| 13 |
+
from free_claude_code.harnesses.resources import LaunchResources
|
| 14 |
+
|
| 15 |
+
from .catalog_http import fetch_proxy_model_catalog
|
| 16 |
+
from .runner import (
|
| 17 |
+
HarnessSpec,
|
| 18 |
+
LaunchContext,
|
| 19 |
+
LaunchError,
|
| 20 |
+
launch_harness,
|
| 21 |
+
version_at_least,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
_VERSION_PATTERN = re.compile(r"(?m)^\s*(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?\s*$")
|
| 25 |
+
_INSTALL_HINT = (
|
| 26 |
+
"Install Antigravity CLI with `irm https://antigravity.google/cli/install.ps1 | iex` "
|
| 27 |
+
"on Windows or `curl -fsSL https://antigravity.google/cli/install.sh | bash` "
|
| 28 |
+
"on macOS/Linux. Upgrade an existing installation with: agy update"
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _configure(
|
| 33 |
+
ctx: LaunchContext, args: list[str], _files: LaunchResources
|
| 34 |
+
) -> PreparedLaunch:
|
| 35 |
+
admin_url = ctx.proxy_root_url.rstrip("/") + "/admin/integrations"
|
| 36 |
+
path = antigravity_integration.config_path()
|
| 37 |
+
state = antigravity_integration.state_path()
|
| 38 |
+
try:
|
| 39 |
+
if not antigravity_integration.status(path, state)["connected"]:
|
| 40 |
+
raise antigravity_integration.DisconnectedError()
|
| 41 |
+
catalog = fetch_proxy_model_catalog(ctx.proxy_root_url, ctx.auth_token)
|
| 42 |
+
antigravity_integration.configure(path, state, catalog)
|
| 43 |
+
except antigravity_integration.DisconnectedError as exc:
|
| 44 |
+
raise LaunchError(
|
| 45 |
+
f"{exc}\nConnect it on the Integrations page first:\n{admin_url}"
|
| 46 |
+
) from None
|
| 47 |
+
if args and not args[0].startswith("-"):
|
| 48 |
+
# Native subcommands dispatch before the session flag parser.
|
| 49 |
+
command = [ctx.binary_path, *args]
|
| 50 |
+
else:
|
| 51 |
+
command = [ctx.binary_path, "--model", catalog.default_model_id, *args]
|
| 52 |
+
return PreparedLaunch(
|
| 53 |
+
command,
|
| 54 |
+
client_environment(
|
| 55 |
+
ctx.base_env,
|
| 56 |
+
proxy_root_url=ctx.proxy_root_url,
|
| 57 |
+
updates={
|
| 58 |
+
"GEMINI_API_KEY": ctx.auth_token,
|
| 59 |
+
"GOOGLE_GEMINI_BASE_URL": ctx.proxy_root_url.rstrip("/"),
|
| 60 |
+
},
|
| 61 |
+
),
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
SPEC = HarnessSpec(
|
| 66 |
+
binary_name="agy",
|
| 67 |
+
display_name="Antigravity CLI",
|
| 68 |
+
install_hint=_INSTALL_HINT,
|
| 69 |
+
configure=_configure,
|
| 70 |
+
compatibility_check=NativeCheck(
|
| 71 |
+
("--version",),
|
| 72 |
+
lambda output: version_at_least(output, _VERSION_PATTERN, (1, 4, 7)),
|
| 73 |
+
"FCC requires Antigravity CLI 1.4.7 or newer.",
|
| 74 |
+
),
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def launch(argv: Sequence[str] | None = None) -> None:
|
| 79 |
+
args = list(sys.argv[1:] if argv is None else argv)
|
| 80 |
+
if args in (["--connect"], ["--disconnect"]):
|
| 81 |
+
try:
|
| 82 |
+
url = local_admin_url(get_settings()) + "/integrations"
|
| 83 |
+
except (OSError, ValueError):
|
| 84 |
+
print(
|
| 85 |
+
"Could not load FCC settings. Run fcc-server to check the configuration.",
|
| 86 |
+
file=sys.stderr,
|
| 87 |
+
)
|
| 88 |
+
else:
|
| 89 |
+
print(
|
| 90 |
+
"Manage the Antigravity CLI connection on the Integrations page:\n"
|
| 91 |
+
f"{url}\nStart FCC with fcc-server if it is not running.",
|
| 92 |
+
file=sys.stderr,
|
| 93 |
+
)
|
| 94 |
+
raise SystemExit(1)
|
| 95 |
+
launch_harness(SPEC, args)
|
src/free_claude_code/cli/launchers/opencode_config.py
CHANGED
|
@@ -40,6 +40,9 @@ def build_opencode_config(
|
|
| 40 |
"settings": {
|
| 41 |
"baseURL": proxy_v1_url(proxy_root_url),
|
| 42 |
"apiKey": f"{{env:{OPENCODE_API_KEY_ENV}}}",
|
|
|
|
|
|
|
|
|
|
| 43 |
},
|
| 44 |
}
|
| 45 |
default_model = f"{OPENCODE_PROVIDER_ID}/{default_model_id}"
|
|
|
|
| 40 |
"settings": {
|
| 41 |
"baseURL": proxy_v1_url(proxy_root_url),
|
| 42 |
"apiKey": f"{{env:{OPENCODE_API_KEY_ENV}}}",
|
| 43 |
+
"headerTimeout": False,
|
| 44 |
+
"chunkTimeout": False,
|
| 45 |
+
"timeout": False,
|
| 46 |
},
|
| 47 |
}
|
| 48 |
default_model = f"{OPENCODE_PROVIDER_ID}/{default_model_id}"
|
src/free_claude_code/cli/macos_app.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
"""Construct the macOS application around the installed managed Python runtime."""
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import platform
|
| 6 |
+
import plistlib
|
| 7 |
+
import shutil
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import sysconfig
|
| 11 |
+
import tempfile
|
| 12 |
+
from importlib.metadata import metadata
|
| 13 |
+
from importlib.resources import files
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
from packaging.specifiers import SpecifierSet
|
| 17 |
+
|
| 18 |
+
from free_claude_code.cli.desktop_assets import export_app_icon
|
| 19 |
+
|
| 20 |
+
BUNDLE_ID = "io.github.alishahryar1.free-claude-code"
|
| 21 |
+
OWNER_FILE = ".free-claude-code-owner"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def runtime_settings() -> tuple[dict[str, str], str]:
|
| 25 |
+
"""Keep the venv executable while locating the standalone runtime's library."""
|
| 26 |
+
if (
|
| 27 |
+
platform.python_implementation() != "CPython"
|
| 28 |
+
or sysconfig.get_config_var("Py_GIL_DISABLED")
|
| 29 |
+
or sysconfig.get_config_var("Py_DEBUG")
|
| 30 |
+
):
|
| 31 |
+
raise ValueError(
|
| 32 |
+
"The desktop app requires a GIL-enabled CPython release build."
|
| 33 |
+
)
|
| 34 |
+
version = platform.python_version()
|
| 35 |
+
requirement = metadata("free-claude-code")["Requires-Python"]
|
| 36 |
+
if not requirement or version not in SpecifierSet(requirement):
|
| 37 |
+
raise ValueError(
|
| 38 |
+
"The installed Python version does not match Free Claude Code."
|
| 39 |
+
)
|
| 40 |
+
architecture = platform.machine()
|
| 41 |
+
if architecture not in {"arm64", "x86_64"}:
|
| 42 |
+
raise ValueError(f"Unsupported macOS Python architecture: {architecture}")
|
| 43 |
+
# Do not resolve this symlink: CPython needs its venv path for pyvenv.cfg.
|
| 44 |
+
executable = Path(sys.executable).absolute()
|
| 45 |
+
if not executable.is_file() or not os.access(executable, os.X_OK):
|
| 46 |
+
raise ValueError("The installed Python executable is missing or inaccessible.")
|
| 47 |
+
library_name = sysconfig.get_config_var("LDLIBRARY")
|
| 48 |
+
if not isinstance(library_name, str) or Path(library_name).name != library_name:
|
| 49 |
+
raise ValueError("The managed Python shared library is unavailable.")
|
| 50 |
+
library = Path(sys.base_prefix) / "lib" / library_name
|
| 51 |
+
if not library.is_file():
|
| 52 |
+
raise ValueError(f"The managed Python shared library is missing: {library}")
|
| 53 |
+
return {
|
| 54 |
+
"PythonExecutable": str(executable),
|
| 55 |
+
"PythonLibrary": str(library.absolute()),
|
| 56 |
+
"PythonVersion": version,
|
| 57 |
+
}, architecture
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def is_owned(app: Path) -> bool:
|
| 61 |
+
if app.is_symlink() or not app.is_dir():
|
| 62 |
+
return False
|
| 63 |
+
# Existing shell bundles used Contents directly. Signed bundles use Resources.
|
| 64 |
+
for directory in (app / "Contents/Resources", app / "Contents"):
|
| 65 |
+
marker = directory / OWNER_FILE
|
| 66 |
+
if marker.is_file() and marker.read_text(encoding="utf-8").strip() == BUNDLE_ID:
|
| 67 |
+
return True
|
| 68 |
+
return False
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def install() -> Path:
|
| 72 |
+
"""Sign a complete sibling bundle before replacing an FCC-owned application."""
|
| 73 |
+
if sys.platform != "darwin":
|
| 74 |
+
raise ValueError("Application installation is supported only on macOS.")
|
| 75 |
+
home = Path.home()
|
| 76 |
+
app = home / "Applications/Free Claude Code.app"
|
| 77 |
+
if (app.exists() or app.is_symlink()) and not is_owned(app):
|
| 78 |
+
raise ValueError(
|
| 79 |
+
f"An app not managed by Free Claude Code already exists at {app}."
|
| 80 |
+
)
|
| 81 |
+
settings, architecture = runtime_settings()
|
| 82 |
+
template = (
|
| 83 |
+
files("free_claude_code")
|
| 84 |
+
.joinpath("assets", "macos", f"fcc-desktop-{architecture}")
|
| 85 |
+
.read_bytes()
|
| 86 |
+
)
|
| 87 |
+
app.parent.mkdir(parents=True, exist_ok=True)
|
| 88 |
+
root = Path(tempfile.mkdtemp(prefix=".fcc-app-", dir=app.parent))
|
| 89 |
+
backup = root / "previous.app"
|
| 90 |
+
published = False
|
| 91 |
+
try:
|
| 92 |
+
staged = root / app.name
|
| 93 |
+
contents = staged / "Contents"
|
| 94 |
+
resources = contents / "Resources"
|
| 95 |
+
resources.mkdir(parents=True)
|
| 96 |
+
(contents / "MacOS").mkdir()
|
| 97 |
+
executable = contents / "MacOS/fcc-desktop"
|
| 98 |
+
executable.write_bytes(template)
|
| 99 |
+
executable.chmod(0o755)
|
| 100 |
+
export_app_icon(resources / "AppIcon.icns")
|
| 101 |
+
(resources / OWNER_FILE).write_text(BUNDLE_ID + "\n", encoding="utf-8")
|
| 102 |
+
with (resources / "runtime.plist").open("wb") as stream:
|
| 103 |
+
plistlib.dump(settings, stream)
|
| 104 |
+
with (contents / "Info.plist").open("wb") as stream:
|
| 105 |
+
plistlib.dump(
|
| 106 |
+
{
|
| 107 |
+
"CFBundleDisplayName": "Free Claude Code",
|
| 108 |
+
"CFBundleExecutable": "fcc-desktop",
|
| 109 |
+
"CFBundleIdentifier": BUNDLE_ID,
|
| 110 |
+
"CFBundleIconFile": "AppIcon",
|
| 111 |
+
"CFBundleName": "Free Claude Code",
|
| 112 |
+
"CFBundlePackageType": "APPL",
|
| 113 |
+
"LSMultipleInstancesProhibited": True,
|
| 114 |
+
"LSUIElement": True,
|
| 115 |
+
},
|
| 116 |
+
stream,
|
| 117 |
+
)
|
| 118 |
+
subprocess.run(
|
| 119 |
+
["/usr/bin/codesign", "--force", "--sign", "-", str(staged)], check=True
|
| 120 |
+
)
|
| 121 |
+
subprocess.run(
|
| 122 |
+
["/usr/bin/codesign", "--verify", "--strict", str(staged)], check=True
|
| 123 |
+
)
|
| 124 |
+
if app.exists():
|
| 125 |
+
app.rename(backup)
|
| 126 |
+
try:
|
| 127 |
+
staged.rename(app)
|
| 128 |
+
except OSError:
|
| 129 |
+
if backup.exists():
|
| 130 |
+
backup.rename(app)
|
| 131 |
+
raise
|
| 132 |
+
published = True
|
| 133 |
+
finally:
|
| 134 |
+
if published or not backup.exists():
|
| 135 |
+
shutil.rmtree(root)
|
| 136 |
+
else:
|
| 137 |
+
print(
|
| 138 |
+
f"The previous application is preserved at {backup}.", file=sys.stderr
|
| 139 |
+
)
|
| 140 |
+
desktop = home / "Desktop/Free Claude Code.app"
|
| 141 |
+
desktop.parent.mkdir(parents=True, exist_ok=True)
|
| 142 |
+
if desktop.is_symlink() and desktop.readlink() == app:
|
| 143 |
+
return app
|
| 144 |
+
if desktop.exists() or desktop.is_symlink():
|
| 145 |
+
print(f"A non-FCC item already exists at {desktop}; leaving it unchanged.")
|
| 146 |
+
else:
|
| 147 |
+
desktop.symlink_to(app, target_is_directory=True)
|
| 148 |
+
return app
|
src/free_claude_code/cli/uvicorn_server.py
CHANGED
|
@@ -1,18 +1,46 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
"""Uvicorn adapter imported only by the server worker."""
|
| 3 |
|
|
|
|
| 4 |
import socket
|
| 5 |
from collections.abc import Awaitable, Callable
|
| 6 |
from copy import deepcopy
|
|
|
|
| 7 |
|
| 8 |
import uvicorn
|
| 9 |
|
| 10 |
from free_claude_code.config.logging_config import InterceptHandler
|
| 11 |
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
def uvicorn_log_config(*, console: bool) -> dict[str, object]:
|
| 14 |
"""Send Uvicorn records to FCC's file and optional standard console handlers."""
|
| 15 |
config = deepcopy(uvicorn.config.LOGGING_CONFIG)
|
|
|
|
|
|
|
| 16 |
if not console:
|
| 17 |
config["formatters"] = {}
|
| 18 |
config["handlers"] = {}
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
"""Uvicorn adapter imported only by the server worker."""
|
| 3 |
|
| 4 |
+
import logging
|
| 5 |
import socket
|
| 6 |
from collections.abc import Awaitable, Callable
|
| 7 |
from copy import deepcopy
|
| 8 |
+
from urllib.parse import parse_qsl, urlencode
|
| 9 |
|
| 10 |
import uvicorn
|
| 11 |
|
| 12 |
from free_claude_code.config.logging_config import InterceptHandler
|
| 13 |
|
| 14 |
|
| 15 |
+
class QueryCredentialFilter(logging.Filter):
|
| 16 |
+
"""Mask query API keys before either Uvicorn output handler sees them."""
|
| 17 |
+
|
| 18 |
+
def filter(self, record: logging.LogRecord) -> bool:
|
| 19 |
+
if (
|
| 20 |
+
record.name == "uvicorn.access"
|
| 21 |
+
and isinstance(record.args, tuple)
|
| 22 |
+
and len(record.args) == 5
|
| 23 |
+
):
|
| 24 |
+
address, method, target, version, status = record.args
|
| 25 |
+
if isinstance(target, str) and "?" in target:
|
| 26 |
+
path, _, query = target.partition("?")
|
| 27 |
+
pairs = parse_qsl(query, keep_blank_values=True)
|
| 28 |
+
if any(key == "key" for key, _ in pairs):
|
| 29 |
+
query = urlencode(
|
| 30 |
+
[
|
| 31 |
+
(key, "[REDACTED]" if key == "key" else value)
|
| 32 |
+
for key, value in pairs
|
| 33 |
+
]
|
| 34 |
+
)
|
| 35 |
+
record.args = (address, method, f"{path}?{query}", version, status)
|
| 36 |
+
return True
|
| 37 |
+
|
| 38 |
+
|
| 39 |
def uvicorn_log_config(*, console: bool) -> dict[str, object]:
|
| 40 |
"""Send Uvicorn records to FCC's file and optional standard console handlers."""
|
| 41 |
config = deepcopy(uvicorn.config.LOGGING_CONFIG)
|
| 42 |
+
config["filters"] = {"query_credentials": {"()": QueryCredentialFilter}}
|
| 43 |
+
config["loggers"]["uvicorn.access"]["filters"] = ["query_credentials"]
|
| 44 |
if not console:
|
| 45 |
config["formatters"] = {}
|
| 46 |
config["handlers"] = {}
|
src/free_claude_code/config/admin/manifest.py
CHANGED
|
@@ -388,46 +388,6 @@ _NON_PROVIDER_FIELDS: tuple[ConfigFieldSpec, ...] = (
|
|
| 388 |
settings_attr="whisper_model",
|
| 389 |
session_sensitive=True,
|
| 390 |
),
|
| 391 |
-
ConfigFieldSpec(
|
| 392 |
-
"FAST_PREFIX_DETECTION",
|
| 393 |
-
"Fast Prefix Detection",
|
| 394 |
-
"runtime",
|
| 395 |
-
"boolean",
|
| 396 |
-
settings_attr="fast_prefix_detection",
|
| 397 |
-
advanced=True,
|
| 398 |
-
),
|
| 399 |
-
ConfigFieldSpec(
|
| 400 |
-
"ENABLE_NETWORK_PROBE_MOCK",
|
| 401 |
-
"Network Probe Mock",
|
| 402 |
-
"runtime",
|
| 403 |
-
"boolean",
|
| 404 |
-
settings_attr="enable_network_probe_mock",
|
| 405 |
-
advanced=True,
|
| 406 |
-
),
|
| 407 |
-
ConfigFieldSpec(
|
| 408 |
-
"ENABLE_TITLE_GENERATION_SKIP",
|
| 409 |
-
"Title Generation Skip",
|
| 410 |
-
"runtime",
|
| 411 |
-
"boolean",
|
| 412 |
-
settings_attr="enable_title_generation_skip",
|
| 413 |
-
advanced=True,
|
| 414 |
-
),
|
| 415 |
-
ConfigFieldSpec(
|
| 416 |
-
"ENABLE_SUGGESTION_MODE_SKIP",
|
| 417 |
-
"Suggestion Mode Skip",
|
| 418 |
-
"runtime",
|
| 419 |
-
"boolean",
|
| 420 |
-
settings_attr="enable_suggestion_mode_skip",
|
| 421 |
-
advanced=True,
|
| 422 |
-
),
|
| 423 |
-
ConfigFieldSpec(
|
| 424 |
-
"ENABLE_FILEPATH_EXTRACTION_MOCK",
|
| 425 |
-
"Filepath Extraction Mock",
|
| 426 |
-
"runtime",
|
| 427 |
-
"boolean",
|
| 428 |
-
settings_attr="enable_filepath_extraction_mock",
|
| 429 |
-
advanced=True,
|
| 430 |
-
),
|
| 431 |
ConfigFieldSpec(
|
| 432 |
"ENABLE_WEB_SERVER_TOOLS",
|
| 433 |
"Web Server Tools",
|
|
|
|
| 388 |
settings_attr="whisper_model",
|
| 389 |
session_sensitive=True,
|
| 390 |
),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 391 |
ConfigFieldSpec(
|
| 392 |
"ENABLE_WEB_SERVER_TOOLS",
|
| 393 |
"Web Server Tools",
|
src/free_claude_code/config/admin/provider_manifest.py
CHANGED
|
@@ -20,7 +20,7 @@ class ProviderFieldOverride(TypedDict, total=False):
|
|
| 20 |
|
| 21 |
_PROVIDER_FIELD_OVERRIDES: dict[str, ProviderFieldOverride] = {
|
| 22 |
"ANTHROPIC_API_KEY": {
|
| 23 |
-
"description": "Anthropic API access with separate usage billing. Messages requests use Anthropic tools and client thinking controls. Native fallback uses other Anthropic models. FCC local web
|
| 24 |
},
|
| 25 |
"OPENAI_API_KEY": {
|
| 26 |
"label": "OpenAI API Keys",
|
|
@@ -28,7 +28,8 @@ _PROVIDER_FIELD_OVERRIDES: dict[str, ProviderFieldOverride] = {
|
|
| 28 |
},
|
| 29 |
"OPENAI_PROXY": {
|
| 30 |
"description": (
|
| 31 |
-
"Optional proxy
|
|
|
|
| 32 |
"Changing it restarts FCC."
|
| 33 |
),
|
| 34 |
"restart_required": True,
|
|
@@ -475,6 +476,7 @@ def _proxy_field_specs() -> tuple[ConfigFieldSpec, ...]:
|
|
| 475 |
ConfigFieldSpec(
|
| 476 |
key=_settings_env_key(descriptor.proxy_attr),
|
| 477 |
label=f"{descriptor.display_name} Proxy",
|
|
|
|
| 478 |
section_id="providers",
|
| 479 |
field_type="secret",
|
| 480 |
settings_attr=descriptor.proxy_attr,
|
|
|
|
| 20 |
|
| 21 |
_PROVIDER_FIELD_OVERRIDES: dict[str, ProviderFieldOverride] = {
|
| 22 |
"ANTHROPIC_API_KEY": {
|
| 23 |
+
"description": "Anthropic API access with separate usage billing. Messages requests use Anthropic tools and client thinking controls. Native fallback uses other Anthropic models. FCC local web tools apply to compatibility routes.",
|
| 24 |
},
|
| 25 |
"OPENAI_API_KEY": {
|
| 26 |
"label": "OpenAI API Keys",
|
|
|
|
| 28 |
},
|
| 29 |
"OPENAI_PROXY": {
|
| 30 |
"description": (
|
| 31 |
+
"Optional network proxy. Leave blank unless you use one. "
|
| 32 |
+
"Used for OpenAI sign-in and ChatGPT Codex requests. "
|
| 33 |
"Changing it restarts FCC."
|
| 34 |
),
|
| 35 |
"restart_required": True,
|
|
|
|
| 476 |
ConfigFieldSpec(
|
| 477 |
key=_settings_env_key(descriptor.proxy_attr),
|
| 478 |
label=f"{descriptor.display_name} Proxy",
|
| 479 |
+
description="Optional network proxy. Leave blank unless you use one",
|
| 480 |
section_id="providers",
|
| 481 |
field_type="secret",
|
| 482 |
settings_attr=descriptor.proxy_attr,
|
src/free_claude_code/config/constants.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
"""Shared defaults used by config models and provider adapters."""
|
| 3 |
|
| 4 |
-
DEFAULT_MODEL = "nvidia_nim/nvidia/nemotron-3-
|
| 5 |
|
| 6 |
# Client context allocation when the provider reports no model limit.
|
| 7 |
DEFAULT_MODEL_CONTEXT_TOKENS = 200_000
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
"""Shared defaults used by config models and provider adapters."""
|
| 3 |
|
| 4 |
+
DEFAULT_MODEL = "nvidia_nim/nvidia/nemotron-3-ultra-550b-a55b"
|
| 5 |
|
| 6 |
# Client context allocation when the provider reports no model limit.
|
| 7 |
DEFAULT_MODEL_CONTEXT_TOKENS = 200_000
|
src/free_claude_code/config/env_migrations.py
CHANGED
|
@@ -141,8 +141,6 @@ def settings_env_keys() -> frozenset[str]:
|
|
| 141 |
|
| 142 |
keys: set[str] = set()
|
| 143 |
for name, field in Settings.model_fields.items():
|
| 144 |
-
if name == "nim":
|
| 145 |
-
continue
|
| 146 |
alias = field.validation_alias
|
| 147 |
if not isinstance(alias, str):
|
| 148 |
raise AssertionError(f"Settings field {name!r} needs one string alias")
|
|
@@ -312,7 +310,7 @@ def _log_model_repairs(before: Mapping[str, str], after: Mapping[str, str]) -> N
|
|
| 312 |
changed = sorted(key for key in before if before[key] != after.get(key))
|
| 313 |
if changed:
|
| 314 |
logger.info(
|
| 315 |
-
"Repaired retired
|
| 316 |
", ".join(changed),
|
| 317 |
)
|
| 318 |
|
|
|
|
| 141 |
|
| 142 |
keys: set[str] = set()
|
| 143 |
for name, field in Settings.model_fields.items():
|
|
|
|
|
|
|
| 144 |
alias = field.validation_alias
|
| 145 |
if not isinstance(alias, str):
|
| 146 |
raise AssertionError(f"Settings field {name!r} needs one string alias")
|
|
|
|
| 310 |
changed = sorted(key for key in before if before[key] != after.get(key))
|
| 311 |
if changed:
|
| 312 |
logger.info(
|
| 313 |
+
"Repaired retired model selections in managed config: {}",
|
| 314 |
", ".join(changed),
|
| 315 |
)
|
| 316 |
|
src/free_claude_code/config/loader.py
CHANGED
|
@@ -2,7 +2,7 @@ from __future__ import annotations
|
|
| 2 |
"""Canonical managed-config loading, precedence, provenance, and caching."""
|
| 3 |
|
| 4 |
import os
|
| 5 |
-
from collections.abc import
|
| 6 |
from contextlib import contextmanager
|
| 7 |
from dataclasses import dataclass
|
| 8 |
from dataclasses import field as dataclass_field
|
|
@@ -66,7 +66,7 @@ class ManagedConfigStore:
|
|
| 66 |
self._lock_path = config_lock_path()
|
| 67 |
|
| 68 |
@contextmanager
|
| 69 |
-
def _storage_lock(self) ->
|
| 70 |
lock = InterprocessFileLock(self._lock_path)
|
| 71 |
if not lock.acquire(wait=True, timeout=10.0):
|
| 72 |
raise TimeoutError(
|
|
@@ -208,8 +208,6 @@ def clear_settings_cache() -> None:
|
|
| 208 |
def _settings_aliases() -> dict[str, str]:
|
| 209 |
aliases: dict[str, str] = {}
|
| 210 |
for name, field in Settings.model_fields.items():
|
| 211 |
-
if name == "nim":
|
| 212 |
-
continue
|
| 213 |
alias = field.validation_alias
|
| 214 |
if not isinstance(alias, str):
|
| 215 |
raise AssertionError(f"Settings field {name!r} needs one string alias")
|
|
|
|
| 2 |
"""Canonical managed-config loading, precedence, provenance, and caching."""
|
| 3 |
|
| 4 |
import os
|
| 5 |
+
from collections.abc import Generator, Mapping
|
| 6 |
from contextlib import contextmanager
|
| 7 |
from dataclasses import dataclass
|
| 8 |
from dataclasses import field as dataclass_field
|
|
|
|
| 66 |
self._lock_path = config_lock_path()
|
| 67 |
|
| 68 |
@contextmanager
|
| 69 |
+
def _storage_lock(self) -> Generator[None]:
|
| 70 |
lock = InterprocessFileLock(self._lock_path)
|
| 71 |
if not lock.acquire(wait=True, timeout=10.0):
|
| 72 |
raise TimeoutError(
|
|
|
|
| 208 |
def _settings_aliases() -> dict[str, str]:
|
| 209 |
aliases: dict[str, str] = {}
|
| 210 |
for name, field in Settings.model_fields.items():
|
|
|
|
|
|
|
| 211 |
alias = field.validation_alias
|
| 212 |
if not isinstance(alias, str):
|
| 213 |
raise AssertionError(f"Settings field {name!r} needs one string alias")
|
src/free_claude_code/config/model_refs.py
CHANGED
|
@@ -22,6 +22,13 @@ from .reasoning import ReasoningPreference
|
|
| 22 |
RETIRED_PROVIDER_IDS = frozenset({"github_models"})
|
| 23 |
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
class ModelFallback(BaseModel):
|
| 26 |
"""One ordered fallback's model, reasoning preference, and key number."""
|
| 27 |
|
|
@@ -98,6 +105,8 @@ def normalize_retired_model_settings(
|
|
| 98 |
normalized[key] = DEFAULT_MODEL if key == "MODEL" else ""
|
| 99 |
else:
|
| 100 |
normalized.pop(key)
|
|
|
|
|
|
|
| 101 |
try:
|
| 102 |
fallbacks = decode_model_fallbacks(normalized.get("MODEL_FALLBACKS"))
|
| 103 |
except ValueError:
|
|
@@ -106,6 +115,18 @@ def normalize_retired_model_settings(
|
|
| 106 |
retained = tuple(
|
| 107 |
entry for entry in fallbacks if not is_retired_model_ref(entry.model)
|
| 108 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
if retained:
|
| 110 |
normalized["MODEL_FALLBACKS"] = encode_model_fallbacks(retained)
|
| 111 |
elif preserve_empty_overrides:
|
|
@@ -125,12 +146,23 @@ class ConfiguredChatModelRef:
|
|
| 125 |
|
| 126 |
|
| 127 |
class ChatModelConfig(Protocol):
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
|
| 136 |
def split_provider_model_ref(model_ref: str) -> tuple[str, str]:
|
|
|
|
| 22 |
RETIRED_PROVIDER_IDS = frozenset({"github_models"})
|
| 23 |
|
| 24 |
|
| 25 |
+
def replace_retired_model_ref(model_ref: str) -> str:
|
| 26 |
+
"""Replace the exact retired hosted endpoint, retaining independent providers."""
|
| 27 |
+
if model_ref.strip() == "nvidia_nim/nvidia/nemotron-3-super-120b-a12b":
|
| 28 |
+
return "nvidia_nim/nvidia/nemotron-3-ultra-550b-a55b"
|
| 29 |
+
return model_ref
|
| 30 |
+
|
| 31 |
+
|
| 32 |
class ModelFallback(BaseModel):
|
| 33 |
"""One ordered fallback's model, reasoning preference, and key number."""
|
| 34 |
|
|
|
|
| 105 |
normalized[key] = DEFAULT_MODEL if key == "MODEL" else ""
|
| 106 |
else:
|
| 107 |
normalized.pop(key)
|
| 108 |
+
elif key in normalized:
|
| 109 |
+
normalized[key] = replace_retired_model_ref(normalized[key])
|
| 110 |
try:
|
| 111 |
fallbacks = decode_model_fallbacks(normalized.get("MODEL_FALLBACKS"))
|
| 112 |
except ValueError:
|
|
|
|
| 115 |
retained = tuple(
|
| 116 |
entry for entry in fallbacks if not is_retired_model_ref(entry.model)
|
| 117 |
)
|
| 118 |
+
original_pairs = [(entry.model, entry.api_key_number) for entry in retained]
|
| 119 |
+
if len(original_pairs) != len(set(original_pairs)):
|
| 120 |
+
return normalized # Settings must still reject pre-existing duplicates.
|
| 121 |
+
migrated: list[ModelFallback] = []
|
| 122 |
+
seen: set[tuple[str, int]] = set()
|
| 123 |
+
for entry in retained:
|
| 124 |
+
model = replace_retired_model_ref(entry.model)
|
| 125 |
+
pair = (model, entry.api_key_number)
|
| 126 |
+
if pair not in seen:
|
| 127 |
+
seen.add(pair)
|
| 128 |
+
migrated.append(entry.model_copy(update={"model": model}))
|
| 129 |
+
retained = tuple(migrated)
|
| 130 |
if retained:
|
| 131 |
normalized["MODEL_FALLBACKS"] = encode_model_fallbacks(retained)
|
| 132 |
elif preserve_empty_overrides:
|
|
|
|
| 146 |
|
| 147 |
|
| 148 |
class ChatModelConfig(Protocol):
|
| 149 |
+
@property
|
| 150 |
+
def model(self) -> str: ...
|
| 151 |
+
|
| 152 |
+
@property
|
| 153 |
+
def model_fable(self) -> str | None: ...
|
| 154 |
+
|
| 155 |
+
@property
|
| 156 |
+
def model_opus(self) -> str | None: ...
|
| 157 |
+
|
| 158 |
+
@property
|
| 159 |
+
def model_sonnet(self) -> str | None: ...
|
| 160 |
+
|
| 161 |
+
@property
|
| 162 |
+
def model_haiku(self) -> str | None: ...
|
| 163 |
+
|
| 164 |
+
@property
|
| 165 |
+
def model_fallbacks(self) -> tuple[ModelFallback, ...] | None: ...
|
| 166 |
|
| 167 |
|
| 168 |
def split_provider_model_ref(model_ref: str) -> tuple[str, str]:
|
src/free_claude_code/config/nim.py
DELETED
|
@@ -1,122 +0,0 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
"""NVIDIA NIM settings (fixed values, no env config)."""
|
| 3 |
-
|
| 4 |
-
from pydantic import BaseModel, ConfigDict, Field, ValidationInfo, field_validator
|
| 5 |
-
|
| 6 |
-
from free_claude_code.config.constants import ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
class NimSettings(BaseModel):
|
| 10 |
-
"""Fixed NVIDIA NIM settings (not configurable via env)."""
|
| 11 |
-
|
| 12 |
-
temperature: float = Field(
|
| 13 |
-
1.0, ge=0.0, le=2.0, description="Sampling temperature, must be >=0 and <=2."
|
| 14 |
-
)
|
| 15 |
-
top_p: float = Field(
|
| 16 |
-
0.95,
|
| 17 |
-
ge=0.95,
|
| 18 |
-
le=0.95,
|
| 19 |
-
description="FCC's fixed NVIDIA NIM nucleus sampling probability.",
|
| 20 |
-
)
|
| 21 |
-
top_k: int = -1
|
| 22 |
-
max_tokens: int = Field(
|
| 23 |
-
ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS,
|
| 24 |
-
ge=1,
|
| 25 |
-
description="Maximum number of tokens in output.",
|
| 26 |
-
)
|
| 27 |
-
presence_penalty: float = Field(0.0, ge=-2.0, le=2.0)
|
| 28 |
-
frequency_penalty: float = Field(0.0, ge=-2.0, le=2.0)
|
| 29 |
-
min_p: float = Field(
|
| 30 |
-
0.0, ge=0.0, le=1.0, description="Minimum probability threshold [0,1]."
|
| 31 |
-
)
|
| 32 |
-
repetition_penalty: float = Field(
|
| 33 |
-
1.0, ge=0.0, description="Penalty for repeated tokens. Must be >=0."
|
| 34 |
-
)
|
| 35 |
-
seed: int | None = None
|
| 36 |
-
stop: str | None = None
|
| 37 |
-
parallel_tool_calls: bool = True
|
| 38 |
-
ignore_eos: bool = False
|
| 39 |
-
min_tokens: int = Field(0, ge=0, description="Minimum tokens in the response.")
|
| 40 |
-
chat_template: str | None = None
|
| 41 |
-
request_id: str | None = None
|
| 42 |
-
|
| 43 |
-
model_config = ConfigDict(extra="forbid")
|
| 44 |
-
|
| 45 |
-
@field_validator("top_k", mode="before")
|
| 46 |
-
@classmethod
|
| 47 |
-
def validate_top_k(cls, v, info: ValidationInfo):
|
| 48 |
-
if v is None or v == "":
|
| 49 |
-
return -1
|
| 50 |
-
int_v = int(v)
|
| 51 |
-
if int_v < -1:
|
| 52 |
-
raise ValueError(f"{info.field_name} must be -1 or >= 0")
|
| 53 |
-
return int_v
|
| 54 |
-
|
| 55 |
-
@field_validator(
|
| 56 |
-
"temperature",
|
| 57 |
-
"top_p",
|
| 58 |
-
"min_p",
|
| 59 |
-
"presence_penalty",
|
| 60 |
-
"frequency_penalty",
|
| 61 |
-
"repetition_penalty",
|
| 62 |
-
mode="before",
|
| 63 |
-
)
|
| 64 |
-
@classmethod
|
| 65 |
-
def validate_float_fields(cls, v, info: ValidationInfo):
|
| 66 |
-
field_defaults = {
|
| 67 |
-
"temperature": 1.0,
|
| 68 |
-
"top_p": 0.95,
|
| 69 |
-
"min_p": 0.0,
|
| 70 |
-
"presence_penalty": 0.0,
|
| 71 |
-
"frequency_penalty": 0.0,
|
| 72 |
-
"repetition_penalty": 1.0,
|
| 73 |
-
}
|
| 74 |
-
if v is None or v == "":
|
| 75 |
-
key = info.field_name or "temperature"
|
| 76 |
-
return field_defaults.get(key, 1.0)
|
| 77 |
-
try:
|
| 78 |
-
val = float(v)
|
| 79 |
-
except (TypeError, ValueError) as err:
|
| 80 |
-
raise ValueError(
|
| 81 |
-
f"{info.field_name} must be a float. Got {type(v).__name__}."
|
| 82 |
-
) from err
|
| 83 |
-
return val
|
| 84 |
-
|
| 85 |
-
@field_validator("max_tokens", "min_tokens", mode="before")
|
| 86 |
-
@classmethod
|
| 87 |
-
def validate_int_fields(cls, v, info: ValidationInfo):
|
| 88 |
-
field_defaults = {
|
| 89 |
-
"max_tokens": ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS,
|
| 90 |
-
"min_tokens": 0,
|
| 91 |
-
}
|
| 92 |
-
if v is None or v == "":
|
| 93 |
-
key = info.field_name or "max_tokens"
|
| 94 |
-
return field_defaults.get(key, ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS)
|
| 95 |
-
try:
|
| 96 |
-
val = int(v)
|
| 97 |
-
except (TypeError, ValueError) as err:
|
| 98 |
-
raise ValueError(
|
| 99 |
-
f"{info.field_name} must be an int. Got {type(v).__name__}."
|
| 100 |
-
) from err
|
| 101 |
-
return val
|
| 102 |
-
|
| 103 |
-
@field_validator("seed", mode="before")
|
| 104 |
-
@classmethod
|
| 105 |
-
def parse_optional_int(cls, v, info: ValidationInfo):
|
| 106 |
-
if v == "" or v is None:
|
| 107 |
-
return None
|
| 108 |
-
try:
|
| 109 |
-
return int(v)
|
| 110 |
-
except (TypeError, ValueError) as err:
|
| 111 |
-
raise ValueError(
|
| 112 |
-
f"{info.field_name} must be an int or empty/None."
|
| 113 |
-
) from err
|
| 114 |
-
|
| 115 |
-
@field_validator("stop", "chat_template", "request_id", mode="before")
|
| 116 |
-
@classmethod
|
| 117 |
-
def parse_optional_str(cls, v, info: ValidationInfo):
|
| 118 |
-
if v == "":
|
| 119 |
-
return None
|
| 120 |
-
if v is not None and not isinstance(v, str):
|
| 121 |
-
return str(v)
|
| 122 |
-
return v
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/free_claude_code/config/settings.py
CHANGED
|
@@ -17,7 +17,6 @@ from .api_keys import ApiKeyList
|
|
| 17 |
from .constants import DEFAULT_MODEL, HTTP_CONNECT_TIMEOUT_DEFAULT
|
| 18 |
from .custom_providers import CustomProviderDefinition, decode_custom_providers
|
| 19 |
from .model_refs import ModelFallback, ModelFallbacks
|
| 20 |
-
from .nim import NimSettings
|
| 21 |
from .provider_catalog import (
|
| 22 |
BEDROCK_DEFAULT_BASE,
|
| 23 |
PROVIDER_CATALOG,
|
|
@@ -59,6 +58,7 @@ class Settings(BaseModel):
|
|
| 59 |
"""Validated application settings with no file or process I/O."""
|
| 60 |
|
| 61 |
model_config = ConfigDict(
|
|
|
|
| 62 |
validate_default=True,
|
| 63 |
populate_by_name=True,
|
| 64 |
extra="ignore",
|
|
@@ -651,30 +651,6 @@ class Settings(BaseModel):
|
|
| 651 |
validation_alias="HTTP_CONNECT_TIMEOUT",
|
| 652 |
)
|
| 653 |
|
| 654 |
-
# ==================== Fast Prefix Detection ====================
|
| 655 |
-
fast_prefix_detection: bool = Field(
|
| 656 |
-
default=True,
|
| 657 |
-
validation_alias="FAST_PREFIX_DETECTION",
|
| 658 |
-
)
|
| 659 |
-
|
| 660 |
-
# ==================== Optimizations ====================
|
| 661 |
-
enable_network_probe_mock: bool = Field(
|
| 662 |
-
default=True,
|
| 663 |
-
validation_alias="ENABLE_NETWORK_PROBE_MOCK",
|
| 664 |
-
)
|
| 665 |
-
enable_title_generation_skip: bool = Field(
|
| 666 |
-
default=True,
|
| 667 |
-
validation_alias="ENABLE_TITLE_GENERATION_SKIP",
|
| 668 |
-
)
|
| 669 |
-
enable_suggestion_mode_skip: bool = Field(
|
| 670 |
-
default=True,
|
| 671 |
-
validation_alias="ENABLE_SUGGESTION_MODE_SKIP",
|
| 672 |
-
)
|
| 673 |
-
enable_filepath_extraction_mock: bool = Field(
|
| 674 |
-
default=True,
|
| 675 |
-
validation_alias="ENABLE_FILEPATH_EXTRACTION_MOCK",
|
| 676 |
-
)
|
| 677 |
-
|
| 678 |
# ==================== Local web server tools (web_search / web_fetch) ====================
|
| 679 |
# On by default to match Claude Code's normal web-tool availability.
|
| 680 |
enable_web_server_tools: bool = Field(
|
|
@@ -722,9 +698,6 @@ class Settings(BaseModel):
|
|
| 722 |
default=False, validation_alias="DEBUG_SUBAGENT_STACK"
|
| 723 |
)
|
| 724 |
|
| 725 |
-
# ==================== NIM Settings ====================
|
| 726 |
-
nim: NimSettings = Field(default_factory=NimSettings)
|
| 727 |
-
|
| 728 |
# ==================== Voice Note Transcription ====================
|
| 729 |
voice_note_enabled: bool = Field(
|
| 730 |
default=True, validation_alias="VOICE_NOTE_ENABLED"
|
|
|
|
| 17 |
from .constants import DEFAULT_MODEL, HTTP_CONNECT_TIMEOUT_DEFAULT
|
| 18 |
from .custom_providers import CustomProviderDefinition, decode_custom_providers
|
| 19 |
from .model_refs import ModelFallback, ModelFallbacks
|
|
|
|
| 20 |
from .provider_catalog import (
|
| 21 |
BEDROCK_DEFAULT_BASE,
|
| 22 |
PROVIDER_CATALOG,
|
|
|
|
| 58 |
"""Validated application settings with no file or process I/O."""
|
| 59 |
|
| 60 |
model_config = ConfigDict(
|
| 61 |
+
frozen=True,
|
| 62 |
validate_default=True,
|
| 63 |
populate_by_name=True,
|
| 64 |
extra="ignore",
|
|
|
|
| 651 |
validation_alias="HTTP_CONNECT_TIMEOUT",
|
| 652 |
)
|
| 653 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 654 |
# ==================== Local web server tools (web_search / web_fetch) ====================
|
| 655 |
# On by default to match Claude Code's normal web-tool availability.
|
| 656 |
enable_web_server_tools: bool = Field(
|
|
|
|
| 698 |
default=False, validation_alias="DEBUG_SUBAGENT_STACK"
|
| 699 |
)
|
| 700 |
|
|
|
|
|
|
|
|
|
|
| 701 |
# ==================== Voice Note Transcription ====================
|
| 702 |
voice_note_enabled: bool = Field(
|
| 703 |
default=True, validation_alias="VOICE_NOTE_ENABLED"
|
src/free_claude_code/core/anthropic/tokens.py
CHANGED
|
@@ -7,7 +7,10 @@ from typing import Any
|
|
| 7 |
|
| 8 |
from loguru import logger
|
| 9 |
|
| 10 |
-
from free_claude_code.core.token_estimation import
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
from .content import get_block_attr, get_block_type
|
| 13 |
from .models import Message, NativeTokenCountMessage, SystemContent, Tool
|
|
@@ -28,8 +31,8 @@ def _image_tokens(block: Any) -> int:
|
|
| 28 |
if isinstance(source, dict):
|
| 29 |
data = source.get("data") or source.get("base64") or ""
|
| 30 |
if isinstance(data, str) and data:
|
| 31 |
-
return
|
| 32 |
-
return
|
| 33 |
|
| 34 |
|
| 35 |
def get_token_count(
|
|
|
|
| 7 |
|
| 8 |
from loguru import logger
|
| 9 |
|
| 10 |
+
from free_claude_code.core.token_estimation import (
|
| 11 |
+
estimate_image_tokens,
|
| 12 |
+
estimate_text_tokens,
|
| 13 |
+
)
|
| 14 |
|
| 15 |
from .content import get_block_attr, get_block_type
|
| 16 |
from .models import Message, NativeTokenCountMessage, SystemContent, Tool
|
|
|
|
| 31 |
if isinstance(source, dict):
|
| 32 |
data = source.get("data") or source.get("base64") or ""
|
| 33 |
if isinstance(data, str) and data:
|
| 34 |
+
return estimate_image_tokens(len(data))
|
| 35 |
+
return estimate_image_tokens()
|
| 36 |
|
| 37 |
|
| 38 |
def get_token_count(
|
src/free_claude_code/core/async_rwlock.py
CHANGED
|
@@ -2,7 +2,7 @@ from __future__ import annotations
|
|
| 2 |
"""Concurrent readers and exclusive writers with preference for queued writes."""
|
| 3 |
|
| 4 |
import asyncio
|
| 5 |
-
from collections.abc import
|
| 6 |
from contextlib import asynccontextmanager
|
| 7 |
|
| 8 |
from .async_tasks import wait_owned
|
|
@@ -16,7 +16,7 @@ class AsyncReadWriteLock:
|
|
| 16 |
self._waiting_writers = 0
|
| 17 |
|
| 18 |
@asynccontextmanager
|
| 19 |
-
async def read(self) ->
|
| 20 |
async with self._condition:
|
| 21 |
await self._condition.wait_for(
|
| 22 |
lambda: not self._writer and not self._waiting_writers
|
|
@@ -28,7 +28,7 @@ class AsyncReadWriteLock:
|
|
| 28 |
await wait_owned(asyncio.create_task(self._release(writer=False)))
|
| 29 |
|
| 30 |
@asynccontextmanager
|
| 31 |
-
async def write(self) ->
|
| 32 |
async with self._condition:
|
| 33 |
self._waiting_writers += 1
|
| 34 |
try:
|
|
|
|
| 2 |
"""Concurrent readers and exclusive writers with preference for queued writes."""
|
| 3 |
|
| 4 |
import asyncio
|
| 5 |
+
from collections.abc import AsyncGenerator
|
| 6 |
from contextlib import asynccontextmanager
|
| 7 |
|
| 8 |
from .async_tasks import wait_owned
|
|
|
|
| 16 |
self._waiting_writers = 0
|
| 17 |
|
| 18 |
@asynccontextmanager
|
| 19 |
+
async def read(self) -> AsyncGenerator[None]:
|
| 20 |
async with self._condition:
|
| 21 |
await self._condition.wait_for(
|
| 22 |
lambda: not self._writer and not self._waiting_writers
|
|
|
|
| 28 |
await wait_owned(asyncio.create_task(self._release(writer=False)))
|
| 29 |
|
| 30 |
@asynccontextmanager
|
| 31 |
+
async def write(self) -> AsyncGenerator[None]:
|
| 32 |
async with self._condition:
|
| 33 |
self._waiting_writers += 1
|
| 34 |
try:
|
src/free_claude_code/core/continuation_overlap.py
CHANGED
|
@@ -8,20 +8,11 @@ from typing import Any
|
|
| 8 |
try:
|
| 9 |
import simplejson
|
| 10 |
except ImportError:
|
| 11 |
-
import json
|
| 12 |
-
class _SimpleJsonFallback:
|
| 13 |
-
@staticmethod
|
| 14 |
-
def dumps(obj, *args, **kwargs):
|
| 15 |
-
kwargs.pop('use_decimal', None)
|
| 16 |
-
return json.dumps(obj, *args, **kwargs)
|
| 17 |
-
@staticmethod
|
| 18 |
-
def loads(s, *args, **kwargs):
|
| 19 |
-
kwargs.pop('use_decimal', None)
|
| 20 |
-
return json.loads(s, *args, **kwargs)
|
| 21 |
-
simplejson = _SimpleJsonFallback()
|
| 22 |
|
| 23 |
from .delivered_response import RECOVERY_RETENTION_BYTES
|
| 24 |
from .failures import ExecutionFailure, FailureKind
|
|
|
|
| 25 |
|
| 26 |
type PartKey = tuple[int | str, int]
|
| 27 |
|
|
@@ -88,7 +79,7 @@ class ContinuationOverlap:
|
|
| 88 |
|
| 89 |
def _feed(self, data: dict[str, Any]) -> list[dict[str, Any]]:
|
| 90 |
kind = data.get("type", "")
|
| 91 |
-
if kind in {"error", "response.error", "response.failed"}:
|
| 92 |
self._frames.clear()
|
| 93 |
self._frame_bytes = 0
|
| 94 |
return [data]
|
|
@@ -96,13 +87,18 @@ class ContinuationOverlap:
|
|
| 96 |
return self._render(_Frame(data, self._texts(data)))
|
| 97 |
texts = self._texts(data)
|
| 98 |
frame = _Frame(data, texts)
|
| 99 |
-
terminal =
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
)
|
| 107 |
if not self._pending:
|
| 108 |
if kind in {"response.completed", "response.incomplete"}:
|
|
@@ -168,6 +164,12 @@ class ContinuationOverlap:
|
|
| 168 |
return identity
|
| 169 |
|
| 170 |
def _texts(self, data: dict[str, Any]) -> list[_Text]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
kind = data.get("type", "")
|
| 172 |
index = data.get("index", 0)
|
| 173 |
if kind == "content_block_start":
|
|
@@ -314,6 +316,17 @@ class ContinuationOverlap:
|
|
| 314 |
and all(text.delta for text in frame.texts)
|
| 315 |
and not any(text.value.get(text.field) for text in frame.texts)
|
| 316 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
return []
|
| 318 |
return [frame.data]
|
| 319 |
|
|
|
|
| 8 |
try:
|
| 9 |
import simplejson
|
| 10 |
except ImportError:
|
| 11 |
+
import json as simplejson
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
from .delivered_response import RECOVERY_RETENTION_BYTES
|
| 14 |
from .failures import ExecutionFailure, FailureKind
|
| 15 |
+
from .gemini.response import gemini_finished, gemini_parts
|
| 16 |
|
| 17 |
type PartKey = tuple[int | str, int]
|
| 18 |
|
|
|
|
| 79 |
|
| 80 |
def _feed(self, data: dict[str, Any]) -> list[dict[str, Any]]:
|
| 81 |
kind = data.get("type", "")
|
| 82 |
+
if kind in {"error", "response.error", "response.failed"} or "error" in data:
|
| 83 |
self._frames.clear()
|
| 84 |
self._frame_bytes = 0
|
| 85 |
return [data]
|
|
|
|
| 87 |
return self._render(_Frame(data, self._texts(data)))
|
| 88 |
texts = self._texts(data)
|
| 89 |
frame = _Frame(data, texts)
|
| 90 |
+
terminal = (
|
| 91 |
+
gemini_finished(data)
|
| 92 |
+
or kind
|
| 93 |
+
in {
|
| 94 |
+
"response.completed",
|
| 95 |
+
"response.incomplete",
|
| 96 |
+
"message_stop",
|
| 97 |
+
}
|
| 98 |
+
or (
|
| 99 |
+
kind == "message_delta"
|
| 100 |
+
and data.get("delta", {}).get("stop_reason") is not None
|
| 101 |
+
)
|
| 102 |
)
|
| 103 |
if not self._pending:
|
| 104 |
if kind in {"response.completed", "response.incomplete"}:
|
|
|
|
| 164 |
return identity
|
| 165 |
|
| 166 |
def _texts(self, data: dict[str, Any]) -> list[_Text]:
|
| 167 |
+
if "candidates" in data:
|
| 168 |
+
return [
|
| 169 |
+
_Text(("gemini", 0), (0, 0), part, "text", delta=True)
|
| 170 |
+
for part in gemini_parts(data)
|
| 171 |
+
if "text" in part and not part.get("thought")
|
| 172 |
+
]
|
| 173 |
kind = data.get("type", "")
|
| 174 |
index = data.get("index", 0)
|
| 175 |
if kind == "content_block_start":
|
|
|
|
| 316 |
and all(text.delta for text in frame.texts)
|
| 317 |
and not any(text.value.get(text.field) for text in frame.texts)
|
| 318 |
):
|
| 319 |
+
if "candidates" in frame.data:
|
| 320 |
+
for candidate in frame.data["candidates"]:
|
| 321 |
+
content = candidate.get("content", {})
|
| 322 |
+
content["parts"] = [
|
| 323 |
+
part
|
| 324 |
+
for part in content.get("parts", [])
|
| 325 |
+
if part.get("text")
|
| 326 |
+
or any(key not in {"text", "thought"} for key in part)
|
| 327 |
+
]
|
| 328 |
+
if gemini_finished(frame.data) or gemini_parts(frame.data):
|
| 329 |
+
return [frame.data]
|
| 330 |
return []
|
| 331 |
return [frame.data]
|
| 332 |
|
src/free_claude_code/core/continuation_stream.py
CHANGED
|
@@ -12,6 +12,7 @@ from .delivered_response import (
|
|
| 12 |
responses_text_constraint,
|
| 13 |
)
|
| 14 |
from .failures import ExecutionFailure, FailureKind
|
|
|
|
| 15 |
|
| 16 |
|
| 17 |
class ContinuationStream:
|
|
@@ -90,6 +91,11 @@ class ContinuationStream:
|
|
| 90 |
return [self._map(event) for event in events]
|
| 91 |
|
| 92 |
def _map(self, data: dict[str, Any]) -> dict[str, Any]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
if not self.handoff:
|
| 94 |
if isinstance(data.get("index"), int):
|
| 95 |
data["index"] += self._offset
|
|
@@ -117,6 +123,17 @@ class ContinuationStream:
|
|
| 117 |
"""Finish the response only after preceding frames have been published."""
|
| 118 |
if not self.active:
|
| 119 |
return data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
kind = data.get("type")
|
| 121 |
response = data.get("response")
|
| 122 |
output = response.get("output", []) if isinstance(response, dict) else []
|
|
|
|
| 12 |
responses_text_constraint,
|
| 13 |
)
|
| 14 |
from .failures import ExecutionFailure, FailureKind
|
| 15 |
+
from .gemini.response import gemini_finished
|
| 16 |
|
| 17 |
|
| 18 |
class ContinuationStream:
|
|
|
|
| 91 |
return [self._map(event) for event in events]
|
| 92 |
|
| 93 |
def _map(self, data: dict[str, Any]) -> dict[str, Any]:
|
| 94 |
+
if self.delivered.wire_api == "gemini":
|
| 95 |
+
for key in ("responseId", "modelVersion"):
|
| 96 |
+
if key in self.delivered.header:
|
| 97 |
+
data[key] = self.delivered.header[key]
|
| 98 |
+
return data
|
| 99 |
if not self.handoff:
|
| 100 |
if isinstance(data.get("index"), int):
|
| 101 |
data["index"] += self._offset
|
|
|
|
| 123 |
"""Finish the response only after preceding frames have been published."""
|
| 124 |
if not self.active:
|
| 125 |
return data
|
| 126 |
+
if self.delivered.wire_api == "gemini":
|
| 127 |
+
if gemini_finished(data) and not self.handoff and not self.made_progress:
|
| 128 |
+
raise ExecutionFailure(
|
| 129 |
+
kind=FailureKind.UPSTREAM,
|
| 130 |
+
status_code=502,
|
| 131 |
+
message="The provider continuation completed without adding output.",
|
| 132 |
+
retryable=False,
|
| 133 |
+
)
|
| 134 |
+
# Per-attempt usage cannot describe a synthesized multi-attempt answer.
|
| 135 |
+
data.pop("usageMetadata", None)
|
| 136 |
+
return data
|
| 137 |
kind = data.get("type")
|
| 138 |
response = data.get("response")
|
| 139 |
output = response.get("output", []) if isinstance(response, dict) else []
|
src/free_claude_code/core/delivered_response.py
CHANGED
|
@@ -7,28 +7,17 @@ from typing import Any, Literal
|
|
| 7 |
try:
|
| 8 |
import simplejson
|
| 9 |
except ImportError:
|
| 10 |
-
import json
|
| 11 |
-
class _SimpleJsonFallback:
|
| 12 |
-
@staticmethod
|
| 13 |
-
def dumps(obj, *args, **kwargs):
|
| 14 |
-
kwargs.pop('use_decimal', None)
|
| 15 |
-
return json.dumps(obj, *args, **kwargs)
|
| 16 |
-
@staticmethod
|
| 17 |
-
def loads(s, *args, **kwargs):
|
| 18 |
-
kwargs.pop('use_decimal', None)
|
| 19 |
-
return json.loads(s, *args, **kwargs)
|
| 20 |
-
simplejson = _SimpleJsonFallback()
|
| 21 |
|
|
|
|
| 22 |
from .history_replay import (
|
| 23 |
readable_reasoning,
|
| 24 |
unencrypted_responses_replay,
|
| 25 |
)
|
| 26 |
from .openai_responses import is_client_search
|
| 27 |
-
from .stream_recovery import DeliveredPrefix
|
| 28 |
from .token_estimation import estimate_text_tokens
|
| 29 |
|
| 30 |
-
RECOVERY_RETENTION_BYTES = 1_048_576
|
| 31 |
-
|
| 32 |
CLIENT_CALL_TYPES = frozenset(
|
| 33 |
{
|
| 34 |
"function_call",
|
|
@@ -82,7 +71,7 @@ def responses_text_constraint(data: dict[str, Any]) -> str | None:
|
|
| 82 |
class DeliveredResponse:
|
| 83 |
"""Track this response only; the harness continues to own conversation history."""
|
| 84 |
|
| 85 |
-
def __init__(self, wire_api: Literal["messages", "responses"]) -> None:
|
| 86 |
self.wire_api = wire_api
|
| 87 |
self.items: dict[int, dict[str, Any]] = {}
|
| 88 |
self.closed: set[int] = set()
|
|
@@ -121,6 +110,9 @@ class DeliveredResponse:
|
|
| 121 |
return self._limited
|
| 122 |
|
| 123 |
def observe(self, data: dict[str, Any], *, count_progress: bool = True) -> None:
|
|
|
|
|
|
|
|
|
|
| 124 |
kind = data.get("type", "")
|
| 125 |
if not isinstance(kind, str):
|
| 126 |
self.unsafe_reason = "unknown_event"
|
|
@@ -169,6 +161,44 @@ class DeliveredResponse:
|
|
| 169 |
if self._limited:
|
| 170 |
self._limited_output_tokens += estimate_text_tokens(text)
|
| 171 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
def _new_snapshot_text(self, data: dict[str, Any]) -> bool:
|
| 173 |
"""Cumulative text is progress only when it adds published characters."""
|
| 174 |
kind = data.get("type")
|
|
@@ -401,7 +431,12 @@ class DeliveredResponse:
|
|
| 401 |
has_calls = False
|
| 402 |
for index, item in sorted(self.items.items()):
|
| 403 |
kind = item.get("type")
|
| 404 |
-
if self.wire_api == "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 405 |
if kind == "text":
|
| 406 |
text.append(item.get("text", ""))
|
| 407 |
elif kind == "thinking":
|
|
@@ -435,6 +470,7 @@ class DeliveredResponse:
|
|
| 435 |
unsafe_reason is None,
|
| 436 |
self.can_handoff,
|
| 437 |
unsafe_reason,
|
|
|
|
| 438 |
)
|
| 439 |
|
| 440 |
def output_tokens(self, output: list[dict[str, Any]] | None = None) -> int:
|
|
@@ -463,6 +499,8 @@ class DeliveredResponse:
|
|
| 463 |
)
|
| 464 |
|
| 465 |
def closing_events(self) -> list[dict[str, Any]]:
|
|
|
|
|
|
|
| 466 |
events: list[dict[str, Any]] = []
|
| 467 |
for index, item in sorted(self.items.items()):
|
| 468 |
if index in self.closed:
|
|
@@ -518,6 +556,13 @@ class DeliveredResponse:
|
|
| 518 |
|
| 519 |
def handoff_events(self) -> list[dict[str, Any]]:
|
| 520 |
"""Signal handoff; the public writer fills output and usage after closure."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 521 |
if self.wire_api == "messages":
|
| 522 |
return [
|
| 523 |
{
|
|
|
|
| 7 |
try:
|
| 8 |
import simplejson
|
| 9 |
except ImportError:
|
| 10 |
+
import json as simplejson
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
from .gemini.response import gemini_parts
|
| 13 |
from .history_replay import (
|
| 14 |
readable_reasoning,
|
| 15 |
unencrypted_responses_replay,
|
| 16 |
)
|
| 17 |
from .openai_responses import is_client_search
|
| 18 |
+
from .stream_recovery import RECOVERY_RETENTION_BYTES, DeliveredPrefix
|
| 19 |
from .token_estimation import estimate_text_tokens
|
| 20 |
|
|
|
|
|
|
|
| 21 |
CLIENT_CALL_TYPES = frozenset(
|
| 22 |
{
|
| 23 |
"function_call",
|
|
|
|
| 71 |
class DeliveredResponse:
|
| 72 |
"""Track this response only; the harness continues to own conversation history."""
|
| 73 |
|
| 74 |
+
def __init__(self, wire_api: Literal["messages", "responses", "gemini"]) -> None:
|
| 75 |
self.wire_api = wire_api
|
| 76 |
self.items: dict[int, dict[str, Any]] = {}
|
| 77 |
self.closed: set[int] = set()
|
|
|
|
| 110 |
return self._limited
|
| 111 |
|
| 112 |
def observe(self, data: dict[str, Any], *, count_progress: bool = True) -> None:
|
| 113 |
+
if self.wire_api == "gemini":
|
| 114 |
+
self._gemini(data, count_progress=count_progress)
|
| 115 |
+
return
|
| 116 |
kind = data.get("type", "")
|
| 117 |
if not isinstance(kind, str):
|
| 118 |
self.unsafe_reason = "unknown_event"
|
|
|
|
| 161 |
if self._limited:
|
| 162 |
self._limited_output_tokens += estimate_text_tokens(text)
|
| 163 |
|
| 164 |
+
def _gemini(self, data: dict[str, Any], *, count_progress: bool) -> None:
|
| 165 |
+
if not self.header:
|
| 166 |
+
self.header = {
|
| 167 |
+
key: data[key] for key in ("responseId", "modelVersion") if key in data
|
| 168 |
+
}
|
| 169 |
+
parts = gemini_parts(data)
|
| 170 |
+
if count_progress and any(
|
| 171 |
+
part.get("text") or part.get("functionCall") for part in parts
|
| 172 |
+
):
|
| 173 |
+
self.progress += 1
|
| 174 |
+
for part in parts:
|
| 175 |
+
if not self._retain(part):
|
| 176 |
+
self._limited_output_tokens += estimate_text_tokens(
|
| 177 |
+
part.get("text", "")
|
| 178 |
+
)
|
| 179 |
+
continue
|
| 180 |
+
if part.get("thoughtSignature"):
|
| 181 |
+
self.unsafe_reason = "opaque_reasoning"
|
| 182 |
+
if any(
|
| 183 |
+
key not in {"text", "thought", "thoughtSignature", "functionCall"}
|
| 184 |
+
for key in part
|
| 185 |
+
):
|
| 186 |
+
self.unsafe_reason = "unsupported_output"
|
| 187 |
+
index = max(self.items, default=-1) + 1
|
| 188 |
+
previous = self.items.get(index - 1)
|
| 189 |
+
if (
|
| 190 |
+
previous is not None
|
| 191 |
+
and "text" in part
|
| 192 |
+
and "text" in previous
|
| 193 |
+
and set(part) <= {"text", "thought"}
|
| 194 |
+
and set(previous) <= {"text", "thought"}
|
| 195 |
+
and part.get("thought", False) == previous.get("thought", False)
|
| 196 |
+
):
|
| 197 |
+
previous["text"] += part["text"]
|
| 198 |
+
else:
|
| 199 |
+
self.items[index] = deepcopy(part)
|
| 200 |
+
self.closed.add(index)
|
| 201 |
+
|
| 202 |
def _new_snapshot_text(self, data: dict[str, Any]) -> bool:
|
| 203 |
"""Cumulative text is progress only when it adds published characters."""
|
| 204 |
kind = data.get("type")
|
|
|
|
| 431 |
has_calls = False
|
| 432 |
for index, item in sorted(self.items.items()):
|
| 433 |
kind = item.get("type")
|
| 434 |
+
if self.wire_api == "gemini":
|
| 435 |
+
if "text" in item:
|
| 436 |
+
(thinking if item.get("thought") else text).append(item["text"])
|
| 437 |
+
if "functionCall" in item:
|
| 438 |
+
has_calls = True
|
| 439 |
+
elif self.wire_api == "messages":
|
| 440 |
if kind == "text":
|
| 441 |
text.append(item.get("text", ""))
|
| 442 |
elif kind == "thinking":
|
|
|
|
| 470 |
unsafe_reason is None,
|
| 471 |
self.can_handoff,
|
| 472 |
unsafe_reason,
|
| 473 |
+
retained_bytes=self._bytes,
|
| 474 |
)
|
| 475 |
|
| 476 |
def output_tokens(self, output: list[dict[str, Any]] | None = None) -> int:
|
|
|
|
| 499 |
)
|
| 500 |
|
| 501 |
def closing_events(self) -> list[dict[str, Any]]:
|
| 502 |
+
if self.wire_api == "gemini":
|
| 503 |
+
return []
|
| 504 |
events: list[dict[str, Any]] = []
|
| 505 |
for index, item in sorted(self.items.items()):
|
| 506 |
if index in self.closed:
|
|
|
|
| 556 |
|
| 557 |
def handoff_events(self) -> list[dict[str, Any]]:
|
| 558 |
"""Signal handoff; the public writer fills output and usage after closure."""
|
| 559 |
+
if self.wire_api == "gemini":
|
| 560 |
+
return [
|
| 561 |
+
{
|
| 562 |
+
**deepcopy(self.header),
|
| 563 |
+
"candidates": [{"index": 0, "finishReason": "STOP"}],
|
| 564 |
+
}
|
| 565 |
+
]
|
| 566 |
if self.wire_api == "messages":
|
| 567 |
return [
|
| 568 |
{
|