workbuddy2api 2.0.7__py3-none-any.whl → 2.0.8.dev1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,7 +15,9 @@ Usage with uv:
15
15
 
16
16
  import argparse
17
17
  import asyncio
18
+ import copy
18
19
  from contextlib import asynccontextmanager, nullcontext
20
+ from contextvars import ContextVar
19
21
  import base64
20
22
  import hashlib
21
23
  import io
@@ -29,6 +31,7 @@ import pathlib
29
31
  import platform
30
32
  import sys
31
33
  import time
34
+ import tempfile
32
35
  import uuid
33
36
  from contextlib import AsyncExitStack
34
37
  from typing import Any, Optional
@@ -44,13 +47,16 @@ from codebuddy_proxy.backend_profile import (
44
47
  BackendProfile,
45
48
  ResolvedBackend,
46
49
  DOMESTIC_PROFILE,
50
+ GLOBAL_PROFILE,
51
+ resolve_backend,
47
52
  resolve_backend_from_args,
48
53
  )
49
54
  from codebuddy_proxy.codebuddy_client_demo import CodeBuddyClient, CodeBuddyError
50
- from codebuddy_proxy.billing_proxy import forward_billing
55
+ from daily_checkin.workbuddy_api import create_legacy_router
51
56
  from codebuddy_proxy.upstream_request import ChatRequestPreparer
52
57
  from codebuddy_proxy.protocol_response import format_nonstream_response
53
58
  from codebuddy_proxy.process_diagnostics import ProcessDiagnostics
59
+ from codebuddy_proxy.admin_api import create_admin_router
54
60
 
55
61
  # 尝试导入高级功能模块(可选)
56
62
  try:
@@ -180,8 +186,12 @@ class ProxyState:
180
186
  verbose_llm: bool = False,
181
187
  logger: logging.Logger | None = None,
182
188
  json_logger: logging.Logger | None = None,
189
+ account_manager=None,
183
190
  ):
184
- self.client = client
191
+ self._client = client
192
+ self.account_manager = account_manager
193
+ self.account_runtime = account_manager
194
+ self.managed_auth = account_manager is not None
185
195
  self.mock_dir = mock_dir
186
196
  self.log_file = log_file
187
197
  self.enable_desensitize = enable_desensitize
@@ -191,13 +201,47 @@ class ProxyState:
191
201
  self.json_logger = json_logger
192
202
  self.runtime_info = get_runtime_info()
193
203
  self.started_at = time.time()
204
+ checkins = getattr(account_manager, "checkins", None)
205
+ if checkins is not None:
206
+ checkins.configure_logging(self.log_checkin)
207
+
208
+ def log_checkin(self, event: str, **fields) -> None:
209
+ """Send safe check-in events to existing files and the process console."""
210
+ self.write_log(event, **fields)
211
+ summary = json.dumps(fields, ensure_ascii=False)
212
+ if self.logger is not None:
213
+ self.logger.info("%s: %s", event, summary)
214
+ try:
215
+ print(f"[Checkin] {event} {summary}", flush=True)
216
+ except (OSError, UnicodeError):
217
+ pass
218
+
219
+ @property
220
+ def client(self):
221
+ if self.account_manager is not None:
222
+ return self.account_manager.client or self._client
223
+ return self._client
224
+
225
+ @client.setter
226
+ def client(self, value):
227
+ self._client = value
228
+
229
+ def for_request(self):
230
+ """Pin the account before any await, including refresh and billing retries."""
231
+ snapshot = copy.copy(self)
232
+ snapshot._client = self.client
233
+ snapshot.account_manager = None
234
+ return snapshot
194
235
 
195
236
  def ensure_auth(self) -> None:
196
237
  """确保已认证;认证失败(token 过期/网络错误/登录未完成)返回结构化 401 而非 500。"""
197
238
  if self.mock_dir is not None:
198
239
  return
199
240
  try:
200
- self.client.ensure_authenticated()
241
+ if self.managed_auth:
242
+ self.client.ensure_authenticated(open_browser=False, allow_login=False)
243
+ else:
244
+ self.client.ensure_authenticated()
201
245
  except HTTPException:
202
246
  raise # 已是结构化异常,原样透传(如 503 proxy not initialized)
