Repository navigation
Expand file tree
/
Copy pathproxy.py
More file actions
7125 lines (6385 loc) · 274 KB
/
Copy pathproxy.py
File metadata and controls
7125 lines (6385 loc) · 274 KB
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Lightweight GitHub Copilot reverse proxy — Responses API path.
Designed for Codex / codex-mini / gpt-5.1-codex and any model that
requires the Responses API instead of Chat Completions.
Usage:
python proxy.py
→ If no token exists, prompts you to authorize via GitHub device flow
→ Then starts serving on http://127.0.0.1:8000
Configure Codex:
export OPENAI_BASE_URL=http://127.0.0.1:8000/v1
export OPENAI_API_KEY=anything
"""
import base64
import copy
import os
import sys
def _prepare_standalone_process_file_descriptors():
"""Avoid inheriting a descriptor table that is already near the soft limit."""
try:
import resource
except ImportError:
return
try:
soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
except (OSError, ValueError):
return
target_limit = 4096
if hard_limit != resource.RLIM_INFINITY:
target_limit = min(target_limit, hard_limit)
if soft_limit < target_limit:
try:
resource.setrlimit(resource.RLIMIT_NOFILE, (target_limit, hard_limit))
soft_limit = target_limit
except (OSError, ValueError):
pass
try:
close_until = int(soft_limit)
except (OverflowError, ValueError):
close_until = 4096
os.closerange(3, max(3, close_until))
if __name__ == "__main__":
_prepare_standalone_process_file_descriptors()
import asyncio
import auth
import atexit
import auto_update
import background_proxy
import codex_agent_compat
import codex_native_ingest
import copilot_sdk_upstream
import dashboard as dashboard_module
import excel_session_capture
import excel_model_catalog
import excel_upstream
import format_translation
import gzip
import hashlib
import messages_preprocess
import migrate_runtime_paths
import json
import sqlite3
import ssl
import tempfile
import time
import threading
import safeguard_config as safeguard_config_module
import protocol_replies
import upstream_errors
import update_notice
import usage_reminder
import usage_tracking
import util
from collections import OrderedDict, deque
from dataclasses import dataclass, field
from threading import Lock, Thread
from urllib.parse import urlsplit
from uuid import uuid4
import httpx
import uvicorn
from anyio import CancelScope
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response, StreamingResponse
from starlette.requests import ClientDisconnect
from anthropic_stream import AnthropicStreamTranslator
from bridge_streams import (
AnthropicToResponsesStreamTranslator,
ChatToResponsesStreamTranslator,
ResponsesStreamIdSyncer,
ResponsesToAnthropicStreamTranslator,
)
from initiator_policy import InitiatorPolicy, is_approval_agent_request
from event_bus import EventBus
from model_routing_config import ModelRoutingConfig, ModelRoutingConfigService, model_provider_family, normalize_routing_model_name
from protocol_bridge import BridgeExecutionPlan, ProtocolBridgePlanner
from proxy_client_config import (
ProxyClientConfig,
ProxyClientConfigService,
normalize_proxy_targets,
)
# ─── Import from new modules ─────────────────────────────────────────────────
from constants import (
CLIENT_PROXY_SETTINGS_FILE,
DASHBOARD_FILE,
DETAILED_REQUEST_HISTORY_LIMIT,
CODEX_PRIMARY_CONFIG_FILE,
CODEX_MANAGED_CONFIG_FILE,
CODEX_PROXY_MODEL_CATALOG_FILE,
CODEX_PROXY_CONFIG,
CODEX_PROXY_MODEL_CONTEXT_WINDOW,
CODEX_PROXY_MODEL_AUTO_COMPACT_TOKEN_LIMIT,
CLAUDE_SETTINGS_FILE,
CLAUDE_PROXY_SETTINGS,
CLAUDE_MAX_CONTEXT_TOKENS,
CLAUDE_MAX_OUTPUT_TOKENS,
DEFAULT_UPSTREAM_TIMEOUT_SECONDS,
EXCEL_IMAGE_FILE_ID_CACHE_FILE,
LEGACY_BILLING_TOKEN_FILE,
LEGACY_PREMIUM_PLAN_CONFIG_FILE,
PROXY_PID_FILE,
REQUEST_TRACE_LOG_FILE,
REQUEST_PROMPT_ARCHIVE_DIR,
REQUEST_TRACE_HISTORY_LIMIT,
REQUEST_TRACE_RETENTION_SLACK,
REQUEST_TRACE_BODY_MAX_BYTES,
REQUEST_PROMPT_PREVIEW_MAX_CHARS,
TOKEN_DIR,
)
from rate_limiting import (
throttle_upstream_request,
throttled_client_post,
throttled_client_send,
)
# ─── App & Global State ──────────────────────────────────────────────────────
app = FastAPI()
_REQUEST_TRACE_LOCK = Lock()
_REQUEST_PROMPT_LOCK = Lock()
_REQUEST_PROMPT_ACTIVE_IDS: set[str] = set()
_REQUEST_PROMPT_FILE_PREFIX = "request-prompt-"
# Prompt archives are retained for drill-downs, but pruning the directory on
# every completed request turns normal proxy traffic into a directory scan and
# delete workload. Keep the cleanup opportunistic and amortized.
_REQUEST_PROMPT_PRUNE_INTERVAL_SECONDS = 60.0
_REQUEST_PROMPT_LAST_PRUNED_MONOTONIC = 0.0
_CLIENT_PROXY_STARTUP_RESTORE_LOCK = Lock()
_CLIENT_PROXY_STARTUP_RESTORE_COMPLETE = False
_CLIENT_PROXY_SHUTDOWN_REVERT_LOCK = Lock()
_CLIENT_PROXY_SHUTDOWN_REVERT_COMPLETE = False
migrated_runtime_files = migrate_runtime_paths.migrate_legacy_runtime_files()
if migrated_runtime_files:
print(f"runtime migration: copied {len(migrated_runtime_files)} legacy file(s)", flush=True)
_TRACE_HEADER_ALLOWLIST = {
"content-type",
"user-agent",
"openai-intent",
"editor-version",
"editor-plugin-version",
"copilot-integration-id",
"x-initiator",
"copilot-vision-request",
"anthropic-beta",
"session_id",
"x-client-request-id",
"x-openai-subagent",
"x-interaction-id",
"x-interaction-type",
"x-agent-task-id",
"x-parent-agent-id",
"x-client-session-id",
"x-client-machine-id",
"x-copilot-client-exp-assignment-context",
"x-github-api-version",
"x-stainless-retry-count",
"x-stainless-lang",
"x-stainless-package-version",
"x-stainless-os",
"x-stainless-arch",
"x-stainless-runtime",
"x-stainless-runtime-version",
"accept-language",
"sec-fetch-mode",
"x-request-id",
"x-github-request-id",
"accept",
"accept-encoding",
"host",
"connection",
"content-length",
}
AUTH_FAILURE_MESSAGE = "GitHub Copilot authorization required. Open /ui to sign in."
INVALID_BRIDGE_REQUEST_MESSAGE = "Invalid request"
DEBUG_DETAIL_CONTEXT_REQUESTS = 10
safeguard_event_store = dashboard_module.create_safeguard_event_store()
_DEBUG_DETAIL_CAPTURE_LOCK = threading.Lock()
DEBUG_DETAIL_SESSION_BUFFER_LIMIT = 64
_DEBUG_DETAIL_REQUEST_SNAPSHOT_INDEX_MAXLEN = DEBUG_DETAIL_SESSION_BUFFER_LIMIT
DEBUG_DETAIL_SESSION_DETAIL_LIMIT = DEBUG_DETAIL_CONTEXT_REQUESTS
_DEBUG_DETAIL_SESSION_RECENT_REQUESTS: OrderedDict[str, deque[dict]] = OrderedDict()
_DEBUG_DETAIL_REQUEST_SNAPSHOTS_BY_ID: OrderedDict[str, dict] = OrderedDict()
_DEBUG_DETAIL_SESSION_CAPTURED_REQUEST_IDS: OrderedDict[str, set[str]] = OrderedDict()
_DEBUG_DETAIL_SNAPSHOT_SEQUENCE = 0
# Cache-settle bookkeeping remains for trace compatibility, but production
# requests never pause for upstream cache visibility.
_PROMPT_CACHE_SETTLE_LOCK = threading.Lock()
_PROMPT_CACHE_LAST_FINISH_BY_FAMILY: dict[tuple[str, str], tuple[str, float]] = {}
_PROMPT_CACHE_LAST_PRUNE_AT = 0.0
def _reset_debug_detail_capture_state() -> None:
global _DEBUG_DETAIL_SNAPSHOT_SEQUENCE
with _DEBUG_DETAIL_CAPTURE_LOCK:
_DEBUG_DETAIL_SESSION_RECENT_REQUESTS.clear()
_DEBUG_DETAIL_REQUEST_SNAPSHOTS_BY_ID.clear()
_DEBUG_DETAIL_SESSION_CAPTURED_REQUEST_IDS.clear()
_DEBUG_DETAIL_SNAPSHOT_SEQUENCE = 0
def _stream_with_update_notice(byte_iter, protocol: str, upstream_headers=None):
notices: list[str] = []
update_text = auto_update_runtime_controller.update_notice_text_if_due()
if update_text:
notices.append(update_text)
usage_windows = usage_tracking.extract_usage_ratelimits_from_headers(upstream_headers)
usage_text = usage_reminder_controller.usage_notice_text_if_due(usage_windows)
if usage_text:
notices.append(usage_text)
if not notices:
return byte_iter
notice_text = "\n\n".join(notices)
return update_notice.inject_text_notice(byte_iter, protocol, notice_text)
def _record_safeguard_trigger(event: dict):
safeguard_event_store.record_event(event)
try:
dashboard_service.notify_dashboard_stream_listeners()
except NameError:
pass
_initiator_policy = InitiatorPolicy(on_safeguard_triggered=_record_safeguard_trigger)
safeguard_config_service = safeguard_config_module.SafeguardConfigService(
safeguard_config_module.SafeguardConfig()
)
def _apply_safeguard_settings(settings: dict):
cooldown = settings.get("cooldown_seconds") if isinstance(settings, dict) else None
if isinstance(cooldown, (int, float)):
_initiator_policy.request_finish_guard_seconds = float(cooldown)
_apply_safeguard_settings(safeguard_config_service.load_settings())
usage_event_bus = EventBus()
class GracefulStreamingResponse(StreamingResponse):
"""Suppress shutdown/disconnect cancellation noise for long-lived streams."""
async def __call__(self, scope, receive, send):
try:
await super().__call__(scope, receive, send)
except (asyncio.CancelledError, ClientDisconnect):
return
finally:
# ASGI 2.3 can return normally after its disconnect task cancels
# the streaming task, while ASGI 2.4 raises outside the iterator.
# Always close the body owner, including when response.start fails
# before the first body iteration.
close_iterator = getattr(self.body_iterator, "aclose", None)
if callable(close_iterator):
with CancelScope(shield=True):
await close_iterator()
def set_initiator_policy(policy: InitiatorPolicy):
global _initiator_policy
policy.on_safeguard_triggered = _record_safeguard_trigger
_initiator_policy = policy
_apply_safeguard_settings(safeguard_config_service.load_settings())
usage_tracker.on_request_finished = policy.note_request_finished
def request_prompt_archive_dir() -> str:
configured = str(os.environ.get("GHCP_REQUEST_PROMPT_ARCHIVE_DIR", "")).strip()
return os.path.expanduser(configured or REQUEST_PROMPT_ARCHIVE_DIR)
def _request_prompt_file_name(request_id: str | None) -> str | None:
if not isinstance(request_id, str):
return None
normalized_request_id = request_id.strip()
if not normalized_request_id:
return None
safe_request_id = "".join(
ch if ch.isalnum() or ch in {"-", "_", "."} else "_"
for ch in normalized_request_id
)
if not safe_request_id:
return None
return f"{_REQUEST_PROMPT_FILE_PREFIX}{safe_request_id}.json"
def _request_prompt_file_path(request_id: str | None) -> str | None:
filename = _request_prompt_file_name(request_id)
if filename is None:
return None
return os.path.join(request_prompt_archive_dir(), filename)
def _save_request_prompt_record(
request_id: str | None,
request_path: str | None,
request_body: dict | None,
) -> None:
archive_path = _request_prompt_file_path(request_id)
if archive_path is None or not isinstance(request_body, dict):
return
prompt_text = util.extract_request_prompt_text(request_body)
if not prompt_text:
return
record = {
"request_id": request_id,
"path": request_path,
"stored_at": util.utc_now_iso(),
"char_count": len(prompt_text),
"prompt_text": prompt_text,
}
archive_dir = os.path.dirname(archive_path)
temp_path = None
try:
os.makedirs(archive_dir, exist_ok=True)
with _REQUEST_PROMPT_LOCK:
_REQUEST_PROMPT_ACTIVE_IDS.add(str(request_id))
fd, temp_path = tempfile.mkstemp(prefix="request-prompt-", suffix=".tmp", dir=archive_dir)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(json.dumps(record, separators=(",", ":"), default=util._json_default))
os.replace(temp_path, archive_path)
except OSError as exc:
with _REQUEST_PROMPT_LOCK:
_REQUEST_PROMPT_ACTIVE_IDS.discard(str(request_id))
if temp_path is not None:
try:
os.unlink(temp_path)
except OSError:
pass
print(f"Warning: failed to write request prompt archive: {exc}", file=sys.stderr, flush=True)
def _load_request_prompt_record(request_id: str | None) -> dict | None:
archive_path = _request_prompt_file_path(request_id)
if archive_path is None or not os.path.exists(archive_path):
return None
try:
with open(archive_path, encoding="utf-8") as handle:
payload = json.load(handle)
except (OSError, json.JSONDecodeError):
return None
if not isinstance(payload, dict):
return None
prompt_text = payload.get("prompt_text")
if not isinstance(prompt_text, str) or not prompt_text.strip():
return None
char_count = payload.get("char_count")
if not isinstance(char_count, int):
char_count = len(prompt_text)
return {
"request_id": payload.get("request_id") if isinstance(payload.get("request_id"), str) else request_id,
"path": payload.get("path") if isinstance(payload.get("path"), str) else None,
"stored_at": payload.get("stored_at") if isinstance(payload.get("stored_at"), str) else None,
"char_count": char_count,
"prompt_text": prompt_text,
}
def _recent_request_prompt_ids() -> set[str]:
keep_ids = {
request_id
for event in usage_tracker.snapshot_usage_events()
if isinstance(event, dict)
for request_id in [event.get("request_id")]
if isinstance(request_id, str) and request_id
}
with _REQUEST_PROMPT_LOCK:
keep_ids.update(_REQUEST_PROMPT_ACTIVE_IDS)
return keep_ids
def _prune_request_prompt_archive(request_ids: set[str] | None = None) -> None:
global _REQUEST_PROMPT_LAST_PRUNED_MONOTONIC
if request_ids is None:
now = time.monotonic()
with _REQUEST_PROMPT_LOCK:
if now - _REQUEST_PROMPT_LAST_PRUNED_MONOTONIC < _REQUEST_PROMPT_PRUNE_INTERVAL_SECONDS:
return
_REQUEST_PROMPT_LAST_PRUNED_MONOTONIC = now
archive_dir = request_prompt_archive_dir()
if not os.path.isdir(archive_dir):
return
keep_ids = set(request_ids or _recent_request_prompt_ids())
keep_files = {
filename
for request_id in keep_ids
if (filename := _request_prompt_file_name(request_id)) is not None
}
try:
with _REQUEST_PROMPT_LOCK:
for entry in os.listdir(archive_dir):
if not entry.startswith(_REQUEST_PROMPT_FILE_PREFIX) or not entry.endswith(".json"):
continue
if entry in keep_files:
continue
try:
os.unlink(os.path.join(archive_dir, entry))
except OSError:
continue
except OSError as exc:
print(f"Warning: failed to prune request prompt archive: {exc}", file=sys.stderr, flush=True)
def _handle_usage_event_recorded(event: dict | None) -> None:
request_id = event.get("request_id") if isinstance(event, dict) else None
if isinstance(request_id, str) and request_id:
with _REQUEST_PROMPT_LOCK:
_REQUEST_PROMPT_ACTIVE_IDS.discard(request_id)
_prune_request_prompt_archive()
dashboard_service.notify_dashboard_stream_listeners()
usage_tracker = usage_tracking.UsageTracker(
state=usage_tracking.UsageTrackingState(),
archive_store=dashboard_module.create_usage_archive_store(),
event_bus=usage_event_bus,
on_request_finished=_initiator_policy.note_request_finished,
on_usage_event_recorded=_handle_usage_event_recorded,
)
usage_reminder_controller = usage_reminder.UsageReminderController(
usage_tracker.snapshot_all_usage_events,
)
model_routing_config_service = ModelRoutingConfigService(
ModelRoutingConfig(),
model_capabilities_provider=lambda: fetch_available_model_capabilities(),
)
client_proxy_config_service = ProxyClientConfigService(
ProxyClientConfig(
codex_primary_config_file=CODEX_PRIMARY_CONFIG_FILE,
codex_managed_config_file=CODEX_MANAGED_CONFIG_FILE,
codex_model_catalog_file=CODEX_PROXY_MODEL_CATALOG_FILE,
codex_proxy_config=CODEX_PROXY_CONFIG,
codex_model_context_window=CODEX_PROXY_MODEL_CONTEXT_WINDOW,
codex_model_auto_compact_token_limit=CODEX_PROXY_MODEL_AUTO_COMPACT_TOKEN_LIMIT,
claude_settings_file=CLAUDE_SETTINGS_FILE,
claude_proxy_settings=CLAUDE_PROXY_SETTINGS,
claude_max_context_tokens=CLAUDE_MAX_CONTEXT_TOKENS,
claude_max_output_tokens=CLAUDE_MAX_OUTPUT_TOKENS,
client_proxy_settings_file=CLIENT_PROXY_SETTINGS_FILE,
),
model_capabilities_provider=lambda: fetch_available_model_capabilities(),
model_routing_settings_provider=lambda: model_routing_config_service.load_settings(),
)
background_proxy_manager = background_proxy.BackgroundProxyManager()
auto_update_manager = auto_update.AutoUpdateManager()
auto_update_runtime_controller = auto_update.AutoUpdateRuntimeController(auto_update_manager)
bridge_planner = ProtocolBridgePlanner(
model_routing_config_service,
capability_resolver=lambda model: model_supports_native_messages(model) if model else False,
)
def _debug_prompt_logging_settings() -> dict[str, object]:
try:
settings = client_proxy_config_service.load_client_proxy_settings()
except Exception:
return {}
return settings if isinstance(settings, dict) else {}
def _debug_prompt_logging_enabled() -> bool:
return bool(_debug_prompt_logging_settings().get("debug_prompt_logging_enabled", False))
def _prompt_logging_permitted() -> bool:
return _debug_prompt_logging_enabled()
def _prompt_trace_value(value):
return value
def _prompt_payload_for_dashboard(value):
return value
def _client_proxy_settings_with_trace_status(payload: dict[str, object]) -> dict[str, object]:
return dict(payload)
def _save_client_proxy_settings(payload: dict) -> dict[str, object]:
if not isinstance(payload, dict):
raise HTTPException(status_code=400, detail="Request body must be an object")
# Forward only the keys the caller sent; the service merges them with the
# saved settings so a partial update leaves the other settings unchanged.
result = client_proxy_config_service.save_client_proxy_settings({
key: payload[key]
for key in ("revert_on_shutdown", "debug_prompt_logging_enabled", "setup_skipped")
if key in payload
})
try:
dashboard_service.notify_dashboard_stream_listeners()
except NameError:
pass
return _client_proxy_settings_with_trace_status(result)
dashboard_service = dashboard_module.create_dashboard_service(
dependencies=dashboard_module.DashboardDependencies(
load_api_key_payload=auth.load_api_key_payload,
snapshot_all_usage_events=usage_tracker.snapshot_all_usage_events,
snapshot_usage_events=usage_tracker.snapshot_usage_events,
native_lifecycle_revision=usage_tracker.native_lifecycle_revision,
snapshot_native_http_timings=codex_native_ingest.snapshot_native_http_timings,
native_http_timing_revision=codex_native_ingest.native_http_timing_revision,
usage_snapshots_are_deduplicated=True,
load_safeguard_trigger_stats=safeguard_event_store.load_stats,
prompt_payload=_prompt_payload_for_dashboard,
),
utc_now=util.utc_now,
utc_now_iso=util.utc_now_iso,
thread_class=Thread,
)
async def parse_json_request(request: Request) -> dict:
return await util.parse_json_request(request, error_callback=usage_tracker.record_request_error)
def configured_upstream_timeout_seconds() -> int:
raw = str(os.environ.get("GHCP_UPSTREAM_TIMEOUT_SECONDS", "")).strip()
if not raw:
return DEFAULT_UPSTREAM_TIMEOUT_SECONDS
try:
value = int(raw)
except ValueError:
print(
f"Warning: ignoring invalid GHCP_UPSTREAM_TIMEOUT_SECONDS={raw!r}; using {DEFAULT_UPSTREAM_TIMEOUT_SECONDS}",
file=sys.stderr,
flush=True,
)
return DEFAULT_UPSTREAM_TIMEOUT_SECONDS
if value <= 0:
print(
f"Warning: GHCP_UPSTREAM_TIMEOUT_SECONDS must be > 0; using {DEFAULT_UPSTREAM_TIMEOUT_SECONDS}",
file=sys.stderr,
flush=True,
)
return DEFAULT_UPSTREAM_TIMEOUT_SECONDS
return value
def _first_non_empty_env(names: tuple[str, ...]) -> tuple[str | None, str | None]:
for name in names:
raw = os.environ.get(name)
if not isinstance(raw, str):
continue
value = raw.strip()
if value:
return value, name
return None, None
def _apply_upstream_proxy_env_aliases() -> tuple[str, ...]:
"""Apply GHCP-specific proxy aliases to standard HTTP(S)_PROXY keys.
httpx reads standard proxy environment variables when ``trust_env=True``.
This helper lets operators provide GHCP-specific aliases (for example in a
launchd plist) without overwriting already-defined standard values.
"""
applied: list[str] = []
https_proxy, _ = _first_non_empty_env(("HTTPS_PROXY", "https_proxy"))
http_proxy, _ = _first_non_empty_env(("HTTP_PROXY", "http_proxy"))
no_proxy, _ = _first_non_empty_env(("NO_PROXY", "no_proxy"))
ghcp_proxy, _ = _first_non_empty_env(("GHCP_UPSTREAM_PROXY",))
ghcp_https_proxy, _ = _first_non_empty_env(("GHCP_HTTPS_PROXY",))
ghcp_http_proxy, _ = _first_non_empty_env(("GHCP_HTTP_PROXY",))
ghcp_no_proxy, _ = _first_non_empty_env(("GHCP_NO_PROXY",))
if https_proxy is None:
chosen_https = ghcp_https_proxy or ghcp_proxy
if chosen_https:
os.environ["HTTPS_PROXY"] = chosen_https
os.environ.setdefault("https_proxy", chosen_https)
applied.append("HTTPS_PROXY")
if http_proxy is None:
chosen_http = ghcp_http_proxy or ghcp_proxy
if chosen_http:
os.environ["HTTP_PROXY"] = chosen_http
os.environ.setdefault("http_proxy", chosen_http)
applied.append("HTTP_PROXY")
if no_proxy is None and ghcp_no_proxy:
os.environ["NO_PROXY"] = ghcp_no_proxy
os.environ.setdefault("no_proxy", ghcp_no_proxy)
applied.append("NO_PROXY")
return tuple(applied)
def _optional_env_bool(name: str) -> bool | None:
raw = str(os.environ.get(name, "")).strip().lower()
if not raw:
return None
if raw in {"1", "true", "yes", "on"}:
return True
if raw in {"0", "false", "no", "off"}:
return False
print(
f"Warning: ignoring invalid {name}={raw!r}; expected true/false",
file=sys.stderr,
flush=True,
)
return None
def _upstream_proxy_configured() -> bool:
https_proxy, _ = _first_non_empty_env(
("HTTPS_PROXY", "https_proxy", "GHCP_HTTPS_PROXY", "GHCP_UPSTREAM_PROXY"),
)
http_proxy, _ = _first_non_empty_env(
("HTTP_PROXY", "http_proxy", "GHCP_HTTP_PROXY", "GHCP_UPSTREAM_PROXY"),
)
return bool(https_proxy or http_proxy)
def _configured_upstream_tls_verify(proxy_configured: bool) -> tuple[bool, str]:
explicit = _optional_env_bool("GHCP_UPSTREAM_TLS_VERIFY")
if explicit is not None:
return explicit, "GHCP_UPSTREAM_TLS_VERIFY"
if proxy_configured:
# Enterprise HTTPS interception proxies often terminate TLS with an
# internal CA that isn't present in certifi-based trust stores.
return False, "proxy_default"
return True, "default"
def _configured_upstream_http2(proxy_configured: bool) -> tuple[bool, str]:
explicit = _optional_env_bool("GHCP_UPSTREAM_HTTP2")
if explicit is not None:
return explicit, "GHCP_UPSTREAM_HTTP2"
if proxy_configured:
return False, "proxy_default"
return True, "default"
_UPSTREAM_CLIENT: "httpx.AsyncClient | None" = None
_EXCEL_UPSTREAM_CLIENT: "httpx.AsyncClient | None" = None
_UPSTREAM_CLIENT_LOCK = threading.Lock()
_UPSTREAM_CLIENT_SHUTDOWN_REGISTERED = False
_EXCEL_NON_STREAMING_RETRY_ATTEMPTS = 2
_EXCEL_STREAM_IDLE_TIMEOUT_SECONDS = 120
def _build_upstream_client(
*,
http2_override: bool | None = None,
keepalive_expiry: float = 300.0,
) -> "httpx.AsyncClient":
proxy_aliases = _apply_upstream_proxy_env_aliases()
if proxy_aliases:
print(
f"Configured upstream proxy environment aliases: {', '.join(proxy_aliases)}",
flush=True,
)
proxy_configured = _upstream_proxy_configured()
tls_verify, tls_verify_source = _configured_upstream_tls_verify(proxy_configured)
if http2_override is None:
upstream_http2, upstream_http2_source = _configured_upstream_http2(proxy_configured)
else:
upstream_http2, upstream_http2_source = http2_override, "client_override"
if not tls_verify and tls_verify_source == "proxy_default":
print(
"Upstream proxy detected: defaulting GHCP upstream TLS verification off. "
"Set GHCP_UPSTREAM_TLS_VERIFY=1 once a trusted proxy CA bundle is configured.",
flush=True,
)
elif not tls_verify:
print(
"GHCP_UPSTREAM_TLS_VERIFY disabled: upstream TLS certificates will not be validated.",
flush=True,
)
if not upstream_http2 and upstream_http2_source == "proxy_default":
print(
"Upstream proxy detected: defaulting GHCP upstream HTTP/2 off for compatibility.",
flush=True,
)
timeout = httpx.Timeout(configured_upstream_timeout_seconds())
limits = httpx.Limits(
max_connections=8,
max_keepalive_connections=4,
keepalive_expiry=keepalive_expiry,
)
try:
return httpx.AsyncClient(
http2=upstream_http2,
timeout=timeout,
limits=limits,
verify=tls_verify,
trust_env=True,
)
except (ImportError, RuntimeError):
return httpx.AsyncClient(
timeout=timeout,
limits=limits,
verify=tls_verify,
trust_env=True,
)
def _ensure_upstream_client_shutdown_registered() -> None:
global _UPSTREAM_CLIENT_SHUTDOWN_REGISTERED
if not _UPSTREAM_CLIENT_SHUTDOWN_REGISTERED:
atexit.register(_shutdown_upstream_client)
_UPSTREAM_CLIENT_SHUTDOWN_REGISTERED = True
def _get_upstream_client() -> "httpx.AsyncClient":
global _UPSTREAM_CLIENT
if _UPSTREAM_CLIENT is not None:
return _UPSTREAM_CLIENT
with _UPSTREAM_CLIENT_LOCK:
if _UPSTREAM_CLIENT is None:
_UPSTREAM_CLIENT = _build_upstream_client()
_ensure_upstream_client_shutdown_registered()
return _UPSTREAM_CLIENT
def _get_excel_upstream_client() -> "httpx.AsyncClient":
"""Keep Excel traffic isolated from the shared Copilot transport pool."""
global _EXCEL_UPSTREAM_CLIENT
if _EXCEL_UPSTREAM_CLIENT is not None:
return _EXCEL_UPSTREAM_CLIENT
with _UPSTREAM_CLIENT_LOCK:
if _EXCEL_UPSTREAM_CLIENT is None:
# Avoid retaining idle proxy-tunneled sockets for five minutes.
# This limits stale reuse, not failures in an already-open stream.
_EXCEL_UPSTREAM_CLIENT = _build_upstream_client(
http2_override=False, keepalive_expiry=5.0
)
_ensure_upstream_client_shutdown_registered()
return _EXCEL_UPSTREAM_CLIENT
class _DownstreamDisconnectedBeforeResponse(RuntimeError):
def __init__(self, transport_close: str):
super().__init__("downstream disconnected before the upstream response started")
self.transport_close = transport_close
async def _wait_for_downstream_disconnect(request: Request) -> None:
"""Wait on the ASGI receive channel after the request body was consumed."""
while True:
message = await request.receive()
if message.get("type") == "http.disconnect":
return
async def _open_streaming_upstream(
client: httpx.AsyncClient,
request: httpx.Request,
*,
trace_plan: "UpstreamRequestPlan | None",
downstream_request: Request | None,
active_stream: "_ActiveResponsesStream | None" = None,
) -> httpx.Response:
"""Open an upstream stream while observing pre-response disconnects.
Starlette cannot monitor the downstream until a Response object is
returned. Copilot commonly aborts the old turn while this function is
still waiting for upstream headers, so own that earlier ASGI window here.
Once the upstream send has begun, wait for its response handle and cancel
the actual wire stream instead of abandoning an untracked generation.
"""
send_started = False
async def open_upstream() -> httpx.Response:
nonlocal send_started
await _wait_for_responses_cache_settle(trace_plan)
send_started = True
if active_stream is not None:
active_stream.send_started = True
upstream = await throttled_client_send(client, request, stream=True)
if active_stream is not None:
active_stream.upstream = upstream
return upstream
upstream_task = asyncio.create_task(open_upstream())
disconnect_task = (
asyncio.create_task(_wait_for_downstream_disconnect(downstream_request))
if downstream_request is not None
else None
)
try:
if disconnect_task is None:
return await asyncio.shield(upstream_task)
done, _pending = await asyncio.wait(
{upstream_task, disconnect_task},
return_when=asyncio.FIRST_COMPLETED,
)
if disconnect_task not in done:
disconnect_task.cancel()
with CancelScope(shield=True):
try:
await disconnect_task
except asyncio.CancelledError:
pass
return await upstream_task
if not send_started:
upstream_task.cancel()
with CancelScope(shield=True):
try:
await upstream_task
except (asyncio.CancelledError, Exception):
pass
raise _DownstreamDisconnectedBeforeResponse("not_sent")
# Do not cancel httpx while it is waiting for headers. On HTTP/2 that
# can discard the only object through which we can send RST_STREAM.
# Wait for the handle, then explicitly end the server-side generation.
try:
upstream = await asyncio.shield(upstream_task)
except httpx.RequestError:
raise _DownstreamDisconnectedBeforeResponse(
"pre_response_request_error"
)
transport_close = await _close_upstream_response(
upstream,
cancel_generation=True,
)
raise _DownstreamDisconnectedBeforeResponse(transport_close)
except asyncio.CancelledError:
# Preserve the same ownership guarantee if the ASGI server cancels the
# route task directly instead of delivering http.disconnect.
with CancelScope(shield=True):
if not send_started:
upstream_task.cancel()
try:
upstream = await upstream_task
except (asyncio.CancelledError, Exception):
upstream = None
if upstream is not None and active_stream is None:
await _close_upstream_response(upstream, cancel_generation=True)
raise
finally:
if disconnect_task is not None and not disconnect_task.done():
disconnect_task.cancel()
with CancelScope(shield=True):
try:
await disconnect_task
except asyncio.CancelledError:
pass
def _shutdown_upstream_client() -> None:
global _UPSTREAM_CLIENT, _EXCEL_UPSTREAM_CLIENT
clients = [
client
for client in (_UPSTREAM_CLIENT, _EXCEL_UPSTREAM_CLIENT)
if client is not None
]
_UPSTREAM_CLIENT = None
_EXCEL_UPSTREAM_CLIENT = None
if not clients:
return
try:
loop = asyncio.new_event_loop()
try:
for client in clients:
loop.run_until_complete(client.aclose())
finally:
loop.close()
except Exception:
pass
def _proxy_port_in_use(host: str = "127.0.0.1", port: int = 8000) -> bool:
import socket
try:
with socket.create_connection((host, port), timeout=0.5):
return True
except OSError:
return False
def _write_proxy_pid_file() -> None:
try:
os.makedirs(os.path.dirname(PROXY_PID_FILE), exist_ok=True)
with open(PROXY_PID_FILE, "w", encoding="utf-8") as f:
f.write(str(os.getpid()))
f.write("\n")
except OSError as exc:
print(f"Warning: failed to write proxy pid file: {exc}", file=sys.stderr, flush=True)
def _remove_proxy_pid_file() -> None:
try:
with open(PROXY_PID_FILE, encoding="utf-8") as f:
recorded_pid = f.read().strip()
except OSError:
return
if recorded_pid != str(os.getpid()):
return
try:
os.remove(PROXY_PID_FILE)
except OSError:
pass
usage_tracker.load_archived_history()
usage_tracker.load_history()
_initiator_policy.seed_from_usage_events(usage_tracker.snapshot_usage_events())
dashboard_module.initialize()
try:
import codex_native_ingest
_codex_native_interval = float(os.environ.get("GHCP_CODEX_NATIVE_INGEST_INTERVAL", "5") or 5)
if _codex_native_interval > 0:
codex_native_ingest.start_background_scanner(
usage_tracker.record_usage_event,
interval_seconds=_codex_native_interval,
)
except Exception as _codex_ingest_exc: # pragma: no cover - best effort
print(f"codex_native_ingest: disabled ({_codex_ingest_exc})", flush=True)
try:
_copilot_sdk_interval = float(os.environ.get("GHCP_COPILOT_SDK_INGEST_INTERVAL", "5") or 5)
if _copilot_sdk_interval > 0:
copilot_sdk_upstream.start_background_scanner(
usage_tracker.record_usage_event,
interval_seconds=_copilot_sdk_interval,
)
except Exception as _sdk_ingest_exc: # pragma: no cover - best effort
print(f"copilot_sdk_ingest: disabled ({_sdk_ingest_exc})", flush=True)
@app.on_event("startup")
async def _app_startup_restore_client_proxy_configs():
excel_upstream.excel_session_store.load()
asyncio.create_task(asyncio.to_thread(
excel_session_capture.refresh_macos_excel_session,
excel_upstream.excel_session_store,
force=True,
))
asyncio.create_task(asyncio.to_thread(
excel_session_capture.refresh_windows_excel_session,
excel_upstream.excel_session_store,
force=True,
))
restore_client_proxy_configs_on_startup()
# Refresh any persisted picker catalog as well as request-time discovery.
# Run in the background so two independent backends cannot stall startup.
asyncio.create_task(asyncio.to_thread(
client_proxy_config_service.refresh_codex_model_catalog,
))
auto_update_runtime_controller.start_periodic_checks()
@app.on_event("shutdown")
async def _app_shutdown_revert_client_proxy_configs():
await auto_update_runtime_controller.stop_periodic_checks()
await copilot_sdk_upstream.shutdown()
revert_client_proxy_configs_on_shutdown()
def _extract_upstream_json_payload(upstream: httpx.Response) -> dict | None:
content_type = upstream.headers.get("content-type", "").lower()