prompt-optimizer-magpie 0.2.4 → 0.2.6

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 CHANGED
@@ -71,7 +71,7 @@ magpie plugin options prompt-optimizer-magpie '{
71
71
  "optimizeTimeoutMs": 15000,
72
72
  "gatewayTimeoutMs": 25000,
73
73
  "gatewayUrl": "http://127.0.0.1:3425",
74
- "port": 0,
74
+ "port": 27497,
75
75
  "bind": "127.0.0.1"
76
76
  }'
77
77
  ```
@@ -83,6 +83,7 @@ magpie plugin options prompt-optimizer-magpie '{
83
83
  | `deciderGroup` | `group/route-decider` | 决策模型组;留空 `""` = 纯规则模式(长线程全放行,只优化首轮) |
84
84
  | `optimizeGroup` | `group/prompt-optimize` | 优化调用的模型组 |
85
85
  | `minChars` / `maxChars` | `6` / `12000` | 用户原文长度窗口。`<minChars` 同步硬放行;`maxChars` 是防整本书粘贴的绝对上限,正常范围内的长文本交决策模型判断 |
86
+ | `guardRatioLimit` | `10` | 输出护栏上限倍率:改写词元数上限 `clamp(原文词元 × N, 60, 2000)`。默认 ×10(生产实测:52 词元原文的结构化改写 430 词元曾被 ×5 误杀);配置页可改 |
86
87
  | `bypassPrefix` | `["!!", "##"]` | 用户原文以任一前缀开头则原样发送。**推荐用 `##`**:omp/pi 等 TUI 会把 `!!` 当 shell 转义吃掉,根本到不了网关;claude 类 TUI 也把 `!!` 当 bash 输入。`##` 在所有实测 agent 上都能原样到达(claude/grok 已验证 bypass-prefix) |
87
88
  | `bypassModels` | `[]` | 命中这些 `body.model` 直接放行(排除机器任务模型,如 `group/bili-summary`) |
88
89
  | `bypassAgents` | `[]` | 命中这些 `ctx.agent` 直接放行(不想被优化的 agent 白名单,任何网关调用前拦截) |
@@ -101,11 +102,11 @@ magpie plugin options prompt-optimizer-magpie '{
101
102
  | `logSkips` | `true` | `false` 时不记录常规 `pass` 事件(not-turn / self-loop / no-tools 等噪音);**失败类始终记录**(optimize-fail / decider-fail / optimize-empty / error),排障不瞎 |
102
103
  | `logOptimizes` | `true` | `false` 时不记录成功路径的 `optimize` / `decide` 事件(optimized / cache-hit / dry-run / followup 等);失败类不受此开关影响 |
103
104
 
104
- | `port` / `bind` | `0` / `127.0.0.1` | 统计服务监听:`port=0` OS 自动分配(绑定后实际端口写入 `page/port.js`,页面自动发现,适合 in-app 页面);固定端口默认 3497,**远程经 magpie web 访问时必须用固定端口**(宿主代理只认 manifest 端口)。`bind` 默认仅本机回环。**开 LAN 访问(如 `0.0.0.0`)= stats 日志里的提示词原文(`orig`/`rewritten` 截断文本)对内网可见**,只在可信内网开;serve.mjs 也可用环境变量 `POM_BIND` 覆盖 |
105
+ | `port` / `bind` | `27497` / `127.0.0.1` | 统计服务监听:**浏览器一律走 magpie 同源代理** `/_magpie/plugin/<token>/_magpie/service/`(宿主对声明了 `magpie.page.service` 的插件自动反向代理,本机与远程一致),不直连该端口。`port` 必须为 1–65535 固定值(默认 27497,与 magpie 文档一致;冲突时自动顺延尝试 +1..+5)。`bind` 默认仅本机回环;**开 `0.0.0.0` 仅限脱离 magpie 单独跑 `serve.mjs` 时使用**——stats 日志里的提示词原文(`orig`/`rewritten` 截断文本)会对网络可见,只在可信内网开;serve.mjs 也可用环境变量 `POM_BIND` 覆盖 |
105
106
 
106
107
  ## 日志布局与保留(按天分文件,7 天清理)
107
108
 
108
- 事件写在插件目录 `stats/` 下,**每天一个文件**(`stats/YYYY-MM-DD.ndjson`,UTC)。为什么不是单文件:`record()` 在 magpie plugin-host 进程里 append,而 `prune()` 在服务进程里执行——两个进程对同一个文件做「重写+rename」和「append」存在竞态(rename 瞬间落地的 append 会写进旧 inode 丢一条)。按天分文件后,保留策略变成 **unlink 整个过期日文件**,写者永远只 append 今天的文件,两边操作的 inode 不相交,竞态从结构上消除;单文件也不再无限增长,prune 从全量重写降为删文件。
109
+ 事件写在**包外用户配置区** `~/.config/magpie/prompt-optimizer-magpie/stats/`(`homedir()` 解析;Windows 同样落到 `~/.config/...`),**每天一个文件**(`YYYY-MM-DD.ndjson`,**本地时区**日界;页面时间戳同按本地时区渲染)。数据目录在包外,`magpie plugin update` 重装包目录不再丢数据;环境变量 `POM_STATS_DIR` 可显式覆盖。首次启动时若检测到包内旧 `stats/` 目录,会自动**复制**到新目录(同名文件跳过、不覆盖)并写入 `MIGRATED.txt` 标记,只迁一次。历史存量文件为 UTC 日命名,不重命名不合并——升级当天本地日与 UTC 日可能各有一个文件,属一次性过渡,读端按文件名分组不受影响。为什么不是单文件:`record()` 在 magpie plugin-host 进程里 append,而 `prune()` 在服务进程里执行——两个进程对同一个文件做「重写+rename」和「append」存在竞态(rename 瞬间落地的 append 会写进旧 inode 丢一条)。按天分文件后,保留策略变成 **unlink 整个过期日文件**,写者永远只 append 今天的文件,两边操作的 inode 不相交,竞态从结构上消除;单文件也不再无限增长,prune 从全量重写降为删文件。
109
110
 
110
111
  - `prune` 由共享的 `startStatsService` 在**两个入口**(index.mjs 宿主内服务 + serve.mjs daemon)启动时和每 24 小时执行:删除文件名日期早于 `POM_RETAIN_DAYS`(默认 `7`)的日文件;`0` 或负数 = 永久保留。只跑 in-app 页面、不部署 serve.mjs 的安装也会自动清理。
111
112
  - systemd 部署示例:`Environment=POM_RETAIN_DAYS=7`。
@@ -115,7 +116,7 @@ magpie plugin options prompt-optimizer-magpie '{
115
116
 
116
117
  - 剥离外围代码围栏;新结果和缓存命中都比对 `[REDACTED]`、双花括号占位符和反引号标识符的**数量**;字面比对容错等价写法(`{{ name }}` ≡ `{{name}}`,反引号 token 比内容),数量增减仍拦截;
117
118
  - 长度上下限按**词元数**而非字符数(中文 1 字 = 1 词元,连续英文单词/数字/标识符 = 1 词元,标点空白不计):JS `.length` 按 UTF-16 code unit 计数,天然低估中文、高估英文,同一护栏对两种语言宽严不一;
118
- - 下限 `0.4×` 原文词元(防止越改越短);上限 `clamp(5× 原文词元, 60, 2000)`——短需求给足结构化扩写空间(60 词元保底,实测 17 字需求 → 552 字提示词是期望效果),长输入最多扩 5 倍且封顶 2000 词元。生产事故驱动:182 字中文原文 → 612 字优质改写曾被字符级 ×3 上限误杀;
119
+ - 下限 `0.4×` 原文词元(防止越改越短);上限 `clamp(guardRatioLimit × 原文词元, 60, 2000)`,倍率默认 `10` 可配(配置页 `guardRatioLimit`)——短需求给足结构化扩写空间(60 词元保底,实测 17 字需求 → 552 字提示词是期望效果),长输入最多扩 N 倍且封顶 2000 词元。生产事故驱动:182 字中文原文 → 612 字优质改写曾被字符级 ×3 上限误杀;
119
120
  - 护栏触发细分为三个 reason,统计页红色分组可观测:`output-guard-short`(低于下限)/ `output-guard-long`(超上限)/ `output-guard-tokens`(token 校验失败)。
120
121
 
121
122
  替换只动最后一条 user 消息中**唯一匹配**的用户原文 span:先逐字匹配,失败后空白规范化匹配;零命中或多重命中一律放行,绝不用 `ctx.query` 整段覆盖。
@@ -128,7 +129,7 @@ magpie plugin options prompt-optimizer-magpie '{
128
129
 