203
247
  except Exception as exc:
@@ -205,9 +249,9 @@ class ProxyState:
205
249
  status_code=401,
206
250
  detail={
207
251
  "error": {
208
- "message": "认证失败:token 无效或已过期,请重新登录(--login)",
252
+ "message": "认证失败:请在 /admin 关联或切换账号,或重新登录(--login)",
209
253
  "type": "authentication_error",
210
- "details": str(exc)[:200],
254
+ "details": type(exc).__name__ if self.managed_auth else str(exc)[:200],
211
255
  }
212
256
  },
213
257
  )
@@ -252,11 +296,26 @@ class ProxyState:
252
296
  # FastAPI 应用
253
297
  # ============================================================================
254
298
 
255
- app = FastAPI(title="CodeBuddy Proxy (FastAPI)", version="2.0.7")
299
+ app = FastAPI(title="CodeBuddy Proxy (FastAPI)", version="2.0.8.dev1")
256
300
 
257
301
  # 全局状态(在 main() 中初始化)
258
302
  proxy_state: ProxyState | None = None
259
303
  process_diagnostics: ProcessDiagnostics | None = None
304
+ _request_state: ContextVar[Any] = ContextVar("account_request_state", default=None)
305
+
306
+
307
+ @app.middleware("http")
308
+ async def pin_account_at_request_entry(request: Request, call_next):
309
+ # Capture before body parsing or other awaits. Each downstream task also
310
+ # inherits this context, including streaming responses.
311
+ if proxy_state is None or not request.url.path.startswith("/v1/"):
312
+ return await call_next(request)
313
+ state = proxy_state.for_request() if isinstance(proxy_state, ProxyState) else proxy_state
314
+ token = _request_state.set(state)
315
+ try:
316
+ return await call_next(request)
317
+ finally:
318
+ _request_state.reset(token)
260
319
 
261
320
 
262
321
  async def install_process_asyncio_diagnostics() -> None:
@@ -269,12 +328,82 @@ async def install_process_asyncio_diagnostics() -> None:
269
328
  app.router.add_event_handler("startup", install_process_asyncio_diagnostics)
270
329
 
271
330
 
331
+ async def start_account_checkin() -> None:
332
+ if isinstance(proxy_state, ProxyState) and proxy_state.account_manager is not None:
333
+ await proxy_state.account_manager.checkins.start()
334
+
335
+
336
+ app.router.add_event_handler("startup", start_account_checkin)
337
+
338
+ # Trae automation is opt-in because its local login is independent of WorkBuddy.
339
+ _trae_checkin_service = None
340
+
341
+
342
+ async def start_trae_checkin() -> None:
343
+ global _trae_checkin_service
344
+ native = os.environ.get("DAILYCHECKIN_TRAE_NATIVE") == "1"
345
+ creds = os.environ.get("DAILYCHECKIN_TRAE_CREDS") or None
346
+ if not native and not creds:
347
+ return
348
+ try:
349
+ from daily_checkin.trae_scheduler import create_service
350
+ service = await asyncio.to_thread(
351
+ create_service, native=native, creds=creds,
352
+ device_id_source=os.environ.get("DAILYCHECKIN_TRAE_DEVICE_ID_SOURCE", "get-device-id"))
353
+ if isinstance(proxy_state, ProxyState):
354
+ service.configure_logging(proxy_state.log_checkin)
355
+ await service.start()
356
+ _trae_checkin_service = service
357
+ except Exception:
358
+ logging.getLogger(__name__).warning(
359
+ "Trae automatic check-in could not start; check the configured account and device source")
360
+
361
+
362
+ async def close_trae_checkin() -> None:
363
+ global _trae_checkin_service
364
+ service, _trae_checkin_service = _trae_checkin_service, None
365
+ if service is not None:
366
+ await service.close()
367
+
368
+
369
+ app.router.add_event_handler("startup", start_trae_checkin)
370
+ app.router.add_event_handler("shutdown", close_trae_checkin)
371
+
372
+
373
+
374
+ async def close_account_manager() -> None:
375
+ if isinstance(proxy_state, ProxyState) and proxy_state.account_manager is not None:
376
+ await proxy_state.account_manager.checkins.close()
377
+ proxy_state.account_manager.close()
378
+
379
+
380
+ app.router.add_event_handler("shutdown", close_account_manager)
381
+
382
+
272
383
  def get_state() -> ProxyState:
