dsh-connect-godagent 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +175 -2
- package/cordis.patch.yml +3 -0
- package/lib/client.js +408 -0
- package/lib/index.js +681 -0
- package/package.json +52 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 atorber
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,176 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-connect-godagent
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
把本机登录的 [God Agent](https://gptgod.online) 桌面 App(gptgod.online 中转)的模型接入 DSH。
|
|
4
|
+
|
|
5
|
+
参考 [dsh-connect-workbuddy](https://github.com/dingminhua/dsh-connect-workbuddy) 的实现思路(pi-ai Provider + PiAiAdapter 装配范式)。
|
|
6
|
+
|
|
7
|
+
## 工作原理
|
|
8
|
+
|
|
9
|
+
1. **凭据复用**(按优先级):
|
|
10
|
+
- God Agent 把会话 cookie(`EGG_SESS` + `EGG_SESS.sig`)存在
|
|
11
|
+
`~/Library/Caches/com.xiangsx.godagent/.cookies`;
|
|
12
|
+
- cookie 失效时读取 Keychain 里的 refresh_token
|
|
13
|
+
(`security find-generic-password -s com.xiangsx.godagent -w`),
|
|
14
|
+
调 `POST /api/user/app-refresh-login` 换新会话。
|
|
15
|
+
**refresh_token 是单次轮换的**,拿到新值立刻写回 Keychain(`-U` 更新),
|
|
16
|
+
与 App 共享同一凭据槽。
|
|
17
|
+
2. **API Key**:自动在 gptgod 创建一枚 `title="DSH GodAgent"` 的 sk- key
|
|
18
|
+
(gptgod 的 key 全文只在创建响应出现,因此存进
|
|
19
|
+
`~/.dsh/godagent-connect/state.json`,0600;state 丢失时删旧建新保证幂等)。
|
|
20
|
+
也可在插件设置里显式填 `apiKey`。
|
|
21
|
+
3. **模型目录**:`GET https://api.gptgod.online/v1/models`(Bearer sk-),
|
|
22
|
+
能力元数据(vision / reasoning / context_window / max_output_tokens)取自
|
|
23
|
+
God Agent App 本地 `cap-cache.json`(App 自己对每模型×格式做过真实探测;
|
|
24
|
+
openai 格式探测失败的模型默认排除,可用 `enabledModelIds` 显式点名覆盖)。
|
|
25
|
+
|
|
26
|
+
## 分组(多倍率)
|
|
27
|
+
|
|
28
|
+
gptgod 的模型按**分组**计费(倍率 0.3×–5× 不等),分组由 API key 绑定
|
|
29
|
+
(请求头/模型名前缀均无效,实测)。因此插件为每个启用分组自动创建一枚
|
|
30
|
+
专用 key(`DSH GodAgent · <分组code>`),并注册为独立 provider:
|
|
31
|
+
|
|
32
|
+
| provider id | 说明 |
|
|
33
|
+
| --- | --- |
|
|
34
|
+
| `godagent` | default 分组(1×,账户级模型目录) |
|
|
35
|
+
| `godagent:<分组code>` | 其他分组,如 `godagent:cc-cheap`(0.4×)、`godagent:codex`(0.3×) |
|
|
36
|
+
|
|
37
|
+
- 分组清单来自公开接口 `GET /api/god-agent/groups`(缓存 6h),
|
|
38
|
+
含 `name/multiplier/models/pricing`;倍率会显示在 provider 名称上。
|
|
39
|
+
- **非 default 分组的 `models` 清单即权威**(`/v1/models` 只反映 default 组的面),
|
|
40
|
+
分组专属模型(如 codex 组的 `gpt-6-sol`)直接从清单注册。
|
|
41
|
+
- `enabledGroups` 设置控制启用哪些分组(留空 = 仅 default,`default` 永远保留);
|
|
42
|
+
`enabledModelIds` 白名单跨分组按裸模型 id 生效。
|
|
43
|
+
|
|
44
|
+
## 费率展示
|
|
45
|
+
|
|
46
|
+
模型选择器的行文案(模型显示名)直接带费率后缀,格式按 gptgod 的
|
|
47
|
+
`billing_type` 区分:
|
|
48
|
+
|
|
49
|
+
| 计费类型 | 显示 | 说明 |
|
|
50
|
+
| --- | --- | --- |
|
|
51
|
+
| `official` | `claude-opus-5 · $2/$10` (cc-cheap 0.4×) | 接口官方美元价 × 分组倍率 = 实际美元/百万 token(输入/输出);cost 字段同步用折算后实际价,供宿主成本统计 |
|
|
52
|
+
| `times` | `claude-haiku-4-5-20251001 · 100分/次` | 积分/次 × 倍率(按秒的显示 `分/秒`) |
|
|
53
|
+
| `token` | `gemini-3-pro · 0.02/0分/M` | 积分计价 × 倍率(非美元) |
|
|
54
|
+
| `characters` | `· 按字符` | 按字符计费 |
|
|
55
|
+
|
|
56
|
+
价格全部取自公开接口 `GET /api/god-agent/groups` 返回的
|
|
57
|
+
`pricing` + `multiplier` 并直接相乘,展示的就是该分组的实际费率;
|
|
58
|
+
分组倍率另显示在 provider 名称上(如 `God Agent · ClaudeCode 青春版 (0.4×)`)。
|
|
59
|
+
provider 目录按倍率升序注册,搜索同名模型时回车直选最便宜分组。
|
|
60
|
+
|
|
61
|
+
## 设置项
|
|
62
|
+
|
|
63
|
+
**GUI 设置页**:设置 → God Agent(参考 WorkBuddy 的 `settings.section` 范式注册)。
|
|
64
|
+
可视化编辑以下全部字段:分组列表从公开接口实时拉取(带倍率/模型数徽章),
|
|
65
|
+
保存后模型目录按新配置自动重建;分组 key 首次启用时自动创建。
|
|
66
|
+
|
|
67
|
+
**volatile 生效机制**:全部字段都标 schemastery `.volatile()`——DSH 设置页
|
|
68
|
+
(`dsh-settings` 的 `volatileForm`)只展示带 `meta.volatile` 标记的字段,普通标量
|
|
69
|
+
Config 的整个 namespace 会从 `settings.describe()` 消失(表现为"等待宿主配置就绪…")。
|
|
70
|
+
代价是 volatile-only 变更不重载插件(apply 不重跑),宿主侧由 60s 配置指纹巡检
|
|
71
|
+
补偿:enabled/enabledGroups/enabledModelIds/refreshMinutes 任一变化即重新拉目录并
|
|
72
|
+
重注册(先 dispose 旧句柄),最迟 60s 生效;停用开关会注销全部 provider。
|
|
73
|
+
|
|
74
|
+
| 字段 | 默认 | 说明 |
|
|
75
|
+
| --- | --- | --- |
|
|
76
|
+
| `enabled` | `true` | 启用 God Agent (gptgod) 模型接入 |
|
|
77
|
+
| `apiKey` | `''` | gptgod API Key(sk-…),仅用于 default 分组;其余分组自动创建 |
|
|
78
|
+
| `enabledGroups` | `[]` | 启用的分组 code(留空 = 仅 default),如 `cc-cheap`/`codex`/`aws-vip` |
|
|
79
|
+
| `enabledModelIds` | `[]` | 只启用这些模型 id(留空 = 全部聊天模型) |
|
|
80
|
+
| `refreshMinutes` | `30` | 模型目录刷新周期(分钟) |
|
|
81
|
+
|
|
82
|
+
实现:`lib/client.js` 为 Lazy-CJS 工厂(`window.__ModuleLoader__.load`),
|
|
83
|
+
经 `ctx.slots.inject('settings.section')` 注册页面、`settings.section.icon` 注册
|
|
84
|
+
导航图标;配置读写走 `configForms` 服务的 `ConfigFormController`
|
|
85
|
+
(`whileServed` 晚绑定宿主 namespace)。`test-client.mjs` 用 mock 平台模块
|
|
86
|
+
单测注册与渲染全链路(18 项断言)。
|
|
87
|
+
|
|
88
|
+
## 注意
|
|
89
|
+
|
|
90
|
+
- 模型调用直接走 `https://api.gptgod.online/v1`(openai-completions),
|
|
91
|
+
计费落在你的 gptgod 账户积分上。
|
|
92
|
+
- 本插件只读 App 的凭据与缓存文件,不写 App 数据目录(Keychain 的
|
|
93
|
+
refresh_token 轮换除外,这与 App 自身行为一致)。
|
|
94
|
+
- God Agent App 未登录时插件无法工作(无凭据可复用)。
|
|
95
|
+
|
|
96
|
+
## 在 DSH 中安装(一句话)
|
|
97
|
+
|
|
98
|
+
对 DSH 助手说这一句即可:
|
|
99
|
+
|
|
100
|
+
> 安装 dsh-connect-godagent 插件,仓库地址 https://github.com/atorber/dsh-connect-godagent
|
|
101
|
+
|
|
102
|
+
助手只需要执行**一条命令**(脚本自动完成:git 依赖安装 + bundles 注册 +
|
|
103
|
+
patch 挂载条目,幂等可重复执行):
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
# 国内网络优先(raw.githubusercontent.com 常被阻断,gcore CDN 实测可用):
|
|
107
|
+
curl -fsSL https://gcore.jsdelivr.net/gh/atorber/dsh-connect-godagent@main/install.sh | bash
|
|
108
|
+
# 或 GitHub 源:
|
|
109
|
+
curl -fsSL https://raw.githubusercontent.com/atorber/dsh-connect-godagent/main/install.sh | bash
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
- 默认装到 `web` profile;其它 profile 在后面加参数:`… | bash -s -- <profile名>`
|
|
113
|
+
- 完成后**重启 DSH**(`dsh web`)生效;GUI「设置 → God Agent」出现配置卡片
|
|
114
|
+
|
|
115
|
+
### 从本仓库安装(手动方式)
|
|
116
|
+
|
|
117
|
+
**方法一:git 依赖**
|
|
118
|
+
|
|
119
|
+
在 profile 目录(`$DSH_HOME/profiles/web`,可用 `dsh web` 启动参数
|
|
120
|
+
`--profile <name>` 指定其它 profile)执行:
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
cd $DSH_HOME/profiles/web
|
|
124
|
+
|
|
125
|
+
# 1. 把仓库装成 git 依赖
|
|
126
|
+
dsh plugin --profile web add "git+https://github.com/atorber/dsh-connect-godagent.git"
|
|
127
|
+
# (不用 dsh CLI 的话等价于:pnpm add "git+https://github.com/atorber/dsh-connect-godagent.git")
|
|
128
|
+
|
|
129
|
+
# 2. profile/package.json 的 dsh.profile.bundles 数组追加 "dsh-connect-godagent"
|
|
130
|
+
# 3. profile/cordis.patch.yml 追加两行:
|
|
131
|
+
# - id: dsh-connect-godagent
|
|
132
|
+
# name: dsh-connect-godagent
|
|
133
|
+
# 4. 重启 DSH
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
> **务必写全 `git+https://` 前缀**。写成 `github:atorber/dsh-connect-godagent`
|
|
137
|
+
> 短格式时 pnpm 会解析成 `git+ssh://git@github.com/...`,未配置 SSH key 的机器
|
|
138
|
+
> 会报 `Permission denied (publickey)`。
|
|
139
|
+
|
|
140
|
+
安装即生效,无需 pnpm approve-builds:本包没有任何 build 脚本,依赖全部由
|
|
141
|
+
DSH 宿主提供(profile 树内的插件在加载时由 DSH Loader 把裸导入重路由到宿主
|
|
142
|
+
DSH 自带副本,见下文「依赖策略」)。
|
|
143
|
+
|
|
144
|
+
### 方法二:clone + link:(本地开发推荐,源码改动即时生效)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
```bash
|
|
148
|
+
git clone https://github.com/atorber/dsh-connect-godagent.git /path/to/dsh-connect-godagent
|
|
149
|
+
|
|
150
|
+
# profile: $DSH_HOME/profiles/web/package.json
|
|
151
|
+
"dsh-connect-godagent": "link:/path/to/dsh-connect-godagent"
|
|
152
|
+
# dsh.profile.bundles 追加 "dsh-connect-godagent"
|
|
153
|
+
# cordis.patch.yml 追加 `- id: dsh-connect-godagent / name: dsh-connect-godagent`
|
|
154
|
+
# 重启 DSH
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
link: 模式下依赖经 symlink 解析(目录里有 node_modules 时),源码改动无需重新
|
|
158
|
+
拷贝,重启 DSH 即生效;方法一为纯快照安装,更新需重新 `pnpm add` 拉取。
|
|
159
|
+
|
|
160
|
+
两种方法安装后,GUI「设置 → God Agent」应出现本插件的配置卡片
|
|
161
|
+
(启用开关 / 分组复选 / 模型白名单等)。
|
|
162
|
+
|
|
163
|
+
## 本地开发 / 安装
|
|
164
|
+
|
|
165
|
+
(开发期调试也可直接把仓库以 `link:` 依赖挂进 DSH profile,方法同上。)
|
|
166
|
+
|
|
167
|
+
- **依赖策略:零自带副本**。`package.json` 不声明任何 DSH 公共包
|
|
168
|
+
(`@deepseek-ai/dsh-llm`、`@deepseek-ai/cordis`、`@earendil-works/pi-ai` 等)为
|
|
169
|
+
dependencies,只保留 peerDependencies 声明运行时契约;本地 `node_modules/` 里
|
|
170
|
+
这些包是**指向宿主 DSH 自带副本的 symlink**
|
|
171
|
+
(`ln -s <DSH>/node_modules/@deepseek-ai/dsh-llm node_modules/@deepseek-ai/`)。
|
|
172
|
+
Node 沿 realpath 解析后与宿主加载同一物理模块(单副本,require cache 同 key),
|
|
173
|
+
避免 DSH 升级后出现两份版本漂移的 dsh-llm/pi-ai 互相干扰。`.npmrc`
|
|
174
|
+
`auto-install-peers=false` 防止 pnpm 意外把 peer 拉成本地实体。
|
|
175
|
+
(cordis 服务访问仍需 `export const inject = ['llm']`。)
|
|
176
|
+
- 冒烟测试:`node test-e2e.mjs [providerId] [modelId] [reasoningEffort]`。
|
package/cordis.patch.yml
ADDED
package/lib/client.js
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-connect-godagent · 客户端设置页(参考 dsh-connect-workbuddy 的 settings.section 范式)。
|
|
3
|
+
*
|
|
4
|
+
* 宿主协议(从 dsh-client-modules README 与 workbuddy 5.31.1 实现核对):
|
|
5
|
+
* - client 入口是 `window.__ModuleLoader__.load({ id: <包名>, factory })` 形式的
|
|
6
|
+
* Lazy-CJS 工厂;react / react-dom 由平台种子表(PLATFORM_MODULES)提供,直接 require。
|
|
7
|
+
* - package.json 需要 `dsh.client: { platform: 'web', inject: [...] }` 与
|
|
8
|
+
* `exports['./client']`;宿主把启用插件的 client bundle 组进 /plugins 引导图。
|
|
9
|
+
* - 设置面板导航:`ctx.slots.inject('settings.section', cb)` 后
|
|
10
|
+
* `ctx.slots.register({ name: 'settings.section', id, order, label }, Component)`;
|
|
11
|
+
* 图标同法注册 `settings.section.icon`(shell 以 `{ only: row.id }` 渲染)。
|
|
12
|
+
* - 配置读写:`ctx.get('configForms')` 的 `whileServed(nsCandidates, cb)` 等到宿主
|
|
13
|
+
* describe 出本插件 namespace 后 `forms.get(ns)` 拿 ConfigFormController:
|
|
14
|
+
* `getSnapshot().value`(宿主解析后的完整 Config)、`subscribe`、`set(field, value)`。
|
|
15
|
+
* - 分组目录:`GET https://gptgod.online/api/god-agent/groups` 公开且 CORS 全开
|
|
16
|
+
* (实测 access-control-allow-origin: *),client 直接拉取展示勾选。
|
|
17
|
+
*/
|
|
18
|
+
window.__ModuleLoader__.load({
|
|
19
|
+
id: 'dsh-connect-godagent',
|
|
20
|
+
factory: (require) => {
|
|
21
|
+
var module = { exports: {} };
|
|
22
|
+
var exports = module.exports;
|
|
23
|
+
|
|
24
|
+
const react = require('react');
|
|
25
|
+
const { useState, useEffect, useMemo, useCallback } = react;
|
|
26
|
+
|
|
27
|
+
const PLUGIN_ID = 'dsh-connect-godagent';
|
|
28
|
+
const GROUPS_URL = 'https://gptgod.online/api/god-agent/groups';
|
|
29
|
+
|
|
30
|
+
//#region 轻量内联样式(跟随主题变量,缺省回落暗色值)
|
|
31
|
+
const S = {
|
|
32
|
+
page: { display: 'flex', flexDirection: 'column', gap: 14, padding: 0, minHeight: 0 },
|
|
33
|
+
head: {
|
|
34
|
+
display: 'grid', gridTemplateColumns: 'auto minmax(0,1fr)', columnGap: 10, rowGap: 2,
|
|
35
|
+
alignItems: 'center', background: 'var(--dsw-alias-bg-layer-1,#17181b)',
|
|
36
|
+
borderRadius: 12, padding: '10px 12px',
|
|
37
|
+
},
|
|
38
|
+
title: { fontSize: 15, lineHeight: '22px', fontWeight: 600, color: 'var(--dsw-alias-label-primary,#e8e9ed)' },
|
|
39
|
+
desc: { gridColumn: '1/-1', fontSize: 12, lineHeight: '18px', color: 'var(--dsw-alias-label-secondary,#b8bcc4)' },
|
|
40
|
+
card: {
|
|
41
|
+
display: 'flex', flexDirection: 'column', gap: 12,
|
|
42
|
+
background: 'var(--dsw-alias-bg-layer-1,#17181b)', borderRadius: 12, padding: '12px 14px',
|
|
43
|
+
},
|
|
44
|
+
fieldTitle: { fontSize: 12, fontWeight: 600, color: 'var(--dsw-alias-label-primary,#e8e9ed)', margin: 0 },
|
|
45
|
+
hint: { fontSize: 11, lineHeight: '16px', color: 'var(--dsw-alias-label-tertiary,#8a8f98)', margin: '2px 0 0' },
|
|
46
|
+
input: {
|
|
47
|
+
font: 'inherit', fontSize: 12, lineHeight: '20px', width: '100%', boxSizing: 'border-box',
|
|
48
|
+
fontFamily: 'ui-monospace,SFMono-Regular,Menlo,Consolas,monospace', padding: '5px 8px', borderRadius: 6,
|
|
49
|
+
color: 'var(--dsw-alias-label-primary,#e8e9ed)', background: 'var(--dsw-alias-bg-l1,transparent)',
|
|
50
|
+
border: '1px solid var(--dsw-alias-border-l2,#3a3d45)',
|
|
51
|
+
},
|
|
52
|
+
textarea: {
|
|
53
|
+
font: 'inherit', fontSize: 12, lineHeight: '18px', width: '100%', boxSizing: 'border-box',
|
|
54
|
+
fontFamily: 'ui-monospace,SFMono-Regular,Menlo,Consolas,monospace', padding: '6px 8px', borderRadius: 6,
|
|
55
|
+
minHeight: 52, resize: 'vertical', color: 'var(--dsw-alias-label-primary,#e8e9ed)',
|
|
56
|
+
background: 'var(--dsw-alias-bg-l1,transparent)', border: '1px solid var(--dsw-alias-border-l2,#3a3d45)',
|
|
57
|
+
},
|
|
58
|
+
row: { display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: 'var(--dsw-alias-label-primary,#e8e9ed)' },
|
|
59
|
+
check: { accentColor: 'var(--dsw-alias-brand-primary,#5686fe)', width: 14, height: 14, flex: 'none', cursor: 'pointer' },
|
|
60
|
+
groupList: { display: 'flex', flexDirection: 'column', gap: 2, marginTop: 6 },
|
|
61
|
+
groupRow: {
|
|
62
|
+
display: 'flex', alignItems: 'center', gap: 8, padding: '4px 6px', borderRadius: 6,
|
|
63
|
+
fontSize: 12, cursor: 'pointer', color: 'var(--dsw-alias-label-primary,#e8e9ed)',
|
|
64
|
+
},
|
|
65
|
+
groupRowHover: { background: 'var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.12))' },
|
|
66
|
+
badge: {
|
|
67
|
+
flex: 'none', fontSize: 10, lineHeight: '14px', padding: '0 6px', borderRadius: 999,
|
|
68
|
+
background: 'var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.16))',
|
|
69
|
+
color: 'var(--dsw-alias-label-secondary,#b8bcc4)',
|
|
70
|
+
},
|
|
71
|
+
groupName: { color: 'var(--dsw-alias-label-secondary,#b8bcc4)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
|
|
72
|
+
button: {
|
|
73
|
+
alignSelf: 'flex-start', appearance: 'none', border: 0, cursor: 'pointer',
|
|
74
|
+
font: 'inherit', fontSize: 12, fontWeight: 600, lineHeight: '24px', padding: '2px 14px', borderRadius: 8,
|
|
75
|
+
background: 'var(--dsw-alias-brand-primary,#5686fe)', color: 'var(--dsw-alias-brand-label,#fff)',
|
|
76
|
+
},
|
|
77
|
+
buttonDisabled: { opacity: 0.55, cursor: 'default' },
|
|
78
|
+
status: { fontSize: 11, lineHeight: '16px', color: 'var(--dsw-alias-label-secondary,#b8bcc4)' },
|
|
79
|
+
statusError: { color: '#e5697a' },
|
|
80
|
+
navIcon: { borderRadius: 4, display: 'block' },
|
|
81
|
+
};
|
|
82
|
+
//#endregion
|
|
83
|
+
|
|
84
|
+
//#region 分组目录(公开接口,CORS 全开)
|
|
85
|
+
async function fetchGroups() {
|
|
86
|
+
const ctrl = typeof AbortController === 'function' ? new AbortController() : undefined;
|
|
87
|
+
const timer = ctrl ? setTimeout(() => ctrl.abort(), 15000) : undefined;
|
|
88
|
+
try {
|
|
89
|
+
const response = await fetch(GROUPS_URL, { headers: { accept: 'application/json' }, signal: ctrl?.signal });
|
|
90
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
91
|
+
const body = await response.json();
|
|
92
|
+
if (body?.code !== 0 || !Array.isArray(body?.data)) throw new Error(body?.msg || '响应格式不符');
|
|
93
|
+
return body.data;
|
|
94
|
+
} finally {
|
|
95
|
+
if (timer) clearTimeout(timer);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
//#endregion
|
|
99
|
+
|
|
100
|
+
//#region 设置卡片
|
|
101
|
+
/** 与 workbuddy 的 WorkBuddyCard 相同的 props 约定:inject 返回 { t, settingsScope, surface }。 */
|
|
102
|
+
function GodAgentSettingsCard({ settingsScope, healDescribe }) {
|
|
103
|
+
const snapshot = settingsScope?.getSnapshot?.();
|
|
104
|
+
const ready = snapshot?.status === 'ready' && snapshot.value && typeof snapshot.value === 'object';
|
|
105
|
+
const server = ready ? snapshot.value : {};
|
|
106
|
+
|
|
107
|
+
/** 本地草稿:undefined = 未编辑(跟随服务端值)。字段级编辑后切到草稿值。 */
|
|
108
|
+
const [draft, setDraft] = useState(undefined);
|
|
109
|
+
const [groups, setGroups] = useState(undefined); // undefined=加载中, []=失败/空
|
|
110
|
+
const [groupError, setGroupError] = useState('');
|
|
111
|
+
const [busy, setBusy] = useState(false);
|
|
112
|
+
/**
|
|
113
|
+
* 等待超过 12s 进入 slow 分支。describe mirror 首拉失败后不会自动重试
|
|
114
|
+
* (status 停在 idle,直到下次 settings 写入触发 settings/document-updated
|
|
115
|
+
* 或 WS 重连才重拉),所以 slow 后做一次"同值写回"自愈:
|
|
116
|
+
* describe → 用原值 mutate 一次 → 宿主广播 document-updated → mirror 重拉 →
|
|
117
|
+
* whileServed 边沿触发 → 表单无需刷新即渲染(2026-11-24 实机验证有效)。
|
|
118
|
+
* 自愈过一次仍不 ready 则只给手动重试按钮,避免循环写。
|
|
119
|
+
*/
|
|
120
|
+
const [slow, setSlow] = useState(false);
|
|
121
|
+
const [healing, setHealing] = useState(false);
|
|
122
|
+
const healedRef = react.useRef(false);
|
|
123
|
+
useEffect(() => {
|
|
124
|
+
if (ready) {
|
|
125
|
+
setSlow(false); setHealing(false);
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
const t = setTimeout(() => {
|
|
129
|
+
setSlow(true);
|
|
130
|
+
if (healedRef.current) return; // 已自愈过仍不 ready → 只给手动按钮
|
|
131
|
+
healedRef.current = true;
|
|
132
|
+
setHealing(true);
|
|
133
|
+
Promise.resolve()
|
|
134
|
+
.then(() => healDescribe?.())
|
|
135
|
+
.catch((error) => console.warn('[dsh-connect-godagent] describe 自愈写入失败(可点重试):', error))
|
|
136
|
+
.finally(() => setHealing(false));
|
|
137
|
+
}, 12000);
|
|
138
|
+
return () => clearTimeout(t);
|
|
139
|
+
}, [ready]);
|
|
140
|
+
const [note, setNote] = useState(''); // 保存结果 { ok, text }
|
|
141
|
+
const [hoverRow, setHoverRow] = useState('');
|
|
142
|
+
|
|
143
|
+
// 服务端值变化(保存回包 / 其他端修改)时丢弃草稿,回到权威值。
|
|
144
|
+
useEffect(() => settingsScope?.subscribe?.(() => setDraft(undefined)), [settingsScope]);
|
|
145
|
+
|
|
146
|
+
useEffect(() => {
|
|
147
|
+
let alive = true;
|
|
148
|
+
fetchGroups()
|
|
149
|
+
.then((data) => { if (alive) setGroups(data); })
|
|
150
|
+
.catch((error) => { if (alive) { setGroups([]); setGroupError(error.message); } });
|
|
151
|
+
return () => { alive = false; };
|
|
152
|
+
}, []);
|
|
153
|
+
|
|
154
|
+
const value = useMemo(() => ({ ...server, ...(draft ?? {}) }), [server, draft]);
|
|
155
|
+
const patch = useCallback((fields) => {
|
|
156
|
+
setNote('');
|
|
157
|
+
setDraft((prev) => ({ ...(prev ?? server), ...fields }));
|
|
158
|
+
}, [server]);
|
|
159
|
+
|
|
160
|
+
const enabledGroups = Array.isArray(value.enabledGroups) ? value.enabledGroups : [];
|
|
161
|
+
const modelIdsText = Array.isArray(value.enabledModelIds) ? value.enabledModelIds.join(', ')
|
|
162
|
+
: typeof value.enabledModelIds === 'string' ? value.enabledModelIds : '';
|
|
163
|
+
|
|
164
|
+
const save = useCallback(async () => {
|
|
165
|
+
if (!settingsScope || busy) return;
|
|
166
|
+
setBusy(true);
|
|
167
|
+
setNote('');
|
|
168
|
+
try {
|
|
169
|
+
const next = { ...(draft ?? server) };
|
|
170
|
+
const modelIds = modelIdsText.split(/[\s,,]+/).map((s) => s.trim()).filter(Boolean);
|
|
171
|
+
const groups$1 = ['default', ...enabledGroups.filter((c) => c !== 'default')];
|
|
172
|
+
const fields = {
|
|
173
|
+
enabled: value.enabled !== false,
|
|
174
|
+
apiKey: String(next.apiKey ?? '').trim(),
|
|
175
|
+
enabledGroups: groups$1,
|
|
176
|
+
enabledModelIds: modelIds,
|
|
177
|
+
refreshMinutes: Math.max(5, Math.round(Number(next.refreshMinutes) || 30)),
|
|
178
|
+
};
|
|
179
|
+
let ok = true;
|
|
180
|
+
for (const [field, v] of Object.entries(fields)) {
|
|
181
|
+
if (!(await settingsScope.set(field, v))) ok = false;
|
|
182
|
+
}
|
|
183
|
+
setNote(ok
|
|
184
|
+
? { ok: true, text: '已保存 · 模型目录正在按新配置重建(分组 key 首次启用时自动创建)' }
|
|
185
|
+
: { ok: false, text: '保存未生效:宿主拒绝了写入,请查看设置面板的错误说明' });
|
|
186
|
+
if (ok) setDraft(undefined);
|
|
187
|
+
} catch (error) {
|
|
188
|
+
setNote({ ok: false, text: `保存失败:${error?.message ?? error}` });
|
|
189
|
+
} finally {
|
|
190
|
+
setBusy(false);
|
|
191
|
+
}
|
|
192
|
+
}, [settingsScope, busy, draft, server, value, modelIdsText, enabledGroups]);
|
|
193
|
+
|
|
194
|
+
const dirty = draft !== undefined;
|
|
195
|
+
|
|
196
|
+
return react.createElement('div', { style: S.page },
|
|
197
|
+
// 页头
|
|
198
|
+
react.createElement('div', { style: S.head },
|
|
199
|
+
react.createElement(NavIcon, { size: 28 }),
|
|
200
|
+
react.createElement('div', { style: S.title }, 'God Agent (gptgod)'),
|
|
201
|
+
react.createElement('div', { style: S.desc },
|
|
202
|
+
'把本机 God Agent / gptgod 接入 DSH:按分组倍率接入全部聊天模型,费率显示在模型选择器里。配置改动保存后自动重建模型目录。'),
|
|
203
|
+
),
|
|
204
|
+
// 表单
|
|
205
|
+
react.createElement('div', { style: S.card },
|
|
206
|
+
// 总开关
|
|
207
|
+
react.createElement('label', { style: { ...S.row, cursor: 'pointer' } },
|
|
208
|
+
react.createElement('input', {
|
|
209
|
+
type: 'checkbox', style: S.check, checked: value.enabled !== false,
|
|
210
|
+
onChange: (e) => patch({ enabled: e.target.checked }),
|
|
211
|
+
}),
|
|
212
|
+
'启用 God Agent (gptgod) 模型接入',
|
|
213
|
+
),
|
|
214
|
+
// API Key
|
|
215
|
+
react.createElement('div', null,
|
|
216
|
+
react.createElement('p', { style: S.fieldTitle }, 'API Key(可选,default 分组)'),
|
|
217
|
+
react.createElement('input', {
|
|
218
|
+
style: S.input, type: 'text', placeholder: 'sk-…(留空 = 自动创建并管理 DSH GodAgent 专用 key)',
|
|
219
|
+
value: String(value.apiKey ?? ''), onChange: (e) => patch({ apiKey: e.target.value }),
|
|
220
|
+
spellCheck: false,
|
|
221
|
+
}),
|
|
222
|
+
react.createElement('p', { style: S.hint },
|
|
223
|
+
'仅作用于 default 分组;其他分组各用一枚自动创建的专用 key(标题「DSH GodAgent · 分组」),在 gptgod 控制台可管理。'),
|
|
224
|
+
),
|
|
225
|
+
// 分组
|
|
226
|
+
react.createElement('div', null,
|
|
227
|
+
react.createElement('p', { style: S.fieldTitle }, '启用分组'),
|
|
228
|
+
react.createElement('p', { style: S.hint }, '每个分组一份独立模型清单与计费倍率(默认分组 1× 恒启用);同名模型按倍率从低到高排序,模型选择器直接显示折算后的实际费率。'),
|
|
229
|
+
groups === undefined
|
|
230
|
+
? react.createElement('p', { style: S.status }, '正在读取分组目录…')
|
|
231
|
+
: react.createElement('div', { style: S.groupList },
|
|
232
|
+
groups.length === 0
|
|
233
|
+
? react.createElement('p', { style: { ...S.status, ...(groupError ? S.statusError : {}) } },
|
|
234
|
+
groupError ? `分组目录读取失败:${groupError}` : '分组目录为空')
|
|
235
|
+
: groups.map((group) => {
|
|
236
|
+
const code = group.code;
|
|
237
|
+
const isDefault = code === 'default';
|
|
238
|
+
const checked = isDefault || enabledGroups.includes(code);
|
|
239
|
+
const mult = Number(group.multiplier ?? 1);
|
|
240
|
+
return react.createElement('label', {
|
|
241
|
+
key: code, style: { ...S.groupRow, ...(hoverRow === code ? S.groupRowHover : {}) },
|
|
242
|
+
onMouseEnter: () => setHoverRow(code), onMouseLeave: () => setHoverRow(''),
|
|
243
|
+
},
|
|
244
|
+
react.createElement('input', {
|
|
245
|
+
type: 'checkbox', style: S.check, checked, disabled: isDefault,
|
|
246
|
+
onChange: (e) => {
|
|
247
|
+
const next = new Set(enabledGroups);
|
|
248
|
+
if (e.target.checked) next.add(code); else next.delete(code);
|
|
249
|
+
patch({ enabledGroups: [...next] });
|
|
250
|
+
},
|
|
251
|
+
}),
|
|
252
|
+
react.createElement('span', { style: { fontFamily: 'ui-monospace,SFMono-Regular,Menlo,Consolas,monospace' } }, code),
|
|
253
|
+
react.createElement('span', { style: S.groupName }, group.name || ''),
|
|
254
|
+
react.createElement('span', { style: S.badge }, `${mult}×`),
|
|
255
|
+
Number.isFinite(Number(group.model_count)) ? react.createElement('span', { style: S.badge }, `${group.model_count} 模型`) : null,
|
|
256
|
+
group.description ? react.createElement('span', { style: { ...S.groupName, fontSize: 11 } }, group.description) : null,
|
|
257
|
+
);
|
|
258
|
+
}),
|
|
259
|
+
),
|
|
260
|
+
),
|
|
261
|
+
// 模型白名单
|
|
262
|
+
react.createElement('div', null,
|
|
263
|
+
react.createElement('p', { style: S.fieldTitle }, '模型白名单(可选)'),
|
|
264
|
+
react.createElement('textarea', {
|
|
265
|
+
style: S.textarea, placeholder: '留空 = 接入全部聊天模型;填写模型 id(逗号或换行分隔)只接入这些模型,跨所有启用分组生效',
|
|
266
|
+
value: modelIdsText, onChange: (e) => patch({ enabledModelIds: e.target.value }), spellCheck: false,
|
|
267
|
+
}),
|
|
268
|
+
),
|
|
269
|
+
// 刷新周期
|
|
270
|
+
react.createElement('div', { style: S.row },
|
|
271
|
+
react.createElement('label', { style: S.row, htmlFor: 'dsh-godagent-refresh' }, '目录刷新周期'),
|
|
272
|
+
react.createElement('input', {
|
|
273
|
+
id: 'dsh-godagent-refresh', style: { ...S.input, width: 72 }, type: 'number', min: 5,
|
|
274
|
+
value: String(value.refreshMinutes ?? 30), onChange: (e) => patch({ refreshMinutes: e.target.value }),
|
|
275
|
+
}),
|
|
276
|
+
react.createElement('span', { style: S.hint }, '分钟'),
|
|
277
|
+
),
|
|
278
|
+
// 保存
|
|
279
|
+
react.createElement('div', { style: { ...S.row, gap: 10 } },
|
|
280
|
+
react.createElement('button', {
|
|
281
|
+
style: { ...S.button, ...(busy || !ready || !dirty ? S.buttonDisabled : {}) },
|
|
282
|
+
disabled: busy || !ready || !dirty, onClick: save,
|
|
283
|
+
}, busy ? '保存中…' : '保存'),
|
|
284
|
+
!ready ? react.createElement('span', { style: S.status },
|
|
285
|
+
snapshot?.status === 'unavailable'
|
|
286
|
+
? '宿主未提供 God Agent 配置表单(硬刷新页面 / 重启 DSH 后重试)'
|
|
287
|
+
: (slow
|
|
288
|
+
? (healing
|
|
289
|
+
? '配置读取未完成,正在自动修复(触发宿主刷新配置缓存)...'
|
|
290
|
+
: '等待God Agent主配置就绪...(自动修复未生效——可点"重试",或重启 DSH 后硬刷新 Cmd+Shift+R)')
|
|
291
|
+
: '等待God Agent主配置就绪...')) : null,
|
|
292
|
+
slow && !healing ? react.createElement('button', {
|
|
293
|
+
style: S.button,
|
|
294
|
+
onClick: () => { window.location.reload(); },
|
|
295
|
+
}, '重试') : null,
|
|
296
|
+
dirty && ready && !busy ? react.createElement('span', { style: S.status }, '有未保存的修改') : null,
|
|
297
|
+
note ? react.createElement('span', { style: { ...S.status, ...(note.ok ? {} : S.statusError) } }, note.text) : null,
|
|
298
|
+
),
|
|
299
|
+
),
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
//#endregion
|
|
303
|
+
|
|
304
|
+
//#region 导航图标(内联 SVG,无需静态资源路由)
|
|
305
|
+
function NavIcon({ size = 16, active = true }) {
|
|
306
|
+
return react.createElement('svg', {
|
|
307
|
+
width: size, height: size, viewBox: '0 0 32 32', style: S.navIcon,
|
|
308
|
+
opacity: active === false ? 0.75 : 1, 'aria-hidden': true,
|
|
309
|
+
},
|
|
310
|
+
react.createElement('rect', { x: 1, y: 1, width: 30, height: 30, rx: 8, fill: '#5686fe' }),
|
|
311
|
+
react.createElement('path', {
|
|
312
|
+
d: 'M22.5 12.2a7.4 7.4 0 1 0 .5 3.4h-6.6v2.9h3.5a4.6 4.6 0 1 1-1.2-4.6l2.1-2.1a7.4 7.4 0 0 0-12.3 5.4 7.4 7.4 0 0 0 13.9 3.5z',
|
|
313
|
+
fill: '#fff',
|
|
314
|
+
}),
|
|
315
|
+
react.createElement('circle', { cx: 23.5, cy: 23.5, r: 3.2, fill: '#ffd257' }),
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
//#endregion
|
|
319
|
+
|
|
320
|
+
//#region 入口
|
|
321
|
+
const inject = ['slots', 'remote', 'remote.settings'];
|
|
322
|
+
|
|
323
|
+
function apply(ctx) {
|
|
324
|
+
try {
|
|
325
|
+
const softGet = (name) => ctx.get(name);
|
|
326
|
+
|
|
327
|
+
/** settingsScope 晚绑定:宿主 describe 出本插件 namespace 后才可用(whileServed 边沿触发)。 */
|
|
328
|
+
let settingsScope;
|
|
329
|
+
let liveDisposers = [];
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* 自愈:当浏览器端 settings describe mirror 卡在 idle(首拉失败无重试)时,
|
|
333
|
+
* 用一次"同值写回"触发宿主广播 settings/document-updated,mirror 会重拉
|
|
334
|
+
* describe → whileServed 边沿触发 → 表单无需刷新即渲染(2026-11-24 实机验证)。
|
|
335
|
+
*/
|
|
336
|
+
const healDescribe = async () => {
|
|
337
|
+
const remoteSettings = ctx.remote?.settings;
|
|
338
|
+
if (!remoteSettings?.describe || !remoteSettings?.mutate) throw new Error('remote.settings 不可用');
|
|
339
|
+
const described = await remoteSettings.describe();
|
|
340
|
+
const rows = described?.namespaces ?? described?.value?.namespaces ?? [];
|
|
341
|
+
const row = rows.find((entry) => entry?.ns === PLUGIN_ID)
|
|
342
|
+
?? rows.find((entry) => /godagent/i.test(String(entry?.ns ?? '')));
|
|
343
|
+
if (!row) throw new Error('describe 结果里没有本插件配置');
|
|
344
|
+
const current = row.value ?? {};
|
|
345
|
+
const ops = [{ op: 'set', path: ['refreshMinutes'], value: current.refreshMinutes ?? 30 }];
|
|
346
|
+
await remoteSettings.mutate(row.ns, ops, row.revision);
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
const registerAllSlots = () => {
|
|
350
|
+
const disposers = [];
|
|
351
|
+
try {
|
|
352
|
+
const sectionInject = ctx.slots.inject('settings.section', () => ctx.slots.register({
|
|
353
|
+
name: 'settings.section',
|
|
354
|
+
id: PLUGIN_ID,
|
|
355
|
+
order: 36,
|
|
356
|
+
label: () => 'God Agent',
|
|
357
|
+
inject: () => ({ settingsScope, surface: 'settings', healDescribe }),
|
|
358
|
+
}, GodAgentSettingsCard));
|
|
359
|
+
disposers.push(sectionInject);
|
|
360
|
+
} catch (error) {
|
|
361
|
+
console.error('[dsh-connect-godagent] settings section failed to register:', error);
|
|
362
|
+
}
|
|
363
|
+
try {
|
|
364
|
+
const iconInject = ctx.slots.inject('settings.section.icon', () => ctx.slots.register({
|
|
365
|
+
name: 'settings.section.icon',
|
|
366
|
+
id: PLUGIN_ID,
|
|
367
|
+
}, NavIcon));
|
|
368
|
+
disposers.push(iconInject);
|
|
369
|
+
} catch (error) {
|
|
370
|
+
console.error('[dsh-connect-godagent] settings nav icon failed to register:', error);
|
|
371
|
+
}
|
|
372
|
+
return disposers;
|
|
373
|
+
};
|
|
374
|
+
|
|
375
|
+
const rebindSlots = () => {
|
|
376
|
+
for (const dispose of liveDisposers) try { dispose(); } catch {}
|
|
377
|
+
liveDisposers = registerAllSlots();
|
|
378
|
+
};
|
|
379
|
+
|
|
380
|
+
const forms = softGet('configForms');
|
|
381
|
+
const candidates = [PLUGIN_ID, `include:${PLUGIN_ID}`];
|
|
382
|
+
if (forms && typeof forms.whileServed === 'function') {
|
|
383
|
+
ctx.effect(() => forms.whileServed(candidates, (served) => {
|
|
384
|
+
const ns = candidates.find((candidate) => served.has(candidate))
|
|
385
|
+
?? [...served].find((entry) => /godagent/i.test(entry));
|
|
386
|
+
settingsScope = ns === undefined ? undefined : forms.get(ns);
|
|
387
|
+
rebindSlots();
|
|
388
|
+
return () => {
|
|
389
|
+
for (const dispose of liveDisposers) try { dispose(); } catch {}
|
|
390
|
+
liveDisposers = [];
|
|
391
|
+
};
|
|
392
|
+
}), 'dsh-connect-godagent: settings namespace binding');
|
|
393
|
+
} else {
|
|
394
|
+
console.warn('[dsh-connect-godagent] configForms 服务不可用,设置页不可用(模型接入不受影响)');
|
|
395
|
+
}
|
|
396
|
+
rebindSlots();
|
|
397
|
+
} catch (error) {
|
|
398
|
+
console.error('[dsh-connect-godagent] client card failed to load (host provider unaffected):', error);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
//#endregion
|
|
402
|
+
|
|
403
|
+
exports.apply = apply;
|
|
404
|
+
exports.inject = inject;
|
|
405
|
+
exports.name = PLUGIN_ID;
|
|
406
|
+
return module.exports;
|
|
407
|
+
},
|
|
408
|
+
});
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,681 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-connect-godagent
|
|
3
|
+
*
|
|
4
|
+
* 把本机登录的 God Agent 桌面 App(gptgod.online)模型接入 DSH。
|
|
5
|
+
*
|
|
6
|
+
* 认证链(全部实测验证过):
|
|
7
|
+
* 1) 会话 cookie:God Agent 把 EGG_SESS + EGG_SESS.sig 存在
|
|
8
|
+
* ~/Library/Caches/com.xiangsx.godagent/.cookies(滚动 ~30 天);
|
|
9
|
+
* 2) cookie 失效时回退 Keychain refresh_token:
|
|
10
|
+
* `security find-generic-password -s com.xiangsx.godagent -w`
|
|
11
|
+
* → POST /api/user/app-refresh-login {refresh_token}
|
|
12
|
+
* → 响应里的 refresh_token 是单次轮换的,必须立刻写回 Keychain;
|
|
13
|
+
* 3) API Key:gptgod 的 sk- key 全文只在创建时可见(list 只给 secret_hint),
|
|
14
|
+
* 所以首次自动创建一枚 title="DSH GodAgent" 的 key 并存进本地 state 文件。
|
|
15
|
+
*
|
|
16
|
+
* 模型目录:GET https://api.gptgod.online/v1/models(Bearer sk-…),
|
|
17
|
+
* 能力元数据(vision / reasoning / max_output_tokens)取自 God Agent 本地
|
|
18
|
+
* cap-cache.json(App 自己维护),失败时给出保守缺省。
|
|
19
|
+
*/
|
|
20
|
+
import { execFile } from 'node:child_process';
|
|
21
|
+
import { promisify } from 'node:util';
|
|
22
|
+
import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
23
|
+
import { homedir } from 'node:os';
|
|
24
|
+
import path from 'node:path';
|
|
25
|
+
import { PiAiAdapter } from '@deepseek-ai/dsh-llm-pi-ai';
|
|
26
|
+
import { resolveRetryPolicy } from '@deepseek-ai/dsh-llm';
|
|
27
|
+
import { createProvider } from '@earendil-works/pi-ai';
|
|
28
|
+
import { openAICompletionsApi } from '@earendil-works/pi-ai/api/openai-completions.lazy';
|
|
29
|
+
import z from '@deepseek-ai/schemastery';
|
|
30
|
+
|
|
31
|
+
const execFileP = promisify(execFile);
|
|
32
|
+
|
|
33
|
+
const PLUGIN_ID = 'dsh-connect-godagent';
|
|
34
|
+
const PROVIDER = 'godagent';
|
|
35
|
+
const DISPLAY_NAME = 'God Agent (gptgod)';
|
|
36
|
+
|
|
37
|
+
const API_BASE = 'https://gptgod.online/api';
|
|
38
|
+
const OPENAI_BASE = 'https://api.gptgod.online/v1';
|
|
39
|
+
const SITE_BASE = 'https://gptgod.online';
|
|
40
|
+
|
|
41
|
+
const GA_CACHE_DIR = path.join(homedir(), 'Library', 'Caches', 'com.xiangsx.godagent');
|
|
42
|
+
const GA_COOKIES_FILE = path.join(GA_CACHE_DIR, '.cookies');
|
|
43
|
+
const GA_DATA_DIR = path.join(homedir(), 'Library', 'Application Support', 'com.xiangsx.godagent');
|
|
44
|
+
const GA_CAP_CACHE = path.join(GA_DATA_DIR, 'cap-cache.json');
|
|
45
|
+
|
|
46
|
+
const KEYCHAIN_SERVICE = 'com.xiangsx.godagent';
|
|
47
|
+
const KEYCHAIN_ACCOUNT = 'auth.refresh_token';
|
|
48
|
+
|
|
49
|
+
const STATE_DIR = path.join(homedir(), '.dsh', 'godagent-connect');
|
|
50
|
+
const STATE_FILE = path.join(STATE_DIR, 'state.json');
|
|
51
|
+
|
|
52
|
+
const API_KEY_TITLE = 'DSH GodAgent';
|
|
53
|
+
|
|
54
|
+
/** /user/api/create 的响应结构里全文密钥的候选字段名(未逐字确认,逐个尝试)。 */
|
|
55
|
+
const SECRET_KEYS = ['secret', 'key', 'api_key', 'apiKey', 'secret_full'];
|
|
56
|
+
|
|
57
|
+
//#region 状态持久化
|
|
58
|
+
|
|
59
|
+
async function loadState() {
|
|
60
|
+
try {
|
|
61
|
+
return JSON.parse(await readFile(STATE_FILE, 'utf8'));
|
|
62
|
+
} catch {
|
|
63
|
+
return {};
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function saveState(state) {
|
|
68
|
+
await mkdir(STATE_DIR, { recursive: true });
|
|
69
|
+
await writeFile(STATE_FILE, JSON.stringify(state, null, 2), { mode: 0o600 });
|
|
70
|
+
await chmod(STATE_FILE, 0o600).catch(() => {});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
//#endregion
|
|
74
|
+
//#region God Agent 本机凭据读取
|
|
75
|
+
|
|
76
|
+
/** God Agent 的会话 cookie 文件 → "EGG_SESS=…; EGG_SESS.sig=…"。 */
|
|
77
|
+
async function readAppCookieHeader() {
|
|
78
|
+
try {
|
|
79
|
+
const rows = JSON.parse(await readFile(GA_COOKIES_FILE, 'utf8'));
|
|
80
|
+
const pairs = rows
|
|
81
|
+
.map((row) => String(row.raw_cookie ?? '').split(';')[0])
|
|
82
|
+
.filter(Boolean);
|
|
83
|
+
return pairs.length ? pairs.join('; ') : undefined;
|
|
84
|
+
} catch {
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function keychainReadToken() {
|
|
90
|
+
try {
|
|
91
|
+
const { stdout } = await execFileP('security', [
|
|
92
|
+
'find-generic-password', '-s', KEYCHAIN_SERVICE, '-w',
|
|
93
|
+
], { timeout: 5000 });
|
|
94
|
+
const parsed = JSON.parse(stdout.trim());
|
|
95
|
+
return { token: parsed.token, email: parsed.email };
|
|
96
|
+
} catch {
|
|
97
|
+
return {};
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function keychainWriteToken(token, email) {
|
|
102
|
+
const payload = JSON.stringify({ email: email ?? '', token });
|
|
103
|
+
// promisify(execFile) 以非零退出码拒绝——拒绝即失败,无需检查 returnCode
|
|
104
|
+
await execFileP('security', [
|
|
105
|
+
'add-generic-password', '-s', KEYCHAIN_SERVICE,
|
|
106
|
+
'-a', KEYCHAIN_ACCOUNT, '-U', '-w', payload,
|
|
107
|
+
], { timeout: 5000 });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
//#endregion
|
|
111
|
+
//#region gptgod API 客户端
|
|
112
|
+
|
|
113
|
+
async function gptgodPost(pathname, body, cookieHeader) {
|
|
114
|
+
const res = await fetch(API_BASE + pathname, {
|
|
115
|
+
method: 'POST',
|
|
116
|
+
headers: {
|
|
117
|
+
'Content-Type': 'application/json',
|
|
118
|
+
...(cookieHeader ? { Cookie: cookieHeader } : {}),
|
|
119
|
+
'User-Agent': 'GodAgent/1.4.11 (Macintosh; Intel Mac OS X)',
|
|
120
|
+
},
|
|
121
|
+
body: JSON.stringify(body ?? {}),
|
|
122
|
+
signal: AbortSignal.timeout(20000),
|
|
123
|
+
});
|
|
124
|
+
if (!res.ok) throw new Error(`gptgod ${pathname} -> HTTP ${res.status}`);
|
|
125
|
+
return res.json();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function collectSetCookies(res) {
|
|
129
|
+
// Node fetch: res.headers.getSetCookie() 数组;每条形如 "EGG_SESS=…; Path=/; …"
|
|
130
|
+
return (res.headers.getSetCookie?.() ?? [])
|
|
131
|
+
.map((line) => line.split(';')[0])
|
|
132
|
+
.filter(Boolean);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* 确保"可用会话":依次尝试 state cookies → App cookie 文件 → Keychain 刷新。
|
|
137
|
+
* 返回 { cookieHeader, email };全部失败则抛错。
|
|
138
|
+
*/
|
|
139
|
+
export async function ensureSession(state) {
|
|
140
|
+
const candidates = [];
|
|
141
|
+
if (state.cookies?.length) candidates.push(state.cookies.join('; '));
|
|
142
|
+
const appCookie = await readAppCookieHeader();
|
|
143
|
+
if (appCookie) candidates.push(appCookie);
|
|
144
|
+
|
|
145
|
+
for (const cookieHeader of candidates) {
|
|
146
|
+
try {
|
|
147
|
+
const reply = await gptgodPost('/user/info', {}, cookieHeader);
|
|
148
|
+
if (reply?.code === 0) {
|
|
149
|
+
state.cookies = cookieHeader.split('; ');
|
|
150
|
+
return { cookieHeader, email: reply.data?.email };
|
|
151
|
+
}
|
|
152
|
+
} catch {} // 网络失败换下一个凭据源
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// cookie 全部失效 → Keychain refresh_token 换新会话
|
|
156
|
+
const { token, email } = await keychainReadToken();
|
|
157
|
+
if (!token) throw new Error('God Agent 凭据全部不可用:请先在 God Agent App 里登录');
|
|
158
|
+
|
|
159
|
+
const res = await fetch(API_BASE + '/user/app-refresh-login', {
|
|
160
|
+
method: 'POST',
|
|
161
|
+
headers: { 'Content-Type': 'application/json', 'User-Agent': 'GodAgent/1.4.11 (Macintosh; Intel Mac OS X)' },
|
|
162
|
+
body: JSON.stringify({ refresh_token: token }),
|
|
163
|
+
signal: AbortSignal.timeout(20000),
|
|
164
|
+
});
|
|
165
|
+
const reply = await res.json().catch(() => ({}));
|
|
166
|
+
if (reply?.code !== 0 || !reply.data?.refresh_token) {
|
|
167
|
+
throw new Error(`God Agent 刷新登录失败:${reply?.msg ?? `HTTP ${res.status}`}`);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// 单次轮换:必须立刻写回,否则 App 下次冷启动要求重新登录
|
|
171
|
+
await keychainWriteToken(reply.data.refresh_token, email);
|
|
172
|
+
|
|
173
|
+
const fresh = collectSetCookies(res);
|
|
174
|
+
if (fresh.length) {
|
|
175
|
+
state.cookies = fresh;
|
|
176
|
+
await saveState(state);
|
|
177
|
+
return { cookieHeader: fresh.join('; '), email };
|
|
178
|
+
}
|
|
179
|
+
// 上游没下发新 cookie 时退回旧候选再探测一次
|
|
180
|
+
return ensureSession({ ...state, cookies: [] });
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** 拿到可用的 sk- key:config 显式 > state 已存 > 同名旧 key 清理后新建一枚。 */
|
|
184
|
+
export async function ensureApiKey(state, cookieHeader, config, groupCode = 'default') {
|
|
185
|
+
const explicit = liveValue(config.apiKey)?.trim?.();
|
|
186
|
+
if (explicit && groupCode === 'default') return explicit;
|
|
187
|
+
|
|
188
|
+
state.apiKeys = state.apiKeys ?? {};
|
|
189
|
+
if (state.apiKeys[groupCode]?.key) return state.apiKeys[groupCode].key;
|
|
190
|
+
|
|
191
|
+
// 旧版单 key state 迁移:default 分组直接继承
|
|
192
|
+
if (groupCode === 'default' && state.apiKey) return state.apiKey;
|
|
193
|
+
|
|
194
|
+
const title = groupCode === 'default' ? API_KEY_TITLE : `${API_KEY_TITLE} · ${groupCode}`;
|
|
195
|
+
// 全文密钥只在创建响应里出现(list 只给 secret_hint):state 丢失后旧 key 无法复用,删除重建避免堆积
|
|
196
|
+
const listReply = await gptgodPost('/user/api/list', {}, cookieHeader).catch(() => undefined);
|
|
197
|
+
const rows = listReply?.code === 0 ? (listReply.data?.rows ?? listReply.data ?? []) : [];
|
|
198
|
+
const stale = Array.isArray(rows)
|
|
199
|
+
? rows.find((row) => row?.title === title && (!row.group_code || row.group_code === groupCode))
|
|
200
|
+
: undefined;
|
|
201
|
+
if (stale?.id != null) {
|
|
202
|
+
await gptgodPost('/user/api/delete', { id: stale.id }, cookieHeader).catch(() => {});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const reply = await gptgodPost('/user/api/create', {
|
|
206
|
+
title,
|
|
207
|
+
group_code: groupCode,
|
|
208
|
+
}, cookieHeader);
|
|
209
|
+
if (reply?.code !== 0) {
|
|
210
|
+
throw new Error(`创建 gptgod API Key(分组 ${groupCode})失败:${reply?.msg ?? 'unknown'}`);
|
|
211
|
+
}
|
|
212
|
+
const data = reply.data ?? {};
|
|
213
|
+
const secret = SECRET_KEYS.map((k) => data[k]).find((v) => typeof v === 'string' && v.startsWith('sk-'));
|
|
214
|
+
if (!secret) {
|
|
215
|
+
throw new Error(`创建成功但未识别密钥字段(keys: ${Object.keys(data).join(',')})`);
|
|
216
|
+
}
|
|
217
|
+
state.apiKeys[groupCode] = { key: secret, id: data.id };
|
|
218
|
+
if (groupCode === 'default') { state.apiKey = secret; state.apiKeyId = data.id; } // 兼容旧读取方
|
|
219
|
+
await saveState(state);
|
|
220
|
+
return secret;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* 拉取 gptgod 分组目录(公开接口,无需认证):
|
|
225
|
+
* [{code, name, description, multiplier, models: ['*']|[id...], is_default}]
|
|
226
|
+
* 结果缓存 6 小时(分组上下线频率低)。
|
|
227
|
+
*/
|
|
228
|
+
export async function loadGroups(state) {
|
|
229
|
+
const CACHE_TTL = 6 * 3600_000;
|
|
230
|
+
const cached = state.groupsCache;
|
|
231
|
+
if (cached?.groups?.length && Date.now() - cached.at < CACHE_TTL) return cached.groups;
|
|
232
|
+
const res = await fetch(`${SITE_BASE}/api/god-agent/groups`, {
|
|
233
|
+
method: 'GET',
|
|
234
|
+
signal: AbortSignal.timeout(15000),
|
|
235
|
+
});
|
|
236
|
+
if (!res.ok) throw new Error(`GET /api/god-agent/groups -> HTTP ${res.status}`);
|
|
237
|
+
const body = await res.json();
|
|
238
|
+
if (body?.code !== 0 || !Array.isArray(body.data)) {
|
|
239
|
+
throw new Error(`分组目录响应异常: code=${body?.code}`);
|
|
240
|
+
}
|
|
241
|
+
const groups = body.data.filter((g) => g?.code);
|
|
242
|
+
state.groupsCache = { at: Date.now(), groups };
|
|
243
|
+
await saveState(state);
|
|
244
|
+
return groups;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
//#endregion
|
|
248
|
+
//#region 模型目录
|
|
249
|
+
|
|
250
|
+
/** 明显不是聊天模型的 id 片段(图像/语音/视频/向量化/审核/批量类)。 */
|
|
251
|
+
const NON_CHAT_RE = /(embed|whisper|tts|suno|dall[-.]?e|flux|midjourney|^mj|stable[- ]?diffusion|^sd[0-9x]|sora|veo|kling|runway|pika|luma|pixverse|hailuo|vidu|seedance|seedream|cogvideo|wan[-.]?x?|hidream|recraft|ideogram|gpt-image|image|video|music|audio|voice|asr|ocr|rerank|moderation|guard|clip|caption|transcribe|realtime|bge-|jina-clip|batch|gpts)/i;
|
|
252
|
+
|
|
253
|
+
/** openai-completions 的推理档位 → wire 值。 */
|
|
254
|
+
const OPENAI_REASONING_EFFORTS = { low: 'low', medium: 'medium', high: 'high' };
|
|
255
|
+
const THINKING_LEVELS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
256
|
+
/** 订阅额度无单价可查,一律报 0(workbuddy 同款约定)。 */
|
|
257
|
+
const NO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
258
|
+
const DEFAULT_CONTEXT_WINDOW = 128_000;
|
|
259
|
+
const DEFAULT_MAX_TOKENS = 8_192;
|
|
260
|
+
|
|
261
|
+
/** 无探测数据时按 id 猜 reasoning:claude/gpt-5+/o系列/thinking 后缀等惯例。 */
|
|
262
|
+
const REASONING_HINT_RE = /(thinking|reasoning|^o[1-9]|gpt-[5-9]|claude-(opus|sonnet|haiku|fable)|gemini-[23]|deepseek-r|qwen3|kimi-[st]|glm-4\.[5-9]|minimax-m)/i;
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* 模型费率 → 展示后缀 + pi-ai cost。
|
|
266
|
+
* gptgod 计价四种:official(官方美元价/百万token)、times(积分/次)、
|
|
267
|
+
* token(积分/百万token)、characters(按字符)。
|
|
268
|
+
* 接口返回的分组 multiplier 直接乘进费率,展示与 cost 均为该分组实际费率
|
|
269
|
+
* (倍率也显示在 provider 名称上);展示折进模型 name(模型选择器的行
|
|
270
|
+
* 文案就是 name),official 的 cost 同时供宿主成本统计使用。
|
|
271
|
+
*/
|
|
272
|
+
function priceInfo(id, group) {
|
|
273
|
+
const p = group?.pricing?.[id];
|
|
274
|
+
if (!p) return {};
|
|
275
|
+
const mult = Number(group.multiplier) || 1;
|
|
276
|
+
const fmt = (n) => (Number.isFinite(n) ? String(Math.round(n * 100) / 100) : '?');
|
|
277
|
+
if (p.billing_type === 'official') {
|
|
278
|
+
const input = Number(p.input_price) * mult, output = Number(p.output_price) * mult;
|
|
279
|
+
return {
|
|
280
|
+
suffix: ` · $${fmt(input)}/$${fmt(output)}`,
|
|
281
|
+
...(Number.isFinite(input) && Number.isFinite(output)
|
|
282
|
+
? { cost: { input, output, cacheRead: 0, cacheWrite: 0 } }
|
|
283
|
+
: {}),
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
if (p.billing_type === 'times') {
|
|
287
|
+
const unit = p.price_unit === 'second' ? '分/秒' : '分/次';
|
|
288
|
+
return { suffix: ` · ${fmt(Number(p.input_price) * mult)}${unit}` };
|
|
289
|
+
}
|
|
290
|
+
if (p.billing_type === 'token') {
|
|
291
|
+
return { suffix: ` · ${fmt(Number(p.input_price) * mult)}/${fmt(Number(p.output_price) * mult)}分/M` };
|
|
292
|
+
}
|
|
293
|
+
if (p.billing_type === 'characters') return { suffix: ' · 按字符' };
|
|
294
|
+
return {};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** 单个模型 → pi-ai Model 描述符(workbuddy toPiModel 同款形状)。 */
|
|
298
|
+
function toPiModel(id, cap, providerId = PROVIDER, group) {
|
|
299
|
+
// cap.reasoning 缺省(分组专属模型未被 App 探测过)时按 id 惯例推断
|
|
300
|
+
const reasoning = typeof cap.reasoning === 'boolean' ? cap.reasoning : REASONING_HINT_RE.test(id);
|
|
301
|
+
const thinkingLevelMap = reasoning
|
|
302
|
+
? Object.fromEntries(THINKING_LEVELS.map((level) => [level, level in OPENAI_REASONING_EFFORTS ? level : null]))
|
|
303
|
+
: undefined;
|
|
304
|
+
const { suffix, cost } = priceInfo(id, group);
|
|
305
|
+
return {
|
|
306
|
+
id,
|
|
307
|
+
name: `${id}${suffix}`,
|
|
308
|
+
api: 'openai-completions',
|
|
309
|
+
provider: providerId,
|
|
310
|
+
baseUrl: OPENAI_BASE,
|
|
311
|
+
input: cap.vision ? ['text', 'image'] : ['text'],
|
|
312
|
+
...(cost ? { cost } : { cost: NO_COST }),
|
|
313
|
+
contextWindow: cap.contextWindow || DEFAULT_CONTEXT_WINDOW,
|
|
314
|
+
maxTokens: cap.maxOutputTokens || DEFAULT_MAX_TOKENS,
|
|
315
|
+
reasoning,
|
|
316
|
+
...(thinkingLevelMap ? { thinkingLevelMap } : {}),
|
|
317
|
+
compat: { supportsReasoningEffort: reasoning },
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* 解析 God Agent 本地 cap-cache.json。
|
|
323
|
+
* 结构:{ doc: { groups: { <group>: { caps: { <modelId>: {
|
|
324
|
+
* by_format: { openai: {…}, claude: {…} }, formats: 'openai,claude',
|
|
325
|
+
* context_window, max_output_tokens, reasoning, vision, … } } } } } }
|
|
326
|
+
* App 对每个模型×格式做过真实探测(by_format.openai.status),
|
|
327
|
+
* 只有 openai 格式探测通过的模型才走 openai-completions 路由。
|
|
328
|
+
*/
|
|
329
|
+
async function loadCapIndex() {
|
|
330
|
+
try {
|
|
331
|
+
const raw = JSON.parse(await readFile(GA_CAP_CACHE, 'utf8'));
|
|
332
|
+
const index = new Map();
|
|
333
|
+
for (const group of Object.values(raw?.doc?.groups ?? {})) {
|
|
334
|
+
for (const [modelId, cap] of Object.entries(group?.caps ?? {})) {
|
|
335
|
+
const openai = cap?.by_format?.openai ?? {};
|
|
336
|
+
const prev = index.get(modelId);
|
|
337
|
+
const entry = {
|
|
338
|
+
contextWindow: cap.context_window || prev?.contextWindow,
|
|
339
|
+
maxOutputTokens: cap.max_output_tokens || openai.max_output_tokens || prev?.maxOutputTokens,
|
|
340
|
+
reasoning: openai.reasoning ?? prev?.reasoning,
|
|
341
|
+
vision: openai.vision ?? prev?.vision,
|
|
342
|
+
formats: String(cap.formats ?? prev?.formats ?? ''),
|
|
343
|
+
openaiStatus: openai.status ?? prev?.openaiStatus,
|
|
344
|
+
};
|
|
345
|
+
// 同一模型在多个分组出现:任一分组 openai 探测 ok 即视为可用
|
|
346
|
+
if (prev?.openaiStatus === 'ok' && entry.openaiStatus !== 'ok') {
|
|
347
|
+
entry.openaiStatus = 'ok';
|
|
348
|
+
}
|
|
349
|
+
index.set(modelId, entry);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
return index;
|
|
353
|
+
} catch {
|
|
354
|
+
return new Map();
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** 该模型的 openai 格式可用(无探测数据时保守放行)。 */
|
|
359
|
+
function openaiFormatUsable(cap) {
|
|
360
|
+
if (!cap || Object.keys(cap).length === 0) return true;
|
|
361
|
+
if (cap.formats && !cap.formats.includes('openai')) return false;
|
|
362
|
+
if (cap.openaiStatus === 'error' || cap.openaiStatus === 'failed') return false;
|
|
363
|
+
return true;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** 把模型清单 + cap-cache 能力 + 用户选择,折成 pi-ai 模型档案。 */
|
|
367
|
+
function buildModelProfiles(rawIds, caps, config, group, providerId) {
|
|
368
|
+
const wanted = (liveValue(config.enabledModelIds) ?? []).filter(Boolean);
|
|
369
|
+
// 分组模型清单:'*' 表示账户级 /v1/models 全量;否则分组清单即权威(/v1/models 只反映 default 组)
|
|
370
|
+
const scope = Array.isArray(group?.models) && !group.models.includes('*') ? new Set(group.models) : null;
|
|
371
|
+
const profiles = [];
|
|
372
|
+
for (const id of scope ? [...scope] : rawIds) {
|
|
373
|
+
if (!id || typeof id !== 'string') continue;
|
|
374
|
+
if (NON_CHAT_RE.test(id)) continue;
|
|
375
|
+
if (wanted.length && !wanted.includes(id)) continue;
|
|
376
|
+
const cap = caps.get(id) ?? {};
|
|
377
|
+
// 探测数据来自 App(default key 探测),对分组专属模型不可靠:
|
|
378
|
+
// 仅在账户级目录('*')时用探测过滤;用户显式点名时以用户为准
|
|
379
|
+
if (!scope && !openaiFormatUsable(cap) && !(wanted.length && wanted.includes(id))) continue;
|
|
380
|
+
profiles.push(toPiModel(id, cap, providerId, group));
|
|
381
|
+
}
|
|
382
|
+
profiles.sort((a, b) => a.id.localeCompare(b.id));
|
|
383
|
+
return profiles;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
async function fetchModelIds(apiKey) {
|
|
387
|
+
const res = await fetch(`${OPENAI_BASE}/models`, {
|
|
388
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
389
|
+
signal: AbortSignal.timeout(20000),
|
|
390
|
+
});
|
|
391
|
+
if (!res.ok) throw new Error(`GET /v1/models -> HTTP ${res.status}`);
|
|
392
|
+
const body = await res.json();
|
|
393
|
+
const rows = body?.data ?? body?.models ?? [];
|
|
394
|
+
return rows.map((row) => row?.id).filter(Boolean);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
//#endregion
|
|
398
|
+
//#region pi-ai 认证桩(本路由没有 pi-ai 自己的凭据生命周期)
|
|
399
|
+
|
|
400
|
+
const INERT_AUTH = {
|
|
401
|
+
credentials: {
|
|
402
|
+
async read() { return undefined; },
|
|
403
|
+
async list() { return []; },
|
|
404
|
+
async modify() {
|
|
405
|
+
throw new Error('dsh-connect-godagent: 本路由没有 pi-ai 凭据生命周期');
|
|
406
|
+
},
|
|
407
|
+
async delete() {
|
|
408
|
+
throw new Error('dsh-connect-godagent: 本路由没有 pi-ai 凭据生命周期');
|
|
409
|
+
},
|
|
410
|
+
},
|
|
411
|
+
async authContextEnv() { return undefined; },
|
|
412
|
+
authContext: {
|
|
413
|
+
async env() { return undefined; },
|
|
414
|
+
async fileExists() { return false; },
|
|
415
|
+
},
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
//#endregion
|
|
419
|
+
//#region 插件配置
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* DSH 设置页只展示 volatile 字段:dsh-settings 的 volatileForm(schema) 会丢弃一切
|
|
423
|
+
* 未标 meta.volatile 的标量字段(嵌套 object 除外),全标量 Config 的 namespace 会
|
|
424
|
+
* 从 settings.describe() 整个消失,浏览器端表现为"等待宿主配置就绪…"。
|
|
425
|
+
* WorkBuddy 的同款做法:每个设置页字段都包 asVolatile()。
|
|
426
|
+
* 代价(已知并已处理):volatile-only 的配置变更不会重载插件(cordis-plugin-loader
|
|
427
|
+
* 的 volatileOnly 判断),apply 不重跑——宿主侧由 startConfigWatch() 每 60s 比对
|
|
428
|
+
* 配置指纹,变化即重建模型目录并重新注册,弥补无重载的影响。
|
|
429
|
+
*/
|
|
430
|
+
/** schemastery .volatile() 包装:字段标 meta.volatile 后才会出现在 DSH 设置页(见 Config 注释)。 */
|
|
431
|
+
function volatile(schema) {
|
|
432
|
+
if (typeof schema.volatile === 'function') return schema.volatile();
|
|
433
|
+
return schema;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** volatile 字段 resolve 后是 {get()} live reference,读取处统一解引用;普通值原样返回。 */
|
|
437
|
+
export function liveValue(value) {
|
|
438
|
+
return value !== null && typeof value === 'object' && typeof value.get === 'function' ? value.get() : value;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
export const Config = z.object({
|
|
442
|
+
enabled: volatile(z.boolean().default(true)).description('启用 God Agent (gptgod) 模型接入'),
|
|
443
|
+
apiKey: volatile(z.string().default('').role('secret'))
|
|
444
|
+
.description('gptgod API Key(sk-…),仅用于 default 分组;其余分组自动创建专用 key。留空全部自动'),
|
|
445
|
+
enabledGroups: volatile(z.array(z.string()).default([]))
|
|
446
|
+
.description('启用的分组 code,每个分组一个独立模型清单与计费倍率(留空 = 仅 default)。如 cc-cheap(0.4×)、codex(0.3×)、aws-vip(5×)'),
|
|
447
|
+
enabledModelIds: volatile(z.array(z.string()).default([]))
|
|
448
|
+
.description('只启用这些模型 id(留空 = 自动接入全部聊天模型,跨所有启用分组生效)'),
|
|
449
|
+
refreshMinutes: volatile(z.number().step(1).min(5).default(30))
|
|
450
|
+
.description('模型目录刷新周期(分钟)'),
|
|
451
|
+
}).description('God Agent (gptgod) 接入设置');
|
|
452
|
+
|
|
453
|
+
/** cordis 服务依赖:llm 服务由 @deepseek-ai/dsh-llm 提供,未声明会报 "cannot get property llm without inject"。 */
|
|
454
|
+
export const inject = ['llm'];
|
|
455
|
+
export const name = PLUGIN_ID;
|
|
456
|
+
|
|
457
|
+
//#endregion
|
|
458
|
+
//#region 入口
|
|
459
|
+
|
|
460
|
+
export async function apply(ctx, config) {
|
|
461
|
+
// 注意:volatile 字段运行时可变且不触发插件重载,不能在 apply 里读一次就定终身。
|
|
462
|
+
// enabled 的启停由下方 syncCatalog/巡检动态处理(false = 注销全部 provider)。
|
|
463
|
+
|
|
464
|
+
const settingsNs = ctx.fiber?.entry?.options?.id ?? PLUGIN_ID;
|
|
465
|
+
const state = await loadState();
|
|
466
|
+
|
|
467
|
+
/** 每个 provider 一条:{providerId, group, models(pi-ai), discovery[]};目录刷新时整体替换。 */
|
|
468
|
+
let currentEntries = [];
|
|
469
|
+
/** PiAiAdapter 快照:providerId → resolved profile(含各组分组的 piProvider)。 */
|
|
470
|
+
let currentProfiles = new Map();
|
|
471
|
+
|
|
472
|
+
const providerIdOf = (code) => (code === 'default' ? PROVIDER : `${PROVIDER}:${code}`);
|
|
473
|
+
const displayNameOf = (group) => {
|
|
474
|
+
const base = `${DISPLAY_NAME} · ${group.name || group.code}`;
|
|
475
|
+
const mult = Number(group.multiplier ?? 1);
|
|
476
|
+
return Number.isFinite(mult) && mult !== 1 ? `${base} (${mult}×)` : base;
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
/** 由分组清单重建全部 provider(每个分组一个 pi-ai Provider + 独立 API key)。 */
|
|
480
|
+
const rebuildProfiles = (entries) => {
|
|
481
|
+
currentEntries = entries;
|
|
482
|
+
currentProfiles = new Map();
|
|
483
|
+
for (const entry of entries) {
|
|
484
|
+
const piProvider = createProvider({
|
|
485
|
+
id: entry.providerId,
|
|
486
|
+
name: entry.displayName,
|
|
487
|
+
baseUrl: OPENAI_BASE,
|
|
488
|
+
auth: {
|
|
489
|
+
apiKey: {
|
|
490
|
+
name: 'gptgod API Key',
|
|
491
|
+
async resolve() {
|
|
492
|
+
const key = entry.apiKey ?? liveValue(config.apiKey) ?? undefined;
|
|
493
|
+
if (!key) return undefined;
|
|
494
|
+
return { auth: { apiKey: key }, source: PLUGIN_ID };
|
|
495
|
+
},
|
|
496
|
+
},
|
|
497
|
+
},
|
|
498
|
+
models: entry.profiles,
|
|
499
|
+
api: openAICompletionsApi(),
|
|
500
|
+
});
|
|
501
|
+
currentProfiles.set(entry.providerId, {
|
|
502
|
+
provider: entry.providerId,
|
|
503
|
+
displayName: entry.displayName,
|
|
504
|
+
piProvider,
|
|
505
|
+
streamIdleTimeoutMs: 300_000,
|
|
506
|
+
retryPolicy: resolveRetryPolicy(undefined, `${PLUGIN_ID} retryPolicy`),
|
|
507
|
+
configuredMaxTokens: new Map(),
|
|
508
|
+
modelErrors: new Map(),
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
const discoveryOf = (providerId) =>
|
|
514
|
+
currentEntries.find((e) => e.providerId === providerId)?.discovery ?? [];
|
|
515
|
+
|
|
516
|
+
/** 拉一次目录并落到 profiles;会话/密钥失败时保留旧目录并抛错。 */
|
|
517
|
+
const refreshCatalog = async () => {
|
|
518
|
+
const { cookieHeader } = await ensureSession(state);
|
|
519
|
+
|
|
520
|
+
// 分组清单(公开接口):config.enabledGroups 为空时仅 default
|
|
521
|
+
const allGroups = await loadGroups(state);
|
|
522
|
+
const wantedCodes = ((liveValue(config.enabledGroups) ?? []).length ? liveValue(config.enabledGroups) : ['default'])
|
|
523
|
+
.map((c) => String(c).trim()).filter(Boolean);
|
|
524
|
+
const knownCodes = new Set(allGroups.map((g) => g.code));
|
|
525
|
+
const unknown = wantedCodes.filter((c) => !knownCodes.has(c));
|
|
526
|
+
if (unknown.length) {
|
|
527
|
+
ctx.logger?.warn?.(`[${PLUGIN_ID}] 未知分组已忽略: ${unknown.join(', ')}(可用: ${[...knownCodes].slice(0, 8).join(', ')}…)`);
|
|
528
|
+
}
|
|
529
|
+
const enabledCodes = wantedCodes.filter((c) => knownCodes.has(c));
|
|
530
|
+
if (!enabledCodes.includes('default')) enabledCodes.unshift('default'); // default 永远保留
|
|
531
|
+
|
|
532
|
+
// /v1/models 是账户级目录:default 组 key 拉一次即可
|
|
533
|
+
const modelIdsKey = await ensureApiKey(state, cookieHeader, config, 'default');
|
|
534
|
+
const [ids, caps] = [await fetchModelIds(modelIdsKey), await loadCapIndex()];
|
|
535
|
+
|
|
536
|
+
const entries = [];
|
|
537
|
+
for (const group of enabledCodes.map((code) => allGroups.find((g) => g.code === code))) {
|
|
538
|
+
const apiKey = await ensureApiKey(state, cookieHeader, config, group.code);
|
|
539
|
+
const profiles = buildModelProfiles(ids, caps, config, group, providerIdOf(group.code));
|
|
540
|
+
entries.push({
|
|
541
|
+
providerId: providerIdOf(group.code),
|
|
542
|
+
group,
|
|
543
|
+
apiKey,
|
|
544
|
+
profiles,
|
|
545
|
+
discovery: profiles.map((m) => ({
|
|
546
|
+
id: m.id,
|
|
547
|
+
name: m.name,
|
|
548
|
+
...(m.contextWindow ? { contextWindow: m.contextWindow } : {}),
|
|
549
|
+
...(m.maxTokens ? { maxTokens: m.maxTokens } : {}),
|
|
550
|
+
...(m.input ? { inputModalities: m.input } : {}),
|
|
551
|
+
})),
|
|
552
|
+
displayName: displayNameOf(group),
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
// 按倍率升序注册:模型选择器按目录顺序排列 provider,搜索同名模型时
|
|
556
|
+
// 首个命中(回车直选的行)落在最便宜的分组上,避免总是命中 default(1×)
|
|
557
|
+
entries.sort((a, b) =>
|
|
558
|
+
Number(a.group.multiplier ?? 1) - Number(b.group.multiplier ?? 1)
|
|
559
|
+
|| (a.group.code === 'default' ? -1 : b.group.code === 'default' ? 1 : a.group.code.localeCompare(b.group.code)));
|
|
560
|
+
rebuildProfiles(entries);
|
|
561
|
+
await saveState(state);
|
|
562
|
+
return entries;
|
|
563
|
+
};
|
|
564
|
+
|
|
565
|
+
const adapter = new PiAiAdapter({
|
|
566
|
+
profiles: () => currentProfiles,
|
|
567
|
+
resolveApiKey: async (provider) => {
|
|
568
|
+
const entry = currentEntries.find((e) => e.providerId === provider);
|
|
569
|
+
return entry?.apiKey ?? state.apiKey ?? liveValue(config.apiKey) ?? undefined;
|
|
570
|
+
},
|
|
571
|
+
auth: INERT_AUTH,
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
/** 当前注册句柄;重注册前先全部释放,避免 "already registered"。 */
|
|
575
|
+
let releases = [];
|
|
576
|
+
const releaseAll = () => {
|
|
577
|
+
releases.splice(0).forEach((release) => {
|
|
578
|
+
try { release(); } catch {}
|
|
579
|
+
});
|
|
580
|
+
};
|
|
581
|
+
|
|
582
|
+
/** 把目录挂上 llm 服务;disabled=true 时全部注销(设置页开关关闭态)。 */
|
|
583
|
+
const registerAll = (disabled = false) => {
|
|
584
|
+
releaseAll();
|
|
585
|
+
if (disabled) return;
|
|
586
|
+
// currentProfiles.keys() 已含 default 组的 'godagent';Set 去重避免 "already registered"
|
|
587
|
+
releases.push(ctx.llm.registerAdapter([...new Set([PROVIDER, ...currentProfiles.keys()])], adapter));
|
|
588
|
+
releases.push(ctx.llm.registerConfigurableProviders(currentEntries.length
|
|
589
|
+
? currentEntries.map((entry) => ({
|
|
590
|
+
provider: entry.providerId,
|
|
591
|
+
displayName: entry.displayName,
|
|
592
|
+
settingsNs,
|
|
593
|
+
settingsPath: [],
|
|
594
|
+
declared: false,
|
|
595
|
+
}))
|
|
596
|
+
: [{
|
|
597
|
+
provider: PROVIDER,
|
|
598
|
+
displayName: DISPLAY_NAME,
|
|
599
|
+
settingsNs,
|
|
600
|
+
settingsPath: [],
|
|
601
|
+
declared: false,
|
|
602
|
+
}]));
|
|
603
|
+
releases.push(ctx.llm.registerModelDiscovery(settingsNs, async (request, signal) => {
|
|
604
|
+
if (!currentEntries.length) {
|
|
605
|
+
try { await refreshCatalog(); } catch {} // 兜底重试,失败则交空
|
|
606
|
+
}
|
|
607
|
+
signal?.throwIfAborted?.();
|
|
608
|
+
const provider = request?.provider;
|
|
609
|
+
if (provider) return discoveryOf(provider);
|
|
610
|
+
// 未指明 provider:返回 default 组的目录
|
|
611
|
+
return discoveryOf(PROVIDER);
|
|
612
|
+
}));
|
|
613
|
+
};
|
|
614
|
+
|
|
615
|
+
/** 同步目录:enabled=false 时注销全部 provider,否则拉目录并挂载。 */
|
|
616
|
+
const syncCatalog = async () => {
|
|
617
|
+
if (liveValue(config.enabled) === false) {
|
|
618
|
+
rebuildProfiles([]);
|
|
619
|
+
registerAll(true);
|
|
620
|
+
ctx.logger?.info?.(`[${PLUGIN_ID}] 已停用(设置页可重新开启)`);
|
|
621
|
+
return [];
|
|
622
|
+
}
|
|
623
|
+
const entries = await refreshCatalog();
|
|
624
|
+
registerAll(false);
|
|
625
|
+
return entries;
|
|
626
|
+
};
|
|
627
|
+
|
|
628
|
+
// 启动即同步;失败不阻塞挂载(保留空目录,discovery 兜底再试)。
|
|
629
|
+
let firstError;
|
|
630
|
+
try {
|
|
631
|
+
await syncCatalog();
|
|
632
|
+
} catch (error) {
|
|
633
|
+
firstError = error;
|
|
634
|
+
rebuildProfiles([]);
|
|
635
|
+
registerAll(false);
|
|
636
|
+
ctx.logger?.warn?.(`[${PLUGIN_ID}] 启动目录拉取失败(稍后自动重试): ${error.message}`);
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// 周期刷新目录(模型上下线跟随 App)。
|
|
640
|
+
const refreshTimer = setInterval(() => {
|
|
641
|
+
syncCatalog().catch((error) => {
|
|
642
|
+
ctx.logger?.debug?.(`[${PLUGIN_ID}] 目录刷新失败: ${error.message}`);
|
|
643
|
+
});
|
|
644
|
+
}, Math.max(5, liveValue(config.refreshMinutes) ?? 30) * 60_000);
|
|
645
|
+
refreshTimer.unref?.();
|
|
646
|
+
|
|
647
|
+
// volatile-only 的配置变更不会重载插件(apply 不重跑,见 Config 注释),这里
|
|
648
|
+
// 每 60s 比对一次配置指纹,变化即重新同步目录:开关/分组/白名单最迟 60s 生效。
|
|
649
|
+
const configFingerprint = () => JSON.stringify([
|
|
650
|
+
liveValue(config.enabled),
|
|
651
|
+
liveValue(config.enabledGroups),
|
|
652
|
+
liveValue(config.enabledModelIds),
|
|
653
|
+
liveValue(config.refreshMinutes),
|
|
654
|
+
]);
|
|
655
|
+
let fingerprint = configFingerprint();
|
|
656
|
+
const watchTimer = setInterval(() => {
|
|
657
|
+
let next;
|
|
658
|
+
try { next = configFingerprint(); } catch { return; }
|
|
659
|
+
if (next === fingerprint) return;
|
|
660
|
+
fingerprint = next;
|
|
661
|
+
ctx.logger?.info?.(`[${PLUGIN_ID}] 检测到配置变更,重建模型目录…`);
|
|
662
|
+
syncCatalog().catch((error) => {
|
|
663
|
+
ctx.logger?.warn?.(`[${PLUGIN_ID}] 配置变更后的目录重建失败: ${error.message}`);
|
|
664
|
+
});
|
|
665
|
+
}, 60_000);
|
|
666
|
+
watchTimer.unref?.();
|
|
667
|
+
|
|
668
|
+
ctx.on('dispose', () => {
|
|
669
|
+
clearInterval(refreshTimer);
|
|
670
|
+
clearInterval(watchTimer);
|
|
671
|
+
releaseAll();
|
|
672
|
+
});
|
|
673
|
+
|
|
674
|
+
const summary = currentEntries
|
|
675
|
+
.map((e) => `${e.group.code}=${e.profiles.length}`)
|
|
676
|
+
.join(', ');
|
|
677
|
+
ctx.logger?.info?.(`[${PLUGIN_ID}] 已挂载分组模型 ${currentEntries.reduce((n, e) => n + e.profiles.length, 0)} 个(${summary})` +
|
|
678
|
+
(firstError ? `(启动时目录拉取失败: ${firstError.message})` : ''));
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
//#endregion
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-connect-godagent",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "把本机登录的 God Agent 桌面 App(gptgod.online)模型接入 DSH:复用其会话凭据自动创建/复用 API Key,注册 OpenAI 兼容模型目录,展示分组倍率。",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "lib/index.js",
|
|
7
|
+
"platform": "web",
|
|
8
|
+
"license": "MIT",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": "./lib/index.js",
|
|
11
|
+
"./client": "./lib/client.js",
|
|
12
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
13
|
+
"./package.json": "./package.json"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"lib",
|
|
17
|
+
"cordis.patch.yml",
|
|
18
|
+
"README.md"
|
|
19
|
+
],
|
|
20
|
+
"dsh": {
|
|
21
|
+
"bundle": {
|
|
22
|
+
"patch": "./cordis.patch.yml"
|
|
23
|
+
},
|
|
24
|
+
"client": {
|
|
25
|
+
"platform": "web",
|
|
26
|
+
"inject": [
|
|
27
|
+
"@deepseek-ai/dsh-client-ui-settings",
|
|
28
|
+
"@deepseek-ai/dsh-client-ui-slots",
|
|
29
|
+
"remote",
|
|
30
|
+
"remote.settings"
|
|
31
|
+
]
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"@deepseek-ai/cordis": ">=4.1.0",
|
|
36
|
+
"@deepseek-ai/cordis-plugin-loader": ">=1.1.0",
|
|
37
|
+
"@deepseek-ai/dsh-llm": ">=0.2.2-rc.1",
|
|
38
|
+
"@deepseek-ai/dsh-llm-pi-ai": ">=0.2.2-rc.1",
|
|
39
|
+
"@earendil-works/pi-ai": ">=1.5.2",
|
|
40
|
+
"@deepseek-ai/schemastery": ">=3.19.0"
|
|
41
|
+
},
|
|
42
|
+
"repository": {
|
|
43
|
+
"type": "git",
|
|
44
|
+
"url": "https://github.com/atorber/dsh-connect-godagent.git"
|
|
45
|
+
},
|
|
46
|
+
"homepage": "https://github.com/atorber/dsh-connect-godagent#readme",
|
|
47
|
+
"keywords": [
|
|
48
|
+
"dsh",
|
|
49
|
+
"deepseek-harness",
|
|
50
|
+
"dsh-plugin",
|
|
51
|
+
"gptgod",
|
|
52
|
+
"god-agent"
|
|
53
|
+
]
|
|
54
|
+
}
|