prompt-optimizer-magpie 0.2.5 → 0.2.7
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 +2 -2
- package/README_EN.md +2 -2
- package/hooks.mjs +26 -9
- package/index.mjs +13 -12
- package/lib/rewrite-guard.mjs +15 -6
- package/lib/stats-page.mjs +3 -2
- package/lib/stats-service.mjs +3 -2
- package/package.json +3 -3
- package/page/app.js +5 -46
- package/page/index.html +5 -4
- package/serve.mjs +7 -6
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":
|
|
74
|
+
"port": 27497,
|
|
75
75
|
"bind": "127.0.0.1"
|
|
76
76
|
}'
|
|
77
77
|
```
|
|
@@ -102,7 +102,7 @@ magpie plugin options prompt-optimizer-magpie '{
|
|
|
102
102
|
| `logSkips` | `true` | `false` 时不记录常规 `pass` 事件(not-turn / self-loop / no-tools 等噪音);**失败类始终记录**(optimize-fail / decider-fail / optimize-empty / error),排障不瞎 |
|
|
103
103
|
| `logOptimizes` | `true` | `false` 时不记录成功路径的 `optimize` / `decide` 事件(optimized / cache-hit / dry-run / followup 等);失败类不受此开关影响 |
|
|
104
104
|
|
|
105
|
-
| `port` / `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` 覆盖 |
|
|
106
106
|
|
|
107
107
|
## 日志布局与保留(按天分文件,7 天清理)
|
|
108
108
|
|
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":
|
|
72
|
+
"port": 27497,
|
|
73
73
|
"bind": "127.0.0.1"
|
|
74
74
|
}'
|
|
75
75
|
```
|
|
@@ -96,7 +96,7 @@ magpie plugin options prompt-optimizer-magpie '{
|
|
|
96
96
|
| `gatewayTimeoutMs` | `25000` | **must be set explicitly** — per-hook budget, see above |
|
|
97
97
|
| `gatewayUrl` | `http://127.0.0.1:3425` | gateway loopback address (decide + optimize both call back into the gateway) |
|
|
98
98
|
| `logRewrites` / `logRewriteChars` | `true` / `600` | audit log carries clipped prompt text (`orig`/`rewritten`); `false` logs lengths only |
|
|
99
|
-
| `port` / `bind` | `
|
|
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 |
|
|
100
100
|
|
|
101
101
|
## Output guardrails
|
|
102
102
|
|
package/hooks.mjs
CHANGED
|
@@ -20,6 +20,10 @@ const DEFAULTS = {
|
|
|
20
20
|
minChars: 6,
|
|
21
21
|
maxChars: 12000,
|
|
22
22
|
bypassPrefix: ["!!", "##"],
|
|
23
|
+
// 机器注入包装(Hermes out-of-band/system-notice、title-request、progress-check、
|
|
24
|
+
// job 完成通知、recap 等)不是人类输入,改写它们只会破坏协议语义且必然触发
|
|
25
|
+
// output-guard。命中即整条放行,不进优化。
|
|
26
|
+
bypassWrappers: ["<system-notice>", "<title-request>", "<progress-check>", "<job>", "<recap>"],
|
|
23
27
|
bypassModels: [],
|
|
24
28
|
bypassAgents: [],
|
|
25
29
|
allowedOrigins: [],
|
|
@@ -113,6 +117,10 @@ export async function onRequest(body, ctx) {
|
|
|
113
117
|
}
|
|
114
118
|
const prefixes = [].concat(o.bypassPrefix).filter(Boolean);
|
|
115
119
|
if (typeof (ctx && ctx.query) === "string" && prefixes.some((p) => ctx.query.trimStart().startsWith(p))) return pass("bypass-prefix");
|
|
120
|
+
// Machine-injected wrappers (bypassWrappers) anywhere in the newest turn:
|
|
121
|
+
// they wrap protocol text the rewrite must not touch.
|
|
122
|
+
const wrappers = [].concat(o.bypassWrappers || []).filter(Boolean);
|
|
123
|
+
if (typeof (ctx && ctx.query) === "string" && wrappers.length && wrappers.some((w) => ctx.query.includes(w))) return pass("bypass-wrapper");
|
|
116
124
|
|
|
117
125
|
const protocol = (ctx && ctx.protocol) || "chat";
|
|
118
126
|
if (o.skipToolless && !hasTools(body, protocol)) return pass("no-tools");
|
|
@@ -129,6 +137,7 @@ export async function onRequest(body, ctx) {
|
|
|
129
137
|
} catch {}
|
|
130
138
|
}
|
|
131
139
|
if (prefixes.some((p) => orig.startsWith(p))) return pass("bypass-prefix");
|
|
140
|
+
if (wrappers.length && wrappers.some((w) => orig.includes(w))) return pass("bypass-wrapper");
|
|
132
141
|
if (orig.length < o.minChars) return pass("short-text", { in: orig.length, inUnits: countUnits(orig) });
|
|
133
142
|
if (orig.length > o.maxChars) return pass("too-long", { in: orig.length, inUnits: countUnits(orig) });
|
|
134
143
|
|
|
@@ -164,7 +173,7 @@ export async function onRequest(body, ctx) {
|
|
|
164
173
|
let d;
|
|
165
174
|
if (!beginCall("deciderTimeoutMs")) return pass("budget-exhausted", size);
|
|
166
175
|
const tDecide = Date.now();
|
|
167
|
-
try { d = await decide(o, thread, orig); } catch (error) {
|
|
176
|
+
try { d = await decide(o, thread, orig, timeoutSignal(ctx, o.deciderTimeoutMs)); } catch (error) {
|
|
168
177
|
if (expired(error)) return pass("budget-exhausted", size);
|
|
169
178
|
} finally { input.decideMs = Date.now() - tDecide; }
|
|
170
179
|
if (remaining() <= 0) return pass("budget-exhausted", size);
|
|
@@ -214,7 +223,7 @@ export async function onRequest(body, ctx) {
|
|
|
214
223
|
let parsed;
|
|
215
224
|
const tOpt = Date.now();
|
|
216
225
|
try {
|
|
217
|
-
const raw = await completion(o, mergedSystemPrompt(langSuffix), orig);
|
|
226
|
+
const raw = await completion(o, mergedSystemPrompt(langSuffix), orig, timeoutSignal(ctx, o.optimizeTimeoutMs));
|
|
218
227
|
parsed = parseMerged(raw, langSuffix);
|
|
219
228
|
} catch (error) {
|
|
220
229
|
if (expired(error)) return pass("budget-exhausted", size);
|
|
@@ -229,7 +238,7 @@ export async function onRequest(body, ctx) {
|
|
|
229
238
|
out = parsed.rest;
|
|
230
239
|
} else {
|
|
231
240
|
const tOpt = Date.now();
|
|
232
|
-
try { out = await optimize(o, orig, templateId); } catch (error) {
|
|
241
|
+
try { out = await optimize(o, orig, templateId, timeoutSignal(ctx, o.optimizeTimeoutMs)); } catch (error) {
|
|
233
242
|
return pass(expired(error) ? "budget-exhausted" : "optimize-fail", size);
|
|
234
243
|
} finally { input.optimizeMs = Date.now() - tOpt; }
|
|
235
244
|
if (remaining() <= 0) return pass("budget-exhausted", size);
|
|
@@ -262,7 +271,15 @@ export async function onRequest(body, ctx) {
|
|
|
262
271
|
// System One decider: is the newest user input a new task or a follow-up?
|
|
263
272
|
// `orig` is sent verbatim in state.latestUserInput — without it the model
|
|
264
273
|
// has nothing to classify and would just guess.
|
|
265
|
-
|
|
274
|
+
// Host budget first: combine ctx.signal (magpie giving up on the hook) with
|
|
275
|
+
// our own timeout so an abandoned hook stops burning gateway tokens.
|
|
276
|
+
function timeoutSignal(ctx, ms) {
|
|
277
|
+
const t = AbortSignal.timeout(ms);
|
|
278
|
+
const host = ctx?.signal;
|
|
279
|
+
return host && AbortSignal.any ? AbortSignal.any([host, t]) : t;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async function decide(o, thread, orig, signal) {
|
|
266
283
|
const res = await fetch(`${o.gatewayUrl}/v1/systemone`, {
|
|
267
284
|
method: "POST",
|
|
268
285
|
headers: { "content-type": "application/json" },
|
|
@@ -271,7 +288,7 @@ async function decide(o, thread, orig) {
|
|
|
271
288
|
state: { hasAssistantReply: thread, latestUserInput: orig, inputChars: orig.length },
|
|
272
289
|
questions,
|
|
273
290
|
}),
|
|
274
|
-
signal
|
|
291
|
+
signal,
|
|
275
292
|
});
|
|
276
293
|
if (!res.ok) return undefined;
|
|
277
294
|
const j = await res.json();
|
|
@@ -287,14 +304,14 @@ function hasAssistantReply(body, protocol) {
|
|
|
287
304
|
return Array.isArray(arr) && arr.some((m) => m && (m.role === "assistant" || m.role === "model"));
|
|
288
305
|
}
|
|
289
306
|
|
|
290
|
-
async function optimize(o, orig, templateId) {
|
|
307
|
+
async function optimize(o, orig, templateId, signal) {
|
|
291
308
|
const tpl = getTemplate(templateId);
|
|
292
309
|
if (!tpl) return undefined;
|
|
293
310
|
const user = MUSTACHE.test(tpl.user) ? tpl.user.replace(MUSTACHE, () => JSON.stringify(orig)) : `${tpl.user}\n\n${orig}`;
|
|
294
|
-
return completion(o, `${tpl.system}\n\n${TAIL_NOTE}`, user);
|
|
311
|
+
return completion(o, `${tpl.system}\n\n${TAIL_NOTE}`, user, signal);
|
|
295
312
|
}
|
|
296
313
|
|
|
297
|
-
async function completion(o, system, user) {
|
|
314
|
+
async function completion(o, system, user, signal) {
|
|
298
315
|
const res = await fetch(`${o.gatewayUrl}/v1/chat/completions`, {
|
|
299
316
|
method: "POST",
|
|
300
317
|
headers: { "content-type": "application/json" },
|
|
@@ -306,7 +323,7 @@ async function completion(o, system, user) {
|
|
|
306
323
|
{ role: "user", content: user },
|
|
307
324
|
],
|
|
308
325
|
}),
|
|
309
|
-
signal
|
|
326
|
+
signal,
|
|
310
327
|
});
|
|
311
328
|
if (!res.ok) return undefined;
|
|
312
329
|
const j = await res.json();
|
package/index.mjs
CHANGED
|
@@ -25,22 +25,21 @@ export default {
|
|
|
25
25
|
started = startStatsService({
|
|
26
26
|
statsDir: resolveStatsDir(),
|
|
27
27
|
// options.port: magpie.page.service.option "port" in package.json;
|
|
28
|
-
// 0 = ephemeral — `||
|
|
29
|
-
port: Number.isFinite(Number(options?.port)) ? Number(options.port) :
|
|
30
|
-
// options.bind:
|
|
31
|
-
//
|
|
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.
|
|
32
33
|
bind: typeof options?.bind === "string" && options.bind ? options.bind : "127.0.0.1",
|
|
33
34
|
// options.configPage: enable the /?page=config sub-page (default off).
|
|
34
35
|
options: { configPage: options?.configPage === true },
|
|
35
36
|
}).then((svc) => {
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
//
|
|
39
|
-
// the sandboxed page is a file beside app.js, which it loads after
|
|
40
|
-
// 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.
|
|
41
40
|
try {
|
|
42
41
|
writeFileSync(join(PAGE_DIR, "port.js"), `window.__POM_PORT__ = ${svc.port};\n`);
|
|
43
|
-
} catch { /* read-only install:
|
|
42
|
+
} catch { /* read-only install: no reader left, harmless */ }
|
|
44
43
|
return svc;
|
|
45
44
|
}).catch((error) => {
|
|
46
45
|
started = null;
|
|
@@ -55,5 +54,7 @@ export default {
|
|
|
55
54
|
},
|
|
56
55
|
};
|
|
57
56
|
|
|
58
|
-
// test-only: stop the singleton service (page/port.js stays behind, stale)
|
|
59
|
-
|
|
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(() => {}) };
|
package/lib/rewrite-guard.mjs
CHANGED
|
@@ -3,17 +3,26 @@
|
|
|
3
3
|
// {{ name }} ≡ {{name}} (inner whitespace stripped) and backtick tokens compare
|
|
4
4
|
// their content, so a wider fence around the same identifier still passes.
|
|
5
5
|
// Per-category counts must still match exactly — a swallowed or invented
|
|
6
|
-
// placeholder always trips the guard (fail-safe).
|
|
6
|
+
// placeholder always trips the guard (fail-safe). Backticks are one-way
|
|
7
|
+
// tolerant: the optimizer ADDING code fences around bare text is legitimate
|
|
8
|
+
// emphasis and cannot corrupt meaning, so added backticks are ignored while
|
|
9
|
+
// any backticked token present in the original must survive verbatim
|
|
10
|
+
// (2026-11-23: 4/5 guard reverts were bare paths gaining fences, 0→3).
|
|
7
11
|
const protectedTokens = [
|
|
8
12
|
{ re: /\[REDACTED\]/g, norm: (t) => t },
|
|
9
13
|
{ re: /\{\{[^{}\r\n]+\}\}/g, norm: (t) => t.replace(/\s+/g, "") },
|
|
10
|
-
{ re: /(?<!`)(`+)(?!`)[^`\r\n]+\1(?!`)/g, norm: (t) => t.replace(/^`+/, "").replace(/`+$/, "") },
|
|
14
|
+
{ re: /(?<!`)(`+)(?!`)[^`\r\n]+\1(?!`)/g, norm: (t) => t.replace(/^`+/, "").replace(/`+$/, ""), addedOk: true },
|
|
11
15
|
];
|
|
12
16
|
export function preservesTokens(orig, out) {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
+
const o = String(orig), u = String(out);
|
|
18
|
+
return protectedTokens.every(({ re, norm, addedOk }) => {
|
|
19
|
+
const before = (o.match(re) || []).map(norm).sort();
|
|
20
|
+
const after = (u.match(re) || []).map(norm).sort();
|
|
21
|
+
if (!before.every((token, i) => token === after[i] || after.includes(token))) return false;
|
|
22
|
+
if (!addedOk) return before.length === after.length;
|
|
23
|
+
// addedOk: new tokens are fencing text that already existed in the original;
|
|
24
|
+
// an invented identifier is still a corruption.
|
|
25
|
+
return after.every((token) => before.includes(token) || o.includes(token));
|
|
17
26
|
});
|
|
18
27
|
}
|
|
19
28
|
|
package/lib/stats-page.mjs
CHANGED
|
@@ -110,7 +110,7 @@ export const T = {
|
|
|
110
110
|
hintOptimizeGroup: ["执行提示词改写所用模型组", "model group used to rewrite prompts"],
|
|
111
111
|
hintDeciderTimeoutMs: ["判定调用超时毫秒,超时按失败处理(默认 1500)", "decider call timeout in ms; timeout counts as failure (default 1500)"],
|
|
112
112
|
hintOptimizeTimeoutMs: ["改写调用超时毫秒,超时放行原文(默认 15000)", "optimizer call timeout in ms; timeout passes the original through (default 15000)"],
|
|
113
|
-
hintPort: ["
|
|
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"],
|
|
114
114
|
cfgSubmit: ["保存", "Save"],
|
|
115
115
|
cfgErrInt: ["必须是整数", "must be an integer"],
|
|
116
116
|
cfgErrRange: ["超出允许范围", "out of allowed range"],
|
|
@@ -131,6 +131,7 @@ export const T = {
|
|
|
131
131
|
"r_bypass-agent": ["agent 名命中旁路", "agent bypassed"],
|
|
132
132
|
"r_bypass-model": ["模型名命中旁路", "model bypassed"],
|
|
133
133
|
"r_bypass-prefix": ["前缀命中旁路", "prefix bypassed"],
|
|
134
|
+
"r_bypass-wrapper": ["机器注入包装旁路", "machine-injected wrapper bypassed"],
|
|
134
135
|
r_subagent: ["子代理请求放行", "subagent request passed"],
|
|
135
136
|
"r_self-loop": ["自身回路放行", "self loop passed"],
|
|
136
137
|
r_disabled: ["插件未启用", "plugin disabled"],
|
|
@@ -339,7 +340,7 @@ export function shortId(id) {
|
|
|
339
340
|
export const ACTION_TAG = { optimize: "green", decide: "amber", pass: "muted", summary: "accent" };
|
|
340
341
|
export const REASON_GROUPS = {
|
|
341
342
|
green: ["optimized", "merged-optimized", "cache-hit", "dry-run"],
|
|
342
|
-
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"],
|
|
343
|
+
amber: ["not-turn", "no-tools", "short-text", "too-long", "bypass-agent", "bypass-model", "bypass-prefix", "bypass-wrapper", "subagent", "self-loop", "disabled", "origin", "followup", "tpl-skip", "experiment-control", "no-decider-followup", "merged-passthrough", "merged-circuit-open", "budget-exhausted", "low-confidence", "unknown-choice"],
|
|
343
344
|
red: ["optimize-empty", "output-guard", "output-guard-short", "output-guard-long", "output-guard-tokens", "no-span", "error"],
|
|
344
345
|
};
|
|
345
346
|
export function reasonGroup(reason) {
|
package/lib/stats-service.mjs
CHANGED
|
@@ -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
|
-
//
|
|
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
|
|
@@ -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 =
|
|
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "prompt-optimizer-magpie",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.7",
|
|
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":
|
|
46
|
+
"port": 27497,
|
|
47
47
|
"option": "port"
|
|
48
48
|
}
|
|
49
49
|
},
|
|
@@ -74,7 +74,7 @@
|
|
|
74
74
|
"optimizeTimeoutMs": 15000,
|
|
75
75
|
"gatewayTimeoutMs": 25000,
|
|
76
76
|
"gatewayUrl": "http://127.0.0.1:3425",
|
|
77
|
-
"port":
|
|
77
|
+
"port": 27497,
|
|
78
78
|
"bind": "127.0.0.1",
|
|
79
79
|
"configPage": false,
|
|
80
80
|
"minChars": 6,
|
package/page/app.js
CHANGED
|
@@ -1,48 +1,7 @@
|
|
|
1
|
-
// External script (the sandbox CSP blocks inline
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
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
|
-
|
|
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
|
-
|
|
4
|
-
|
|
5
|
-
|
|
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"
|
|
27
|
+
<div id="said">正在打开统计服务…</div>
|
|
27
28
|
</div>
|
|
28
29
|
<script src="./app.js"></script>
|
|
29
30
|
</body>
|
package/serve.mjs
CHANGED
|
@@ -27,14 +27,15 @@ if (migrateLegacyStats()) console.log("serve: migrated legacy stats/ to " + STAT
|
|
|
27
27
|
const server = makeStatsServer({ statsDir: STATS, bind: BIND });
|
|
28
28
|
// design §6: ephemeral (PORT=0) is the norm; a fixed PORT may hit EADDRINUSE —
|
|
29
29
|
// per candidate: same-port retry 16×100ms (a leaving process's socket often
|
|
30
|
-
// clears), then move to the next candidate (fixed fallback
|
|
31
|
-
// hello.service-down path). Each candidate gets its own 16-retry budget
|
|
32
|
-
// fallback port also survives a lingering socket (systemd restarts
|
|
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).
|
|
33
34
|
const port = Number(process.env.PORT ?? 0);
|
|
34
35
|
// hello.service-down fallback (design §6.2b). Overridable so tests can pick
|
|
35
|
-
// a free port — hardcoding
|
|
36
|
-
// plugin host holds it.
|
|
37
|
-
const FIXED_FALLBACK = [Number(process.env.POM_FALLBACK_PORT ??
|
|
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)];
|
|
38
39
|
const RETRIES_PER_CANDIDATE = 16;
|
|
39
40
|
const RETRY_DELAY_MS = 100;
|
|
40
41
|
const candidates = port === 0 ? [0] : [port, ...FIXED_FALLBACK.filter((p) => p !== port)];
|