129
130
  例如 `"overrides":[{"agent":"cli","model":"group/interactive","budgetMs":350},{"agent":"batch","optimizerMode":"merged"}]`。350 毫秒从进入 hook 起算,判定和改写共用;耗尽时放行原文并记录 `budget-exhausted`,0 表示直接放行。目标模型匹配的是入站 `body.model`。实验组优先选择模式,预算仍生效;线程保留原有门禁。没有匹配项使用全局配置。
130
131
 
131
- 钩子将审计事件写入插件目录 `stats/YYYY-MM-DD.ndjson`(UTC 日文件,按事件追加,写失败静默)。默认在 `optimized` / `dry-run` / `output-guard*` / `no-span` / `decide` 事件上附带先脱敏、再截断的文本(`orig`/`rewritten`,默认 600 字),插件层可直接审计每次改写质量;`logRewrites: false` 可关闭。`action`/`reason` 覆盖:`pass`(disabled / subagent / self-loop / bypass-model / origin / bypass-prefix / no-tools / not-turn / no-user-text / short-text / too-long / no-decider-followup / optimize-fail / optimize-empty / output-guard-short / output-guard-long / output-guard-tokens / merged-fail / merged-passthrough / merged-circuit-open / error)、`decide`(decider-fail / decider-fail-rule / decider-fail-merged / followup / low-confidence)、`optimize`(dry-run / optimized / merged-optimized / cache-hit / no-span)。
132
+ 钩子将审计事件写入 `~/.config/magpie/prompt-optimizer-magpie/stats/YYYY-MM-DD.ndjson`(本地时区日文件,按事件追加,写失败静默;数据目录在包外,update 不丢)。默认在 `optimized` / `dry-run` / `output-guard*` / `no-span` / `decide` 事件上附带先脱敏、再截断的文本(`orig`/`rewritten`,默认 600 字),插件层可直接审计每次改写质量;`logRewrites: false` 可关闭。`action`/`reason` 覆盖:`pass`(disabled / subagent / self-loop / bypass-model / origin / bypass-prefix / no-tools / not-turn / no-user-text / short-text / too-long / no-decider-followup / optimize-fail / optimize-empty / output-guard-short / output-guard-long / output-guard-tokens / merged-fail / merged-passthrough / merged-circuit-open / error)、`decide`(decider-fail / decider-fail-rule / decider-fail-merged / followup / low-confidence)、`optimize`(dry-run / optimized / merged-optimized / cache-hit / no-span)。
132
133
 
133
134
  决策失败后,已有助手回复的线程直接放行;首轮按实际降级路径记录 `decider-fail-rule` 或 `decider-fail-merged`。Responses 携带 `previous_response_id` 时直接放行。每个请求只上报一次终态;实际回写报 `ready` 并附返回请求体的 UTF-8 字节数,干跑或普通放行报 `skipped, 0`,最终模型调用失败报 `unavailable, 0`。
134
135
 
package/README_EN.md CHANGED
@@ -69,7 +69,7 @@ magpie plugin options prompt-optimizer-magpie '{
69
69
  "optimizeTimeoutMs": 15000,
70
70
  "gatewayTimeoutMs": 25000,
71
71
  "gatewayUrl": "http://127.0.0.1:3425",
72
- "port": 0,
72
+ "port": 27497,
73
73
  "bind": "127.0.0.1"
74
74
  }'
75
75
  ```
@@ -83,6 +83,7 @@ magpie plugin options prompt-optimizer-magpie '{
83
83
  | `cacheTtlMs` | `60000` | Atomically published rewrites in `.cache.json.d/` are keyed by agent, original text, gateway, optimize group, configured and effective modes, tier and dry-run state. A value ≤0 disables cache I/O. The old `.cache.json` stays on disk and is ignored. |
84
84
  | `debugDump` | off | Append a redacted copy of candidate requests to a file. Set a path or use `true` for `debug-dump.log` beside the hook. Sensitive fields become `[REDACTED]` before clipping. |
85
85
  | `minChars` / `maxChars` | `6` / `12000` | user-text length window. `<minChars` is a sync hard pass; `maxChars` is an absolute ceiling against book-length pastes — in-range long text is left to the decider |
86
+ | `guardRatioLimit` | `10` | output-guard ceiling ratio: rewrite unit ceiling is `clamp(orig units × N, 60, 2000)`. Default ×10 (in production a 430-unit structured rewrite of a 52-unit prompt was killed by ×5); editable on the config page |
86
87
  | `bypassPrefix` | `["!!", "##"]` | user text starting with either prefix is sent verbatim |
87
88
  | `bypassModels` | `[]` | requests whose `body.model` matches pass through (machine-task models, e.g. `group/bili-summary`) |
88
89
  | `allowedOrigins` | `[]` | when non-empty, only these `ctx.origin` values pass; a missing origin is fail-open (not blocked) |
@@ -95,7 +96,7 @@ magpie plugin options prompt-optimizer-magpie '{
95
96
  | `gatewayTimeoutMs` | `25000` | **must be set explicitly** — per-hook budget, see above |
96
97
  | `gatewayUrl` | `http://127.0.0.1:3425` | gateway loopback address (decide + optimize both call back into the gateway) |
97
98
  | `logRewrites` / `logRewriteChars` | `true` / `600` | audit log carries clipped prompt text (`orig`/`rewritten`); `false` logs lengths only |
98
- | `port` / `bind` | `0` / `127.0.0.1` | stats service listener: `port=0` = OS-assigned (the bound port is written to `page/port.js` and the page discovers it — for the in-app page); fixed-port default is 3497, and **remote access through magpie web needs a fixed port** (the host proxy targets the manifest port). `bind` defaults to loopback only. **Enabling LAN access (e.g. `0.0.0.0`) makes the clipped prompt text in the stats log (`orig`/`rewritten`) visible to your LAN** — only on trusted networks. serve.mjs also honors the `POM_BIND` env override |
99
+ | `port` / `bind` | `27497` / `127.0.0.1` | stats service listener: **the browser always goes through magpie's same-origin proxy** `/_magpie/plugin/<token>/_magpie/service/` (the host reverse-proxies plugins that declare `magpie.page.service`, local and remote alike) and never connects to this port directly. `port` must be a fixed value in 1–65535 (default 27497, matching the magpie docs; on conflict the service retries +1..+5). `bind` defaults to loopback only; **`0.0.0.0` is only for running `serve.mjs` standalone, outside magpie** — it makes the clipped prompt text in the stats log (`orig`/`rewritten`) visible to the network, so only on trusted LANs. serve.mjs also honors the `POM_BIND` env override |
99
100
 
100
101
  ## Output guardrails
101
102
 
@@ -103,7 +104,7 @@ An optimized result is only substituted after passing the guardrails, otherwise
103
104
 
104
105
  - strip surrounding code fences and verify **counts** of `[REDACTED]`, double-brace placeholders and backticked identifiers, including on cache hits; literal comparison tolerates equivalent spelling (`{{ name }}` ≡ `{{name}}`, backtick tokens compare their content), while any count change still trips the guard;
105
106
  - length bounds use **token units**, not chars (each CJK ideograph = 1 unit, each contiguous word/number/identifier run = 1, punctuation/whitespace = 0): JS `.length` counts UTF-16 code units, under-measuring CJK and over-measuring English, so one char-based rule was strict for Chinese and loose for English;
106
- - lower bound `0.4×` original units (prevents over-shrinking); upper bound `clamp(5× original units, 60, 2000)` — short prompts get room for structured expansion (60-unit floor; measured: a 17-char request → a 552-char prompt is the desired outcome), long inputs may expand at most 5× capped at 2000 units. Production-incident driven: a 182-char Chinese orig → 612-char good rewrite was killed by the char-based ×3 ceiling;
107
+ - lower bound `0.4×` original units (prevents over-shrinking); upper bound `clamp(guardRatioLimit × original units, 60, 2000)` — ratio defaults to `10` and is configurable (config page `guardRatioLimit`). Short prompts get room for structured expansion (60-unit floor; measured: a 17-char request → a 552-char prompt is the desired outcome); long inputs may expand at most N× capped at 2000 units. Production-incident driven: a 182-char Chinese orig → 612-char good rewrite was killed by the char-based ×3 ceiling;
107
108
  - guard trips split into three red-group reasons on the stats page: `output-guard-short` (below floor) / `output-guard-long` (above ceiling) / `output-guard-tokens` (token check failed).
108
109
 
109
110
  Substitution touches only the **uniquely matched** user-text span in the last user message: verbatim match first, then whitespace-normalized; zero or multiple hits → pass through. `ctx.query` is never used to overwrite the whole message.
@@ -116,7 +117,7 @@ Enable `rollout` only for agents whose `ctx.session` is stable across retries. E
116
117
 
