File size: 33,136 Bytes
691dc7c
e99df76
691dc7c
 
 
e99df76
691dc7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e99df76
691dc7c
 
 
 
 
f7872b8
691dc7c
e99df76
691dc7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e99df76
691dc7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7b8ca
691dc7c
 
 
 
2e7b8ca
691dc7c
 
 
 
 
 
 
 
e99df76
 
 
691dc7c
 
 
 
 
 
 
 
 
 
e99df76
691dc7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e99df76
691dc7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e99df76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691dc7c
e99df76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691dc7c
e99df76
 
 
 
 
 
 
 
 
 
 
2e7b8ca
e99df76
2e7b8ca
 
 
 
691dc7c
e99df76
 
 
 
 
 
 
 
691dc7c
e99df76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691dc7c
 
2e7b8ca
691dc7c
 
 
 
2e7b8ca
 
 
 
691dc7c
 
 
 
 
 
 
 
 
 
e99df76
 
691dc7c
 
 
e99df76
 
691dc7c
 
 
 
 
 
 
 
e99df76
 
691dc7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7872b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7b8ca
 
 
 
f7872b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691dc7c
 
 
 
 
 
e99df76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7b8ca
e99df76
 
 
 
 
 
 
691dc7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e99df76
 
 
 
 
 
 
 
 
 
 
691dc7c
e99df76
 
 
 
 
 
 
 
 
 
 
 
691dc7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e99df76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691dc7c
e99df76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691dc7c
 
e99df76
 
 
 
 
 
 
f7872b8
e99df76
 
 
 
f7872b8
e99df76
f7872b8
 
 
 
e99df76
 
 
 
 
f7872b8
 
 
 
 
 
691dc7c
e99df76
 
 
 
 
f7872b8
 
 
 
 
e99df76
f7872b8
e99df76
 
f7872b8
 
 
 
 
e99df76
f7872b8
e99df76
691dc7c
 
 
 
 
 
 
 
 
 
 
 
 
 
e99df76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691dc7c
e99df76
 
 
 
691dc7c
 
e99df76
 
 
 
691dc7c
2e7b8ca
691dc7c
 
 
 
2e7b8ca
 
 
 
691dc7c
 
2e7b8ca
 
 
 
 
691dc7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e99df76
691dc7c
 
 
 
 
 
 
 
 
 
 
 
 
 
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
from __future__ import annotations
"""Own integration workflows while sharing configuration publication ordering."""

import asyncio
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from functools import partial
from typing import Literal

from loguru import logger

from free_claude_code.application.errors import (
    ApplicationError,
    ApplicationUnavailableError,
    InvalidRequestError,
)
from free_claude_code.application.model_catalog import ModelCatalog, read_model_catalog
from free_claude_code.application.readiness import InitializationWait
from free_claude_code.config.paths import (
    claude_desktop_disconnect_path,
    codex_model_catalog_path,
)
from free_claude_code.config.server_urls import local_proxy_root_url
from free_claude_code.config.settings import Settings
from free_claude_code.core.async_rwlock import AsyncReadWriteLock
from free_claude_code.core.async_tasks import run_sync_owned
from free_claude_code.core.json_types import JsonObject
from free_claude_code.harnesses import (
    claude_desktop_integration,
    claude_integration,
    claude_onboarding,
    codex_integration,
    dsh_desktop_integration,
    jetbrains_acp_integration,
    vscode_chat_integration,
)

from .provider_manager import ProviderRuntimeManager

IntegrationAction = Literal["status", "connect", "disconnect", "refresh"]


@dataclass
class _IntegrationUpdate:
    state: Literal["starting", "ready", "failed"] = "ready"
    changed: bool = False
    message: str | None = None
    task: asyncio.Task[None] | None = None
    access: AsyncReadWriteLock = field(default_factory=AsyncReadWriteLock)

    def snapshot(self) -> JsonObject:
        return {"state": self.state, "changed": self.changed, "message": self.message}

    def complete(self, changed: bool = False) -> None:
        self.state = "ready"
        self.changed = changed
        self.message = None