273
384
  if proxy_state is None:
274
385
  raise HTTPException(status_code=503, detail={"error": {"message": "proxy not initialized", "type": "internal_error"}})
275
386
  return proxy_state
276
387
 
277
388
 
389
+ def get_request_state():
390
+ pinned = _request_state.get()
391
+ if pinned is not None:
392
+ return pinned
393
+ state = get_state()
394
+ return state.for_request() if isinstance(state, ProxyState) else state
395
+
396
+
397
+ def get_account_manager():
398
+ manager = getattr(get_state(), "account_manager", None)
399
+ if manager is None:
400
+ raise HTTPException(status_code=503, detail="Account management is unavailable in this mode")
401
+ return manager
402
+
403
+
404
+ app.include_router(create_admin_router(get_account_manager))
405
+
406
+
278
407
  # ============================================================================
279
408
  # 辅助函数
280
409
  # ============================================================================
@@ -849,15 +978,17 @@ async def health():
849
978
  }
850
979
 
851
980
 
852
- # ============================================================================
853
- # 端点:/v1/checkin-status 与 /v1/checkin(每日签到透传)
981
+ # Compatibility routes are implemented and maintained by DailyCheckin.
982
+ app.include_router(create_legacy_router(get_request_state, diagnostic))
983
+
984
+
854
985
  # ============================================================================
855
986
 
856
987
  @app.api_route("/v1/checkin-status", methods=["GET", "POST"])
857
988
  async def checkin_status():
858
989
  """Accept GET/POST locally; the real upstream billing status endpoint requires POST."""
859
990
  return await forward_billing(
860
- get_state(), "POST", "/v2/billing/meter/checkin-status", diagnostic
991
+ get_request_state(), "POST", "/v2/billing/meter/checkin-activity-status", diagnostic
861
992
  )
862
993
 
863
994
 
@@ -865,7 +996,7 @@ async def checkin_status():
865
996
  async def checkin():
866
997
  """POST daily check-in: preserve the upstream HTTP status and raw body."""
867
998
  return await forward_billing(
868
- get_state(), "POST", "/v2/billing/meter/daily-checkin", diagnostic
999
+ get_request_state(), "POST", "/v2/billing/meter/daily-checkin", diagnostic
869
1000
  )
870
1001
 
871
1002
 
@@ -935,7 +1066,7 @@ async def parse_request_body(request: Request) -> Any:
935
1066
 
936
1067
  @app.post("/v1/chat/completions")
937
1068
  async def chat_completions(request: Request):
938
- state = get_state()
1069
+ state = get_request_state()
939
1070
  body = await parse_request_body(request)
940
1071
 
941
1072
  log_client_request("POST", "/v1/chat/completions", body)
@@ -950,7 +1081,7 @@ async def chat_completions(request: Request):
950
1081
 
951
1082
  @app.post("/v1/responses")
952
1083
  async def create_response(request: Request):
953
- state = get_state()
1084
+ state = get_request_state()
954
1085
  body = await parse_request_body(request)
955
1086
 
956
1087
  log_client_request("POST", "/v1/responses", body)
@@ -1013,7 +1144,7 @@ async def create_response(request: Request):
1013
1144
 
1014
1145
  @app.post("/v1/messages")
1015
1146
  async def create_message(request: Request):
1016
- state = get_state()
1147
+ state = get_request_state()
1017
1148
  body = await parse_request_body(request)
1018
1149
 
1019
1150
  log_client_request("POST", "/v1/messages", body)
@@ -1052,14 +1183,71 @@ def _normalize_tool_choice(tool_choice: Any) -> Any:
1052
1183
  return tool_choice
1053
1184
 
1054
1185
 
1186
+ def _retry_after_header(response) -> dict[str, str]:
1187
+ retry_after = getattr(response, "headers", {}).get("Retry-After")
1188
+ return {"Retry-After": retry_after} if retry_after is not None else {}
1189
+
1190
+
1055
1191
  async def forward_chat(
1056
1192
  body: dict[str, Any],
1057
1193
  protocol: str,
1058
1194
  original: dict[str, Any] | None = None
1059
1195
  ) -> StreamingResponse | JSONResponse:
