mslxdff 0.1.43 → 0.1.54

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.
@@ -0,0 +1,30 @@
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`.
@@ -0,0 +1,15 @@
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.
@@ -0,0 +1,185 @@
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 就是稳定契约。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mslxdff",
3
- "version": "0.1.43",
3
+ "version": "0.1.54",
4
4
  "description": "测试项目,请勿使用。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -16,6 +16,8 @@
16
16
  "files": [
17
17
  "bin/",
18
18
  "src/",
19
+ "plugins/",
20
+ "docs/",
19
21
  "README.md"
20
22
  ],
21
23
  "keywords": [
@@ -0,0 +1,14 @@
1
+ # mslxdff 官方插件目录
2
+
3
+ 本目录随 mslxdff 包分发(`*.mjs` 会被自动加载)。**注意:auto-update 重装包时本目录会被重置**——你自己的正式插件请放 `~/.config/mslxdff/plugins/`(升级永不丢)。
4
+
5
+ 优先级:同名文件时用户目录(`~/.config/mslxdff/plugins/`)覆盖本目录。
6
+
7
+ ## 目录约定
8
+
9
+ - `*.mjs` / `*.js` — 插件模块(default export `{ name, version, hooks, onEvent?, createUpstream? }`)
10
+ - `*.example` — 示例模板,不会被加载;复制成 `.mjs` 并去掉后缀即可启用
11
+
12
+ ## Hook 全表
13
+
14
+ 见 `docs/plugins.md`。
@@ -0,0 +1,14 @@
1
+ // 示例:把首选模型排到最前(复制为 prefer-model.mjs 即生效;或放 ~/.config/mslxdff/plugins/ 永久生效)
2
+ const PREFER = "big-pickle";
3
+
4
+ export default {
5
+ name: "prefer-model",
6
+ version: "1.0.0",
7
+ description: `auto 时优先使用 ${PREFER}`,
8
+ hooks: {
9
+ "model:select": (ctx) => {
10
+ if (!ctx.order.includes(PREFER)) return;
11
+ return [PREFER, ...ctx.order.filter((m) => m !== PREFER)];
12
+ },
13
+ },
14
+ };
package/src/auto.js CHANGED
@@ -1,7 +1,29 @@
1
- import { loadModelErrors, saveModelErrors, loadModelLatencies, saveModelLatencies } from "./state.js";
2
-
3
- // auto 的默认首选模型:一处定义,全局生效(可用 MSLXDFF_PREFERRED_MODEL 覆盖)
4
- export const PREFERRED_MODEL = (process.env.MSLXDFF_PREFERRED_MODEL || "big-pickle").trim();
1
+ import { statSync } from "node:fs";
2
+ import { loadModelErrors, saveModelErrors, loadModelLatencies, saveModelLatencies, loadPreferredModel, defaultStateFile } from "./state.js";
3
+
4
+ // 出厂默认首选模型(state.json 的 preferredModel / env MSLXDFF_PREFERRED_MODEL 可覆盖)
5
+ export const DEFAULT_PREFERRED_MODEL = "big-pickle";
6
+ // 兼容旧导出名:语义为"出厂默认",当前生效值请用 getPreferredModel()
7
+ export const PREFERRED_MODEL = DEFAULT_PREFERRED_MODEL;
8
+
9
+ // 当前生效的首选模型:state.json > env > 出厂默认;mtime 缓存保证 daemon 热生效
10
+ const _prefCache = { mtimeMs: -1, file: null, value: null };
11
+ export function getPreferredModel({ file = defaultStateFile() } = {}) {
12
+ try {
13
+ const st = statSync(file);
14
+ if (_prefCache.file !== file || st.mtimeMs !== _prefCache.mtimeMs) {
15
+ _prefCache.file = file;
16
+ _prefCache.mtimeMs = st.mtimeMs;
17
+ _prefCache.value = loadPreferredModel({ file });
18
+ }
19
+ } catch {
20
+ _prefCache.file = file;
21
+ _prefCache.mtimeMs = -1;
22
+ _prefCache.value = null;
23
+ }
24
+ const env = (process.env.MSLXDFF_PREFERRED_MODEL || "").trim();
25
+ return _prefCache.value || env || DEFAULT_PREFERRED_MODEL;
26
+ }
5
27
 
6
28
  export const DEFAULT_AUTO_MODELS = [
7
29
  PREFERRED_MODEL,
@@ -74,14 +96,15 @@ function normLatency(e) {
74
96
  return Number.isFinite(ema) && ema > 0 ? ema : null;
75
97
  }
76
98
 
77
- export function rankModels(ids, errors = {}, { now = Date.now(), cooldownMs = 0, slowCooldownMs = 0, latencies = {} } = {}) {
99
+ export function rankModels(ids, errors = {}, { now = Date.now(), cooldownMs = 0, slowCooldownMs = 0, latencies = {}, preferred } = {}) {
100
+ const pref = preferred ?? getPreferredModel();
78
101
  return [...new Set(ids)]
79
102
  .filter(Boolean)
80
103
  .map((id) => ({
81
104
  id,
82
105
  e: normEntry(errors[id]),
83
106
  err: normEntry(errors[id])?.at ?? 0,
84
- isPreferred: id === PREFERRED_MODEL,
107
+ isPreferred: id === pref,
85
108
  cooling: inCooldown(id, errors, now, cooldownMs, slowCooldownMs),
86
109
  latency: normLatency(latencies[id]) ?? Number.MAX_SAFE_INTEGER,
87
110
  }))
@@ -122,7 +145,7 @@ export function createAutoSelector({
122
145
  }
123
146
 
124
147
  async function candidates() {
125
- return rankModels(await loadList(), lastErrorAt, { now: now(), cooldownMs, slowCooldownMs, latencies });
148
+ return rankModels(await loadList(), lastErrorAt, { now: now(), cooldownMs, slowCooldownMs, latencies, preferred: getPreferredModel({ file: file ?? undefined }) });
126
149
  }
127
150
 
128
151
  async function candidatesFor(requested) {
@@ -134,6 +157,7 @@ export function createAutoSelector({
134
157
  cooldownMs,
135
158
  slowCooldownMs,
136
159
  latencies,
160
+ preferred: getPreferredModel({ file: file ?? undefined }),
137
161
  });
138
162
  // 显式指定模型:严格优先,永不因冷却被挤到最后(原设计:A deepseek 失败 → B/D deepseek 并发 → 都失败才 fallback)
139
163
  // 冷却仅影响 auto 的择优,不影响指定模型的“很难被更改”语义
package/src/chooser.js ADDED
@@ -0,0 +1,29 @@
1
+ // 交互式模型选择器的纯渲染逻辑(便于测试);键盘循环在 bin/mslxdff.js
2
+
3
+ // items: [{ id, status?, ms?, fail?, current? }];cursor 当前高亮行
4
+ // 返回行数组(无 ANSI 颜色,纯文本标记,Windows 终端友好)
5
+ export function renderChooser(items, cursor = 0) {
6
+ return items.map((it, i) => {
7
+ const arrow = i === cursor ? "❯" : " ";
8
+ const check = it.current ? " ✓ (current)" : "";
9
+ let state = "";
10
+ if (it.fail) state = ` [fail: ${it.fail}]`;
11
+ else if (it.ms != null) state = ` [${it.ms}ms]`;
12
+ else if (it.status && it.status !== "normal") state = ` [${it.status}]`;
13
+ return `${arrow} ${it.id}${check}${state}`;
14
+ });
15
+ }
16
+
17
+ export function renderChooserHelp() {
18
+ return ["", "↑/↓ move · Enter select as default · q/Esc cancel"];
19
+ }
20
+
21
+ // 解析按键:返回 "up" | "down" | "enter" | "cancel" | null(忽略)
22
+ export function parseKey(str) {
23
+ if (!str) return null;
24
+ if (str === "\x1b[A" || str === "k") return "up";
25
+ if (str === "\x1b[B" || str === "j") return "down";
26
+ if (str === "\r" || str === "\n") return "enter";
27
+ if (str === "\x1b" || str === "q" || str === "\x03") return "cancel";
28
+ return null;
29
+ }
package/src/daemon.js CHANGED
@@ -1,84 +1,84 @@
1
- import { spawn } from "node:child_process";
2
- import { existsSync, mkdirSync, openSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";
3
- import { join, dirname } from "node:path";
4
- import os from "node:os";
5
- import { fileURLToPath } from "node:url";
6
-
7
- export function daemonDir() {
8
- return process.env.MSLXDFF_DAEMON_DIR || join(os.homedir(), ".config", "mslxdff");
9
- }
10
-
11
- export function pidFile() {
12
- return join(daemonDir(), "daemon.pid");
13
- }
14
-
15
- export function logFile() {
16
- return join(daemonDir(), "daemon.log");
17
- }
18
-
19
- export function startDaemon(args = []) {
20
- const here = fileURLToPath(import.meta.url);
21
- const entry = here.endsWith("bin/mslxdff.js")
22
- ? here
23
- : join(dirname(here), "..", "bin", "mslxdff.js");
24
- const dir = daemonDir();
25
- mkdirSync(dir, { recursive: true });
26
- const logFd = openSync(logFile(), "a", 0o600);
27
- const env = { ...process.env, MSLXDFF_DAEMON: "1" };
28
- // a -debug foreground session wouldn't pass MSLXDFF_DEBUG to the
29
- // background daemon it restores (that flag means "print events to stdout")
30
- delete env.MSLXDFF_DEBUG;
31
- const child = spawn(process.execPath, [entry, ...args, "--daemon"], {
32
- detached: true,
33
- stdio: ["ignore", logFd, logFd],
34
- env,
35
- });
36
- child.unref();
37
- return child.pid;
38
- }
39
-
40
- export function writePid(pid, version) {
41
- const dir = daemonDir();
42
- mkdirSync(dir, { recursive: true });
43
- writeFileSync(pidFile(), version ? `${pid}\n${version}` : String(pid), { mode: 0o600 });
44
- }
45
-
46
- export function readPid() {
47
- if (!existsSync(pidFile())) return null;
48
- const raw = readFileSync(pidFile(), "utf8").trim();
49
- const n = Number(raw.split("\n")[0]);
50
- return Number.isInteger(n) && n > 0 ? n : null;
51
- }
52
-
53
- export function readPidVersion() {
54
- if (!existsSync(pidFile())) return null;
55
- const raw = readFileSync(pidFile(), "utf8");
56
- const lines = raw.split("\n");
57
- return lines.length > 1 && lines[1].trim() ? lines[1].trim() : null;
58
- }
59
-
60
- // Best-effort liveness check (signal 0); ESRCH means the process is gone.
61
- export function isPidAlive(pid) {
62
- try {
63
- process.kill(pid, 0);
64
- return true;
65
- } catch (err) {
66
- return err.code !== "ESRCH";
67
- }
68
- }
69
-
70
- export function stopDaemon() {
71
- const pid = readPid();
72
- if (!pid) return { stopped: false, reason: "no pid file" };
73
- try {
74
- process.kill(pid, "SIGTERM");
75
- } catch (err) {
76
- if (err.code !== "ESRCH") throw err;
77
- }
78
- try {
79
- unlinkSync(pidFile());
80
- } catch {
81
- // already gone
82
- }
83
- return { stopped: true, pid };
84
- }
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync, mkdirSync, openSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";
3
+ import { join, dirname } from "node:path";
4
+ import os from "node:os";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ export function daemonDir() {
8
+ return process.env.MSLXDFF_DAEMON_DIR || join(os.homedir(), ".config", "mslxdff");
9
+ }
10
+
11
+ export function pidFile() {
12
+ return join(daemonDir(), "daemon.pid");
13
+ }
14
+
15
+ export function logFile() {
16
+ return join(daemonDir(), "daemon.log");
17
+ }
18
+
19
+ export function startDaemon(args = []) {
20
+ const here = fileURLToPath(import.meta.url);
21
+ const entry = here.endsWith("bin/mslxdff.js")
22
+ ? here
23
+ : join(dirname(here), "..", "bin", "mslxdff.js");
24
+ const dir = daemonDir();
25
+ mkdirSync(dir, { recursive: true });
26
+ const logFd = openSync(logFile(), "a", 0o600);
27
+ const env = { ...process.env, MSLXDFF_DAEMON: "1" };
28
+ // a -debug foreground session wouldn't pass MSLXDFF_DEBUG to the
29
+ // background daemon it restores (that flag means "print events to stdout")
30
+ delete env.MSLXDFF_DEBUG;
31
+ const child = spawn(process.execPath, [entry, ...args, "--daemon"], {
32
+ detached: true,
33
+ stdio: ["ignore", logFd, logFd],
34
+ env,
35
+ });
36
+ child.unref();
37
+ return child.pid;
38
+ }
39
+
40
+ export function writePid(pid, version) {
41
+ const dir = daemonDir();
42
+ mkdirSync(dir, { recursive: true });
43
+ writeFileSync(pidFile(), version ? `${pid}\n${version}` : String(pid), { mode: 0o600 });
44
+ }
45
+
46
+ export function readPid() {
47
+ if (!existsSync(pidFile())) return null;
48
+ const raw = readFileSync(pidFile(), "utf8").trim();
49
+ const n = Number(raw.split("\n")[0]);
50
+ return Number.isInteger(n) && n > 0 ? n : null;
51
+ }
52
+
53
+ export function readPidVersion() {
54
+ if (!existsSync(pidFile())) return null;
55
+ const raw = readFileSync(pidFile(), "utf8");
56
+ const lines = raw.split("\n");
57
+ return lines.length > 1 && lines[1].trim() ? lines[1].trim() : null;
58
+ }
59
+
60
+ // Best-effort liveness check (signal 0); ESRCH means the process is gone.
61
+ export function isPidAlive(pid) {
62
+ try {
63
+ process.kill(pid, 0);
64
+ return true;
65
+ } catch (err) {
66
+ return err.code !== "ESRCH";
67
+ }
68
+ }
69
+
70
+ export function stopDaemon() {
71
+ const pid = readPid();
72
+ if (!pid) return { stopped: false, reason: "no pid file" };
73
+ try {
74
+ process.kill(pid, "SIGTERM");
75
+ } catch (err) {
76
+ if (err.code !== "ESRCH") throw err;
77
+ }
78
+ try {
79
+ unlinkSync(pidFile());
80
+ } catch {
81
+ // already gone
82
+ }
83
+ return { stopped: true, pid };
84
+ }
package/src/logs.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { appendFileSync, readFileSync, mkdirSync, existsSync, writeFileSync, statSync } from "node:fs";
2
+ import { appendFile, stat, readFile, writeFile } from "node:fs/promises";
2
3
  import { dirname, join } from "node:path";
3
4
  import os from "node:os";
4
5
  import { defaultStateFile } from "./state.js";
@@ -40,10 +41,48 @@ function trimIfOversized(file, maxBytes = MAX_BYTES) {
40
41
  }
41
42
  }
42
43
 
44
+ async function trimIfOversizedAsync(file, maxBytes = MAX_BYTES) {
45
+ try {
46
+ const st = await stat(file);
47
+ if (st.size <= maxBytes) return;
48
+ const text = await readFile(file, "utf8");
49
+ const lines = text.split("\n");
50
+ const keep = lines.slice(-100);
51
+ await writeFile(file, keep.join("\n"));
52
+ } catch {
53
+ // ignore
54
+ }
55
+ }
56
+
57
+ function shouldSync(file) {
58
+ if (process.env.MSLXDFF_LOGS_SYNC === "1") return true;
59
+ if (process.env.MSLXDFF_DAEMON_DIR) {
60
+ const dir = process.env.MSLXDFF_DAEMON_DIR;
61
+ if (file.startsWith(dir)) return true;
62
+ }
63
+ // 显式 tmp 文件(所有 test 的 mkdtemp 前缀)走同步,保证 read-after-write 可见
64
+ const low = file.toLowerCase();
65
+ if (low.includes("mslxdff-") || low.includes("tmp") || low.includes("temp")) return true;
66
+ // 非默认目录的文件一律同步(测试传入的临时路径)
67
+ try {
68
+ const def = logDir().toLowerCase();
69
+ if (!low.startsWith(def)) return true;
70
+ } catch {}
71
+ return false;
72
+ }
73
+
43
74
  function appendLine(file, entry) {
44
75
  ensureDir(dirname(file));
45
- appendFileSync(file, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + "\n");
46
- trimIfOversized(file);
76
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry }) + "\n";
77
+ if (shouldSync(file)) {
78
+ appendFileSync(file, line);
79
+ trimIfOversized(file);
80
+ return;
81
+ }
82
+ // 线上异步:不阻塞事件循环
83
+ appendFile(file, line)
84
+ .catch(() => {})
85
+ .then(() => trimIfOversizedAsync(file).catch(() => {}));
47
86
  }
48
87
 
49
88
  export function appendCall(entry, { file = callsFile() } = {}) {