mslxdff 0.1.55 → 0.1.56

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.
Files changed (39) hide show
  1. package/README.md +1 -160
  2. package/bin/mslxdff.js +666 -26
  3. package/package.json +3 -2
  4. package/src/chat/config.js +10 -0
  5. package/src/chat/index.js +6 -0
  6. package/src/chat/prompt.js +63 -0
  7. package/src/chat/repl.js +245 -0
  8. package/src/chat/spinner.js +38 -0
  9. package/src/chat/stats.js +170 -0
  10. package/src/chat/store.js +48 -0
  11. package/src/chat/tools.js +304 -0
  12. package/src/chat/upstream.js +90 -0
  13. package/src/models.js +90 -2
  14. package/src/providers/dispatcher.js +100 -0
  15. package/src/providers/generic.js +221 -0
  16. package/src/providers/index.js +6 -0
  17. package/src/providers/keyring.js +38 -0
  18. package/src/providers/model-id.js +36 -0
  19. package/src/providers/opencode.js +20 -0
  20. package/src/providers/openrouter.js +217 -0
  21. package/src/providers/share-keys.js +53 -0
  22. package/src/providers/workbuddy-balance.js +76 -0
  23. package/src/providers/workbuddy.js +563 -0
  24. package/src/routes/chat/index.js +20 -1
  25. package/src/routes/peers.js +12 -7
  26. package/src/routes/stream.js +9 -0
  27. package/src/state.js +299 -4
  28. package/src/time.js +73 -0
  29. package/src/upstream.js +126 -8
  30. package/docs/adr/0001-reasoning-content-injection.md +0 -14
  31. package/docs/adr/0002-models-free-filter.md +0 -12
  32. package/docs/adr/0003-zero-state-no-auth.md +0 -10
  33. package/docs/adr/0004-bearer-token.md +0 -18
  34. package/docs/adr/0005-peer-mesh.md +0 -53
  35. package/docs/adr/0006-broadband-member.md +0 -103
  36. package/docs/agents/domain.md +0 -51
  37. package/docs/agents/issue-tracker.md +0 -30
  38. package/docs/agents/triage-labels.md +0 -15
  39. package/docs/plugins.md +0 -185