1060
- """转发 chat 请求到 CodeBuddy 上游,支持流式和非流式。"""
1061
- state = get_state()
1062
- state.ensure_auth()
1196
+ """Forward with bounded account failover before sending a client response."""
1197
+ state = get_request_state()
1198
+ manager = getattr(state, "account_runtime", None)
1199
+ attempted: set[str] = set()
1200
+ max_attempts = 1
1201
+ if manager is not None:
1202
+ max_attempts = max(1, len(manager.snapshot()["accounts"]))
1203
+ for attempt in range(max_attempts):
1204
+ response = await _forward_chat_once(body, protocol, original, state)
1205
+ if response.status_code != 429:
1206
+ return response
1207
+ retry_state = await rate_limited_account(
1208
+ state, response.headers.get("Retry-After"), attempted, model=body.get("model"),
1209
+ )
1210
+ if retry_state is None or attempt + 1 == max_attempts:
1211
+ return response
1212
+ state = retry_state
1213
+ return response
1214
+
1215
+
1216
+ async def rate_limited_account(state, retry_after, attempted, *, model):
1217
+ """Record the original identity; late failures cannot override manual switches."""
1218
+ manager = getattr(state, "account_runtime", None)
1219
+ if manager is None:
1220
+ return None
1221
+ try:
1222
+ account_id = manager.account_id_for_client(state.client)
1223
+ if account_id is not None:
1224
+ attempted.add(account_id)
1225
+ candidate = await asyncio.to_thread(
1226
+ manager.handle_rate_limit, state.client, retry_after,
1227
+ model=model, excluded_account_ids=set(attempted),
1228
+ )
1229
+ next_id = manager.account_id_for_client(candidate) if candidate is not None else None
1230
+ state.write_log(
1231
+ "account_rate_limited", account_id=account_id, model=model, switched_to=next_id,
1232
+ )
1233
+ if candidate is None or next_id is None or next_id in attempted:
1234
+ return None
1235
+ retry_state = copy.copy(state)
1236
+ retry_state._client = candidate
1237
+ retry_state.account_manager = None
1238
+ return retry_state
1239
+ except Exception as exc:
1240
+ # Persistence or selection failures must not hide the provider's 429.
1241
+ state.write_log("account_rate_limit_record_failed", error_type=type(exc).__name__)
1242
+ return None
1243
+
1244
+
1245
+ async def _forward_chat_once(body, protocol, original, state):
1246
+ """One account attempt; any returned stream has already passed HTTP preflight."""
1247
+ if isinstance(state, ProxyState) and state.managed_auth:
1248
+ await asyncio.to_thread(state.ensure_auth)
1249
+ else:
1250
+ state.ensure_auth()
1063
1251
 
1064
1252
  diagnostic("upstream_request", protocol=protocol, **body_summary(body))
1065
1253
 
@@ -1138,7 +1326,8 @@ async def forward_chat(
1138
1326
  if protocol == "anthropic" else {"error": error_info}
1139
1327
  )
1140
1328
  return JSONResponse(
1141
- status_code=upstream_response.status_code, content=error_payload
1329
+ status_code=upstream_response.status_code, content=error_payload,
1330
+ headers=_retry_after_header(upstream_response),
1142
1331
  )
1143
1332
  finally:
1144
1333
  await upstream_response.aclose()
@@ -1155,7 +1344,14 @@ async def forward_chat(
1155
1344
  )
1156
1345
 
1157
1346
  # 非流式:聚合后返回
1158
- collected = await collect_upstream(url, headers, upstream_body, protocol)
1347
+ try:
1348
+ collected = await collect_upstream(url, headers, upstream_body, protocol)
1349
+ except HTTPException as exc:
1350
+ if exc.status_code != 429:
1351
+ raise
1352
+ return JSONResponse(
1353
+ status_code=429, content={"detail": exc.detail}, headers=exc.headers,
1354
+ )
1159
1355
  return JSONResponse(content=convert_nonstream(collected, protocol, original))
1160
1356
 
1161
1357
 
