prompt-optimizer-magpie 0.2.5 → 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 +2 -2
- package/README_EN.md +2 -2
- package/hooks.mjs +17 -9
- package/index.mjs +13 -12
- package/lib/stats-page.mjs +1 -1
- 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
|
@@ -164,7 +164,7 @@ export async function onRequest(body, ctx) {
|
|
|
164
164
|
let d;
|
|
165
165
|
if (!beginCall("deciderTimeoutMs")) return pass("budget-exhausted", size);
|
|
166
166
|
const tDecide = Date.now();
|
|
167
|
-
try { d = await decide(o, thread, orig); } catch (error) {
|
|
167
|
+
try { d = await decide(o, thread, orig, timeoutSignal(ctx, o.deciderTimeoutMs)); } catch (error) {
|
|
168
168
|
if (expired(error)) return pass("budget-exhausted", size);
|
|
169
169
|
} finally { input.decideMs = Date.now() - tDecide; }
|
|
170
170
|
if (remaining() <= 0) return pass("budget-exhausted", size);
|
|
@@ -214,7 +214,7 @@ export async function onRequest(body, ctx) {
|
|
|
214
214
|
let parsed;
|
|
215
215
|
const tOpt = Date.now();
|
|
216
216
|
try {
|
|
217
|
-
const raw = await completion(o, mergedSystemPrompt(langSuffix), orig);
|
|
217
|
+
const raw = await completion(o, mergedSystemPrompt(langSuffix), orig, timeoutSignal(ctx, o.optimizeTimeoutMs));
|
|
218
218
|
parsed = parseMerged(raw, langSuffix);
|
|
219
219
|
} catch (error) {
|
|
220
220
|
if (expired(error)) return pass("budget-exhausted", size);
|
|
@@ -229,7 +229,7 @@ export async function onRequest(body, ctx) {
|
|
|
229
229
|
out = parsed.rest;
|
|
230
230
|
} else {
|
|
231
231
|
const tOpt = Date.now();
|
|
232
|
-
try { out = await optimize(o, orig, templateId); } catch (error) {
|
|
232
|
+
try { out = await optimize(o, orig, templateId, timeoutSignal(ctx, o.optimizeTimeoutMs)); } catch (error) {
|
|
233
233
|
return pass(expired(error) ? "budget-exhausted" : "optimize-fail", size);
|
|
234
234
|
} finally { input.optimizeMs = Date.now() - tOpt; }
|
|
235
235
|
if (remaining() <= 0) return pass("budget-exhausted", size);
|
|
@@ -262,7 +262,15 @@ export async function onRequest(body, ctx) {
|
|
|
262
262
|
// System One decider: is the newest user input a new task or a follow-up?
|
|
263
263
|
// `orig` is sent verbatim in state.latestUserInput — without it the model
|
|
264
264
|
// has nothing to classify and would just guess.
|
|
265
|
-
|
|
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) {
|
|
266
274
|
const res = await fetch(`${o.gatewayUrl}/v1/systemone`, {
|
|
267
275
|
method: "POST",
|
|
268
276
|
headers: { "content-type": "application/json" },
|
|
@@ -271,7 +279,7 @@ async function decide(o, thread, orig) {
|
|
|
271
279
|
state: { hasAssistantReply: thread, latestUserInput: orig, inputChars: orig.length },
|
|
272
280
|
questions,
|
|
273
281
|
}),
|
|
274
|
-
signal
|
|
282
|
+
signal,
|
|
275
283
|
});
|
|
276
284
|
if (!res.ok) return undefined;
|
|
277
285
|
const j = await res.json();
|
|
@@ -287,14 +295,14 @@ function hasAssistantReply(body, protocol) {
|
|
|
287
295
|
return Array.isArray(arr) && arr.some((m) => m && (m.role === "assistant" || m.role === "model"));
|
|
288
296
|
}
|
|
289
297
|
|
|
290
|
-
async function optimize(o, orig, templateId) {
|
|
298
|
+
async function optimize(o, orig, templateId, signal) {
|
|
291
299
|
const tpl = getTemplate(templateId);
|
|
292
300
|
if (!tpl) return undefined;
|
|
293
301
|
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);
|
|
302
|
+
return completion(o, `${tpl.system}\n\n${TAIL_NOTE}`, user, signal);
|
|
295
303
|
}
|
|
296
304
|
|
|
297
|
-
async function completion(o, system, user) {
|
|
305
|
+
async function completion(o, system, user, signal) {
|
|
298
306
|
const res = await fetch(`${o.gatewayUrl}/v1/chat/completions`, {
|
|
299
307
|
method: "POST",
|
|
300
308
|
headers: { "content-type": "application/json" },
|
|
@@ -306,7 +314,7 @@ async function completion(o, system, user) {
|
|
|
306
314
|
{ role: "user", content: user },
|
|
307
315
|
],
|
|
308
316
|
}),
|
|
309
|
-
signal
|
|
317
|
+
signal,
|
|
310
318
|
});
|
|
311
319
|
if (!res.ok) return undefined;
|
|
312
320
|
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/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"],
|
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.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":
|
|
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)];
|