buddy-agent-auth 0.1.0.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.
Files changed (34) hide show
  1. buddy_agent_auth/__init__.py +5 -0
  2. buddy_agent_auth/account_store.py +4 -0
  3. buddy_agent_auth/backend_profile.py +4 -0
  4. buddy_agent_auth/client.py +4 -0
  5. buddy_agent_auth/locking.py +81 -0
  6. buddy_agent_auth/providers/__init__.py +4 -0
  7. buddy_agent_auth/providers/base.py +9 -0
  8. buddy_agent_auth/providers/codebuddy/__init__.py +17 -0
  9. buddy_agent_auth/providers/codebuddy/account_store.py +506 -0
  10. buddy_agent_auth/providers/codebuddy/backend_profile.py +198 -0
  11. buddy_agent_auth/providers/codebuddy/client.py +666 -0
  12. buddy_agent_auth/providers/trae/__init__.py +27 -0
  13. buddy_agent_auth/providers/trae/aha_cache_codec.py +84 -0
  14. buddy_agent_auth/providers/trae/aha_device_cache.py +45 -0
  15. buddy_agent_auth/providers/trae/aha_device_service.py +325 -0
  16. buddy_agent_auth/providers/trae/aha_native_backend.py +61 -0
  17. buddy_agent_auth/providers/trae/aha_native_lifecycle.py +226 -0
  18. buddy_agent_auth/providers/trae/aha_native_semantics.py +67 -0
  19. buddy_agent_auth/providers/trae/aha_registration.py +157 -0
  20. buddy_agent_auth/providers/trae/aha_tiny_storage.py +135 -0
  21. buddy_agent_auth/providers/trae/app_storage.py +195 -0
  22. buddy_agent_auth/providers/trae/auth.py +362 -0
  23. buddy_agent_auth/providers/trae/client_metadata.py +102 -0
  24. buddy_agent_auth/providers/trae/credential_decrypt.py +111 -0
  25. buddy_agent_auth/providers/trae/credentials.py +39 -0
  26. buddy_agent_auth/providers/trae/device_hardware.py +377 -0
  27. buddy_agent_auth/providers/trae/diagnostics.py +38 -0
  28. buddy_agent_auth/providers/trae/login.py +415 -0
  29. buddy_agent_auth/providers/trae/login_identity.py +134 -0
  30. buddy_agent_auth/providers/trae/native_identity.py +111 -0
  31. buddy_agent_auth-0.1.0.dev1.dist-info/METADATA +40 -0
  32. buddy_agent_auth-0.1.0.dev1.dist-info/RECORD +34 -0
  33. buddy_agent_auth-0.1.0.dev1.dist-info/WHEEL +5 -0
  34. buddy_agent_auth-0.1.0.dev1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,5 @@