@@ -1812,7 +2008,8 @@ async def collect_upstream(
1812
2008
  error_body = await resp.aread()
1813
2009
  raise HTTPException(
1814
2010
  status_code=resp.status_code,
1815
- detail={"error": {"message": error_body.decode("utf-8", "replace")[:500], "type": "upstream_error"}}
2011
+ detail={"error": {"message": error_body.decode("utf-8", "replace")[:500], "type": "upstream_error"}},
2012
+ headers=_retry_after_header(resp),
1816
2013
  )
1817
2014
 
1818
2015
  async for line in resp.aiter_lines():
@@ -1973,6 +2170,11 @@ def build_parser() -> argparse.ArgumentParser:
1973
2170
  )
1974
2171
  parser.add_argument("--session-file", type=pathlib.Path,
1975
2172
  help="会话文件路径(默认按 backend profile 隔离)")
2173
+ parser.add_argument(
2174
+ "--accounts-dir", type=pathlib.Path,
2175
+ default=pathlib.Path.home() / ".workbuddy2api" / "accounts",
2176
+ help="独立账号库目录;管理页位于 /admin",
2177
+ )
1976
2178
  parser.add_argument("--mock-dir", type=pathlib.Path,
1977
2179
  help="只使用指定目录中的真实响应 fixture,不访问 CodeBuddy 后端")
