dsh-llm-mock 0.0.0-stage → 0.2.9
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 +22 -2
- package/package.json +30 -4
- package/src/index.mjs +152 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dsh-plugin-e2e contributors
|
|
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,23 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-llm-mock
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Self-contained, **OpenAI-compatible**, **scriptable** mock LLM server for DSH plugin development / testing / CI.
|
|
4
|
+
不依赖 DSH 源码树、不需要真实 key;用固定/序列响应替代真实模型。
|
|
5
|
+
|
|
6
|
+
```js
|
|
7
|
+
import { startMockServer } from 'dsh-llm-mock'
|
|
8
|
+
|
|
9
|
+
const mock = await startMockServer({
|
|
10
|
+
sequence: ['success', 'stall', 'tool_call'], // 按请求顺序切换
|
|
11
|
+
successText: '已按指令完成。',
|
|
12
|
+
// chunkSize / chunkDelayMs / toolName / toolArguments / stallMs / port 也可配
|
|
13
|
+
})
|
|
14
|
+
// mock.url -> http://127.0.0.1:<port>/v1 (给 DSH profile 的 baseURL)
|
|
15
|
+
// mock.requests -> 收到的请求记录
|
|
16
|
+
await mock.close()
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
- 端点:`GET /v1/models`、`POST /v1/chat/completions`(SSE 流式 & JSON 非流式)。
|
|
20
|
+
- 序列行为:`success`(逐块流式回复)、`stall`(挂住,制造"在飞 step")、`tool_call`(发工具调用)。
|
|
21
|
+
- 环境变量兜底:`MOCK_PORT` / `MOCK_SEQUENCE` / `MOCK_SUCCESS_TEXT` / `MOCK_CHUNK_SIZE` / `MOCK_CHUNK_DELAY_MS` / `MOCK_TOOL_NAME` / `MOCK_TOOL_ARGS` / `MOCK_STALL_MS`。
|
|
22
|
+
- 也可用已安装包的 CLI 直接跑(**发布后的消费者用这个**):`npx dsh-llm-mock`(打印 `{"t":"ready","url":...}`)。
|
|
23
|
+
- 在本 monorepo 内开发时可直接跑源码:`node packages/dsh-llm-mock/src/index.mjs`(仅仓库内路径,装了包之后不适用)。
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-llm-mock",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.9",
|
|
4
|
+
"private": false,
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"description": "Self-contained, OpenAI-compatible, scriptable mock LLM server for DSH plugin development / testing / CI. No DSH source tree and no real key needed. Sequences: success / stall / tool_call.",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/index.mjs"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"src/",
|
|
13
|
+
"README.md"
|
|
14
|
+
],
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/metal-huang/dsh-devtools.git",
|
|
18
|
+
"directory": "packages/dsh-llm-mock"
|
|
19
|
+
},
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public",
|
|
22
|
+
"registry": "https://registry.npmjs.org/"
|
|
23
|
+
},
|
|
24
|
+
"engines": {
|
|
25
|
+
"dsh": ">=0.2.2-rc.5",
|
|
26
|
+
"node": ">=22.15.0"
|
|
27
|
+
},
|
|
28
|
+
"dshTestedOn": [
|
|
29
|
+
"0.2.2-rc.5",
|
|
30
|
+
"0.2.3-alpha.2"
|
|
31
|
+
]
|
|
32
|
+
}
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// 自带、自包含、OpenAI 兼容的脚本化 mock LLM server。
|
|
2
|
+
// 目的:行为层 E2E 用它当模型,**不依赖 DSH 源码里的官方 mock**(官方 mock 不在 npm 闭包)。
|
|
3
|
+
// 支持按序列切换行为:success(正常流式回复)/ stall(挂住,制造"在飞 step")/ tool_call(发工具调用)。
|
|
4
|
+
import { createServer } from 'node:http'
|
|
5
|
+
import { pathToFileURL } from 'node:url'
|
|
6
|
+
|
|
7
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @param {{port?:number,host?:string,sequence?:string[],repeatLast?:boolean,successText?:string,chunkSize?:number,chunkDelayMs?:number,toolName?:string,toolArguments?:string,stallMs?:number}} opts
|
|
11
|
+
* @returns {Promise<{port:number,url:string,requests:any[],close:()=>Promise<void>}>}
|
|
12
|
+
*/
|
|
13
|
+
export async function startMockServer(opts = {}) {
|
|
14
|
+
const host = opts.host ?? '127.0.0.1'
|
|
15
|
+
const port = opts.port ?? Number(process.env.MOCK_PORT ?? 8123)
|
|
16
|
+
const sequence = opts.sequence ?? (process.env.MOCK_SEQUENCE ?? 'success').split(',').filter(Boolean)
|
|
17
|
+
const successText = opts.successText ?? process.env.MOCK_SUCCESS_TEXT ?? '已按指令完成。'
|
|
18
|
+
const chunkSize = Math.max(1, opts.chunkSize ?? Number(process.env.MOCK_CHUNK_SIZE ?? 1))
|
|
19
|
+
const chunkDelayMs = opts.chunkDelayMs ?? Number(process.env.MOCK_CHUNK_DELAY_MS ?? 0)
|
|
20
|
+
const toolName = opts.toolName ?? process.env.MOCK_TOOL_NAME
|
|
21
|
+
const toolArguments = opts.toolArguments ?? process.env.MOCK_TOOL_ARGS
|
|
22
|
+
const stallMs = opts.stallMs ?? Number(process.env.MOCK_STALL_MS ?? 600000)
|
|
23
|
+
const requests = []
|
|
24
|
+
let index = 0
|
|
25
|
+
const pick = () => {
|
|
26
|
+
const i = Math.min(index, sequence.length - 1)
|
|
27
|
+
index += 1
|
|
28
|
+
return sequence[i] ?? 'success'
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const server = createServer(async (req, res) => {
|
|
32
|
+
let url
|
|
33
|
+
try {
|
|
34
|
+
url = new URL(req.url, `http://${host}:${port}`)
|
|
35
|
+
} catch {
|
|
36
|
+
res.writeHead(400)
|
|
37
|
+
res.end('bad url')
|
|
38
|
+
return
|
|
39
|
+
}
|
|
40
|
+
if (req.method === 'GET' && /\/models$/.test(url.pathname)) {
|
|
41
|
+
res.writeHead(200, { 'content-type': 'application/json' })
|
|
42
|
+
res.end(JSON.stringify({ object: 'list', data: [{ id: 'mock/echo', object: 'model', owned_by: 'mock' }] }))
|
|
43
|
+
return
|
|
44
|
+
}
|
|
45
|
+
if (req.method === 'POST' && /\/chat\/completions$/.test(url.pathname)) {
|
|
46
|
+
let raw = ''
|
|
47
|
+
for await (const c of req) raw += c
|
|
48
|
+
let body = {}
|
|
49
|
+
try {
|
|
50
|
+
body = JSON.parse(raw)
|
|
51
|
+
} catch {}
|
|
52
|
+
const behavior = pick()
|
|
53
|
+
const model = body?.model ?? 'mock/echo'
|
|
54
|
+
const id = 'chatcmpl-mock-' + Date.now()
|
|
55
|
+
requests.push({ behavior, model })
|
|
56
|
+
const stream = body?.stream !== false
|
|
57
|
+
const text = successText
|
|
58
|
+
|
|
59
|
+
if (!stream) {
|
|
60
|
+
const message =
|
|
61
|
+
behavior === 'tool_call'
|
|
62
|
+
? { role: 'assistant', content: null, tool_calls: makeToolCalls(toolName, toolArguments) }
|
|
63
|
+
: { role: 'assistant', content: text }
|
|
64
|
+
res.writeHead(200, { 'content-type': 'application/json' })
|
|
65
|
+
res.end(
|
|
66
|
+
JSON.stringify({
|
|
67
|
+
id,
|
|
68
|
+
object: 'chat.completion',
|
|
69
|
+
model,
|
|
70
|
+
choices: [{ index: 0, message, finish_reason: behavior === 'tool_call' ? 'tool_calls' : 'stop' }],
|
|
71
|
+
usage: { prompt_tokens: 10, completion_tokens: 10, total_tokens: 20 },
|
|
72
|
+
}),
|
|
73
|
+
)
|
|
74
|
+
return
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' })
|
|
78
|
+
const send = (o) => res.write('data: ' + JSON.stringify(o) + '\n\n')
|
|
79
|
+
const chunk = (delta, finish = null) => ({
|
|
80
|
+
id,
|
|
81
|
+
object: 'chat.completion.chunk',
|
|
82
|
+
model,
|
|
83
|
+
choices: [{ index: 0, delta, finish_reason: finish }],
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
send(chunk({ role: 'assistant' }))
|
|
87
|
+
|
|
88
|
+
if (behavior === 'stall') {
|
|
89
|
+
const t = setTimeout(() => {
|
|
90
|
+
try {
|
|
91
|
+
res.end()
|
|
92
|
+
} catch {}
|
|
93
|
+
}, stallMs)
|
|
94
|
+
t.unref?.()
|
|
95
|
+
req.on('close', () => clearTimeout(t))
|
|
96
|
+
return
|
|
97
|
+
}
|
|
98
|
+
if (behavior === 'tool_call') {
|
|
99
|
+
send(chunk({ tool_calls: makeToolCallDeltas(toolName, toolArguments) }))
|
|
100
|
+
send(chunk({}, 'tool_calls'))
|
|
101
|
+
res.write('data: [DONE]\n\n')
|
|
102
|
+
res.end()
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
// success:逐块流式
|
|
106
|
+
for (let i = 0; i < text.length; i += chunkSize) {
|
|
107
|
+
send(chunk({ content: text.slice(i, i + chunkSize) }))
|
|
108
|
+
if (chunkDelayMs > 0) await sleep(chunkDelayMs)
|
|
109
|
+
}
|
|
110
|
+
send(chunk({}, 'stop'))
|
|
111
|
+
res.write('data: [DONE]\n\n')
|
|
112
|
+
res.end()
|
|
113
|
+
return
|
|
114
|
+
}
|
|
115
|
+
res.writeHead(404, { 'content-type': 'text/plain' })
|
|
116
|
+
res.end('not found')
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
await new Promise((resolve, reject) => {
|
|
120
|
+
server.once('error', reject)
|
|
121
|
+
server.listen(port, host, resolve)
|
|
122
|
+
})
|
|
123
|
+
const actualPort = server.address().port
|
|
124
|
+
return {
|
|
125
|
+
port: actualPort,
|
|
126
|
+
url: `http://${host}:${actualPort}/v1`,
|
|
127
|
+
requests,
|
|
128
|
+
close: () => new Promise((r) => server.close(() => r())),
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function makeToolCalls(name, args) {
|
|
133
|
+
return [{ id: 'call_mock_1', type: 'function', function: { name: name ?? 'mock_tool', arguments: args ?? '{}' } }]
|
|
134
|
+
}
|
|
135
|
+
function makeToolCallDeltas(name, args) {
|
|
136
|
+
return [{ index: 0, id: 'call_mock_1', type: 'function', function: { name: name ?? 'mock_tool', arguments: args ?? '{}' } }]
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// 直接执行:读 env 起服务并打印 ready JSON(供脚本/CI 用)。
|
|
140
|
+
if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
141
|
+
try {
|
|
142
|
+
const s = await startMockServer()
|
|
143
|
+
console.log(JSON.stringify({ t: 'ready', url: s.url, port: s.port }))
|
|
144
|
+
} catch (e) {
|
|
145
|
+
if (e?.code === 'EADDRINUSE') {
|
|
146
|
+
console.error(`端口被占用(多半是上次 mock 还活着且序列已消费)。换 MOCK_PORT 或先杀掉旧的。`)
|
|
147
|
+
} else {
|
|
148
|
+
console.error(String(e?.stack ?? e))
|
|
149
|
+
}
|
|
150
|
+
process.exit(1)
|
|
151
|
+
}
|
|
152
|
+
}
|