prompt-optimizer-magpie 0.2.2 → 0.2.4
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 +6 -8
- package/README_EN.md +6 -6
- package/docs/design.md +1 -1
- package/hooks.mjs +6 -4
- package/index.mjs +23 -2
- package/lib/config-store.mjs +29 -1
- package/lib/rewrite-guard.mjs +23 -4
- package/lib/stats-page.mjs +6 -1
- package/package.json +1 -1
- package/page/app.js +26 -14
package/README.md
CHANGED
|
@@ -101,7 +101,7 @@ magpie plugin options prompt-optimizer-magpie '{
|
|
|
101
101
|
| `logSkips` | `true` | `false` 时不记录常规 `pass` 事件(not-turn / self-loop / no-tools 等噪音);**失败类始终记录**(optimize-fail / decider-fail / optimize-empty / error),排障不瞎 |
|
|
102
102
|
| `logOptimizes` | `true` | `false` 时不记录成功路径的 `optimize` / `decide` 事件(optimized / cache-hit / dry-run / followup 等);失败类不受此开关影响 |
|
|
103
103
|
|
|
104
|
-
| `port` / `bind` | `0` / `127.0.0.1` | 统计服务监听:`port=0` OS
|
|
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
105
|
|
|
106
106
|
## 日志布局与保留(按天分文件,7 天清理)
|
|
107
107
|
|
|
@@ -113,12 +113,10 @@ magpie plugin options prompt-optimizer-magpie '{
|
|
|
113
113
|
|
|
114
114
|
## 输出护栏
|
|
115
115
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
-
|
|
119
|
-
-
|
|
120
|
-
- 长度上限 `max(3×原文, 1500)`——短需求本就该展开成长结构化提示词(实测 17 字需求 → 552 字提示词是期望效果),固定 3× 会误杀所有短输入;
|
|
121
|
-
- 绝对上限 `max(6000, 原文长度)`——上限随 `maxChars` 放行宽度联动,合法长输入不会「优化完再被固定 6000 丢弃」。
|
|
116
|
+
- 剥离外围代码围栏;新结果和缓存命中都比对 `[REDACTED]`、双花括号占位符和反引号标识符的**数量**;字面比对容错等价写法(`{{ name }}` ≡ `{{name}}`,反引号 token 比内容),数量增减仍拦截;
|
|
117
|
+
- 长度上下限按**词元数**而非字符数(中文 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
|
+
- 护栏触发细分为三个 reason,统计页红色分组可观测:`output-guard-short`(低于下限)/ `output-guard-long`(超上限)/ `output-guard-tokens`(token 校验失败)。
|
|
122
120
|
|
|
123
121
|
替换只动最后一条 user 消息中**唯一匹配**的用户原文 span:先逐字匹配,失败后空白规范化匹配;零命中或多重命中一律放行,绝不用 `ctx.query` 整段覆盖。
|
|
124
122
|
|
|
@@ -130,7 +128,7 @@ magpie plugin options prompt-optimizer-magpie '{
|
|
|
130
128
|
|
|
131
129
|
例如 `"overrides":[{"agent":"cli","model":"group/interactive","budgetMs":350},{"agent":"batch","optimizerMode":"merged"}]`。350 毫秒从进入 hook 起算,判定和改写共用;耗尽时放行原文并记录 `budget-exhausted`,0 表示直接放行。目标模型匹配的是入站 `body.model`。实验组优先选择模式,预算仍生效;线程保留原有门禁。没有匹配项使用全局配置。
|
|
132
130
|
|
|
133
|
-
钩子将审计事件写入插件目录 `stats/YYYY-MM-DD.ndjson`(UTC 日文件,按事件追加,写失败静默)。默认在 `optimized` / `dry-run` / `output-guard
|
|
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)。
|
|
134
132
|
|
|
135
133
|
决策失败后,已有助手回复的线程直接放行;首轮按实际降级路径记录 `decider-fail-rule` 或 `decider-fail-merged`。Responses 携带 `previous_response_id` 时直接放行。每个请求只上报一次终态;实际回写报 `ready` 并附返回请求体的 UTF-8 字节数,干跑或普通放行报 `skipped, 0`,最终模型调用失败报 `unavailable, 0`。
|
|
136
134
|
|
package/README_EN.md
CHANGED
|
@@ -95,16 +95,16 @@ magpie plugin options prompt-optimizer-magpie '{
|
|
|
95
95
|
| `gatewayTimeoutMs` | `25000` | **must be set explicitly** — per-hook budget, see above |
|
|
96
96
|
| `gatewayUrl` | `http://127.0.0.1:3425` | gateway loopback address (decide + optimize both call back into the gateway) |
|
|
97
97
|
| `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; `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 |
|
|
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
99
|
|
|
100
100
|
## Output guardrails
|
|
101
101
|
|
|
102
102
|
An optimized result is only substituted after passing the guardrails, otherwise the original passes through:
|
|
103
103
|
|
|
104
|
-
- strip surrounding code fences and verify
|
|
105
|
-
-
|
|
106
|
-
- upper bound `
|
|
107
|
-
-
|
|
104
|
+
- 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
|
+
- 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
|
+
- 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
108
|
|
|
109
109
|
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.
|
|
110
110
|
|
|
@@ -116,7 +116,7 @@ Enable `rollout` only for agents whose `ctx.session` is stable across retries. E
|
|
|
116
116
|
|
|
117
117
|
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
118
|
|
|
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
|
|
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
120
|
|
|
121
121
|
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
122
|
|
package/docs/design.md
CHANGED
|
@@ -248,7 +248,7 @@ Magpie 插件页运行在 `sandbox="allow-scripts"` frame:**无 fetch/WebSocke
|
|
|
248
248
|
| 插件异常阻断请求 | 全链路 try/catch,任何异常 `return undefined`(fail-open) |
|
|
249
249
|
| 网关自环 | 步骤 0 按 `body.model` 跳过优化组/决策组自身的请求 |
|
|
250
250
|
| 机器调用被误优化 | `skipToolless` + `bypassAgents` + `bypassModels` + `kind=subagent` + 压缩/进度标记。Magpie 自有标题请求官方已跳过 hook |
|
|
251
|
-
| decider 把追问误判为新任务 | confidence<0.6 放行 +
|
|
251
|
+
| decider 把追问误判为新任务 | confidence<0.6 放行 + 输出护栏(词元归一:0.4× 下限 / clamp(5×,60,2000) 上限)+ dryRun 期统计误判率,超标调 criteria 或关插件 |
|
|
252
252
|
| 链预算被钳在 10s(文档与实现不符) | 写码前 sleep 探针实测(§12-2);被钳则 optimizeTimeoutMs 降 8s、模板用 basic 缩短输出 |
|
|
253
253
|
| 重试把同一句优化两次 | `cacheTtlMs` 60s |
|
|
254
254
|
| dryRun 把提示词写进磁盘 | `logRewrites=false` 省略审计原文,`cacheTtlMs=0` 停止缓存读写 |
|
package/hooks.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { fileURLToPath } from "node:url";
|
|
|
6
6
|
import { inspect } from "node:util";
|
|
7
7
|
import { questions, mergedSystemPrompt, parseMerged, stripFence, TAIL_NOTE } from "./lib/prompts.mjs";
|
|
8
8
|
import { rewriteCacheKey, readRewrite, writeRewrite } from "./lib/rewrite-cache.mjs";
|
|
9
|
-
import { preservesTokens, redact } from "./lib/rewrite-guard.mjs";
|
|
9
|
+
import { countUnits, preservesTokens, redact } from "./lib/rewrite-guard.mjs";
|
|
10
10
|
import { assignRollout } from "./lib/rollout.mjs";
|
|
11
11
|
import { contentVersion, getTemplate } from "./templates/index.mjs";
|
|
12
12
|
import { hasTools, opensTurn, lastUserText } from "./lib/turn.mjs";
|
|
@@ -234,9 +234,11 @@ export async function onRequest(body, ctx) {
|
|
|
234
234
|
}
|
|
235
235
|
|
|
236
236
|
const audit = { ...input, out: out.length, newText: out, markCache: fromCache };
|
|
237
|
-
const
|
|
238
|
-
|
|
239
|
-
|
|
237
|
+
const origUnits = countUnits(orig), outUnits = countUnits(out);
|
|
238
|
+
const maxUnits = Math.min(Math.max(origUnits * 5, 60), 2000);
|
|
239
|
+
if (outUnits < origUnits * 0.4) return pass("output-guard-short", audit);
|
|
240
|
+
if (outUnits > maxUnits) return pass("output-guard-long", audit);
|
|
241
|
+
if (!preservesTokens(orig, out)) return pass("output-guard-tokens", audit);
|
|
240
242
|
const newBody = replaceSpan(body, protocol, lu.index, orig, out);
|
|
241
243
|
if (!newBody) {
|
|
242
244
|
log("optimize", "no-span", audit);
|
package/index.mjs
CHANGED
|
@@ -6,8 +6,13 @@
|
|
|
6
6
|
// day-files, and a port clash between them resolves via serve's
|
|
7
7
|
// retry+fallback. Retention (prune) runs inside startStatsService, so this
|
|
8
8
|
// in-app path prunes too.
|
|
9
|
+
import { writeFileSync } from "node:fs";
|
|
10
|
+
import { join, dirname } from "node:path";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
9
12
|
import { startStatsService } from "./lib/stats-service.mjs";
|
|
10
13
|
|
|
14
|
+
const PAGE_DIR = join(dirname(fileURLToPath(import.meta.url)), "page");
|
|
15
|
+
|
|
11
16
|
let started = null;
|
|
12
17
|
|
|
13
18
|
export default {
|
|
@@ -23,12 +28,28 @@ export default {
|
|
|
23
28
|
bind: typeof options?.bind === "string" && options.bind ? options.bind : "127.0.0.1",
|
|
24
29
|
// options.configPage: enable the /?page=config sub-page (default off).
|
|
25
30
|
options: { configPage: options?.configPage === true },
|
|
31
|
+
}).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
|
+
try {
|
|
38
|
+
writeFileSync(join(PAGE_DIR, "port.js"), `window.__POM_PORT__ = ${svc.port};\n`);
|
|
39
|
+
} catch { /* read-only install: page falls back to 3497 */ }
|
|
40
|
+
return svc;
|
|
26
41
|
}).catch((error) => {
|
|
27
42
|
started = null;
|
|
28
43
|
throw error;
|
|
29
44
|
});
|
|
30
45
|
}
|
|
31
|
-
await started;
|
|
32
|
-
return
|
|
46
|
+
const svc = await started;
|
|
47
|
+
// The return value is the plugin's hooks object: hosts read only known
|
|
48
|
+
// keys, so `port` is ignored today but already correct if a future host
|
|
49
|
+
// forwards it (design §6.2a).
|
|
50
|
+
return { port: svc.port };
|
|
33
51
|
},
|
|
34
52
|
};
|
|
53
|
+
|
|
54
|
+
// test-only: stop the singleton service (page/port.js stays behind, stale)
|
|
55
|
+
export const __testClose = () => started?.then((s) => s.close()).catch(() => {});
|
package/lib/config-store.mjs
CHANGED
|
@@ -9,9 +9,36 @@
|
|
|
9
9
|
import { readFileSync, writeFileSync, renameSync, unlinkSync } from "node:fs";
|
|
10
10
|
import { join, dirname } from "node:path";
|
|
11
11
|
import { randomBytes } from "node:crypto";
|
|
12
|
+
import { createRequire } from "node:module";
|
|
12
13
|
|
|
13
14
|
export const SPEC = process.env.POM_PLUGIN_SPEC ?? "/root/prompt-optimizer-magpie";
|
|
14
15
|
|
|
16
|
+
// This plugin's npm name — the match target for fuzzy spec lookup.
|
|
17
|
+
const NAME = (() => {
|
|
18
|
+
try { return createRequire(import.meta.url)("../package.json").name; }
|
|
19
|
+
catch { return "prompt-optimizer-magpie"; }
|
|
20
|
+
})();
|
|
21
|
+
|
|
22
|
+
// Three-tier spec match (.omp-spec-brief.md): an explicit POM_PLUGIN_SPEC
|
|
23
|
+
// keeps literal equality (70 drop-in compat); otherwise entries match by
|
|
24
|
+
// npm install form, preferring npm: > bare/bare@ver > path entries.
|
|
25
|
+
export function matchEntry(doc) {
|
|
26
|
+
const plugins = Array.isArray(doc?.plugins) ? doc.plugins : [];
|
|
27
|
+
if (process.env.POM_PLUGIN_SPEC) {
|
|
28
|
+
return plugins.find((p) => p && p.spec === SPEC) ?? null;
|
|
29
|
+
}
|
|
30
|
+
const tiers = [
|
|
31
|
+
(s) => s === `npm:${NAME}` || s.startsWith(`npm:${NAME}@`),
|
|
32
|
+
(s) => s === NAME || (s.startsWith(`${NAME}@`) && s.length > NAME.length + 1),
|
|
33
|
+
(s) => s.startsWith("/") && s.replace(/\/+$/, "").endsWith(`/${NAME}`),
|
|
34
|
+
];
|
|
35
|
+
for (const hit of tiers) {
|
|
36
|
+
const e = plugins.find((p) => p && typeof p.spec === "string" && hit(p.spec));
|
|
37
|
+
if (e) return e;
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
15
42
|
// Whitelist + validation (brief 需求 1 表格). `type` drives form rendering;
|
|
16
43
|
// `check` returns an error string (keyed for T lookup) or null.
|
|
17
44
|
export const CONFIG_FIELDS = [
|
|
@@ -26,6 +53,7 @@ export const CONFIG_FIELDS = [
|
|
|
26
53
|
{ key: "optimizeGroup", type: "string", def: "group/prompt-optimize", maxLen: 200 },
|
|
27
54
|
{ key: "deciderTimeoutMs", type: "int", def: 1500, min: 500, max: 60000 },
|
|
28
55
|
{ key: "optimizeTimeoutMs", type: "int", def: 15000, min: 500, max: 60000 },
|
|
56
|
+
{ key: "port", type: "int", def: 0, min: 0, max: 65535 },
|
|
29
57
|
];
|
|
30
58
|
const BY_KEY = Object.fromEntries(CONFIG_FIELDS.map((f) => [f.key, f]));
|
|
31
59
|
|
|
@@ -83,7 +111,7 @@ export function readPluginsJson(file) {
|
|
|
83
111
|
const doc = JSON.parse(raw);
|
|
84
112
|
if (!doc || typeof doc !== "object" || !Array.isArray(doc.plugins))
|
|
85
113
|
return { error: "cfgErrBadFile" };
|
|
86
|
-
const entry = doc
|
|
114
|
+
const entry = matchEntry(doc);
|
|
87
115
|
if (!entry || typeof entry.options !== "object" || entry.options === null)
|
|
88
116
|
return { error: "cfgErrNoSpec" };
|
|
89
117
|
return { doc, entry, options: entry.options };
|
package/lib/rewrite-guard.mjs
CHANGED
|
@@ -1,13 +1,32 @@
|
|
|
1
1
|
// Compare each kind independently: a backticked identifier can itself contain a placeholder.
|
|
2
|
-
|
|
2
|
+
// Literal compare is tolerant where the optimizer cannot help reformatting:
|
|
3
|
+
// {{ name }} ≡ {{name}} (inner whitespace stripped) and backtick tokens compare
|
|
4
|
+
// their content, so a wider fence around the same identifier still passes.
|
|
5
|
+
// Per-category counts must still match exactly — a swallowed or invented
|
|
6
|
+
// placeholder always trips the guard (fail-safe).
|
|
7
|
+
const protectedTokens = [
|
|
8
|
+
{ re: /\[REDACTED\]/g, norm: (t) => t },
|
|
9
|
+
{ re: /\{\{[^{}\r\n]+\}\}/g, norm: (t) => t.replace(/\s+/g, "") },
|
|
10
|
+
{ re: /(?<!`)(`+)(?!`)[^`\r\n]+\1(?!`)/g, norm: (t) => t.replace(/^`+/, "").replace(/`+$/, "") },
|
|
11
|
+
];
|
|
3
12
|
export function preservesTokens(orig, out) {
|
|
4
|
-
return protectedTokens.every((
|
|
5
|
-
const before = (orig.match(
|
|
6
|
-
const after = (out.match(
|
|
13
|
+
return protectedTokens.every(({ re, norm }) => {
|
|
14
|
+
const before = (String(orig).match(re) || []).map(norm).sort();
|
|
15
|
+
const after = (String(out).match(re) || []).map(norm).sort();
|
|
7
16
|
return before.length === after.length && before.every((token, i) => token === after[i]);
|
|
8
17
|
});
|
|
9
18
|
}
|
|
10
19
|
|
|
20
|
+
// Length units for the output guard: each CJK ideograph = 1, each contiguous
|
|
21
|
+
// non-CJK word/number/identifier run = 1, punctuation/whitespace = 0. JS
|
|
22
|
+
// `.length` counts UTF-16 code units, which under-measures CJK (1 unit/char)
|
|
23
|
+
// and over-measures English (5+ units/word) — char-based bounds were strict
|
|
24
|
+
// for Chinese and loose for English. Same ideograph range as cjkRatio.
|
|
25
|
+
const unitPattern = /[\u3400-\u9FFF]|[0-9A-Za-z_]+/g;
|
|
26
|
+
export function countUnits(text) {
|
|
27
|
+
return (String(text).match(unitPattern) || []).length;
|
|
28
|
+
}
|
|
29
|
+
|
|
11
30
|
// Shared by structured wire fields and credential assignments embedded in prompt text.
|
|
12
31
|
const field = String.raw`(?:[a-z\d]+[-_])*(?:authorization|cookie|api[-_]?key|access[-_]?key|private[-_]?key|(?:access|auth|refresh|id|session|csrf)?[-_]?token|(?:client[-_]?)?secret(?:[-_]?key)?|password|passwd|credentials?)`;
|
|
13
32
|
const sensitive = new RegExp(`^${field}$`, 'i');
|
package/lib/stats-page.mjs
CHANGED
|
@@ -96,6 +96,7 @@ export const T = {
|
|
|
96
96
|
cfgOptimizeGroup: ["改写模型组", "optimizer model group"],
|
|
97
97
|
cfgDeciderTimeoutMs: ["判定超时(毫秒)", "decider timeout (ms)"],
|
|
98
98
|
cfgOptimizeTimeoutMs: ["改写超时(毫秒)", "optimizer timeout (ms)"],
|
|
99
|
+
cfgPort: ["统计服务端口", "stats service port"],
|
|
99
100
|
hintEnabled: ["总开关,关闭后 hook 直接放行,不调用任何模型", "master switch; when off the hook passes every request through, no model calls"],
|
|
100
101
|
hintDryRun: ["只记录改写结果到统计,不替换实际请求", "rewrite results are logged to stats only; requests are never replaced"],
|
|
101
102
|
hintOptimizerMode: ["auto = 判定+改写按各自模型组两段式;merged = 单次合并调用(决策组可空)", "auto = decide+rewrite as two calls per their groups; merged = single combined call (decider group may be empty)"],
|
|
@@ -107,6 +108,7 @@ export const T = {
|
|
|
107
108
|
hintOptimizeGroup: ["执行提示词改写所用模型组", "model group used to rewrite prompts"],
|
|
108
109
|
hintDeciderTimeoutMs: ["判定调用超时毫秒,超时按失败处理(默认 1500)", "decider call timeout in ms; timeout counts as failure (default 1500)"],
|
|
109
110
|
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)"],
|
|
110
112
|
cfgSubmit: ["保存", "Save"],
|
|
111
113
|
cfgErrInt: ["必须是整数", "must be an integer"],
|
|
112
114
|
cfgErrRange: ["超出允许范围", "out of allowed range"],
|
|
@@ -142,6 +144,9 @@ export const T = {
|
|
|
142
144
|
"r_unknown-choice": ["decider 未知判定保守放行", "unknown decider choice, passed"],
|
|
143
145
|
"r_optimize-empty": ["优化返回空已回退", "optimize returned empty, reverted"],
|
|
144
146
|
"r_output-guard": ["改写超护栏已回退", "output guard tripped, reverted"],
|
|
147
|
+
"r_output-guard-short": ["改写过短已回退", "rewrite below length floor, reverted"],
|
|
148
|
+
"r_output-guard-long": ["改写超长已回退", "rewrite above length ceiling, reverted"],
|
|
149
|
+
"r_output-guard-tokens": ["改写丢占位符已回退", "rewrite broke protected tokens, reverted"],
|
|
145
150
|
"r_no-span": ["改写不含原文已回退", "rewrite lost the original span, reverted"],
|
|
146
151
|
r_error: ["处理异常已放行", "error, passed through"],
|
|
147
152
|
"r_decider-fail": ["decider 调用失败走纯规则", "decider call failed, rules fallback"],
|
|
@@ -312,7 +317,7 @@ export const ACTION_TAG = { optimize: "green", decide: "amber", pass: "muted", s
|
|
|
312
317
|
export const REASON_GROUPS = {
|
|
313
318
|
green: ["optimized", "merged-optimized", "cache-hit", "dry-run"],
|
|
314
319
|
amber: ["not-turn", "no-tools", "short-text", "too-long", "bypass-agent", "bypass-model", "bypass-prefix", "subagent", "self-loop", "disabled", "origin", "followup", "tpl-skip", "experiment-control", "no-decider-followup", "merged-passthrough", "merged-circuit-open", "budget-exhausted", "low-confidence", "unknown-choice"],
|
|
315
|
-
red: ["optimize-empty", "output-guard", "no-span", "error"],
|
|
320
|
+
red: ["optimize-empty", "output-guard", "output-guard-short", "output-guard-long", "output-guard-tokens", "no-span", "error"],
|
|
316
321
|
};
|
|
317
322
|
export function reasonGroup(reason) {
|
|
318
323
|
if (REASON_GROUPS.green.includes(reason)) return "green";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "prompt-optimizer-magpie",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.4",
|
|
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",
|
package/page/app.js
CHANGED
|
@@ -11,23 +11,35 @@
|
|
|
11
11
|
said.textContent =
|
|
12
12
|
"统计服务未启动:请在插件 options 设 port,或在插件目录运行 node serve.mjs。";
|
|
13
13
|
}, 2500);
|
|
14
|
-
|
|
15
|
-
|
|
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;
|
|
16
32
|
let service = "";
|
|
17
33
|
try {
|
|
18
|
-
await
|
|
19
|
-
const s = document.createElement("script");
|
|
20
|
-
s.src = "./_magpie/bridge.js";
|
|
21
|
-
s.onload = res;
|
|
22
|
-
s.onerror = () => rej(new Error("bridge failed to load"));
|
|
23
|
-
document.head.appendChild(s);
|
|
24
|
-
});
|
|
34
|
+
await load("./_magpie/bridge.js");
|
|
25
35
|
await window.magpie?.ready; // rejects outside a magpie frame — degrade
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
+
}
|
|
31
43
|
} catch { /* stay on defaults */ }
|
|
32
44
|
const host = location.hostname || "127.0.0.1";
|
|
33
45
|
location.replace(service || `http://${host}:${port}/`);
|