buddy-agent-checkin 0.1.1.dev2__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.
@@ -0,0 +1,254 @@
1
+ Metadata-Version: 2.4
2
+ Name: buddy-agent-checkin
3
+ Version: 0.1.1.dev2
4
+ Summary: Account-aware activity check-in library for Trae CN
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: fastapi<1,>=0.100
8
+ Requires-Dist: httpx<1,>=0.25
9
+ Requires-Dist: buddy-agent-auth[trae]<0.2,>=0.1.0.dev1
10
+ Provides-Extra: workbuddy
11
+ Requires-Dist: buddy-agent-auth<0.2,>=0.1.0.dev1; extra == "workbuddy"
12
+
13
+ # DailyCheckin
14
+
15
+ DailyCheckin 是一个专注活动签到的 Python 库,目前支持 Trae CN 签到及签到状态查询,按账号保存设备配置和绑定。Trae 和 WorkBuddy 的登录态获取由 `buddy-agent-auth` 的品牌 provider 提供,Trae 的独立浏览器 OAuth 登录、设备注册和账号绑定也由认证包提供。项目原名 trae2api;旧代理和研究代码保留在源码中,但不包含在 DailyCheckin 发行包中。
16
+
17
+ ## 使用 uv 开发和构建
18
+
19
+ 当前开发版为 `0.1.1.dev2`。发布后可通过 `uv sync --prerelease allow` 从 PyPI 安装;本地联调可先把认证包构建到本项目 `dist`:
20
+
21
+ ```powershell
22
+ # 在 DailyCheckin 项目目录执行;需要相邻的 WorkBuddy2API 源码
23
+ uv build ..\workbuddy2api\packages\buddy-agent-auth --out-dir dist
24
+ uv sync --prerelease allow --find-links dist --extra workbuddy
25
+
26
+ # 启动命令;去掉 --status-only/--execute 是不会读取凭据的 dry run
27
+ uv run daily-checkin --native --device-id-source get-device-id --status-only
28
+ uv run --extra workbuddy daily-checkin workbuddy --help
29
+
30
+ # 运行测试、构建 sdist 和 wheel
31
+ uv run --extra workbuddy pytest
32
+ uv build --out-dir dist
33
+ ```
34
+
35
+ 生成的 `dist/buddy_agent_checkin-0.1.1.dev2-py3-none-any.whl` 可供 WorkBuddy2API 本地依赖;`dist/buddy_agent_auth-0.1.0.dev1-py3-none-any.whl` 用于当前开发环境解析 WorkBuddy 可选依赖。`dist` 中的包文件不提交到 Git,因此新检出仓库需要先构建认证 wheel,已发布版本可从包仓库解析。需要更新依赖时请增加 dev 版本号并重新构建。
36
+
37
+ ## 签到快速开始
38
+
39
+ 在项目目录安装依赖后,可使用新名称运行(也可通过 `pip install -e .` 安装并使用 `daily-checkin` 命令):
40
+
41
+ ```powershell
42
+ # 查询签到状态
43
+ python -m daily_checkin --native --device-id-source get-device-id --status-only
44
+
45
+ # 执行签到
46
+ python -m daily_checkin --native --device-id-source get-device-id --execute
47
+
48
+ # 指定独立凭据文件
49
+ python -m daily_checkin --creds .\trae2api\trae2api.json --status-only
50
+ ```
51
+
52
+ 作为 Python 库使用:
53
+
54
+ ```python
55
+ import httpx
56
+ from daily_checkin import Account, checkin
57
+
58
+ account = Account.from_native(device_id_source="get-device-id")
59
+ with httpx.Client(timeout=30, trust_env=False) as client:
60
+ result = checkin(account, client, status_only=True)
61
+ ```
62
+
63
+ `--native` 读取原生账号和 token;默认的 `--device-id-source get-device-id` 使用项目中按账号保存的设备配置及绑定,不需要原生设备缓存或会话日志,默认地区为 CN(可用 `--user-region` 覆盖)。显式选择 `--device-id-source existing` 才使用并校验原生设备 ID 和日志地区。首次使用账号设备来源可能触发设备注册和激活;`--execute` 会在符合条件时请求领取。源码检出中的原有 `python -m trae2api.checkin` 入口及 `.traeapi` 账号设备数据继续沿用。发行包使用 `python -m daily_checkin`。设备激活与签到仍需真实环境验收。
64
+
65
+ ## WorkBuddy 独立签到
66
+
67
+ DailyCheckin 不需要运行 WorkBuddy2API,即可通过独立的 `buddy-agent-auth` 包读取并维护 WorkBuddy 账号。源码开发时先安装 WorkBuddy2API 仓库的认证包,再安装本项目:
68
+
69
+ ```powershell
70
+ python -m pip install -e D:\workspace\workbuddy2api\packages\buddy-agent-auth
71
+ python -m pip install -e ".[workbuddy]"
72
+
73
+ python -m daily_checkin workbuddy login --global
74
+ python -m daily_checkin workbuddy list
75
+ python -m daily_checkin workbuddy status --account <账号ID>
76
+ python -m daily_checkin workbuddy execute --account <账号ID>
77
+ python -m daily_checkin workbuddy schedule
78
+ ```
79
+
80
+ `--accounts-dir` 位于 `workbuddy` 与子命令之间;未指定时使用 `~/.workbuddy2api/accounts`。`schedule` 会持续运行并在启动及每日按计划检查,Ctrl+C 停止。签到前先查询,结果不确定时不重复领取。WorkBuddy2API 作为宿主时调用同一活动服务;两个进程共用账号目录时,通过持久化的 `daily-checkin-attempts.sqlite3` 防止同一账号当天的未知结果被重复提交。这个记录会保守地阻止重试,不能代替上游状态确认。
81
+
82
+ 开发版本发布后可使用 `pip install --pre buddy-agent-checkin` 安装;本地源码联调仍可使用认证包源码或 wheel。真实 WorkBuddy 登录和签到尚未完成本次集成的线上验收。 WorkBuddy2API 的 `/v1/checkin` 和 `/v1/checkin-status` 兼容端点也由 DailyCheckin 提供,保持原有上游透传语义;其中 `/v1/checkin` 直接提交,不经过账号签到服务的状态预检或跨进程去重。管理界面和独立 `execute` 命令使用账号签到服务。
83
+
84
+ ### Trae CN 自动签到
85
+
86
+ 使用本机 Trae 登录态运行常驻调度器:
87
+
88
+ ```powershell
89
+ uv run daily-checkin trae schedule --native --device-id-source get-device-id
90
+ ```
91
+
92
+ 独立登录凭据可使用 `uv run daily-checkin trae schedule --creds <凭据文件>`。启动时检查当天状态;跨日后先查状态,再在北京时间零点后的 0~10 分钟内随机安排签到。进程需要持续运行;按 `Ctrl+C` 停止。调度器固定启动时的账号,每次操作重新读取登录态;账号切换后需重启。设备已签到或签到结果未知时不会重复领取。
93
+
94
+ 如果希望随 WorkBuddy2API 一起启动,在启动它之前设置 `$env:DAILYCHECKIN_TRAE_NATIVE = "1"`;或者仅设置 `$env:DAILYCHECKIN_TRAE_CREDS = "凭据文件路径"` 使用独立凭据。可选的 `DAILYCHECKIN_TRAE_DEVICE_ID_SOURCE` 支持 `get-device-id`(默认)或 `existing`(仅本机登录态)。Trae 的开关与 WorkBuddy 自动签到开关独立。
95
+
96
+ 独立 Trae 登录可使用 `daily-checkin trae login`,默认凭据写入 `.traeapi/trae2api.json`;源码目录中已有旧凭据文件时继续使用旧文件,也可通过 `--creds` 指定。`TRAE2API_HOME` 仍可指定设备数据目录。
97
+
98
+ ## 原有 trae2api 代理及研究记录(仅源码)
99
+
100
+ 本节历史代理和研究代码不包含在 DailyCheckin 的 wheel 中;源码模式运行旧代理需要额外安装其依赖。
101
+
102
+ TRAE CN IDE (3.4.7) 后端的 OpenAI 兼容代理。当前实现包含本地认证路径和 V1 chat upstream;历史结果曾报告文本请求成功,但远端模型选择及原生能力仍需按下方计划逐项验证。
103
+
104
+ ## 当前证据状态
105
+
106
+ - 代理实现了 OpenAI 兼容 `/v1/chat/completions`,并通过 V1
107
+ `POST /api/ide/v1/chat` 处理文本与 SSE。保存的 `_e2e_verify` 结果曾报告
108
+ 成功回复和 usage;本轮没有重跑,不能当作当前运行验收。
109
+ - `/v1/models` 来自本地模型目录/快照,不证明远端模型可用或实际选中。
110
+ - 目前没有把 Trae 正常会话的一条新输入、远端请求和响应闭合到同一 turn。
111
+ 静态 V2/V3 route、局部 HTTP 探针或 aha IPC 连接日志都不足以证明原生
112
+ 正常链路,也不足以证明 Python 独立调用不可行。
113
+ - 最近一次 45 秒 metadata-only baseline 安装了 `InitWithParams` 与 `Start`
114
+ 两个 hook,记录到 0 次调用,随后正常卸载、detach 且身份复核一致;该窗口
115
+ 没有伴随 UI 测试输入,因此只说明窗口内无可见 Cronet 请求,不说明推理路由不存在。
116
+
117
+ | 能力 | 当前代理证据范围 |
118
+ |---|---|
119
+ | 普通文本 | V1 有历史成功结果;本轮未重验,且未证明是原生会话使用的 route。 |
120
+ | 流式输出与 usage | V1 代码解析 SSE/usage;历史观察不能证明所有终止、错误或截断语义。 |
121
+ | 模型选择 | 默认 V1 请求不透传调用方模型;响应会回显输入模型。本地目录不证明上游选择。 |
122
+ | system / developer | 当前兼容修复将其作为标记文本放入普通用户内容,不等同真正 role。 |
123
+ | tools / tool_choice | V1 使用文本兼容表示和本地工具循环;没有证明上游原生结构化 tool-call 契约。 |
124
+ | reasoning、取消及其他事件 | 尚未按当前远端链路验证;未知能力不应标为已支持。 |
125
+
126
+ 当前证据与阶段门槛见 [Python 客户端复现计划](notes/PYTHON_CLIENT_REPRODUCTION_PLAN_2026-10-27.md)、
127
+ [认证协议审查](notes/AUTH_PROTOCOL_REVIEW_2026-10-27.md) 和
128
+ [原生会话取证记录](notes/NATIVE_CAPTURE_SESSION_2026-10-27.md)、
129
+ [近期远端契约与 metadata 基线](notes/NATIVE_REMOTE_CONTRACT_2026-10-27.md)。历史结论保留在
130
+ [FINAL-VERDICT](notes/FINAL-VERDICT.md) 与
131
+ [HANDOFF](notes/HANDOFF-2026-10-27.md),但其中的绝对架构结论已在文首复核说明中撤回/降级。
132
+
133
+ ### 工具调用是怎么做的
134
+
135
+ 当前 V1 兼容路径以普通文本传递工具说明,让模型输出
136
+ `<|FunctionCallBegin|>[{"name":...,"parameters":...}]<|FunctionCallEnd|>` 标记,
137
+ 再由 `translate.py` 解析成 OpenAI `tool_calls`。
138
+
139
+ 这是现有兼容实现,不证明上游结构化工具协议,也不是“唯一可行”结论。
140
+
141
+ ## 快速开始
142
+
143
+ ```bash
144
+ # 依赖: Python 3.10+, fastapi, uvicorn, httpx, cryptography
145
+ cd D:\workspace\trae2api
146
+
147
+ # 方式 A: 独立登录(当前设备注册实现面向 Windows x64)
148
+ python -m trae2api login # 打开浏览器完成登录,凭据存 trae2api/trae2api.json
149
+ python -m trae2api login --no-browser --timeout 3600 # 手动复制 URL
150
+ python -m trae2api login --creds .\trae2api\trae2api.json --prepare-device # 仅准备独立设备
151
+
152
+ # 方式 B: 复用本机 Trae 的凭据(默认,只读不干扰)
153
+ python -m trae2api # 0.0.0.0:8080
154
+ ```
155
+
156
+ 登录成功后代理优先使用 `trae2api.json`;删除该文件即回到方式 B。
157
+ 独立登录在凭据旁保存 `.device.secret` 设备配置,重复登录会复用注册 ID 和密钥。
158
+ 默认在启动时创建 `~/.traeapi`;如用户目录无创建权限,会依次尝试 Python 所在的同名 Windows 用户目录和项目目录下的 `.traeapi`,并提示实际位置。也可通过 `TRAE2API_HOME` 指定完整存储目录(例如 PowerShell 中 `$env:TRAE2API_HOME="D:\traeapi-data"`);切换目录不会自动迁移已有数据。已注册的独立设备缓存保存在 `~/.traeapi/<deviceId>/TinyStorage`。
159
+ 签到或查询签到状态时,以凭据中的 `auth.userId` 为账号标识,`~/.traeapi/device_pair.json` 保存账号 ID 到设备 ID 的映射,不保存 token。账号没有映射时会先注册设备,并按原生设备流程发送激活请求;HTTP 200 后保存 TinyStorage 和映射,再发送签到请求。HTTP 200 表示激活请求完成,不单独证明服务端已激活或账号有签到资格。激活请求失败时保留待处理的注册记录,下次复用该设备重试;已有映射时直接使用账号已绑定的设备 ID。凭据缺少 `userId` 时无法记录绑定,签到会报错。原生客户端的凭据和缓存仍保持只读。
160
+ 设备激活时会输出 `device_activation` 结构化诊断,包括 HTTP 状态、响应类型和激活标志;不会记录响应正文、令牌或设备 ID。其他日志(例如设备快照)仍可能包含账号和设备标识。首次注册的设备与现有登录 token 的组合尚未完成真实签到验收。
161
+
162
+ 设备硬件信息在进程首次读取时采集一次。签到按 `auth.userId` 在 `~/.traeapi/device_hardware.json` 中查找设备快照;首次使用的账号会生成独立 UUID、漂移后的磁盘序列号和 MAC,并保存完整设备信息,之后直接复用,包括型号和系统版本。调用方可使用 `Hardware.read_native(user_id)` 获取账号快照;不提供账号的设备读取使用进程内缓存的真实设备信息,以兼容原生设备缓存,不会生成漂移结果。设备信息写入控制台和 `logs/debug-<日期>.log`,其中包含账号与设备标识,请注意日志的访问权限和分享范围。
163
+ 设备注册/激活已经实测成功;新版独立浏览器授权、换 token 和签到仍待真实验收,详见
164
+ [独立登录实现与证据](docs/INDEPENDENT_LOGIN_2026-11-20.md)。
165
+
166
+ ```bash
167
+ # 测试
168
+ curl http://127.0.0.1:8080/health
169
+ curl http://127.0.0.1:8080/v1/models
170
+ curl http://127.0.0.1:8080/v1/chat/completions ^
171
+ -H "Content-Type: application/json" ^
172
+ -d "{\"model\":\"x\",\"messages\":[{\"role\":\"user\",\"content\":\"你好\"}],\"stream\":false}"
173
+ ```
174
+
175
+ ### 环境变量
176
+
177
+ | 变量 | 默认 | 说明 |
178
+ |---|---|---|
179
+ | `TRAE2API_PORT` | 8080 | 监听端口 |
180
+ | `TRAE2API_API_KEY` | 空 | 可选的客户端 Bearer 鉴权 |
181
+ | `TRAE2API_GATEWAY` | `https://trae-api-cn.mchost.guru` | 网关地址 |
182
+ | `TRAE2API_MODEL` | 空 | 强制 model_name(默认省略→服务端默认模型) |
183
+ | `TRAE2API_PASSTHROUGH_MODEL` | 0 | 为 1 时透传调用方 model 名(当前网关白名单会 4023) |
184
+ | `TRAE2API_TLS_IMPERSONATE` | `chrome124` | TLS 指纹模拟(curl_cffi);`off` 关闭用 httpx |
185
+ | `TRAE2API_ALLOW_ROTATION` | 0 | 为 1 时允许 RefreshToken 轮换(会使运行中的 Trae 登出,慎用) |
186
+ | `TRAE2API_DEV_CPU/DEV_MODEL/DEV_OS_TYPE/DEV_OS_VERSION/UA` | 本机实机值 | 设备指纹覆盖 |
187
+
188
+ ### 登录流(`python -m trae2api login`)原理
189
+ 1. 读取持久化的独立设备身份;首次通过 Aha 注册/激活真实硬件,保存远端 device_id、machine_id 和 ECDSA P-256 密钥,每轮重新生成 PKCE S256 对
190
+ 2. 本地起一次性 HTTP 服务器监听 `/authorize`(随机端口,30 分钟超时)
191
+ 3. 打开 `https://www.trae.cn/authorization?...`(按已确认的原生字段构建;plugin_version 来自 tronBuildVersion,设备字段来自系统信息,完整线上等价尚未验收)
192
+ 4. 用户在浏览器完成登录 → 重定向回 `http://127.0.0.1:{port}/authorize?authCodeInfo={"AuthCode":"..."}`
193
+ 5. `POST /trae/api/v3/oauth/ExchangeToken`(AuthCode+CodeVerifier+DeviceInfo,无签名)→ Token/RefreshToken
194
+ 6. `POST /cloudide/api/v3/trae/GetUserInfo` 拉取有效用户资料 → 原子替换指定的独立凭据文件
195
+
196
+ ## 逆向结论摘要(详见 notes/)
197
+
198
+ ### 认证链
199
+ 1. **凭据存储**: `%APPDATA%\Trae CN\User\globalStorage\storage.json`
200
+ - `iCubeAuthInfo://icube.cloudide` → `{token, refreshToken, userId, host, userRegion, ...}`(自研 AES-128-CBC 包装,`credential_decrypt.py` 已破解并实测)
201
+ - `iCubeAuthInfo://icube-dc:{deviceId}` → ECDSA P-256 设备密钥对
202
+ 2. **RefreshToken 轮换(默认关闭)**: `POST {host}/trae/api/v3/oauth/ExchangeToken`
203
+ - body: `{ClientID:"ono9krqynydwx5", RefreshToken, DeviceInfo, DeviceProof{ECDSA 签名}, IDEVersion}`
204
+ - 签名串: `POST\n/trae/api/v3/oauth/ExchangeToken\n{ClientID}\n{RefreshToken}\n{ts}\n{nonce}`
205
+ 3. **Token 使用/更新**: 当前 PKCE 登录保存 `ExchangeToken.Result.Token`;代理 `auth.py` 会优先复用有效凭据,并在特定过期/强制刷新路径尝试 `GetUserToken`。尚未证明普通 CN 推理请求必须先 mint 该 JWT,或该 token 与远端 LLM 授权头的对应关系。
206
+ 4. **请求头**: `Authorization: Cloud-IDE-JWT {jwt}` + `X-User-Region: CN` + 设备头组
207
+ (`X-Device-Id/X-Machine-Id/X-App-Id/x-ide-version-code` 等,来自运行日志实证)
208
+
209
+ ### 聊天通道(V1 直连 HTTP)
210
+ - `POST https://trae-api-cn.mchost.guru/api/ide/v1/chat` (SSE)
211
+ - body: `{user_input, session_id, chat_history[]}`(`model_name` 省略→服务端默认模型;传未知名会 4023)
212
+ - 事件流: `progress_notice → prompt → metadata → output{response,reasoning_content} → token_usage → done`
213
+ - **必须使用 legacy 设备头**(`X-App-Id` / `X-Device-*` / `x-ide-token`);
214
+ 改用「现代头」会得到 500 / 4001 / 2001。详见 handoff 2.4。
215
+ - 字段必须放在 body **顶层**;嵌进 `data{}` 会得到 `3003 all models failed`
216
+
217
+ ### 已观察到的独立边界(不是闭合的原生请求链)
218
+
219
+ ```
220
+ Python trae2api ── V1 HTTPS/SSE 请求 ──> trae-api-cn.mchost.guru
221
+
222
+ Trae renderer ── 本地 native RPC ──> ai_agent.dll / 会话处理
223
+ │
224
+ └── 该 turn 的远端请求/响应尚未与
225
+ Python V1 或某条静态 route 关联
226
+
227
+ cue-server 的日志含 @aha-kit/rpc / electron.ahaIpc 连接信息;这是本地进程
228
+ 间通道证据,不等于远端推理使用该 transport。
229
+ ```
230
+
231
+ ### 关键主机
232
+ | 用途 | 地址 |
233
+ |---|---|
234
+ | 认证 | `https://api.trae.cn` |
235
+ | 代理 V1 host(当前配置) | `https://trae-api-cn.mchost.guru` |
236
+ | 登录页 | `https://www.trae.cn` |
237
+ | 动态配置 | `https://api.trae.com.cn/icube/api/v1/native/config/query` |
238
+
239
+ ## 文件
240
+
241
+ - `trae2api/credential_decrypt.py` — storage.json 凭据解密(已验证)
242
+ - `trae2api/auth.py` — 凭据加载 + JWT 生命周期 + ECDSA DeviceProof 签名
243
+ - `trae2api/gateway.py` — 网关 SSE 客户端(设备头 + 流式)
244
+ - `trae2api/server.py` — FastAPI OpenAI 兼容层(SSE 解析 + 工具循环 + usage 透出)
245
+ - `trae2api/translate.py` — `<|FunctionCallBegin|>` 标记 ↔ OpenAI tool_calls
246
+ - `trae2api/events.py` — SSE 事件候选、当前解析逻辑与错误码语义;不代表所有上游事件已验证
247
+ - `trae2api/trae_schema.py` — 静态结构体字段摘录,不是完整 wire schema
248
+ - `trae2api/model_catalog.py` — 模型目录(state.vscdb 缓存 → 静态快照)
249
+ - `trae2api/verify_auth.py` — 只读认证验证脚本
250
+ - `notes/` — 逆向证据;先读当前 Python 复现计划与认证审查,再把旧 verdict/handoff 当历史记录阅读
251
+
252
+ ## 免责声明
253
+
254
+ 仅用于学习研究协议设计。请遵守 Trae 服务条款;账号与额度归属本人,勿滥用。
@@ -0,0 +1,15 @@
1
+ daily_checkin/__init__.py,sha256=PN3f3Fe1IPUjKgiWVsFAw9rTcgdFEUhsLmXc8ERUBTo,206
2
+ daily_checkin/__main__.py,sha256=AcGGzsV9jKfNPIYBXtQp3uNHN5W66vVkKVKClJXcGbc,140
3
+ daily_checkin/checkin.py,sha256=m7n7qzz0orZ3jUxK2DYNjhoduP3dk7ZzqjBUyw6d1pc,1178
4
+ daily_checkin/trae.py,sha256=Y28HFU_iVjjFpT-6f8unrBj7uPpNS2GcpMQYNPToVUI,11551
5
+ daily_checkin/trae_profile.py,sha256=c0wN6xFoYBb_kUikYoE12rgNwVEftp9QFa2VI7YJtjY,5089
6
+ daily_checkin/trae_scheduler.py,sha256=79m6P0QwsK6gggjHbI3M3rsME7zKhDGumzeqDKgch2c,9617
7
+ daily_checkin/workbuddy.py,sha256=mLK-wGcHoiUA5FgNxNQjVEhBhpZZALRreVi6p32ikn0,32807
8
+ daily_checkin/workbuddy_api.py,sha256=9J9ka8DGvwhLugb53L5bs_Ueac6yh--uhkeKXc54F2k,2852
9
+ daily_checkin/workbuddy_billing.py,sha256=EEhLZrQhF2-U3hXPrjYjrCtR6NDVl3Qjs3Wi60_7RUM,5128
10
+ daily_checkin/workbuddy_cli.py,sha256=3YPVGzywhVRN8o3qTO_nrStVuXqzhPDCNBautE3ejgc,3563
11
+ buddy_agent_checkin-0.1.1.dev2.dist-info/METADATA,sha256=tk9xYgN7TykeXfJcjaDustzZIQIAh41T0tiNF_rGnyg,17917
12
+ buddy_agent_checkin-0.1.1.dev2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
13
+ buddy_agent_checkin-0.1.1.dev2.dist-info/entry_points.txt,sha256=ux2WGp0KWT2ZsF4aPJ5fgKVWa-FbvbI8eiH2b8-VGKQ,61
14
+ buddy_agent_checkin-0.1.1.dev2.dist-info/top_level.txt,sha256=nwe-6zXS-X4MthcUh5O0kAfDY0kUk0F-gKjQtX7evDk,14
15
+ buddy_agent_checkin-0.1.1.dev2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ daily-checkin = daily_checkin.checkin:main
@@ -0,0 +1 @@
1
+ daily_checkin
@@ -0,0 +1,5 @@
1
+ """DailyCheckin: account-aware activity check-in for Trae CN."""
2
+ __version__ = "0.1.1.dev2"
3
+ from .trae import Account, CheckinError, checkin
4
+
5
+ __all__ = ["Account", "CheckinError", "checkin", "__version__"]
@@ -0,0 +1,5 @@
1
+ """Run DailyCheckin with ``python -m daily_checkin``."""
2
+ from .checkin import main
3
+
4
+ if __name__ == "__main__":
5
+ raise SystemExit(main())
@@ -0,0 +1,29 @@
1
+ """Public check-in API and command entry point."""
2
+ import sys
3
+ from .trae import Account, CheckinError, checkin, main as _trae_main
4
+
5
+ __all__ = ["Account", "CheckinError", "checkin", "main"]
6
+
7
+
8
+ def main(argv=None):
9
+ arguments = list(sys.argv[1:] if argv is None else argv)
10
+ if arguments and (arguments[0] == 'login' or arguments[:2] == ['trae', 'login']):
11
+ from pathlib import Path
12
+ from buddy_agent_auth.providers.trae import login
13
+ legacy = Path(__file__).resolve().parent.parent / 'trae2api' / 'trae2api.json'
14
+ if legacy.is_file():
15
+ login.configure_legacy_credentials(legacy)
16
+ return login.main(arguments[2:] if arguments[0] == 'trae' else arguments[1:])
17
+ if arguments[:2] == ['trae', 'schedule']:
18
+ from .trae_scheduler import main as schedule_main
19
+ return schedule_main(arguments[2:])
20
+ if arguments and arguments[0] == 'trae':
21
+ arguments = arguments[1:]
22
+ if arguments and arguments[0] == 'workbuddy':
23
+ from .workbuddy_cli import main as workbuddy_main
24
+ return workbuddy_main(arguments[1:])
25
+ return _trae_main(arguments)
26
+
27
+
28
+ if __name__ == "__main__":
29
+ raise SystemExit(main())
daily_checkin/trae.py ADDED
@@ -0,0 +1,230 @@
1
+ """Trae CN IDE check-in, based on the locally installed client's code.
2
+
3
+ Only sends requests when explicitly invoked. The supplied device ID is an
4
+ opaque client identifier, not a proven replacement for device registration.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass, field, replace
9
+ import json
10
+ from pathlib import Path
11
+ import time
12
+ from typing import Any, Callable
13
+
14
+ import httpx
15
+ from buddy_agent_auth.providers.trae.client_metadata import clean_model, client_version, device_model, os_metadata
16
+ from .trae_profile import CheckinProfile, validate_base_url
17
+ from buddy_agent_auth.providers.trae.credentials import load_file, reject_expired_token as _reject_expired_token
18
+ from buddy_agent_auth.providers.trae import DeviceIdSource, NativeIdentity, NativeIdentityError, TraeNativeProvider
19
+
20
+ # Keep the source checkout fallback used by existing account/device data.
21
+ from buddy_agent_auth.providers.trae import app_storage as _storage
22
+ _storage.configure_fallback(Path(__file__).resolve().parent.parent)
23
+
24
+ BASE_URL = "https://api.trae.cn"
25
+ STATUS_PATH = "/trae/api/v2/ug/checkin_credits/status"
26
+ CLAIM_PATH = "/trae/api/v2/ug/checkin_credits/claim"
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Account:
31
+ token: str = field(repr=False)
32
+ device_id: str = field(repr=False)
33
+ device_brand: str = ""
34
+ device_type: str = ""
35
+ os_version: str = ""
36
+ app_version: str = ""
37
+ editor_version: str = "1.107.1"
38
+ client_name: str = "Trae CN"
39
+ user_region: str = "CN"
40
+ base_url: str = BASE_URL
41
+ session_headers: tuple[tuple[str, str], ...] = field(default=(), repr=False)
42
+ native_identity: NativeIdentity | None = field(default=None, repr=False)
43
+ user_id: str = field(default="", repr=False)
44
+
45
+ @classmethod
46
+ def from_native(cls, *, device_id_source: DeviceIdSource = "get-device-id") -> "Account":
47
+ identity = TraeNativeProvider(device_id_source=device_id_source).load()
48
+ try:
49
+ _reject_expired_token(identity.token)
50
+ except ValueError:
51
+ raise NativeIdentityError("native login token expired; sign in to Trae CN again") from None
52
+ profile = CheckinProfile.load()
53
+ os_name, os_version = os_metadata()
54
+ return cls(token=identity.token, device_id=identity.device_id,
55
+ device_brand=device_model(), device_type=os_name, os_version=os_version,
56
+ app_version=client_version("3.4.20"), editor_version=profile.editor_version,
57
+ client_name=profile.client_name, user_region=identity.user_region,
58
+ base_url=profile.base_url, session_headers=profile.headers,
59
+ native_identity=identity, user_id=identity.user_id)
60
+
61
+ @classmethod
62
+ def from_file(cls, path: str | Path) -> "Account":
63
+ auth, device, token, device_id = load_file(path)
64
+ model = device_model() or device.get("deviceModel") or device.get("deviceBrand") or ""
65
+ # Older login code stored the user-chosen device name as its model.
66
+ if not model or model == device.get("deviceName"):
67
+ model = device_model()
68
+ os_name, os_version = os_metadata()
69
+ profile = CheckinProfile.load()
70
+ return cls(token=token, device_id=device_id, device_brand=clean_model(model),
71
+ device_type=os_name, os_version=os_version,
72
+ app_version=client_version(device.get("clientVersion") or "3.4.20"),
73
+ editor_version=profile.editor_version, client_name=profile.client_name,
74
+ user_region="CN", base_url=profile.base_url, session_headers=profile.headers,
75
+ user_id=str(auth.get("userId") or ""))
76
+
77
+ def headers(self) -> dict[str, str]:
78
+ result = {"Authorization": f"Cloud-IDE-JWT {self.token}",
79
+ "Content-Type": "application/json", "x-device-id": self.device_id,
80
+ "x-rust-request-timeout": "30000",
81
+ "User-Agent": f"VSCode {self.editor_version} ({self.client_name})",
82
+ "X-Market-Client-Id": f"VSCode {self.editor_version}",
83
+ "X-User-Region": self.user_region}
84
+ result.update(self.session_headers)
85
+ for key, value in (("x-device-brand", self.device_brand),
86
+ ("x-device-type", self.device_type),
87
+ ("x-os-version", self.os_version),
88
+ ("x-app-version", self.app_version)):
89
+ if value:
90
+ result[key] = value
91
+ return result
92
+
93
+
94
+ class CheckinError(Exception):
95
+ pass
96
+
97
+
98
+ def _post(client: httpx.Client, path: str, account: Account) -> dict[str, Any]:
99
+ try:
100
+ if account.native_identity is not None:
101
+ try:
102
+ account.native_identity.ensure_current()
103
+ except NativeIdentityError as exc:
104
+ raise CheckinError(str(exc)) from None
105
+ response = client.post(account.base_url + path, content=b'{"req_source":1}',
106
+ headers=account.headers(), follow_redirects=False)
107
+ if response.status_code != 200:
108
+ raise CheckinError(f"HTTP {response.status_code}; outcome may be unknown")
109
+ try:
110
+ body = response.json()
111
+ except ValueError as exc:
112
+ raise CheckinError("invalid JSON response; outcome may be unknown") from exc
113
+ except httpx.HTTPError as exc:
114
+ raise CheckinError(f"network error ({type(exc).__name__}); outcome may be unknown") from exc
115
+ if not isinstance(body, dict):
116
+ raise CheckinError("invalid response object; outcome may be unknown")
117
+ if "code" in body:
118
+ code = body["code"]
119
+ if type(code) not in (int, float) or code != 0:
120
+ message = next((body[k] for k in ("message", "msg", "error_message")
121
+ if isinstance(body.get(k), str) and body[k]), "")
122
+ # Do not dump the response body or echo a credential in diagnostics.
123
+ message = message.replace(account.token, "[redacted]")
124
+ detail = f"; message={message[:500]!r}" if message else ""
125
+ raise CheckinError(f"business or protocol error: code={code!r}{detail}")
126
+ return body
127
+
128
+
129
+ def _read_status(account: Account, client: httpx.Client) -> dict[str, Any]:
130
+ try:
131
+ status = _post(client, STATUS_PATH, account)
132
+ except CheckinError as exc:
133
+ raise CheckinError(f"status query failed: {exc}") from exc
134
+ enabled, checked = status.get("enable"), status.get("checked_in")
135
+ if type(enabled) is not bool or type(checked) is not bool:
136
+ raise CheckinError("status query failed: response missing boolean enable/checked_in")
137
+ result = {"enable": enabled, "checked_in": checked, "credits": status.get("credits")}
138
+ for key in ("did_checked_in", "extra_credits"):
139
+ if key in status:
140
+ result[key] = status[key]
141
+ if "did_checked_in" in result and type(result["did_checked_in"]) is not bool:
142
+ raise CheckinError("status query failed: did_checked_in must be boolean when present")
143
+ return result
144
+
145
+
146
+ def checkin(account: Account, client: httpx.Client, *, status_only: bool = False,
147
+ before_claim: Callable[[], bool] | None = None) -> dict[str, Any]:
148
+ """Query, claim once if eligible, then verify status without retrying claim."""
149
+ if account.native_identity is not None:
150
+ try:
151
+ account.native_identity.ensure_current()
152
+ except NativeIdentityError as exc:
153
+ raise CheckinError(str(exc)) from None
154
+ if account.native_identity is None or getattr(account.native_identity, "device_id_source", "get-device-id") != "existing":
155
+ from buddy_agent_auth.providers.trae.app_storage import resolve_pair
156
+ device_id, hardware = resolve_pair(account.user_id, account.device_id, client, account.app_version)
157
+ account = replace(account, device_id=device_id)
158
+ if hardware is not None:
159
+ account = replace(account, device_brand=clean_model(hardware.model),
160
+ device_type=hardware.os_name, os_version=hardware.os_version)
161
+ status = _read_status(account, client)
162
+ if status_only:
163
+ return {"action": "status", **status}
164
+ if status["checked_in"]:
165
+ return {"action": "already_checked_in", "credits": status.get("credits")}
166
+ if status.get("did_checked_in") is True:
167
+ return {"action": "device_already_checked_in", "credits": status.get("credits"),
168
+ "status": status}
169
+ if not status["enable"]:
170
+ return {"action": "disabled", "credits": status.get("credits")}
171
+ if before_claim is not None and not before_claim():
172
+ return {"action": "cancelled"}
173
+ try:
174
+ _post(client, CLAIM_PATH, account)
175
+ except CheckinError as exc:
176
+ raise CheckinError(f"claim failed: {exc}") from exc
177
+ result = {"action": "claim_accepted", "credits": status.get("credits"), "verified": False}
178
+ try:
179
+ after = _read_status(account, client)
180
+ except CheckinError as exc:
181
+ # A failed confirmation must not cause a second claim.
182
+ result["verification_error"] = str(exc)
183
+ return result
184
+ result["status"] = after
185
+ if after["checked_in"]:
186
+ result.update(action="checked_in", verified=True)
187
+ return result
188
+
189
+
190
+ def main(argv: list[str] | None = None) -> int:
191
+ import argparse
192
+
193
+ parser = argparse.ArgumentParser(description="Trae CN IDE check-in")
194
+ source = parser.add_mutually_exclusive_group(required=True)
195
+ source.add_argument("--creds", help="explicit independent credentials JSON file")
196
+ source.add_argument("--native", action="store_true", help="read the account and token from the native client")
197
+ parser.add_argument("--device-id-source", choices=["existing", "get-device-id"],
198
+ help="--native only: get-device-id (default) uses the account-bound device; "
199
+ "existing uses the native session device")
200
+ parser.add_argument("--base-url", help="override the installed ug API HTTPS origin")
201
+ parser.add_argument("--user-region", help="override the CN store region header with an observed native value")
202
+ mode = parser.add_mutually_exclusive_group()
203
+ mode.add_argument("--execute", action="store_true", help="send status and, if eligible, claim")
204
+ mode.add_argument("--status-only", action="store_true", help="query status without claiming credits")
205
+ args = parser.parse_args(argv)
206
+ if args.device_id_source is not None and not args.native:
207
+ parser.error("--device-id-source requires --native")
208
+ if not args.execute and not args.status_only:
209
+ print("Dry run: no credentials read and no requests sent. Add --execute or --status-only to run.")
210
+ return 0
211
+ try:
212
+ from buddy_agent_auth.providers.trae.app_storage import root
213
+ root()
214
+ account = (Account.from_native(device_id_source=args.device_id_source or "get-device-id")
215
+ if args.native else Account.from_file(args.creds))
216
+ if args.base_url:
217
+ account = replace(account, base_url=validate_base_url(args.base_url))
218
+ if args.user_region is not None:
219
+ account = replace(account, user_region=args.user_region)
220
+ with httpx.Client(timeout=30, trust_env=False) as client:
221
+ result = checkin(account, client, status_only=args.status_only)
222
+ print(json.dumps(result, ensure_ascii=False))
223
+ return 0
224
+ except (CheckinError, OSError, ValueError, TypeError, KeyError) as exc:
225
+ print(f"Check-in failed: {exc}")
226
+ return 1
227
+
228
+
229
+ if __name__ == "__main__":
230
+ raise SystemExit(main())