117
118
  Example: `"overrides":[{"agent":"cli","model":"group/interactive","budgetMs":350},{"agent":"batch","optimizerMode":"merged"}]`. The 350 ms budget starts at hook entry and is shared by decision and rewrite calls. Exhaustion passes the original with reason `budget-exhausted`; zero passes immediately. Model selectors match inbound `body.model`. Rollout arms take precedence over the first-turn mode override, while the budget still applies. Threads keep their existing gates; unmatched requests use global settings.
118
119
 
119
- The hook appends audit events to the daily file `stats/YYYY-MM-DD.ndjson` in the plugin directory (UTC, append-only, write failures are silent). By default `optimized` / `dry-run` / `output-guard*` / `no-span` / `decide` events carry redacted, clipped prompt text (`orig`/`rewritten`, 600 chars by default) so every rewrite can be audited at the plugin layer; set `logRewrites: false` to log lengths only. `action`/`reason` cover: `pass` (disabled / subagent / self-loop / bypass-model / origin / bypass-prefix / no-tools / not-turn / no-user-text / short-text / too-long / no-decider-followup / optimize-fail / optimize-empty / output-guard-short / output-guard-long / output-guard-tokens / merged-fail / merged-passthrough / merged-circuit-open / error), `decide` (decider-fail / decider-fail-rule / decider-fail-merged / followup / low-confidence), `optimize` (dry-run / optimized / merged-optimized / cache-hit / no-span).
120
+ The hook appends audit events to the daily file `YYYY-MM-DD.ndjson` under `~/.config/magpie/prompt-optimizer-magpie/stats/` (resolved from `homedir()`; Windows uses `~/.config/...` too — local-timezone day boundaries, append-only, write failures are silent; page timestamps render in local time). The data dir lives **outside the package**, so `magpie plugin update` reinstalls no longer wipe it; set `POM_STATS_DIR` to override. On first start, a legacy package-internal `stats/` dir is **copied** to the new location (same-name files skipped, never overwritten; a `MIGRATED.txt` marker makes it one-shot). Existing files are UTC-day named and are neither renamed nor merged — on upgrade day a local-day and a UTC-day file may coexist; a one-off transition, harmless to the filename-grouped reader. By default `optimized` / `dry-run` / `output-guard*` / `no-span` / `decide` events carry redacted, clipped prompt text (`orig`/`rewritten`, 600 chars by default) so every rewrite can be audited at the plugin layer; set `logRewrites: false` to log lengths only. `action`/`reason` cover: `pass` (disabled / subagent / self-loop / bypass-model / origin / bypass-prefix / no-tools / not-turn / no-user-text / short-text / too-long / no-decider-followup / optimize-fail / optimize-empty / output-guard-short / output-guard-long / output-guard-tokens / merged-fail / merged-passthrough / merged-circuit-open / error), `decide` (decider-fail / decider-fail-rule / decider-fail-merged / followup / low-confidence), `optimize` (dry-run / optimized / merged-optimized / cache-hit / no-span).
120
121
 
121
122
  Retention: the active listener (embedded service or standalone daemon) prunes day files older than `POM_RETAIN_DAYS` (default `7`) at startup and every 24h; `0`/negative keeps everything. Installs that only use the in-app page never grow `stats/` unbounded either. The legacy single-file `stats.ndjson` is no longer read — archive it yourself if you want the history.
122
123
 