@@ -1,53 +0,0 @@
1
- # ADR-0005: Peer mesh for same-model failover across machines
2
-
3
- > **Update (group model):** peers are now configured through named groups, and the
4
- > group name doubles as the join password (supersedes the random join key). CLI:
5
- > `-creategroup <name>` on the leader (no address needed — the first joiner seeds
6
- > the leader's own entry from the address it connects from), `-addtogroup <leader-host> <name>`
7
- > elsewhere. Every member (leader included) re-registers with the leader on a timer
8
- > (`MSLXDFF_GROUP_SYNC_MS`, default 60s) and rebuilds its local peer list from the
9
- > freshest member map, so membership changes propagate to all nodes automatically.
10
- > The `-peer` commands are removed; peers are an internal mechanism. Wrong group
11
- > names/tokens are counted per source IP: `MSLXDFF_BAN_THRESHOLD` (default 5)
12
- > failures ban the IP for `MSLXDFF_BAN_WINDOW_MS` (default 48h); `-resetban [ip]`
13
- > clears bans.
14
-
15
- A single mslxdff instance depends on one upstream quota; when that upstream
16
- starts rate-limiting or failing for a model, the only local fallback is
17
- switching to a *different* model. That changes the model out from under the
18
- client. To keep the requested model working while the local path recovers,
19
- multiple instances can be joined into a group: when the local upstream
20
- fails for model X, the instance forwards the request (still model X) to a
21
- group member that runs its own mslxdff and has its own upstream quota.
22
-
23
- ## Design
24
-
25
- - **Peers are plain mslxdff instances.** Each peer is identified by
26
- `{ url, token }` (its bearer token, per ADR-0004). Configured with
27
- `mslxdff -peer add <token> <url> [name]`, removed with `-peer remove`,
28
- listed with `-peer list`; persisted in the state file. No new protocol —
29
- forwarding is a normal authenticated `POST /v1/chat/completions` to the
30
- peer, reusing the existing API surface.
31
- - **Local-first routing.** A request always tries the local upstream first.
32
- Only on local failure (network error or HTTP ≥ 400) does it iterate peers
33
- for the *same model*, round-robin over currently-available peers.
34
- - **Model lock.** Forwarded requests carry `x-mslxdff-model-lock: <model>`
35
- so the receiving peer uses exactly that model — it must not re-select or
36
- fall back to another model, keeping "same model, different machine" true.
37
- - **Hop bound.** Forwarded requests carry `x-mslxdff-hops` (incremented each
38
- hop). A peer receiving hops ≥ `maxHops` (default 3, `MSLXDFF_MAX_HOPS`)
39
- stops forwarding further, bounding mesh depth and preventing loops.
40
- - **Peer cooldown.** A peer that fails a request enters a cooldown window
41
- (default 30s, `MSLXDFF_PEER_COOLDOWN_MS`), during which it is skipped by
42
- the round-robin, so the mesh rotates to healthy peers instead of
43
- hammering a down one. Mirrors the model cooldown in ADR-0001.
44
-
45
- ## Why not alternatives
46
-
47
- - **Point the whole proxy at another machine** (client-side failover): the
48
- client can't detect per-model upstream failure, and every request pays the
49
- cross-machine latency even when local is healthy.
50
- - **Different model per machine**: violates the requirement of keeping the
51
- same model, and hides the model-change from the client.
52
- - **Central coordinator / service discovery**: overkill for a handful of
53
- private instances; static peer config is zero-config and debuggable.
@@ -1,103 +0,0 @@
1
- # ADR-0006: 宽带动态IP成员(broadband)经 Leader 中继共享配额
2
-
3
- > **状态**:规划完成,待实现(基于 v0.1.33)。用户确认:`--broadband` 为唯一语义,不设 `--relay` 别名;默认 `127.0.0.1` 监听。
4
-
5
- ## 1. 背景与问题
6
-
7
- 现有组模型(ADR-0005)假设组员均为公网 VPS,`A->D` 直连 `http://D公网IP:8989/v1/chat/completions` 用 `D` 的出口 IP 打 `opencode.ai`,实现 `IP级免费池` 分散。家庭宽带 `D` 有公网 IP 但:
8
-
9
- 1. **入站不可达**:无端口映射/CGNAT,`probeHealth GET http://D:8989/health` 恒 `fail`,`peer-race` 直接跳过,`D` 的配额永不被用。
10
- 2. **IP 动态**:`refreshGroupMembers` 透传旧 `myUrl`,IP 变更后 60s 同步期内全组仍用旧 IP。
11
- 3. **语义缺失**:组内无法区分 `static(VPS直连)` 与 `broadband(家庭中继)`,`-group list` 无标识。
12
-
13
- 需求:家庭 `D` 以 `broadband` 类型加入,无需公网入站,经 `Leader` 中继仍用 `D` 的家庭出口打上游,且全程可观测。
14
-
15
- ## 2. 决策
16
-
17
- 新增成员类型 `kind: "broadband"`(默认 `kind: "static"` 兼容老数据),`broadband` 隐含 `relay` 中继:
18
-
19
- * **加入**:`mslxdff -addtogroup <leader-host> <group> --broadband`(唯一旗标,不设 `--relay`)。
20
- * **监听**:`--broadband` 下默认 `listen 127.0.0.1:8989`,仅本机 `WorkBuddy` 可用;不加该旗标的为 `static` 走 `0.0.0.0`。
21
- * **共享**:`D --WS--> Leader` 常驻出站,`A(429) -> Leader -> D -> opencode.ai -> D -> Leader -> A`,上游仍见 `D` 家庭 IP。
22
- * **展示**:`-help` 新增用法行,`-group list / -status / -log` 标注 `[broadband] via leader Xs ago ip=...`。
23
-
24
- ## 3. 设计
25
-
26
- ### 3.1 成员模型
27
-
28
- `state.json groups[name].members[id]` 扩展:
29
-
30
- ```json
31
- "home-D": {
32
- "url": "relay://home-D",
33
- "token": "...",
34
- "kind": "broadband",
35
- "publicIp": "183.14.22.78",
36
- "lastSeen": 1724212345678,
37
- "status": {"upstreamOk": true, "latencyMs": 4200}
38
- }
39
- ```
40
-
41
- * `static`:`url: http://IP:8989`,参与 `probeHealth`。
42
- * `broadband`:`url: relay://id`,不探活,只看 `lastSeen`(`>90s` 标 `cooling`)+ `status`,`rankModels` 同 `slow` 5m 冷却共用。
43
-
44
- ### 3.2 连接与心跳
45
-
46
- **D 端(家庭)**
47
- * 解析 `--broadband`,建 `WS wss://Leader/v1/groups/relay/connect?group=my@mslxd`,`Authorization: Bearer <token>`。
48
- * `hello {group, token, kind:"broadband", version}` → Leader 回 `welcome {memberId}`。
49
- * `heartbeat 30s {status:{upstreamOk, models, load}}`,`publicIp` 由 Leader 的 `clientIp(req)` 填,不靠 `ifconfig.me`。
50
- * 断线指数退避 `1s/2s/4s...` 重连,IP 变更导致 `TCP RST` 自动重建即完成 IP 更新。
51
-
52
- **Leader 端(VPS)**
53
- * `GET /v1/groups/relay/connect` 升级 WS,鉴权 `membersForToken`,存 `relayConns[group][id]=ws`,`ws.remoteIp=clientIp`。
54
- * 每条 `heartbeat` 对比 `remoteIp` vs `members[id].publicIp`,变则 `saveGroups` + `evt relay-ip-change` 入 `events.log`。
55
- * `lastSeen >90s` 或 `WS断开` 立即标 `cooling`,`A` 下次 `candidatesFor` 自动避开。
56
-
57
- ### 3.3 转发路径
58
-
59
- ```
60
- 用户 -> A: POST /v1/chat/completions {model: deepseek, stream:true}
61
- A -> opencode.ai (用A IP) 429
62
- A选 candidatesFor -> [B(static), home-D(broadband via Leader), ...] 按 latency EMA
63
- A -> Leader: POST /v1/groups/relay/forward {target: home-D, body, hops:1, reqId}
64
- Leader -> D (WS): {reqId, body:{model,messages}}
65
- D -> opencode.ai (用D家庭IP) 200 SSE chunk*
66
- D --WS {reqId, data:chunk}--> Leader --HTTP chunk--> A --SSE--> 用户
67
- A断开 -> Leader --WS {abort reqId}--> D controller.abort()
68
- ```
69
-
70
- * `hops` 每跳 +1,`MAX_HOPS=3` 防环;`broadband` 节点自身 `429` 时可直接 `fetch` 到 VPS `static` 节点(出站直连,无需中继)。
71
- * 多请求复用一条 WS,`reqId` 复用现有 `relay` 日志的 `reqId/detail` 串联。
72
-
73
- ### 3.4 可观测
74
-
75
- * `-help`:` -addtogroup <host> <name> [--broadband] 宽带动态IP成员(经Leader中继,无需公网入站,默认127.0.0.1)`
76
- * `-group list`:`3. relay://home-D [broadband] ok via leader 12s ago ip=183.14.22.78`
77
- * `-log [N]`:`relay-ip-change / relay-forward / relay-heartbeat / client-abort` 均带 `reqId/detail`。
78
-
79
- ## 4. 实现清单
80
-
81
- | 文件 | 改动 |
82
- |---|---|
83
- | `bin/mslxdff.js` | `-addtogroup` 解析 `--broadband`,`WS` 客户端+心跳+重连,`listen` 在 `broadband` 下绑 `127.0.0.1`,`printHelp` 新增行,`groupSyncTimer` 对 `broadband` 组 30s |
84
- | `src/groups.js` | 成员结构 `kind/publicIp/lastSeen/status`,`addGroupMember/upsertMember/syncPeersFromMembers` 支持 `broadband`,`refreshGroupMembers` 透传 `kind` |
85
- | `src/peers.js` | 新增 `relayVia` 字段,`add({relayVia, kind}) / isRelay`,`broadband` 不进 `ordered()` 直连池 |
86
- | `src/routes.js` | 新增 `WS /v1/groups/relay/connect` + `POST /v1/groups/relay/forward`,`forwardToPeer` 中继分支,`hops` 处理 |
87
- | `src/state.js` | 持久化 `kind/publicIp/lastSeen`,新增 `load/save` 兼容 |
88
- | `src/logs.js` | `relay-*` 事件类型 |
89
-
90
- 依赖:`ws`(或 Node 22 原生 `WebSocket`,服务端需 `upgrade` 处理)。
91
-
92
- ## 5. 验证
93
-
94
- 1. **IP变更**:`D` 拨号重拨,`WS` 重连,`events.log` 出现 `relay-ip-change old->new`,`-group list` IP 更新,`A` 经 `Leader` 仍命中 `D`。
95
- 2. **配额共享**:`A` 指定 `deepseek 429`,`-log` 显示 `peer-race via=relay-leader target=home-D`,`D` 的 `upstream-done 200` 且 `detail.exitReason:normal`,回包完整。
96
- 3. **本地可用**:`D` 本机 `curl http://127.0.0.1:8989/v1/chat/completions` 200,外网 `curl http://家庭公网IP:8989` 超时(符合预期)。
97
- 4. **`-help` / `-group list`** 均含 `broadband` 标识。
98
-
99
- ## 6. 风险与取舍
100
-
101
- * `Leader` 单点中继增加 `10-30ms` 延迟,可接受;`Leader` 宕则 `broadband` 配额暂不可用(`static` 组员仍直连可用)。
102
- * 多并发复用单 `WS` 需 `reqId` 复用与背压控制,首版可限并发 3(复用 `PEER_RACE_LIMIT`)。
103
- * 不设 `--relay` 别名,术语统一为 `broadband`,内部变量 `relay` 仅作实现名。
@@ -1,51 +0,0 @@
1
- # Domain Docs
2
-
3
- How the engineering skills should consume this repo's domain documentation when exploring the codebase.
4
-
5
- ## Before exploring, read these
6
-
7
- - **`CONTEXT.md`** at the repo root, or
8
- - **`CONTEXT-MAP.md`** at the repo root if it exists — it points at one `CONTEXT.md` per context. Read each one relevant to the topic.
9
- - **`docs/adr/`** — read ADRs that touch the area you're about to work in. In multi-context repos, also check `src/<context>/docs/adr/` for context-scoped decisions.
10
-
11
- If any of these files don't exist, **proceed silently**. Don't flag their absence; don't suggest creating them upfront. The `/domain-modeling` skill (reached via `/grill-with-docs` and `/improve-codebase-architecture`) creates them lazily when terms or decisions actually get resolved.
12
-
13
- ## File structure
14
-
15
- Single-context repo (most repos):
16
-
17
- ```
18
- /
19
- ├── CONTEXT.md
20
- ├── docs/adr/
21
- │ ├── 0001-event-sourced-orders.md
22
- │ └── 0002-postgres-for-write-model.md
23
- └── src/
24
- ```
25
-
26
- Multi-context repo (presence of `CONTEXT-MAP.md` at the root):
27
-
28
- ```
29
- /
30
- ├── CONTEXT-MAP.md
31
- ├── docs/adr/ ← system-wide decisions
32
- └── src/
33
- ├── ordering/
34
- │ ├── CONTEXT.md
35
- │ └── docs/adr/ ← context-specific decisions
36
- └── billing/
37
- ├── CONTEXT.md
38
- └── docs/adr/
39
- ```
40
-
41
- ## Use the glossary's vocabulary
42
-
43
- When your output names a domain concept (in an issue title, a refactor proposal, a hypothesis, a test name), use the term as defined in `CONTEXT.md`. Don't drift to synonyms the glossary explicitly avoids.
44
-
45
- If the concept you need isn't in the glossary yet, that's a signal — either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/domain-modeling`).
46
-
47
- ## Flag ADR conflicts
48
-
49
- If your output contradicts an existing ADR, surface it explicitly rather than silently overriding:
50
-
51
- > _Contradicts ADR-0007 (event-sourced orders) — but worth reopening because…_
@@ -1,30 +0,0 @@
1
- # Issue tracker: Local Markdown
2
-
3
- Issues and specs (you may know a spec as a PRD) for this repo live as markdown files in `.scratch/`.
4
-
5
- ## Conventions
6
-
7
- - One feature per directory: `.scratch/<feature-slug>/`
8
- - The spec is `.scratch/<feature-slug>/spec.md`
9
- - Implementation issues are one file per ticket at `.scratch/<feature-slug>/issues/<NN>-<slug>.md`, numbered from `01` — never a single combined tickets file
10
- - Triage state is recorded as a `Status:` line near the top of each issue file (see `triage-labels.md` for the role strings)
11
- - Comments and conversation history append to the bottom of the file under a `## Comments` heading
12
-
13
- ## When a skill says "publish to the issue tracker"
14
-
15
- Create a new file under `.scratch/<feature-slug>/` (creating the directory if needed).
16
-
17
- ## When a skill says "fetch the relevant ticket"
18
-
19
- Read the file at the referenced path. The user will normally pass the path or the issue number directly.
20
-
21
- ## Wayfinding operations
22
-
23
- Used by `/wayfinder`. The **map** is a file with one **child** file per ticket.
24
-
25
- - **Map**: `.scratch/<effort>/map.md` — the Notes / Decisions-so-far / Fog body.
26
- - **Child ticket**: `.scratch/<effort>/issues/NN-<slug>.md`, numbered from `01`, with the question in the body. A `Type:` line records the ticket type (`research`/`prototype`/`grilling`/`task`); a `Status:` line records `claimed`/`resolved`.
27
- - **Blocking**: a `Blocked by: NN, NN` line near the top. A ticket is unblocked when every file it lists is `resolved`.
28
- - **Frontier**: scan `.scratch/<effort>/issues/` for files that are open, unblocked, and unclaimed; first by number wins.
29
- - **Claim**: set `Status: claimed` and save before any work.
30
- - **Resolve**: append the answer under an `## Answer` heading, set `Status: resolved`, then append a context pointer (gist + link) to the map's Decisions-so-far in `map.md`.
@@ -1,15 +0,0 @@
1
- # Triage Labels
2
-
3
- The skills speak in terms of five canonical triage roles. This file maps those roles to the actual label strings used in this repo's issue tracker.
4
-
5
- | Label in mattpocock/skills | Label in our tracker | Meaning |
6
- | -------------------------- | -------------------- | ---------------------------------------- |
7
- | `needs-triage` | `needs-triage` | Maintainer needs to evaluate this issue |
8
- | `needs-info` | `needs-info` | Waiting on reporter for more information |
9
- | `ready-for-agent` | `ready-for-agent` | Fully specified, ready for an AFK agent |
10
- | `ready-for-human` | `ready-for-human` | Requires human implementation |
11
- | `wontfix` | `wontfix` | Will not be actioned |
12
-
13
- When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding label string from this table.
14
-
15
- Edit the right-hand column to match whatever vocabulary you actually use.
package/docs/plugins.md DELETED
@@ -1,185 +0,0 @@
1
- # mslxdff 插件开发指南
2
-
3
- mslxdff 内置一个零依赖的插件系统:把符合约定的 `.mjs` 模块放进插件目录,daemon 启动时自动加载,在**请求链路的所有关键节点**(hook 点)调用你的代码——包括替换上游 provider 本身。**插件出错只记日志,绝不影响主链路。**
4
-
5
- ## 快速开始
6
-
7
- ### 1. 插件目录(双目录,都会被加载)
8
-
9
- ```
10
- 官方插件: <mslxdff安装目录>/plugins/ ← 随包分发,auto-update 一起更新
11
- 用户插件: ~/.config/mslxdff/plugins/ ← 你自己的正式插件,升级永不丢
12
- 完全接管: 环境变量 MSLXDFF_PLUGINS_DIR=/path/to/dir(只扫这一个)
13
- ```
14
-
15
- 优先级:同名文件时**用户目录覆盖官方目录**;加载顺序官方在前、用户在后。
16
-
17
- > 为什么不直接放安装目录?npm 升级会重置包内文件——所以自己的正式插件务必放用户目录。
18
-
19
- ### 2. 写一个最小插件
20
-
21
- 创建 `~/.config/mslxdff/plugins/hello.mjs`:
22
-
23
- ```js
24
- export default {
25
- name: "hello",
26
- version: "1.0.0",
27
- description: "我的第一个 mslxdff 插件",
28
- hooks: {
29
- "server:start": (ctx) => {
30
- console.log(`[hello] mslxdff 已启动 port=${ctx.port}`);
31
- },
32
- },
33
- };
34
- ```
35
-
36
- ### 3. 查看是否被识别
37
-
38
- ```bash
39
- mslxdff -plugins
40
- # plugins dir: C:\Users\you\.config\mslxdff\plugins
41
- # hello@1.0.0 [server:start]
42
- # 我的第一个 mslxdff 插件
43
- ```
44
-
45
- 重启 daemon(`mslxdff -stop && mslxdff`)后生效。日志里会出现 `plugins loaded (1): hello@1.0.0`。
46
-
47
- ## Hook 全表
48
-
49
- ### 请求链路(按触发顺序)
50
-
51
- | Hook | 触发时机 | ctx 内容 | 返回值语义 |
52
- |---|---|---|---|
53
- | `request:received` | 读到请求 body 后 | `{ ip, hops, headers, body }` | 返回 `{ respond: { status, body } }` **可短路请求**,直接响应客户端 |
54
- | `model:select` | 候选顺序确定后 | `{ reqId, requested, useAuto, order, hops, stream }` | 返回数组**替换候选顺序** |
55
- | `model:beforeTry` | 每个模型尝试前(循环内) | `{ reqId, requested, model, idx, hops }` | 返回 `false` 或 `{ skip: true }` **跳过该候选** |
56
- | `upstream:request` | 发往上游前 | `{ reqId, requested, model, payload, stream }` | 返回 `{ payload }` **替换本次上游负载**(含 model 字段) |
57
- | `upstream:response` | 上游响应/错误后 | `{ reqId, requested, model, status, ok, error, timing }` | 只观察 |
58
- | `relay:first-chunk` | 流式首块到达 | `{ reqId, requested, model, via, ttfMs }` | 只观察 |
59
- | `request:completed` | 请求结束(所有出口) | `{ reqId, requested, via, status, actual, durationMs, fallback?, interrupted?, error? }` | 只观察 |
60
-
61
- > `x-mslxdff-model-lock` 锁定模型时 `model:select` 不触发——锁是硬约束。
62
-
63
- ### 上游层(upstream 内部,作用于内置 client 的每次 fetch)
64
-
65
- | Hook | 触发时机 | ctx 内容 | 返回值语义 |
66
- |---|---|---|---|
67
- | `upstream:headers` | 构建请求头后 | `{ url, body, headers }` | 返回 `{ headers }` **替换请求头** |
68
- | `upstream:before-request` | fetch 调用前 | `{ url, method, body, headers }` | 返回 `{ url?, headers? }` **改目标地址/头** —— 上游不限于 opencode,可指向任意兼容端点 |
69
-
70
- ### 模型列表 / 组内转发 / 生命周期
71
-
72
- | Hook | 触发时机 | ctx 内容 | 返回值语义 |
73
- |---|---|---|---|
74
- | `models:list` | `/v1/models` 返回前 | `{ data }` | 返回 id 数组或完整 data 数组**替换对外模型列表** |
75
- | `peer:beforeForward` | 转发给组员前 | `{ reqId, peer, model, hops }` | 只观察 |
76
- | `peer:result` | 组员响应后 | `{ reqId, peer, model, ok, status, latencyMs }` | 只观察 |
77
- | `server:start` | 服务就绪 | `{ port, host, version }` | 只观察 |
78
- | `server:stop` | 关闭前 | `{ version }` | 只观察 |
79
-
80
- ### 特殊接口(非 hooks 字段)
81
-
82
- ```js
83
- export default {
84
- name: "my-plugin",
85
- // ① 订阅全部事件流(request/ordered/upstream/fallback/result...每条 evt 都会推给你)
86
- onEvent(evt) { /* fire-and-forget,抛错被吞 */ },
87
- // ② 整体替换上游 provider(接任意 OpenAI 兼容服务;多个插件声明时取第一个)
88
- async createUpstream(ctx) {
89
- // ctx = { baseUrl, authToken, env }
90
- return {
91
- chat(body) { /* 返回 fetch Response,status>=400 会走 fallback */ },
92
- preheat() { /* 可选:返回 { ok, status, ms } */ },
93
- close() { /* 可选 */ },
94
- };
95
- },
96
- hooks: { /* ...上表全部 hook */ },
97
- };
98
- ```
99
-
100
- ## 实战示例
101
-
102
- ### 改变模型列表设定(首选模型)
103
-
104
- ```js
105
- // prefer-model.mjs — 把指定模型排到最前
106
- const PREFER = "big-pickle"; // 改这里,或读你自己的配置文件
107
-
108
- export default {
109
- name: "prefer-model",
110
- hooks: {
111
- "model:select": (ctx) => {
112
- if (!ctx.order.includes(PREFER)) return; // 不在列表就不动
113
- return [PREFER, ...ctx.order.filter((m) => m !== PREFER)];
114
- },
115
- "models:list": (ctx) => {
116
- // 对外只暴露白名单模型
117
- return ctx.data.filter((m) => /big-pickle|deepseek/i.test(m.id ?? m));
118
- },
119
- },
120
- };
121
- ```
122
-
123
- ### 把上游换成任意 OpenAI 兼容服务(不改 URL 配置)
124
-
125
- ```js
126
- // redirect-upstream.mjs
127
- export default {
128
- name: "redirect-upstream",
129
- hooks: {
130
- "upstream:before-request": (ctx) => ({
131
- url: ctx.url.replace("https://opencode.ai", "https://my-proxy.example.com"),
132
- }),
133
- },
134
- };
135
- ```
136
-
137
- ### 自定义鉴权 / 限流
138
-
139
- ```js
140
- export default {
141
- name: "guard",
142
- hooks: {
143
- "request:received": (ctx) => {
144
- if (String(ctx.body?.messages?.[0]?.content || "").includes("BLOCK")) {
145
- return { respond: { status: 403, body: { error: "blocked by plugin" } } };
146
- }
147
- },
148
- },
149
- };
150
- ```
151
-
152
- ### 监控统计(事件流)
153
-
154
- ```js
155
- let total = 0;
156
- export default {
157
- name: "stats",
158
- onEvent(evt) {
159
- if (evt.type === "request") total++;
160
- if (evt.type === "result" && evt.status >= 500) console.log(`[stats] 5xx! ${evt.model}`);
161
- },
162
- };
163
- ```
164
-
165
- ## 规则与保证
166
-
167
- - **文件格式**:仅 `.mjs` / `.js`,ESM,必须有 `export default { ... }`;`name` 缺省取文件名
168
- - **串行执行**:多个插件的同一 hook 按文件名排序依次执行;返回值链式传递(前一个的输出是后一个的输入)
169
- - **错误隔离**:
170
- - 加载失败 → 不注册,错误进 events.log(`plugin-load-error`)和 `-plugins` 输出
171
- - hook 抛错 → 跳过该插件继续执行后续插件,主链路无感
172
- - **可观测**:hook 生效时 events.log 记 `plugin-hook`;报错记 `plugin-hook-error`;替换上游记 `plugin-upstream-active`
173
- - **性能**:`request:received / model:select / model:beforeTry / upstream:request` 是 await 串行的,别做慢操作(>100ms 请改 fire-and-forget);`onEvent / request:completed / relay:first-chunk / upstream:response / peer:*` 本身就是异步不阻塞
174
-
175
- ## 调试
176
-
177
- ```bash
178
- mslxdff -plugins # 列出已识别插件与其 hooks
179
- mslxdff -debug # 前台跑,实时看 plugin-hook / plugin-hook-error 事件
180
- mslxdff -log 50 # 回看事件日志
181
- ```
182
-
183
- ## 与 WorkBuddy 集成
184
-
185
- WorkBuddy 插件的 SKILL.md 可以教 AI 在用户说"切换首选模型到 xxx"时,自动改写上面的 `prefer-model.mjs` 并重启 daemon —— mslxdff 侧无需任何改动,hook 就是稳定契约。