1
+ """WorkBuddy / CodeBuddy authentication and account storage."""
2
+ from .client import CodeBuddyClient, CodeBuddyError
3
+ from .account_store import AccountStore
4
+
5
+ __all__ = ["AccountStore", "CodeBuddyClient", "CodeBuddyError"]
@@ -0,0 +1,4 @@
1
+ """Compatibility alias for the CodeBuddy provider."""
2
+ import sys
3
+ from .providers.codebuddy import account_store as _module
4
+ sys.modules[__name__] = _module
@@ -0,0 +1,4 @@
1
+ """Compatibility alias for the CodeBuddy provider."""
2
+ import sys
3
+ from .providers.codebuddy import backend_profile as _module
4
+ sys.modules[__name__] = _module
@@ -0,0 +1,4 @@
1
+ """Compatibility alias for the CodeBuddy provider."""
2
+ import sys
3
+ from .providers.codebuddy import client as _module
4
+ sys.modules[__name__] = _module
@@ -0,0 +1,81 @@
1
+ """Process-wide and cross-process locks for the account storage directory."""
2
+ import os
3
+ from pathlib import Path
4
+ import threading
5
+ import time
6
+
7
+ _guard = threading.Lock()
8
+ _locks = {}
9
+
10
+
11
+ class SharedDirectoryLock:
12
+ def __init__(self, directory: Path):
13
+ # Keep the legacy lock name so old and renamed clients still coordinate.
14
+ self.path = directory / '.workbuddy-auth.lock'
15
+ self._thread_lock = threading.RLock()
16
+ self._local = threading.local()
17
+
18
+ def __enter__(self):
19
+ self._thread_lock.acquire()
20
+ try:
21
+ depth = getattr(self._local, 'depth', 0)
22
+ if not depth:
23
+ self.path.parent.mkdir(parents=True, exist_ok=True)
24
+ f = self.path.open('a+b')
25
+ try:
26
+ if os.name == 'nt':
27
+ import msvcrt
28
+ # LockFile can lock a byte beyond EOF. Do not read or
29
+ # write byte zero before acquiring it: Windows rejects
30
+ # those operations while another process owns the lock.
31
+ deadline = time.monotonic() + 30
32
+ while True:
33
+ try:
34
+ f.seek(0)
35
+ msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK, 1)
36
+ break
37
+ except OSError:
38
+ if time.monotonic() >= deadline:
39
+ raise TimeoutError("timed out waiting for account storage lock") from None
40
+ time.sleep(0.05)
41
+ else:
42
+ import fcntl
43
+ fcntl.flock(f, fcntl.LOCK_EX)
44
+ except BaseException:
45
+ f.close()
46
+ raise
47
+ self._local.file = f
48
+ self._local.depth = depth + 1
49
+ return self
50
+ except BaseException:
51
+ self._thread_lock.release()
52
+ raise
53
+
54
+ def __exit__(self, *args):
55
+ try:
56
+ depth = self._local.depth - 1
57
+ self._local.depth = depth
58
+ if depth == 0:
59
+ f = self._local.file
60
+ try:
61
+ if os.name == 'nt':
62
+ import msvcrt
63
+ f.seek(0)
64
+ msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1)
65
+ else:
66
+ import fcntl
67
+ fcntl.flock(f, fcntl.LOCK_UN)
68
+ finally:
69
+ f.close()
70
+ del self._local.file
71
+ finally:
72
+ self._thread_lock.release()
73
+
74
+
75
+ def directory_lock(directory: Path) -> SharedDirectoryLock:
76
+ directory = Path(directory).expanduser().resolve()
77
+ key = os.path.normcase(os.fspath(directory))
78
+ with _guard:
79
+ if key not in _locks:
80
+ _locks[key] = SharedDirectoryLock(directory)
81
+ return _locks[key]
@@ -0,0 +1,4 @@
1
+ """Brand-specific authentication providers and their shared contract."""
2
+ from .base import SessionProvider
3
+
4
+ __all__ = ["SessionProvider"]
@@ -0,0 +1,9 @@
1
+ """Small contract for brand-specific login-state providers."""
2
+ from typing import Protocol, TypeVar
3
+
4
+ SessionT = TypeVar('SessionT', covariant=True)
5
+
6
+
7
+ class SessionProvider(Protocol[SessionT]):
8
+ """Load a brand-specific session without imposing a shared token format."""
9
+ def load(self) -> SessionT: ...
@@ -0,0 +1,17 @@
1
+ """CodeBuddy and WorkBuddy account session source."""
2
+ from .account_store import AccountStore
3
+ from .client import CodeBuddyClient, CodeBuddyError
4
+
5
+
6
+ class CodeBuddyProvider:
7
+ def __init__(self, store: AccountStore, account_id: str):
8
+ self.store = store
9
+ self.account_id = account_id
10
+
11
+ def load(self) -> CodeBuddyClient:
12
+ client = self.store.get_client(self.account_id)
13
+ client.ensure_authenticated(open_browser=False, allow_login=False)
14
+ return client
15
+
16
+
17
+ __all__ = ['AccountStore', 'CodeBuddyClient', 'CodeBuddyError', 'CodeBuddyProvider']
@@ -0,0 +1,506 @@
1
+ """Persistent, credential-isolated storage for CodeBuddy accounts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import pathlib
9
+ import re
10
+ import tempfile
11
+ import threading
12
+ from contextlib import nullcontext
13
+ from typing import Any
14
+ from urllib.parse import urlsplit
15
+
16
+ from .backend_profile import (
17
+ normalize_endpoint,
18
+ profile_for_key,
19
+ resolve_backend,
20
+ )
21
+ from .client import CodeBuddyClient, CodeBuddyError
22
+
23
+
24
+ _INDEX_VERSION = 1
25
+ _ACCOUNT_ID_RE = re.compile(r"^acct_[0-9a-f]{64}$")
26
+ _INDEX_FIELDS = {"id", "backend", "endpoint", "uid", "nickname"}
27
+ from buddy_agent_auth.locking import directory_lock
28
+
29
+
30
+ def _root_lock(root: pathlib.Path):
31
+ return directory_lock(root)
32
+
33
+
34
+ def _safe_endpoint(value: str) -> str:
35
+ try:
36
+ endpoint = normalize_endpoint(value)
37
+ parsed = urlsplit(endpoint)
38
+ except (TypeError, ValueError) as exc:
39
+ raise CodeBuddyError("账号 endpoint 无效") from exc
40
+ if parsed.username or parsed.password or parsed.query or parsed.fragment:
41
+ raise CodeBuddyError("账号 endpoint 不得在地址中包含凭据或查询参数")
42
+ return endpoint
43
+
44
+
45
+ def _account_id(backend: str, endpoint: str, uid: str) -> str:
46
+ identity = json.dumps(
47
+ [backend, endpoint, uid], ensure_ascii=False, separators=(",", ":")
48
+ ).encode("utf-8")
49
+ return f"acct_{hashlib.sha256(identity).hexdigest()}"
50
+
51
+
52
+ def _has_auth_token(auth: Any) -> bool:
53
+ return isinstance(auth, dict) and any(
54
+ isinstance(auth.get(name), str) and bool(auth[name].strip())
55
+ for name in ("accessToken", "refreshToken")
56
+ )
57
+
58
+
59
+ def _atomic_json(path: pathlib.Path, payload: dict[str, Any]) -> None:
60
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
61
+ try:
62
+ os.chmod(path.parent, 0o700)
63
+ except OSError:
64
+ pass
65
+ temp_name: str | None = None
66
+ try:
67
+ fd, temp_name = tempfile.mkstemp(
68
+ prefix=f".{path.name}.", suffix=".tmp", dir=path.parent
69
+ )
70
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
71
+ json.dump(payload, stream, ensure_ascii=False, indent=2)
72
+ stream.write("\n")
73
+ stream.flush()
74
+ os.fsync(stream.fileno())
75
+ os.replace(temp_name, path)
76
+ temp_name = None
77
+ try:
78
+ os.chmod(path, 0o600)
79
+ except OSError:
80
+ pass
81
+ except OSError as exc:
82
+ raise CodeBuddyError(f"无法原子写入账号文件: {path.name}") from exc
83
+ finally:
84
+ if temp_name is not None:
85
+ try:
86
+ os.unlink(temp_name)
87
+ except OSError:
88
+ pass
89
+
90
+
91
+ def _capture_file(path: pathlib.Path) -> bytes | None:
92
+ if path.is_symlink():
93
+ raise CodeBuddyError("账号文件路径无效")
94
+ try:
95
+ return path.read_bytes()
96
+ except FileNotFoundError:
97
+ return None
98
+ except OSError as exc:
99
+ raise CodeBuddyError("无法读取账号文件进行安全更新") from exc
100
+
101
+
102
+ def _restore_file(path: pathlib.Path, contents: bytes | None) -> None:
103
+ if path.is_symlink():
104
+ raise CodeBuddyError("账号文件路径无效")
105
+ if contents is None:
106
+ try:
107
+ path.unlink()
108
+ except FileNotFoundError:
109
+ pass
110
+ except OSError as exc:
111
+ raise CodeBuddyError("无法清理账号事务文件") from exc
112
+ return
113
+ temp_name: str | None = None
114
+ try:
115
+ fd, temp_name = tempfile.mkstemp(
116
+ prefix=f".{path.name}.", suffix=".rollback.tmp", dir=path.parent
117
+ )
118
+ with os.fdopen(fd, "wb") as stream:
119
+ stream.write(contents)
120
+ stream.flush()
121
+ os.fsync(stream.fileno())
122
+ os.replace(temp_name, path)
123
+ temp_name = None
124
+ try:
125
+ os.chmod(path, 0o600)
126
+ except OSError:
127
+ pass
128
+ except OSError as exc:
129
+ raise CodeBuddyError("无法恢复账号文件") from exc
130
+ finally:
131
+ if temp_name is not None:
132
+ try:
133
+ os.unlink(temp_name)
134
+ except OSError:
135
+ pass
136
+
137
+
138
+ class AccountStore:
139
+ """Store account metadata separately from each credential-bearing session."""
140
+
141
+ def __init__(self, root: pathlib.Path | str | None = None) -> None:
142
+ self.root = pathlib.Path(root or (pathlib.Path.home() / ".workbuddy2api" / "accounts"))
143
+ self.root = self.root.expanduser().resolve()
144
+ self.index_file = self.root / "index.json"
145
+ self._lock = _root_lock(self.root)
146
+ self._clients: dict[str, CodeBuddyClient] = {}
147
+ with self._lock:
148
+ try:
149
+ self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
150
+ os.chmod(self.root, 0o700)
151
+ except OSError as exc:
152
+ raise CodeBuddyError("无法创建私有账号目录") from exc
153
+ if self.index_file.is_symlink():
154
+ raise CodeBuddyError("账号索引文件路径无效")
155
+ self._read_index_locked()
156
+
157
+ def _session_file(self, account_id: str) -> pathlib.Path:
158
+ if not _ACCOUNT_ID_RE.fullmatch(account_id):
159
+ raise CodeBuddyError("账号 id 无效")
160
+ return self.root / f"account-{account_id}.json"
161
+
162
+ def _read_index_locked(self) -> dict[str, Any]:
163
+ try:
164
+ raw = self.index_file.read_text(encoding="utf-8")
165
+ except FileNotFoundError:
166
+ return {"version": _INDEX_VERSION, "active_account_id": None, "accounts": []}
167
+ except OSError as exc:
168
+ raise CodeBuddyError("无法读取账号索引文件") from exc
169
+ try:
170
+ value = json.loads(raw)
171
+ except json.JSONDecodeError as exc:
172
+ raise CodeBuddyError("账号索引文件损坏,未修改任何账号数据") from exc
173
+ if (
174
+ not isinstance(value, dict)
175
+ or set(value) != {"version", "active_account_id", "accounts"}
176
+ or value.get("version") != _INDEX_VERSION
177
+ ):
178
+ raise CodeBuddyError("账号索引文件格式或版本无效,未修改任何账号数据")
179
+ accounts = value.get("accounts")
180
+ if not isinstance(accounts, list):
181
+ raise CodeBuddyError("账号索引中的 accounts 字段无效")
182
+ normalized_accounts: list[dict[str, Any]] = []
183
+ seen: set[str] = set()
184
+ for record in accounts:
185
+ if not isinstance(record, dict) or set(record) != _INDEX_FIELDS:
186
+ raise CodeBuddyError("账号索引包含无效字段,未修改任何账号数据")
187
+ backend = record.get("backend")
188
+ endpoint = record.get("endpoint")
189
+ uid = record.get("uid")
190
+ account_id = record.get("id")
191
+ nickname = record.get("nickname")
192
+ if not all(isinstance(item, str) and item for item in (backend, endpoint, uid)):
193
+ raise CodeBuddyError("账号索引包含不完整的身份信息")
194
+ try:
195
+ profile_for_key(backend)
196
+ canonical_endpoint = _safe_endpoint(endpoint)
197
+ except (ValueError, CodeBuddyError) as exc:
198
+ raise CodeBuddyError("账号索引包含无效的 backend 或 endpoint") from exc
199
+ if canonical_endpoint != endpoint or _account_id(backend, endpoint, uid) != account_id:
200
+ raise CodeBuddyError("账号索引身份校验失败,未修改任何账号数据")
201
+ if nickname is not None and not isinstance(nickname, str):
202
+ raise CodeBuddyError("账号索引包含无效的 nickname")
203
+ if account_id in seen:
204
+ raise CodeBuddyError("账号索引包含重复账号 id")
205
+ seen.add(account_id)
206
+ normalized_accounts.append(
207
+ {
208
+ "id": account_id,
209
+ "backend": backend,
210
+ "endpoint": endpoint,
211
+ "uid": uid,
212
+ "nickname": nickname,
213
+ }
214
+ )
215
+ active_id = value.get("active_account_id")
216
+ if active_id is not None and active_id not in seen:
217
+ raise CodeBuddyError("账号索引的 active_account_id 不存在")
218
+ return {
219
+ "version": _INDEX_VERSION,
220
+ "active_account_id": active_id,
221
+ "accounts": normalized_accounts,
222
+ }
223
+
224
+ def _write_index_locked(self, index: dict[str, Any]) -> None:
225
+ metadata = [
226
+ {key: record[key] for key in ("id", "backend", "endpoint", "uid", "nickname")}
227
+ for record in index["accounts"]
228
+ ]
229
+ _atomic_json(
230
+ self.index_file,
231
+ {
232
+ "version": _INDEX_VERSION,
233
+ "active_account_id": index["active_account_id"],
234
+ "accounts": metadata,
235
+ },
236
+ )
237
+
238
+ @staticmethod
239
+ def _find_account(index: dict[str, Any], account_id: str) -> dict[str, Any]:
240
+ if not isinstance(account_id, str) or not _ACCOUNT_ID_RE.fullmatch(account_id):
241
+ raise CodeBuddyError("账号 id 无效")
242
+ for record in index["accounts"]:
243
+ if record["id"] == account_id:
244
+ return record
245
+ raise CodeBuddyError("账号不存在")
246
+
247
+ @staticmethod
248
+ def _validated_client_session(
249
+ client: CodeBuddyClient,
250
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
251
+ if not isinstance(client, CodeBuddyClient):
252
+ raise CodeBuddyError("只能导入 CodeBuddyClient 会话")
253
+ session, _ = client._snapshot_session()
254
+ account = session.get("account")
255
+ auth = session.get("auth")
256
+ if (
257
+ not isinstance(account, dict)
258
+ or account.get("uid") is None
259
+ or not str(account.get("uid")).strip()
260
+ ):
261
+ raise CodeBuddyError("账号 session 缺少 uid,不能导入")
262
+ if not _has_auth_token(auth):
263
+ raise CodeBuddyError("账号 session 缺少认证 token,不能导入")
264
+ try:
265
+ client._validate_session_metadata(session)
266
+ backend = client.profile.key
267
+ profile_for_key(backend)
268
+ endpoint = _safe_endpoint(client.endpoint)
269
+ except (ValueError, CodeBuddyError) as exc:
270
+ raise CodeBuddyError("账号 session 的 backend 或 endpoint 无效") from exc
271
+ uid = str(account["uid"]).strip()
272
+ if not uid:
273
+ raise CodeBuddyError("账号 session 缺少 uid,不能导入")
274
+ session["backend"] = backend
275
+ session["endpoint"] = endpoint
276
+ session_account = dict(account)
277
+ session_account["uid"] = uid
278
+ session["account"] = session_account
279
+ metadata = {
280
+ "id": _account_id(backend, endpoint, uid),
281
+ "backend": backend,
282
+ "endpoint": endpoint,
283
+ "uid": uid,
284
+ "nickname": (
285
+ str(account.get("nickname"))[:200]
286
+ if account.get("nickname") is not None
287
+ else None
288
+ ),
289
+ }
290
+ return session, metadata
291
+
292
+ def _new_client(self, record: dict[str, Any]) -> CodeBuddyClient:
293
+ session_file = self._session_file(record["id"])
294
+ if session_file.is_symlink():
295
+ raise CodeBuddyError("账号 session 路径无效")
296
+ profile = profile_for_key(record["backend"])
297
+ client = CodeBuddyClient(
298
+ backend=resolve_backend(
299
+ profile=profile,
300
+ endpoint=record["endpoint"],
301
+ session_file=session_file,
302
+ environment={},
303
+ )
304
+ )
305
+ session, _ = client._snapshot_session()
306
+ identity = self._identity_from_session(client, session)
307
+ if identity != record["id"]:
308
+ raise CodeBuddyError("账号 session 身份与索引不一致")
309
+ if not _has_auth_token(session.get("auth")):
310
+ raise CodeBuddyError("账号 session 缺少认证 token")
311
+ return client
312
+
313
+ @staticmethod
314
+ def _identity_from_session(client: CodeBuddyClient, session: dict[str, Any]) -> str:
315
+ account = session.get("account") or {}
316
+ uid = account.get("uid") if isinstance(account, dict) else None
317
+ if uid is None or not str(uid).strip():
318
+ raise CodeBuddyError("账号 session 缺少 uid")
319
+ endpoint = _safe_endpoint(client.endpoint)
320
+ return _account_id(client.profile.key, endpoint, str(uid).strip())
321
+
322
+ def _get_client_locked(self, record: dict[str, Any]) -> CodeBuddyClient:
323
+ client = self._clients.get(record["id"])
324
+ if client is None:
325
+ client = self._new_client(record)
326
+ self._clients[record["id"]] = client
327
+ return client
328
+
329
+ def list_accounts(self) -> list[dict[str, Any]]:
330
+ with self._lock:
331
+ index = self._read_index_locked()
332
+ active_id = index["active_account_id"]
333
+ return [
334
+ {**record, "active": record["id"] == active_id}
335
+ for record in index["accounts"]
336
+ ]
337
+
338
+ @property
339
+ def active_account_id(self) -> str | None:
340
+ with self._lock:
341
+ return self._read_index_locked()["active_account_id"]
342
+
343
+ def import_client(self, client: CodeBuddyClient, activate: bool = False) -> str:
344
+ session, metadata = self._validated_client_session(client)
345
+ with self._lock:
346
+ index = self._read_index_locked()
347
+ existing = next(
348
+ (record for record in index["accounts"] if record["id"] == metadata["id"]),
349
+ None,
350
+ )
351
+ record = metadata
352
+ session_file = self._session_file(metadata["id"])
353
+ if session_file.is_symlink():
354
+ raise CodeBuddyError("账号 session 路径无效")
355
+ cached = self._clients.get(metadata["id"])
356
+ # Keep cached-client session writers outside the full disk/cache
357
+ # transaction. This covers the rollback interval too, so no writer
358
+ # can persist a newer session between restoring the file and cache.
359
+ session_guard = cached._session_lock if cached is not None else nullcontext()
360
+ with session_guard:
361
+ index_backup = _capture_file(self.index_file)
362
+ session_backup: bytes | None = None
363
+ cached_snapshot: dict[str, Any] | None = None
364
+ session_written = False
365
+ index_write_attempted = False
366
+ try:
367
+ if cached is None:
368
+ session_backup = _capture_file(session_file)
369
+ _atomic_json(session_file, session)
370
+ session_written = True
371
+ persistent_client = self._new_client(record)
372
+ else:
373
+ persistent_client = cached
374
+ for _ in range(5):
375
+ previous_session, generation = cached._snapshot_session()
376
+ candidate_backup = _capture_file(session_file)
377
+ if cached._save_session(
378
+ session, expected_generation=generation
379
+ ):
380
+ session_backup = candidate_backup
381
+ cached_snapshot = previous_session
382
+ session_written = True
383
+ break
384
+ else:
385
+ raise CodeBuddyError(
386
+ "账号 session 正在更新,请稍后重试关联"
387
+ )
388
+
389
+ if existing is None:
390
+ index["accounts"].append(record)
391
+ else:
392
+ position = index["accounts"].index(existing)
393
+ index["accounts"][position] = record
394
+ if activate or (existing is None and len(index["accounts"]) == 1):
395
+ index["active_account_id"] = metadata["id"]
396
+ index_write_attempted = True
397
+ self._write_index_locked(index)
398
+ except Exception as original_error:
399
+ rollback_errors: list[Exception] = []
400
+ if session_written:
401
+ try:
402
+ _restore_file(session_file, session_backup)
403
+ except Exception as exc:
404
+ rollback_errors.append(exc)
405
+ if cached is not None and cached_snapshot is not None:
406
+ try:
407
+ cached._restore_session_snapshot(cached_snapshot)
408
+ except Exception as exc:
409
+ rollback_errors.append(exc)
410
+ if index_write_attempted:
411
+ try:
412
+ _restore_file(self.index_file, index_backup)
413
+ except Exception as exc:
414
+ rollback_errors.append(exc)
415
+ if rollback_errors:
416
+ raise CodeBuddyError(
417
+ "账号关联失败,且事务回滚未能完整恢复"
418
+ ) from rollback_errors[0]
419
+ raise original_error
420
+ self._clients[metadata["id"]] = persistent_client
421
+ return metadata["id"]
422
+
423
+ def get_client(self, account_id: str) -> CodeBuddyClient:
424
+ with self._lock:
425
+ index = self._read_index_locked()
426
+ record = self._find_account(index, account_id)
427
+ return self._get_client_locked(record)
428
+
429
+ def set_active(self, account_id: str) -> CodeBuddyClient:
430
+ with self._lock:
431
+ index = self._read_index_locked()
432
+ record = self._find_account(index, account_id)
433
+ client = self._get_client_locked(record)
434
+ index["active_account_id"] = account_id
435
+ self._write_index_locked(index)
436
+ return client
437
+
438
+ def clear_active(self) -> None:
439
+ """Persist an empty active selection while retaining stored accounts."""
440
+ with self._lock:
441
+ index = self._read_index_locked()
442
+ index["active_account_id"] = None
443
+ self._write_index_locked(index)
444
+
445
+ def active_client(self) -> CodeBuddyClient | None:
446
+ with self._lock:
447
+ index = self._read_index_locked()
448
+ active_id = index["active_account_id"]
449
+ if active_id is None:
450
+ return None
451
+ record = self._find_account(index, active_id)
452
+ return self._get_client_locked(record)
453
+
454
+ def delete_account(self, account_id: str) -> None:
455
+ with self._lock:
456
+ index = self._read_index_locked()
457
+ record = self._find_account(index, account_id)
458
+ if index["active_account_id"] == account_id:
459
+ raise CodeBuddyError("不能删除当前生效账号")
460
+ session_file = self._session_file(record["id"])
461
+ if session_file.is_symlink():
462
+ raise CodeBuddyError("账号 session 路径无效")
463
+ cached = self._clients.get(account_id)
464
+ if cached is not None:
465
+ cached._invalidate_persistence()
466
+ saved_bytes: bytes | None = None
467
+ try:
468
+ if session_file.exists():
469
+ saved_bytes = session_file.read_bytes()
470
+ session_file.unlink()
471
+ except OSError as exc:
472
+ if cached is not None:
473
+ cached._enable_persistence()
474
+ raise CodeBuddyError("无法删除账号 session 文件") from exc
475
+ index["accounts"] = [
476
+ item for item in index["accounts"] if item["id"] != account_id
477
+ ]
478
+ try:
479
+ self._write_index_locked(index)
480
+ except Exception:
481
+ if saved_bytes is not None:
482
+ temp_name: str | None = None
483
+ try:
484
+ fd, temp_name = tempfile.mkstemp(
485
+ prefix=f".{session_file.name}.",
486
+ suffix=".restore.tmp",
487
+ dir=self.root,
488
+ )
489
+ with os.fdopen(fd, "wb") as stream:
490
+ stream.write(saved_bytes)
491
+ stream.flush()
492
+ os.fsync(stream.fileno())
493
+ os.replace(temp_name, session_file)
494
+ temp_name = None
495
+ except OSError:
496
+ pass
497
+ finally:
498
+ if temp_name is not None:
499
+ try:
500
+ os.unlink(temp_name)
501
+ except OSError:
502
+ pass
503
+ if cached is not None:
504
+ cached._enable_persistence()
505
+ raise
506
+ self._clients.pop(account_id, None)