From b844b75127adab9fedb33a64633dde6c7f953be3 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Sat, 31 Oct 2026 18:28:53 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20guided=20pack=20editor=20in=20setti?= =?UTF-8?q?ngs=20=E2=80=94=20per-field=20form=20with=20base=20texts,=20AI-?= =?UTF-8?q?assist=20prompt,=20raw=20JSON=20kept=20as=20Advanced=20tab?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #5344 The pack Edit dialog was a bare JSON textarea with no field docs and no samples. Replace the default view with three tabs: 1. Guided form: philosophy + howToCompress fields with plain-language help; one-click base text loaded from the resolvable default/chat/lean packs (new read-only GET /__bili/packs/templates, tri-state-resolved like buildCompressSystemPrompt); empty fields are omitted so runtime falls back to system defaults. 2. AI assist: describe the scenario in one sentence -> generates a ready-to-copy prompt for any LLM constrained to bili-pack.json shape -> paste the returned JSON back -> parsed into the form (extra top-level keys are kept in the JSON tab and saved with the pack). 3. Advanced (JSON): the previous raw-text editing, unchanged. Docs: CONFIGURATION.md / CONFIGURATION.zh-CN.md updated (paired). --- CONFIGURATION.md | 2 +- CONFIGURATION.zh-CN.md | 2 +- src/server/admin.ts | 5 +- src/web/api.ts | 28 +++- src/web/client.ts | 246 ++++++++++++++++++++++++++++++++++- src/web/i18n.ts | 66 ++++++++++ src/web/index.ts | 1 + tests/web-user-packs.test.ts | 16 +++ 8 files changed, 356 insertions(+), 10 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 95f22352c3..901625367a 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -1492,7 +1492,7 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t - **Type:** `string` (pack name, e.g. `"lean"`) - **Default:** `default` *(unset is equivalent — identity surface, kernel defaults everywhere)* - **Status:** ACTIVE -- **Description:** Select a named prompt pack — a curated surface preset covering tool descriptions, compress system-prompt sections, and nudge sections — resolved from the host's pack chain: **project** `./.billion-context/packs/.json` → **user** `/packs/.json` → **shipped** (`chat`) → **builtin** (`default`, `lean`). Built-in `lean` swaps the four ACP tool descriptions for one-liners (no snippet/guideline chrome) while keeping the compression rules default. Built-in `chat` (#5319) rewrites only the compress philosophy and how-to-compress prose for long-term companionship / multi-session memory use; every other surface piece stays at the host defaults, and a same-name user or project file overrides it. Unknown names fall back to the identity surface with a one-time warning. Same three-level merge as the other fields; pack-surface sections (tool/section overrides) apply directly, without the `acknowledgePromptsRisk` gate — that gate governs only inline `compress.prompts` rule-text overrides. Note a pack's `prompts` block is ignored by this proxy: rule-text overrides are possible only via inline `compress.prompts`. Requires `acp-kernel` >= 0.0.66. The settings panel can manage the user-dir files directly — New/Edit/Delete for packs under `/packs/` (the picker knows each entry's provenance; builtins and shipped packs stay read-only there, override them with a same-named user pack instead). +- **Description:** Select a named prompt pack — a curated surface preset covering tool descriptions, compress system-prompt sections, and nudge sections — resolved from the host's pack chain: **project** `./.billion-context/packs/.json` → **user** `/packs/.json` → **shipped** (`chat`) → **builtin** (`default`, `lean`). Built-in `lean` swaps the four ACP tool descriptions for one-liners (no snippet/guideline chrome) while keeping the compression rules default. Built-in `chat` (#5319) rewrites only the compress philosophy and how-to-compress prose for long-term companionship / multi-session memory use; every other surface piece stays at the host defaults, and a same-name user or project file overrides it. Unknown names fall back to the identity surface with a one-time warning. Same three-level merge as the other fields; pack-surface sections (tool/section overrides) apply directly, without the `acknowledgePromptsRisk` gate — that gate governs only inline `compress.prompts` rule-text overrides. Note a pack's `prompts` block is ignored by this proxy: rule-text overrides are possible only via inline `compress.prompts`. Requires `acp-kernel` >= 0.0.66. The settings panel can manage the user-dir files directly — New/Edit/Delete for packs under `/packs/` (the picker knows each entry's provenance; builtins and shipped packs stay read-only there, override them with a same-named user pack instead). The Edit dialog has three tabs (#5344): **Guided form** — per-field help text plus one-click base text loaded from `default`/`chat`/`lean` (empty fields are omitted and fall back to system defaults at runtime); **AI assist** — describe your scenario in plain words, copy the generated prompt to any LLM, paste its JSON back and it parses straight into the form; **Advanced (JSON)** — raw file text for full control. **Pack file format.** Each `/.json` holds one pack object. Unknown fields are dropped by the same sanitizer used on every load path (`sanitizePackSurface`), so extra metadata is harmless: diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 5fe979e7f3..adf3ba23ea 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -1483,7 +1483,7 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 - **类型:** `string`(包名,如 `"lean"`) - **默认值:** `default`(未设置等同——恒等表面,全部使用内核默认值) - **状态:** ACTIVE -- **说明:** 选择一个具名 prompt pack —— 一套策划好的表面预设,覆盖工具描述、压缩系统提示词段落、nudge 段落 —— 从宿主侧的包解析链解析:**项目** `./.billion-context/packs/.json` → **用户** `/packs/.json` → **随包附带**(`chat`)→ **内核内置**(`default`、`lean`)。内置 `lean` 把四个 ACP 工具描述换成单行版(无 snippet/guideline 包装),压缩规则保持默认。内置 `chat`(#5319)只替换压缩哲学段与 how-to-compress 规则段,面向长期陪伴 / 多会话记忆场景;其余表面全部保持宿主默认,同名的用户/项目文件会覆盖它。未知包名回退到恒等表面并记录一次警告。与其他字段一样三级级联合并;包的表面覆盖(工具/段落)直接生效,不经 `acknowledgePromptsRisk` 门控——该门控只管内联 `compress.prompts` 的规则文本覆盖。注意:包文件里的 `prompts` 块会被本代理忽略,规则文本只能经内联 `compress.prompts` 设置。需要 `acp-kernel` >= 0.0.66。设置面板可以直接管理用户目录里的包文件——对 `/packs/` 下的包 新建/编辑/删除(选择器知道每个条目的来源;内置与 shipped 包在那里只读,要用同名用户包覆盖)。 +- **说明:** 选择一个具名 prompt pack —— 一套策划好的表面预设,覆盖工具描述、压缩系统提示词段落、nudge 段落 —— 从宿主侧的包解析链解析:**项目** `./.billion-context/packs/.json` → **用户** `/packs/.json` → **随包附带**(`chat`)→ **内核内置**(`default`、`lean`)。内置 `lean` 把四个 ACP 工具描述换成单行版(无 snippet/guideline 包装),压缩规则保持默认。内置 `chat`(#5319)只替换压缩哲学段与 how-to-compress 规则段,面向长期陪伴 / 多会话记忆场景;其余表面全部保持宿主默认,同名的用户/项目文件会覆盖它。未知包名回退到恒等表面并记录一次警告。与其他字段一样三级级联合并;包的表面覆盖(工具/段落)直接生效,不经 `acknowledgePromptsRisk` 门控——该门控只管内联 `compress.prompts` 的规则文本覆盖。注意:包文件里的 `prompts` 块会被本代理忽略,规则文本只能经内联 `compress.prompts` 设置。需要 `acp-kernel` >= 0.0.66。设置面板可以直接管理用户目录里的包文件——对 `/packs/` 下的包 新建/编辑/删除(选择器知道每个条目的来源;内置与 shipped 包在那里只读,要用同名用户包覆盖)。编辑对话框有三个页签(#5344):**表单填写**——逐字段说明文字,可一键载入 `default`/`chat`/`lean` 的现有文案做起稿底本(留空字段不写入包文件,运行时沿用系统默认);**AI 辅助**——用大白话描述使用场景,把生成的提示词复制到任意大模型执行,再把返回的 JSON 粘回来即可自动填入表单;**高级(JSON)**——原始文件文本,给需要完整控制的用户。 **包文件格式。** 每个 `/.json` 是一个 pack 对象。未识别的字段会被与所有加载路径相同的 sanitize 器丢弃(`sanitizePackSurface`),所以多写元数据无害: diff --git a/src/server/admin.ts b/src/server/admin.ts index 306c78d879..c28f69b8f5 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -33,7 +33,7 @@ import { formatUpstreamError, getUpstreamConnectionStatus, proxyDispatcher, reco import { detectStaleInstall, getLastInstall } from "../update.js"; import { getPlannedUpgrade, getUpdatePolicyState } from "../update-policy.js"; import { PACKAGE_NAME, VERSION, BUILD_COMMIT } from "../version.js"; -import { buildBlockContent, buildMessageContent, buildOverview, buildSessionDetail, buildSessionList, buildSessionPage, buildSessionTree, handleConfigGet, handleConfigPut, handlePricingGet, handleUserPackDelete, handleUserPackGet, handleUserPackPut, hiddenEmptyCount, renderUI, type BlockContentView } from "../web/index.js"; +import { buildBlockContent, buildMessageContent, buildOverview, buildSessionDetail, buildSessionList, buildSessionPage, buildSessionTree, handleConfigGet, handleConfigPut, handlePackTemplatesGet, handlePricingGet, handleUserPackDelete, handleUserPackGet, handleUserPackPut, hiddenEmptyCount, renderUI, type BlockContentView } from "../web/index.js"; import { handleChangelogGet } from "../web/changelog.js"; import { kickBlogRefresh } from "../web/blog-refresh.js"; import { handleBlogAssetGet, handleBlogGet } from "../web/blogfeed.js"; @@ -348,6 +348,9 @@ export async function handleAdminRoute(req: http.IncomingMessage, res: http.Serv res.end(JSON.stringify({ packs, userDir: path.join(configDir(), "packs") })); return; } + // #5344: base texts for the guided pack-editor form (tri-state resolved + // exactly like buildCompressSystemPrompt). Read-only; same gates. + if (req.method === "GET" && req.url === "/__bili/packs/templates") return handlePackTemplatesGet(res); // #5328: user-dir pack management — GET/PUT/DELETE /packs/ // .json. The route regex shapes the name to the pack-name charset // ([A-Za-z0-9][A-Za-z0-9._-]*) before dispatch; the handlers re-validate diff --git a/src/web/api.ts b/src/web/api.ts index c68888968c..baae2ef1b6 100644 --- a/src/web/api.ts +++ b/src/web/api.ts @@ -3,7 +3,8 @@ import { dirname, join } from "node:path"; import { randomUUID } from "node:crypto"; import type { IncomingMessage, ServerResponse } from "node:http"; import { configDir, configFile } from "../paths.js"; -import { isValidPackName, sanitizePackSurface, type PromptPackFile } from "acp-kernel"; +import { defaultPrompts, isValidPackName, sanitizePackSurface, type PromptPackFile } from "acp-kernel"; +import { resolveCompressSurfaceDetailed } from "../compress-settings.js"; import { collectNamedProviders, loadNamedProviders, @@ -172,6 +173,31 @@ export async function handleUserPackDelete(res: ServerResponse, name: string): P res.end(JSON.stringify({ ok: true })); } +// #5344: base texts for the guided pack editor (form tab). Mirrors the +// tri-state resolution buildCompressSystemPrompt performs: absent key -> +// kernel default text; null -> removed (empty); string -> verbatim. +const PACK_TEMPLATE_NAMES = ["default", "chat", "lean"] as const; +export type PackTemplate = { description?: string; philosophy: string; howToCompress: string }; + +function packTemplateFor(name: string): PackTemplate { + const resolution = resolveCompressSurfaceDetailed({ promptPack: name }); + const sections = resolution.surface.promptSections ?? {}; + const pick = (key: "philosophy" | "howToCompress"): string => { + const override = sections[key]; + if (override === null) return ""; + if (typeof override === "string") return override; + return key === "philosophy" ? defaultPrompts.compressPhilosophy : defaultPrompts.howToCompressRules; + }; + return { philosophy: pick("philosophy"), howToCompress: pick("howToCompress") }; +} + +export async function handlePackTemplatesGet(res: ServerResponse): Promise { + const packs: Record = {}; + for (const name of PACK_TEMPLATE_NAMES) packs[name] = packTemplateFor(name); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ packs })); +} + export async function handleConfigGet(res: ServerResponse): Promise { const upstream = readUpstreamSettings(); const config = readConfig(); diff --git a/src/web/client.ts b/src/web/client.ts index 148c9d01e8..2ad50f2c2f 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -4063,6 +4063,38 @@ if (d.keepalive) kv(parts, t("det.keepalive"), d.keepalive.tierLabel + " · " + const peBox = document.createElement("div"); peBox.hidden = true; peBox.style.cssText = "margin:4px 0"; + // #5344: the editor is a three-tab panel (guided form / AI assist / + // raw JSON); the bare-JSON box below becomes the third tab. + // WEB_CLIENT embedding rules: no backtick literals; runtime \n + // escapes are written \\n in this source file. + const peTabs = document.createElement("div"); + peTabs.style.cssText = "display:flex;gap:8px;margin-bottom:6px"; + const PE_TAB_DEFS = [ + { key: "form", label: t("cfg.q_pack_tab_form") }, + { key: "ai", label: t("cfg.q_pack_tab_ai") }, + { key: "json", label: t("cfg.q_pack_tab_json") }, + ]; + const peTabBtns = {}; + for (const def of PE_TAB_DEFS) { + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "btn sm"; + btn.textContent = def.label; + btn.style.borderBottom = "2px solid transparent"; + (function (key) { btn.addEventListener("click", () => showPeTab(key)); })(def.key); + peTabBtns[def.key] = btn; + peTabs.appendChild(btn); + } + function showPeTab(key) { + for (const def of PE_TAB_DEFS) { + const btn = peTabBtns[def.key]; + btn.style.fontWeight = def.key === key ? "700" : "400"; + btn.style.borderBottom = def.key === key ? "2px solid #0969da" : "2px solid transparent"; + } + peFormPane.hidden = key !== "form"; + peAiPane.hidden = key !== "ai"; + peJsonPane.hidden = key !== "json"; + } const peTa = document.createElement("textarea"); peTa.className = "editor mono codebox"; peTa.spellcheck = false; @@ -4077,8 +4109,199 @@ if (d.keepalive) kv(parts, t("det.keepalive"), d.keepalive.tierLabel + " · " + peCancel.className = "btn sm"; peCancel.textContent = t("cfg.q_pack_cancel"); peBtns.append(peSave, peCancel); - peBox.append(peTa, peBtns); + // #5344 tab 1: guided form — start from a base text, tweak, save. + const peFormPane = document.createElement("div"); + const peAiPane = document.createElement("div"); + const peJsonPane = document.createElement("div"); + peFormPane.hidden = false; + peAiPane.hidden = true; + peJsonPane.hidden = true; + peJsonPane.append(peTa, peBtns); + const baseRow = document.createElement("div"); + baseRow.style.cssText = "display:flex;gap:8px;align-items:center;margin:2px 0 8px;flex-wrap:wrap"; + const baseLab = document.createElement("label"); + baseLab.htmlFor = "pack-base-sel"; + baseLab.textContent = t("cfg.q_pack_base_label"); + baseLab.style.cssText = "font-size:12px;color:#57606a"; + const baseSel = document.createElement("select"); + baseSel.id = "pack-base-sel"; + baseSel.className = "field-input"; + [["", "cfg.q_pack_base_blank"], ["default", "cfg.q_pack_base_default"], ["chat", "cfg.q_pack_base_chat"], ["lean", "cfg.q_pack_base_lean"]].forEach((pair) => { + const opt = document.createElement("option"); + opt.value = pair[0]; + opt.textContent = t(pair[1]); + baseSel.appendChild(opt); + }); + const btnBaseLoad = document.createElement("button"); + btnBaseLoad.type = "button"; + btnBaseLoad.className = "btn sm"; + btnBaseLoad.textContent = t("cfg.q_pack_base_load"); + baseRow.append(baseLab, baseSel, btnBaseLoad); + const descWrap = document.createElement("div"); + descWrap.style.cssText = "margin:8px 0"; + const descLab = document.createElement("div"); + descLab.textContent = t("cfg.q_pack_desc"); + descLab.style.cssText = "font-size:13px;font-weight:600;margin-bottom:2px"; + const descIn = document.createElement("input"); + descIn.type = "text"; + descIn.className = "field-input"; + descIn.placeholder = t("cfg.q_pack_desc_ph"); + descIn.style.cssText = "width:100%;box-sizing:border-box"; + descWrap.append(descLab, descIn); + function packSectionField(labelKey, helpKey, rows) { + const wrap = document.createElement("div"); + wrap.style.cssText = "margin:8px 0"; + const lab = document.createElement("div"); + lab.textContent = t(labelKey); + lab.style.cssText = "font-size:13px;font-weight:600;margin-bottom:2px"; + const help = document.createElement("div"); + help.textContent = t(helpKey); + help.style.cssText = "font-size:12px;color:#57606a;margin-bottom:4px"; + const ta = document.createElement("textarea"); + ta.className = "field-input mono"; + ta.spellcheck = false; + ta.rows = rows; + ta.style.cssText = "width:100%;box-sizing:border-box"; + wrap.append(lab, help, ta); + return { wrap, ta }; + } + const phF = packSectionField("cfg.q_pack_phil", "cfg.q_pack_phil_help", 5); + const hcF = packSectionField("cfg.q_pack_hc", "cfg.q_pack_hc_help", 8); + const taPh = phF.ta; + const taHc = hcF.ta; + const formHint = document.createElement("div"); + formHint.textContent = t("cfg.q_pack_form_hint"); + formHint.style.cssText = "font-size:12px;color:#57606a;margin:8px 0"; + const btnFormSave = document.createElement("button"); + btnFormSave.type = "button"; + btnFormSave.className = "btn sm"; + btnFormSave.textContent = t("cfg.q_pack_form_save"); + peFormPane.append(baseRow, descWrap, phF.wrap, hcF.wrap, formHint, btnFormSave); + // #5344 tab 2: AI assist — plain-language need -> self-contained + // prompt -> copy to any LLM -> paste its JSON back -> fills the form. + const aiNeedLab = document.createElement("div"); + aiNeedLab.textContent = t("cfg.q_pack_ai_need"); + aiNeedLab.style.cssText = "font-size:13px;font-weight:600;margin:2px 0"; + const aiNeed = document.createElement("textarea"); + aiNeed.className = "field-input"; + aiNeed.rows = 3; + aiNeed.placeholder = t("cfg.q_pack_ai_need_ph"); + aiNeed.style.cssText = "width:100%;box-sizing:border-box"; + const aiBtnRow = document.createElement("div"); + aiBtnRow.style.cssText = "display:flex;gap:8px;margin:6px 0"; + const btnAiGen = document.createElement("button"); + btnAiGen.type = "button"; + btnAiGen.className = "btn sm"; + btnAiGen.textContent = t("cfg.q_pack_ai_gen"); + const btnAiCopy = document.createElement("button"); + btnAiCopy.type = "button"; + btnAiCopy.className = "btn sm"; + btnAiCopy.textContent = t("cfg.q_pack_ai_copy"); + aiBtnRow.append(btnAiGen, btnAiCopy); + const aiOut = document.createElement("textarea"); + aiOut.className = "editor mono codebox"; + aiOut.readOnly = true; + aiOut.rows = 8; + aiOut.spellcheck = false; + aiOut.style.cssText = "width:100%;box-sizing:border-box"; + const aiHint = document.createElement("div"); + aiHint.textContent = t("cfg.q_pack_ai_hint"); + aiHint.style.cssText = "font-size:12px;color:#57606a;margin:8px 0 2px"; + const aiIn = document.createElement("textarea"); + aiIn.className = "editor mono codebox"; + aiIn.rows = 8; + aiIn.spellcheck = false; + aiIn.placeholder = '{"promptSections": {"philosophy": "..."}}'; + aiIn.style.cssText = "width:100%;box-sizing:border-box"; + const btnAiApply = document.createElement("button"); + btnAiApply.type = "button"; + btnAiApply.className = "btn sm"; + btnAiApply.textContent = t("cfg.q_pack_ai_apply"); + const aiApplyRow = document.createElement("div"); + aiApplyRow.style.cssText = "display:flex;gap:8px;margin-top:6px"; + aiApplyRow.append(btnAiApply); + peAiPane.append(aiNeedLab, aiNeed, aiBtnRow, aiOut, aiHint, aiIn, aiApplyRow); + async function loadBaseText() { + const baseName = baseSel.value; + if (!baseName) { descIn.value = ""; taPh.value = ""; taHc.value = ""; return; } + try { + const r = await json(API_ROOT + "/packs/templates"); + const pk = r && r.packs ? r.packs[baseName] : null; + if (!pk) { pmSet(t("cfg.q_pack_json_obj"), true); return; } + descIn.value = typeof pk.description === "string" ? pk.description : ""; + taPh.value = typeof pk.philosophy === "string" ? pk.philosophy : ""; + taHc.value = typeof pk.howToCompress === "string" ? pk.howToCompress : ""; + pmSet(""); + } catch (e) { pmSet(String(e), true); } + } + btnBaseLoad.addEventListener("click", () => loadBaseText()); + // Shared pack-name normalizer (WEB_CLIENT rule: charCode, no regex + // with backslashes) for both save paths. + function packNameForSave() { + const rawName = (editingNew ? pmName.value.trim() : editingPack); + const first = rawName.charCodeAt(0); + return (first === 47 || first === 92 ? rawName.slice(1) : rawName).trim(); + } + btnFormSave.addEventListener("click", async () => { + const name = packNameForSave(); + if (!name || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name) || name.indexOf("..") !== -1) { pmSet(t("cfg.q_pack_bad_name"), true); return; } + const phil = taPh.value.trim(); + const hc = taHc.value.trim(); + if (!phil && !hc) { pmSet(t("cfg.q_pack_form_empty"), true); return; } + const obj = { promptSections: {} }; + if (phil) obj.promptSections.philosophy = phil; + if (hc) obj.promptSections.howToCompress = hc; + const desc = descIn.value.trim(); + if (desc) obj.description = desc; + try { + await json(API_ROOT + "/packs/user/" + encodeURIComponent(name), { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ json: JSON.stringify(obj, null, 2) }), + }); + pmSet(t("cfg.q_pack_saved", { name })); + peBox.hidden = true; + editingPack = ""; + editingNew = false; + refreshPackInventory(); + commit((d) => { if (!compressOf(d)) d.compress = {}; d.compress.promptPack = name; }); + } catch (e) { pmSet(String(e), true); } + }); + btnAiGen.addEventListener("click", () => { + const need = aiNeed.value.trim(); + if (!need) { pmSet(t("cfg.q_pack_ai_need_empty"), true); return; } + aiOut.value = [t("cfg.q_pack_ai_p1", { need }), t("cfg.q_pack_ai_p2"), t("cfg.q_pack_ai_p3")].join("\\n\\n"); + pmSet(t("cfg.q_pack_ai_gen_ok")); + }); + btnAiCopy.addEventListener("click", async () => { + try { await navigator.clipboard.writeText(aiOut.value); pmSet(t("cfg.q_pack_ai_copied")); } + catch (e) { pmSet(String(e), true); } + }); + btnAiApply.addEventListener("click", () => { + // Tolerate markdown fences around the model's reply (build the + // fence from charCodes — no backtick literals here). + const FENCE = String.fromCharCode(96) + String.fromCharCode(96) + String.fromCharCode(96); + let text = (aiIn.value || "").trim(); + const lines = text.split("\\n"); + if (lines.length > 0 && lines[0].trim().indexOf(FENCE) === 0) lines.shift(); + if (lines.length > 0 && lines[lines.length - 1].trim() === FENCE) lines.pop(); + text = lines.join("\\n").trim(); + let obj = null; + try { obj = JSON.parse(text); } catch (e) { pmSet(t("cfg.q_pack_bad_json", { err: String(e) }), true); return; } + if (!obj || typeof obj !== "object" || Array.isArray(obj)) { pmSet(t("cfg.q_pack_json_obj"), true); return; } + const ps = (obj.promptSections && typeof obj.promptSections === "object") ? obj.promptSections : {}; + descIn.value = typeof obj.description === "string" ? obj.description : ""; + taPh.value = typeof ps.philosophy === "string" ? ps.philosophy : ""; + taHc.value = typeof ps.howToCompress === "string" ? ps.howToCompress : ""; + const extra = Object.keys(obj).filter((k) => k !== "name" && k !== "version" && k !== "description" && k !== "promptSections"); + Object.keys(ps).forEach((k) => { if (k !== "philosophy" && k !== "howToCompress") extra.push("promptSections." + k); }); + peTa.value = JSON.stringify(obj, null, 2); + showPeTab("form"); + pmSet(extra.length ? t("cfg.q_pack_ai_extra", { names: extra.join(", ") }) : t("cfg.q_pack_ai_apply_ok")); + }); + peBox.append(peTabs, peFormPane, peAiPane, peJsonPane); box.append(pmRow, peBox); + showPeTab("form"); let editingPack = ""; // "" = closed; otherwise the name being edited let editingNew = false; function pmSet(text, isError) { @@ -4093,8 +4316,16 @@ if (d.keepalive) kv(parts, t("det.keepalive"), d.keepalive.tierLabel + " · " + editingNew = true; pmName.value = ""; peTa.value = '{\\n "promptSections": {\\n "philosophy": ""\\n }\\n}\\n'; + baseSel.value = ""; + descIn.value = ""; + taPh.value = ""; + taHc.value = ""; + aiNeed.value = ""; + aiOut.value = ""; + aiIn.value = ""; peBox.hidden = false; pmSet(""); + showPeTab("form"); }); pmEdit.addEventListener("click", async () => { const name = packSel.value; @@ -4107,11 +4338,18 @@ if (d.keepalive) kv(parts, t("det.keepalive"), d.keepalive.tierLabel + " · " + try { const r = await json(API_ROOT + "/packs/user/" + encodeURIComponent(name)); peTa.value = r && typeof r.json === "string" && r.json ? r.json : "{}\\n"; + let loadedObj = null; + try { loadedObj = peTa.value ? JSON.parse(peTa.value) : null; } catch (e) { loadedObj = null; } + const loadedPs = (loadedObj && loadedObj.promptSections && typeof loadedObj.promptSections === "object") ? loadedObj.promptSections : {}; + descIn.value = (loadedObj && typeof loadedObj.description === "string") ? loadedObj.description : ""; + taPh.value = (typeof loadedPs.philosophy === "string") ? loadedPs.philosophy : ""; + taHc.value = (typeof loadedPs.howToCompress === "string") ? loadedPs.howToCompress : ""; editingPack = name; editingNew = false; pmName.value = name; peBox.hidden = false; pmSet(""); + showPeTab("form"); } catch (e) { pmSet(String(e), true); } }); pmDel.addEventListener("click", async () => { @@ -4131,11 +4369,7 @@ if (d.keepalive) kv(parts, t("det.keepalive"), d.keepalive.tierLabel + " · " + pmSet(""); }); peSave.addEventListener("click", async () => { - // No regex literals with backslashes here (WEB_CLIENT template): - // strip one leading path separator via charCode instead. - const rawName = (editingNew ? pmName.value.trim() : editingPack); - const first = rawName.charCodeAt(0); - const name = (first === 47 || first === 92 ? rawName.slice(1) : rawName).trim(); + const name = packNameForSave(); if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name) || name.includes("..")) { pmSet(t("cfg.q_pack_bad_name"), true); return; } let parsed; try { parsed = JSON.parse(peTa.value); } catch (e) { pmSet(t("cfg.q_pack_bad_json", { err: String(e) }), true); return; } diff --git a/src/web/i18n.ts b/src/web/i18n.ts index 28ace83317..8024e28b5a 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -603,6 +603,39 @@ export const MESSAGES: Record> = { "cfg.q_pack_ro_builtin": "内置/随包发布(shipped)的包不能在此编辑——在 ~/.config/billion-context/packs/ 新建一个同名包即可整体覆盖它", "cfg.q_pack_ro_del": "只有用户目录(~/.config/billion-context/packs/)里的包可以删除;内置/shipped/项目包请用同名用户包覆盖或直接删文件", "cfg.q_pack_confirm_del": "删除用户目录里的 pack:{name}?(配置文件本身不受影响)", + "cfg.q_pack_tab_form": "表单填写", + "cfg.q_pack_tab_ai": "AI 辅助", + "cfg.q_pack_tab_json": "高级(JSON)", + "cfg.q_pack_base_label": "起稿底本", + "cfg.q_pack_base_blank": "空白新建", + "cfg.q_pack_base_default": "系统默认规则", + "cfg.q_pack_base_chat": "chat(长期陪伴)", + "cfg.q_pack_base_lean": "lean(精简)", + "cfg.q_pack_base_load": "载入底本", + "cfg.q_pack_desc": "用途说明(可选)", + "cfg.q_pack_desc_ph": "一句话说明这个包干什么用,会显示在包名下拉里", + "cfg.q_pack_phil": "摘要哲学(philosophy)", + "cfg.q_pack_phil_help": "告诉模型写摘要时站什么立场:从谁的视角出发、优先保留什么信息、什么算绝不能丢的关键内容。留空 = 沿用系统默认哲学。例:「这是一段与用户的长期陪伴对话,摘要必须保留人物设定、关系状态与未完成的约定。」", + "cfg.q_pack_hc": "怎么写摘要(howToCompress)", + "cfg.q_pack_hc_help": "摘要的具体写作规则:结构、粒度、是否要时间线等硬性要求。留空 = 沿用系统默认规则。", + "cfg.q_pack_form_hint": "留空的字段不会写进包文件,运行时自动沿用系统默认文案;保存前请至少填写一项。", + "cfg.q_pack_form_save": "保存这个包", + "cfg.q_pack_form_empty": "两个字段都留空会被拒绝——至少填「摘要哲学」或「怎么写摘要」其中一项", + "cfg.q_pack_ai_need": "先用大白话描述你的需求:", + "cfg.q_pack_ai_need_ph": "例如:我主要用它做长期聊天陪伴,希望摘要记住人物设定和承诺,不要像修代码那样记录……", + "cfg.q_pack_ai_need_empty": "先用一两句话描述你的使用场景,再点「生成提示词」", + "cfg.q_pack_ai_gen": "生成提示词", + "cfg.q_pack_ai_gen_ok": "提示词已生成——点「复制提示词」后原样丢给任意 AI 执行", + "cfg.q_pack_ai_copy": "复制提示词", + "cfg.q_pack_ai_copied": "提示词已复制到剪贴板", + "cfg.q_pack_ai_hint": "把上面生成的提示词原样发给任意大模型,等它返回 JSON,再粘进下面这个框:", + "cfg.q_pack_ai_apply": "解析并填入表单", + "cfg.q_pack_ai_apply_ok": "已解析并填进表单;完整 JSON 已同步到「高级(JSON)」页签", + "cfg.q_pack_ai_extra": "模型还给了这些高级字段:{names}——已放进「高级(JSON)」页签,随包一并保存", + "cfg.q_pack_json_obj": "粘贴的内容必须是单个 JSON 对象", + "cfg.q_pack_ai_p1": "你是帮我定制『压缩提示词包』的助手。我用 billion-context 的场景与需求如下:{need}", + "cfg.q_pack_ai_p2": "请据此写出 bili-pack.json 格式的 JSON。结构:顶层对象可含 name(可选,小写字母数字与 ._-,不想要就不写)、description(可选,一句人话说明用途)、promptSections(对象,必含以下至少一项):philosophy —— 摘要哲学:写摘要时站什么立场、优先保留什么信息、什么算绝不能丢;howToCompress —— 摘要的具体写作规则:结构、粒度、时间线等硬性要求。", + "cfg.q_pack_ai_p3": "写作要求:1. 内容必须贴合我给的具体场景,禁止泛泛而谈;2. 这两节的读者是 AI 模型本身,用清晰的祈使句分条陈述;3. 若某节对我的场景没有价值,就整段省略该字段(省略 = 系统沿用默认文案),不要用空字符串占位;4. 最终只输出一个 JSON 对象,不要 markdown 围栏、不要注释、不要任何解释文字。", "cfg.q_pck": "prompt_cache_key 自注入(promptCache.routing)", "cfg.q_pck_disabled_desc": "关闭(当前默认):bili 不自行写 prompt_cache_key,客户端自带的值仍原样转发。直连官方 API 的用户保持此项即可。", "cfg.q_pck_auto_desc": "旧版默认行为:插件车道请求一律加盖会话 id,Responses 线仅对 api.openai.com 注入;上游拒绝时自动 A/B 探测并记忆停用。中转站/号池场景推荐此项。", @@ -1290,6 +1323,39 @@ export const MESSAGES: Record> = { "cfg.q_pack_ro_builtin": "built-in / shipped packs can't be edited here — create a same-named pack in ~/.config/billion-context/packs/ to override it", "cfg.q_pack_ro_del": "only user-dir packs (~/.config/billion-context/packs/) can be deleted; override builtins with a same-named user pack instead", "cfg.q_pack_confirm_del": "delete the user-dir pack: {name}? (your config file is untouched)", + "cfg.q_pack_tab_form": "Guided form", + "cfg.q_pack_tab_ai": "AI assist", + "cfg.q_pack_tab_json": "Advanced (JSON)", + "cfg.q_pack_base_label": "Start from", + "cfg.q_pack_base_blank": "Blank", + "cfg.q_pack_base_default": "System defaults", + "cfg.q_pack_base_chat": "chat (companionship)", + "cfg.q_pack_base_lean": "lean (token-saving)", + "cfg.q_pack_base_load": "Load base text", + "cfg.q_pack_desc": "Description (optional)", + "cfg.q_pack_desc_ph": "one line on what this pack is for; shown under the pack name in the picker", + "cfg.q_pack_phil": "Compression philosophy (philosophy)", + "cfg.q_pack_phil_help": "Which stance summaries take: whose perspective, what to keep first, what counts as must-never-lose information. Empty = system default philosophy. E.g. \"this is a long-term companionship chat; summaries must preserve persona, relationship state and open promises.\"", + "cfg.q_pack_hc": "How to summarize (howToCompress)", + "cfg.q_pack_hc_help": "Concrete writing rules for summaries: structure, granularity, timeline requirements. Empty = system default rules.", + "cfg.q_pack_form_hint": "Empty fields are omitted from the pack file and fall back to system defaults at runtime; fill at least one before saving.", + "cfg.q_pack_form_save": "Save this pack", + "cfg.q_pack_form_empty": "Both fields empty is rejected — fill at least \"compression philosophy\" or \"how to summarize\"", + "cfg.q_pack_ai_need": "Describe your need in plain words:", + "cfg.q_pack_ai_need_ph": "e.g. I mainly use it for long-term chat companionship; summaries should remember personas and promises, not read like bug reports...", + "cfg.q_pack_ai_need_empty": "Describe your use case in a couple of sentences first, then press Generate prompt", + "cfg.q_pack_ai_gen": "Generate prompt", + "cfg.q_pack_ai_gen_ok": "Prompt generated — copy it and hand it to any AI as-is", + "cfg.q_pack_ai_copy": "Copy prompt", + "cfg.q_pack_ai_copied": "Prompt copied to clipboard", + "cfg.q_pack_ai_hint": "Send the generated prompt as-is to any LLM, paste the JSON it returns below, then press the button:", + "cfg.q_pack_ai_apply": "Parse into the form", + "cfg.q_pack_ai_apply_ok": "Parsed and filled into the form; the full JSON is synced to the Advanced (JSON) tab", + "cfg.q_pack_ai_extra": "The model also returned advanced fields: {names} — kept in the Advanced (JSON) tab and saved with the pack", + "cfg.q_pack_json_obj": "the pasted content must be a single JSON object", + "cfg.q_pack_ai_p1": "You are helping me customize a compression prompt pack for billion-context. My scenario and requirements:", + "cfg.q_pack_ai_p2": "Write the JSON in bili-pack.json shape. Top-level object may contain: name (optional; lowercase letters/digits and ._- ; omit if unwanted), description (optional; one plain-sentence purpose), promptSections (object; at least one of): philosophy — the stance summaries take, what to keep first, what must never be lost; howToCompress — concrete summary-writing rules: structure, granularity, timeline requirements.", + "cfg.q_pack_ai_p3": "Rules: 1. Content must fit my concrete scenario — no generic filler; 2. The readers of both sections are the AI model itself — clear imperative bullet-style sentences; 3. If a section adds no value for my scenario, OMIT that key entirely (omitted = system defaults stay) instead of writing an empty string; 4. Output ONLY one JSON object — no markdown fences, no comments, no prose.", "cfg.q_pck": "prompt_cache_key self-stamping (promptCache.routing)", "cfg.q_pck_disabled_desc": "Off (current default): bili never writes its own prompt_cache_key; client-supplied values still forward verbatim. Direct official-API users stay here.", "cfg.q_pck_auto_desc": "Pre-#5079 behavior: plugin-lane requests are stamped with the session id, the Responses wire injects only for api.openai.com; rejecting upstreams are auto-detected via A/B probe and remembered. Recommended for relay/account-pool setups.", diff --git a/src/web/index.ts b/src/web/index.ts index c1890b3bf7..f11b93e0b4 100644 --- a/src/web/index.ts +++ b/src/web/index.ts @@ -4,6 +4,7 @@ import { VERSION, BUILD_COMMIT } from "../version.js"; export { handleConfigGet, handleConfigPut, + handlePackTemplatesGet, handlePricingGet, handleSummaryCredentialPut, handleUserPackDelete, diff --git a/tests/web-user-packs.test.ts b/tests/web-user-packs.test.ts index 8569fb5b13..e6cffc354f 100644 --- a/tests/web-user-packs.test.ts +++ b/tests/web-user-packs.test.ts @@ -17,6 +17,7 @@ import type { ProxyOptions } from "../src/config.js"; import { SessionStore, _setStoreForTest } from "../src/persist.js"; import { _setForTest as setRegistryForTest } from "../src/registry.js"; import { rmrf } from "./tmp-rm.js"; +import { CHAT_COMPRESS_PHILOSOPHY, CHAT_HOW_TO_COMPRESS } from "../src/chat-pack.js"; async function waitReady(port: number): Promise { for (let i = 0; i < 200; i++) { @@ -113,6 +114,21 @@ test("#5328: user-dir pack management endpoints", async (t) => { assert.equal(got.name, "my-pack"); assert.equal(JSON.parse(got.json).promptSections.philosophy, "user philosophy"); + // #5344: base texts for the guided editor — exactly the three + // resolvable shipped/builtin packs, tri-state resolved like + // buildCompressSystemPrompt (chat overrides both sections verbatim, + // default has none so the kernel default prose comes through). + const tplRes = await request("GET", port, "/__bili/packs/templates"); + assert.equal(tplRes.status, 200, `templates ok (${tplRes.body})`); + const tpl = JSON.parse(tplRes.body) as { packs: Record }; + assert.deepEqual(Object.keys(tpl.packs).sort(), ["chat", "default", "lean"]); + assert.ok(tpl.packs.default.philosophy.length > 100, "default philosophy falls back to kernel prose"); + assert.ok(tpl.packs.default.howToCompress.length > 100, "default howToCompress falls back to kernel prose"); + assert.equal(tpl.packs.chat.philosophy, CHAT_COMPRESS_PHILOSOPHY, "chat philosophy is the shipped text verbatim"); + assert.equal(tpl.packs.chat.howToCompress, CHAT_HOW_TO_COMPRESS, "chat howToCompress is the shipped text verbatim"); + assert.ok(tpl.packs.lean.howToCompress.length > 50, "lean provides its condensed rules"); + assert.notEqual(tpl.packs.lean.howToCompress, tpl.packs.default.howToCompress, "lean howToCompress differs from default"); + // Invalid payloads are refused before touching disk. const badJson = await request("PUT", port, "/__bili/packs/user/bad-json", JSON.stringify({ json: "{nope" })); assert.equal(badJson.status, 400, `invalid JSON refused (${badJson.body})`); From d2bc4fc36de4def2b3ac8157990acb1f3ae6f9b5 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Sat, 31 Oct 2026 21:44:53 +0800 Subject: [PATCH 2/2] fix(web): PackTemplate stays internal (unused-exports gate) Internal-only type in src/web/api.ts; drop the leading export so the unused-exports CI gate stops flagging PR #5345. --- src/web/api.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/web/api.ts b/src/web/api.ts index baae2ef1b6..059f38bc18 100644 --- a/src/web/api.ts +++ b/src/web/api.ts @@ -177,7 +177,7 @@ export async function handleUserPackDelete(res: ServerResponse, name: string): P // tri-state resolution buildCompressSystemPrompt performs: absent key -> // kernel default text; null -> removed (empty); string -> verbatim. const PACK_TEMPLATE_NAMES = ["default", "chat", "lean"] as const; -export type PackTemplate = { description?: string; philosophy: string; howToCompress: string }; +type PackTemplate = { description?: string; philosophy: string; howToCompress: string }; function packTemplateFor(name: string): PackTemplate { const resolution = resolveCompressSurfaceDetailed({ promptPack: name });