dsh-wtq-pool 1.3.0 → 1.3.1
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.
- package/CHANGELOG.md +13 -0
- package/README.en.md +6 -6
- package/README.md +6 -6
- package/lib/client.js +7 -5
- package/lib/index.d.ts +1 -1
- package/lib/index.js +294 -131
- package/package.json +3 -1
- package/renderer/panel.js +4 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# 更新说明
|
|
2
2
|
|
|
3
|
+
## [1.3.1]
|
|
4
|
+
|
|
5
|
+
- 账号池:两个区域共用一个账号池时,轮流使用与同一对话固定账号的轮转位置按区域分开;跳过刷新失败的登录后仍会轮到每个账号,两个区域也不会重复落在同一个账号上。
|
|
6
|
+
- 输入框积分:已有会话中点击读数可以正常打开换号弹窗,滚动或缩放窗口时不再报错。
|
|
7
|
+
- 积分读数:额度耗尽的账号在冷却期间仍会读取余额,充值后下一次读取即可解除挂起,面板的刷新判断不再把它当作无需更新。
|
|
8
|
+
- 积分读数:手动刷新后按最新结果重新计时,未读到的余额不会等满五分钟;请求未返回时切换模型或提供商,弹窗不再停留在切换中。
|
|
9
|
+
- 换号:登录失效返回 200 且刷新令牌成功、会话仍然失效时,该账号挂起并改用下一个,不再反复刷新同一账号。
|
|
10
|
+
- 模型:Trae、Qoder 保存的默认思考等级会写入声明,选中该模型时按设置的等级发送,不再回落到目录默认值。
|
|
11
|
+
- 换号:上游主机不可达时,尚未失败的网关仍有尝试机会,不再因同域名的连续超时错过健康账号。
|
|
12
|
+
- 账号池:同一对话固定账号命中时刷新使用顺序,长时间对话不会因绑定上限被换到新账号;不同区域的同名对话不再共用绑定。
|
|
13
|
+
- 设置:写入与当前值相同时不再影响对宿主修改的判断,插件保存后宿主刚做的修改不再丢失。
|
|
14
|
+
- 面板:登录链接缺失时按界面语言提示,不再显示英文原文。
|
|
15
|
+
|
|
3
16
|
## [1.3.0]
|
|
4
17
|
|
|
5
18
|
- 账号池:升级前的停用、移除、保底与偏好设置按旧账号 ID 继续生效。
|
package/README.en.md
CHANGED
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
|
|
38
38
|
WorkBuddy fails over when an account is rate-limited, out of quota or answered with an upstream 5xx. Trae and Qoder select an account per request and move on to the next sign-in on an authentication failure, a rate limit or exhausted quota, while a problem with the request itself, such as an unknown model or a malformed body, is answered locally with 404 or 400. Each source has its own switch, with domestic and international accounts grouped separately.
|
|
39
39
|
|
|
40
|
-
A rate limit cools for the wait the upstream stated, or the configured window when it stated none. Exhausted quota and a dead sign-in do not recover on their own: that account leaves rotation. A balance read releases an exhausted-quota hold; a successful token refresh, a fresh sign-in or a manual cooldown reset releases a refused-sign-in hold
|
|
40
|
+
A rate limit cools for the wait the upstream stated, or the configured window when it stated none. An upstream 5xx moves the turn on to the next sign-in. Exhausted quota and a dead sign-in do not recover on their own: that account leaves rotation. A balance read that finds credits releases an exhausted-quota hold; a successful token refresh, a fresh sign-in or a manual cooldown reset releases a refused-sign-in hold. Both lapse at six hours at the latest (WorkBuddy). The non-stream requests for credits, check-in state, the model catalogue and check-ins force one token refresh and one retry when a sign-in is refused: an account whose refresh token still works recovers on the spot and never leaves rotation, and only one whose refresh token is spent too is held. Trae and Qoder holds are accounted separately, demoting the sign-in only by the cooldown window (60 seconds by default, configurable up to 24 hours) or by the wait the upstream stated, and it is still used when it is the only one left. When the upstream host cannot be reached, that account is skipped for the request and the next one is tried; after two accounts fail that way the turn keeps going while a sign-in belongs to a gateway that has not failed yet, and ends with a network error only once every gateway has. When the upstream says an account's plan does not include a model (11158), that model is disabled on that account for 24 hours while its other models keep serving; if no account includes it, the turn is answered with 400. A Trae sign-in expiry can arrive as one sentence with no error code; a frame matching the known wording is read as an expired sign-in and rotated past, and any other wording is answered as upstream failure with 502.
|
|
41
41
|
|
|
42
42
|
## Preview
|
|
43
43
|
|
|
@@ -71,9 +71,9 @@ To run the preview locally, clone the repository, run `node docs/serve.cjs`, and
|
|
|
71
71
|
- Register model groups by region: each region of each vendor becomes its own provider, and several can be on at once; a region with no account is not registered. A domestic model runs only on domestic accounts, and an international model only on international ones.
|
|
72
72
|
- Account distribution: WorkBuddy supports priority, round-robin, expiring credits first and conversation-sticky accounts, and fails over on a rate limit, exhausted quota or upstream 5xx. Trae and Qoder support priority, round-robin and expiring credits first, and move on to the next sign-in on an authentication failure, a rate limit or exhausted quota.
|
|
73
73
|
- Gateway responses are SSE streams of `chat.completion.chunk`; the `stream` field in the request body does not change the format.
|
|
74
|
-
- Credit automation: automatic check-in is off by default. When enabled, scheduled runs perform check-ins
|
|
74
|
+
- Credit automation: automatic check-in is off by default. When enabled, scheduled runs and "Run now" perform the same pass: check-ins for all three sources, WorkBuddy streak claims and cat travel. Streak days advance through upstream conversations, so each pass posts one activity report per account before reading its tiers; a tier becomes claimable the moment it unlocks. The pass also claims the one-time newbie gift and campaign compensation, spends a make-up card only when yesterday is missing, and uses the lottery draws an unlocked tier grants. These growth steps run on both domestic and international accounts; cat travel is domestic only.
|
|
75
75
|
- Token keep-alive: on demand, on a card of its own. A snapshot the desktop client left behind is adopted into the plugin's own sign-in directory when the pool scans, and the plugin renews it from then on; the desktop app renews the sign-in it is using. "Refresh now" works on the plugin's own copies and judges by issue time: anything signed more than six hours ago is refreshed, and a token within five minutes of expiry takes the same path. The answer is written back into the sign-in file the plugin owns, so a sign-in the upstream refused is found the same day. When one account has sign-ins in several places, the newest issue time wins. Disabled accounts, disabled regions and accounts whose sign-in the upstream refused stay out.
|
|
76
|
-
- Composer credits: with `showComposerPoints` on, the composer toolbar shows the balance of the account behind the current model; click it to switch accounts. In round-robin and conversation-sticky modes
|
|
76
|
+
- Composer credits: with `showComposerPoints` on, the composer toolbar shows the balance of the account behind the current model; click it to switch accounts. The two WorkBuddy regions are listed as two providers, `WTQ Pool (CN)` and `WTQ Pool (Global)`; each publishes the catalogue its own gateway serves, and the readout resolves the selected provider and follows this plugin's models only. In round-robin and conversation-sticky modes the readout names the account that serves next or served last. Switching the feature off hides the readout and slows the poll to once every five minutes, so switching it back on recovers without a model change.
|
|
77
77
|
- Panel: account and pool state, model selection, the connection check and the growth centre all live in the account-pool card on the plugin page. The model catalogue loads at startup and refreshes on demand once its cache expires; it does not poll while idle. Disabled accounts and accounts whose sign-in the upstream refused are never probed.
|
|
78
78
|
- Connection check: every finding carries a verdict. A gateway that is not listening, a catalogue that could not be read, a published address that differs from the one actually bound, and a provider the host did not accept all count as failures and say what to change. A gateway whose start failed is reported with the reason, and the panel surfaces address drift as a reload hint. A check that fails on its own becomes a finding, and the rest of the report still appears.
|
|
79
79
|
|
|
@@ -142,7 +142,7 @@ Every key below is editable in the plugin page or the DSH settings page and save
|
|
|
142
142
|
| `sourceWorkbuddy` / `sourceTrae` / `sourceQoder` | `true` | Off: that source is not scanned, published or requested |
|
|
143
143
|
| `distribution` | `priority` | How the WorkBuddy pool spreads requests: `priority` uses one account first, `round-robin` spreads evenly, `expiry` spends expiring credits first, `sticky` pins one account per conversation |
|
|
144
144
|
| `sourceDistributions` | `{}` | Trae/Qoder distribution: `priority` / `round-robin` / `expiry`; unset behaves as `priority` |
|
|
145
|
-
| `cooldownSeconds` | `60` | Rate-limit cooldown. A reset time the upstream reports takes precedence; with none, consecutive limits double it up to 15 minutes (a longer configured window is left alone). A reported reset is capped at two hours; a spent balance or a refused sign-in is held for six hours instead |
|
|
145
|
+
| `cooldownSeconds` | `60` | Rate-limit cooldown. A reset time the upstream reports takes precedence; with none, consecutive limits double it up to 15 minutes (a longer configured window is left alone). A reported reset is capped at two hours; a spent balance or a refused sign-in is held for up to six hours instead, and a balance read that finds credits releases a spent hold sooner |
|
|
146
146
|
| `creditReserves` | `{}` | Per-account credit floor, keyed by account id; an account at or below its floor is not distributed to |
|
|
147
147
|
| `authFile` | `""` | WorkBuddy sign-in file path; every `.info` sign-in in its directory is scanned. Empty discovers it |
|
|
148
148
|
| `autoCheckin` | `{"enabled":false,"hours":[9]}` | Automatic check-in switch and times; `hours` are Beijing-time hours, empty means 09:00 |
|
|
@@ -176,7 +176,7 @@ The PI-Desktop edition uses a separate port range starting at 41831. Both editio
|
|
|
176
176
|
|
|
177
177
|
The plugin reads the vendors' local sign-in files. Providers are registered at runtime; the host persists plugin settings in the profile. Tokens are held by the plugin and go only to the relevant vendor endpoints. Gateways listen on `127.0.0.1`, so other local processes can call them and spend account quota. The panel accepts loopback requests only. The plugin is designed for a single-user desktop and does not separate other OS users on the same machine; use separate OS accounts on a shared machine.
|
|
178
178
|
|
|
179
|
-
The plugin's own data directory, `~/.dsh/dsh-wtq-pool/` (or `$DSH_HOME/dsh-wtq-pool/` when set), holds four data files. An interrupted archive, delete-record or sign-in write can leave temporary files behind: writing the same file again clears leftovers older than ten minutes, and a scan does the same for sign-in temps in the plugin's own directory; deleting an account removes its sign-in temps with it. `checkin-slots.json` records the check-in slots already collected and the pending Qoder retry time; slots are kept for three days. `doctor.txt` is the most recent connection report, item by item, and lists no account label. `credentials-archive.json` keeps the sign-ins a later account switch overwrote: access and refresh tokens, account identifiers (nickname, uin/uid, enterprise id) and the local sign-in path. Entries are kept by token expiry, dropping each 30 days after it; an entry with no stated expiry is kept until the account is deleted. `deleted-signins.json` records deleted sign-ins as a token digest, the sign-in's issue time, a delete time and a random record id, so a scan cannot take the same superseded snapshot back over from the desktop app; a scan clears the entry after the account signs in again with a different token and a newer issue time; deletes for one account that cannot be ordered by issue time are kept together, so a stale one cannot replace a newer one; a record written by 1.2.3 matches only by token digest and is not cleared automatically. These files carry no additional encryption; access is bounded by the operating system's file ACLs.
|
|
179
|
+
The plugin's own data directory, `~/.dsh/dsh-wtq-pool/` (or `$DSH_HOME/dsh-wtq-pool/` when set), holds four data files. Writing an archive or delete record briefly creates the matching `.lock` file. An interrupted archive, delete-record or sign-in write can leave temporary files behind: writing the same file again clears leftovers older than ten minutes, and a scan does the same for sign-in temps in the plugin's own directory; deleting an account removes its sign-in temps with it. `checkin-slots.json` records the check-in slots already collected and the pending Qoder retry time; slots are kept for three days. `doctor.txt` is the most recent connection report, item by item, and lists no account label. `credentials-archive.json` keeps the sign-ins a later account switch overwrote: access and refresh tokens, account identifiers (nickname, uin/uid, enterprise id) and the local sign-in path. Entries are kept by token expiry, dropping each 30 days after it; an entry with no stated expiry is kept until the account is deleted. `deleted-signins.json` records deleted sign-ins as a token digest, the sign-in's issue time, a delete time and a random record id, so a scan cannot take the same superseded snapshot back over from the desktop app; a scan clears the entry after the account signs in again with a different token and a newer issue time; deletes for one account that cannot be ordered by issue time are kept together, so a stale one cannot replace a newer one; a record written by 1.2.3 matches only by token digest and is not cleared automatically. These files carry no additional encryption; access is bounded by the operating system's file ACLs. On Windows the directory inherits its parent's permissions, so keep it somewhere only the current user can write.
|
|
180
180
|
|
|
181
181
|
Every sign-in the plugin writes lives in `signins/` beside it: ones added from the panel, snapshots adopted from the desktop app, and renewed copies. Each file is named after the account's billing identity and read on the same terms as a desktop sign-in. These files are not additionally encrypted either; access is bounded by the operating system's file ACLs. "Delete" in the panel removes that file together with its archive entry, and the snapshot the desktop app left behind stops being adopted; signing the account in again brings it back. "Remove" only disables the account, and "Removed accounts" restores it.
|
|
182
182
|
|
|
@@ -193,7 +193,7 @@ Tokens go only to the hosts below:
|
|
|
193
193
|
```sh
|
|
194
194
|
pnpm install
|
|
195
195
|
pnpm run build # emits lib/ (host half as ESM, client half as CJS)
|
|
196
|
-
pnpm run typecheck # host
|
|
196
|
+
pnpm run typecheck # entry, panel and client (src/host.ts is excluded)
|
|
197
197
|
pnpm run typecheck:client
|
|
198
198
|
pnpm test # Node's own test runner, offline regressions
|
|
199
199
|
```
|
package/README.md
CHANGED
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
|
|
40
40
|
Trae 的登录失效有时不带错误码、只给一句说明。插件按已知的英文措辞识别这种帧并换号;其余措辞按上游故障返回 502。
|
|
41
41
|
|
|
42
|
-
限流按上游给出的等待时间冷却,上游未给出时按配置的窗口。上游 5xx
|
|
42
|
+
限流按上游给出的等待时间冷却,上游未给出时按配置的窗口。上游 5xx 改用下一个登录。额度用尽与登录失效不会自行恢复,账号退出轮换:额度用尽的挂起在重新读到有余额后释放,登录失效的挂起在刷新成功、重新登录或手动重置冷却后释放,两者都以六小时为上限(WorkBuddy 侧)。积分、签到状态、模型目录与手动签到这些非流式请求遇到登录失效,会先强制刷新令牌并重试一次:刷新令牌还有效的账号当场恢复,不退出轮换;刷新令牌同样失效的才挂起。Trae、Qoder 的失败挂起另计:只按冷却窗口(默认 60 秒,最长可配到 24 小时)或上游给出的等待时间降权,池中只剩它一个时仍会使用。上游主机不可达时跳过该账号并尝试下一个;连续两个账号都不可达后,只要还有登录属于尚未失败的网关就继续尝试,所有网关都失败才结束本轮并报告网络错误。上游判定账号套餐不含某模型(11158)时,该账号的这个模型停用 24 小时,其他模型照常服务;全部账号都不含该模型时按 400 返回。
|
|
43
43
|
|
|
44
44
|
## 预览
|
|
45
45
|
|
|
@@ -75,8 +75,8 @@ Trae 的登录失效有时不带错误码、只给一句说明。插件按已知
|
|
|
75
75
|
- 网关以 SSE 返回 `chat.completion.chunk`;请求体里的 `stream` 字段不改变响应格式。
|
|
76
76
|
- 积分自动化:自动签到默认关闭。开启后的定时任务与「立即运行」执行同一轮,包含三家签到、WorkBuddy 的连登奖励和猫猫旅行。连登天数由上游按对话推进,该轮在每个账号读取连登档位前先补发一次对话活动上报,因此档位到点即可解锁领取。连登环节还会在昨日漏签且持有补签卡时自动补签以保住连续天数,领取一次性的新手礼包与活动补偿,并在兑换解锁的档位后把由此获得的抽奖次数抽完。这些成长步骤国内版与国际版都执行;猫猫旅行仅用于国内账号。
|
|
77
77
|
- 登录令牌保活:独立卡片,按需执行。桌面端留下的登录快照在扫描时并入插件自己的登录目录,由插件接管续期;桌面端正在使用的登录由桌面端续期。「立即刷新」处理插件自管的副本,按签发时间判断:签发满 6 小时的刷新,距到期不足 5 分钟的同样刷新。刷新结果写回插件自己的登录文件,登录被上游拒绝时当天即可发现。同一账号在多处留有登录时按签发时间取最新的一份。停用账号、已停用的 region 与登录已被上游拒绝的账号不参与。
|
|
78
|
-
- 输入框积分:开启 `showComposerPoints`
|
|
79
|
-
-
|
|
78
|
+
- 输入框积分:开启 `showComposerPoints` 后,输入框工具栏显示当前模型所用账号的余额,点开可换号。国内版与国际版各自发布所在网关的模型目录,分别列为 `WTQ Pool (CN)` 与 `WTQ Pool (Global)` 两个提供商;积分浮层按当前选中的提供商确认归属,只跟随本插件的模型。轮流使用与同一对话固定账号时,浮层显示下一个或最近一次服务该模型的账号。功能关闭后浮层隐藏,读数降为每 5 分钟一次,重新开启后无需切换模型即可恢复。
|
|
79
|
+
- 面板:账号与池状态、模型勾选、连接检查、成长中心都在插件页的「账号池(dsh-wtq-pool)」卡片内。模型目录在启动时加载,缓存过期后按需刷新,空闲时不轮询。停用的账号与登录已被上游拒绝的账号不参与探测。
|
|
80
80
|
- 连接检查:每条发现都带判定。网关没有监听、模型目录读取失败、发布的地址与实际绑定的不一致、provider 未被宿主接受,都算失败并给出需要修改的内容。网关启动失败时给出原因,面板按地址漂移提示重新加载插件。检查自身出错也记一条发现,报告照常给出其余结果。
|
|
81
81
|
|
|
82
82
|
## 安装
|
|
@@ -144,7 +144,7 @@ WorkBuddy 国内版上游会检查 system 与助手轮次里的措辞,命中
|
|
|
144
144
|
| `sourceWorkbuddy` / `sourceTrae` / `sourceQoder` | `true` | 关闭后该来源不扫描、不发布、不请求 |
|
|
145
145
|
| `distribution` | `priority` | WorkBuddy 池的发放方式:`priority` 先用一个账号,`round-robin` 均摊,`expiry` 优先消耗临期积分,`sticky` 同一对话固定 |
|
|
146
146
|
| `sourceDistributions` | `{}` | Trae、Qoder 的分发方式:`priority` / `round-robin` / `expiry`;未设时按 `priority` |
|
|
147
|
-
| `cooldownSeconds` | `60` | 限流冷却时长。上游报出重置时间时以它为准;没有重置时间时,连续限流会让它逐次翻倍,封顶 15 分钟(窗口本身超过 15 分钟时不再翻倍)。上游给出的重置时间最长按 2 小时计;余额耗尽或登录被上游拒绝另按 6
|
|
147
|
+
| `cooldownSeconds` | `60` | 限流冷却时长。上游报出重置时间时以它为准;没有重置时间时,连续限流会让它逐次翻倍,封顶 15 分钟(窗口本身超过 15 分钟时不再翻倍)。上游给出的重置时间最长按 2 小时计;余额耗尽或登录被上游拒绝另按 6 小时停用,额度耗尽的挂起在读到有余额时提前解除 |
|
|
148
148
|
| `creditReserves` | `{}` | 按账号 id 设定的积分保底,余额不高于它的账号不参与分发 |
|
|
149
149
|
| `authFile` | `""` | WorkBuddy 登录文件路径;扫描其所在目录的全部 `.info` 登录,留空则自动发现 |
|
|
150
150
|
| `autoCheckin` | `{"enabled":false,"hours":[9]}` | 自动签到的开关与时点;`hours` 为北京时间整点,留空用 09:00 |
|
|
@@ -178,7 +178,7 @@ PI-Desktop 版使用 41831 开头的独立端口,两版可以同时安装,
|
|
|
178
178
|
|
|
179
179
|
读取三家 App 的本机登录文件。provider 通过运行时注册接入,插件设置由宿主持久化至 profile。令牌由插件保管,只发往对应厂商的接口。网关监听 `127.0.0.1`,同机其他进程可调用并消耗账号额度;面板只接受本机回环请求。插件按单用户桌面环境设计,不区分本机其他系统用户;多人共用的机器应使用独立系统账户隔离。
|
|
180
180
|
|
|
181
|
-
插件自管数据目录 `~/.dsh/dsh-wtq-pool/`(设置了 `DSH_HOME` 时为 `$DSH_HOME/dsh-wtq-pool/`)包含四个文件(写归档或删除记录时会短暂出现对应的 `.lock` 文件;写入归档、删除记录或登录文件中断时可能留下临时文件:再次写入同一文件时会清理超过十分钟的残留,登录临时文件由扫描按同一时限清理;删除账号会连同该账号的临时文件一并清除)。`checkin-slots.json` 记录已领取的签到时段和待重试的 Qoder 时点,时段只保留三天。`doctor.txt` 是最近一次连接检查的报告,逐项记录通过与否,不列账号标签。`credentials-archive.json` 留存被切号覆盖的登录,含访问令牌、刷新令牌、账号标识(昵称、uin/uid、企业 ID)与本机登录文件路径;按令牌到期时间保留,到期后再过 30 天清除,没有到期时间的记录保留到该账号被删除。`deleted-signins.json` 记录已删除的登录,只存令牌摘要、该登录的签发时间、删除时间与一个随机记录标识,用来阻止扫描把桌面端遗留的同一份快照重新接管回来;桌面端重新登录该账号后(令牌不同且签发时间更新),下一次扫描会清除该记录;同一账号的多条删除记录若无法按签发时间排序,会一并保留,避免较早的删除覆盖较新的记录;1.2.3 写入的旧记录只按令牌摘要匹配,不会自动清除。上述文件未额外加密,访问权限由操作系统文件 ACL
|
|
181
|
+
插件自管数据目录 `~/.dsh/dsh-wtq-pool/`(设置了 `DSH_HOME` 时为 `$DSH_HOME/dsh-wtq-pool/`)包含四个文件(写归档或删除记录时会短暂出现对应的 `.lock` 文件;写入归档、删除记录或登录文件中断时可能留下临时文件:再次写入同一文件时会清理超过十分钟的残留,登录临时文件由扫描按同一时限清理;删除账号会连同该账号的临时文件一并清除)。`checkin-slots.json` 记录已领取的签到时段和待重试的 Qoder 时点,时段只保留三天。`doctor.txt` 是最近一次连接检查的报告,逐项记录通过与否,不列账号标签。`credentials-archive.json` 留存被切号覆盖的登录,含访问令牌、刷新令牌、账号标识(昵称、uin/uid、企业 ID)与本机登录文件路径;按令牌到期时间保留,到期后再过 30 天清除,没有到期时间的记录保留到该账号被删除。`deleted-signins.json` 记录已删除的登录,只存令牌摘要、该登录的签发时间、删除时间与一个随机记录标识,用来阻止扫描把桌面端遗留的同一份快照重新接管回来;桌面端重新登录该账号后(令牌不同且签发时间更新),下一次扫描会清除该记录;同一账号的多条删除记录若无法按签发时间排序,会一并保留,避免较早的删除覆盖较新的记录;1.2.3 写入的旧记录只按令牌摘要匹配,不会自动清除。上述文件未额外加密,访问权限由操作系统文件 ACL 决定;在 Windows 上数据目录会继承父目录的权限,请把它放在仅当前用户可写的位置。
|
|
182
182
|
|
|
183
183
|
插件写入的登录都在同目录的 `signins/`:面板添加的、接管桌面端快照的、续期后的副本。文件名带账号的计费身份,与桌面登录同等参与分发。这些文件同样未额外加密,访问权限由操作系统文件 ACL 决定。在面板中「删除」该账号会连同 `credentials-archive.json` 里的留档一起清除,桌面端遗留的同一份快照随之失效;重新登录该账号即解除。「移除」只是停用,可在「已移除的账号」中恢复。
|
|
184
184
|
|
|
@@ -195,7 +195,7 @@ PI-Desktop 版使用 41831 开头的独立端口,两版可以同时安装,
|
|
|
195
195
|
```sh
|
|
196
196
|
pnpm install
|
|
197
197
|
pnpm run build # 产出 lib/(宿主半为 ESM,客户端半为 CJS)
|
|
198
|
-
pnpm run typecheck #
|
|
198
|
+
pnpm run typecheck # 入口、面板与客户端(src/host.ts 不在检查范围内)
|
|
199
199
|
pnpm run typecheck:client
|
|
200
200
|
pnpm test # Node 自带测试,离线回归
|
|
201
201
|
```
|
package/lib/client.js
CHANGED
|
@@ -28,6 +28,7 @@ window.__ModuleLoader__.load({
|
|
|
28
28
|
//#endregion
|
|
29
29
|
let react = require("react");
|
|
30
30
|
react = __toESM(react, 1);
|
|
31
|
+
let react_dom = require("react-dom");
|
|
31
32
|
//#region src/panel-route.ts
|
|
32
33
|
/**
|
|
33
34
|
* The panel's route prefix.
|
|
@@ -250,7 +251,7 @@ window.__ModuleLoader__.load({
|
|
|
250
251
|
.xd-points-btn{border:0;background:transparent;color:inherit;font:inherit;font-size:12px;line-height:1;display:inline-flex;align-items:center;gap:5px;padding:4px 7px;border-radius:999px;cursor:pointer;max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
251
252
|
.xd-points-btn:hover{background:var(--dsw-alias-bg-layer-3,rgba(127,127,127,.12))}
|
|
252
253
|
.xd-points-mark{display:inline-block;width:6px;height:6px;flex:0 0 auto;border-radius:50%;background:var(--dsw-alias-state-success-primary,#4f9f7c)}
|
|
253
|
-
.xd-points-panel{position:fixed;z-index:
|
|
254
|
+
.xd-points-panel{position:fixed;z-index:1100;box-sizing:border-box;width:max-content;max-width:${PANEL_MAX_WIDTH}px;max-height:${PANEL_MAX_HEIGHT}px;overflow:auto;padding:8px;border-radius:12px;background:var(--dsw-alias-bg-layer-2,#1c1d21);color:var(--dsw-alias-label-primary,#e8e8ea);box-shadow:0 8px 28px rgba(0,0,0,.28);border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.25))}
|
|
254
255
|
.xd-points-table{width:100%;border-collapse:collapse;font-size:11px;line-height:1.4}
|
|
255
256
|
.xd-points-table th{text-align:left;font-weight:600;padding:4px 6px;color:var(--dsw-alias-label-tertiary,#8b8d93)}
|
|
256
257
|
.xd-points-table td{padding:4px 6px;vertical-align:top}
|
|
@@ -378,7 +379,7 @@ window.__ModuleLoader__.load({
|
|
|
378
379
|
if (!open) return void 0;
|
|
379
380
|
const onPointer = (event) => {
|
|
380
381
|
const target = event.target;
|
|
381
|
-
if (target
|
|
382
|
+
if (!(target instanceof Node)) return;
|
|
382
383
|
if (rootRef.current?.contains(target) === true) return;
|
|
383
384
|
if (panelRef.current?.contains(target) === true) return;
|
|
384
385
|
setOpen(false);
|
|
@@ -388,7 +389,7 @@ window.__ModuleLoader__.load({
|
|
|
388
389
|
};
|
|
389
390
|
const onViewport = (event) => {
|
|
390
391
|
const target = event.target;
|
|
391
|
-
if (target
|
|
392
|
+
if (target instanceof Node && panelRef.current?.contains(target) === true) return;
|
|
392
393
|
setOpen(false);
|
|
393
394
|
};
|
|
394
395
|
document.addEventListener("pointerdown", onPointer, true);
|
|
@@ -469,6 +470,7 @@ window.__ModuleLoader__.load({
|
|
|
469
470
|
if (routeRef.current !== requestedRoute) return;
|
|
470
471
|
setRefreshing(false);
|
|
471
472
|
if (next.show === true) setPoints(next);
|
|
473
|
+
restartPollRef.current();
|
|
472
474
|
}).catch((failure) => {
|
|
473
475
|
if (routeRef.current !== requestedRoute) return;
|
|
474
476
|
setRefreshing(false);
|
|
@@ -489,7 +491,7 @@ window.__ModuleLoader__.load({
|
|
|
489
491
|
}, react.createElement("span", {
|
|
490
492
|
className: "xd-points-mark",
|
|
491
493
|
"aria-hidden": "true"
|
|
492
|
-
}), balance === void 0 ? "—" : formatCredits(balance)), open && rect !== null ? react.createElement("div", {
|
|
494
|
+
}), balance === void 0 ? "—" : formatCredits(balance)), open && rect !== null && typeof document !== "undefined" ? (0, react_dom.createPortal)(react.createElement("div", {
|
|
493
495
|
className: "xd-points-panel",
|
|
494
496
|
ref: panelRef,
|
|
495
497
|
role: "dialog",
|
|
@@ -512,7 +514,7 @@ window.__ModuleLoader__.load({
|
|
|
512
514
|
title: account.label ?? "",
|
|
513
515
|
disabled: account.active === true || busy,
|
|
514
516
|
onClick: () => pick(account)
|
|
515
|
-
}, account.label ?? "—")), react.createElement("td", null, typeof account.total === "number" ? formatCredits(account.total) : account.plan ?? "—", points.source === "qoder" && Array.isArray(account.packages) ? react.createElement("ul", { className: "xd-points-packs" }, account.packages.map((pack, index) => react.createElement("li", { key: index }, packageText(pack, t)))) : null)))))) : null);
|
|
517
|
+
}, account.label ?? "—")), react.createElement("td", null, typeof account.total === "number" ? formatCredits(account.total) : account.plan ?? "—", points.source === "qoder" && Array.isArray(account.packages) ? react.createElement("ul", { className: "xd-points-packs" }, account.packages.map((pack, index) => react.createElement("li", { key: index }, packageText(pack, t)))) : null)))))), document.body) : null);
|
|
516
518
|
}
|
|
517
519
|
//#endregion
|
|
518
520
|
//#region src/ids.ts
|
package/lib/index.d.ts
CHANGED
|
@@ -69,7 +69,7 @@ interface Config {
|
|
|
69
69
|
preferredAccountIds?: Record<string, string>;
|
|
70
70
|
/** Picked Trae/Qoder account per region. */
|
|
71
71
|
preferredSourceAccounts?: Record<string, string>;
|
|
72
|
-
/** Accounts removed from the pool
|
|
72
|
+
/** Accounts removed from the pool, with their label and region kept so the panel can restore them. */
|
|
73
73
|
removedAccounts?: unknown[];
|
|
74
74
|
/** Whether the credits readout is shown beside the composer. */
|
|
75
75
|
showComposerPoints?: boolean;
|
package/lib/index.js
CHANGED
|
@@ -1666,6 +1666,17 @@ function globalBase(credential) {
|
|
|
1666
1666
|
function chatBase(credential) {
|
|
1667
1667
|
return regionOf(credential.domain) === "global" ? globalBase(credential) : CN_CHAT_BASE;
|
|
1668
1668
|
}
|
|
1669
|
+
/**
|
|
1670
|
+
* The host a sign-in's chat traffic actually reaches.
|
|
1671
|
+
*
|
|
1672
|
+
* The sign-in domain is not the chat host: every CN spelling (including an
|
|
1673
|
+
* empty one) is served by one gateway, and the two international brand domains
|
|
1674
|
+
* have gateways of their own. Failover keys transport failures on this value so
|
|
1675
|
+
* that one unreachable gateway condemns exactly the accounts it serves.
|
|
1676
|
+
*/
|
|
1677
|
+
function chatHostOf(credential) {
|
|
1678
|
+
return new URL(chatBase(credential)).host;
|
|
1679
|
+
}
|
|
1669
1680
|
function billingBase(credential) {
|
|
1670
1681
|
return regionOf(credential.domain) === "global" ? globalBase(credential) : CN_BILLING_BASE;
|
|
1671
1682
|
}
|
|
@@ -3607,10 +3618,10 @@ function processIsAlive(pid) {
|
|
|
3607
3618
|
return;
|
|
3608
3619
|
}
|
|
3609
3620
|
}
|
|
3610
|
-
function processOutput(command, args, env, cwd) {
|
|
3621
|
+
function processOutput(command, args, env, cwd, timeoutMs) {
|
|
3611
3622
|
return new Promise((resolve) => {
|
|
3612
3623
|
execFile(command, [...args], {
|
|
3613
|
-
timeout:
|
|
3624
|
+
timeout: timeoutMs,
|
|
3614
3625
|
maxBuffer: 1024,
|
|
3615
3626
|
windowsHide: true,
|
|
3616
3627
|
env,
|
|
@@ -3621,7 +3632,7 @@ function processOutput(command, args, env, cwd) {
|
|
|
3621
3632
|
});
|
|
3622
3633
|
});
|
|
3623
3634
|
}
|
|
3624
|
-
async function processStartedAt(pid) {
|
|
3635
|
+
async function processStartedAt(pid, timeoutMs = 2e3) {
|
|
3625
3636
|
if (pid === process.pid) return PROCESS_STARTED_AT_MS;
|
|
3626
3637
|
if (process.platform === "win32") {
|
|
3627
3638
|
const systemRoot = trustedSystemRootOf(process.env);
|
|
@@ -3636,7 +3647,7 @@ async function processStartedAt(pid) {
|
|
|
3636
3647
|
], trustedWindowsChildEnv(process.env, {
|
|
3637
3648
|
inheritTemp: true,
|
|
3638
3649
|
includeSystemDrive: true
|
|
3639
|
-
}), join(systemRoot, "System32")))?.match(/\d{10,}/);
|
|
3650
|
+
}), join(systemRoot, "System32"), timeoutMs))?.match(/\d{10,}/);
|
|
3640
3651
|
return match === void 0 || match === null ? void 0 : Number(match[0]);
|
|
3641
3652
|
}
|
|
3642
3653
|
const ps = ["/usr/bin/ps", "/bin/ps"].find(existsSync);
|
|
@@ -3650,11 +3661,11 @@ async function processStartedAt(pid) {
|
|
|
3650
3661
|
PATH: "/usr/bin:/bin",
|
|
3651
3662
|
LC_ALL: "C",
|
|
3652
3663
|
TZ: "UTC"
|
|
3653
|
-
}, "/");
|
|
3664
|
+
}, "/", timeoutMs);
|
|
3654
3665
|
const started = output === void 0 ? NaN : Date.parse(`${output.trim()} UTC`);
|
|
3655
3666
|
return Number.isFinite(started) ? started : void 0;
|
|
3656
3667
|
}
|
|
3657
|
-
async function lockState(file) {
|
|
3668
|
+
async function lockState(file, probeTimeoutMs = 2e3, probe = processStartedAt) {
|
|
3658
3669
|
let text;
|
|
3659
3670
|
try {
|
|
3660
3671
|
text = await readFile(file, "utf8");
|
|
@@ -3679,7 +3690,7 @@ async function lockState(file) {
|
|
|
3679
3690
|
if (ownerAlive === true && typeof owner?.pid === "number") {
|
|
3680
3691
|
const recordedStart = typeof owner.processStartedAtMs === "number" ? owner.processStartedAtMs : typeof owner.createdAtMs === "number" ? owner.createdAtMs : void 0;
|
|
3681
3692
|
if (recordedStart !== void 0 && Math.abs(fileAge) > PROCESS_START_TOLERANCE_MS) {
|
|
3682
|
-
const actualStart = await
|
|
3693
|
+
const actualStart = await probe(owner.pid, probeTimeoutMs);
|
|
3683
3694
|
if (actualStart !== void 0 && actualStart - recordedStart > PROCESS_START_TOLERANCE_MS) return "stale";
|
|
3684
3695
|
}
|
|
3685
3696
|
if (recordedStart === void 0) return fileAge > UNOWNED_FILE_LOCK_STALE_MS ? "stale" : "current";
|
|
@@ -3818,7 +3829,7 @@ async function cleanupTerminalReclaims(lock) {
|
|
|
3818
3829
|
}
|
|
3819
3830
|
return !blocked;
|
|
3820
3831
|
}
|
|
3821
|
-
async function claimStaleReclaim(lock) {
|
|
3832
|
+
async function claimStaleReclaim(lock, probeTimeoutMs = 2e3, probe = processStartedAt) {
|
|
3822
3833
|
const directory = dirname(lock);
|
|
3823
3834
|
const prefix = `${basename(lock)}.reclaim.`;
|
|
3824
3835
|
const names = await readdir(directory);
|
|
@@ -3846,7 +3857,7 @@ async function claimStaleReclaim(lock) {
|
|
|
3846
3857
|
}
|
|
3847
3858
|
if (owner.state === "complete" || owner.state === "abandoned") return void 0;
|
|
3848
3859
|
if (owner.token !== void 0 && ABANDONED_RECLAIMS.get(claim) === owner.token) return void 0;
|
|
3849
|
-
if (await lockState(claim) === "current") return void 0;
|
|
3860
|
+
if (await lockState(claim, probeTimeoutMs, probe) === "current") return void 0;
|
|
3850
3861
|
try {
|
|
3851
3862
|
await unlink(claim);
|
|
3852
3863
|
} catch (error) {
|
|
@@ -3932,14 +3943,23 @@ async function withFileLock(lock, work) {
|
|
|
3932
3943
|
mode: 448
|
|
3933
3944
|
});
|
|
3934
3945
|
const deadline = Date.now() + FILE_LOCK_WAIT_MS;
|
|
3946
|
+
const probes = /* @__PURE__ */ new Map();
|
|
3947
|
+
const probe = (pid, timeoutMs) => {
|
|
3948
|
+
let pending = probes.get(pid);
|
|
3949
|
+
if (pending === void 0) {
|
|
3950
|
+
pending = processStartedAt(pid, timeoutMs);
|
|
3951
|
+
probes.set(pid, pending);
|
|
3952
|
+
}
|
|
3953
|
+
return pending;
|
|
3954
|
+
};
|
|
3935
3955
|
let token;
|
|
3936
3956
|
while (token === void 0) {
|
|
3937
3957
|
token = await createOwnedFile(lock);
|
|
3938
3958
|
if (token !== void 0) break;
|
|
3939
|
-
if (await lockState(lock) === "stale") {
|
|
3940
|
-
const reclaim = await cleanupTerminalReclaims(lock) ? await claimStaleReclaim(lock) : void 0;
|
|
3959
|
+
if (await lockState(lock, Math.max(250, deadline - Date.now()), probe) === "stale") {
|
|
3960
|
+
const reclaim = await cleanupTerminalReclaims(lock) ? await claimStaleReclaim(lock, Math.max(250, deadline - Date.now()), probe) : void 0;
|
|
3941
3961
|
if (reclaim !== void 0) try {
|
|
3942
|
-
if (await newestReclaimGeneration(lock) === reclaim.generation && await lockState(lock) === "stale" && await newestReclaimGeneration(lock) === reclaim.generation) await unlink(lock).catch(() => {});
|
|
3962
|
+
if (await newestReclaimGeneration(lock) === reclaim.generation && await lockState(lock, Math.max(250, deadline - Date.now()), probe) === "stale" && await newestReclaimGeneration(lock) === reclaim.generation) await unlink(lock).catch(() => {});
|
|
3943
3963
|
} finally {
|
|
3944
3964
|
try {
|
|
3945
3965
|
await completeReclaim(reclaim);
|
|
@@ -5104,23 +5124,33 @@ var WorkBuddyAccountPool = class {
|
|
|
5104
5124
|
* from settings and only filters at pick time.
|
|
5105
5125
|
*/
|
|
5106
5126
|
disabledIds = /* @__PURE__ */ new Set();
|
|
5107
|
-
/**
|
|
5108
|
-
|
|
5127
|
+
/**
|
|
5128
|
+
* Last account handed out per region, for round-robin.
|
|
5129
|
+
*
|
|
5130
|
+
* Both region shims share one pool, and filtering to the caller's region
|
|
5131
|
+
* before indexing used to make each region renormalise the same cursor
|
|
5132
|
+
* against its own length: with two accounts per region, alternating turns
|
|
5133
|
+
* served the same account in each region and never reached the others.
|
|
5134
|
+
* A stored id also survives the pool shrinking between picks: an account
|
|
5135
|
+
* whose refresh fails is excluded from the retry, and a numeric position
|
|
5136
|
+
* would then point at an account that already had its turn.
|
|
5137
|
+
*/
|
|
5138
|
+
lastServed = /* @__PURE__ */ new Map();
|
|
5109
5139
|
/** Sticky mode: conversation key → account id. Content stays out of memory. */
|
|
5110
5140
|
sticky = /* @__PURE__ */ new Map();
|
|
5111
5141
|
/**
|
|
5112
5142
|
* Account id → the order in which it last served. A readout only: the composer
|
|
5113
5143
|
* shows the account a sticky conversation is on, and that account is the one
|
|
5114
5144
|
* that just answered. A counter rather than a clock, because two acquires can
|
|
5115
|
-
* land in the same millisecond. Not persisted; after a restart the
|
|
5116
|
-
*
|
|
5145
|
+
* land in the same millisecond. Not persisted; after a restart the rotation
|
|
5146
|
+
* starts over.
|
|
5117
5147
|
*/
|
|
5118
5148
|
servedOrder = /* @__PURE__ */ new Map();
|
|
5119
5149
|
servedCount = 0;
|
|
5120
5150
|
lastScanAtMs = 0;
|
|
5121
5151
|
preferredIds = /* @__PURE__ */ new Map();
|
|
5122
5152
|
/**
|
|
5123
|
-
* Account ids the user removed from the pool
|
|
5153
|
+
* Account ids the user removed from the pool.
|
|
5124
5154
|
*
|
|
5125
5155
|
* Enforced while scan() assembles its result, so a removed account cannot
|
|
5126
5156
|
* re-enter the pool when the desktop app rewrites its sign-in file. That is
|
|
@@ -6243,7 +6273,7 @@ var WorkBuddyAccountPool = class {
|
|
|
6243
6273
|
const preferredId = this.preferredIdFor(region);
|
|
6244
6274
|
const remaining = new Set(pool.map((account) => account.id));
|
|
6245
6275
|
while (remaining.size > 0) {
|
|
6246
|
-
const account = pool.find((item) => item.id === preferredId) ?? this.pick(pool, conversationKey);
|
|
6276
|
+
const account = pool.find((item) => item.id === preferredId) ?? this.pick(pool, conversationKey, region);
|
|
6247
6277
|
if (account === void 0) return void 0;
|
|
6248
6278
|
remaining.delete(account.id);
|
|
6249
6279
|
await this.ensureFresh(account);
|
|
@@ -6256,16 +6286,21 @@ var WorkBuddyAccountPool = class {
|
|
|
6256
6286
|
pool = eligible.filter((item) => remaining.has(item.id));
|
|
6257
6287
|
}
|
|
6258
6288
|
}
|
|
6259
|
-
pick(pool, conversationKey) {
|
|
6289
|
+
pick(pool, conversationKey, region) {
|
|
6260
6290
|
if (this.distribution === "expiry") return this.pickByExpiry(pool);
|
|
6261
6291
|
if (this.distribution === "sticky" && conversationKey !== void 0) {
|
|
6262
6292
|
const bound = this.sticky.get(conversationKey);
|
|
6263
6293
|
const kept = bound === void 0 ? void 0 : pool.find((account) => account.id === bound);
|
|
6264
|
-
if (kept !== void 0)
|
|
6265
|
-
|
|
6294
|
+
if (kept !== void 0) {
|
|
6295
|
+
this.sticky.delete(conversationKey);
|
|
6296
|
+
this.sticky.set(conversationKey, kept.id);
|
|
6297
|
+
return kept;
|
|
6298
|
+
}
|
|
6299
|
+
const account = this.successor(pool, this.lastServedFor(region));
|
|
6266
6300
|
if (account === void 0) return void 0;
|
|
6301
|
+
this.sticky.delete(conversationKey);
|
|
6267
6302
|
this.sticky.set(conversationKey, account.id);
|
|
6268
|
-
this.
|
|
6303
|
+
this.setLastServed(region, account.id);
|
|
6269
6304
|
while (this.sticky.size > 200) {
|
|
6270
6305
|
const oldest = this.sticky.keys().next().value;
|
|
6271
6306
|
if (oldest === void 0) break;
|
|
@@ -6273,37 +6308,63 @@ var WorkBuddyAccountPool = class {
|
|
|
6273
6308
|
}
|
|
6274
6309
|
return account;
|
|
6275
6310
|
}
|
|
6276
|
-
const
|
|
6277
|
-
|
|
6278
|
-
if (account !== void 0 && this.distribution === "round-robin") this.cursor = (index + 1) % pool.length;
|
|
6311
|
+
const account = this.distribution === "round-robin" ? this.successor(pool, this.lastServedFor(region)) : pool[0];
|
|
6312
|
+
if (account !== void 0 && this.distribution === "round-robin") this.setLastServed(region, account.id);
|
|
6279
6313
|
return account;
|
|
6280
6314
|
}
|
|
6315
|
+
/**
|
|
6316
|
+
* The first account after `previous` in roster order that is still in `pool`.
|
|
6317
|
+
*
|
|
6318
|
+
* `previous` can be missing from `pool` because this request already skipped
|
|
6319
|
+
* it: a sign-in whose refresh failed is excluded from the retry. Walking the
|
|
6320
|
+
* full roster keeps the rotation moving past it; looking only inside `pool`
|
|
6321
|
+
* would restart at its head and retry the same account every turn while the
|
|
6322
|
+
* accounts behind the skipped one never served.
|
|
6323
|
+
*/
|
|
6324
|
+
successor(pool, previous) {
|
|
6325
|
+
if (pool.length === 0) return void 0;
|
|
6326
|
+
const start = previous === void 0 ? -1 : this.accounts.findIndex((account) => account.id === previous);
|
|
6327
|
+
if (start === -1) return pool[0];
|
|
6328
|
+
const present = new Set(pool.map((account) => account.id));
|
|
6329
|
+
for (let step = 1; step <= this.accounts.length; step += 1) {
|
|
6330
|
+
const candidate = this.accounts[(start + step) % this.accounts.length];
|
|
6331
|
+
if (candidate !== void 0 && present.has(candidate.id)) return candidate;
|
|
6332
|
+
}
|
|
6333
|
+
return pool[0];
|
|
6334
|
+
}
|
|
6335
|
+
/** The last account served through one region; absent regions share one. */
|
|
6336
|
+
lastServedFor(region) {
|
|
6337
|
+
return this.lastServed.get(region ?? "");
|
|
6338
|
+
}
|
|
6339
|
+
setLastServed(region, accountId) {
|
|
6340
|
+
this.lastServed.set(region ?? "", accountId);
|
|
6341
|
+
}
|
|
6281
6342
|
pickByExpiry(pool) {
|
|
6282
6343
|
return pickSoonestExpiry(pool, this.creditExpiries, Date.now());
|
|
6283
6344
|
}
|
|
6284
6345
|
/**
|
|
6285
|
-
* Next account the panel may name as "next up". Does not move the
|
|
6346
|
+
* Next account the panel may name as "next up". Does not move the rotation.
|
|
6286
6347
|
*
|
|
6287
6348
|
* Sticky has no single next account - it is per conversation - so it names
|
|
6288
6349
|
* nothing rather than pointing at a guess. The composer readout uses
|
|
6289
6350
|
* `readoutPreview`, which can name the account that served last instead.
|
|
6290
6351
|
*/
|
|
6291
|
-
preview(eligible) {
|
|
6352
|
+
preview(eligible, region) {
|
|
6292
6353
|
if (eligible.length === 0) return void 0;
|
|
6293
6354
|
if (this.distribution === "expiry") return this.pickByExpiry(eligible);
|
|
6294
6355
|
if (this.distribution === "priority") return eligible[0];
|
|
6295
|
-
if (this.distribution === "round-robin") return
|
|
6356
|
+
if (this.distribution === "round-robin") return this.successor(eligible, this.lastServedFor(region));
|
|
6296
6357
|
}
|
|
6297
6358
|
/**
|
|
6298
|
-
* The account the composer readout names. Does not move the
|
|
6359
|
+
* The account the composer readout names. Does not move the rotation.
|
|
6299
6360
|
*
|
|
6300
6361
|
* Round-robin names the account the next request takes. Sticky names the one
|
|
6301
6362
|
* that served most recently, because the current conversation is most likely
|
|
6302
|
-
* on it; before the first turn the
|
|
6363
|
+
* on it; before the first turn the rotation stands in.
|
|
6303
6364
|
*/
|
|
6304
|
-
readoutPreview(eligible) {
|
|
6365
|
+
readoutPreview(eligible, region) {
|
|
6305
6366
|
if (eligible.length === 0) return void 0;
|
|
6306
|
-
if (this.distribution !== "sticky") return this.preview(eligible);
|
|
6367
|
+
if (this.distribution !== "sticky") return this.preview(eligible, region);
|
|
6307
6368
|
let latest;
|
|
6308
6369
|
let latestAt = -1;
|
|
6309
6370
|
for (const account of eligible) {
|
|
@@ -6313,7 +6374,7 @@ var WorkBuddyAccountPool = class {
|
|
|
6313
6374
|
latestAt = servedAt;
|
|
6314
6375
|
}
|
|
6315
6376
|
}
|
|
6316
|
-
return latest ??
|
|
6377
|
+
return latest ?? this.successor(eligible, this.lastServedFor(region));
|
|
6317
6378
|
}
|
|
6318
6379
|
/** Prefer one billing account per gateway; undefined restores automatic use. */
|
|
6319
6380
|
prefer(accountId, region) {
|
|
@@ -7151,6 +7212,18 @@ function conversationKeyOf(raw) {
|
|
|
7151
7212
|
return;
|
|
7152
7213
|
}
|
|
7153
7214
|
}
|
|
7215
|
+
/**
|
|
7216
|
+
* The upstream a sign-in's chat traffic goes to.
|
|
7217
|
+
*
|
|
7218
|
+
* Transport failures are a property of the host, not of the account: a pool can
|
|
7219
|
+
* hold sign-ins served by different gateways, and one unreachable host says
|
|
7220
|
+
* nothing about the next one. The sign-in domain is not the chat host (every CN
|
|
7221
|
+
* spelling lands on one gateway, and each international brand has its own), so
|
|
7222
|
+
* the host is read from the same mapping the request itself uses.
|
|
7223
|
+
*/
|
|
7224
|
+
function upstreamHostOf(account) {
|
|
7225
|
+
return chatHostOf(account.credential);
|
|
7226
|
+
}
|
|
7154
7227
|
const EMPTY_STREAM_REFUSAL = "workbuddy returned an empty answer stream";
|
|
7155
7228
|
/**
|
|
7156
7229
|
* Read enough of a 200 body to tell an SSE stream from a refusal wearing a 200.
|
|
@@ -7412,7 +7485,8 @@ function createWorkBuddyShim(options) {
|
|
|
7412
7485
|
res.on("close", () => controller.abort());
|
|
7413
7486
|
const raw = (await readRequestBody(req)).toString("utf8");
|
|
7414
7487
|
const prepared = client.prepareChatBody(raw);
|
|
7415
|
-
const
|
|
7488
|
+
const conversationHash = conversationKeyOf(raw);
|
|
7489
|
+
const conversationKey = conversationHash === void 0 || region === void 0 ? conversationHash : `${region}\n${conversationHash}`;
|
|
7416
7490
|
let modelId;
|
|
7417
7491
|
let bodyIsJson = true;
|
|
7418
7492
|
try {
|
|
@@ -7437,14 +7511,52 @@ function createWorkBuddyShim(options) {
|
|
|
7437
7511
|
let last;
|
|
7438
7512
|
let accountSkipped = false;
|
|
7439
7513
|
let transportAttempts = 0;
|
|
7514
|
+
/** Hosts that failed transport in this request; one failure condemns none of the others. */
|
|
7515
|
+
const transportHosts = /* @__PURE__ */ new Set();
|
|
7516
|
+
/** Whether any eligible account this request has not tried belongs to a host that has not failed. */
|
|
7517
|
+
const hasUntriedHost = () => {
|
|
7518
|
+
for (const peer of pool.available(Date.now(), modelId, region)) if (!skipped.has(peer.id) && !transportHosts.has(upstreamHostOf(peer))) return true;
|
|
7519
|
+
return false;
|
|
7520
|
+
};
|
|
7521
|
+
/**
|
|
7522
|
+
* Stop trying accounts served by a host that has already timed out.
|
|
7523
|
+
*
|
|
7524
|
+
* Used only once the transport cap is reached and another host is still
|
|
7525
|
+
* waiting: the first failure gets one retry, and after that a peer on the
|
|
7526
|
+
* same host only pays the same timeout again while a healthy account behind
|
|
7527
|
+
* it waits. A single-host pool never reaches this branch because no other
|
|
7528
|
+
* host is left to justify it.
|
|
7529
|
+
*/
|
|
7530
|
+
const skipHost = (host) => {
|
|
7531
|
+
for (const peer of pool.list(region)) if (upstreamHostOf(peer) === host) skipped.add(peer.id);
|
|
7532
|
+
};
|
|
7533
|
+
/**
|
|
7534
|
+
* Record one transport failure and answer whether the turn is spent.
|
|
7535
|
+
*
|
|
7536
|
+
* Up to the cap the next account gets its turn, including a peer on the
|
|
7537
|
+
* same host. Past the cap another host still waiting is what keeps the turn
|
|
7538
|
+
* alive, and the failed host's remaining peers are skipped so the healthy
|
|
7539
|
+
* host is reached without paying their timeouts first.
|
|
7540
|
+
*/
|
|
7541
|
+
const transportSpent = (host) => {
|
|
7542
|
+
transportHosts.add(host);
|
|
7543
|
+
transportAttempts += 1;
|
|
7544
|
+
if (transportAttempts < MAX_TRANSPORT_ATTEMPTS) return false;
|
|
7545
|
+
if (!hasUntriedHost()) return true;
|
|
7546
|
+
skipHost(host);
|
|
7547
|
+
return false;
|
|
7548
|
+
};
|
|
7440
7549
|
let emptyStreams = 0;
|
|
7550
|
+
const refreshedSessions = /* @__PURE__ */ new Set();
|
|
7551
|
+
let retryAccountId;
|
|
7441
7552
|
let effortFallback;
|
|
7442
7553
|
let effortFallbackBuilt = false;
|
|
7443
|
-
const maxAttempts = Math.max(8, pool.list(region).length + 2);
|
|
7554
|
+
const maxAttempts = Math.max(8, pool.list(region).length * 2 + 2);
|
|
7444
7555
|
const maxEmptyStreams = emptyStreamAttemptsFor(pool.list(region).length);
|
|
7445
7556
|
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
|
7446
7557
|
if (controller.signal.aborted) return;
|
|
7447
|
-
const account = await pool.acquire(modelId, region, conversationKey, skipped);
|
|
7558
|
+
const account = retryAccountId !== void 0 ? pool.available(Date.now(), modelId, region).find((candidate) => candidate.id === retryAccountId) ?? await pool.acquire(modelId, region, conversationKey, skipped) : await pool.acquire(modelId, region, conversationKey, skipped);
|
|
7559
|
+
retryAccountId = void 0;
|
|
7448
7560
|
if (account === void 0) {
|
|
7449
7561
|
if (accountSkipped && last !== void 0) {
|
|
7450
7562
|
const model = ` for model ${modelId}`;
|
|
@@ -7478,7 +7590,7 @@ function createWorkBuddyShim(options) {
|
|
|
7478
7590
|
tried += 1;
|
|
7479
7591
|
let result = await client.chatStream(account.credential, prepared, controller.signal);
|
|
7480
7592
|
let refreshOutcome;
|
|
7481
|
-
if (!result.ok && result.kind === "session_dead") {
|
|
7593
|
+
if (!result.ok && result.kind === "session_dead" && !refreshedSessions.has(account.id)) {
|
|
7482
7594
|
const failure = result;
|
|
7483
7595
|
refreshOutcome = await pool.refreshAccountOutcome(account.id);
|
|
7484
7596
|
if (refreshOutcome === "failed") {
|
|
@@ -7494,6 +7606,7 @@ function createWorkBuddyShim(options) {
|
|
|
7494
7606
|
}
|
|
7495
7607
|
}
|
|
7496
7608
|
if (refreshOutcome === "refreshed") {
|
|
7609
|
+
refreshedSessions.add(account.id);
|
|
7497
7610
|
if (controller.signal.aborted) return;
|
|
7498
7611
|
result = await client.chatStream(account.credential, prepared, controller.signal);
|
|
7499
7612
|
}
|
|
@@ -7614,7 +7727,7 @@ function createWorkBuddyShim(options) {
|
|
|
7614
7727
|
logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} answered 200 with an empty stream; rotating`);
|
|
7615
7728
|
return;
|
|
7616
7729
|
}
|
|
7617
|
-
logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} answered 200 with no stream: ${peeked.refusal}`);
|
|
7730
|
+
logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} answered 200 with no stream: ${safeMessage(peeked.refusal)}`);
|
|
7618
7731
|
if (peeked.code === "11128" || unapprovedChannelRefusal(peeked.refusal) !== void 0) {
|
|
7619
7732
|
writeOpenAIError(res, 400, "upstream_channel_check", channelCheckRefusal());
|
|
7620
7733
|
return;
|
|
@@ -7635,15 +7748,25 @@ function createWorkBuddyShim(options) {
|
|
|
7635
7748
|
pool.penalize(account.id, resetAtMs, modelId);
|
|
7636
7749
|
} else if (envelopeKind === "model_tier") pool.blockModel(account.id, modelId, Date.now() + MODEL_TIER_HOLD_MS);
|
|
7637
7750
|
else if (envelopeKind === "session_dead") {
|
|
7638
|
-
|
|
7639
|
-
|
|
7640
|
-
else if (refreshOutcome === "failed") {
|
|
7751
|
+
if (refreshedSessions.has(account.id)) {
|
|
7752
|
+
pool.penalize(account.id, holdUntil(), void 0, "session");
|
|
7641
7753
|
skipped.add(account.id);
|
|
7642
|
-
|
|
7643
|
-
|
|
7644
|
-
|
|
7645
|
-
|
|
7646
|
-
|
|
7754
|
+
} else {
|
|
7755
|
+
const refreshOutcome = await pool.refreshAccountOutcome(account.id);
|
|
7756
|
+
if (refreshOutcome === "refused") {
|
|
7757
|
+
pool.penalize(account.id, holdUntil(), void 0, "session");
|
|
7758
|
+
skipped.add(account.id);
|
|
7759
|
+
} else if (refreshOutcome === "failed") {
|
|
7760
|
+
skipped.add(account.id);
|
|
7761
|
+
last = {
|
|
7762
|
+
kind: "transport",
|
|
7763
|
+
status: 502,
|
|
7764
|
+
message: `could not refresh the sign-in: ${peeked.refusal.slice(0, 200)}`
|
|
7765
|
+
};
|
|
7766
|
+
} else {
|
|
7767
|
+
refreshedSessions.add(account.id);
|
|
7768
|
+
retryAccountId = account.id;
|
|
7769
|
+
}
|
|
7647
7770
|
}
|
|
7648
7771
|
} else pool.penalize(account.id, holdUntil(), void 0, envelopeKind === "hard_credit" ? "spent" : "restricted");
|
|
7649
7772
|
return;
|
|
@@ -7702,10 +7825,7 @@ function createWorkBuddyShim(options) {
|
|
|
7702
7825
|
if (headIsEmptyStream) {
|
|
7703
7826
|
emptyStreams += 1;
|
|
7704
7827
|
spent = emptyStreams >= maxEmptyStreams;
|
|
7705
|
-
} else
|
|
7706
|
-
transportAttempts += 1;
|
|
7707
|
-
spent = transportAttempts >= MAX_TRANSPORT_ATTEMPTS;
|
|
7708
|
-
}
|
|
7828
|
+
} else spent = transportSpent(upstreamHostOf(account));
|
|
7709
7829
|
if (spent) break;
|
|
7710
7830
|
continue;
|
|
7711
7831
|
}
|
|
@@ -7757,8 +7877,7 @@ function createWorkBuddyShim(options) {
|
|
|
7757
7877
|
};
|
|
7758
7878
|
accountSkipped = true;
|
|
7759
7879
|
skipped.add(account.id);
|
|
7760
|
-
|
|
7761
|
-
if (transportAttempts >= MAX_TRANSPORT_ATTEMPTS) break;
|
|
7880
|
+
if (transportSpent(upstreamHostOf(account))) break;
|
|
7762
7881
|
logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} transport failure; rotating`);
|
|
7763
7882
|
continue;
|
|
7764
7883
|
}
|
|
@@ -14399,8 +14518,8 @@ function creditReserves() {
|
|
|
14399
14518
|
return clean;
|
|
14400
14519
|
}
|
|
14401
14520
|
/**
|
|
14402
|
-
* Accounts removed from the pool
|
|
14403
|
-
*
|
|
14521
|
+
* Accounts removed from the pool, with label and gateway kept so the panel can
|
|
14522
|
+
* still offer a restore after the account stops being scanned.
|
|
14404
14523
|
*/
|
|
14405
14524
|
function removedAccounts() {
|
|
14406
14525
|
const value = settings.removedAccounts;
|
|
@@ -14489,6 +14608,7 @@ function sourceModelView(key, model, native) {
|
|
|
14489
14608
|
nativeSupportsImages: native.supportsImages,
|
|
14490
14609
|
...Array.isArray(native.thinkingLevels) && native.thinkingLevels.length > 0 ? { nativeThinkingLevels: [...native.thinkingLevels] } : {},
|
|
14491
14610
|
...Array.isArray(override.thinkingLevels) && override.thinkingLevels.length > 0 ? { thinkingLevels: override.thinkingLevels } : {},
|
|
14611
|
+
...typeof override.defaultThinkingLevel === "string" && override.defaultThinkingLevel !== "" ? { defaultThinkingLevel: override.defaultThinkingLevel } : {},
|
|
14492
14612
|
...native.multiplier === void 0 ? {} : { multiplier: native.multiplier },
|
|
14493
14613
|
advanced: Object.keys(override).length > 0
|
|
14494
14614
|
};
|
|
@@ -15233,14 +15353,17 @@ function traeDeclarationModels(region) {
|
|
|
15233
15353
|
const advertised = native.thinkingLevels;
|
|
15234
15354
|
const edited = Array.isArray(view.thinkingLevels) && view.thinkingLevels.length > 0 ? view.thinkingLevels.filter((level) => HOST_THINKING_LEVELS.includes(level)) : [];
|
|
15235
15355
|
const levels = edited.length > 0 ? HOST_THINKING_LEVELS.filter((level) => edited.includes(level)) : advertised;
|
|
15236
|
-
|
|
15356
|
+
const published = offersThinking(levels) ? levels : ["off"];
|
|
15357
|
+
const entry = {
|
|
15237
15358
|
id: view.id,
|
|
15238
15359
|
name: modelLabel(view),
|
|
15239
15360
|
contextWindow: view.contextWindow,
|
|
15240
15361
|
maxTokens: view.maxOutputTokens,
|
|
15241
15362
|
supportsImages: view.supportsImages,
|
|
15242
|
-
thinkingLevels:
|
|
15243
|
-
}
|
|
15363
|
+
thinkingLevels: published
|
|
15364
|
+
};
|
|
15365
|
+
if (typeof view.defaultThinkingLevel === "string" && published.includes(view.defaultThinkingLevel)) entry.defaultThinkingLevel = view.defaultThinkingLevel;
|
|
15366
|
+
models.push(entry);
|
|
15244
15367
|
if (models.length >= MAX_MODELS) break;
|
|
15245
15368
|
}
|
|
15246
15369
|
return models;
|
|
@@ -15403,14 +15526,17 @@ function qoderDeclarationModels(region) {
|
|
|
15403
15526
|
const levels = native.thinkingLevels;
|
|
15404
15527
|
const edited = Array.isArray(view.thinkingLevels) && view.thinkingLevels.length > 0 ? view.thinkingLevels.filter((level) => HOST_THINKING_LEVELS.includes(level)) : [];
|
|
15405
15528
|
const published = edited.length > 0 ? HOST_THINKING_LEVELS.filter((level) => edited.includes(level)) : levels;
|
|
15406
|
-
|
|
15529
|
+
const entry = {
|
|
15407
15530
|
id: view.id,
|
|
15408
15531
|
name: view.name,
|
|
15409
15532
|
contextWindow: view.contextWindow,
|
|
15410
15533
|
maxTokens: view.maxOutputTokens,
|
|
15411
15534
|
supportsImages: view.supportsImages,
|
|
15412
15535
|
thinkingLevels: offersThinking(published) ? published : ["off"]
|
|
15413
|
-
}
|
|
15536
|
+
};
|
|
15537
|
+
const levelsOffered = entry.thinkingLevels;
|
|
15538
|
+
if (typeof view.defaultThinkingLevel === "string" && levelsOffered.includes(view.defaultThinkingLevel)) entry.defaultThinkingLevel = view.defaultThinkingLevel;
|
|
15539
|
+
models.push(entry);
|
|
15414
15540
|
if (models.length >= MAX_MODELS) break;
|
|
15415
15541
|
}
|
|
15416
15542
|
return models;
|
|
@@ -15694,7 +15820,7 @@ function cooldownPending() {
|
|
|
15694
15820
|
function probesStale() {
|
|
15695
15821
|
const now = Date.now();
|
|
15696
15822
|
for (const account of core.pool.list()) {
|
|
15697
|
-
if (account.cooldownUntilMs > now || core.pool.isDisabled(account.id) || !regionEnabled("workbuddy", regionOf(account.credential.domain))) continue;
|
|
15823
|
+
if (account.cooldownUntilMs > now && core.pool.activeHold?.(account.id)?.reason !== "spent" || core.pool.isDisabled(account.id) || !regionEnabled("workbuddy", regionOf(account.credential.domain))) continue;
|
|
15698
15824
|
const cached = probeCache.get(account.id);
|
|
15699
15825
|
if (cached === void 0) return true;
|
|
15700
15826
|
const ttl = cached.value.creditsError !== void 0 ? PROBE_RETRY_MS : PROBE_TTL_MS;
|
|
@@ -16051,7 +16177,7 @@ async function refreshSourceAccounts(generation) {
|
|
|
16051
16177
|
const rows = await Promise.all(wanted.map(async ({ credential, label }) => {
|
|
16052
16178
|
const region = traeRegionOfCredential(credential);
|
|
16053
16179
|
const probe = await traeRowProbe(credential, traeAccountRows.find((row) => row.label === label && row.region === region));
|
|
16054
|
-
noteSourceExpiry("trae", region, label, probe?.usage?.credits?.packages);
|
|
16180
|
+
if (generation === loadGeneration) noteSourceExpiry("trae", region, label, probe?.usage?.credits?.packages);
|
|
16055
16181
|
return {
|
|
16056
16182
|
label,
|
|
16057
16183
|
region,
|
|
@@ -16066,7 +16192,10 @@ async function refreshSourceAccounts(generation) {
|
|
|
16066
16192
|
if (generation !== loadGeneration) return;
|
|
16067
16193
|
traeLabelOverrides = overrides;
|
|
16068
16194
|
traeAccountRows = rows.filter((row) => regionEnabled("trae", row.region));
|
|
16069
|
-
} else
|
|
16195
|
+
} else {
|
|
16196
|
+
if (generation !== loadGeneration) return;
|
|
16197
|
+
traeAccountRows = [];
|
|
16198
|
+
}
|
|
16070
16199
|
} catch (error) {
|
|
16071
16200
|
log("warn", "listing Trae sign-ins failed: " + safeMessage(error));
|
|
16072
16201
|
}
|
|
@@ -16074,6 +16203,7 @@ async function refreshSourceAccounts(generation) {
|
|
|
16074
16203
|
const regions = activeQoderRegions();
|
|
16075
16204
|
if (regions.length > 0) {
|
|
16076
16205
|
const found = await discoverQoderCredentials();
|
|
16206
|
+
if (generation !== loadGeneration) return;
|
|
16077
16207
|
const allLabels = uniqueSourceLabels(found.credentials, qoderBaseLabel, (credential) => credential.userID);
|
|
16078
16208
|
const overrides = /* @__PURE__ */ new Map();
|
|
16079
16209
|
found.credentials.forEach((credential, index) => {
|
|
@@ -16087,10 +16217,12 @@ async function refreshSourceAccounts(generation) {
|
|
|
16087
16217
|
const { left } = budget(SOURCE_ACCOUNTS_BUDGET_MS);
|
|
16088
16218
|
let seen = 0;
|
|
16089
16219
|
for (const { credential, label } of wanted) {
|
|
16220
|
+
if (generation !== loadGeneration) return;
|
|
16090
16221
|
if (seen > 0) await delay(QODER_ACCOUNT_DELAY_MS);
|
|
16091
16222
|
seen += 1;
|
|
16092
16223
|
const previous = qoderAccountRows.find((row) => row.label === label && row.region === credential.region);
|
|
16093
16224
|
const probe = left() > 0 ? await qoderRowProbe(credential, previous) : previous;
|
|
16225
|
+
if (generation !== loadGeneration) return;
|
|
16094
16226
|
noteSourceExpiry("qoder", credential.region, label, probe?.usage?.credits?.packages);
|
|
16095
16227
|
rows.push({
|
|
16096
16228
|
label,
|
|
@@ -16104,10 +16236,14 @@ async function refreshSourceAccounts(generation) {
|
|
|
16104
16236
|
if (generation !== loadGeneration) return;
|
|
16105
16237
|
qoderLabelOverrides = overrides;
|
|
16106
16238
|
qoderAccountRows = rows.filter((row) => regionEnabled("qoder", row.region));
|
|
16107
|
-
} else
|
|
16239
|
+
} else {
|
|
16240
|
+
if (generation !== loadGeneration) return;
|
|
16241
|
+
qoderAccountRows = [];
|
|
16242
|
+
}
|
|
16108
16243
|
} catch (error) {
|
|
16109
16244
|
log("warn", "listing Qoder sign-ins failed: " + safeMessage(error));
|
|
16110
16245
|
}
|
|
16246
|
+
if (generation !== loadGeneration) return;
|
|
16111
16247
|
pruneSourceState();
|
|
16112
16248
|
}
|
|
16113
16249
|
/**
|
|
@@ -16375,7 +16511,7 @@ async function statusDocument(options) {
|
|
|
16375
16511
|
selectionByRegion[region] = effectiveSelectionFor(region, runtimes.get(region)?.catalog);
|
|
16376
16512
|
if (selectionStale(region, runtimes.get(region)?.catalog)) staleSelectionRegions.push(region);
|
|
16377
16513
|
const available = core.pool.available(now, void 0, region);
|
|
16378
|
-
const nextUp = available.find((account) => account.id === preferredAccountIds[region]) ?? core.pool.preview(available);
|
|
16514
|
+
const nextUp = available.find((account) => account.id === preferredAccountIds[region]) ?? core.pool.preview(available, region);
|
|
16379
16515
|
runtimeNextUpId.set(region, nextUp === void 0 ? void 0 : nextUp.id);
|
|
16380
16516
|
for (const account of core.pool.list(region)) {
|
|
16381
16517
|
const cooling = account.cooldownUntilMs > now;
|
|
@@ -16402,7 +16538,7 @@ async function statusDocument(options) {
|
|
|
16402
16538
|
...creditReserve === void 0 ? {} : { creditReserve }
|
|
16403
16539
|
};
|
|
16404
16540
|
if (!core.pool.isDisabled(account.id)) {
|
|
16405
|
-
const checkinOnly = cooling;
|
|
16541
|
+
const checkinOnly = cooling && core.pool.activeHold?.(account.id)?.reason !== "spent";
|
|
16406
16542
|
pendingProbes.push(accountProbe(account, allowNetwork, checkinOnly).then((probe) => {
|
|
16407
16543
|
applyProbe(row, probe);
|
|
16408
16544
|
}));
|
|
@@ -16441,7 +16577,29 @@ async function statusDocument(options) {
|
|
|
16441
16577
|
}
|
|
16442
16578
|
}
|
|
16443
16579
|
}
|
|
16444
|
-
if (pendingProbes.length > 0)
|
|
16580
|
+
if (pendingProbes.length > 0) {
|
|
16581
|
+
await settleWithin(Promise.all(pendingProbes).catch(() => {}), probeBudget);
|
|
16582
|
+
const liveAccounts = new Map(core.pool.list().map((account) => [account.id, account]));
|
|
16583
|
+
const heldNow = Date.now();
|
|
16584
|
+
const nextUpNow = /* @__PURE__ */ new Map();
|
|
16585
|
+
for (const region of activeRegions()) {
|
|
16586
|
+
const available = core.pool.available(heldNow, void 0, region);
|
|
16587
|
+
const preferredNow = available.find((account) => account.id === preferredAccountIds[region]);
|
|
16588
|
+
nextUpNow.set(region, (preferredNow ?? core.pool.preview(available, region))?.id);
|
|
16589
|
+
}
|
|
16590
|
+
for (const row of accounts) {
|
|
16591
|
+
const account = liveAccounts.get(row.id);
|
|
16592
|
+
if (account === void 0) continue;
|
|
16593
|
+
const cooling = account.cooldownUntilMs > heldNow;
|
|
16594
|
+
row.cooling = cooling;
|
|
16595
|
+
if (cooling) row.cooldownUntil = new Date(account.cooldownUntilMs).toISOString();
|
|
16596
|
+
else delete row.cooldownUntil;
|
|
16597
|
+
const hold = core.pool.activeHold(account.id);
|
|
16598
|
+
if (hold === null || hold.untilMs <= heldNow) delete row.hold;
|
|
16599
|
+
else row.hold = hold.reason;
|
|
16600
|
+
row.active = nextUpNow.get(row.region) === row.id;
|
|
16601
|
+
}
|
|
16602
|
+
}
|
|
16445
16603
|
return {
|
|
16446
16604
|
regions: activeRegions(),
|
|
16447
16605
|
sources: {
|
|
@@ -16818,7 +16976,10 @@ async function doctorReport() {
|
|
|
16818
16976
|
""
|
|
16819
16977
|
].join("\n");
|
|
16820
16978
|
if (dataPath !== "") try {
|
|
16821
|
-
fs$1.writeFileSync(path.join(dataPath, "doctor.txt"), report,
|
|
16979
|
+
fs$1.writeFileSync(path.join(dataPath, "doctor.txt"), report, {
|
|
16980
|
+
encoding: "utf8",
|
|
16981
|
+
mode: 384
|
|
16982
|
+
});
|
|
16822
16983
|
} catch {}
|
|
16823
16984
|
return {
|
|
16824
16985
|
ok,
|
|
@@ -17480,15 +17641,24 @@ async function onPanelInvoke(channel, payload) {
|
|
|
17480
17641
|
*/
|
|
17481
17642
|
case "xd.startLogin": {
|
|
17482
17643
|
const realm = payload?.realm === "global" ? "global" : "cn";
|
|
17483
|
-
|
|
17484
|
-
|
|
17485
|
-
|
|
17486
|
-
|
|
17487
|
-
|
|
17488
|
-
|
|
17489
|
-
|
|
17490
|
-
|
|
17491
|
-
|
|
17644
|
+
try {
|
|
17645
|
+
const start = await startDeviceLogin(realm);
|
|
17646
|
+
deviceLogins.set(realm, {
|
|
17647
|
+
state: start.state,
|
|
17648
|
+
at: Date.now()
|
|
17649
|
+
});
|
|
17650
|
+
return {
|
|
17651
|
+
realm,
|
|
17652
|
+
authUrl: start.authUrl
|
|
17653
|
+
};
|
|
17654
|
+
} catch (error) {
|
|
17655
|
+
deviceLogins.delete(realm);
|
|
17656
|
+
log("warn", "could not start a WorkBuddy sign-in: " + safeMessage(error));
|
|
17657
|
+
return {
|
|
17658
|
+
realm,
|
|
17659
|
+
authUrl: ""
|
|
17660
|
+
};
|
|
17661
|
+
}
|
|
17492
17662
|
}
|
|
17493
17663
|
/**
|
|
17494
17664
|
* Poll the login the panel started on this realm.
|
|
@@ -18990,7 +19160,7 @@ function workbuddyComposerAccounts(region, modelId) {
|
|
|
18990
19160
|
const list = core.pool.list(region);
|
|
18991
19161
|
const available = core.pool.available(now, modelId, region);
|
|
18992
19162
|
const preferredId = core.pool.resolvedPreferredId(region);
|
|
18993
|
-
const next = available.find((account) => account.id === preferredId) ?? core.pool.readoutPreview(available);
|
|
19163
|
+
const next = available.find((account) => account.id === preferredId) ?? core.pool.readoutPreview(available, region);
|
|
18994
19164
|
return list.map((account) => {
|
|
18995
19165
|
const cached = probeCache.get(account.id)?.value?.credits;
|
|
18996
19166
|
return {
|
|
@@ -19178,16 +19348,6 @@ const INERT_AUTH = {
|
|
|
19178
19348
|
/** The sentinel every loopback gateway accepts. */
|
|
19179
19349
|
const LOOPBACK_BEARER = "dsh-wtq-pool-loopback";
|
|
19180
19350
|
/**
|
|
19181
|
-
* Whether the installed schemastery can mark a field volatile.
|
|
19182
|
-
*
|
|
19183
|
-
* `Config` is built at module evaluation, before any `ctx` exists to log
|
|
19184
|
-
* through, so the finding is recorded here and reported by the activation's
|
|
19185
|
-
* first logger-reaching call rather than dropped.
|
|
19186
|
-
*/
|
|
19187
|
-
let volatileSupported = true;
|
|
19188
|
-
/** Whether the finding above has already been named, so it is named once. */
|
|
19189
|
-
let degradationReported = false;
|
|
19190
|
-
/**
|
|
19191
19351
|
* Which activation currently owns the module-global state the core keeps.
|
|
19192
19352
|
*
|
|
19193
19353
|
* A re-provided service re-runs `apply()`, and the core's state (runtimes,
|
|
@@ -19196,53 +19356,32 @@ let degradationReported = false;
|
|
|
19196
19356
|
* gateways the newer one just brought up.
|
|
19197
19357
|
*/
|
|
19198
19358
|
let activationToken = 0;
|
|
19199
|
-
/**
|
|
19200
|
-
* Wrap one schema in `volatile()` when the installed schemastery has it.
|
|
19201
|
-
*
|
|
19202
|
-
* `volatile()` landed in schemastery 3.18.3. Hand-writing `meta.volatile` on an
|
|
19203
|
-
* older copy would bypass the host's own `validateVolatileSchema`, so an older
|
|
19204
|
-
* builder degrades to the plain schema instead.
|
|
19205
|
-
*/
|
|
19206
|
-
function asVolatile(schema) {
|
|
19207
|
-
const candidate = schema;
|
|
19208
|
-
if (typeof candidate.volatile !== "function") {
|
|
19209
|
-
volatileSupported = false;
|
|
19210
|
-
return schema;
|
|
19211
|
-
}
|
|
19212
|
-
return candidate.volatile();
|
|
19213
|
-
}
|
|
19214
|
-
/** Report the schema degradation once, when a logger is finally in reach. */
|
|
19215
|
-
function reportSchemaDegradation(logger) {
|
|
19216
|
-
if (volatileSupported || degradationReported) return;
|
|
19217
|
-
degradationReported = true;
|
|
19218
|
-
logger.warn("dsh-wtq-pool: the installed schemastery has no volatile(), so no settings field can be marked volatile: the settings card cannot render its section and every settings write this plugin makes is refused");
|
|
19219
|
-
}
|
|
19220
19359
|
const Config = z.object({
|
|
19221
|
-
enabled:
|
|
19222
|
-
sourceWorkbuddy:
|
|
19223
|
-
sourceTrae:
|
|
19224
|
-
sourceQoder:
|
|
19225
|
-
authFile:
|
|
19226
|
-
autoCheckin:
|
|
19360
|
+
enabled: z.boolean().default(true).description("Serve this pool at all").volatile(),
|
|
19361
|
+
sourceWorkbuddy: z.boolean().default(true).description("Merge the WorkBuddy desktop sign-ins").volatile(),
|
|
19362
|
+
sourceTrae: z.boolean().default(true).description("Merge the Trae desktop sign-ins").volatile(),
|
|
19363
|
+
sourceQoder: z.boolean().default(true).description("Merge the Qoder desktop sign-ins").volatile(),
|
|
19364
|
+
authFile: z.string().description("WorkBuddy desktop auth file (defaults to the app's own location)").volatile(),
|
|
19365
|
+
autoCheckin: z.object({
|
|
19227
19366
|
enabled: z.boolean().default(false),
|
|
19228
19367
|
hours: z.array(z.number()).default([])
|
|
19229
|
-
}).description("Daily check-in across every discovered sign-in")),
|
|
19230
|
-
cooldownSeconds:
|
|
19231
|
-
creditReserves:
|
|
19232
|
-
disabledAccountIds:
|
|
19233
|
-
disabledRegions:
|
|
19234
|
-
distribution:
|
|
19368
|
+
}).description("Daily check-in across every discovered sign-in").volatile(),
|
|
19369
|
+
cooldownSeconds: z.number().default(60).description("Rate-limit cooldown per account, in seconds").volatile(),
|
|
19370
|
+
creditReserves: z.dict(z.number()).default({}).description("Per-account credit floor, keyed by account id").volatile(),
|
|
19371
|
+
disabledAccountIds: z.array(z.string()).default([]).description("Account ids the pool must never pick").volatile(),
|
|
19372
|
+
disabledRegions: z.array(z.string()).default([]).description("Regions parked on their own, as source:region").volatile(),
|
|
19373
|
+
distribution: z.union([
|
|
19235
19374
|
"priority",
|
|
19236
19375
|
"round-robin",
|
|
19237
19376
|
"expiry",
|
|
19238
19377
|
"sticky"
|
|
19239
|
-
]).default("priority").description("How the WorkBuddy pool spreads requests")),
|
|
19240
|
-
modelSelection:
|
|
19241
|
-
preferredAccountIds:
|
|
19242
|
-
preferredSourceAccounts:
|
|
19243
|
-
removedAccounts:
|
|
19244
|
-
showComposerPoints:
|
|
19245
|
-
sourceDistributions:
|
|
19378
|
+
]).default("priority").description("How the WorkBuddy pool spreads requests").volatile(),
|
|
19379
|
+
modelSelection: z.any().description("Per-gateway model selection").volatile(),
|
|
19380
|
+
preferredAccountIds: z.any().description("Picked WorkBuddy account per region").volatile(),
|
|
19381
|
+
preferredSourceAccounts: z.any().description("Picked Trae/Qoder account per region").volatile(),
|
|
19382
|
+
removedAccounts: z.any().description("Accounts taken out of the pool; their label and region are kept so the panel can restore them").volatile(),
|
|
19383
|
+
showComposerPoints: z.boolean().default(false).description("Show the active account credits beside the composer").volatile(),
|
|
19384
|
+
sourceDistributions: z.any().description("How each Trae/Qoder region spreads requests").volatile()
|
|
19246
19385
|
});
|
|
19247
19386
|
/** Peel one volatile reference, if the running line wrapped it. */
|
|
19248
19387
|
function unwrapVolatile(value) {
|
|
@@ -19495,22 +19634,47 @@ function apply(ctx, config = {}) {
|
|
|
19495
19634
|
let writesInFlight = 0;
|
|
19496
19635
|
let writesStarted = 0;
|
|
19497
19636
|
let droppedPushes = 0;
|
|
19637
|
+
/**
|
|
19638
|
+
* Whether two setting values are the same document.
|
|
19639
|
+
*
|
|
19640
|
+
* Object key order carries no meaning in the stored document, and the loader's
|
|
19641
|
+
* own comparison ignores it, so a key-order-sensitive check would predict an
|
|
19642
|
+
* echo the host never emits.
|
|
19643
|
+
*/
|
|
19644
|
+
function sameSetting(a, b) {
|
|
19645
|
+
if (Object.is(a, b)) return true;
|
|
19646
|
+
if (typeof a !== "object" || a === null || typeof b !== "object" || b === null) return false;
|
|
19647
|
+
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
|
19648
|
+
const aRecord = a;
|
|
19649
|
+
const bRecord = b;
|
|
19650
|
+
const keys = Object.keys(aRecord).filter((key) => aRecord[key] !== void 0);
|
|
19651
|
+
if (keys.length !== Object.keys(bRecord).filter((key) => bRecord[key] !== void 0).length) return false;
|
|
19652
|
+
for (const key of keys) {
|
|
19653
|
+
if (!Object.prototype.hasOwnProperty.call(bRecord, key)) return false;
|
|
19654
|
+
if (!sameSetting(aRecord[key], bRecord[key])) return false;
|
|
19655
|
+
}
|
|
19656
|
+
return true;
|
|
19657
|
+
}
|
|
19498
19658
|
/** Replace patched top-level fields without merging their dictionaries. */
|
|
19499
19659
|
const writeSettings = async (patch) => {
|
|
19500
19660
|
const mutate = settingsService?.mutate;
|
|
19501
19661
|
if (mutate === void 0) throw new Error("this host exposes no settings mutate()");
|
|
19662
|
+
const before = current();
|
|
19502
19663
|
writesStarted += 1;
|
|
19503
19664
|
writesInFlight += 1;
|
|
19504
|
-
let
|
|
19665
|
+
let echoExpected = false;
|
|
19505
19666
|
try {
|
|
19667
|
+
echoExpected = Object.keys(patch).some((key) => !sameSetting(before[key], patch[key]));
|
|
19506
19668
|
await mutate.call(settingsService, settingsNamespace, Object.entries(patch).map(([key, value]) => ({
|
|
19507
19669
|
op: "set",
|
|
19508
19670
|
path: [key],
|
|
19509
19671
|
value
|
|
19510
19672
|
})));
|
|
19511
|
-
|
|
19673
|
+
} catch (error) {
|
|
19674
|
+
echoExpected = false;
|
|
19675
|
+
throw error;
|
|
19512
19676
|
} finally {
|
|
19513
|
-
if (!
|
|
19677
|
+
if (!echoExpected) writesStarted -= 1;
|
|
19514
19678
|
writesInFlight -= 1;
|
|
19515
19679
|
if (writesInFlight === 0) {
|
|
19516
19680
|
if (droppedPushes > writesStarted) {
|
|
@@ -19529,7 +19693,6 @@ function apply(ctx, config = {}) {
|
|
|
19529
19693
|
getSettings: () => current(),
|
|
19530
19694
|
setSettings: writeSettings,
|
|
19531
19695
|
getDataPath: async () => {
|
|
19532
|
-
reportSchemaDegradation(ctx.logger);
|
|
19533
19696
|
const dir = path.join(dshHome(), "dsh-wtq-pool");
|
|
19534
19697
|
await fs.mkdir(dir, {
|
|
19535
19698
|
recursive: true,
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "dsh-wtq-pool",
|
|
3
3
|
"displayName": "WTQ Pool",
|
|
4
4
|
"description": "把本机 WorkBuddy、Trae、Qoder 的桌面登录接入 DeepSeek Harness。限流或额度用尽时自动换号,三家各自开关,国内与国际账号分别成组。",
|
|
5
|
-
"version": "1.3.
|
|
5
|
+
"version": "1.3.1",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "chengzhi-c",
|
|
8
8
|
"homepage": "https://github.com/chengzhi-c/dsh-wtq-pool#readme",
|
|
@@ -80,7 +80,9 @@
|
|
|
80
80
|
"@earendil-works/pi-ai": "1.5.0",
|
|
81
81
|
"@types/node": "^22.20.0",
|
|
82
82
|
"@types/react": "~18.3.31",
|
|
83
|
+
"@types/react-dom": "18.3.7",
|
|
83
84
|
"react": "^18.3.1",
|
|
85
|
+
"react-dom": "18.3.1",
|
|
84
86
|
"tsdown": "^0.22.2",
|
|
85
87
|
"typescript": "^5.9.3"
|
|
86
88
|
},
|
package/renderer/panel.js
CHANGED
|
@@ -72,6 +72,7 @@ var EN = {
|
|
|
72
72
|
"login.openAgain": "Open the link again",
|
|
73
73
|
"login.waiting": "Finish the sign-in in your browser; this panel picks the account up by itself.",
|
|
74
74
|
"login.timeout": "The sign-in did not finish. Start again for a new link.",
|
|
75
|
+
"login.noLink": "The plugin did not return a sign-in link.",
|
|
75
76
|
"login.added": "Added {name}",
|
|
76
77
|
"login.addedNoName": "Account added",
|
|
77
78
|
"trae.title": "Trae",
|
|
@@ -359,6 +360,7 @@ var ZH = {
|
|
|
359
360
|
"login.openAgain": "再打开一次链接",
|
|
360
361
|
"login.waiting": "在浏览器里完成登录即可,面板会自己把这个账号收进来。",
|
|
361
362
|
"login.timeout": "登录没有完成。重新开始一次拿新链接。",
|
|
363
|
+
"login.noLink": "插件没有返回登录链接。",
|
|
362
364
|
"login.added": "已添加 {name}",
|
|
363
365
|
"login.addedNoName": "账号已添加",
|
|
364
366
|
"trae.title": "Trae",
|
|
@@ -1604,7 +1606,7 @@ function startLogin() {
|
|
|
1604
1606
|
render();
|
|
1605
1607
|
invoke("xd.startLogin", { realm: realm }).then(function (answer) {
|
|
1606
1608
|
loginUrl = answer && typeof answer.authUrl === "string" ? answer.authUrl : "";
|
|
1607
|
-
if (loginUrl === "") throw new Error("
|
|
1609
|
+
if (loginUrl === "") throw new Error(t("login.noLink"));
|
|
1608
1610
|
// This page is a real browser tab, so the link opens the way its own footer
|
|
1609
1611
|
// links do: a new tab, leaving the panel where it is.
|
|
1610
1612
|
window.open(loginUrl, "_blank", "noopener,noreferrer");
|
|
@@ -2362,7 +2364,7 @@ function paintAccounts(host) {
|
|
|
2362
2364
|
}
|
|
2363
2365
|
|
|
2364
2366
|
/**
|
|
2365
|
-
* Accounts the user removed
|
|
2367
|
+
* Accounts the user removed, each with a button that brings it back.
|
|
2366
2368
|
*
|
|
2367
2369
|
* Shown because "remove" would otherwise be a one-way door: the account stops
|
|
2368
2370
|
* being scanned, so there is nothing left in the account list to click.
|