dsh-llm-mock 0.0.0-stage → 0.2.10

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 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,122 @@
1
- # Temporary Holding Version
1
+ # dsh-llm-mock
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English | [简体中文](./README.zh-CN.md)
4
+
5
+ A self-contained, **OpenAI-compatible, scriptable mock LLM server** for DSH plugin development, testing and CI. No DSH source tree, no real API key — you get deterministic, sequenced replies instead of a real model.
6
+
7
+ ```js
8
+ import { startMockServer } from 'dsh-llm-mock'
9
+
10
+ const mock = await startMockServer({ sequence: ['success', 'stall', 'tool_call'] })
11
+ console.log(mock.url) // http://127.0.0.1:8123/v1 — use as the provider baseURL
12
+ await mock.close()
13
+ ```
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ npm i -D dsh-llm-mock
19
+ ```
20
+
21
+ **Node >= 22.15.0** (`engines.dsh`: `>=0.2.2-rc.5`, tested on `0.2.2-rc.5` and `0.2.3-alpha.2`). There are no runtime dependencies.
22
+
23
+ ## Quick start
24
+
25
+ ```js
26
+ import { startMockServer } from 'dsh-llm-mock'
27
+
28
+ const mock = await startMockServer({
29
+ port: 8123, // 0 = let the OS pick a free port
30
+ sequence: ['success', 'success', 'stall'], // consumed one per request, last one repeats
31
+ successText: 'done.',
32
+ chunkSize: 4, // characters per SSE chunk
33
+ chunkDelayMs: 10, // pause between chunks
34
+ })
35
+
36
+ console.log(mock.url) // http://127.0.0.1:8123/v1
37
+ console.log(mock.requests) // live array: [{ behavior, model }, ...]
38
+
39
+ await mock.close()
40
+ ```
41
+
42
+ Point a DSH profile's provider at `mock.url` and every chat completion is answered by the script.
43
+
44
+ ## Running it standalone
45
+
46
+ The package root exports `startMockServer`; `src/index.mjs` also runs as a script. When executed directly it starts a server from the environment and prints one line of JSON, which is convenient for CI wrappers:
47
+
48
+ ```bash
49
+ MOCK_PORT=8123 node ./node_modules/dsh-llm-mock/src/index.mjs
50
+ # {"t":"ready","url":"http://127.0.0.1:8123/v1","port":8123}
51
+ ```
52
+
53
+ > ⚠️ **`npx dsh-llm-mock` does not work in this version** — `package.json` declares no `bin` entry, so npm has nothing to execute. Use the programmatic import, or the `node ./node_modules/...` form above. (`npx` would start working the moment a `bin` field is added.)
54
+
55
+ ## API
56
+
57
+ | Export | Signature | Returns |
58
+ |---|---|---|
59
+ | `startMockServer(opts?)` | `opts` is optional | `Promise<{ port, url, requests, close }>` |
60
+
61
+ The returned object:
62
+
63
+ | Field | Meaning |
64
+ |---|---|
65
+ | `port` | The actual listening port (useful when you passed `port: 0`) |
66
+ | `url` | `http://<host>:<port>/v1` — the value to use as a provider `baseURL` |
67
+ | `requests` | Array appended to on every chat completion: `{ behavior, model }` |
68
+ | `close()` | `() => Promise<void>`; resolves once the server and its open connections are done |
69
+
70
+ ## `startMockServer` options
71
+
72
+ | Option | Env fallback | Default | Meaning |
73
+ |---|---|---|---|
74
+ | `port` | `MOCK_PORT` | `8123` | Listening port; `0` picks a free one |
75
+ | `host` | — | `'127.0.0.1'` | Bind address |
76
+ | `sequence` | `MOCK_SEQUENCE` (comma-separated) | `['success']` | Behaviors, one per request |
77
+ | `successText` | `MOCK_SUCCESS_TEXT` | `'已按指令完成。'` | Text streamed back for `success` |
78
+ | `chunkSize` | `MOCK_CHUNK_SIZE` | `1` | Characters per SSE chunk (clamped to ≥ 1) |
79
+ | `chunkDelayMs` | `MOCK_CHUNK_DELAY_MS` | `0` | Delay between chunks, ms |
80
+ | `toolName` | `MOCK_TOOL_NAME` | `'mock_tool'` | Tool name emitted for `tool_call` |
81
+ | `toolArguments` | `MOCK_TOOL_ARGS` | `'{}'` | Raw JSON string emitted as the tool arguments |
82
+ | `stallMs` | `MOCK_STALL_MS` | `600000` | How long a `stall` holds the connection |
83
+
84
+ `repeatLast` appears in the source's JSDoc but is **not implemented** — do not pass it. Reuse is controlled by the sequence itself (see below).
85
+
86
+ ## Endpoints
87
+
88
+ | Method + path | Response |
89
+ |---|---|
90
+ | `GET .../models` | `{ object: 'list', data: [{ id: 'mock/echo', ... }] }` |
91
+ | `POST .../chat/completions` | SSE stream, or a JSON completion when `stream: false` |
92
+ | Anything else | `404` `not found` |
93
+
94
+ Both routes are matched by suffix (`/models$`, `/chat/completions$`), so `/v1/...` is not required.
95
+
96
+ **Streaming is the default**: the code checks `body.stream !== false`, so omitting `stream` gives you SSE. Pass `stream: false` explicitly for a single JSON body.
97
+
98
+ ## Behaviors
99
+
100
+ The sequence is consumed **one entry per chat-completion request**. `index` only ever increases, and the picker clamps to the last entry — so the final behavior repeats forever once you reach it.
101
+
102
+ | Behavior | Streaming (`stream` omitted or `true`) | Non-streaming (`stream: false`) |
103
+ |---|---|---|
104
+ | `success` | Role chunk, then `successText` in `chunkSize` pieces (with `chunkDelayMs` between), a `finish_reason: 'stop'` chunk, then `data: [DONE]` | One JSON body, `content: successText`, `finish_reason: 'stop'` |
105
+ | `stall` | Role chunk only, then the connection **hangs** for `stallMs` and ends with no finish chunk — this is how you manufacture an in-flight step | ⚠️ Behaves like `success`: returns the text immediately (measured ~15 ms), no stall |
106
+ | `tool_call` | Role chunk, tool-call deltas (`toolName` / `toolArguments`), a `finish_reason: 'tool_calls'` chunk, then `data: [DONE]` | One JSON body with `tool_calls` and `finish_reason: 'tool_calls'` |
107
+
108
+ If the sequence runs out, the last entry repeats — you cannot get an empty behavior.
109
+
110
+ ## Notes and pitfalls
111
+
112
+ - **The default port is fixed (8123).** A stale mock still holding it gives `EADDRINUSE`; the direct-run path prints a hint telling you to change `MOCK_PORT` or kill the old process. Pass `port: 0` in tests to avoid this entirely.
113
+ - **The sequence is stateful per server.** Each `startMockServer` call starts again at index 0, but a long-lived server keeps consuming — a second test that expects `success` may get whatever the first one left off at. Start a fresh server per test, or account for the sequence.
114
+ - **`stall` needs streaming to stall.** With `stream: false` it is indistinguishable from `success`.
115
+ - **`stallMs` defaults to 10 minutes**, longer than most test timeouts. The timer is `unref`'d and cleared when the client disconnects, so a closed request does not keep the process alive.
116
+ - **`toolArguments` is emitted verbatim as a string**, not parsed. Pass `'{"a":1}'`, not an object.
117
+ - **`requests` is the only inspection surface** — it records `{ behavior, model }` per call. There is no body capture, so assert on the DSH side if you need payload details.
118
+ - **`close()` waits for open connections.** It resolves from `server.close()`, which does not finish while a request is still in flight — an unanswered `stall` (default `stallMs` = 10 min) will hold `await mock.close()` open that long. Abort the client request first if you stall on purpose.
119
+
120
+ ## License
121
+
122
+ MIT
@@ -0,0 +1,122 @@
1
+ # dsh-llm-mock
2
+
3
+ [English](./README.md) | 简体中文
4
+
5
+ 一个自带、**OpenAI 兼容、可脚本化**的 mock LLM 服务,用于 DSH 插件的开发、测试与 CI。不依赖 DSH 源码树、不需要真实 API key——你拿到的是确定性的、按序列切换的回复,而不是真模型。
6
+
7
+ ```js
8
+ import { startMockServer } from 'dsh-llm-mock'
9
+
10
+ const mock = await startMockServer({ sequence: ['success', 'stall', 'tool_call'] })
11
+ console.log(mock.url) // http://127.0.0.1:8123/v1 —— 拿去当 provider 的 baseURL
12
+ await mock.close()
13
+ ```
14
+
15
+ ## 安装
16
+
17
+ ```bash
18
+ npm i -D dsh-llm-mock
19
+ ```
20
+
21
+ **Node >= 22.15.0**(`engines.dsh`:`>=0.2.2-rc.5`,实测于 `0.2.2-rc.5` 与 `0.2.3-alpha.2`)。无运行时依赖。
22
+
23
+ ## 快速开始
24
+
25
+ ```js
26
+ import { startMockServer } from 'dsh-llm-mock'
27
+
28
+ const mock = await startMockServer({
29
+ port: 8123, // 0 = 让系统分配空闲端口
30
+ sequence: ['success', 'success', 'stall'], // 每次请求消费一个,最后一个一直重复
31
+ successText: 'done.',
32
+ chunkSize: 4, // 每个 SSE 分片的字符数
33
+ chunkDelayMs: 10, // 分片之间的停顿
34
+ })
35
+
36
+ console.log(mock.url) // http://127.0.0.1:8123/v1
37
+ console.log(mock.requests) // 实时数组:[{ behavior, model }, ...]
38
+
39
+ await mock.close()
40
+ ```
41
+
42
+ 把 DSH profile 的 provider 指向 `mock.url`,之后每次 chat completion 都由这个脚本回答。
43
+
44
+ ## 单独运行
45
+
46
+ 包根导出 `startMockServer`;`src/index.mjs` 同时也能当脚本直接跑。直接执行时会按环境变量起服务并打印一行 JSON,方便 CI 包装:
47
+
48
+ ```bash
49
+ MOCK_PORT=8123 node ./node_modules/dsh-llm-mock/src/index.mjs
50
+ # {"t":"ready","url":"http://127.0.0.1:8123/v1","port":8123}
51
+ ```
52
+
53
+ > ⚠️ **这个版本 `npx dsh-llm-mock` 不可用**——`package.json` 没有声明 `bin` 字段,npm 没有可执行目标。请用编程式 import,或上面 `node ./node_modules/...` 的形式。(等哪天补上 `bin` 字段,`npx` 就能用。)
54
+
55
+ ## API
56
+
57
+ | 导出 | 签名 | 返回 |
58
+ |---|---|---|
59
+ | `startMockServer(opts?)` | `opts` 可省略 | `Promise<{ port, url, requests, close }>` |
60
+
61
+ 返回对象:
62
+
63
+ | 字段 | 含义 |
64
+ |---|---|
65
+ | `port` | 实际监听端口(传 `port: 0` 时用它) |
66
+ | `url` | `http://<host>:<port>/v1`——拿去当 provider 的 `baseURL` |
67
+ | `requests` | 每次 chat completion 追加一项:`{ behavior, model }` |
68
+ | `close()` | `() => Promise<void>`;服务与其未完成连接都结束后才 resolve |
69
+
70
+ ## `startMockServer` 选项
71
+
72
+ | 选项 | 环境变量兜底 | 默认 | 说明 |
73
+ |---|---|---|---|
74
+ | `port` | `MOCK_PORT` | `8123` | 监听端口;`0` 表示自动选空闲端口 |
75
+ | `host` | — | `'127.0.0.1'` | 绑定地址 |
76
+ | `sequence` | `MOCK_SEQUENCE`(逗号分隔) | `['success']` | 行为序列,每次请求消费一个 |
77
+ | `successText` | `MOCK_SUCCESS_TEXT` | `'已按指令完成。'` | `success` 时流式回传的文本 |
78
+ | `chunkSize` | `MOCK_CHUNK_SIZE` | `1` | 每个 SSE 分片的字符数(下限 1) |
79
+ | `chunkDelayMs` | `MOCK_CHUNK_DELAY_MS` | `0` | 分片之间的停顿,毫秒 |
80
+ | `toolName` | `MOCK_TOOL_NAME` | `'mock_tool'` | `tool_call` 时发出的工具名 |
81
+ | `toolArguments` | `MOCK_TOOL_ARGS` | `'{}'` | 作为工具参数原样发出的 JSON 字符串 |
82
+ | `stallMs` | `MOCK_STALL_MS` | `600000` | `stall` 挂住连接的时长 |
83
+
84
+ 源码 JSDoc 里出现的 `repeatLast` **并未实现**,不要传。重复行为由序列自身决定(见下文)。
85
+
86
+ ## 端点
87
+
88
+ | 方法 + 路径 | 响应 |
89
+ |---|---|
90
+ | `GET .../models` | `{ object: 'list', data: [{ id: 'mock/echo', ... }] }` |
91
+ | `POST .../chat/completions` | SSE 流,或 `stream: false` 时的 JSON 响应 |
92
+ | 其它 | `404` `not found` |
93
+
94
+ 两条路由都是按后缀匹配(`/models$`、`/chat/completions$`),所以不强制带 `/v1/`。
95
+
96
+ **默认走流式**:代码判的是 `body.stream !== false`,所以不传 `stream` 得到的是 SSE。要一次性 JSON 响应必须显式传 `stream: false`。
97
+
98
+ ## 行为
99
+
100
+ 序列按 **chat completion 请求数**逐个消费。`index` 只增不减,取用时钳制到最后一个元素——所以走到末尾之后,最后那个行为会一直重复。
101
+
102
+ | 行为 | 流式(不传 `stream` 或传 `true`) | 非流式(`stream: false`) |
103
+ |---|---|---|
104
+ | `success` | 先发 role 分片,再把 `successText` 按 `chunkSize` 切开逐片发出(间隔 `chunkDelayMs`),然后一个 `finish_reason: 'stop'` 分片,最后 `data: [DONE]` | 一个 JSON 体,`content: successText`,`finish_reason: 'stop'` |
105
+ | `stall` | 只发 role 分片,然后连接**挂住** `stallMs`,结束时没有 finish 分片——这就是制造"在飞 step"的方式 | ⚠️ 行为等同 `success`:立刻返回文本(实测约 15ms),不挂起 |
106
+ | `tool_call` | role 分片、工具调用分片(`toolName` / `toolArguments`)、`finish_reason: 'tool_calls'` 分片,最后 `data: [DONE]` | 一个 JSON 体,带 `tool_calls` 与 `finish_reason: 'tool_calls'` |
107
+
108
+ 序列用尽后重复最后一项——不会拿到空行为。
109
+
110
+ ## 注意事项与坑
111
+
112
+ - **默认端口是固定的(8123)。** 上一次的 mock 还活着占着端口就会 `EADDRINUSE`;直接运行的路径会打印提示,让你换 `MOCK_PORT` 或先杀掉旧进程。测试里传 `port: 0` 可以彻底避开这个问题。
113
+ - **序列是按 server 实例有状态的。** 每次 `startMockServer` 都从索引 0 开始,但一个长命的 server 会一直消费——第二个期望 `success` 的测试可能拿到第一个测试留下的进度。每个测试起一个新 server,或者自己算好序列。
114
+ - **`stall` 只有流式才挂住。** 传 `stream: false` 时它和 `success` 无法区分。
115
+ - **`stallMs` 默认 10 分钟**,比多数测试超时都长。定时器带 `unref`,且客户端断开时会被清掉,所以关掉的请求不会吊住进程。
116
+ - **`toolArguments` 是原样字符串**,不做解析。传 `'{"a":1}'`,别传对象。
117
+ - **`requests` 是唯一的观察面**——每次调用记录 `{ behavior, model }`。它不抓请求体,需要 payload 细节就在 DSH 侧断言。
118
+ - **`close()` 会等未完成的连接。** 它 resolve 自 `server.close()`,而有请求在飞时该回调不会结束——一个没人接的 `stall`(默认 `stallMs` = 10 分钟)会让 `await mock.close()` 挂那么久。故意 stall 时先 abort 客户端请求。
119
+
120
+ ## License
121
+
122
+ MIT
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "dsh-llm-mock",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.10",
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
+ "README.zh-CN.md"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/metal-huang/dsh-devtools.git",
19
+ "directory": "packages/dsh-llm-mock"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public",
23
+ "registry": "https://registry.npmjs.org/"
24
+ },
25
+ "engines": {
26
+ "dsh": ">=0.2.2-rc.5",
27
+ "node": ">=22.15.0"
28
+ },
29
+ "dshTestedOn": [
30
+ "0.2.2-rc.5",
31
+ "0.2.3-alpha.2"
32
+ ],
33
+ "bin": {
34
+ "dsh-llm-mock": "src/index.mjs"
35
+ }
36
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,198 @@
1
+ #!/usr/bin/env node
2
+ // 自带、自包含、OpenAI 兼容的脚本化 mock LLM server。
3
+ // 目的:行为层 E2E 用它当模型,**不依赖 DSH 源码里的官方 mock**(官方 mock 不在 npm 闭包)。
4
+ // 支持按序列切换行为:success(正常流式回复)/ stall(挂住,制造"在飞 step")/ tool_call(发工具调用)。
5
+ import { createServer } from 'node:http'
6
+ import { pathToFileURL } from 'node:url'
7
+
8
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
9
+
10
+ /**
11
+ * @param {{port?:number,host?:string,sequence?:string[],repeatLast?:boolean,successText?:string,chunkSize?:number,chunkDelayMs?:number,toolName?:string,toolArguments?:string,stallMs?:number}} opts
12
+ * @returns {Promise<{port:number,url:string,requests:any[],close:()=>Promise<void>}>}
13
+ */
14
+ export async function startMockServer(opts = {}) {
15
+ const host = opts.host ?? '127.0.0.1'
16
+ const port = opts.port ?? Number(process.env.MOCK_PORT ?? 8123)
17
+ const sequence =
18
+ opts.sequence ?? (process.env.MOCK_SEQUENCE ?? 'success').split(',').filter(Boolean)
19
+ const successText = opts.successText ?? process.env.MOCK_SUCCESS_TEXT ?? '已按指令完成。'
20
+ const chunkSize = Math.max(1, opts.chunkSize ?? Number(process.env.MOCK_CHUNK_SIZE ?? 1))
21
+ const chunkDelayMs = opts.chunkDelayMs ?? Number(process.env.MOCK_CHUNK_DELAY_MS ?? 0)
22
+ const toolName = opts.toolName ?? process.env.MOCK_TOOL_NAME
23
+ const toolArguments = opts.toolArguments ?? process.env.MOCK_TOOL_ARGS
24
+ const stallMs = opts.stallMs ?? Number(process.env.MOCK_STALL_MS ?? 600000)
25
+ const requests = []
26
+ let index = 0
27
+ const pick = () => {
28
+ const i = Math.min(index, sequence.length - 1)
29
+ index += 1
30
+ return sequence[i] ?? 'success'
31
+ }
32
+
33
+ const server = createServer(async (req, res) => {
34
+ let url
35
+ try {
36
+ url = new URL(req.url, `http://${host}:${port}`)
37
+ } catch {
38
+ res.writeHead(400)
39
+ res.end('bad url')
40
+ return
41
+ }
42
+ if (req.method === 'GET' && /\/models$/.test(url.pathname)) {
43
+ res.writeHead(200, { 'content-type': 'application/json' })
44
+ res.end(
45
+ JSON.stringify({
46
+ object: 'list',
47
+ data: [{ id: 'mock/echo', object: 'model', owned_by: 'mock' }],
48
+ }),
49
+ )
50
+ return
51
+ }
52
+ if (req.method === 'POST' && /\/chat\/completions$/.test(url.pathname)) {
53
+ let raw = ''
54
+ for await (const c of req) raw += c
55
+ let body = {}
56
+ try {
57
+ body = JSON.parse(raw)
58
+ } catch {}
59
+ const behavior = pick()
60
+ const model = body?.model ?? 'mock/echo'
61
+ const id = 'chatcmpl-mock-' + Date.now()
62
+ requests.push({ behavior, model })
63
+ const stream = body?.stream !== false
64
+ const text = successText
65
+
66
+ if (!stream) {
67
+ const message =
68
+ behavior === 'tool_call'
69
+ ? {
70
+ role: 'assistant',
71
+ content: null,
72
+ tool_calls: makeToolCalls(toolName, toolArguments),
73
+ }
74
+ : { role: 'assistant', content: text }
75
+ res.writeHead(200, { 'content-type': 'application/json' })
76
+ res.end(
77
+ JSON.stringify({
78
+ id,
79
+ object: 'chat.completion',
80
+ model,
81
+ choices: [
82
+ {
83
+ index: 0,
84
+ message,
85
+ finish_reason: behavior === 'tool_call' ? 'tool_calls' : 'stop',
86
+ },
87
+ ],
88
+ usage: { prompt_tokens: 10, completion_tokens: 10, total_tokens: 20 },
89
+ }),
90
+ )
91
+ return
92
+ }
93
+
94
+ res.writeHead(200, {
95
+ 'content-type': 'text/event-stream',
96
+ 'cache-control': 'no-cache',
97
+ connection: 'keep-alive',
98
+ })
99
+ const send = (o) => res.write('data: ' + JSON.stringify(o) + '\n\n')
100
+ const chunk = (delta, finish = null) => ({
101
+ id,
102
+ object: 'chat.completion.chunk',
103
+ model,
104
+ choices: [{ index: 0, delta, finish_reason: finish }],
105
+ })
106
+
107
+ send(chunk({ role: 'assistant' }))
108
+
109
+ if (behavior === 'stall') {
110
+ const t = setTimeout(() => {
111
+ try {
112
+ res.end()
113
+ } catch {}
114
+ }, stallMs)
115
+ t.unref?.()
116
+ req.on('close', () => clearTimeout(t))
117
+ return
118
+ }
119
+ if (behavior === 'tool_call') {
120
+ send(chunk({ tool_calls: makeToolCallDeltas(toolName, toolArguments) }))
121
+ send(chunk({}, 'tool_calls'))
122
+ res.write('data: [DONE]\n\n')
123
+ res.end()
124
+ return
125
+ }
126
+ // success:逐块流式
127
+ for (let i = 0; i < text.length; i += chunkSize) {
128
+ send(chunk({ content: text.slice(i, i + chunkSize) }))
129
+ if (chunkDelayMs > 0) await sleep(chunkDelayMs)
130
+ }
131
+ send(chunk({}, 'stop'))
132
+ res.write('data: [DONE]\n\n')
133
+ res.end()
134
+ return
135
+ }
136
+ res.writeHead(404, { 'content-type': 'text/plain' })
137
+ res.end('not found')
138
+ })
139
+
140
+ await new Promise((resolve, reject) => {
141
+ server.once('error', reject)
142
+ server.listen(port, host, resolve)
143
+ })
144
+ const actualPort = server.address().port
145
+ return {
146
+ port: actualPort,
147
+ url: `http://${host}:${actualPort}/v1`,
148
+ requests,
149
+ close: () => new Promise((r) => server.close(() => r())),
150
+ }
151
+ }
152
+
153
+ function makeToolCalls(name, args) {
154
+ return [
155
+ {
156
+ id: 'call_mock_1',
157
+ type: 'function',
158
+ function: { name: name ?? 'mock_tool', arguments: args ?? '{}' },
159
+ },
160
+ ]
161
+ }
162
+ function makeToolCallDeltas(name, args) {
163
+ return [
164
+ {
165
+ index: 0,
166
+ id: 'call_mock_1',
167
+ type: 'function',
168
+ function: { name: name ?? 'mock_tool', arguments: args ?? '{}' },
169
+ },
170
+ ]
171
+ }
172
+
173
+ // 直接执行:读 env 起服务并打印 ready JSON(供脚本/CI 用)。
174
+ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
175
+ // --help/-h:只打印用法退出,不起服务(否则 bin 冒烟测试会占住端口)。
176
+ if (process.argv.includes('--help') || process.argv.includes('-h')) {
177
+ console.log(`dsh-llm-mock:自包含、OpenAI 兼容的脚本化 mock LLM server
178
+ 用法:
179
+ dsh-llm-mock 启动服务,打印 {"t":"ready","url":...,"port":...}
180
+ dsh-llm-mock --help 显示本帮助
181
+ 环境变量:
182
+ MOCK_PORT 监听端口(默认 8123,0 = 随机)
183
+ MOCK_HOST 监听地址(默认 127.0.0.1)
184
+ 序列: success / stall / tool_call(由 startMockServer 的 sequence 参数控制)`)
185
+ process.exit(0)
186
+ }
187
+ try {
188
+ const s = await startMockServer()
189
+ console.log(JSON.stringify({ t: 'ready', url: s.url, port: s.port }))
190
+ } catch (e) {
191
+ if (e?.code === 'EADDRINUSE') {
192
+ console.error(`端口被占用(多半是上次 mock 还活着且序列已消费)。换 MOCK_PORT 或先杀掉旧的。`)
193
+ } else {
194
+ console.error(String(e?.stack ?? e))
195
+ }
196
+ process.exit(1)
197
+ }
198
+ }