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,226 @@
1
+ """Native Aha device lifecycle, separated from OAuth installation-key policy.
2
+
3
+ The backend is injected. Merely constructing/reading this service cannot issue
4
+ requests; start(allow_network=True) is an explicit lifecycle operation.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ from collections import deque
10
+ from dataclasses import dataclass
11
+ from typing import Awaitable, Callable, Protocol
12
+ import uuid
13
+
14
+ from .aha_device_cache import DeviceRecord
15
+ from .aha_native_semantics import migrate_old_id, needs_registration, retry_delay_ms
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class RegisterReply:
20
+ device_id: object = None
21
+ install_id: object = None
22
+ status: int = 200
23
+ net_error: int = 0
24
+ region_record_ready: bool | None = None
25
+ country_code: str | None = None
26
+ country_source: str = "did"
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class ActiveReply:
31
+ status: int = 200
32
+ net_error: int = 0
33
+
34
+
35
+ class NativeBackend(Protocol):
36
+ async def register(self, device_id: str, install_id: str) -> RegisterReply: ...
37
+ async def activate(self, device_id: str, install_id: str) -> ActiveReply: ...
38
+
39
+
40
+ class NativeAhaDeviceService:
41
+ def __init__(self, *, hardware_uuid: str | None, record: DeviceRecord | None = None,
42
+ local_device_id: str | None = None,
43
+ app_region: str = "CN", region_record_ready: bool = False,
44
+ flags_2: bool = False, flags_3: bool = False,
45
+ backend: NativeBackend | None = None,
46
+ save_cache: Callable[[DeviceRecord], Awaitable[None]] | None = None,
47
+ update_region: Callable[[str, str], Awaitable[None]] | None = None,
48
+ sleep: Callable[[float], Awaitable[None]] = asyncio.sleep):
49
+ self.hardware_uuid = hardware_uuid
50
+ self.local_device_id = (local_device_id if local_device_id is not None else
51
+ hardware_uuid if hardware_uuid is not None else str(uuid.uuid4()))
52
+ self.device_id = record.device_id if record else ""
53
+ self.install_id = record.install_id if record else ""
54
+ self.old_device_id = ""
55
+ self.main_id = self.device_id or "0"
56
+ self.remote_id = self.device_id or "0"
57
+ self.app_region, self.region_record_ready = app_region, region_record_ready
58
+ self.defer_callback = bool(flags_2 and flags_3)
59
+ # The reviewed GetDeviceId wrapper initializes the four-byte context
60
+ # to zero at 0x0284a683. The two-bit branch is retained for other inputs.
61
+ self.backend, self.save_cache, self.sleep = backend, save_cache, sleep
62
+ self.update_region = update_region
63
+ self.network_type = 0 # Native connection type 6 is unavailable.
64
+ self.in_flight = False
65
+ self.waiting_network = False
66
+ self.last_error: str | None = None
67
+ self.last_cache_error: str | None = None
68
+ self.retry_delays = deque(maxlen=256)
69
+ self._enabled = False
70
+ self._worker: asyncio.Task | None = None
71
+ self._getters: set[asyncio.Future] = set()
72
+ self._resolutions: set[asyncio.Task] = set()
73
+ self._wrappers: set[asyncio.Task] = set()
74
+
75
+ def start_wrapper(self, *, timeout: float = 40.0) -> asyncio.Task:
76
+ task = asyncio.create_task(self.resolve(timeout=timeout))
77
+ self._wrappers.add(task)
78
+ def finished(done):
79
+ self._wrappers.discard(done)
80
+ if not done.cancelled():
81
+ done.exception()
82
+ task.add_done_callback(finished)
83
+ return task
84
+
85
+ def _needs_registration(self) -> bool:
86
+ return needs_registration(self.device_id, self.app_region, self.region_record_ready)
87
+
88
+ async def start(self, *, allow_network: bool = False) -> None:
89
+ if not allow_network:
90
+ return
91
+ if self.backend is None:
92
+ raise ValueError("native lifecycle requires an explicitly supplied backend")
93
+ self._enabled = True
94
+ if self._needs_registration() and (self._worker is None or self._worker.done()):
95
+ self._worker = asyncio.create_task(self._cycle())
96
+
97
+ async def _save(self) -> None:
98
+ if self.save_cache is not None:
99
+ try:
100
+ await self.save_cache(DeviceRecord(self.device_id, self.install_id, self.hardware_uuid or ""))
101
+ except OSError as error:
102
+ self.last_cache_error = type(error).__name__
103
+
104
+ async def set_old_device_id(self, value: str) -> bool:
105
+ result = migrate_old_id(self.device_id, value, self.old_device_id)
106
+ self.device_id, self.old_device_id = result.device_id, result.old_device_id
107
+ if result.write_cache:
108
+ await self._save()
109
+ return result.accepted
110
+
111
+ async def get_device_id(self, old_device_id: str | None = None) -> str:
112
+ if old_device_id is not None:
113
+ await self.set_old_device_id(old_device_id)
114
+ # Native checks NONEMPTY here, not the numeric validity of the ID.
115
+ if self.device_id:
116
+ return self.device_id
117
+ future = asyncio.get_running_loop().create_future()
118
+ self._getters.add(future)
119
+ try:
120
+ return await future
121
+ finally:
122
+ self._getters.discard(future)
123
+
124
+ def _notify(self) -> None:
125
+ for future in tuple(self._getters):
126
+ if not future.done():
127
+ future.set_result(self.device_id)
128
+
129
+ async def resolve(self, *, timeout: float = 40.0, old_device_id: str | None = None) -> dict[str, str]:
130
+ if timeout < 0:
131
+ raise ValueError("timeout must be nonnegative")
132
+ task = asyncio.create_task(self.get_device_id(old_device_id))
133
+ self._resolutions.add(task)
134
+ def resolved(done):
135
+ self._resolutions.discard(done)
136
+ if not done.cancelled() and done.exception() is None:
137
+ self.main_id = self.remote_id = done.result()
138
+ task.add_done_callback(resolved)
139
+ try:
140
+ self.main_id = self.remote_id = await asyncio.wait_for(asyncio.shield(task), timeout)
141
+ except asyncio.TimeoutError:
142
+ if not self.main_id or self.main_id == "0":
143
+ self.main_id = self.local_device_id
144
+ return self.get_all_ids()
145
+
146
+ def get_all_ids(self) -> dict[str, str]:
147
+ return {"deviceId": self.main_id, "localDeviceId": self.local_device_id, "remoteDeviceId": self.remote_id}
148
+
149
+ async def _cycle(self):
150
+ attempt = 0
151
+ while self._enabled:
152
+ self.in_flight = True
153
+ try:
154
+ reply = await self.backend.register(self.device_id, self.install_id)
155
+ parsed = (reply.net_error == 0 and reply.status == 200
156
+ and isinstance(reply.device_id, str) and isinstance(reply.install_id, str))
157
+ if parsed:
158
+ # Parser copies both fields BEFORE the success check.
159
+ self.device_id, self.install_id = reply.device_id, reply.install_id
160
+ success = parsed and self.device_id not in ("", "0")
161
+ if success:
162
+ await self._save()
163
+ if not self.defer_callback:
164
+ self._notify()
165
+ activation = asyncio.create_task(self.backend.activate(self.device_id, self.install_id))
166
+ try:
167
+ # Native dispatches activation, then persists region;
168
+ # activation response handling follows that callback.
169
+ await asyncio.sleep(0)
170
+ if reply.region_record_ready is not None:
171
+ self.region_record_ready = reply.region_record_ready
172
+ if reply.country_code is not None and self.update_region is not None:
173
+ try:
174
+ await self.update_region(reply.country_code, reply.country_source)
175
+ except OSError as error:
176
+ self.last_cache_error = type(error).__name__
177
+ active = await activation
178
+ finally:
179
+ if not activation.done():
180
+ activation.cancel()
181
+ await asyncio.gather(activation, return_exceptions=True)
182
+ # Body parsing is diagnostic in the original callback.
183
+ active_ok = active.status == 200 and active.net_error == 0
184
+ if not self.defer_callback or active_ok:
185
+ if self.defer_callback:
186
+ self._notify()
187
+ self.last_error = None if active_ok else "activation transport failed after early delivery"
188
+ return
189
+ self.last_error = "activation transport failed"
190
+ else:
191
+ self.last_error = "registration failed"
192
+ finally:
193
+ self.in_flight = False
194
+ if self.network_type == 6:
195
+ self.waiting_network = True
196
+ return
197
+ delay = retry_delay_ms(attempt)
198
+ self.retry_delays.append(delay)
199
+ attempt = (attempt + 1) & 0xffffffff
200
+ await self.sleep(delay / 1000)
201
+
202
+ async def on_network_change(self, connection_type: int) -> None:
203
+ self.network_type = connection_type
204
+ if (not self._enabled or connection_type == 6 or self.in_flight
205
+ or not self._needs_registration()):
206
+ return
207
+ if self._worker is not None and not self._worker.done():
208
+ self._worker.cancel()
209
+ await asyncio.gather(self._worker, return_exceptions=True)
210
+ self.waiting_network = False
211
+ self._worker = asyncio.create_task(self._cycle())
212
+
213
+ async def wait_worker(self) -> None:
214
+ if self._worker is not None:
215
+ await self._worker
216
+
217
+ async def close(self) -> None:
218
+ self._enabled = False
219
+ tasks = list(self._resolutions | self._wrappers)
220
+ if self._worker is not None:
221
+ tasks.append(self._worker)
222
+ for task in tasks:
223
+ task.cancel()
224
+ for future in tuple(self._getters):
225
+ future.cancel()
226
+ await asyncio.gather(*tasks, return_exceptions=True)
@@ -0,0 +1,67 @@
1
+ """Small Aha branches checked against allowlisted original PE instructions."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+
6
+ UINT64_MAX = (1 << 64) - 1
7
+ _SPACE = b"\t\v\f \n\r"
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class ParsedUint64:
12
+ ok: bool
13
+ value: int
14
+
15
+
16
+ def parse_uint64(value: str) -> ParsedUint64:
17
+ """RVA 0x041f5160, including false-result output values."""
18
+ raw = value.encode("utf-8")
19
+ clean, pos, number = True, 0, 0
20
+ while pos < len(raw) and raw[pos] in _SPACE:
21
+ clean, pos = False, pos + 1
22
+ if pos == len(raw) or raw[pos] == 45:
23
+ return ParsedUint64(False, 0)
24
+ if raw[pos] == 43:
25
+ pos += 1
26
+ if pos == len(raw):
27
+ return ParsedUint64(False, 0)
28
+ for byte in raw[pos:]:
29
+ if not 48 <= byte <= 57:
30
+ return ParsedUint64(False, number)
31
+ digit = byte - 48
32
+ if number > UINT64_MAX // 10 or number == UINT64_MAX // 10 and digit >= 6:
33
+ return ParsedUint64(False, UINT64_MAX)
34
+ number = number * 10 + digit
35
+ return ParsedUint64(clean, number)
36
+
37
+
38
+ def needs_registration(device_id: str, region: str, region_record_ready: bool) -> bool:
39
+ """RVA 0x02849050; readiness belongs to decoded RegionManager data."""
40
+ parsed = parse_uint64(device_id)
41
+ if not parsed.ok or not parsed.value:
42
+ return True
43
+ if region in ("CN", "Cn", "cN", "cn"):
44
+ return False
45
+ return not region_record_ready
46
+
47
+
48
+ def retry_delay_ms(attempt: int) -> int:
49
+ """RVA 0x0284eafb: uint32 arithmetic, five-attempt steps, 30s cap."""
50
+ count = attempt & 0xffffffff
51
+ calculated = (count // 5 * 1000 + 1000) & 0xffffffff
52
+ return min(calculated, 30000)
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class OldIdMigration:
57
+ accepted: bool
58
+ device_id: str
59
+ old_device_id: str
60
+ write_cache: bool
61
+
62
+
63
+ def migrate_old_id(current_id: str, old_id: str, previous_old_id: str = "") -> OldIdMigration:
64
+ """RVA 0x02849440. Telemetry checks do not reject the setter's input."""
65
+ if not old_id or old_id == "0":
66
+ return OldIdMigration(False, current_id, previous_old_id, False)
67
+ return OldIdMigration(True, old_id if current_id else current_id, old_id, bool(current_id))
@@ -0,0 +1,157 @@
1
+ """Standalone Aha device registration based on the reviewed 3.4.20 binary.
2
+
3
+ Uses real local hardware. Does not read native login/cache files, rotate a login
4
+ token, or claim that arbitrary locally generated IDs are registered.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass, field
9
+ import json
10
+ import time
11
+ import zlib
12
+
13
+ import httpx
14
+
15
+ from .client_metadata import client_version
16
+ from .device_hardware import Hardware
17
+ from .aha_native_semantics import parse_uint64
18
+
19
+ REGISTER_URL = "https://log.snssdk.com/service/2/desktop/device_register/"
20
+ ACTIVE_URL = "https://log.snssdk.com/service/2/app_alert_check/"
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Registration:
25
+ device_id: str = field(repr=False)
26
+ install_id: str = field(repr=False)
27
+ region: str
28
+
29
+
30
+ def registration_request(hardware: Hardware, version: str, now: float | None = None, *,
31
+ device_id: str = "0", install_id: str = "0") -> tuple[dict, bytes]:
32
+ language = "zh-CN" # Reviewed CN desktop initialization config.
33
+ # Windows native config: appId=787976, package=com.trae.app, channel=stable.
34
+ query = {"aid": "787976", "channel": "stable", "os": "Windows",
35
+ "os_version": hardware.os_release, "device_platform": "PC",
36
+ "version_code": version, "pc_uuid": hardware.pc_uuid, "pc_serial": hardware.pc_serial}
37
+ offset = -(time.altzone if time.daylight and time.localtime().tm_isdst else time.timezone)
38
+ # Native converts the uint64 parser's output to double before Dict.Set.
39
+ header = {"device_id": float(parse_uint64(device_id).value),
40
+ "install_id": float(parse_uint64(install_id).value), "aid": 787976.0, "os": "Windows",
41
+ "device_platform": "PC", "mc": hardware.mac, "channel": "stable", "package": "com.trae.app",
42
+ "language": language, "app_version": version, "os_version": hardware.os_release,
43
+ "device_model": hardware.model, "time_zone": int(offset / 3600),
44
+ "tz_name": time.tzname[time.localtime().tm_isdst > 0], "tz_offset": offset,
45
+ "app_region": "CN", "app_language": language, "display_name": "Trae CN",
46
+ "pc_uuid": hardware.pc_uuid, "pc_serial": hardware.pc_serial}
47
+ body = {"header": header, "_gen_time": int((time.time() if now is None else now) * 1000),
48
+ "magic_tag": "ss_app_log"}
49
+ # RegisterDevice calls deflateInit2(-1, 8, 31, 9, 0): gzip framing,
50
+ # default compression and memLevel=9. The HTTP transport must declare gzip;
51
+ # live standalone validation returned zero IDs without Content-Encoding.
52
+ compressor = zlib.compressobj(-1, zlib.DEFLATED, 31, 9, zlib.Z_DEFAULT_STRATEGY)
53
+ raw = json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
54
+ return query, compressor.compress(raw) + compressor.flush()
55
+
56
+
57
+ def _response(response: httpx.Response, stage: str) -> dict:
58
+ if response.status_code != 200:
59
+ raise ValueError(f"device {stage} failed: HTTP {response.status_code}")
60
+ try:
61
+ body = response.json()
62
+ except ValueError:
63
+ raise ValueError(f"device {stage} returned invalid JSON") from None
64
+ if not isinstance(body, dict):
65
+ raise ValueError(f"device {stage} returned an invalid object")
66
+ return body
67
+
68
+
69
+ def register(client: httpx.Client, hardware: Hardware, version: str | None = None,
70
+ *, strict_ids: bool = True) -> Registration:
71
+ version = version or client_version("3.4.20")
72
+ query, body = registration_request(hardware, version)
73
+ try:
74
+ response = client.post(REGISTER_URL, params=query, content=body,
75
+ headers={"Content-Type": "application/json", "Content-Encoding": "gzip"}, follow_redirects=False)
76
+ except httpx.HTTPError as exc:
77
+ raise ValueError(f"device registration network error ({type(exc).__name__}); not retried") from None
78
+ result = _response(response, "registration")
79
+ device_id, install_id = result.get("device_id_str"), result.get("install_id_str")
80
+ invalid = any(not isinstance(value, str) for value in (device_id, install_id))
81
+ if not invalid:
82
+ invalid = (any(not value.isascii() or not value.isdecimal() or int(value) <= 0
83
+ for value in (device_id, install_id)) if strict_ids else device_id in ("", "0"))
84
+ if invalid:
85
+ states = []
86
+ for key in ("device_id", "install_id"):
87
+ value = result.get(key)
88
+ states.append(f"{key}=" + ("zero" if value == 0 else "present" if value is not None else "missing"))
89
+ raise ValueError("device registration did not return valid device_id_str/install_id_str (" + ", ".join(states) + ")")
90
+ region = response.headers.get("x-tt-store-region", "CN").upper()
91
+ if strict_ids and region not in ("CN", "SG", "US", "USTTP"):
92
+ raise ValueError("device registration returned an unsupported store region")
93
+ return Registration(device_id, install_id, region)
94
+
95
+
96
+
97
+ def _activation_diagnostic(*, response: httpx.Response | None = None,
98
+ error: str | None = None) -> None:
99
+ """Log only an allowlist of non-identifying activation response facts."""
100
+ from .diagnostics import get_logger
101
+ diagnostic = {"kind": "device_activation", "http_status": response.status_code if response is not None else None}
102
+ if error:
103
+ diagnostic["network_error"] = error
104
+ if response is not None:
105
+ try:
106
+ body = response.json()
107
+ except ValueError:
108
+ diagnostic["response_type"] = "invalid_json"
109
+ else:
110
+ diagnostic["response_type"] = type(body).__name__
111
+ if isinstance(body, dict):
112
+ message = body.get("message")
113
+ diagnostic["message_state"] = ("missing" if "message" not in body else
114
+ "success" if message == "success" else "other_string" if isinstance(message, str)
115
+ else type(message).__name__)
116
+ data = body.get("data")
117
+ diagnostic["data_type"] = "missing" if "data" not in body else type(data).__name__
118
+ if isinstance(data, dict):
119
+ flag = data.get("is_activated")
120
+ diagnostic["activation_type"] = ("missing" if "is_activated" not in data
121
+ else type(flag).__name__)
122
+ if type(flag) in (bool, int) and flag in (0, 1):
123
+ diagnostic["activation_value"] = flag
124
+ elif isinstance(flag, str) and flag in ("0", "1", "true", "false"):
125
+ diagnostic["activation_value"] = flag
126
+ elif "is_activated" in data:
127
+ diagnostic["activation_value"] = "other"
128
+ code = body.get("code")
129
+ if type(code) is int and -999999 <= code <= 999999:
130
+ diagnostic["code"] = code
131
+ get_logger().info(json.dumps(diagnostic, ensure_ascii=False))
132
+
133
+
134
+ def activate(client: httpx.Client, result: Registration, hardware: Hardware, version: str, *,
135
+ require_confirmation: bool = True) -> None:
136
+ query = {"aid": "787976", "app_name": "Trae CN", "version_code": version,
137
+ "channel": "stable", "os": "Windows", "device_platform": "PC",
138
+ "device_id": result.device_id, "iid": result.install_id,
139
+ "pc_uuid": hardware.pc_uuid, "pc_serial": hardware.pc_serial}
140
+ try:
141
+ response = client.post(ACTIVE_URL, params=query, content=b"",
142
+ headers={"Content-Type": "application/json"}, follow_redirects=False)
143
+ except httpx.HTTPError as exc:
144
+ _activation_diagnostic(error=type(exc).__name__)
145
+ raise ValueError(f"device activation network error ({type(exc).__name__}); not retried") from None
146
+ _activation_diagnostic(response=response)
147
+ if not require_confirmation:
148
+ # Native Aha's completion condition is transport success plus HTTP 200;
149
+ # the response body is diagnostic, not proof of account eligibility.
150
+ if response.status_code != 200:
151
+ raise ValueError(f"device activation failed: HTTP {response.status_code}")
152
+ return
153
+ body = _response(response, "activation")
154
+ data = body.get("data")
155
+ flag = data.get("is_activated") if isinstance(data, dict) else None
156
+ if body.get("message") != "success" or type(flag) not in (bool, int) or flag != 1:
157
+ raise ValueError("device activation was not confirmed")
@@ -0,0 +1,135 @@
1
+ """Read-only-by-default TinyStorage adapter with an explicit native-root helper."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import threading
9
+
10
+ from .aha_cache_codec import decode, encode
11
+ from .aha_device_cache import DeviceRecord
12
+ from .login_identity import atomic_json
13
+
14
+ PREF = "tiny_storage_data"
15
+ DEVICE = "aha.device.device_id"
16
+ REGION = "aha_device_region"
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class RegionRecord:
21
+ ready: bool = False
22
+ country_code: str = ""
23
+ source: str = ""
24
+ query: dict[str, str] | None = None
25
+ headers: dict[str, str] | None = None
26
+
27
+ @classmethod
28
+ def load(cls, value: object) -> RegionRecord:
29
+ if not isinstance(value, str):
30
+ return cls()
31
+ try:
32
+ data = json.loads(decode(value))
33
+ except (ValueError, UnicodeError):
34
+ return cls()
35
+ if not isinstance(data, dict):
36
+ return cls()
37
+ def text(name):
38
+ value = data.get(name)
39
+ return value if isinstance(value, str) else ""
40
+ def mapping(name):
41
+ value = data.get(name)
42
+ return {key: item for key, item in value.items() if isinstance(item, str)} if isinstance(value, dict) else None
43
+ # 0x02844ce0 marks a parsed dictionary ready even when fields are absent.
44
+ return cls(True, text("countryCode"), text("countryCodeSrc"), mapping("query"), mapping("headers"))
45
+
46
+ def encoded(self, *, clock: int | None = None) -> str:
47
+ data = {"countryCode": self.country_code, "countryCodeSrc": self.source}
48
+ if self.query is not None:
49
+ data["query"] = self.query
50
+ if self.headers is not None:
51
+ data["headers"] = self.headers
52
+ return encode(json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode(), clock=clock)
53
+
54
+ def updated(self, other: RegionRecord) -> RegionRecord:
55
+ # RegionManager updates strings, but keeps optional maps when omitted.
56
+ return RegionRecord(True, other.country_code, other.source,
57
+ self.query if other.query is None else other.query,
58
+ self.headers if other.headers is None else other.headers)
59
+
60
+
61
+ class NativeTinyStorage:
62
+ def __init__(self, path: Path, *, writable: bool = False, legacy_preferences: Path | None = None):
63
+ self.path, self.writable = Path(path), writable
64
+ self.legacy_preferences = (Path(legacy_preferences) if legacy_preferences is not None else
65
+ self.path.parent.parent / "Preferences"
66
+ if self.path.name == "TinyStorage" and self.path.parent.name == "aha" else None)
67
+ self._lock = threading.RLock()
68
+
69
+ @classmethod
70
+ def for_native_client(cls, *, client_root: Path | None = None, writable: bool = False):
71
+ if client_root is None:
72
+ roaming = os.environ.get("APPDATA")
73
+ if not roaming:
74
+ raise ValueError("native Windows cache root requires APPDATA or an explicit client_root")
75
+ client_root = Path(roaming) / "Trae CN"
76
+ return cls(Path(client_root) / "aha" / "TinyStorage", writable=writable)
77
+
78
+ def _root(self) -> dict:
79
+ if not self.path.exists():
80
+ return {}
81
+ try:
82
+ value = json.loads(self.path.read_text(encoding="utf-8-sig"))
83
+ except (ValueError, UnicodeError):
84
+ return {}
85
+ return value if isinstance(value, dict) else {}
86
+
87
+ def get(self, key: str) -> str | None:
88
+ try:
89
+ root = self._root()
90
+ if PREF not in root and self.legacy_preferences is not None:
91
+ source = json.loads(self.legacy_preferences.read_text(encoding="utf-8-sig"))
92
+ if isinstance(source, dict):
93
+ old = source.get(PREF)
94
+ values = dict(old) if isinstance(old, dict) else {}
95
+ if isinstance(source.get(DEVICE), str):
96
+ values[DEVICE] = source[DEVICE]
97
+ root[PREF] = values
98
+ if self.writable:
99
+ with self._lock:
100
+ # Recheck after acquiring the writer lock.
101
+ current = self._root()
102
+ if PREF not in current:
103
+ current[PREF] = values
104
+ atomic_json(self.path, current)
105
+ else:
106
+ root = current
107
+ values = root.get(PREF)
108
+ except (OSError, ValueError, UnicodeError):
109
+ return None
110
+ value = values.get(key) if isinstance(values, dict) else None
111
+ return value if isinstance(value, str) else None
112
+
113
+ def load_device(self, hardware_uuid: str) -> DeviceRecord | None:
114
+ return DeviceRecord.load(self.get(DEVICE), hardware_uuid)
115
+
116
+ def load_region(self) -> RegionRecord:
117
+ return RegionRecord.load(self.get(REGION))
118
+
119
+ def _set(self, key: str, value: str) -> None:
120
+ if not self.writable:
121
+ raise PermissionError("TinyStorage adapter is read-only")
122
+ with self._lock:
123
+ root = self._root()
124
+ values = root.get(PREF)
125
+ if not isinstance(values, dict):
126
+ values = {}
127
+ root[PREF] = values
128
+ values[key] = value
129
+ atomic_json(self.path, root)
130
+
131
+ def save_device(self, record: DeviceRecord) -> None:
132
+ self._set(DEVICE, record.encoded())
133
+
134
+ def save_region(self, record: RegionRecord) -> None:
135
+ self._set(REGION, record.encoded())