File size: 6,172 Bytes
9f6a4bd
e99df76
691dc7c
2415446
a1bab2d
2415446
691dc7c
2415446
 
 
8e438ab
f7872b8
8e438ab
2415446
8e438ab
 
691dc7c
 
8e438ab
 
2415446
691dc7c
2415446
a1bab2d
8e438ab
a9e27c0
691dc7c
 
 
 
 
 
2415446
 
 
8e438ab
 
261c237
8e438ab
2415446
691dc7c
 
2415446
 
 
 
 
 
 
 
61bb677
 
 
 
 
a1bab2d
8e438ab
691dc7c
 
a1bab2d
 
691dc7c
8e438ab
 
 
a1bab2d
 
 
 
 
 
 
 
8e438ab
 
 
 
261c237
a1bab2d
691dc7c
 
 
8e438ab
691dc7c
8e438ab
 
2415446
 
8e438ab
 
691dc7c
 
 
2415446
8e438ab
2415446
 
 
 
 
691dc7c
8e438ab
2415446
 
 
 
691dc7c
 
 
 
 
 
 
a9e27c0
691dc7c
a9e27c0
 
 
691dc7c
 
a1bab2d
 
691dc7c
 
8e438ab
691dc7c
 
 
 
a9e27c0
691dc7c
a9e27c0
 
 
8e438ab
691dc7c
 
 
 
2415446
 
691dc7c
 
 
 
 
 
 
 
f7872b8
 
 
691dc7c
 
 
 
 
2415446
691dc7c
f7872b8
2415446
691dc7c
 
 
abe1c43
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
from __future__ import annotations
"""Single production composition root for the FCC server."""

import os
from functools import partial
from pathlib import Path
from typing import TYPE_CHECKING

from free_claude_code.api.app import create_app
from free_claude_code.api.ports import ApiServices
from free_claude_code.application.code_sessions import CodeService
from free_claude_code.config.api_keys import first_api_key
from free_claude_code.config.loader import ManagedConfigStore
from free_claude_code.config.logging_config import configure_logging
from free_claude_code.config.paths import (
    code_lock_path,
    fcc_database_path,
    legacy_code_database_path,
    server_log_path,
)
from free_claude_code.config.settings import Settings
from free_claude_code.core.async_tasks import run_sync_owned
from free_claude_code.messaging.voice import Transcriber
from free_claude_code.providers.base import BaseProvider, ProviderConfig
from free_claude_code.providers.github_copilot.auth import CopilotAuthManager
from free_claude_code.providers.history_negotiation import HistoryModeCache
from free_claude_code.providers.openai_codex.auth import OpenAIAuthManager
from free_claude_code.providers.runtime.runtime import ProviderRuntime, create_provider

if TYPE_CHECKING:
    from free_claude_code.providers.admission import ProviderAdmissionController
    from free_claude_code.providers.runtime.factory import ProviderFactory

from .application import ApplicationRuntime, RestartCallback
from .asgi import RuntimeASGIApp
from .code_sessions_sqlite import SQLiteCodeStore
from .codex_app_server import CodexHarnessFactory
from .codex_catalog import CodexModelCatalogPublisher
from .configuration import ConfigurationService
from .provider_manager import ProviderRuntimeManager
from .sqlite_database import SQLiteDatabase
from .web_tools.client import HTTPWebToolsClient


def build_asgi_app(
    settings: Settings,
    restart_callback: RestartCallback | None = None,
) -> RuntimeASGIApp:
    """Construct the complete server application and its resource owner."""
    log_path = Path(os.getenv("LOG_FILE", server_log_path()))
    configure_logging(
        log_path,
        level=settings.log_level,
        verbose_third_party=settings.log_raw_api_payloads,
    )
    openai_auth = OpenAIAuthManager(proxy=settings.openai_proxy)
    copilot_auth = CopilotAuthManager()
    copilot_factory = partial(_load_copilot_provider, auth=copilot_auth)
    openai_factory = partial(_load_openai_provider, auth=openai_auth)
    provider_constructor = partial(
        create_provider,
        provider_loaders={
            "openai": openai_factory,
            "github_copilot": copilot_factory,
        },
    )
    runtime_factory = partial(
        ProviderRuntime,
        provider_constructor=provider_constructor,
    )
    provider_manager = ProviderRuntimeManager(
        settings,
        runtime_factory=runtime_factory,
        connected_provider_ids=lambda: (
            *openai_auth.connected_provider_ids(),
            *copilot_auth.connected_provider_ids(),
        ),
        model_catalog_publisher=CodexModelCatalogPublisher(),
    )
    database = SQLiteDatabase(
        fcc_database_path(), code_lock_path(), legacy_path=legacy_code_database_path()
    )
    code_service = CodeService(
        SQLiteCodeStore(database),
        CodexHarnessFactory(provider_manager),
    )
    runtime = ApplicationRuntime(
        provider_manager,
        configuration=ConfigurationService(ManagedConfigStore()),
        code_service=code_service,
        database=database,
        transcriber=None,
        transcriber_factory=_create_transcriber,
        restart_callback=restart_callback,
        connected_accounts={"openai": openai_auth, "github_copilot": copilot_auth},
    )
    services = ApiServices(
        requests=provider_manager,
        admin=runtime,
        tasks=runtime,
        web_tools=HTTPWebToolsClient(),
        code=code_service,
    )
    return RuntimeASGIApp(create_app(services), runtime)


def _load_openai_provider(*, auth: OpenAIAuthManager) -> ProviderFactory:
    from free_claude_code.providers.openai_codex.provider import OpenAICodexProvider

    def construct(
        config: ProviderConfig,
        _settings: Settings,
        admission: ProviderAdmissionController,
        history_cache: HistoryModeCache | None = None,
    ) -> BaseProvider:
        return OpenAICodexProvider(
            config, auth=auth, admission=admission, history_cache=history_cache
        )

    return construct


def _load_copilot_provider(*, auth: CopilotAuthManager) -> ProviderFactory:
    from free_claude_code.providers.github_copilot.provider import GitHubCopilotProvider

    def construct(
        config: ProviderConfig,
        _settings: Settings,
        admission: ProviderAdmissionController,
        history_cache: HistoryModeCache | None = None,
    ) -> BaseProvider:
        return GitHubCopilotProvider(
            config, auth=auth, admission=admission, history_cache=history_cache
        )

    return construct


async def _create_transcriber(settings: Settings) -> Transcriber | None:
    if not settings.voice_note_enabled:
        return None

    def load():
        if settings.whisper_device == "nvidia_nim":
            from free_claude_code.providers.nvidia_nim.voice import NvidiaNimTranscriber

            return partial(
                NvidiaNimTranscriber,
                model=settings.whisper_model,
                api_key=_required_voice_key(
                    first_api_key(settings.nvidia_nim_api_keys)
                ),
            )
        from free_claude_code.messaging.transcription import TranscriptionService

        return partial(
            TranscriptionService,
            model=settings.whisper_model,
            device=settings.whisper_device,
            huggingface_api_key=first_api_key(settings.huggingface_api_keys),
        )

    constructor = await run_sync_owned(load)
    return constructor()


def _required_voice_key(api_key: str | None) -> str:
    if api_key is None:
        raise AssertionError("NIM voice settings were not validated")
    return api_key