class IntegrationService:
    """Own integration state and background refreshes, borrowing runtime resources."""

    def __init__(
        self,
        provider_manager: ProviderRuntimeManager,
        *,
        config_publication: AsyncReadWriteLock,
        is_draining: Callable[[], bool],
        has_pending_restart: Callable[[], bool],
    ) -> None:
        self.provider_manager = provider_manager
        self._config_publication = config_publication
        self._is_draining = is_draining
        self._has_pending_restart = has_pending_restart
        self._claude_update = _IntegrationUpdate()
        self._desktop_update = _IntegrationUpdate()
        self._codex_update = _IntegrationUpdate()
        self._jetbrains_update = _IntegrationUpdate()
        self._vscode_update = _IntegrationUpdate()
        self._vscode_dirty = False
        self._dsh_update = _IntegrationUpdate()
        self._dsh_dirty = False
        self._dsh_action_revision = 0

    @property
    def settings(self) -> Settings:
        return self.provider_manager.current_settings()

    def _updates(self) -> dict[str, _IntegrationUpdate]:
        return {
            "vscode-chat": self._vscode_update,
            "claude-vscode": self._claude_update,
            "claude-desktop": self._desktop_update,
            "dsh-desktop": self._dsh_update,
            "codex": self._codex_update,
            "jetbrains-acp": self._jetbrains_update,
        }

    def snapshot(self) -> JsonObject:
        return {name: update.snapshot() for name, update in self._updates().items()}

    async def start(self) -> None:
        self.catalog_changed()
        await self.refresh_claude_vscode()
        await self.refresh_codex_integration()
        await self.refresh_claude_desktop()
        await self.refresh_jetbrains_acp()

    def cancel_background_tasks(self) -> None:
        for update in self._updates().values():
            if update.task is not None and not update.task.done():
                update.task.cancel()

    async def wait_background_tasks(self) -> None:
        tasks = tuple(
            update.task
            for update in self._updates().values()
            if update.task is not None
        )
        results = await asyncio.gather(*tasks, return_exceptions=True)
        for result in results:
            if isinstance(result, Exception):
                logger.warning(
                    "Background initialization ended with exc_type={}",
                    type(result).__name__,
                )

    async def vscode_chat_status(self) -> JsonObject:
        return await self._vscode_chat("status")

    async def connect_vscode_chat(self) -> JsonObject:
        return await self._vscode_chat("connect")

    async def disconnect_vscode_chat(self) -> JsonObject:
        return await self._vscode_chat("disconnect")

    async def refresh_vscode_chat(self) -> JsonObject:
        self._check_integration_available()
        self.catalog_changed()
        return {"update": self._vscode_update.snapshot()}

    def catalog_changed(self) -> None:
        if self._is_draining():
            return
        self._schedule_dsh_refresh()
        self._vscode_dirty = True
        update = self._vscode_update
        if update.task is not None and not update.task.done():
            return
        update.state, update.changed, update.message = "starting", False, None

        async def drain() -> None:
            while self._vscode_dirty:
                self._vscode_dirty = False
                try:
                    result = await self._vscode_chat("refresh")
                    update.complete(update.changed or result.get("changed") is True)
                except ApplicationError as exc:
                    update.state, update.message = "failed", exc.message
                except Exception as exc:
                    update.state = "failed"
                    update.message = "Could not update VS Code models. Retry shortly."
                    logger.warning(
                        "VS Code integration update failed: exc_type={}",
                        type(exc).__name__,
                    )
                if self._vscode_dirty:
                    update.state = "starting"

        update.task = asyncio.create_task(drain(), name="fcc-vscode-models")

    def _schedule_dsh_refresh(self) -> None:
        self._dsh_dirty = True
        update = self._dsh_update
        if update.task is not None and not update.task.done():
            return
        update.state, update.changed, update.message = "starting", False, None

        async def drain() -> None:
            while self._dsh_dirty:
                self._dsh_dirty = False
                try:
                    result = await self._dsh_desktop("refresh")
                    update.complete(update.changed or result.get("changed") is True)
                except ApplicationError as exc:
                    update.state, update.message = "failed", exc.message
                except Exception as exc:
                    update.state = "failed"
                    update.message = "Could not update DSH Desktop. Retry shortly."
                    logger.warning(
                        "DSH Desktop update failed: exc_type={}", type(exc).__name__
                    )
                if self._dsh_dirty:
                    update.state = "starting"

        update.task = asyncio.create_task(drain(), name="fcc-dsh-desktop-models")

    async def dsh_desktop_status(self) -> JsonObject:
        return await self._dsh_desktop("status")

    async def connect_dsh_desktop(self) -> JsonObject:
        return await self._dsh_desktop("connect")

    async def disconnect_dsh_desktop(self) -> JsonObject:
        return await self._dsh_desktop("disconnect")

    async def refresh_dsh_desktop(self) -> JsonObject:
        self._check_integration_available()
        self._schedule_dsh_refresh()
        return {"update": self._dsh_update.snapshot()}

    async def _dsh_desktop(self, action: IntegrationAction) -> JsonObject:
        if action in {"connect", "disconnect"}:
            self._check_integration_available()
            self._dsh_action_revision += 1
        action_revision = self._dsh_action_revision

        def status_reader() -> Callable[[str, str, bool], JsonObject]:
            catalog = read_model_catalog(self.provider_manager)
            return lambda url, token, ready: dsh_desktop_integration.status(
                dsh_desktop_integration.config_home(),
                url,
                token,
                catalog,
            )

        def disconnect(url: str, token: str, ready: bool) -> JsonObject:
            return dsh_desktop_integration.disconnect(
                dsh_desktop_integration.config_home(),
            )

        try:
            if action == "status":
                for _ in range(2):
                    settings = self.settings
                    revision = self.provider_manager.catalog_status()[
                        "catalog_revision"
                    ]
                    result = await self._read_status(self._dsh_update, status_reader())
                    if (
                        settings is self.settings
                        and revision
                        == self.provider_manager.catalog_status()["catalog_revision"]
                    ):
                        return result
                raise ApplicationUnavailableError(
                    "FCC models changed during the check. Retry shortly."
                )
            if action == "disconnect":
                return await self._run_integration(self._dsh_update, action, disconnect)
            if action == "refresh":
                current = await self._read_status(
                    self._dsh_update,
                    lambda url, token, ready: {
                        "connected": dsh_desktop_integration.has_provider(
                            dsh_desktop_integration.config_home()
                        )
                    },
                )
                if not current["connected"]:
                    return {"changed": False}
            while True:
                snapshot = self.provider_manager.catalog_snapshot()
                revision = self.provider_manager.catalog_status()["catalog_revision"]
                async with (
                    self._dsh_update.access.write(),
                    self._config_publication.read(),
                ):
                    self._check_integration_available()
                    if action_revision != self._dsh_action_revision:
                        return await run_sync_owned(
                            partial(
                                status_reader(),
                                local_proxy_root_url(self.settings),
                                self.settings.proxy_auth_token,
                                True,
                            )
                        )
                    if (
                        snapshot.current_settings() is not self.settings
                        or revision
                        != self.provider_manager.catalog_status()["catalog_revision"]
                    ):
                        continue
                    catalog = read_model_catalog(snapshot)
                    url = local_proxy_root_url(self.settings)
                    token = self.settings.proxy_auth_token

                    def operate(
                        catalog: ModelCatalog = catalog,
                        url: str = url,
                        token: str = token,
                    ) -> JsonObject:
                        home = dsh_desktop_integration.config_home()
                        if action == "refresh":
                            return {
                                "changed": dsh_desktop_integration.refresh_connected(
                                    home,
                                    url,
                                    token,
                                    catalog,
                                )
                            }
                        return dsh_desktop_integration.configure(
                            home,
                            url,
                            token,
                            catalog,
                        )

                    result = await run_sync_owned(operate)
                    if action == "connect":
                        self._dsh_update.complete()
                    return result
        except dsh_desktop_integration.DshConfigError as exc:
            raise InvalidRequestError(str(exc)) from None
        except (ValueError, UnicodeError):
            raise InvalidRequestError(
                "Could not read DSH Desktop configuration. Correct the invalid document and retry."
            ) from None
        except OSError:
            raise ApplicationUnavailableError(
                "Could not update DSH Desktop files. Finish native configuration edits, check file permissions, and retry."
            ) from None

    async def _vscode_chat(self, action: IntegrationAction) -> JsonObject:
        try:
            if action == "status":
                return await self._read_status(
                    self._vscode_update,
                    lambda url, token, ready: vscode_chat_integration.status(
                        vscode_chat_integration.config_path()
                    ),
                )
            if action == "refresh":
                status = await self._read_status(
                    self._vscode_update,
                    lambda url, token, ready: vscode_chat_integration.status(
                        vscode_chat_integration.config_path()
                    ),
                )
                if not status["connected"]:
                    return {"changed": False}
            while True:
                snapshot = (
                    self.provider_manager.catalog_snapshot()
                    if action in {"connect", "refresh"}
                    else None
                )
                revision = self.provider_manager.catalog_status()["catalog_revision"]
                async with (
                    self._vscode_update.access.write(),
                    self._config_publication.read(),
                ):
                    self._check_integration_available()
                    if snapshot is not None and (
                        snapshot.current_settings() is not self.settings
                        or revision
                        != self.provider_manager.catalog_status()["catalog_revision"]
                    ):
                        continue
                    catalog = (
                        read_model_catalog(snapshot) if snapshot is not None else None
                    )
                    url = local_proxy_root_url(self.settings)
                    token = self.settings.proxy_auth_token

                    def operate(
                        catalog: ModelCatalog | None = catalog,
                        url: str = url,
                        token: str = token,
                    ) -> JsonObject:
                        path = vscode_chat_integration.config_path()
                        changed = False
                        if action == "disconnect":
                            vscode_chat_integration.disconnect(path)
                        elif catalog is not None:
                            changed = vscode_chat_integration.configure(
                                path,
                                url,
                                token,
                                catalog.models,
                                only_existing=action == "refresh",
                            )
                        if action == "refresh":
                            return {"changed": changed}
                        return vscode_chat_integration.status(path)

                    result = await run_sync_owned(operate)
                    if action in {"connect", "disconnect"}:
                        self._vscode_update.complete()
                    return result
        except (ValueError, UnicodeError):
            raise InvalidRequestError(
                "Could not configure VS Code Chat. Check chatLanguageModels.json for invalid JSON or conflicting FCC groups."
            ) from None
        except OSError:
            raise ApplicationUnavailableError(
                "Could not access chatLanguageModels.json. Finish configuration edits, check file permissions, and retry."
            ) from None

    async def claude_vscode_status(self) -> JsonObject:
        return await self._claude_vscode("status")

    async def connect_claude_vscode(self) -> JsonObject:
        return await self._claude_vscode("connect")

    async def disconnect_claude_vscode(self) -> JsonObject:
        return await self._claude_vscode("disconnect")

    async def claude_onboarding_status(self) -> JsonObject:
        return await self._claude_onboarding(complete=False)

    async def complete_claude_onboarding(self) -> JsonObject:
        return await self._claude_onboarding(complete=True)

    async def _claude_onboarding(self, *, complete: bool) -> JsonObject:
        def operate() -> JsonObject:
            operation = (
                claude_onboarding.complete if complete else claude_onboarding.status
            )
            return operation(claude_onboarding.state_path())

        try:
            if complete:
                async with (
                    self._claude_update.access.write(),
                    self._config_publication.read(),
                ):
                    self._check_integration_available()
                    return await run_sync_owned(operate)
            async with self._claude_update.access.read():
                self._check_integration_available()
                result = await run_sync_owned(operate)
                self._check_integration_available()
                return result
        except (ValueError, UnicodeError):
            raise InvalidRequestError(
                "Could not read Claude onboarding state. Check the JSON in .claude.json."
            ) from None
        except OSError:
            raise ApplicationUnavailableError(
                "Could not access .claude.json. Check file permissions and try again."
            ) from None

    def _check_integration_available(self) -> None:
        if self._is_draining() or self._has_pending_restart():
            raise ApplicationUnavailableError(
                "Wait for FCC to restart before changing the integration."
            )

    async def _read_status(
        self,
        update: _IntegrationUpdate,
        operation: Callable[[str, str, bool], JsonObject],
        *,
        mask_when_unready: bool = False,
    ) -> JsonObject:
        for _ in range(2):
            async with update.access.read():
                self._check_integration_available()
                generation = self.provider_manager.current_generation_id
                url = local_proxy_root_url(self.settings)
                token = self.settings.proxy_auth_token
                ready = update.state == "ready"
                failure: ValueError | OSError | None = None
                result: JsonObject = {}
                try:
                    result = await run_sync_owned(partial(operation, url, token, ready))
                except (ValueError, OSError) as exc:
                    failure = exc
                self._check_integration_available()
                if generation != self.provider_manager.current_generation_id or (
                    mask_when_unready and not ready and update.state == "ready"
                ):
                    continue
                if failure is not None:
                    raise failure
                if mask_when_unready and update.state != "ready":
                    result["connected"] = None
                result["update"] = update.snapshot()
                return result
        raise ApplicationUnavailableError(
            "FCC configuration changed during the check. Retry shortly."
        )

    async def _run_integration(
        self,
        update: _IntegrationUpdate,
        action: IntegrationAction,
        operation: Callable[[str, str, bool], JsonObject],
        *,
        mask_when_unready: bool = False,
    ) -> JsonObject:
        if action == "status":
            return await self._read_status(
                update, operation, mask_when_unready=mask_when_unready
            )
        async with update.access.write(), self._config_publication.read():
            self._check_integration_available()
            url = local_proxy_root_url(self.settings)
            token = self.settings.proxy_auth_token
            result = await run_sync_owned(partial(operation, url, token, True))
            update.complete(action == "refresh" and result.get("changed") is True)
            return result

    def _start_integration_update(
        self,
        update: _IntegrationUpdate,
        operation: Callable[[], Awaitable[JsonObject]],
    ) -> JsonObject:
        self._check_integration_available()
        if update.task is None or update.task.done():
            update.state, update.changed, update.message = "starting", False, None

            async def run() -> None:
                try:
                    result = await operation()
                    update.complete(result.get("changed") is True)
                except ApplicationError as exc:
                    update.state, update.message = "failed", exc.message
                except Exception as exc:
                    update.state = "failed"
                    update.message = (
                        "Could not update integration settings. Retry shortly."
                    )
                    logger.warning(
                        "Integration update failed: exc_type={}", type(exc).__name__
                    )

            update.task = asyncio.create_task(run(), name="fcc-integration-update")
        return {"update": update.snapshot()}

    async def refresh_claude_vscode(self) -> JsonObject:
        return self._start_integration_update(
            self._claude_update, partial(self._claude_vscode, "refresh")
        )

    async def refresh_codex_integration(self) -> JsonObject:
        return self._start_integration_update(
            self._codex_update, partial(self._codex_integration, "refresh")
        )

    async def jetbrains_acp_status(self) -> JsonObject:
        return await self._jetbrains_acp("status")

    async def connect_jetbrains_acp(self) -> JsonObject:
        return await self._jetbrains_acp("connect")

    async def disconnect_jetbrains_acp(self) -> JsonObject:
        return await self._jetbrains_acp("disconnect")

    async def refresh_jetbrains_acp(self) -> JsonObject:
        return self._start_integration_update(
            self._jetbrains_update, partial(self._jetbrains_acp, "refresh")
        )

    async def _jetbrains_acp(self, action: IntegrationAction) -> JsonObject:
        def operate(url: str, token: str, ready: bool) -> JsonObject:
            path = jetbrains_acp_integration.config_path()
            if action == "refresh":
                return {
                    "changed": jetbrains_acp_integration.refresh_connected(
                        path, url, token
                    )
                }
            return jetbrains_acp_integration.configure(
                path, url, token, None if action == "status" else action == "connect"
            )

        try:
            return await self._run_integration(self._jetbrains_update, action, operate)
        except jetbrains_acp_integration.SetupError as exc:
            raise InvalidRequestError(str(exc)) from None
        except (ValueError, UnicodeError):
            raise InvalidRequestError(
                "Could not read JetBrains ACP configuration. Check the JSON in acp.json and the installed Claude Agent metadata."
            ) from None
        except OSError:
            raise ApplicationUnavailableError(
                "Could not access JetBrains ACP files. Finish any configuration edits, check file permissions, and retry."
            ) from None

    async def claude_desktop_status(self) -> JsonObject:
        return await self._claude_desktop("status")

    async def connect_claude_desktop(self) -> JsonObject:
        return await self._claude_desktop("connect")

    async def disconnect_claude_desktop(self) -> JsonObject:
        return await self._claude_desktop("disconnect")

    async def refresh_claude_desktop(self) -> JsonObject:
        return self._start_integration_update(
            self._desktop_update, partial(self._claude_desktop, "refresh")
        )

    async def _claude_desktop(self, action: IntegrationAction) -> JsonObject:
        def operate(url: str, token: str, ready: bool) -> JsonObject:
            root = claude_desktop_integration.config_root()
            if action == "refresh":
                return {
                    "changed": claude_desktop_integration.refresh_connected(
                        root,
                        url,
                        token,
                        disconnect_path=claude_desktop_disconnect_path(),
                    )
                }
            return claude_desktop_integration.configure(
                root,
                url,
                token,
                None if action == "status" else action == "connect",
                disconnect_path=claude_desktop_disconnect_path(),
            )

        try:
            return await self._run_integration(
                self._desktop_update, action, operate, mask_when_unready=True
            )
        except claude_desktop_integration.ManagedDesktopError:
            raise InvalidRequestError(
                "Claude Desktop is managed by an organization, or its policy could not be read. FCC can configure only unmanaged Desktop installations."
            ) from None
        except claude_desktop_integration.PendingDisconnectError:
            raise InvalidRequestError(
                "Finish disconnecting Claude Desktop before connecting again."
            ) from None
        except claude_desktop_integration.PendingMigrationError:
            raise InvalidRequestError(
                "Claude Desktop has data in its previous Windows location. Launch Claude Desktop once so it can migrate that data, fully quit it, then retry Connect."
            ) from None
        except (ValueError, UnicodeError):
            raise InvalidRequestError(
                "Could not configure Claude Desktop. Check its configuration JSON and FCC disconnect record, and ensure FCC uses a localhost address and a nonempty managed token."
            ) from None
        except OSError:
            raise ApplicationUnavailableError(
                "Could not access Claude Desktop settings or the FCC disconnect record. Fully quit Claude Desktop, check file permissions, and retry."
            ) from None

    async def _claude_vscode(self, action: IntegrationAction) -> JsonObject:
        def operate(url: str, token: str, ready: bool) -> JsonObject:
            path = claude_integration.settings_path()
            if action == "status" and not ready:
                return {
                    "connected": None,
                    "paths": {
                        "vscode_settings": str(path.resolve()),
                        "claude_state": str(claude_onboarding.state_path().absolute()),
                    },
                }
            if action == "refresh":
                return {
                    "changed": claude_integration.refresh_connected(path, url, token)
                }
            if action == "connect":
                claude_integration.configure(path, url, token)
                claude_onboarding.complete(claude_onboarding.state_path())
            result = claude_integration.configure(
                path,
                url,
                token,
                None if action == "status" else action == "connect",
            )
            if action == "status":
                result["paths"] = {
                    "vscode_settings": str(path.resolve()),
                    "claude_state": str(claude_onboarding.state_path().absolute()),
                }
            return result

        try:
            return await self._run_integration(
                self._claude_update, action, operate, mask_when_unready=True
            )
        except (ValueError, UnicodeError):
            files = (
                "VS Code settings.json and .claude.json"
                if action == "connect"
                else "VS Code settings.json"
            )
            raise InvalidRequestError(
                f"Could not read Claude integration settings. Check the JSON in {files}."
            ) from None
        except OSError:
            files = (
                "VS Code settings.json or .claude.json"
                if action == "connect"
                else "VS Code settings.json"
            )
            raise ApplicationUnavailableError(
                f"Could not access {files}. Check file permissions and try again."
            ) from None

    async def codex_integration_status(self) -> JsonObject:
        return await self._codex_integration("status")

    async def connect_codex(self) -> JsonObject:
        return await self._codex_integration("connect")

    async def disconnect_codex(self) -> JsonObject:
        return await self._codex_integration("disconnect")

    async def _codex_integration(self, action: IntegrationAction) -> JsonObject:
        wait = InitializationWait(None) if action == "refresh" else InitializationWait()
        needs_catalog = action in {"connect", "refresh"}
        try:
            if action == "status":

                def status(url: str, token: str, ready: bool) -> JsonObject:
                    path = codex_integration.config_path()
                    if not ready:
                        return {
                            "connected": None,
                            "paths": {"codex_config": str(path.resolve())},
                        }
                    return codex_integration.configure(
                        path, codex_model_catalog_path(), url
                    )

                return await self._read_status(
                    self._codex_update, status, mask_when_unready=True
                )
            if action == "refresh":
                existing = await self._read_status(
                    self._codex_update,
                    lambda url, token, ready: {
                        "connected": codex_integration.recognizes_connection(
                            codex_integration.config_path(), url
                        )
                    },
                )
                if not existing["connected"]:
                    return {"changed": False}
            while True:
                catalog_version = (
                    await self.provider_manager.wait_for_catalog_file(wait)
                    if needs_catalog
                    else None
                )
                async with (
                    self._codex_update.access.write(),
                    self._config_publication.read(),
                ):
                    self._check_integration_available()
                    if needs_catalog and (
                        catalog_version
                        != (
                            self.provider_manager.current_generation_id,
                            self.provider_manager.catalog_status()["catalog_revision"],
                        )
                    ):
                        continue
                    url = local_proxy_root_url(self.settings)

                    def operate(url: str = url) -> JsonObject:
                        path = codex_integration.config_path()
                        if action == "refresh":
                            return {
                                "changed": codex_integration.refresh_connected(
                                    path, codex_model_catalog_path(), url
                                )
                            }
                        return codex_integration.configure(
                            path,
                            codex_model_catalog_path(),
                            url,
                            action == "connect",
                        )

                    result = await run_sync_owned(operate)
                    if action in {"connect", "disconnect"}:
                        self._codex_update.complete()
                    return result
        except (ValueError, UnicodeError):
            raise InvalidRequestError(
                "Could not read Codex settings. Check the TOML in config.toml."
            ) from None
        except OSError:
            raise ApplicationUnavailableError(
                "Could not access Codex config.toml. Check file permissions and try again."
            ) from None