1978
2180
  default_log_file = pathlib.Path(
@@ -2017,11 +2219,92 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
2017
2219
  return args
2018
2220
 
2019
2221
 
2222
+ def initialize_account_manager(args, resolved_backend):
2223
+ """Import legacy identities once and restore a persisted active account.
2224
+
2225
+ Reading legacy files never refreshes or rewrites them. A forced login
2226
+ always uses a temporary session, so --login cannot overwrite an old user.
2227
+ """
2228
+ from codebuddy_proxy.account_store import AccountStore
2229
+ from codebuddy_proxy.account_manager import AccountManager
2230
+
2231
+ store = AccountStore(args.accounts_dir)
2232
+ initial_import = not store.index_file.exists()
2233
+ explicit = bool(args.global_mode or args.endpoint is not None
2234
+ or args.session_file is not None
2235
+ or os.getenv("CODEBUDDY_ENDPOINT"))
2236
+ candidates = [resolved_backend]
2237
+ for profile in (DOMESTIC_PROFILE, GLOBAL_PROFILE):
2238
+ candidate = resolve_backend(profile=profile, environment={})
2239
+ if candidate not in candidates:
2240
+ candidates.append(candidate)
2241
+ selected_uid = None
2242
+ for candidate in candidates:
2243
+ # Migration is one-time. Re-reading a legacy file after its account
2244
+ # was deleted must not silently associate that identity again.
2245
+ if not initial_import and not (args.session_file is not None
2246
+ and candidate is resolved_backend):
2247
+ continue
2248
+ try:
2249
+ old = CodeBuddyClient(backend=candidate)
2250
+ except CodeBuddyError:
2251
+ if args.session_file is not None and candidate is resolved_backend:
2252
+ raise
2253
+ print(f"Skipped incompatible legacy session for {candidate.profile.key}", file=sys.stderr)
2254
+ continue
2255
+ account = old.session.get("account") or {}
2256
+ auth = old.session.get("auth") or {}
2257
+ if not isinstance(account, dict) or not isinstance(auth, dict):
2258
+ continue
2259
+ uid = account.get("uid")
2260
+ if not uid or not (auth.get("accessToken") or auth.get("refreshToken")):
2261
+ continue
2262
+ if candidate is resolved_backend:
2263
+ selected_uid = str(uid).strip()
2264
+ known = any(
2265
+ row["backend"] == old.profile.key and row["endpoint"] == old.endpoint
2266
+ and str(row["uid"]) == str(uid) for row in store.list_accounts()
2267
+ )
2268
+ if not known:
2269
+ store.import_client(old)
2270
+ if args.login:
2271
+ with tempfile.TemporaryDirectory(prefix="login-", dir=store.root) as temporary:
2272
+ login_backend = resolve_backend(
2273
+ profile=resolved_backend.profile, endpoint=resolved_backend.endpoint,
2274
+ session_file=pathlib.Path(temporary) / "session.json", environment={},
2275
+ )
2276
+ login_client = CodeBuddyClient(backend=login_backend)
2277
+ login_client.login(open_browser=not args.no_browser)
2278
+ store.import_client(login_client, activate=True)
2279
+ elif explicit:
2280
+ matching = [row for row in store.list_accounts()
2281
+ if row["backend"] == resolved_backend.profile.key
2282
+ and row["endpoint"] == resolved_backend.endpoint
2283
+ and (args.session_file is None or str(row["uid"]) == selected_uid)]
2284
+ if matching:
2285
+ chosen = next((row for row in matching if row["active"]), matching[0])
2286
+ store.set_active(chosen["id"])
2287
+ else:
2288
+ store.clear_active()
2289
+ manager = AccountManager(store)
2290
+ # The empty fallback preserves the requested profile for health/models.
2291
+ # Managed requests cannot start browser login or write to a legacy file.
2292
+ fallback = CodeBuddyClient(backend=resolve_backend(
2293
+ profile=resolved_backend.profile, endpoint=resolved_backend.endpoint,
2294
+ session_file=store.root / ".unlinked-session.json", environment={},
2295
+ ))
2296
+ return manager, manager.client or fallback
2297
+
2298
+
2020
2299
  def _run_proxy(args: argparse.Namespace) -> int:
2021
2300
  global proxy_state
2022
2301
  try:
2023
2302
  resolved_backend = resolve_backend_from_args(args)
2024
- client = CodeBuddyClient(backend=resolved_backend)
2303
+ manager = None
2304
+ if args.mock_dir is not None:
2305
+ client = CodeBuddyClient(backend=resolved_backend)
2306
+ else:
2307
+ manager, client = initialize_account_manager(args, resolved_backend)
2025
2308
  except (CodeBuddyError, ValueError) as exc:
2026
2309
  print(f"错误: {exc}", file=sys.stderr)
2027
2310
  return 1
@@ -2031,10 +2314,6 @@ def _run_proxy(args: argparse.Namespace) -> int:
2031
2314
  logger = setup_logging(log_dir)
2032
2315
  json_logger = setup_json_logging(args.log_file)
2033
2316
 
2034
- # 处理登录
2035
- if args.login:
2036
- client.login(open_browser=not args.no_browser)
2037
-
2038
2317
  # 创建全局状态
2039
2318
  proxy_state = ProxyState(
2040
2319
  client=client,
@@ -2045,6 +2324,7 @@ def _run_proxy(args: argparse.Namespace) -> int:
2045
2324
  verbose_llm=args.verbose_llm,
2046
2325
  logger=logger,
2047
2326
  json_logger=json_logger,
2327
+ account_manager=manager,
2048
2328
  )
2049
2329
  proxy_state.write_log(
2050
2330
  "startup",
@@ -2086,13 +2366,19 @@ def _run_proxy(args: argparse.Namespace) -> int:
2086
2366
  # 启动信息输出到 stdout
2087
2367
  print(f"CodeBuddy proxy listening on http://{args.host}:{args.port}")
2088
2368
  print("Endpoints: /v1/models /v1/chat/completions /v1/responses /v1/messages /health")
2369
+ if manager is not None:
2370
+ print(f"Account manager: http://127.0.0.1:{args.port}/admin (local access only)")
2089
2371
 
2090
2372
  # 同时记录到日志
2091
2373
  logger.info(f"CodeBuddy proxy listening on http://{args.host}:{args.port}")
2092
2374
  logger.info("Endpoints: /v1/models /v1/chat/completions /v1/responses /v1/messages /health")
2093
2375
 
2094
2376
  # 启动 uvicorn
2095
- run_http_server(host=args.host, port=args.port, windows_loop=args.windows_loop)
2377
+ try:
2378
+ run_http_server(host=args.host, port=args.port, windows_loop=args.windows_loop)
2379
+ finally:
2380
+ if manager is not None:
2381
+ manager.close()
2096
2382
  return 0
2097
2383
 
2098
2384
 
@@ -0,0 +1,4 @@
1
+ """Compatibility alias for DailyCheckin's WorkBuddy activity service."""
2
+ import sys
3
+ from daily_checkin import workbuddy as _module
4
+ sys.modules[__name__] = _module