dsh-apis-plugin 0.3.1 → 0.4.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/README.md +23 -1
- package/api-tools.js +16 -2
- package/client.js +132 -1
- package/cordis.patch.yml +3 -0
- package/package.json +2 -1
- package/rest-server.js +492 -0
package/README.md
CHANGED
|
@@ -70,6 +70,8 @@ apis=
|
|
|
70
70
|
|
|
71
71
|
### Web UI(设置 → 接口管理)
|
|
72
72
|
|
|
73
|
+

|
|
74
|
+
|
|
73
75
|
| 操作 | 说明 |
|
|
74
76
|
|---|---|
|
|
75
77
|
| API配置 | 填集合父目录,失焦或回车自动保存 |
|
|
@@ -86,16 +88,36 @@ apis=
|
|
|
86
88
|
- path 默认写接口路径(如 `/users/page`);**跨集合同名接口用「集合名/路径」消歧**(如 `site-a.example.com/users/page`)
|
|
87
89
|
- 安全机制:`DELETE` 需二次确认(首次只返回确认提示,确认后带 `confirm=true` 再调);写操作返回结果附带警告块
|
|
88
90
|
|
|
91
|
+
### 开放接口(REST API,默认 3088)
|
|
92
|
+
|
|
93
|
+
插件自带一个 REST 服务,封装常用的与 DSH 交互的 API,兼容 OpenAI 风格。**浏览器访问 `http://localhost:3088/` 即可查看在线接口文档**(各端点参数与 curl 示例);「设置 → 开放接口」页可调整服务开关与端口。完全开放、无鉴权,建议仅内网使用。
|
|
94
|
+
|
|
95
|
+
| 端点 | 用途 |
|
|
96
|
+
|---|---|
|
|
97
|
+
| `POST /v1/chat/completions` | OpenAI 兼容对话补全;`stream: true` 走 SSE 流式;`session_id` 可续接会话多轮;支持 `image_url` / `file` 部件上传图片(png/jpeg/webp/gif,data URL 或 http 地址)与文件(base64 data URL);`model` 自由填写(`provider/model` 或纯模型名,不做网关目录校验),缺省用 DSH 当前默认模型 |
|
|
98
|
+
| `POST /ask` | 简易任务:`{task, model?, session_id?}` → `{answer, sessionId, status}` |
|
|
99
|
+
| `GET /` | 在线接口文档(浏览器直接访问) |
|
|
100
|
+
| `GET /v1/models` | OpenAI 兼容模型列表(已注册 provider 的模型目录,仅供参考) |
|
|
101
|
+
| `GET /sessions` / `GET /sessions/:id` | 会话列表 / 详情 |
|
|
102
|
+
| `GET /health` | 健康检查 |
|
|
103
|
+
|
|
104
|
+
```sh
|
|
105
|
+
curl -X POST http://localhost:3088/v1/chat/completions \
|
|
106
|
+
-H "Content-Type: application/json" \
|
|
107
|
+
-d '{"messages":[{"role":"user","content":"你好"}]}'
|
|
108
|
+
```
|
|
109
|
+
|
|
89
110
|
## 排查
|
|
90
111
|
|
|
91
112
|
dsh 控制台日志:
|
|
92
113
|
|
|
93
114
|
```
|
|
94
|
-
[dsh-apis-plugin] loaded; apiDir=/path/to/config, endpoints=N, collections=a.com,b.com
|
|
115
|
+
[dsh-apis-plugin] loaded; apiDir=/path/to/config, endpoints=N, collections=a.com,b.com, rest=on:3088
|
|
95
116
|
```
|
|
96
117
|
|
|
97
118
|
- `endpoints=0`:检查 apiDir 是否正确、其下是否有含 apis 的 `*.cfg`
|
|
98
119
|
- 列表与 cfg 不一致:点「扫描」或重启
|
|
120
|
+
- `rest=on:3088` 但接口不通:端口被占用时 listen 会失败,看控制台 `server error` 日志;改端口请到「设置 → 开放接口」(模型不在此配置,接口 `model` 参数缺省用 DSH 当前默认模型)
|
|
99
121
|
|
|
100
122
|
## License
|
|
101
123
|
|
package/api-tools.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import { readFileSync, writeFileSync, readdirSync } from 'node:fs'
|
|
7
7
|
import { join, dirname, basename } from 'node:path'
|
|
8
8
|
import Schema from '@deepseek-ai/schemastery'
|
|
9
|
+
import { createRestServer } from './rest-server.js'
|
|
9
10
|
|
|
10
11
|
// 读取 cfg 文件(key=value 行,# 注释):host 为集合标识;baseUrl 为服务前缀;
|
|
11
12
|
// apis 为接口列表,支持逗号分隔同行书写,或 apis= 下面逐行一个接口
|
|
@@ -140,9 +141,11 @@ export function defineApiPlugin(options) {
|
|
|
140
141
|
baseUrl: Schema.string().default(defaultBaseUrl), // 接口服务前缀(路径本身已含服务前缀)
|
|
141
142
|
scanToken: Schema.string().default('').volatile(), // 内部字段:客户端「扫描」按钮改写它触发配置变更重应用
|
|
142
143
|
collections: Schema.string().default('').volatile(), // 内部字段:扫描到的集合 JSON [{name, baseUrl, apis}],客户端只读展示
|
|
144
|
+
restEnable: Schema.boolean().default(true), // 开放接口(REST)服务开关,变更自动重应用起停
|
|
145
|
+
restPort: Schema.number().default(3088), // 开放接口(REST)服务端口,默认 3088
|
|
143
146
|
})
|
|
144
147
|
|
|
145
|
-
const inject = ['tools', 'settings']
|
|
148
|
+
const inject = ['tools', 'settings', 'agents', 'sessions', 'agentDefaultModel']
|
|
146
149
|
|
|
147
150
|
function apply(ctx, config) {
|
|
148
151
|
const prefix = config.toolPrefix || toolPrefix
|
|
@@ -200,6 +203,17 @@ export function defineApiPlugin(options) {
|
|
|
200
203
|
}
|
|
201
204
|
}), `${ns}: volatile rescan`)
|
|
202
205
|
|
|
206
|
+
// REST 开放接口服务(默认 3088):封装与 DSH 交互的常用 API(OpenAI 风格 /v1/chat/completions、/ask、会话查询)。
|
|
207
|
+
// 开关/端口为普通配置字段,变更触发重应用,这里经 effect 起停(旧连接排空后关闭)
|
|
208
|
+
if (config.restEnable !== false) {
|
|
209
|
+
const restServer = createRestServer({ ctx, log: (msg) => console.error(`[${ns}] ${msg}`) })
|
|
210
|
+
ctx.effect(() => {
|
|
211
|
+
restServer.listen(config.restPort)
|
|
212
|
+
console.log(`[${ns}] rest server listening on :${config.restPort}`)
|
|
213
|
+
return () => new Promise((resolve) => restServer.close(() => resolve()))
|
|
214
|
+
}, `${ns}: rest server`)
|
|
215
|
+
}
|
|
216
|
+
|
|
203
217
|
// 已配置接口目录(按集合分组展示,title 说明集合用途;部署侧静态接口不在任何集合时单独一组)
|
|
204
218
|
function catalogText() {
|
|
205
219
|
const groups = collections.map((c) =>
|
|
@@ -309,7 +323,7 @@ export function defineApiPlugin(options) {
|
|
|
309
323
|
},
|
|
310
324
|
})
|
|
311
325
|
|
|
312
|
-
console.log(`[${ns}] loaded; apiDir=${val(config.apiDir) || '(未配置)'}, endpoints=${mergedEndpoints(collections).length}, collections=${collections.map((c) => c.name).join(',') || '(无)'}`)
|
|
326
|
+
console.log(`[${ns}] loaded; apiDir=${val(config.apiDir) || '(未配置)'}, endpoints=${mergedEndpoints(collections).length}, collections=${collections.map((c) => c.name).join(',') || '(无)'}, rest=${config.restEnable !== false ? `on:${config.restPort}` : 'off'}`)
|
|
313
327
|
}
|
|
314
328
|
|
|
315
329
|
return { Config, inject, apply }
|
package/client.js
CHANGED
|
@@ -33,6 +33,17 @@ window.__ModuleLoader__.load({
|
|
|
33
33
|
.apis-groupHead:hover{background:var(--dsw-alias-bg-layer-2)}
|
|
34
34
|
.apis-groupName{flex:1;min-width:0;font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
35
35
|
.apis-groupBody{border-top:.5px solid var(--dsw-alias-border-l2);padding:8px 10px;display:grid;gap:8px}
|
|
36
|
+
.apis-toggle{flex:none;position:relative;width:34px;height:20px;border-radius:10px;border:0;cursor:pointer;background:var(--dsw-alias-border-l3);transition:background .16s;padding:0}
|
|
37
|
+
.apis-toggle[data-on="1"]{background:#1a7f37}
|
|
38
|
+
.apis-toggle::after{content:"";position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .16s}
|
|
39
|
+
.apis-toggle[data-on="1"]::after{transform:translateX(14px)}
|
|
40
|
+
.apis-method{flex:none;font-size:11px;font-weight:600;line-height:1;padding:3px 6px;border-radius:4px;font-family:ui-monospace,Consolas,monospace}
|
|
41
|
+
.apis-method[data-m="GET"]{background:#e6f4ea;color:#1a7f37}
|
|
42
|
+
.apis-method[data-m="POST"]{background:#fff1e0;color:#b25e00}
|
|
43
|
+
.apis-path{flex:1;min-width:0;font-family:ui-monospace,Consolas,monospace;font-size:13px;color:var(--dsw-alias-label-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
44
|
+
.apis-doc{display:grid;gap:8px}
|
|
45
|
+
.apis-docDesc{font-size:13px;color:var(--dsw-alias-label-tertiary);line-height:1.6}
|
|
46
|
+
.apis-code{font-family:ui-monospace,Consolas,monospace;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2);border-radius:8px;padding:8px 10px;white-space:pre-wrap;word-break:break-all;user-select:all}
|
|
36
47
|
`;
|
|
37
48
|
if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=dsh-apis-plugin]") === null) {
|
|
38
49
|
const tag = document.createElement("style");
|
|
@@ -174,10 +185,124 @@ window.__ModuleLoader__.load({
|
|
|
174
185
|
] });
|
|
175
186
|
}
|
|
176
187
|
|
|
188
|
+
/** 开放接口(REST)文档条目:方法徽标 + 路径 + 说明 + curl 示例 */
|
|
189
|
+
const REST_DOCS = [
|
|
190
|
+
{
|
|
191
|
+
method: "POST", path: "/v1/chat/completions",
|
|
192
|
+
desc: "OpenAI 兼容对话补全。body:messages(必填,[{role, content}])、model(可选,自由填写 \"provider/model\" 或纯模型名,缺省用 DSH 当前默认模型)、stream(true 走 SSE 流式)、session_id(可选,传则续接该会话多轮对话)。支持图片与文件部件:{\"type\":\"image_url\",\"image_url\":{\"url\":\"data:image/png;base64,…\"}}(png/jpeg/webp/gif,data URL 或 http 地址)、{\"type\":\"file\",\"file\":{\"filename\":\"报告.pdf\",\"file_data\":\"data:application/pdf;base64,…\"}}。",
|
|
193
|
+
curl: (b) => `curl -X POST ${b}/v1/chat/completions \\\n -H "Content-Type: application/json" \\\n -d '{"messages":[{"role":"user","content":[{"type":"text","text":"这张图里是什么?"},{"type":"image_url","image_url":{"url":"data:image/png;base64,iVBOR…"}}]}]}'`,
|
|
194
|
+
},
|
|
195
|
+
{
|
|
196
|
+
method: "POST", path: "/ask",
|
|
197
|
+
desc: "简易任务接口。body:task(必填)、model(可选,自由填写,规则同 chat/completions)、session_id(可选)。返回 { answer, sessionId, status }。",
|
|
198
|
+
curl: (b) => `curl -X POST ${b}/ask \\\n -H "Content-Type: application/json" \\\n -d '{"task":"运行一下测试并总结结果"}'`,
|
|
199
|
+
},
|
|
200
|
+
{
|
|
201
|
+
method: "GET", path: "/v1/models",
|
|
202
|
+
desc: "OpenAI 兼容模型列表:枚举已注册 provider 的模型目录(仅供参考,model 参数可自由填写任意 provider/model,不限于列表)。",
|
|
203
|
+
curl: (b) => `curl ${b}/v1/models`,
|
|
204
|
+
},
|
|
205
|
+
{
|
|
206
|
+
method: "GET", path: "/sessions",
|
|
207
|
+
desc: "会话列表(含活跃与已持久化),返回 id、cwd、createdAt、live、persisted。",
|
|
208
|
+
curl: (b) => `curl ${b}/sessions`,
|
|
209
|
+
},
|
|
210
|
+
{
|
|
211
|
+
method: "GET", path: "/sessions/:id",
|
|
212
|
+
desc: "会话详情:header 与当前模型可见面的事件流。",
|
|
213
|
+
curl: (b) => `curl ${b}/sessions/<sessionId>`,
|
|
214
|
+
},
|
|
215
|
+
{
|
|
216
|
+
method: "GET", path: "/health",
|
|
217
|
+
desc: "健康检查,返回 { ok, model }。",
|
|
218
|
+
curl: (b) => `curl ${b}/health`,
|
|
219
|
+
},
|
|
220
|
+
];
|
|
221
|
+
|
|
222
|
+
function OpenApiSection() {
|
|
223
|
+
const state = react.useSyncExternalStore(store.subscribe, store.getSnapshot);
|
|
224
|
+
const [portDraft, setPortDraft] = react.useState(null); // 端口草稿,null 表示未编辑
|
|
225
|
+
const [openDocs, setOpenDocs] = react.useState({}); // 文档条目展开态(key: path)
|
|
226
|
+
const ready = state.status === "ready" && state.writable;
|
|
227
|
+
|
|
228
|
+
const enabled = state.value?.restEnable !== false;
|
|
229
|
+
const savedPort = Number(state.value?.restPort ?? 3088);
|
|
230
|
+
const shownPort = portDraft ?? String(savedPort);
|
|
231
|
+
const base = `${location.protocol}//${location.hostname}:${savedPort}`;
|
|
232
|
+
|
|
233
|
+
/** 端口失焦/回车保存:合法才落盘,配置变更会自动重应用并重启 REST 服务 */
|
|
234
|
+
async function savePort() {
|
|
235
|
+
const n = parseInt(shownPort, 10);
|
|
236
|
+
setPortDraft(null);
|
|
237
|
+
if (!ready || !form || !Number.isInteger(n) || n < 1 || n > 65535 || n === savedPort) return;
|
|
238
|
+
try {
|
|
239
|
+
await form.set("restPort", n);
|
|
240
|
+
} catch {
|
|
241
|
+
// 写入被拒时静默结束
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function toggleEnable() {
|
|
246
|
+
if (!ready || !form) return;
|
|
247
|
+
try {
|
|
248
|
+
await form.set("restEnable", !enabled);
|
|
249
|
+
} catch {
|
|
250
|
+
// 写入被拒时静默结束
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const doc = (d) => {
|
|
255
|
+
const isOpen = !!openDocs[d.path];
|
|
256
|
+
return jsxs("div", { className: "apis-group", children: [
|
|
257
|
+
jsxs("button", {
|
|
258
|
+
type: "button", className: "apis-groupHead", "aria-expanded": isOpen,
|
|
259
|
+
onClick: () => setOpenDocs((m) => ({ ...m, [d.path]: !m[d.path] })),
|
|
260
|
+
children: [
|
|
261
|
+
jsx(Chevron, { open: isOpen }),
|
|
262
|
+
jsx("span", { className: "apis-method", "data-m": d.method, children: d.method }),
|
|
263
|
+
jsx("span", { className: "apis-path", title: d.path, children: d.path }),
|
|
264
|
+
],
|
|
265
|
+
}),
|
|
266
|
+
isOpen && jsxs("div", { className: "apis-groupBody apis-doc", children: [
|
|
267
|
+
jsx("span", { className: "apis-docDesc", children: d.desc }),
|
|
268
|
+
jsx("pre", { className: "apis-code", children: d.curl(base) }),
|
|
269
|
+
] }),
|
|
270
|
+
] });
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
return jsxs("div", { className: "apis-section", children: [
|
|
274
|
+
jsxs("div", { className: "apis-row", children: [
|
|
275
|
+
jsx("div", { className: "apis-label", children: "启用服务" }),
|
|
276
|
+
jsx("button", {
|
|
277
|
+
type: "button", className: "apis-toggle", "data-on": enabled ? "1" : "0",
|
|
278
|
+
"aria-label": "启用开放接口服务", disabled: !ready, onClick: toggleEnable,
|
|
279
|
+
}),
|
|
280
|
+
jsx("div", { className: "apis-headText", children:
|
|
281
|
+
jsx("span", { className: "apis-desc", children: "REST 服务封装常用的与 DSH 交互的 API,兼容 OpenAI 风格;完全开放、无鉴权,建议仅内网使用" }),
|
|
282
|
+
}),
|
|
283
|
+
] }),
|
|
284
|
+
jsxs("div", { className: "apis-row", children: [
|
|
285
|
+
jsx("div", { className: "apis-label", children: "端口" }),
|
|
286
|
+
jsx("input", {
|
|
287
|
+
value: shownPort, disabled: !ready,
|
|
288
|
+
onChange: (e) => setPortDraft(e.target.value),
|
|
289
|
+
onBlur: savePort,
|
|
290
|
+
onKeyDown: (e) => e.key === "Enter" && e.currentTarget.blur(),
|
|
291
|
+
className: "apis-input", inputMode: "numeric", style: { maxWidth: 160 },
|
|
292
|
+
}),
|
|
293
|
+
enabled && jsx("span", { className: "apis-text", style: { border: "none", padding: "6px 0" }, children: base }),
|
|
294
|
+
] }),
|
|
295
|
+
enabled && jsx("span", { className: "apis-desc", children: `浏览器访问 ${base}/ 可查看在线接口文档;接口的 model 参数可自由填写任意 provider/model,缺省用 DSH 当前默认模型` }),
|
|
296
|
+
!enabled
|
|
297
|
+
? jsx("span", { className: "apis-empty", children: "服务已关闭,开启后可在本页查看接口文档" })
|
|
298
|
+
: REST_DOCS.map(doc),
|
|
299
|
+
] });
|
|
300
|
+
}
|
|
301
|
+
|
|
177
302
|
/** 需要的浏览器侧服务:configForms 由 ui-settings 提供,封装 Host settings 的读快照与写字段 */
|
|
178
303
|
const inject = ["slots", "configForms"];
|
|
179
304
|
|
|
180
|
-
/**
|
|
305
|
+
/** 注册设置弹窗菜单项:settings.section 列表槽位,菜单取 {id, order, label},选中后渲染组件 */
|
|
181
306
|
function apply(ctx) {
|
|
182
307
|
form = ctx.configForms.get(NS);
|
|
183
308
|
store = createStore(form.getSnapshot());
|
|
@@ -188,6 +313,12 @@ window.__ModuleLoader__.load({
|
|
|
188
313
|
order: 30,
|
|
189
314
|
label: "接口管理",
|
|
190
315
|
}, ApisSection)));
|
|
316
|
+
ctx.effect(() => ctx.slots.inject("settings.section", () => ctx.slots.register({
|
|
317
|
+
name: "settings.section",
|
|
318
|
+
id: "dsh-apis-plugin-openapi",
|
|
319
|
+
order: 31,
|
|
320
|
+
label: "开放接口",
|
|
321
|
+
}, OpenApiSection)));
|
|
191
322
|
}
|
|
192
323
|
|
|
193
324
|
return { apply, inject };
|
package/cordis.patch.yml
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-apis-plugin",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "通用接口管理插件:把任意一套 HTTP 接口注册成 agent 可用的文档查询与请求双工具",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
"index.js",
|
|
30
30
|
"client.js",
|
|
31
31
|
"api-tools.js",
|
|
32
|
+
"rest-server.js",
|
|
32
33
|
"cordis.patch.yml"
|
|
33
34
|
],
|
|
34
35
|
"dsh": {
|
package/rest-server.js
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
// REST 开放接口服务:用原生 node:http 封装常用的「与 DSH 交互」API(默认 3088 端口)
|
|
2
|
+
// - OpenAI 风格:POST /v1/chat/completions(支持 stream SSE)、GET /v1/models
|
|
3
|
+
// - 简易风格:POST /ask({task} → {answer})
|
|
4
|
+
// - 会话查询:GET /sessions、GET /sessions/:id;健康检查:GET /health
|
|
5
|
+
// 每次对话请求独立 sessionId(天然并发),完成后 flush 持久化并 dispose 释放 agent;
|
|
6
|
+
// 传 session_id 则经 agents.resume 续接既有会话(多轮)。完全开放、无鉴权,仅建议内网使用。
|
|
7
|
+
import { createServer } from 'node:http'
|
|
8
|
+
import { randomUUID } from 'node:crypto'
|
|
9
|
+
|
|
10
|
+
/** 带 HTTP 状态码的业务错误 */
|
|
11
|
+
class HttpError extends Error {
|
|
12
|
+
constructor(status, message) {
|
|
13
|
+
super(message)
|
|
14
|
+
this.status = status
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const CORS = {
|
|
19
|
+
'Access-Control-Allow-Origin': '*',
|
|
20
|
+
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
|
21
|
+
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function json(res, status, data) {
|
|
25
|
+
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', ...CORS })
|
|
26
|
+
res.end(JSON.stringify(data))
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 读取并解析 JSON 请求体(限 2MB) */
|
|
30
|
+
function readBody(req) {
|
|
31
|
+
return new Promise((resolve, reject) => {
|
|
32
|
+
const chunks = []
|
|
33
|
+
let size = 0
|
|
34
|
+
req.on('data', (c) => {
|
|
35
|
+
size += c.length
|
|
36
|
+
if (size > 2 * 1024 * 1024) return reject(new HttpError(413, 'request body too large'))
|
|
37
|
+
chunks.push(c)
|
|
38
|
+
})
|
|
39
|
+
req.on('end', () => {
|
|
40
|
+
const raw = Buffer.concat(chunks).toString('utf8')
|
|
41
|
+
if (!raw) return resolve({})
|
|
42
|
+
try {
|
|
43
|
+
resolve(JSON.parse(raw))
|
|
44
|
+
} catch {
|
|
45
|
+
reject(new HttpError(400, 'invalid JSON body'))
|
|
46
|
+
}
|
|
47
|
+
})
|
|
48
|
+
req.on('error', reject)
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const IMAGE_MEDIA_TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/gif']
|
|
53
|
+
|
|
54
|
+
/** 解析 data URL(或下载 http 图片),返回 { mediaType, data } */
|
|
55
|
+
async function resolveBytes(url, what) {
|
|
56
|
+
const m = /^data:([^;,]+);base64,([\s\S]*)$/.exec(url)
|
|
57
|
+
if (m) return { mediaType: m[1], data: Buffer.from(m[2], 'base64') }
|
|
58
|
+
const r = await fetch(url)
|
|
59
|
+
if (!r.ok) throw new HttpError(400, `${what} download failed: HTTP ${r.status} (${url.slice(0, 120)})`)
|
|
60
|
+
return {
|
|
61
|
+
mediaType: (r.headers.get('content-type') || '').split(';')[0].trim(),
|
|
62
|
+
data: Buffer.from(await r.arrayBuffer()),
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** OpenAI image_url / input_image part → DSH ImageBlock(经 attachments 服务持久化) */
|
|
67
|
+
async function imageBlock(ctx, part) {
|
|
68
|
+
const url = part.image_url?.url ?? part.url
|
|
69
|
+
if (typeof url !== 'string' || !url) throw new HttpError(400, 'image_url.url is required')
|
|
70
|
+
const { mediaType, data } = await resolveBytes(url, 'image')
|
|
71
|
+
if (!IMAGE_MEDIA_TYPES.includes(mediaType)) throw new HttpError(400, `unsupported image type "${mediaType}"(支持 ${IMAGE_MEDIA_TYPES.join(' / ')})`)
|
|
72
|
+
const ref = await ctx.get('attachments').saveImage({ data: new Uint8Array(data), mediaType })
|
|
73
|
+
return { type: 'image', attachment: ref }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** OpenAI file / input_file part(file_data 为 base64 data URL)→ DSH FileBlock */
|
|
77
|
+
async function fileBlock(ctx, part) {
|
|
78
|
+
const file = part.file ?? part
|
|
79
|
+
const fd = file.file_data ?? file.fileData
|
|
80
|
+
if (typeof fd !== 'string' || !fd) throw new HttpError(400, 'file.file_data(base64 data URL)is required')
|
|
81
|
+
const m = /^data:[^;,]*;base64,([\s\S]*)$/.exec(fd)
|
|
82
|
+
if (!m) throw new HttpError(400, 'file.file_data 必须是 base64 data URL(如 data:application/pdf;base64,...)')
|
|
83
|
+
const ref = await ctx.get('attachments').saveFile({ data: new Uint8Array(Buffer.from(m[1], 'base64')), ...(file.filename ? { name: file.filename } : {}) })
|
|
84
|
+
return { type: 'file', attachment: ref }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* OpenAI messages → 一条 DSH user 消息的内容块:system 作指令文本、历史作带角色标注的文本,
|
|
89
|
+
* 用户消息里的 image_url / file 部件经 attachments 服务转成图片/文件块。
|
|
90
|
+
*/
|
|
91
|
+
async function buildMessageContent(ctx, messages) {
|
|
92
|
+
const textOf = (m) =>
|
|
93
|
+
typeof m.content === 'string'
|
|
94
|
+
? m.content
|
|
95
|
+
: Array.isArray(m.content)
|
|
96
|
+
? m.content.map((b) => (typeof b === 'string' ? b : b?.type === 'text' ? b.text : '')).join('')
|
|
97
|
+
: ''
|
|
98
|
+
const blocks = []
|
|
99
|
+
for (const m of messages) {
|
|
100
|
+
const role = m?.role
|
|
101
|
+
if (!Array.isArray(m.content)) {
|
|
102
|
+
const text = textOf(m).trim()
|
|
103
|
+
if (!text) continue
|
|
104
|
+
blocks.push({ type: 'text', text: role === 'system' || role === 'developer' ? '[指令]\n' + text : role === 'assistant' ? '[上一轮助手回复]\n' + text : text })
|
|
105
|
+
continue
|
|
106
|
+
}
|
|
107
|
+
for (const part of m.content) {
|
|
108
|
+
if (typeof part === 'string') {
|
|
109
|
+
if (part.trim()) blocks.push({ type: 'text', text: part })
|
|
110
|
+
continue
|
|
111
|
+
}
|
|
112
|
+
const t = part?.type
|
|
113
|
+
if (t === 'text') { if (part.text?.trim()) blocks.push({ type: 'text', text: part.text }) }
|
|
114
|
+
else if (t === 'image_url' || t === 'input_image') blocks.push(await imageBlock(ctx, part))
|
|
115
|
+
else if (t === 'file' || t === 'input_file') blocks.push(await fileBlock(ctx, part))
|
|
116
|
+
else if (typeof part?.text === 'string' && part.text.trim()) blocks.push({ type: 'text', text: part.text })
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (!blocks.length) throw new HttpError(400, 'messages produced no usable content')
|
|
120
|
+
return blocks
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* 解析请求的 model 字段为 { provider, model } 路由。不做网关目录校验,自由填写:
|
|
125
|
+
* "provider/model" 精确路由;纯模型名跟随默认 provider;缺省用 DSH 当前默认模型。
|
|
126
|
+
*/
|
|
127
|
+
function resolveRoute(ctx, model) {
|
|
128
|
+
const parse = (s) => {
|
|
129
|
+
if (!s) return undefined
|
|
130
|
+
const i = s.indexOf('/')
|
|
131
|
+
return i > 0 ? { provider: s.slice(0, i), model: s.slice(i + 1) } : { provider: undefined, model: s }
|
|
132
|
+
}
|
|
133
|
+
return parse(model) ?? (() => {
|
|
134
|
+
const sel = ctx.get('agentDefaultModel')?.currentSelection() ?? {}
|
|
135
|
+
return { provider: sel.provider, model: sel.model }
|
|
136
|
+
})()
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 沿用 dsh-headless 的权威提取逻辑:从 durable 事件流聚合最后一段 assistant 文本与结束原因 */
|
|
140
|
+
function summarize(session, firstSeq) {
|
|
141
|
+
let started = false
|
|
142
|
+
let text = ''
|
|
143
|
+
let reason
|
|
144
|
+
for (let seq = firstSeq; seq < session.seq; seq++) {
|
|
145
|
+
const event = session.eventAt(seq)
|
|
146
|
+
if (event === undefined) break
|
|
147
|
+
if (event.type === 'turn/start') {
|
|
148
|
+
started = true
|
|
149
|
+
continue
|
|
150
|
+
}
|
|
151
|
+
if (!started) continue
|
|
152
|
+
if (event.type === 'assistant/message') {
|
|
153
|
+
const joined = event.data.message.content.filter((b) => b.type === 'text').map((b) => b.text).join('')
|
|
154
|
+
if (joined !== '') text = joined
|
|
155
|
+
}
|
|
156
|
+
if (event.type === 'turn/end') reason = event.data.reason
|
|
157
|
+
}
|
|
158
|
+
return { text, reason }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* 驱动一次 agent 任务到结束。content 为 user 消息内容块(文本/图片/文件);
|
|
163
|
+
* route 为解析后的 { provider, model };onDelta 提供时订阅 assistant 流式帧转发 text-delta。
|
|
164
|
+
* @returns {Promise<{ text: string, reason: any, sessionId: string }>}
|
|
165
|
+
*/
|
|
166
|
+
async function driveTask(ctx, { content, sessionId, route, onDelta }) {
|
|
167
|
+
const agents = ctx.get('agents')
|
|
168
|
+
const sessionsStore = ctx.get('sessions')
|
|
169
|
+
if (!agents || !sessionsStore) throw new HttpError(503, 'DSH agent services are not ready')
|
|
170
|
+
const agentOptions = route.provider ? route : undefined
|
|
171
|
+
const fs = ctx.get('fs')
|
|
172
|
+
const cwd = fs ? fs.processPath(await fs.resolve('.')) : process.cwd()
|
|
173
|
+
|
|
174
|
+
let handle = null
|
|
175
|
+
let sid
|
|
176
|
+
if (sessionId) {
|
|
177
|
+
const live = agents.get(sessionId)
|
|
178
|
+
if (live) {
|
|
179
|
+
if (live.status !== 'idle') throw new HttpError(409, `session "${sessionId}" is busy`)
|
|
180
|
+
sid = sessionId // 复用调用方仍在使用的活跃 agent(handle 不归本请求所有,不 dispose)
|
|
181
|
+
} else {
|
|
182
|
+
handle = await agents.resume({ resumeSessionId: sessionId, agentOptions })
|
|
183
|
+
sid = sessionId
|
|
184
|
+
}
|
|
185
|
+
} else {
|
|
186
|
+
sid = 'session-' + randomUUID()
|
|
187
|
+
handle = await agents.create({ sessionId: sid, meta: { cwd }, agentOptions })
|
|
188
|
+
}
|
|
189
|
+
const agent = handle ? handle.agent : agents.get(sid)
|
|
190
|
+
|
|
191
|
+
const firstSeq = agent.session.seq
|
|
192
|
+
const disposeStream = onDelta
|
|
193
|
+
? ctx.on('agent/assistant-stream', ({ agent: subject, frame }) => {
|
|
194
|
+
if (subject !== agent) return
|
|
195
|
+
if (frame.type === 'start' || frame.type === 'end') return
|
|
196
|
+
const chunk = frame.chunk
|
|
197
|
+
if (chunk?.type === 'text-delta' && chunk.text) onDelta(chunk.text)
|
|
198
|
+
})
|
|
199
|
+
: undefined
|
|
200
|
+
|
|
201
|
+
try {
|
|
202
|
+
agent.followup({
|
|
203
|
+
id: randomUUID(),
|
|
204
|
+
role: 'user',
|
|
205
|
+
content,
|
|
206
|
+
source: { kind: 'user' },
|
|
207
|
+
})
|
|
208
|
+
await agent.whenIdle()
|
|
209
|
+
} finally {
|
|
210
|
+
disposeStream?.()
|
|
211
|
+
}
|
|
212
|
+
const outcome = summarize(agent.session, firstSeq)
|
|
213
|
+
try {
|
|
214
|
+
await sessionsStore.flush(agent.session)
|
|
215
|
+
} catch { /* 无持久化后端时忽略 */ }
|
|
216
|
+
if (handle) await handle.dispose()
|
|
217
|
+
return { ...outcome, sessionId: sid }
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export { buildMessageContent, resolveRoute }
|
|
221
|
+
|
|
222
|
+
/** REST 服务构造:返回未 listen 的 http.Server,由调用方在 effect 中起停 */
|
|
223
|
+
export function createRestServer({ ctx, log = () => {} }) {
|
|
224
|
+
const modelOf = () => {
|
|
225
|
+
const sel = ctx.get('agentDefaultModel')?.currentSelection()
|
|
226
|
+
return sel ? `${sel.provider}/${sel.model}` : ''
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const server = createServer(async (req, res) => {
|
|
230
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
231
|
+
const path = url.pathname.replace(/\/+$/, '') || '/'
|
|
232
|
+
if (req.method === 'OPTIONS') {
|
|
233
|
+
res.writeHead(204, CORS)
|
|
234
|
+
return res.end()
|
|
235
|
+
}
|
|
236
|
+
try {
|
|
237
|
+
// 接口文档落地页:浏览器直接访问 http://host:3088/ 展示
|
|
238
|
+
if (req.method === 'GET' && path === '/') {
|
|
239
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', ...CORS })
|
|
240
|
+
return res.end(renderDocsHtml())
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// 健康检查
|
|
244
|
+
if (req.method === 'GET' && path === '/health') return json(res, 200, { ok: true, model: modelOf() })
|
|
245
|
+
|
|
246
|
+
// OpenAI 兼容:模型列表(枚举全部已注册 provider 的模型目录,id 形如 provider/model)
|
|
247
|
+
if (req.method === 'GET' && path === '/v1/models') {
|
|
248
|
+
const llm = ctx.get('llm')
|
|
249
|
+
const data = []
|
|
250
|
+
if (llm?.listProviders) {
|
|
251
|
+
for (const p of llm.listProviders()) {
|
|
252
|
+
try {
|
|
253
|
+
for (const mi of (await llm.listModels(p.id)) ?? []) {
|
|
254
|
+
data.push({ id: `${p.id}/${mi.id}`, object: 'model', owned_by: p.id })
|
|
255
|
+
}
|
|
256
|
+
} catch { /* 单个 provider 目录失败不阻塞列表 */ }
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
if (!data.length) {
|
|
260
|
+
const id = modelOf()
|
|
261
|
+
if (id) data.push({ id, object: 'model', owned_by: 'dsh' })
|
|
262
|
+
}
|
|
263
|
+
return json(res, 200, { object: 'list', data })
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// OpenAI 兼容:对话补全(stream=true 走 SSE;支持图片/文件部件与 model 切换)
|
|
267
|
+
if (req.method === 'POST' && path === '/v1/chat/completions') {
|
|
268
|
+
const body = await readBody(req)
|
|
269
|
+
const messages = Array.isArray(body.messages) ? body.messages : []
|
|
270
|
+
if (!messages.length) throw new HttpError(400, 'messages is required')
|
|
271
|
+
const content = await buildMessageContent(ctx, messages)
|
|
272
|
+
const route = resolveRoute(ctx, body.model)
|
|
273
|
+
const created = Math.floor(Date.now() / 1000)
|
|
274
|
+
const model = body.model || modelOf()
|
|
275
|
+
const id = 'chatcmpl-' + randomUUID()
|
|
276
|
+
|
|
277
|
+
if (body.stream === true) {
|
|
278
|
+
res.writeHead(200, {
|
|
279
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
280
|
+
'Cache-Control': 'no-cache',
|
|
281
|
+
Connection: 'keep-alive',
|
|
282
|
+
...CORS,
|
|
283
|
+
})
|
|
284
|
+
const send = (data) => res.write(`data: ${JSON.stringify(data)}\n\n`)
|
|
285
|
+
const chunkOf = (delta, finish) => ({
|
|
286
|
+
id, object: 'chat.completion.chunk', created, model,
|
|
287
|
+
choices: [{ index: 0, delta, finish_reason: finish ?? null }],
|
|
288
|
+
})
|
|
289
|
+
send(chunkOf({ role: 'assistant' }))
|
|
290
|
+
try {
|
|
291
|
+
await driveTask(ctx, {
|
|
292
|
+
content,
|
|
293
|
+
sessionId: body.session_id,
|
|
294
|
+
route,
|
|
295
|
+
onDelta: (text) => send(chunkOf({ content: text })),
|
|
296
|
+
})
|
|
297
|
+
send(chunkOf({}, 'stop'))
|
|
298
|
+
} catch (err) {
|
|
299
|
+
send({ error: { message: err instanceof Error ? err.message : String(err), type: 'dsh_agent_error' } })
|
|
300
|
+
}
|
|
301
|
+
res.write('data: [DONE]\n\n')
|
|
302
|
+
return res.end()
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const { text, reason } = await driveTask(ctx, { content, sessionId: body.session_id, route })
|
|
306
|
+
if (reason?.kind === 'error') {
|
|
307
|
+
return json(res, 502, { error: { message: `${reason.error?.code}: ${reason.error?.message}`, type: 'dsh_agent_error' } })
|
|
308
|
+
}
|
|
309
|
+
return json(res, 200, {
|
|
310
|
+
id, object: 'chat.completion', created, model,
|
|
311
|
+
choices: [{ index: 0, message: { role: 'assistant', content: text }, finish_reason: 'stop' }],
|
|
312
|
+
usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
|
|
313
|
+
dsh_session_id: body.session_id,
|
|
314
|
+
})
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// 简易风格:一次任务
|
|
318
|
+
if (req.method === 'POST' && path === '/ask') {
|
|
319
|
+
const body = await readBody(req)
|
|
320
|
+
const task = typeof body.task === 'string' ? body.task.trim() : ''
|
|
321
|
+
if (!task) throw new HttpError(400, 'task is required')
|
|
322
|
+
const route = resolveRoute(ctx, body.model)
|
|
323
|
+
const { text, reason, sessionId } = await driveTask(ctx, { content: [{ type: 'text', text: task }], sessionId: body.session_id, route })
|
|
324
|
+
return json(res, 200, {
|
|
325
|
+
answer: text,
|
|
326
|
+
sessionId,
|
|
327
|
+
status: reason?.kind === 'error' ? 'error' : 'completed',
|
|
328
|
+
...(reason?.kind === 'error' ? { error: reason.error } : {}),
|
|
329
|
+
})
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// 会话列表(持久化后端 + 活跃会话)
|
|
333
|
+
if (req.method === 'GET' && path === '/sessions') {
|
|
334
|
+
const query = ctx.get('sessionQuery')
|
|
335
|
+
if (!query) throw new HttpError(503, 'sessionQuery service is not available')
|
|
336
|
+
const records = await query.listSessions()
|
|
337
|
+
return json(res, 200, {
|
|
338
|
+
object: 'list',
|
|
339
|
+
data: records.map((r) => ({
|
|
340
|
+
id: r.header?.id,
|
|
341
|
+
cwd: r.header?.cwd,
|
|
342
|
+
createdAt: r.header?.createdAt,
|
|
343
|
+
live: r.live,
|
|
344
|
+
persisted: r.persisted,
|
|
345
|
+
})),
|
|
346
|
+
})
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// 会话详情:当前模型可见面的事件流
|
|
350
|
+
if (req.method === 'GET' && /^\/sessions\/[^/]+$/.test(path)) {
|
|
351
|
+
const query = ctx.get('sessionQuery')
|
|
352
|
+
if (!query) throw new HttpError(503, 'sessionQuery service is not available')
|
|
353
|
+
const sid = decodeURIComponent(path.split('/')[2])
|
|
354
|
+
const observation = await query.observeSession(sid)
|
|
355
|
+
return json(res, 200, {
|
|
356
|
+
id: sid,
|
|
357
|
+
header: observation.header,
|
|
358
|
+
events: observation.events,
|
|
359
|
+
})
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
json(res, 404, { error: { message: `no route: ${req.method} ${path}` } })
|
|
363
|
+
} catch (err) {
|
|
364
|
+
const status = err instanceof HttpError ? err.status : 500
|
|
365
|
+
if (status >= 500) log(`request error: ${err instanceof Error ? err.stack : err}`)
|
|
366
|
+
if (!res.headersSent) json(res, status, { error: { message: err instanceof Error ? err.message : String(err) } })
|
|
367
|
+
else res.end()
|
|
368
|
+
}
|
|
369
|
+
})
|
|
370
|
+
server.on('error', (err) => log(`server error: ${err.message}`))
|
|
371
|
+
return server
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** 接口文档条目:与 client.js「开放接口」页保持同一份内容口径 */
|
|
375
|
+
const DOCS = [
|
|
376
|
+
{
|
|
377
|
+
method: 'POST', path: '/v1/chat/completions',
|
|
378
|
+
desc: 'OpenAI 兼容对话补全。请求完成后返回完整的 chat.completion 对象;错误时返回 502 与 error 对象。支持图片、文件与切换模型。',
|
|
379
|
+
params: [
|
|
380
|
+
['messages', '必填。消息数组 [{role, content}];content 为字符串或内容块数组,用户消息可含 image_url / file 部件'],
|
|
381
|
+
['model', '可选。模型自由填写:"provider/model" 精确路由(如 id456/glm-5.3-flash),纯模型名跟随默认 provider;缺省用 DSH 当前默认模型。不做网关目录校验'],
|
|
382
|
+
['stream', '可选。true 时以 SSE 流式返回 chat.completion.chunk 增量,以 data: [DONE] 结束'],
|
|
383
|
+
['session_id', '可选。传入此前返回的 dsh_session_id 可续接同一会话进行多轮对话'],
|
|
384
|
+
],
|
|
385
|
+
extra: '图片部件(data URL 或 http(s) 地址,支持 png/jpeg/webp/gif):{"type":"image_url","image_url":{"url":"data:image/png;base64,..."}};文件部件(base64 data URL,任意类型):{"type":"file","file":{"filename":"报告.pdf","file_data":"data:application/pdf;base64,..."}}',
|
|
386
|
+
curl: `curl -X POST __BASE__/v1/chat/completions \\\n -H "Content-Type: application/json" \\\n -d '{"messages":[{"role":"user","content":[{"type":"text","text":"这张图里是什么?"},{"type":"image_url","image_url":{"url":"data:image/png;base64,iVBOR…"}}]}]}'`,
|
|
387
|
+
},
|
|
388
|
+
{
|
|
389
|
+
method: 'POST', path: '/ask',
|
|
390
|
+
desc: '简易任务接口:提交一段任务文本,等待 agent 执行完成后一次性返回结果。',
|
|
391
|
+
params: [
|
|
392
|
+
['task', '必填。任务文本'],
|
|
393
|
+
['model', '可选。模型路由,规则同 /v1/chat/completions(自由填写,缺省用 DSH 当前默认模型)'],
|
|
394
|
+
['session_id', '可选。续接既有会话'],
|
|
395
|
+
],
|
|
396
|
+
resp: `{ "answer": "...", "sessionId": "session-…", "status": "completed" }`,
|
|
397
|
+
curl: `curl -X POST __BASE__/ask \\\n -H "Content-Type: application/json" \\\n -d '{"task":"运行一下测试并总结结果"}'`,
|
|
398
|
+
},
|
|
399
|
+
{
|
|
400
|
+
method: 'GET', path: '/v1/models',
|
|
401
|
+
desc: 'OpenAI 兼容模型列表:枚举全部已注册 provider 的模型目录(仅供参考,model 参数可直接自由填写任意 provider/model,不限于列表)。',
|
|
402
|
+
curl: `curl __BASE__/v1/models`,
|
|
403
|
+
},
|
|
404
|
+
{
|
|
405
|
+
method: 'GET', path: '/sessions',
|
|
406
|
+
desc: '会话列表(含活跃与已持久化),返回 id、cwd、createdAt、live、persisted。',
|
|
407
|
+
curl: `curl __BASE__/sessions`,
|
|
408
|
+
},
|
|
409
|
+
{
|
|
410
|
+
method: 'GET', path: '/sessions/:id',
|
|
411
|
+
desc: '会话详情:header 与当前模型可见面的事件流。',
|
|
412
|
+
curl: `curl __BASE__/sessions/<sessionId>`,
|
|
413
|
+
},
|
|
414
|
+
{
|
|
415
|
+
method: 'GET', path: '/health',
|
|
416
|
+
desc: '健康检查,返回 { ok, model }。',
|
|
417
|
+
curl: `curl __BASE__/health`,
|
|
418
|
+
},
|
|
419
|
+
]
|
|
420
|
+
|
|
421
|
+
const esc = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
422
|
+
|
|
423
|
+
/** 渲染文档落地页(静态 HTML + 内联样式;__BASE__ 占位由页面脚本按实际 origin 替换) */
|
|
424
|
+
function renderDocsHtml() {
|
|
425
|
+
const cards = DOCS.map((d) => `
|
|
426
|
+
<section class="card">
|
|
427
|
+
<div class="head"><span class="method ${d.method}">${d.method}</span><code class="path">${d.path}</code></div>
|
|
428
|
+
<p class="desc">${d.desc}</p>
|
|
429
|
+
${d.params ? `<table><tr><th>参数</th><th>说明</th></tr>${d.params.map(([n, t]) => `<tr><td><code>${n}</code></td><td>${t}</td></tr>`).join('')}</table>` : ''}
|
|
430
|
+
${d.extra ? `<p class="desc">${esc(d.extra)}</p>` : ''}
|
|
431
|
+
${d.resp ? `<div class="label">响应示例</div><pre class="code">${esc(d.resp)}</pre>` : ''}
|
|
432
|
+
<div class="label">调用示例</div><pre class="code">${esc(d.curl)}</pre>
|
|
433
|
+
</section>`).join('')
|
|
434
|
+
|
|
435
|
+
return `<!doctype html>
|
|
436
|
+
<html lang="zh-CN">
|
|
437
|
+
<head>
|
|
438
|
+
<meta charset="utf-8">
|
|
439
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
440
|
+
<title>DSH 开放接口文档</title>
|
|
441
|
+
<style>
|
|
442
|
+
:root{color-scheme:light dark}
|
|
443
|
+
*{box-sizing:border-box}
|
|
444
|
+
body{margin:0;background:var(--bg);color:var(--fg);font:14px/1.7 -apple-system,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}
|
|
445
|
+
:root{--bg:#f6f7f9;--card:#fff;--fg:#1f2328;--muted:#6a737d;--border:#e1e4e8;--code-bg:#f0f2f4;--get-bg:#e6f4ea;--get-fg:#1a7f37;--post-bg:#fff1e0;--post-fg:#b25e00}
|
|
446
|
+
@media(prefers-color-scheme:dark){:root{--bg:#14171a;--card:#1d2126;--fg:#e6e8ea;--muted:#9aa4ad;--border:#2d333a;--code-bg:#262b31;--get-bg:#12261a;--get-fg:#4ec46a;--post-bg:#2b2118;--post-fg:#f0964b}}
|
|
447
|
+
.wrap{max-width:820px;margin:0 auto;padding:32px 20px 64px}
|
|
448
|
+
h1{font-size:22px;margin:0 0 4px}
|
|
449
|
+
.sub{color:var(--muted);margin:0 0 16px}
|
|
450
|
+
.meta{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 16px}
|
|
451
|
+
.chip{font:12px/1 ui-monospace,Consolas,monospace;background:var(--code-bg);border:1px solid var(--border);border-radius:999px;padding:6px 12px;color:var(--muted)}
|
|
452
|
+
.chip b{color:var(--fg);font-weight:600}
|
|
453
|
+
.warn{background:var(--post-bg);color:var(--post-fg);border-radius:10px;padding:10px 14px;font-size:13px;margin:0 0 20px}
|
|
454
|
+
.card{background:var(--card);border:1px solid var(--border);border-radius:12px;padding:16px 18px;margin:0 0 14px}
|
|
455
|
+
.head{display:flex;align-items:center;gap:10px;margin-bottom:6px}
|
|
456
|
+
.method{font:600 11px/1 ui-monospace,Consolas,monospace;padding:4px 8px;border-radius:5px}
|
|
457
|
+
.method.GET{background:var(--get-bg);color:var(--get-fg)}
|
|
458
|
+
.method.POST{background:var(--post-bg);color:var(--post-fg)}
|
|
459
|
+
.path{font:600 14px ui-monospace,Consolas,monospace}
|
|
460
|
+
.desc{color:var(--muted);margin:4px 0 10px}
|
|
461
|
+
table{border-collapse:collapse;width:100%;margin:0 0 10px;font-size:13px}
|
|
462
|
+
th,td{text-align:left;border-bottom:1px solid var(--border);padding:5px 8px;vertical-align:top}
|
|
463
|
+
th{color:var(--muted);font-weight:500;width:120px}
|
|
464
|
+
td code{font:12px ui-monospace,Consolas,monospace;background:var(--code-bg);border-radius:4px;padding:1px 6px}
|
|
465
|
+
.label{font-size:12px;color:var(--muted);margin:8px 0 4px}
|
|
466
|
+
.code{font:12px/1.7 ui-monospace,Consolas,monospace;background:var(--code-bg);border-radius:8px;padding:10px 12px;margin:0;white-space:pre-wrap;word-break:break-all;user-select:all}
|
|
467
|
+
.foot{color:var(--muted);font-size:12px;margin-top:24px}
|
|
468
|
+
</style>
|
|
469
|
+
</head>
|
|
470
|
+
<body>
|
|
471
|
+
<div class="wrap">
|
|
472
|
+
<h1>DSH 开放接口</h1>
|
|
473
|
+
<p class="sub">封装常用的与 DSH 交互的 API,兼容 OpenAI 风格 · dsh-apis-plugin</p>
|
|
474
|
+
<div class="meta">
|
|
475
|
+
<span class="chip">Base URL <b class="base"></b></span>
|
|
476
|
+
<span class="chip">当前模型 <b id="model">…</b></span>
|
|
477
|
+
</div>
|
|
478
|
+
<p class="warn">⚠️ 本服务完全开放、无鉴权,请勿暴露到公网,仅建议内网使用。</p>
|
|
479
|
+
${cards}
|
|
480
|
+
<p class="foot">服务开关与端口在 DSH「设置 → 开放接口」中调整;model 参数支持自由填写任意 provider/model,不限于模型列表;每次对话创建独立会话,传 session_id 可多轮续接。</p>
|
|
481
|
+
</div>
|
|
482
|
+
<script>
|
|
483
|
+
var base = location.origin;
|
|
484
|
+
document.querySelectorAll('.base').forEach(function (el) { el.textContent = base });
|
|
485
|
+
document.querySelectorAll('.code').forEach(function (el) { el.textContent = el.textContent.split('__BASE__').join(base) });
|
|
486
|
+
fetch(base + '/health').then(function (r) { return r.json() }).then(function (d) {
|
|
487
|
+
document.getElementById('model').textContent = d.model || '未知';
|
|
488
|
+
}).catch(function () { document.getElementById('model').textContent = '获取失败' });
|
|
489
|
+
</script>
|
|
490
|
+
</body>
|
|
491
|
+
</html>`
|
|
492
|
+
}
|