package/hooks.mjs CHANGED
@@ -26,6 +26,9 @@ const DEFAULTS = {
26
26
  skipToolless: true,
27
27
  cacheTtlMs: 60000,
28
28
  deciderTimeoutMs: 1500,
29
+ // 输出护栏上限倍率:clamp(origUnits * guardRatioLimit, 60, 2000)。生产
30
+ // 案例 2026-11-22:52 词元原文 ×5 上限 260 误杀 430 词元改写 → 默认 ×10。
31
+ guardRatioLimit: 10,
29
32
  optimizeTimeoutMs: 15000,
30
33
  // merged 模式:单次 optimize 调用同时完成模板选择 + 改写(首行标记协议)。
31
34
  // optimizerMode: "auto"(默认,现行为)| "merged"(跳过 decider,首轮直接 merged)。
@@ -74,6 +77,8 @@ export async function onRequest(body, ctx) {
74
77
  durationMs: Date.now() - t0,
75
78
  inputChars: x.in || 0,
76
79
  outputChars: x.out || 0,
80
+ ...(x.inUnits !== undefined && { inputUnits: x.inUnits }),
81
+ ...(x.outUnits !== undefined && { outputUnits: x.outUnits }),
77
82
  dryRun: !!o.dryRun,
78
83
  ...(x.decideMs !== undefined && { decideMs: x.decideMs }),
79
84
  ...(x.optimizeMs !== undefined && { optimizeMs: x.optimizeMs }),
@@ -124,10 +129,10 @@ export async function onRequest(body, ctx) {
124
129
  } catch {}
125
130
  }
126
131
  if (prefixes.some((p) => orig.startsWith(p))) return pass("bypass-prefix");
127
- if (orig.length < o.minChars) return pass("short-text", { in: orig.length });
128
- if (orig.length > o.maxChars) return pass("too-long", { in: orig.length });
132
+ if (orig.length < o.minChars) return pass("short-text", { in: orig.length, inUnits: countUnits(orig) });
133
+ if (orig.length > o.maxChars) return pass("too-long", { in: orig.length, inUnits: countUnits(orig) });
129
134
 
130
- const size = { in: orig.length };
135
+ const size = { in: orig.length, inUnits: countUnits(orig) };
131
136
  const input = { ...size, origText: orig };
132
137
  if (protocol === "responses" && body.previous_response_id) return pass("no-decider-followup", size);
133
138
  const thread = hasAssistantReply(body, protocol);
@@ -159,7 +164,7 @@ export async function onRequest(body, ctx) {
159
164
  let d;
160
165
  if (!beginCall("deciderTimeoutMs")) return pass("budget-exhausted", size);
161
166
  const tDecide = Date.now();
162
- try { d = await decide(o, thread, orig); } catch (error) {
167
+ try { d = await decide(o, thread, orig, timeoutSignal(ctx, o.deciderTimeoutMs)); } catch (error) {
163
168
  if (expired(error)) return pass("budget-exhausted", size);
164
169
  } finally { input.decideMs = Date.now() - tDecide; }
165
170
  if (remaining() <= 0) return pass("budget-exhausted", size);
@@ -209,7 +214,7 @@ export async function onRequest(body, ctx) {
209
214
  let parsed;
210
215
  const tOpt = Date.now();
211
216
  try {
212
- const raw = await completion(o, mergedSystemPrompt(langSuffix), orig);
217
+ const raw = await completion(o, mergedSystemPrompt(langSuffix), orig, timeoutSignal(ctx, o.optimizeTimeoutMs));
213
218
  parsed = parseMerged(raw, langSuffix);
214
219
  } catch (error) {
215
220
  if (expired(error)) return pass("budget-exhausted", size);
@@ -224,7 +229,7 @@ export async function onRequest(body, ctx) {
224
229
  out = parsed.rest;
225
230
  } else {
226
231
  const tOpt = Date.now();
227
- try { out = await optimize(o, orig, templateId); } catch (error) {
232
+ try { out = await optimize(o, orig, templateId, timeoutSignal(ctx, o.optimizeTimeoutMs)); } catch (error) {
228
233
  return pass(expired(error) ? "budget-exhausted" : "optimize-fail", size);
229
234
  } finally { input.optimizeMs = Date.now() - tOpt; }
230
235
  if (remaining() <= 0) return pass("budget-exhausted", size);
@@ -233,9 +238,9 @@ export async function onRequest(body, ctx) {
233
238
  }
234
239
  }
235
240
 
236
- const audit = { ...input, out: out.length, newText: out, markCache: fromCache };
237
241
  const origUnits = countUnits(orig), outUnits = countUnits(out);
238
- const maxUnits = Math.min(Math.max(origUnits * 5, 60), 2000);
242
+ const audit = { ...input, out: out.length, outUnits, newText: out, markCache: fromCache };
243
+ const maxUnits = Math.min(Math.max(origUnits * (o.guardRatioLimit || 10), 60), 2000);
239
244
  if (outUnits < origUnits * 0.4) return pass("output-guard-short", audit);
240
245
  if (outUnits > maxUnits) return pass("output-guard-long", audit);
241
246
  if (!preservesTokens(orig, out)) return pass("output-guard-tokens", audit);
@@ -257,7 +262,15 @@ export async function onRequest(body, ctx) {
257
262
  // System One decider: is the newest user input a new task or a follow-up?
258
263
  // `orig` is sent verbatim in state.latestUserInput — without it the model
259
264
  // has nothing to classify and would just guess.
260
- async function decide(o, thread, orig) {
265
+ // Host budget first: combine ctx.signal (magpie giving up on the hook) with
266
+ // our own timeout so an abandoned hook stops burning gateway tokens.
267
+ function timeoutSignal(ctx, ms) {
268
+ const t = AbortSignal.timeout(ms);
269
+ const host = ctx?.signal;
270
+ return host && AbortSignal.any ? AbortSignal.any([host, t]) : t;
271
+ }
272
+
273
+ async function decide(o, thread, orig, signal) {
261
274
  const res = await fetch(`${o.gatewayUrl}/v1/systemone`, {
262
275
  method: "POST",
263
276
  headers: { "content-type": "application/json" },
@@ -266,7 +279,7 @@ async function decide(o, thread, orig) {
266
279
  state: { hasAssistantReply: thread, latestUserInput: orig, inputChars: orig.length },
267
280
  questions,
268
281
  }),
269
- signal: AbortSignal.timeout(o.deciderTimeoutMs),
282
+ signal,
270
283
  });
271
284
  if (!res.ok) return undefined;
272
285
  const j = await res.json();
@@ -282,14 +295,14 @@ function hasAssistantReply(body, protocol) {
282
295
  return Array.isArray(arr) && arr.some((m) => m && (m.role === "assistant" || m.role === "model"));
283
296
  }
284
297
 
285
- async function optimize(o, orig, templateId) {
298
+ async function optimize(o, orig, templateId, signal) {
286
299
  const tpl = getTemplate(templateId);
287
300
  if (!tpl) return undefined;
288
301
  const user = MUSTACHE.test(tpl.user) ? tpl.user.replace(MUSTACHE, () => JSON.stringify(orig)) : `${tpl.user}\n\n${orig}`;
289
- return completion(o, `${tpl.system}\n\n${TAIL_NOTE}`, user);
302
+ return completion(o, `${tpl.system}\n\n${TAIL_NOTE}`, user, signal);
290
303
  }
291
304
 
292
- async function completion(o, system, user) {
305
+ async function completion(o, system, user, signal) {
293
306
  const res = await fetch(`${o.gatewayUrl}/v1/chat/completions`, {
294
307
  method: "POST",
295
308
  headers: { "content-type": "application/json" },
@@ -301,7 +314,7 @@ async function completion(o, system, user) {
301
314
  { role: "user", content: user },
302
315
  ],
303
316
  }),
304
- signal: AbortSignal.timeout(o.optimizeTimeoutMs),
317
+ signal,
305
318
  });
306
319
  if (!res.ok) return undefined;
307
320
  const j = await res.json();
package/index.mjs CHANGED
@@ -10,6 +10,7 @@ import { writeFileSync } from "node:fs";
10
10
  import { join, dirname } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { startStatsService } from "./lib/stats-service.mjs";
13
+ import { resolveStatsDir, migrateLegacyStats } from "./lib/stats.mjs";
13
14
 
14
15
  const PAGE_DIR = join(dirname(fileURLToPath(import.meta.url)), "page");
15
16
 
@@ -19,24 +20,26 @@ export default {
19
20
  id: "prompt-optimizer-magpie",
20
21
  server: async (_input, options) => {
21
22
  if (!started) {
23
+ // One-shot: bring package-internal legacy stats/ over (survives updates).
24
+ if (migrateLegacyStats()) console.log("pom: migrated legacy stats/ to " + resolveStatsDir());
22
25
  started = startStatsService({
26
+ statsDir: resolveStatsDir(),
23
27
  // options.port: magpie.page.service.option "port" in package.json;
24
- // 0 = ephemeral — `|| 3497` would silently swallow it.
25
- port: Number.isFinite(Number(options?.port)) ? Number(options.port) : 3497,
26
- // options.bind: LAN opt-in ("0.0.0.0" / a NIC address). Default
27
- // 127.0.0.1 — stats day-files carry clipped prompt text.
28
+ // 0 = ephemeral — `|| 27497` would silently swallow it.
29
+ port: Number.isFinite(Number(options?.port)) ? Number(options.port) : 27497,
30
+ // options.bind: default 127.0.0.1 — the browser goes through
31
+ // magpie's same-origin proxy, so LAN exposure is never needed;
32
+ // stats day-files carry clipped prompt text.
28
33
  bind: typeof options?.bind === "string" && options.bind ? options.bind : "127.0.0.1",
29
34
  // options.configPage: enable the /?page=config sub-page (default off).
30
35
  options: { configPage: options?.configPage === true },
31
36
  }).then((svc) => {
32
- // port 0 discovery: the host's hello.service targets the manifest
33
- // port when the option is 0 (its portOf rejects 0) and a desktop
34
- // window never sets magpie.service — the one channel that reaches
35
- // the sandboxed page is a file beside app.js, which it loads after
36
- // the bridge (page/app.js reads window.__POM_PORT__).
37
+ // The page no longer reads port.js (same-origin proxy navigation),
38
+ // but the host may probe it and serve.mjs dev mode uses it; keep
39
+ // publishing the actual bound port for those readers.
37
40
  try {
38
41
  writeFileSync(join(PAGE_DIR, "port.js"), `window.__POM_PORT__ = ${svc.port};\n`);
39
- } catch { /* read-only install: page falls back to 3497 */ }
42
+ } catch { /* read-only install: no reader left, harmless */ }
40
43
  return svc;
41
44
  }).catch((error) => {
42
45
  started = null;
@@ -51,5 +54,7 @@ export default {
51
54
  },
52
55
  };
53
56
 
54
- // test-only: stop the singleton service (page/port.js stays behind, stale)
55
- export const __testClose = () => started?.then((s) => s.close()).catch(() => {});
57
+ // test-only: stop the singleton service (page/port.js stays behind, stale).
58
+ // Exported as an OBJECT on purpose: magpie calls every exported FUNCTION as a
59
+ // plugin (docs FAQ), so a function export here would be invoked by the host.
60
+ export const __testHooks = { close: () => started?.then((s) => s.close()).catch(() => {}) };
@@ -47,6 +47,7 @@ export const CONFIG_FIELDS = [
47
47
  { key: "optimizerMode", type: "enum", def: "auto", choices: ["auto", "merged"] },
48
48
  { key: "minChars", type: "int", def: 6, min: 1, max: 200 },
49
49
  { key: "maxChars", type: "int", def: 12000, min: 1000, max: 100000 },
50
+ { key: "guardRatioLimit", type: "int", def: 10, min: 1, max: 100 },
50
51
  { key: "logSkips", type: "bool", def: true },
51
52
  { key: "logOptimizes", type: "bool", def: true },
52
53
  { key: "deciderGroup", type: "string", def: "group/route-decider", maxLen: 200 },
@@ -47,7 +47,7 @@ export const T = {
47
47
  colAction: ["动作", "action"],
48
48
  colReason: ["reason", "reason"],
49
49
  skippedAsIs: ["原样跳过", "skipped as-is"],
50
- colInOut: ["输入/输出字符", "in/out"],
50
+ colInOut: ["输入/输出词元", "in/out units"],
51
51
  colView: ["详情", "view"],
52
52
  prev: ["上一页", "prev"],
53
53
  next: ["下一页", "next"],
@@ -90,6 +90,7 @@ export const T = {
90
90
  cfgOptimizerMode: ["优化模式", "optimizer mode"],
91
91
  cfgMinChars: ["最小字符数", "min chars"],
92
92
  cfgMaxChars: ["最大字符数", "max chars"],
93
+ cfgGuardRatioLimit: ["护栏上限倍率", "guard ratio limit"],
93
94
  cfgLogSkips: ["记录跳过事件", "log skipped events"],
94
95
  cfgLogOptimizes: ["记录改写事件", "log optimize events"],
95
96
  cfgDeciderGroup: ["判定模型组", "decider model group"],
@@ -102,13 +103,14 @@ export const T = {
102
103
  hintOptimizerMode: ["auto = 判定+改写按各自模型组两段式;merged = 单次合并调用(决策组可空)", "auto = decide+rewrite as two calls per their groups; merged = single combined call (decider group may be empty)"],
103
104
  hintMinChars: ["短于该字符数的提示词不优化(默认 6)", "prompts shorter than this are skipped (default 6)"],
104
105
  hintMaxChars: ["超过该字符数的提示词不优化(默认 12000)", "prompts longer than this are skipped (default 12000)"],
106
+ hintGuardRatioLimit: ["改写词元数的上限倍率 clamp(原文词元 × N, 60, 2000)(默认 10)", "ceiling for rewrite units: clamp(orig units × N, 60, 2000) (default 10)"],
105
107
  hintLogSkips: ["跳过事件是否记入统计文件", "whether skipped events are written to stats"],
106
108
  hintLogOptimizes: ["改写事件是否记入统计文件", "whether optimize events are written to stats"],
107
109
  hintDeciderGroup: ["判定「新任务还是追问」所用模型组", "model group used to decide new-task vs follow-up"],
108
110
  hintOptimizeGroup: ["执行提示词改写所用模型组", "model group used to rewrite prompts"],
109
111
  hintDeciderTimeoutMs: ["判定调用超时毫秒,超时按失败处理(默认 1500)", "decider call timeout in ms; timeout counts as failure (default 1500)"],
110
112
  hintOptimizeTimeoutMs: ["改写调用超时毫秒,超时放行原文(默认 15000)", "optimizer call timeout in ms; timeout passes the original through (default 15000)"],
111
- hintPort: ["0 = 自动选空闲端口(默认,in-app 页面自动发现);远程 magpie web 访问需固定端口(默认 3497)", "0 = auto-pick a free port (default; the in-app page discovers it); remote access via magpie web needs a fixed port (default 3497)"],
113
+ hintPort: ["固定端口 1–65535(默认 27497)。页面走 magpie 同源代理,不直连该端口;仅本机 serve.mjs 开发模式直接访问", "fixed port 1–65535 (default 27497). The page goes through magpie's same-origin proxy and never connects to this port; direct access only in local serve.mjs dev mode"],
112
114
  cfgSubmit: ["保存", "Save"],
113
115
  cfgErrInt: ["必须是整数", "must be an integer"],
114
116
  cfgErrRange: ["超出允许范围", "out of allowed range"],
@@ -157,7 +159,16 @@ export const T = {
157
159
  "This path does not record prompt text: pass / decide paths log metadata only; the rewrite path records orig/rewritten (controlled by logRewrites). What is shown is the audit clip (first 600 chars).",
158
160
  ],
159
161
  all: ["全部", "all"],
162
+ tzNote: ["时间为本地时区({tz})", "times are in the local timezone ({tz})"],
160
163
  };
164
+
165
+ // Local-timezone `YYYY-MM-DD HH:mm:ss` — the page used to show UTC, 8h
166
+ // behind CST day boundaries. Day-file names went local in the same change.
167
+ export function localStamp(ts) {
168
+ const d = new Date(ts);
169
+ const p = (n) => String(n).padStart(2, "0");
170
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
171
+ }
161
172
  // 双语文案 helper:zh 恒为 [0],en 恒为 [1]。
162
173
  const zh = (k, ...a) => (typeof T[k] === "function" ? T[k](...a)[0] : T[k][0]);
163
174
  const en = (k, ...a) => (typeof T[k] === "function" ? T[k](...a)[1] : T[k][1]);
@@ -165,9 +176,21 @@ const en = (k, ...a) => (typeof T[k] === "function" ? T[k](...a)[1] : T[k][1]);
165
176
  const bi = (k, ...a) => `<span data-lang="zh">${esc(zh(k, ...a))}</span><span data-lang="en">${esc(en(k, ...a))}</span>`;
166
177
 
167
178
  const VARS = "bg,card,fg,fg-2,muted,faint,line,accent,accent-fg,green,red,amber".split(",");
168
- const css = () => `
179
+ export const css = () => `
169
180
  :root { color-scheme: light dark;
170
- --space-1: .25rem; --space-2: .5rem; --space-3: 1rem; --space-4: 1.5rem; }
181
+ --space-1: .25rem; --space-2: .5rem; --space-3: 1rem; --space-4: 1.5rem;
182
+ /* Semantic pairs: stats runs on its own port, host --magpie-* never
183
+ exists, and the old CanvasText fallback collapsed every tag to white
184
+ in dark theme. light-dark() adapts without JS; a host that injects
185
+ --magpie-* still wins. Dark side is the 300 ramp for ≥4.5:1 on #121212. */
186
+ --green-l: #15803d; --green-d: #4ade80;
187
+ --amber-l: #b45309; --amber-d: #fbbf24;
188
+ --red-l: #b91c1c; --red-d: #f87171;
189
+ --accent-l: #1d4ed8; --accent-d: #60a5fa;
190
+ --sem-green: var(--magpie-green, light-dark(var(--green-l), var(--green-d)));
191
+ --sem-amber: var(--magpie-amber, light-dark(var(--amber-l), var(--amber-d)));
192
+ --sem-red: var(--magpie-red, light-dark(var(--red-l), var(--red-d)));
193
+ --sem-accent: var(--magpie-accent, light-dark(var(--accent-l), var(--accent-d))); }
171
194
  html[data-lang="zh"] [data-lang="en"], html[data-lang="en"] [data-lang="zh"] { display: none; }
172
195
  body { font: 13px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; margin: 0;
173
196
  padding: var(--space-4) var(--space-3) 3rem; max-width: 64rem; margin-inline: auto;
@@ -179,8 +202,8 @@ const css = () => `
179
202
  border-radius: 8px; padding: var(--space-2) var(--space-3); min-width: 9rem; }
180
203
  .kpi b { font-size: 1.35rem; display: block; font-variant-numeric: tabular-nums; }
181
204
  /* KPI semantic colors on the value text only; cards stay neutral. */
182
- .kpi b.v-amber { color: var(--magpie-amber, var(--magpie-warn, #b45309)); }
183
- .kpi b.v-green { color: var(--magpie-green, var(--magpie-success, #15803d)); }
205
+ .kpi b.v-amber { color: var(--sem-amber); }
206
+ .kpi b.v-green { color: var(--sem-green); }
184
207
  .kpi b.v-muted { color: var(--magpie-muted, GrayText); }
185
208
  .kpi span { color: var(--magpie-muted, GrayText); font-size: 11px; }
186
209
  /* A. semantic nav, underline tabs via pseudo-element — no size change on state,
@@ -191,14 +214,14 @@ const css = () => `
191
214
  text-decoration: none; border-block-end: 2px solid transparent; }
192
215
  nav.tabs a:hover { color: var(--magpie-fg, CanvasText); }
193
216
  nav.tabs a[aria-current="page"] { color: var(--magpie-fg, CanvasText); font-weight: 600;
194
- border-block-end-color: var(--magpie-accent, AccentColor); }
217
+ border-block-end-color: var(--sem-accent); }
195
218
  /* percentile switcher: same underline-tab affordance as nav.tabs, compact */
196
219
  nav.pct-switch { display: flex; gap: var(--space-2); }
197
220
  nav.pct-switch a { padding: var(--space-1) var(--space-2); color: var(--magpie-fg-2, GrayText);
198
221
  text-decoration: none; border-block-end: 2px solid transparent; font-variant-numeric: tabular-nums; }
199
222
  nav.pct-switch a:hover { color: var(--magpie-fg, CanvasText); }
200
223
  nav.pct-switch a[aria-current="true"] { color: var(--magpie-fg, CanvasText); font-weight: 600;
201
- border-block-end-color: var(--magpie-accent, AccentColor); }
224
+ border-block-end-color: var(--sem-accent); }
202
225
  /* B. responsive tables: wrapper region + sticky head + stacked cards under 40em. */
203
226
  .table-wrapper { container-type: inline-size; overflow-x: auto; }
204
227
  table { border-collapse: separate; border-spacing: 0; width: 100%; font-size: 12px; margin-top: var(--space-1); font-variant-numeric: tabular-nums; }
@@ -222,22 +245,22 @@ const css = () => `
222
245
  border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 4px; padding: .25rem var(--space-2); }
223
246
  button { cursor: pointer; }
224
247
  .pager { display: flex; gap: var(--space-3); align-items: center; margin: var(--space-3) 0; font-size: 12px; }
225
- .pager a { color: var(--magpie-accent, LinkText); }
226
- td a { color: var(--magpie-accent, LinkText); }
248
+ .pager a { color: var(--sem-accent); }
249
+ td a { color: var(--sem-accent); }
227
250
  .detail-cols { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-3); margin-top: var(--space-2); }
228
251
  .detail-cols h3 { margin: 0 0 var(--space-1); font-size: .85rem; color: var(--magpie-fg-2, GrayText); }
229
252
  .detail-cols pre { margin: 0; padding: var(--space-2); overflow: auto; max-height: 24rem; white-space: pre-wrap;
230
253
  word-break: break-word; background: var(--magpie-card, Canvas); font-family: ui-monospace, monospace;
231
254
  border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 8px; font-size: 12px; }
232
255
  @media (max-width: 60rem) { .detail-cols { grid-template-columns: 1fr; } }
233
- .warn { color: var(--magpie-amber, CanvasText); }
256
+ .warn { color: var(--sem-amber); }
234
257
  .tag { display: inline-block; border-radius: 4px; padding: 0 .4rem; font-size: 11px;
235
258
  border: 1px solid var(--magpie-line, ButtonBorder); }
236
- .tag-green { color: var(--magpie-green, CanvasText); border-color: var(--magpie-green, CanvasText); }
237
- .tag-amber { color: var(--magpie-amber, CanvasText); border-color: var(--magpie-amber, CanvasText); }
238
- .tag-red { color: var(--magpie-red, CanvasText); border-color: var(--magpie-red, CanvasText); }
259
+ .tag-green { color: var(--sem-green); border-color: var(--sem-green); }
260
+ .tag-amber { color: var(--sem-amber); border-color: var(--sem-amber); }
261
+ .tag-red { color: var(--sem-red); border-color: var(--sem-red); }
239
262
  .tag-muted { color: var(--magpie-muted, GrayText); }
240
- .tag-accent { color: var(--magpie-accent, LinkText); border-color: var(--magpie-accent, LinkText); }
263
+ .tag-accent { color: var(--sem-accent); border-color: var(--sem-accent); }
241
264
  .legend { margin-top: var(--space-3); }
242
265
  .legend summary { cursor: pointer; color: var(--magpie-fg-2, GrayText); font-size: 12px; }
243
266
  .legend dl { display: grid; grid-template-columns: max-content 1fr; gap: var(--space-1) var(--space-3); margin: var(--space-2) 0 0; font-size: 12px; }
@@ -246,15 +269,15 @@ const css = () => `
246
269
  form[method="POST"] label { display: flex; gap: var(--space-2); align-items: center; margin: .35rem 0; }
247
270
  form[method="POST"] .k { min-width: 11rem; font-family: ui-monospace, monospace; font-size: 12px; }
248
271
  form[method="POST"] input[type="text"], form[method="POST"] select { background: var(--magpie-bg-2, Canvas); color: var(--magpie-fg, CanvasText); border: 1px solid var(--magpie-border, CanvasText); border-radius: 4px; padding: .2rem .4rem; }
249
- .cfg-saved { color: var(--magpie-success, var(--magpie-green, #16a34a)); border: 1px solid var(--magpie-success, var(--magpie-green, #16a34a)); border-radius: 4px; padding: var(--space-1) var(--space-2); max-width: 46rem; }
272
+ .cfg-saved { color: var(--sem-green); border: 1px solid var(--sem-green); border-radius: 4px; padding: var(--space-1) var(--space-2); max-width: 46rem; }
250
273
  .skipped { color: var(--magpie-muted, GrayText); }
251
- .cfg-err input[type="text"], .cfg-err select { border-color: var(--magpie-danger, var(--magpie-red, #dc2626)); }
252
- .cfg-errmsg { color: var(--magpie-danger, var(--magpie-red, #dc2626)); font-style: normal; font-size: 12px; }
274
+ .cfg-err input[type="text"], .cfg-err select { border-color: var(--sem-red); }
275
+ .cfg-errmsg { color: var(--sem-red); font-style: normal; font-size: 12px; }
253
276
  .field-hint { display: block; font-size: 12px; color: var(--magpie-fg-2, var(--magpie-muted, GrayText)); margin: var(--space-1) 0 0; }
254
277
  /* C. focus ring on every focusable element. */
255
278
  a:focus-visible, button:focus-visible, select:focus-visible, input:focus-visible,
256
279
  summary:focus-visible, [tabindex]:focus-visible {
257
- outline: 2px solid var(--magpie-accent, AccentColor); outline-offset: 2px; }
280
+ outline: 2px solid var(--sem-accent); outline-offset: 2px; }
258
281
  `;
259
282
 
260
283
  // ── day files & detail ids ─────────────────────────────────────────────────
@@ -409,7 +432,7 @@ function reasonLegend() {
409
432
  .map((k) => `<dt>${tag(k.slice(2), group)}</dt><dd>${bi(k)}</dd>`).join("");
410
433
  return `<details class="legend"><summary>${bi("legendTitle")}</summary>
411
434
  ${LEGEND_GROUPS.map(([titleKey, group]) => `<h3>${bi(titleKey)}</h3><dl>${section(group)}</dl>`).join("\n")}
412
- <p class="empty">${bi("legendNote")}</p></details>`;
435
+ <p class="empty">${bi("legendNote")}</p><p class="empty">${bi("tzNote").replaceAll("{tz}", Intl.DateTimeFormat().resolvedOptions().timeZone || "local")}</p></details>`;
413
436
  }
414
437
 
415
438
  // Main list page: KPI cards, both summary tables (with empty-state notes),
@@ -472,9 +495,9 @@ export function renderPage(stats, events, q = {}) {
472
495
  const rowsHtml = rows.length
473
496
  ? rows.map((e) => `<tr>
474
497
  <td><a href="${qs(q, { detail: e._id })}">${shortId(e._id)}</a></td>
475
- <td style="--label:var(--label-1)">${esc(new Date(e.ts).toISOString().replace("T", " ").slice(0, 19))}</td>
498
+ <td style="--label:var(--label-1)">${esc(localStamp(e.ts))}</td>
476
499
  <td style="--label:var(--label-2)">${esc(e.agent)}</td><td style="--label:var(--label-3)">${tag(e.action, ACTION_TAG[e.action] ?? "muted", actionLabel(e.action), actionTitle(e.action, lang))}</td><td style="--label:var(--label-4)">${tag(e.reason, reasonGroup(e.reason), reasonLabel(e.reason), reasonTitle(e.reason, lang))}</td>
477
- <td style="--label:var(--label-5)">${e.action === "pass" ? `<span class="skipped">${bi("skippedAsIs")}</span>` : `${e.inputChars ?? ""}/${e.outputChars ?? ""}`}</td><td style="--label:var(--label-6)">${fmtDur(e.durationMs)}</td></tr>`).join("")
500
+ <td style="--label:var(--label-5)">${e.action === "pass" ? `<span class="skipped">${bi("skippedAsIs")}</span>` : `${e.inputUnits ?? e.inputChars ?? ""}/${e.outputUnits ?? e.outputChars ?? ""}`}</td><td style="--label:var(--label-6)">${fmtDur(e.durationMs)}</td></tr>`).join("")
478
501
  : `<tr><td colspan="7" class="empty">${bi("noEvents")}</td></tr>`;
479
502
 
480
503
  const pager = `
@@ -589,9 +612,9 @@ export function renderDetail(event, q = {}) {
589
612
  <p class="empty warn">${bi("notFound")}</p>
590
613
  <p><a href="${qs(q, { detail: null })}">${bi("back")}</a></p>
591
614
  </body></html>`;
592
- const META_KEYS = ["ts", "agent", "action", "reason", "durationMs", "inputChars", "outputChars", "dryRun", "fromCache", "model", "group", "experimentId", "version", "bucket", "turn", "assignment", "finalAction", "mode", "fallbackFrom", "modelCalls"];
615
+ const META_KEYS = ["ts", "agent", "action", "reason", "durationMs", "inputChars", "outputChars", "inputUnits", "outputUnits", "dryRun", "fromCache", "model", "group", "experimentId", "version", "bucket", "turn", "assignment", "finalAction", "mode", "fallbackFrom", "modelCalls"];
593
616
  const meta = META_KEYS.filter((k) => event[k] !== undefined)
594
- .map((k) => `<tr><th>${esc(k)}</th><td>${k === "action" ? tag(event[k], ACTION_TAG[event[k]] ?? "muted", actionLabel(event[k]), actionTitle(event[k], lang)) : k === "reason" ? tag(event[k], reasonGroup(event[k]), reasonLabel(event[k]), reasonTitle(event[k], lang)) : k === "durationMs" ? fmtDur(event[k]) : esc(k === "ts" ? new Date(event.ts).toISOString() : event[k])}</td></tr>`).join("");
617
+ .map((k) => `<tr><th>${esc(k)}</th><td>${k === "action" ? tag(event[k], ACTION_TAG[event[k]] ?? "muted", actionLabel(event[k]), actionTitle(event[k], lang)) : k === "reason" ? tag(event[k], reasonGroup(event[k]), reasonLabel(event[k]), reasonTitle(event[k], lang)) : k === "durationMs" ? fmtDur(event[k]) : esc(k === "ts" ? localStamp(event.ts) : event[k])}</td></tr>`).join("");
595
618
  const extra = Object.keys(event).filter((k) => !META_KEYS.includes(k) && k !== "orig" && k !== "rewritten" && !k.startsWith("_"))
596
619
  .map((k) => `<tr><th>${esc(k)}</th><td>${esc(event[k])}</td></tr>`).join("");
597
620
  return `${head(lang)}
@@ -1,7 +1,8 @@
1
1
  // Shared stats HTTP service (design §6). Used two ways:
2
2
  // index.mjs server() — magpie's plugin host calls it when the stats page
3
3
  // opens; the service lives in the host process and dies with the plugin.
4
- // hello.service (page bridge) points at the manifest port (3497).
4
+ // The browser reaches it through magpie's same-origin proxy
5
+ // (/_magpie/plugin/<token>/_magpie/service/), never the port directly.
5
6
  // serve.mjs — standalone daemon (systemd on 70) with env overrides.
6
7
  // Node stdlib only. Default bind is 127.0.0.1 — origText clips of user
7
8
  // prompts live in the day-files, so never expose beyond loopback unless the
@@ -14,7 +15,7 @@ import { once } from "node:events";
14
15
  import { dirname, join, resolve } from "node:path";
15
16
  import { fileURLToPath } from "node:url";
16
17
  import os from "node:os";
17
- import { readEvents, prune } from "./stats.mjs";
18
+ import { readEvents, prune, resolveStatsDir } from "./stats.mjs";
18
19
  import { readFileSync } from "node:fs";
19
20
  import { eventsByDay, parseDetailId, renderPage, renderDetail, renderConfigPage, renderConfigDisabled, renderConfigError } from "./stats-page.mjs";
20
21
  export { renderPage, renderDetail } from "./stats-page.mjs";
@@ -136,7 +137,7 @@ export function readProviderGroups(providersFile = join(os.homedir(), ".config",
136
137
  // /api/recent last n events (1..500)
137
138
  export function makeStatsServer({ statsDir, recentDefault = 50, bind = "127.0.0.1", retainDays = process.env.POM_RETAIN_DAYS ?? 7, pluginsFile = join(os.homedir(), ".config/magpie/plugins.json"), providersFile, options = {} } = {}) {
138
139
  const GROUPS = () => readProviderGroups(providersFile); // per-render read: picks up magpie edits without restart
139
- const STATS = statsDir || join(ROOT, "stats");
140
+ const STATS = statsDir || resolveStatsDir();
140
141
  const RECENT_DEFAULT = recentDefault;
141
142
  const server = createServer((req, res) => {
142
143
  if (!hostAllowed(req.headers.host, bind)) {
@@ -268,7 +269,7 @@ function probeStatsService(port, bind) {
268
269
  // is a no-op) instead of failing — the host contract only needs *a* live
269
270
  // service on the manifest port. Otherwise retry same port 16×100ms, then
270
271
  // throw. Only the listening server starts its retention timer.
271
- export async function startStatsService({ port = 3497, statsDir, recentDefault, bind = "127.0.0.1", retainDays, pluginsFile, options } = {}) {
272
+ export async function startStatsService({ port = 27497, statsDir, recentDefault, bind = "127.0.0.1", retainDays, pluginsFile, options } = {}) {
272
273
  const server = makeStatsServer({ statsDir, recentDefault, bind, retainDays, pluginsFile, options });
273
274
  for (let attempt = 0; ; attempt++) {
274
275
  try {
package/lib/stats.mjs CHANGED
@@ -1,24 +1,69 @@
1
- // Append-only daily event logs under stats/ next to the plugin root
2
- // (import.meta.url based, never cwd). Silent on failure: stats must never
3
- // break a request.
1
+ // Append-only daily event logs, one ndjson file per day. Stats live OUTSIDE
2
+ // the package dir: `magpie plugin update` wipes node_modules reinstalls and
3
+ // took the whole stats/ dir with it twice on prod. New home (design:
4
+ // ~/.config/magpie/prompt-optimizer-magpie/stats). Silent on failure: stats
5
+ // must never break a request.
4
6
  //
5
7
  // Why daily files: record() runs in the magpie plugin-host process while
6
8
  // prune() runs in serve.mjs (systemd) — two OS processes. A read→tmp→rename
7
9
  // rewrite races with a concurrent append (the append lands in the unlinked
8
- // old inode). With one file per UTC day, retention is an unlink of *old*
10
+ // old inode). With one file per local day, retention is an unlink of *old*
9
11
  // files and writers only ever append to *today's* file: the two operations
10
- // touch disjoint inodes, so the race cannot drop data. It also caps any
12
+ // touch disjoint inodes, so no lock protocol is needed. It also bounds a
11
13
  // single file's growth and makes prune O(files), not O(bytes).
12
- import { appendFileSync, readFileSync, readdirSync, unlinkSync, mkdirSync } from "node:fs";
14
+ import { appendFileSync, readFileSync, readdirSync, unlinkSync, mkdirSync, copyFileSync, writeFileSync, existsSync } from "node:fs";
13
15
  import { dirname, join } from "node:path";
14
16
  import { fileURLToPath } from "node:url";
17
+ import { homedir } from "node:os";
15
18
 
16
19
  const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
17
- const DIR = join(ROOT, "stats");
20
+ const LEGACY_DIR = join(ROOT, "stats"); // pre-0.2.5 location, wiped by plugin updates
18
21
 
19
- // statsDir lets serve.mjs target its POM_DATA_DIR, tests target a tmp dir.
22
+ // One resolver for record/read/prune defaults and both entries (index.mjs,
23
+ // serve.mjs). POM_STATS_DIR explicitly overrides; no XDG dependency — Windows
24
+ // falls back to ~/.config/... too (documented in README).
25
+ export function resolveStatsDir() {
26
+ if (process.env.POM_STATS_DIR) return process.env.POM_STATS_DIR;
27
+ return join(homedir(), ".config", "magpie", "prompt-optimizer-magpie", "stats");
28
+ }
29
+
30
+ // One-shot legacy migration (called from both entries at startup): if the
31
+ // package-internal stats/ dir survived and the new dir would lose data, COPY
32
+ // day files over (never overwrite; the legacy dir is left in place) and drop
33
+ // a MIGRATED.txt marker so it never runs twice. Copy-once beats move: on 70
34
+ // the old dir has manually-restored history an update must not re-destroy.
35
+ // Silent-fail — stats can never block a request.
36
+ export function migrateLegacyStats(oldDir = process.env.POM_LEGACY_STATS_DIR || LEGACY_DIR, newDir = resolveStatsDir()) {
37
+ try {
38
+ if (!existsSync(oldDir)) return false;
39
+ if (existsSync(join(oldDir, "MIGRATED.txt"))) return false;
40
+ mkdirSync(newDir, { recursive: true });
41
+ for (const name of readdirSync(oldDir)) {
42
+ if (!/^\d{4}-\d{2}-\d{2}\.ndjson$/.test(name)) continue;
43
+ const dest = join(newDir, name);
44
+ if (existsSync(dest)) continue; // never overwrite newer data
45
+ copyFileSync(join(oldDir, name), dest);
46
+ }
47
+ writeFileSync(join(oldDir, "MIGRATED.txt"), `migrated to ${newDir} at ${new Date().toISOString()}\n`);
48
+ return true;
49
+ } catch {
50
+ return false;
51
+ }
52
+ }
53
+
54
+ const DIR = resolveStatsDir();
55
+
56
+ // Local-timezone YYYY-MM-DD (not toISOString's UTC): CST 0:00–8:00 events
57
+ // belong to today's local file, not yesterday's UTC one.
58
+ export function localDay(d = new Date()) {
59
+ const p = (n) => String(n).padStart(2, "0");
60
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
61
+ }
62
+
63
+ // statsDir lets serve.mjs target its data dir, tests target a tmp dir.
20
64
  const dayFile = (d = new Date(), statsDir = DIR) =>
21
- join(statsDir, d.toISOString().slice(0, 10) + ".ndjson");
65
+ join(statsDir, localDay(d) + ".ndjson");
66
+
22
67
 
23
68
  export function record(ev, statsDir = DIR) {
24
69
  try {
@@ -48,7 +93,7 @@ export function validEvent(ev) {
48
93
  && typeof ev.fromCache === "boolean" && Number.isSafeInteger(ev.modelCalls) && ev.modelCalls >= 0
49
94
  && Number.isFinite(ev.durationMs) && ev.durationMs >= 0;
50
95
  }
51
- return ["durationMs", "inputChars", "outputChars"].every((k) => ev[k] === undefined || Number.isFinite(ev[k]))
96
+ return ["durationMs", "inputChars", "outputChars", "inputUnits", "outputUnits"].every((k) => ev[k] === undefined || Number.isFinite(ev[k]))
52
97
  && ["agent", "orig", "rewritten"].every((k) => ev[k] === undefined || typeof ev[k] === "string")
53
98
  && ["dryRun", "fromCache"].every((k) => ev[k] === undefined || typeof ev[k] === "boolean");
54
99
  }
@@ -93,10 +138,10 @@ export function prune(retainDays, now = Date.now(), statsDir = DIR) {
93
138
  } catch {
94
139
  return 0;
95
140
  }
96
- // files strictly older than the cutoff date (UTC) are unlinked
141
+ // files strictly older than the cutoff date (local day) are unlinked
97
142
  const date = new Date(now - retainDays * 86400_000);
98
143
  if (!Number.isFinite(date.getTime())) return 0;
99
- const cutoff = date.toISOString().slice(0, 10);
144
+ const cutoff = localDay(date);
100
145
  let removed = 0;
101
146
  for (const name of names) {
102
147
  if (!/^\d{4}-\d{2}-\d{2}\.ndjson$/.test(name)) continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prompt-optimizer-magpie",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "Self-contained Magpie gateway request hook that rewrites vague first-turn prompts into precise ones before they reach your model. Fail-open by design.",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-only",
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "file": "page/index.html",
45
45
  "service": {
46
- "port": 3497,
46
+ "port": 27497,
47
47
  "option": "port"
48
48
  }
49
49
  },
@@ -74,11 +74,12 @@
74
74
  "optimizeTimeoutMs": 15000,
75
75
  "gatewayTimeoutMs": 25000,
76
76
  "gatewayUrl": "http://127.0.0.1:3425",
77
- "port": 0,
77
+ "port": 27497,
78
78
  "bind": "127.0.0.1",
79
79
  "configPage": false,
80
80
  "minChars": 6,
81
- "maxChars": 12000
81
+ "maxChars": 12000,
82
+ "guardRatioLimit": 10
82
83
  }
83
84
  },
84
85
  "engines": {
package/page/app.js CHANGED
@@ -1,48 +1,7 @@
1
- // External script (the sandbox CSP blocks inline scripts). It loads the
2
- // bridge (served beside this page) to answer magpie's hello handshake, then
3
- // lands the frame on the service URL through the gateway proxy — same origin
4
- // as the UI, so the page works from any machine the UI is open on.
1
+ // External script (the sandbox CSP blocks inline ones). The stats UI is
2
+ // reached through magpie's same-origin service proxy: one navigation to
3
+ // ./_magpie/service/ relative to the plugin page. The browser never
4
+ // connects to the stats port directly (loopback-only by default).
5
5
  (() => {
6
- const FALLBACK_PORT = 3497;
7
- const said = document.getElementById("said");
8
- // If the navigation target exists the frame is replaced and this timer
9
- // never fires — it is purely the "service not running" hint.
10
- const timer = setTimeout(() => {
11
- said.textContent =
12
- "统计服务未启动:请在插件 options 设 port,或在插件目录运行 node serve.mjs。";
13
- }, 2500);
14
- const load = (src) =>
15
- new Promise((res) => {
16
- const s = document.createElement("script");
17
- s.src = src;
18
- s.onload = res;
19
- s.onerror = res; // a missing file is fine: fixed-port installs have no port.js
20
- document.head.appendChild(s);
21
- });
22
- (async () => {
23
- // server() writes port.js beside this file once bound (port 0
24
- // auto-select): same-dir script loads pass the sandbox CSP, and it is
25
- // the plugin's own source of truth. The host's hello.service falls
26
- // back to the manifest port when the option is 0, so the bridge
27
- // service URL and options.port only apply when port.js gave nothing.
28
- await load("./port.js");
29
- const v = Number(window.__POM_PORT__);
30
- const runtime = Number.isInteger(v) && v > 0 && v < 65536 ? v : 0;
31
- let port = runtime || FALLBACK_PORT;
32
- let service = "";
33
- try {
34
- await load("./_magpie/bridge.js");
35
- await window.magpie?.ready; // rejects outside a magpie frame — degrade
36
- if (!runtime) {
37
- const s = window.magpie?.service;
38
- if (typeof s === "string" && /^https?:\/\//.test(s)) service = s;
39
- const opts = await window.magpie?.options?.get?.();
40
- const p = Number(opts?.port);
41
- if (!service && Number.isInteger(p) && p > 0 && p < 65536) port = p;
42
- }
43
- } catch { /* stay on defaults */ }
44
- const host = location.hostname || "127.0.0.1";
45
- location.replace(service || `http://${host}:${port}/`);
46
- clearTimeout(timer);
47
- })();
6
+ location.replace("./_magpie/service/");
48
7
  })();
package/page/index.html CHANGED
@@ -1,8 +1,9 @@
1
1
  <!doctype html>
2
2
  <!-- Magpie plugin sandbox page (design.md §6): sandbox="allow-scripts".
3
- Logic lives in app.js — the sandbox CSP allows same-dir scripts but
4
- blocks inline ones. app.js discovers the service URL via the bridge
5
- (_magpie/bridge.js, served beside this page) and navigates there. -->
3
+ The frame lands on the stats service through magpie's same-origin
4
+ proxy (./_magpie/service/) — the browser never touches the stats
5
+ port, which stays loopback-only. Logic lives in app.js; the sandbox
6
+ CSP allows same-dir scripts but blocks inline ones. -->
6
7
  <html lang="zh">
7
8
  <head>
8
9
  <meta charset="utf-8">
@@ -23,7 +24,7 @@
23
24
  <body>
24
25
  <div class="waiting">
25
26
  <b>提示词优化统计</b>
26
- <div id="said">正在连接本地统计服务…</div>
27
+ <div id="said">正在打开统计服务…</div>
27
28
  </div>
28
29
  <script src="./app.js"></script>
29
30
  </body>
package/serve.mjs CHANGED
@@ -1,16 +1,20 @@
1
1
  // v0.2 standalone stats daemon (design §6). All HTTP logic lives in
2
2
  // lib/stats-service.mjs, shared with index.mjs (magpie plugin host entry).
3
- // This file adds: env overrides (PORT, POM_DATA_DIR, POM_BIND), service.json
4
- // discovery for systemd and EADDRINUSE retry+fallback.
3
+ // This file adds: env overrides (PORT, POM_DATA_DIR for service.json, POM_BIND,
4
+ // POM_STATS_DIR for day-files), service.json discovery for systemd and
5
+ // EADDRINUSE retry+fallback.
5
6
  import { writeFileSync, rmSync, readFileSync, symlinkSync, renameSync } from "node:fs";
6
7
  import { randomUUID } from "node:crypto";
7
8
  import { join, dirname, basename } from "node:path";
8
9
  import { fileURLToPath } from "node:url";
9
10
  import { makeStatsServer } from "./lib/stats-service.mjs";
11
+ import { resolveStatsDir, migrateLegacyStats } from "./lib/stats.mjs";
10
12
 
11
13
  const ROOT = join(dirname(fileURLToPath(import.meta.url)));
14
+ // Stats moved out of the package dir (survives `magpie plugin update`);
15
+ // POM_DATA_DIR only relocates service.json/instance records (systemd units).
12
16
  const DATA_DIR = process.env.POM_DATA_DIR || ROOT;
13
- const STATS = join(DATA_DIR, "stats"); // daily day-files (lib/stats.mjs)
17
+ const STATS = resolveStatsDir(); // env POM_STATS_DIR > ~/.config/magpie/prompt-optimizer-magpie/stats
14
18
  const SERVICE = join(DATA_DIR, "service.json");
15
19
  const instanceRecord = join(DATA_DIR, `.service-${randomUUID()}.json`);
16
20
  const VERSION = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")).version;
@@ -18,17 +22,20 @@ const VERSION = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")).ver
18
22
  // (stats 日志里有截断后的提示词原文,对内网可见——见 README 隐私说明)。
19
23
  const BIND = process.env.POM_BIND || "127.0.0.1";
20
24
 
25
+ // One-shot: bring package-internal legacy stats/ over before first read.
26
+ if (migrateLegacyStats()) console.log("serve: migrated legacy stats/ to " + STATS);
21
27
  const server = makeStatsServer({ statsDir: STATS, bind: BIND });
22
28
  // design §6: ephemeral (PORT=0) is the norm; a fixed PORT may hit EADDRINUSE —
23
29
  // per candidate: same-port retry 16×100ms (a leaving process's socket often
24
- // clears), then move to the next candidate (fixed fallback 3497 for the page's
25
- // hello.service-down path). Each candidate gets its own 16-retry budget so a
26
- // fallback port also survives a lingering socket (systemd restarts included).
30
+ // clears), then move to the next candidate (fixed fallback 27497 for the
31
+ // page's hello.service-down path). Each candidate gets its own 16-retry budget
32
+ // so a fallback port also survives a lingering socket (systemd restarts
33
+ // included).
27
34
  const port = Number(process.env.PORT ?? 0);
28
35
  // hello.service-down fallback (design §6.2b). Overridable so tests can pick
29
- // a free port — hardcoding 3497 made the suite hang wherever magpie's own
30
- // plugin host holds it.
31
- const FIXED_FALLBACK = [Number(process.env.POM_FALLBACK_PORT ?? 3497)];
36
+ // a free port — hardcoding the default made the suite hang wherever
37
+ // magpie's own plugin host holds it.
38
+ const FIXED_FALLBACK = [Number(process.env.POM_FALLBACK_PORT ?? 27497)];
32
39
  const RETRIES_PER_CANDIDATE = 16;
33
40
  const RETRY_DELAY_MS = 100;
34
41
  const candidates = port === 0 ? [0] : [port, ...FIXED_FALLBACK.filter((p) => p !== port)];