feat: 支持自由编辑破限提示词与一键恢复默认(v0.2.17)

This commit is contained in:
yexi-by committed 2026-11-28 04:47:29 +08:00
1 parent 3d7177dcb9
commit ccc61fac4c
17 files changed
+1122 -246

No files matched your search

+1
View File
@@ -34,6 +34,7 @@ dsh plugin --profile web remove dsh-unrestricted
Restart `dsh web` or DSH Desktop after installing, then enable both the plugin switch under **Plugins** and **"Enable unrestricted mode"** inside its settings card. Additional card features:
- **Strip Host Brand Identity**: Independently removes `DeepSeek Harness` / `DSH` identity sections and Web GUI checkout context to avoid HTTP `429` client-fingerprinting blocks on third-party proxy routes.
- **Custom Execution Prompt Editor**: Edit the injected `unrestricted:execution-mode` prompt directly inside the settings card (e.g., tweak sensitive keywords or substitute custom rules) with instant hot-apply on the next request and one-click reset to default.
- **Mode Coverage & Prompt Preview**: Inspect and copy the full assembled system prompt across Standard, PTC, Cordis, and Minimal modes.
## Development & Testing
+1
View File
@@ -34,6 +34,7 @@ dsh plugin --profile web remove dsh-unrestricted
インストール後に `dsh web` または DSH Desktop を再起動し、左サイドバーの **「プラグイン → dsh-unrestricted」** でプラグインスイッチとカード内の **「破限を有効化」** をオンにします。設定カードの追加機能:
- **ホストブランド識別子の非表示**:破限スイッチとは独立して動作し、`DeepSeek Harness` / `DSH` の識別セクションや Web GUI パスを除去してサードパーティ経路でのクライアント指紋検知(HTTP `429`)を回避します。
- **破限プロンプトの自由編集**:設定カード内から `unrestricted:execution-mode` プロンプト本文を自由に編集でき(敏感なキーワードの調整や独自ルールへの差し替えなど)、保存後すぐ次のリクエストから反映されます。ワンクリックで内蔵デフォルトへ復元可能です。
- **モード状態とプロンプトプレビュー**:Standard、PTC、Cordis、Minimal の組み立て済みシステムプロンプトを展開確認・コピーできます。
## 開発とテスト
+1
View File
@@ -34,6 +34,7 @@ dsh plugin --profile web remove dsh-unrestricted
安装或更新后重启 `dsh web` 或 DSH 桌面端,在侧栏 **「插件 → dsh-unrestricted」** 打开插件开关与卡片内的 **「启用破限」**。卡片同时提供:
- **隐藏宿主品牌标识**:独立于破限主开关生效,移除系统提示词与运行时上下文中的 `DeepSeek Harness` / `DSH` 身份段落与 Web GUI 路径,避免第三方反代路由因客户端特征检测返回 `429`。
- **破限提示词自由编辑**:支持在卡片内直接编辑 `unrestricted:execution-mode` 破限提示词本体(如删改敏感关键词或替换为自定义规则),保存后从下一次请求即时生效,并支持一键恢复内置默认。
- **模式覆盖与提示词预览**:查看并一键复制 Standard、PTC、Cordis、Minimal 四种模式组装后的完整系统提示词。
## 开发与验证
+545 -215
View File
@@ -11,6 +11,10 @@ window.__ModuleLoader__.load({
const RPC_CHANNEL = "/api";
const RPC_NAMESPACE = "dsh-unrestricted";
const SETTINGS_NS = "unrestricted";
/** Normalize line endings so YAML/browser values compare identically across OSes. */
function normalizePromptText(value) {
return typeof value === "string" ? value.replace(/\r\n?/g, "\n") : "";
}
/** Human-readable error text for the banner. */
function messageOf(error) {
return error instanceof Error ? error.message : String(error);
@@ -26,6 +30,9 @@ window.__ModuleLoader__.load({
let snapshot = {
enabled: false,
stripHostIdentity: false,
customPrompt: "",
defaultPrompt: "",
isCustomPrompt: false,
writable: false,
settingsStatus: "loading",
status: null,
@@ -47,10 +54,16 @@ window.__ModuleLoader__.load({
const settingsSnapshot = settings.getSnapshot();
const enabled = settingsSnapshot.value?.enabled === true;
const stripHostIdentity = settingsSnapshot.value?.stripHostIdentity === true;
if (enabled !== snapshot.enabled || stripHostIdentity !== snapshot.stripHostIdentity) invalidatePreviews();
const customPrompt = normalizePromptText(settingsSnapshot.value?.customPrompt);
const defaultPrompt = normalizePromptText(snapshot.status?.defaultPrompt);
const isCustomPrompt = customPrompt.trim() !== "" && (defaultPrompt === "" || customPrompt !== defaultPrompt);
if (enabled !== snapshot.enabled || stripHostIdentity !== snapshot.stripHostIdentity || customPrompt !== snapshot.customPrompt) invalidatePreviews();
snapshot = {
enabled,
stripHostIdentity,
customPrompt,
defaultPrompt,
isCustomPrompt,
writable: settingsSnapshot.writable,
settingsStatus: settingsSnapshot.status,
status: snapshot.status,
@@ -106,24 +119,52 @@ window.__ModuleLoader__.load({
function refresh(clearPreviews = false) {
return readStatus("status", clearPreviews);
}
function updateSetting(field, value) {
return whileBusy(async () => {
async function updateSetting(field, value) {
let accepted = false;
await whileBusy(async () => {
try {
await settings.set(field, value);
accepted = await settings.set(field, value) !== false;
await refresh(true);
} catch (error) {
snapshot = {
...snapshot,
message: messageOf(error)
};
accepted = false;
}
});
return accepted;
}
function setEnabled(enabled) {
return updateSetting("enabled", enabled);
async function clearCustomPrompt() {
let accepted = false;
await whileBusy(async () => {
try {
accepted = (typeof settings.unset === "function" ? await settings.unset("customPrompt") : await settings.set("customPrompt", "")) !== false;
await refresh(true);
} catch (error) {
snapshot = {
...snapshot,
message: messageOf(error)
};
accepted = false;
}
});
return accepted;
}
function setStripHostIdentity(strip) {
return updateSetting("stripHostIdentity", strip);
async function setEnabled(enabled) {
await updateSetting("enabled", enabled);
}
async function setStripHostIdentity(strip) {
await updateSetting("stripHostIdentity", strip);
}
function setCustomPrompt(prompt) {
const normalized = normalizePromptText(prompt);
const defaultPrompt = normalizePromptText(snapshot.status?.defaultPrompt);
if (normalized.trim() === "" || defaultPrompt !== "" && normalized === defaultPrompt) return clearCustomPrompt();
return updateSetting("customPrompt", normalized);
}
function resetCustomPrompt() {
return clearCustomPrompt();
}
function recheck() {
return readStatus("recheck", true);
@@ -182,6 +223,8 @@ window.__ModuleLoader__.load({
hooks: { view },
setEnabled,
setStripHostIdentity,
setCustomPrompt,
resetCustomPrompt,
recheck,
refresh: () => refresh(true),
loadPreview
@@ -201,9 +244,27 @@ window.__ModuleLoader__.load({
description: "开启后,各运行模式与委派子代理的系统提示词将自动融合无限制本地执行契约;关闭即恢复 DSH 原版提示词。切换从下一次请求生效,不改动正在执行的请求、工具定义、权限配置与会话历史。",
toggle: "启用破限模式",
stripHostBadge: "已隐去宿主标识",
customPromptBadge: "已自定义提示词",
stripHostTitle: "隐藏宿主品牌标识",
stripHostDesc: "移除系统提示词与运行时上下文中的 DeepSeek Harness / DSH 身份段落及开发界面路径,避免第三方路由(适用于 Google Antigravity 反重力反代、Google AI Studio PG 渠道等)因检测到客户端特征而返回 429 拦截(可独立于破限开关生效)。",
scopeNote: "仅作用于由 DSH 组装的系统提示词;模型平台或外部网关的远端策略不在本插件覆盖范围内。",
promptEditorTitle: "破限提示词",
promptEditorDesc: "默认内置英文破限契约;支持自由删改敏感关键词或替换为自定义规则,保存后从下一次请求生效。",
promptStateDefault: "内置默认",
promptStateCustom: "已自定义",
promptStateUnsaved: "未保存",
openPromptEditor: "编辑提示词",
closePromptEditor: "收起编辑",
promptEditorLoading: "正在加载内置提示词内容…",
promptEditorPlaceholder: "输入要注入到 unrestricted:execution-mode 段落的提示词内容…",
promptEditorChars: "字符",
promptEditorShortcutHint: "Ctrl/Cmd + Enter 保存",
promptEditorEmptyHint: "提示词不能为空;如需使用内置内容,请点击「恢复默认」。",
promptEditorSaved: "已保存,下一次请求生效",
promptEditorResetDone: "已恢复内置默认提示词",
promptEditorSave: "保存更改",
promptEditorDiscard: "放弃更改",
promptEditorReset: "恢复默认",
statusTitle: "模式覆盖与提示词预览",
statusSubtitle: "覆盖全部 4 种预设及委派子代理,可随时展开核对或复制融合后的完整提示词。",
modeStandard: "Standard 标准模式",
@@ -252,9 +313,27 @@ window.__ModuleLoader__.load({
description: "When enabled, system prompts across all modes and delegated subagents are fused with the unrestricted local execution contract; disabling restores the stock DSH prompt immediately. Takes effect from the next request without altering in-flight turns, tool schemas, permissions, or session history.",
toggle: "Enable unrestricted mode",
stripHostBadge: "Host identity stripped",
customPromptBadge: "Custom prompt",
stripHostTitle: "Strip host brand identity",
stripHostDesc: "Remove DeepSeek Harness / DSH identity sections and Web GUI checkout context from assembled prompts to prevent HTTP 429 client-fingerprinting blocks on third-party routes such as Google Antigravity proxies and Google AI Studio PG channels (works independently of the main toggle).",
scopeNote: "Applies only to system prompts assembled by DSH; upstream model provider policies outside the prompt are out of scope.",
promptEditorTitle: "Execution Prompt",
promptEditorDesc: "Built-in English contract tuned for reliability. Freely edit keywords or replace with custom rules; saved changes apply on the next request.",
promptStateDefault: "Default",
promptStateCustom: "Customized",
promptStateUnsaved: "Unsaved",
openPromptEditor: "Edit prompt",
closePromptEditor: "Hide editor",
promptEditorLoading: "Loading built-in prompt…",
promptEditorPlaceholder: "Enter the prompt text injected into the unrestricted:execution-mode section…",
promptEditorChars: "chars",
promptEditorShortcutHint: "Ctrl/Cmd + Enter to save",
promptEditorEmptyHint: "Prompt cannot be empty. Click \"Reset to default\" to restore the built-in prompt.",
promptEditorSaved: "Saved — applies on next request",
promptEditorResetDone: "Restored built-in default prompt",
promptEditorSave: "Save changes",
promptEditorDiscard: "Discard",
promptEditorReset: "Reset to default",
statusTitle: "Mode Coverage & Prompt Preview",
statusSubtitle: "Covers all 4 built-in presets and delegated subagents. Expand any mode to inspect or copy the full fused prompt.",
modeStandard: "Standard",
@@ -543,6 +622,67 @@ window.__ModuleLoader__.load({
overflow-wrap: anywhere;
}
.dsh-unrestricted-editor {
display: flex;
flex-direction: column;
gap: 8px;
padding-top: 10px;
border-top: 1px solid var(--dsw-alias-border-l3, var(--dsw-alias-border-l2));
}
.dsh-unrestricted-editorInput {
width: 100%;
min-height: 240px;
max-height: 520px;
box-sizing: border-box;
margin: 0;
border: 1px solid var(--dsw-alias-border-l2);
border-radius: var(--dsw-radius-md, 8px);
padding: 10px 12px;
background: var(--dsw-alias-bg-layer-1, var(--dsw-alias-bg-layer-2));
color: var(--dsw-alias-label-primary);
font-family: var(--ds-font-family-code, ui-monospace, SFMono-Regular, Menlo, monospace);
font-size: 12px;
line-height: 18px;
resize: vertical;
outline: none;
transition: border-color 120ms ease;
}
.dsh-unrestricted-editorInput:focus {
border-color: var(--dsw-alias-state-business-primary, var(--dsw-alias-border-l1));
}
.dsh-unrestricted-editorInput:disabled {
opacity: 0.65;
cursor: not-allowed;
}
.dsh-unrestricted-editorFooter {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 8px 12px;
}
.dsh-unrestricted-editorStatus {
flex: 1;
min-width: 160px;
margin: 0;
font-size: 12px;
line-height: 18px;
color: var(--dsw-alias-label-tertiary);
}
.dsh-unrestricted-editorStatus[data-tone='success'] {
color: var(--dsw-alias-state-success-primary);
}
.dsh-unrestricted-editorStatus[data-tone='warning'] {
color: var(--dsw-alias-state-warning-primary, var(--dsw-alias-state-error-primary));
}
@media (max-width: 640px) {
.dsh-unrestricted-card {
padding: 14px;
@@ -575,6 +715,7 @@ window.__ModuleLoader__.load({
/**
* The unrestricted settings view:
* - Master toggle card with native Switch, status Tag, and scope boundary notes
* - Editable execution-mode prompt card with save, discard, and reset-to-default
* - Per-preset coverage list with StateDot, Tag, preview drawer, and one-click copy
*/
/** Mode rows in display order, with their locale label and description keys. */
@@ -648,6 +789,10 @@ window.__ModuleLoader__.load({
const detail = entry.preview?.reason ?? entry.message;
return detail !== void 0 && detail.trim() !== "" ? `${t("previewUnavailable")}${detail}` : t("errorPreviewFailed");
}
/** UTF-8 byte length of a string in browser environments. */
function utf8ByteLength(text) {
return new TextEncoder().encode(text).length;
}
/**
* Render the unrestricted configuration cards.
*/
@@ -657,7 +802,26 @@ window.__ModuleLoader__.load({
const status = view.status;
const [openPreview, setOpenPreview] = (0, react.useState)(null);
const [copiedPreset, setCopiedPreset] = (0, react.useState)(null);
const [editorOpen, setEditorOpen] = (0, react.useState)(false);
const [draft, setDraft] = (0, react.useState)("");
const [hasLocalEdit, setHasLocalEdit] = (0, react.useState)(false);
const [promptFeedback, setPromptFeedback] = (0, react.useState)(null);
const feedbackTimerRef = (0, react.useRef)(null);
const openEntry = openPreview === null ? void 0 : view.previews[openPreview];
const effectivePrompt = view.customPrompt.trim() !== "" ? view.customPrompt : view.defaultPrompt;
const normalizedDraft = draft.replace(/\r\n?/g, "\n");
const isDirty = hasLocalEdit && normalizedDraft !== effectivePrompt;
const isDraftEmpty = normalizedDraft.trim() === "";
const editorReady = effectivePrompt !== "" || view.status !== null;
const controlsEditable = view.writable && view.settingsStatus === "ready" && !view.busy;
const canSave = controlsEditable && isDirty && !isDraftEmpty;
const canReset = controlsEditable && (view.isCustomPrompt || view.defaultPrompt !== "" && normalizedDraft !== view.defaultPrompt);
(0, react.useEffect)(() => {
if (!hasLocalEdit) setDraft(effectivePrompt);
}, [effectivePrompt, hasLocalEdit]);
(0, react.useEffect)(() => () => {
if (feedbackTimerRef.current !== null) clearTimeout(feedbackTimerRef.current);
}, []);
(0, react.useEffect)(() => {
if (openPreview !== null && openEntry === void 0) loadPreview(openPreview);
}, [
@@ -665,6 +829,35 @@ window.__ModuleLoader__.load({
openEntry,
loadPreview
]);
function showPromptFeedback(kind) {
setPromptFeedback(kind);
if (feedbackTimerRef.current !== null) clearTimeout(feedbackTimerRef.current);
feedbackTimerRef.current = setTimeout(() => {
setPromptFeedback(null);
feedbackTimerRef.current = null;
}, 2600);
}
async function handleSavePrompt() {
if (!canSave) return;
if (!await props.setCustomPrompt(draft)) return;
const matchedDefault = view.defaultPrompt !== "" && normalizedDraft === view.defaultPrompt;
setHasLocalEdit(false);
showPromptFeedback(matchedDefault ? "reset" : "saved");
}
function handleDiscardPrompt() {
setDraft(effectivePrompt);
setHasLocalEdit(false);
setPromptFeedback(null);
}
async function handleResetPrompt() {
if (!canReset) return;
if (view.isCustomPrompt) {
if (!await props.resetCustomPrompt()) return;
}
setDraft(view.defaultPrompt);
setHasLocalEdit(false);
showPromptFeedback("reset");
}
const hasFailedMode = status !== null && Object.values(status.modes).some((mode) => mode.state === "failed");
const summaryKey = view.settingsStatus === "loading" ? "summaryLoading" : view.settingsStatus === "unavailable" ? "summaryUnavailable" : hasFailedMode ? "summaryValidationFailed" : view.enabled ? "summaryEnabled" : "summaryDisabled";
const summaryTone = view.settingsStatus !== "ready" ? "neutral" : hasFailedMode ? "warning" : view.enabled ? "success" : "neutral";
@@ -697,219 +890,356 @@ window.__ModuleLoader__.load({
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-root",
"aria-busy": view.busy,
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
className: "dsh-unrestricted-card",
"aria-labelledby": "dsh-unrestricted-main-title",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-header",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-headerTitle",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h3", {
id: "dsh-unrestricted-main-title",
className: "dsh-unrestricted-title",
children: t("title")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tag, {
tone: summaryTone,
children: t(summaryKey)
}),
view.settingsStatus === "ready" && view.stripHostIdentity && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tag, {
tone: "outline",
children: t("stripHostBadge")
})
]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-headerControls",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "dsh-unrestricted-switchLabel",
children: t("toggle")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Switch, {
checked: view.enabled,
disabled: !view.writable || view.settingsStatus !== "ready" || view.busy,
label: t("toggle"),
onChange: (checked) => {
props.setEnabled(checked);
}
})]
})]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-description",
children: t("description")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-note",
children: t("scopeNote")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-optionRow",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-optionCopy",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "dsh-unrestricted-modeName",
children: t("stripHostTitle")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-note",
children: t("stripHostDesc")
})]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Switch, {
checked: view.stripHostIdentity,
disabled: !view.writable || view.settingsStatus !== "ready" || view.busy,
label: t("stripHostTitle"),
onChange: (checked) => {
props.setStripHostIdentity(checked);
}
})]
}),
view.settingsStatus === "loading" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-note",
role: "status",
children: t("settingsLoading")
}),
view.settingsStatus === "unavailable" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-banner",
"data-tone": "info",
role: "status",
children: t("settingsUnavailable")
}),
view.message !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-banner",
"data-tone": "error",
role: "alert",
children: localizeBannerError(view.message, t)
})
]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
className: "dsh-unrestricted-card",
"aria-labelledby": "dsh-unrestricted-modes-title",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-header",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "dsh-unrestricted-headerTitle",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h4", {
id: "dsh-unrestricted-modes-title",
className: "dsh-unrestricted-subtitle",
children: t("statusTitle")
})
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "dsh-unrestricted-headerControls",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
variant: "outline",
size: "sm",
disabled: view.busy,
onClick: () => {
props.refresh();
},
children: t("refresh")
})
})]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-note",
children: t("statusSubtitle")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("ul", {
className: "dsh-unrestricted-modes",
children: MODE_ROWS.map((row) => {
const mode = status?.modes[row.id];
const entry = view.previews[row.id];
const isOpen = openPreview === row.id;
const previewText = entry?.preview?.text;
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("li", {
className: "dsh-unrestricted-mode",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
className: "dsh-unrestricted-card",
"aria-labelledby": "dsh-unrestricted-main-title",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-header",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-headerTitle",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-modeMain",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-modeInfo",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-modeHeading",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.StateDot, { state: dotStateOf(mode) }),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "dsh-unrestricted-modeName",
children: t(row.labelKey)
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tag, {
tone: "outline",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "dsh-unrestricted-mono",
children: t(row.presetKey)
})
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tag, {
tone: modeTagTone(mode),
children: t(stateKey(mode))
})
]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-modeDesc",
children: t(row.descKey)
})]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "dsh-unrestricted-headerControls",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
variant: isOpen ? "toolbar" : "outline",
size: "sm",
onClick: () => {
togglePreview(row.id);
},
children: t(isOpen ? "hidePreview" : "showPreview")
})
})]
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h3", {
id: "dsh-unrestricted-main-title",
className: "dsh-unrestricted-title",
children: t("title")
}),
mode !== void 0 && mode.issues.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-issues",
children: formatIssues(mode.issues)
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tag, {
tone: summaryTone,
children: t(summaryKey)
}),
isOpen && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "dsh-unrestricted-preview",
children: entry === void 0 || entry.status === "loading" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-note",
role: "status",
children: t("previewLoading")
}) : entry.status === "failed" || entry.preview?.available === false ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-banner",
"data-tone": "error",
role: "alert",
children: localizePreviewError(entry, t)
}) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-previewHeader",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", {
className: "dsh-unrestricted-previewMeta",
children: [
entry.preview?.lines,
" ",
t("previewSize"),
entry.preview?.bytes !== void 0 && ` · ${(0, _deepseek_ai_dsh_client_ui_primitives.fileSizeText)(entry.preview.bytes)}`,
entry.preview?.source !== void 0 && ` · ${t(entry.preview.source === "live" ? "previewSourceLive" : "previewSourceStanding")}`
]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
variant: "ghost",
size: "sm",
onClick: () => {
handleCopyPreview(row.id, previewText);
},
children: t(copiedPreset === row.id ? "copiedPreview" : "copyPreview")
})]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
className: "dsh-unrestricted-previewText",
children: previewText
})] })
view.settingsStatus === "ready" && view.stripHostIdentity && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tag, {
tone: "outline",
children: t("stripHostBadge")
}),
view.settingsStatus === "ready" && view.isCustomPrompt && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tag, {
tone: "info",
children: t("customPromptBadge")
})
]
}, row.id);
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-headerControls",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "dsh-unrestricted-switchLabel",
children: t("toggle")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Switch, {
checked: view.enabled,
disabled: !view.writable || view.settingsStatus !== "ready" || view.busy,
label: t("toggle"),
onChange: (checked) => {
props.setEnabled(checked);
}
})]
})]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-description",
children: t("description")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-note",
children: t("scopeNote")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-optionRow",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-optionCopy",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "dsh-unrestricted-modeName",
children: t("stripHostTitle")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-note",
children: t("stripHostDesc")
})]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Switch, {
checked: view.stripHostIdentity,
disabled: !view.writable || view.settingsStatus !== "ready" || view.busy,
label: t("stripHostTitle"),
onChange: (checked) => {
props.setStripHostIdentity(checked);
}
})]
}),
view.settingsStatus === "loading" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-note",
role: "status",
children: t("settingsLoading")
}),
view.settingsStatus === "unavailable" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-banner",
"data-tone": "info",
role: "status",
children: t("settingsUnavailable")
}),
view.message !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-banner",
"data-tone": "error",
role: "alert",
children: localizeBannerError(view.message, t)
})
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-note",
children: t("subagentNote")
})
]
})]
]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
className: "dsh-unrestricted-card",
"aria-labelledby": "dsh-unrestricted-prompt-title",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-header",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-headerTitle",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h4", {
id: "dsh-unrestricted-prompt-title",
className: "dsh-unrestricted-subtitle",
children: t("promptEditorTitle")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tag, {
tone: view.isCustomPrompt ? "info" : "neutral",
children: t(view.isCustomPrompt ? "promptStateCustom" : "promptStateDefault")
}),
isDirty && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tag, {
tone: "warning",
children: t("promptStateUnsaved")
})
]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-headerControls",
children: [view.isCustomPrompt && !editorOpen && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
variant: "ghost",
size: "sm",
disabled: !controlsEditable,
onClick: () => {
handleResetPrompt();
},
children: t("promptEditorReset")
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
variant: editorOpen ? "toolbar" : "outline",
size: "sm",
onClick: () => {
setEditorOpen((open) => !open);
},
children: t(editorOpen ? "closePromptEditor" : "openPromptEditor")
})]
})]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-note",
children: t("promptEditorDesc")
}),
editorOpen && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "dsh-unrestricted-editor",
children: !editorReady ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-note",
role: "status",
children: t("promptEditorLoading")
}) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-previewHeader",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", {
className: "dsh-unrestricted-previewMeta",
children: [
draft === "" ? 0 : draft.split("\n").length,
" ",
t("previewSize"),
` · ${draft.length} ${t("promptEditorChars")} · ${(0, _deepseek_ai_dsh_client_ui_primitives.fileSizeText)(utf8ByteLength(draft))}`
]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "dsh-unrestricted-previewMeta",
children: t("promptEditorShortcutHint")
})]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("textarea", {
className: "dsh-unrestricted-editorInput",
"aria-label": t("promptEditorTitle"),
placeholder: t("promptEditorPlaceholder"),
spellCheck: false,
value: draft,
disabled: !controlsEditable,
onChange: (event) => {
setDraft(event.target.value);
setHasLocalEdit(true);
setPromptFeedback(null);
},
onKeyDown: (event) => {
if ((event.ctrlKey || event.metaKey) && event.key === "Enter" && canSave) {
event.preventDefault();
handleSavePrompt();
}
}
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-editorFooter",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-editorStatus",
"data-tone": isDraftEmpty ? "warning" : promptFeedback !== null ? "success" : void 0,
role: "status",
children: isDraftEmpty ? t("promptEditorEmptyHint") : promptFeedback === "saved" ? t("promptEditorSaved") : promptFeedback === "reset" ? t("promptEditorResetDone") : ""
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-headerControls",
children: [
isDirty && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
variant: "ghost",
size: "sm",
disabled: view.busy,
onClick: handleDiscardPrompt,
children: t("promptEditorDiscard")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
variant: "outline",
size: "sm",
disabled: !canReset,
onClick: () => {
handleResetPrompt();
},
children: t("promptEditorReset")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
variant: "primary",
size: "sm",
disabled: !canSave,
onClick: () => {
handleSavePrompt();
},
children: t("promptEditorSave")
})
]
})]
})
] })
})
]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
className: "dsh-unrestricted-card",
"aria-labelledby": "dsh-unrestricted-modes-title",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-header",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "dsh-unrestricted-headerTitle",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h4", {
id: "dsh-unrestricted-modes-title",
className: "dsh-unrestricted-subtitle",
children: t("statusTitle")
})
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "dsh-unrestricted-headerControls",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
variant: "outline",
size: "sm",
disabled: view.busy,
onClick: () => {
props.refresh();
},
children: t("refresh")
})
})]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-note",
children: t("statusSubtitle")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("ul", {
className: "dsh-unrestricted-modes",
children: MODE_ROWS.map((row) => {
const mode = status?.modes[row.id];
const entry = view.previews[row.id];
const isOpen = openPreview === row.id;
const previewText = entry?.preview?.text;
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("li", {
className: "dsh-unrestricted-mode",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-modeMain",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-modeInfo",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-modeHeading",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.StateDot, { state: dotStateOf(mode) }),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "dsh-unrestricted-modeName",
children: t(row.labelKey)
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tag, {
tone: "outline",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "dsh-unrestricted-mono",
children: t(row.presetKey)
})
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tag, {
tone: modeTagTone(mode),
children: t(stateKey(mode))
})
]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-modeDesc",
children: t(row.descKey)
})]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "dsh-unrestricted-headerControls",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
variant: isOpen ? "toolbar" : "outline",
size: "sm",
onClick: () => {
togglePreview(row.id);
},
children: t(isOpen ? "hidePreview" : "showPreview")
})
})]
}),
mode !== void 0 && mode.issues.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-issues",
children: formatIssues(mode.issues)
}),
isOpen && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "dsh-unrestricted-preview",
children: entry === void 0 || entry.status === "loading" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-note",
role: "status",
children: t("previewLoading")
}) : entry.status === "failed" || entry.preview?.available === false ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-banner",
"data-tone": "error",
role: "alert",
children: localizePreviewError(entry, t)
}) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
className: "dsh-unrestricted-previewHeader",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", {
className: "dsh-unrestricted-previewMeta",
children: [
entry.preview?.lines,
" ",
t("previewSize"),
entry.preview?.bytes !== void 0 && ` · ${(0, _deepseek_ai_dsh_client_ui_primitives.fileSizeText)(entry.preview.bytes)}`,
entry.preview?.source !== void 0 && ` · ${t(entry.preview.source === "live" ? "previewSourceLive" : "previewSourceStanding")}`
]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
variant: "ghost",
size: "sm",
onClick: () => {
handleCopyPreview(row.id, previewText);
},
children: t(copiedPreset === row.id ? "copiedPreview" : "copyPreview")
})]
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
className: "dsh-unrestricted-previewText",
children: previewText
})] })
})
]
}, row.id);
})
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "dsh-unrestricted-note",
children: t("subagentNote")
})
]
})
]
});
}
//#endregion
+1 -1
View File
@@ -1 +1 @@
{"version":3,"file":"client.js","names":["useState","writeClipboard","Tag","Switch","Button","StateDot","fileSizeText"],"sources":["../src/client/controller.ts","../src/client/locales.ts","../src/client/styles.ts","../src/client/UnrestrictedCard.tsx","../src/client/index.tsx"],"sourcesContent":["/**\n * Browser-half controller for the unrestricted card: binds the `unrestricted`\n * settings namespace (the toggle) and reads per-preset state and previews.\n */\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client'\n// Type-only: the ctx.remote Context merge and the forwarded-event key face.\nimport type {} from '@deepseek-ai/dsh-api-remotes/client'\n// Type-only: the ctx.configForms Context merge.\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client'\n\n/** The toggle section stored in the `unrestricted` settings namespace. */\nexport interface UnrestrictedSettings {\n enabled?: boolean\n stripHostIdentity?: boolean\n}\n\n/** Per-preset fusion state reported by the host half. */\nexport interface UnrestrictedModeState {\n state: 'off' | 'active' | 'failed'\n issues: string[]\n}\n\n/** Host status endpoint payload. */\nexport interface UnrestrictedStatus {\n enabled: boolean\n stripHostIdentity?: boolean\n /** Current plugin version reported by the host half. */\n version?: string\n modes: Record<string, UnrestrictedModeState>\n}\n\n/** Deploy preview for one preset: what switching on would actually assemble. */\nexport interface UnrestrictedPreview {\n presetId: string\n available: boolean\n /** `live` = bytes a live agent received; `standing` = preset scope, no agent bound. */\n source?: 'live' | 'standing'\n /** Fused prompt text; present when available. */\n text?: string\n bytes?: number\n lines?: number\n /** Structured error code when unavailable. */\n errorCode?: string\n /** Diagnostic reason when unavailable. */\n reason?: string\n}\n\n/** One fetched preview, keyed by preset, plus its in-flight/error state. */\nexport interface UnrestrictedPreviewEntry {\n status: 'loading' | 'ready' | 'failed'\n preview?: UnrestrictedPreview\n errorCode?: string\n message?: string\n}\n\n/** Full view snapshot the card subscribes to. */\nexport interface UnrestrictedViewSnapshot {\n /** Persisted toggle; false until the settings scope first syncs. */\n enabled: boolean\n /** Persisted host-brand stripping toggle; false until synced. */\n stripHostIdentity: boolean\n /** Whether the Host document accepts writes. */\n writable: boolean\n /** Settings scope sync state. */\n settingsStatus: 'loading' | 'ready' | 'unavailable'\n /** Live host status; null until the first RPC answer. */\n status: UnrestrictedStatus | null\n /** presetId -> fetched deploy preview. */\n previews: Record<string, UnrestrictedPreviewEntry>\n /** Whether a settings write or status refresh is in flight. */\n busy: boolean\n /** Last transport/business failure, if any. */\n message?: string\n}\n\n/** Minimal RPC wire shape (structural copy of the host RpcResult). */\ntype RpcResult<T> = { ok: true; value: T } | { ok: false; error: { code: string; message: string } }\n\n/** Minimal observable contract consumed by the slot renderer's hook binding. */\nexport interface UnrestrictedViewSource {\n getSnapshot(): UnrestrictedViewSnapshot\n subscribe(listener: () => void): () => void\n}\n\n/** Inject face handed to the card at registration. */\nexport interface UnrestrictedCardInjected {\n hooks: {\n /** Reactive card view. */\n view: UnrestrictedViewSource\n }\n /** Persist the toggle. */\n setEnabled: (enabled: boolean) => Promise<void>\n /** Persist whether host identity branding is stripped from prompts. */\n setStripHostIdentity: (strip: boolean) => Promise<void>\n /** Re-validate runtime state and refresh. */\n recheck: () => Promise<void>\n /** Re-read host status and invalidate cached previews. */\n refresh: () => Promise<void>\n /** Fetch the exact fused prompt this preset would deploy. */\n loadPreview: (presetId: string) => Promise<void>\n}\n\nconst RPC_CHANNEL = '/api'\nconst RPC_NAMESPACE = 'dsh-unrestricted'\nconst SETTINGS_NS = 'unrestricted'\n\n/** Human-readable error text for the banner. */\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/**\n * Create the card controller bound to the calling plugin's context.\n * @param ctx - the browser plugin context (connection + remote + configForms injected).\n * @returns the controller whose face() feeds the slot inject share.\n */\nexport function createUnrestrictedController(ctx: Context) {\n const connection = ctx.get('connection') as ConnectionHandle\n const settings = ctx.configForms.get<UnrestrictedSettings>(SETTINGS_NS)\n\n let snapshot: UnrestrictedViewSnapshot = {\n enabled: false,\n stripHostIdentity: false,\n writable: false,\n settingsStatus: 'loadinLine truncated
{"version":3,"file":"client.js","names":["useState","useRef","writeClipboard","Tag","Switch","Button","fileSizeText","StateDot"],"sources":["../src/client/controller.ts","../src/client/locales.ts","../src/client/styles.ts","../src/client/UnrestrictedCard.tsx","../src/client/index.tsx"],"sourcesContent":["/**\n * Browser-half controller for the unrestricted card: binds the `unrestricted`\n * settings namespace (the toggle) and reads per-preset state and previews.\n */\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client'\n// Type-only: the ctx.remote Context merge and the forwarded-event key face.\nimport type {} from '@deepseek-ai/dsh-api-remotes/client'\n// Type-only: the ctx.configForms Context merge.\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client'\n\n/** The toggle section stored in the `unrestricted` settings namespace. */\nexport interface UnrestrictedSettings {\n enabled?: boolean\n stripHostIdentity?: boolean\n customPrompt?: string\n}\n\n/** Per-preset fusion state reported by the host half. */\nexport interface UnrestrictedModeState {\n state: 'off' | 'active' | 'failed'\n issues: string[]\n}\n\n/** Host status endpoint payload. */\nexport interface UnrestrictedStatus {\n enabled: boolean\n stripHostIdentity?: boolean\n /** Persisted custom execution-mode prompt override, empty when using built-in default. */\n customPrompt?: string\n /** Built-in default execution-mode prompt text owned by the host half. */\n defaultPrompt?: string\n /** Whether a non-default custom execution-mode prompt is currently active. */\n isCustomPrompt?: boolean\n /** Current plugin version reported by the host half. */\n version?: string\n modes: Record<string, UnrestrictedModeState>\n}\n\n/** Deploy preview for one preset: what switching on would actually assemble. */\nexport interface UnrestrictedPreview {\n presetId: string\n available: boolean\n /** `live` = bytes a live agent received; `standing` = preset scope, no agent bound. */\n source?: 'live' | 'standing'\n /** Fused prompt text; present when available. */\n text?: string\n bytes?: number\n lines?: number\n /** Structured error code when unavailable. */\n errorCode?: string\n /** Diagnostic reason when unavailable. */\n reason?: string\n}\n\n/** One fetched preview, keyed by preset, plus its in-flight/error state. */\nexport interface UnrestrictedPreviewEntry {\n status: 'loading' | 'ready' | 'failed'\n preview?: UnrestrictedPreview\n errorCode?: string\n message?: string\n}\n\n/** Full view snapshot the card subscribes to. */\nexport interface UnrestrictedViewSnapshot {\n /** Persisted toggle; false until the settings scope first syncs. */\n enabled: boolean\n /** Persisted host-brand stripping toggle; false until synced. */\n stripHostIdentity: boolean\n /** Persisted custom prompt override (LF-normalized); empty when using built-in default. */\n customPrompt: string\n /** Built-in default execution-mode prompt text returned by the host status RPC. */\n defaultPrompt: string\n /** Whether a custom execution-mode prompt is currently overriding the default. */\n isCustomPrompt: boolean\n /** Whether the Host document accepts writes. */\n writable: boolean\n /** Settings scope sync state. */\n settingsStatus: 'loading' | 'ready' | 'unavailable'\n /** Live host status; null until the first RPC answer. */\n status: UnrestrictedStatus | null\n /** presetId -> fetched deploy preview. */\n previews: Record<string, UnrestrictedPreviewEntry>\n /** Whether a settings write or status refresh is in flight. */\n busy: boolean\n /** Last transport/business failure, if any. */\n message?: string\n}\n\n/** Minimal RPC wire shape (structural copy of the host RpcResult). */\ntype RpcResult<T> = { ok: true; value: T } | { ok: false; error: { code: string; message: string } }\n\n/** Minimal observable contract consumed by the slot renderer's hook binding. */\nexport interface UnrestrictedViewSource {\n getSnapshot(): UnrestrictedViewSnapshot\n subscribe(listener: () => void): () => void\n}\n\n/** Inject face handed to the card at registration. */\nexport interface UnrestrictedCardInjected {\n hooks: {\n /** Reactive card view. */\n view: UnrestrictedViewSource\n }\n /** Persist the toggle. */\n setEnabled: (enabled: boolean) => Promise<void>\n /** Persist whether host identity branding is stripped from prompts. */\n setStripHostIdentity: (strip: boolean) => Promise<void>\n /** Persist a user-edited execution-mode prompt (clears override when equal to default). */\n setCustomPrompt: (prompt: string) => Promise<boolean>\n /** Clear any custom prompt override and restore the built-in default. */\n resetCustomPrompt: () => Promise<boolean>\n /** Re-validate runtime state and refresh. */\n recheck: () => Promise<void>\n /** Re-read host status and invalidate cached previews. */\n refresh: () => Promise<void>\n Line truncated
+1 -1
View File
@@ -1,6 +1,6 @@
{
"meta": {
"title": "Unrestricted mode",
"description": "Toggle unrestricted mode and inspect preset status and previews."
"description": "Toggle unrestricted mode, customize the execution prompt, and inspect preset previews."
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"meta": {
"title": "破限模式",
"description": "切换破限模式,查看各预设状态与提示词预览。"
"description": "切换破限模式,自由编辑破限提示词,查看各预设状态与提示词预览。"
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "dsh-unrestricted",
"version": "0.2.16",
"version": "0.2.17",
"engines": {
"dsh": ">=0.2.0-rc.2 <0.2.4-0"
},
+189 -2
View File
@@ -1,9 +1,10 @@
/**
* The unrestricted settings view:
* - Master toggle card with native Switch, status Tag, and scope boundary notes
* - Editable execution-mode prompt card with save, discard, and reset-to-default
* - Per-preset coverage list with StateDot, Tag, preview drawer, and one-click copy
*/
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import {
Button,
StateDot,
@@ -99,6 +100,11 @@ function localizePreviewError(
: t('errorPreviewFailed')
}
/** UTF-8 byte length of a string in browser environments. */
function utf8ByteLength(text: string): number {
return new TextEncoder().encode(text).length
}
/**
* Render the unrestricted configuration cards.
*/
@@ -108,8 +114,34 @@ export function UnrestrictedCard(props: UnrestrictedCardProps) {
const status = view.status
const [openPreview, setOpenPreview] = useState<string | null>(null)
const [copiedPreset, setCopiedPreset] = useState<string | null>(null)
const [editorOpen, setEditorOpen] = useState(false)
const [draft, setDraft] = useState('')
const [hasLocalEdit, setHasLocalEdit] = useState(false)
const [promptFeedback, setPromptFeedback] = useState<'saved' | 'reset' | null>(null)
const feedbackTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const openEntry = openPreview === null ? undefined : view.previews[openPreview]
const effectivePrompt = view.customPrompt.trim() !== '' ? view.customPrompt : view.defaultPrompt
const normalizedDraft = draft.replace(/\r\n?/g, '\n')
const isDirty = hasLocalEdit && normalizedDraft !== effectivePrompt
const isDraftEmpty = normalizedDraft.trim() === ''
const editorReady = effectivePrompt !== '' || view.status !== null
const controlsEditable = view.writable && view.settingsStatus === 'ready' && !view.busy
const canSave = controlsEditable && isDirty && !isDraftEmpty
const canReset = controlsEditable
&& (view.isCustomPrompt || (view.defaultPrompt !== '' && normalizedDraft !== view.defaultPrompt))
// Keep the editor draft synced with the active prompt until the user starts editing.
useEffect(() => {
if (!hasLocalEdit) {
setDraft(effectivePrompt)
}
}, [effectivePrompt, hasLocalEdit])
useEffect(() => () => {
if (feedbackTimerRef.current !== null) clearTimeout(feedbackTimerRef.current)
}, [])
// When a refresh/toggle invalidates the preview map while a preview drawer
// is open, automatically reload that preset's preview.
useEffect(() => {
@@ -118,6 +150,41 @@ export function UnrestrictedCard(props: UnrestrictedCardProps) {
}
}, [openPreview, openEntry, loadPreview])
function showPromptFeedback(kind: 'saved' | 'reset'): void {
setPromptFeedback(kind)
if (feedbackTimerRef.current !== null) clearTimeout(feedbackTimerRef.current)
feedbackTimerRef.current = setTimeout(() => {
setPromptFeedback(null)
feedbackTimerRef.current = null
}, 2600)
}
async function handleSavePrompt(): Promise<void> {
if (!canSave) return
const saved = await props.setCustomPrompt(draft)
if (!saved) return
const matchedDefault = view.defaultPrompt !== '' && normalizedDraft === view.defaultPrompt
setHasLocalEdit(false)
showPromptFeedback(matchedDefault ? 'reset' : 'saved')
}
function handleDiscardPrompt(): void {
setDraft(effectivePrompt)
setHasLocalEdit(false)
setPromptFeedback(null)
}
async function handleResetPrompt(): Promise<void> {
if (!canReset) return
if (view.isCustomPrompt) {
const cleared = await props.resetCustomPrompt()
if (!cleared) return
}
setDraft(view.defaultPrompt)
setHasLocalEdit(false)
showPromptFeedback('reset')
}
const hasFailedMode = status !== null
&& Object.values(status.modes).some(mode => mode.state === 'failed')
const summaryKey: UnrestrictedLocaleKey = view.settingsStatus === 'loading'
@@ -176,6 +243,9 @@ export function UnrestrictedCard(props: UnrestrictedCardProps) {
{view.settingsStatus === 'ready' && view.stripHostIdentity && (
<Tag tone="outline">{t('stripHostBadge')}</Tag>
)}
{view.settingsStatus === 'ready' && view.isCustomPrompt && (
<Tag tone="info">{t('customPromptBadge')}</Tag>
)}
</div>
<div className="dsh-unrestricted-headerControls">
<span className="dsh-unrestricted-switchLabel">{t('toggle')}</span>
@@ -214,7 +284,124 @@ export function UnrestrictedCard(props: UnrestrictedCardProps) {
)}
</section>
{/* Card 2: Mode Coverage & Prompt Previews */}
{/* Card 2: Editable Execution Prompt */}
<section className="dsh-unrestricted-card" aria-labelledby="dsh-unrestricted-prompt-title">
<div className="dsh-unrestricted-header">
<div className="dsh-unrestricted-headerTitle">
<h4 id="dsh-unrestricted-prompt-title" className="dsh-unrestricted-subtitle">
{t('promptEditorTitle')}
</h4>
<Tag tone={view.isCustomPrompt ? 'info' : 'neutral'}>
{t(view.isCustomPrompt ? 'promptStateCustom' : 'promptStateDefault')}
</Tag>
{isDirty && (
<Tag tone="warning">{t('promptStateUnsaved')}</Tag>
)}
</div>
<div className="dsh-unrestricted-headerControls">
{view.isCustomPrompt && !editorOpen && (
<Button
variant="ghost"
size="sm"
disabled={!controlsEditable}
onClick={() => { void handleResetPrompt() }}
>
{t('promptEditorReset')}
</Button>
)}
<Button
variant={editorOpen ? 'toolbar' : 'outline'}
size="sm"
onClick={() => { setEditorOpen(open => !open) }}
>
{t(editorOpen ? 'closePromptEditor' : 'openPromptEditor')}
</Button>
</div>
</div>
<p className="dsh-unrestricted-note">{t('promptEditorDesc')}</p>
{editorOpen && (
<div className="dsh-unrestricted-editor">
{!editorReady ? (
<p className="dsh-unrestricted-note" role="status">{t('promptEditorLoading')}</p>
) : (
<>
<div className="dsh-unrestricted-previewHeader">
<p className="dsh-unrestricted-previewMeta">
{draft === '' ? 0 : draft.split('\n').length} {t('previewSize')}
{` · ${draft.length} ${t('promptEditorChars')} · ${fileSizeText(utf8ByteLength(draft))}`}
</p>
<span className="dsh-unrestricted-previewMeta">{t('promptEditorShortcutHint')}</span>
</div>
<textarea
className="dsh-unrestricted-editorInput"
aria-label={t('promptEditorTitle')}
placeholder={t('promptEditorPlaceholder')}
spellCheck={false}
value={draft}
disabled={!controlsEditable}
onChange={(event) => {
setDraft(event.target.value)
setHasLocalEdit(true)
setPromptFeedback(null)
}}
onKeyDown={(event) => {
if ((event.ctrlKey || event.metaKey) && event.key === 'Enter' && canSave) {
event.preventDefault()
void handleSavePrompt()
}
}}
/>
<div className="dsh-unrestricted-editorFooter">
<p
className="dsh-unrestricted-editorStatus"
data-tone={isDraftEmpty ? 'warning' : promptFeedback !== null ? 'success' : undefined}
role="status"
>
{isDraftEmpty
? t('promptEditorEmptyHint')
: promptFeedback === 'saved'
? t('promptEditorSaved')
: promptFeedback === 'reset'
? t('promptEditorResetDone')
: ''}
</p>
<div className="dsh-unrestricted-headerControls">
{isDirty && (
<Button
variant="ghost"
size="sm"
disabled={view.busy}
onClick={handleDiscardPrompt}
>
{t('promptEditorDiscard')}
</Button>
)}
<Button
variant="outline"
size="sm"
disabled={!canReset}
onClick={() => { void handleResetPrompt() }}
>
{t('promptEditorReset')}
</Button>
<Button
variant="primary"
size="sm"
disabled={!canSave}
onClick={() => { void handleSavePrompt() }}
>
{t('promptEditorSave')}
</Button>
</div>
</div>
</>
)}
</div>
)}
</section>
{/* Card 3: Mode Coverage & Prompt Previews */}
<section className="dsh-unrestricted-card" aria-labelledby="dsh-unrestricted-modes-title">
<div className="dsh-unrestricted-header">
<div className="dsh-unrestricted-headerTitle">
+79 -9
View File
@@ -13,6 +13,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
export interface UnrestrictedSettings {
enabled?: boolean
stripHostIdentity?: boolean
customPrompt?: string
}
/** Per-preset fusion state reported by the host half. */
@@ -25,6 +26,12 @@ export interface UnrestrictedModeState {
export interface UnrestrictedStatus {
enabled: boolean
stripHostIdentity?: boolean
/** Persisted custom execution-mode prompt override, empty when using built-in default. */
customPrompt?: string
/** Built-in default execution-mode prompt text owned by the host half. */
defaultPrompt?: string
/** Whether a non-default custom execution-mode prompt is currently active. */
isCustomPrompt?: boolean
/** Current plugin version reported by the host half. */
version?: string
modes: Record<string, UnrestrictedModeState>
@@ -60,6 +67,12 @@ export interface UnrestrictedViewSnapshot {
enabled: boolean
/** Persisted host-brand stripping toggle; false until synced. */
stripHostIdentity: boolean
/** Persisted custom prompt override (LF-normalized); empty when using built-in default. */
customPrompt: string
/** Built-in default execution-mode prompt text returned by the host status RPC. */
defaultPrompt: string
/** Whether a custom execution-mode prompt is currently overriding the default. */
isCustomPrompt: boolean
/** Whether the Host document accepts writes. */
writable: boolean
/** Settings scope sync state. */
@@ -93,6 +106,10 @@ export interface UnrestrictedCardInjected {
setEnabled: (enabled: boolean) => Promise<void>
/** Persist whether host identity branding is stripped from prompts. */
setStripHostIdentity: (strip: boolean) => Promise<void>
/** Persist a user-edited execution-mode prompt (clears override when equal to default). */
setCustomPrompt: (prompt: string) => Promise<boolean>
/** Clear any custom prompt override and restore the built-in default. */
resetCustomPrompt: () => Promise<boolean>
/** Re-validate runtime state and refresh. */
recheck: () => Promise<void>
/** Re-read host status and invalidate cached previews. */
@@ -105,6 +122,11 @@ const RPC_CHANNEL = '/api'
const RPC_NAMESPACE = 'dsh-unrestricted'
const SETTINGS_NS = 'unrestricted'
/** Normalize line endings so YAML/browser values compare identically across OSes. */
function normalizePromptText(value: unknown): string {
return typeof value === 'string' ? value.replace(/\r\n?/g, '\n') : ''
}
/** Human-readable error text for the banner. */
function messageOf(error: unknown): string {
return error instanceof Error ? error.message : String(error)
@@ -122,6 +144,9 @@ export function createUnrestrictedController(ctx: Context) {
let snapshot: UnrestrictedViewSnapshot = {
enabled: false,
stripHostIdentity: false,
customPrompt: '',
defaultPrompt: '',
isCustomPrompt: false,
writable: false,
settingsStatus: 'loading',
status: null,
@@ -145,12 +170,22 @@ export function createUnrestrictedController(ctx: Context) {
const settingsSnapshot = settings.getSnapshot()
const enabled = settingsSnapshot.value?.enabled === true
const stripHostIdentity = settingsSnapshot.value?.stripHostIdentity === true
if (enabled !== snapshot.enabled || stripHostIdentity !== snapshot.stripHostIdentity) {
const customPrompt = normalizePromptText(settingsSnapshot.value?.customPrompt)
const defaultPrompt = normalizePromptText(snapshot.status?.defaultPrompt)
const isCustomPrompt = customPrompt.trim() !== '' && (defaultPrompt === '' || customPrompt !== defaultPrompt)
if (
enabled !== snapshot.enabled
|| stripHostIdentity !== snapshot.stripHostIdentity
|| customPrompt !== snapshot.customPrompt
) {
invalidatePreviews()
}
snapshot = {
enabled,
stripHostIdentity,
customPrompt,
defaultPrompt,
isCustomPrompt,
writable: settingsSnapshot.writable,
settingsStatus: settingsSnapshot.status,
status: snapshot.status,
@@ -210,26 +245,59 @@ export function createUnrestrictedController(ctx: Context) {
return readStatus('status', clearPreviews)
}
function updateSetting<K extends keyof UnrestrictedSettings>(
async function updateSetting<K extends keyof UnrestrictedSettings>(
field: K,
value: NonNullable<UnrestrictedSettings[K]>,
): Promise<void> {
return whileBusy(async () => {
): Promise<boolean> {
let accepted = false
await whileBusy(async () => {
try {
await settings.set(field, value)
accepted = (await settings.set(field, value)) !== false
await refresh(true)
} catch (error) {
snapshot = { ...snapshot, message: messageOf(error) }
accepted = false
}
})
return accepted
}
function setEnabled(enabled: boolean): Promise<void> {
return updateSetting('enabled', enabled)
async function clearCustomPrompt(): Promise<boolean> {
let accepted = false
await whileBusy(async () => {
try {
const result = typeof settings.unset === 'function'
? await settings.unset('customPrompt')
: await settings.set('customPrompt', '')
accepted = result !== false
await refresh(true)
} catch (error) {
snapshot = { ...snapshot, message: messageOf(error) }
accepted = false
}
})
return accepted
}
function setStripHostIdentity(strip: boolean): Promise<void> {
return updateSetting('stripHostIdentity', strip)
async function setEnabled(enabled: boolean): Promise<void> {
await updateSetting('enabled', enabled)
}
async function setStripHostIdentity(strip: boolean): Promise<void> {
await updateSetting('stripHostIdentity', strip)
}
function setCustomPrompt(prompt: string): Promise<boolean> {
const normalized = normalizePromptText(prompt)
const defaultPrompt = normalizePromptText(snapshot.status?.defaultPrompt)
if (normalized.trim() === '' || (defaultPrompt !== '' && normalized === defaultPrompt)) {
return clearCustomPrompt()
}
return updateSetting('customPrompt', normalized)
}
function resetCustomPrompt(): Promise<boolean> {
return clearCustomPrompt()
}
function recheck(): Promise<void> {
@@ -290,6 +358,8 @@ export function createUnrestrictedController(ctx: Context) {
hooks: { view },
setEnabled,
setStripHostIdentity,
setCustomPrompt,
resetCustomPrompt,
recheck,
refresh: () => refresh(true),
loadPreview,
+36
View File
@@ -11,9 +11,27 @@ export const zh = {
description: '开启后,各运行模式与委派子代理的系统提示词将自动融合无限制本地执行契约;关闭即恢复 DSH 原版提示词。切换从下一次请求生效,不改动正在执行的请求、工具定义、权限配置与会话历史。',
toggle: '启用破限模式',
stripHostBadge: '已隐去宿主标识',
customPromptBadge: '已自定义提示词',
stripHostTitle: '隐藏宿主品牌标识',
stripHostDesc: '移除系统提示词与运行时上下文中的 DeepSeek Harness / DSH 身份段落及开发界面路径,避免第三方路由(适用于 Google Antigravity 反重力反代、Google AI Studio PG 渠道等)因检测到客户端特征而返回 429 拦截(可独立于破限开关生效)。',
scopeNote: '仅作用于由 DSH 组装的系统提示词;模型平台或外部网关的远端策略不在本插件覆盖范围内。',
promptEditorTitle: '破限提示词',
promptEditorDesc: '默认内置英文破限契约;支持自由删改敏感关键词或替换为自定义规则,保存后从下一次请求生效。',
promptStateDefault: '内置默认',
promptStateCustom: '已自定义',
promptStateUnsaved: '未保存',
openPromptEditor: '编辑提示词',
closePromptEditor: '收起编辑',
promptEditorLoading: '正在加载内置提示词内容…',
promptEditorPlaceholder: '输入要注入到 unrestricted:execution-mode 段落的提示词内容…',
promptEditorChars: '字符',
promptEditorShortcutHint: 'Ctrl/Cmd + Enter 保存',
promptEditorEmptyHint: '提示词不能为空;如需使用内置内容,请点击「恢复默认」。',
promptEditorSaved: '已保存,下一次请求生效',
promptEditorResetDone: '已恢复内置默认提示词',
promptEditorSave: '保存更改',
promptEditorDiscard: '放弃更改',
promptEditorReset: '恢复默认',
statusTitle: '模式覆盖与提示词预览',
statusSubtitle: '覆盖全部 4 种预设及委派子代理,可随时展开核对或复制融合后的完整提示词。',
modeStandard: 'Standard 标准模式',
@@ -66,9 +84,27 @@ export const en = {
description: 'When enabled, system prompts across all modes and delegated subagents are fused with the unrestricted local execution contract; disabling restores the stock DSH prompt immediately. Takes effect from the next request without altering in-flight turns, tool schemas, permissions, or session history.',
toggle: 'Enable unrestricted mode',
stripHostBadge: 'Host identity stripped',
customPromptBadge: 'Custom prompt',
stripHostTitle: 'Strip host brand identity',
stripHostDesc: 'Remove DeepSeek Harness / DSH identity sections and Web GUI checkout context from assembled prompts to prevent HTTP 429 client-fingerprinting blocks on third-party routes such as Google Antigravity proxies and Google AI Studio PG channels (works independently of the main toggle).',
scopeNote: 'Applies only to system prompts assembled by DSH; upstream model provider policies outside the prompt are out of scope.',
promptEditorTitle: 'Execution Prompt',
promptEditorDesc: 'Built-in English contract tuned for reliability. Freely edit keywords or replace with custom rules; saved changes apply on the next request.',
promptStateDefault: 'Default',
promptStateCustom: 'Customized',
promptStateUnsaved: 'Unsaved',
openPromptEditor: 'Edit prompt',
closePromptEditor: 'Hide editor',
promptEditorLoading: 'Loading built-in prompt…',
promptEditorPlaceholder: 'Enter the prompt text injected into the unrestricted:execution-mode section…',
promptEditorChars: 'chars',
promptEditorShortcutHint: 'Ctrl/Cmd + Enter to save',
promptEditorEmptyHint: 'Prompt cannot be empty. Click "Reset to default" to restore the built-in prompt.',
promptEditorSaved: 'Saved — applies on next request',
promptEditorResetDone: 'Restored built-in default prompt',
promptEditorSave: 'Save changes',
promptEditorDiscard: 'Discard',
promptEditorReset: 'Reset to default',
statusTitle: 'Mode Coverage & Prompt Preview',
statusSubtitle: 'Covers all 4 built-in presets and delegated subagents. Expand any mode to inspect or copy the full fused prompt.',
modeStandard: 'Standard',
+61
View File
@@ -246,6 +246,67 @@ const CSS = `
overflow-wrap: anywhere;
}
.dsh-unrestricted-editor {
display: flex;
flex-direction: column;
gap: 8px;
padding-top: 10px;
border-top: 1px solid var(--dsw-alias-border-l3, var(--dsw-alias-border-l2));
}
.dsh-unrestricted-editorInput {
width: 100%;
min-height: 240px;
max-height: 520px;
box-sizing: border-box;
margin: 0;
border: 1px solid var(--dsw-alias-border-l2);
border-radius: var(--dsw-radius-md, 8px);
padding: 10px 12px;
background: var(--dsw-alias-bg-layer-1, var(--dsw-alias-bg-layer-2));
color: var(--dsw-alias-label-primary);
font-family: var(--ds-font-family-code, ui-monospace, SFMono-Regular, Menlo, monospace);
font-size: 12px;
line-height: 18px;
resize: vertical;
outline: none;
transition: border-color 120ms ease;
}
.dsh-unrestricted-editorInput:focus {
border-color: var(--dsw-alias-state-business-primary, var(--dsw-alias-border-l1));
}
.dsh-unrestricted-editorInput:disabled {
opacity: 0.65;
cursor: not-allowed;
}
.dsh-unrestricted-editorFooter {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 8px 12px;
}
.dsh-unrestricted-editorStatus {
flex: 1;
min-width: 160px;
margin: 0;
font-size: 12px;
line-height: 18px;
color: var(--dsw-alias-label-tertiary);
}
.dsh-unrestricted-editorStatus[data-tone='success'] {
color: var(--dsw-alias-state-success-primary);
}
.dsh-unrestricted-editorStatus[data-tone='warning'] {
color: var(--dsw-alias-state-warning-primary, var(--dsw-alias-state-error-primary));
}
@media (max-width: 640px) {
.dsh-unrestricted-card {
padding: 14px;
+37 -7
View File
@@ -26,11 +26,14 @@ import z from '@deepseek-ai/schemastery'
import { renderPrompt } from '@deepseek-ai/dsh-system-prompt'
import {
ANCHORS,
EXECUTION_MODE_BLOCK,
PRESETS,
PRESET_RULES,
fuseSections,
fusedMinimalPrompt,
normalizePromptText,
renderPreview,
resolveExecutionModeBlock,
stripHostIdentityFromAssembly,
} from './rules.js'
import { registerRpcRoutes } from './rpc.js'
@@ -39,7 +42,7 @@ import { registerRpcRoutes } from './rpc.js'
export const name = 'dsh-unrestricted'
/** Current plugin package version. */
export const PLUGIN_VERSION = '0.2.16'
export const PLUGIN_VERSION = '0.2.17'
/** Services required by this plugin (all base-backed profiles provide these). */
export const inject = ['settings', 'systemPrompt', 'loader']
@@ -47,8 +50,9 @@ export const inject = ['settings', 'systemPrompt', 'loader']
export const Config = z.object({
enabled: z.boolean().default(false),
stripHostIdentity: z.boolean().default(false),
customPrompt: z.string().default(''),
extraPresets: z.array(z.string()).default([]),
}).default({ enabled: false, stripHostIdentity: false, extraPresets: [] }).volatile()
}).default({ enabled: false, stripHostIdentity: false, customPrompt: '', extraPresets: [] }).volatile()
/** Human-readable error text for diagnostics and RPC error branches. */
function messageOf(error) {
@@ -68,10 +72,14 @@ export function apply(ctx, config) {
ctx.effect(() => ctx.settings.configure({ auto: false }, ctx.fiber))
const initialConfig = config.get()
const initialCustomPrompt = normalizePromptText(initialConfig.customPrompt)
const initialPromptBlock = resolveExecutionModeBlock(initialCustomPrompt)
const state = {
active: true,
enabled: Boolean(initialConfig.enabled),
stripHostIdentity: Boolean(initialConfig.stripHostIdentity),
customPrompt: initialCustomPrompt,
promptBlock: initialPromptBlock,
extraPresets: new Set(initialConfig.extraPresets ?? []),
/** presetId -> issue codes observed on live assemblies. */
runtime: new Map(),
@@ -83,8 +91,12 @@ export function apply(ctx, config) {
probingMinimal: new WeakSet(),
/** Agents already disposed, guarding async shadow probes against late writes. */
disposed: new WeakSet(),
/** Precomputed fused minimal prompt. */
fusedMinimal: fusedMinimalPrompt(),
/** Precomputed fused minimal prompt for the active prompt block. */
fusedMinimal: fusedMinimalPrompt('', initialPromptBlock),
}
function isCustomPromptActive() {
return state.customPrompt.trim() !== '' && state.promptBlock !== EXECUTION_MODE_BLOCK
}
function isSupportedPreset(presetId) {
@@ -191,12 +203,13 @@ export function apply(ctx, config) {
name: 'deployment:persona-prefix',
order: 0,
complete: true,
interpolate: false,
text: (context) => {
const hasStructured = context?.agent?.ctx?.tools
?.schemas?.(context.agent)
?.some(tool => tool.name === 'structured_output') === true
return hasStructured
? fusedMinimalPrompt(ANCHORS.structuredOutputFull)
? fusedMinimalPrompt(ANCHORS.structuredOutputFull, state.promptBlock)
: state.fusedMinimal
},
})
@@ -282,6 +295,9 @@ export function apply(ctx, config) {
return {
enabled: state.enabled,
stripHostIdentity: state.stripHostIdentity,
customPrompt: state.customPrompt,
defaultPrompt: EXECUTION_MODE_BLOCK,
isCustomPrompt: isCustomPromptActive(),
version: PLUGIN_VERSION,
modes,
}
@@ -336,11 +352,17 @@ export function apply(ctx, config) {
if (presetId === 'minimal') {
previewAssembly = {
...assembly,
sections: [{ name: 'deployment:persona-prefix', text: fusedMinimalPrompt() }],
sections: [{
name: 'deployment:persona-prefix',
order: 0,
interpolate: false,
text: fusedMinimalPrompt('', state.promptBlock),
}],
}
} else {
const fused = fuseSections(assembly.sections, presetId, {
allowDynamicPreset: state.extraPresets.has(presetId),
customPrompt: state.promptBlock,
})
if (fused.issues !== undefined) {
return {
@@ -420,7 +442,10 @@ export function apply(ctx, config) {
}
}
if (state.customMinimal.has(agent)) {
const fused = fuseSections(current.sections, 'minimal', { isSubagent: true })
const fused = fuseSections(current.sections, 'minimal', {
isSubagent: true,
customPrompt: state.promptBlock,
})
if (fused.issues !== undefined) {
state.runtime.set('minimal', fused.issues)
return state.stripHostIdentity ? stripHostIdentityFromAssembly(current) : current
@@ -443,6 +468,7 @@ export function apply(ctx, config) {
const fused = fuseSections(current.sections, presetId, {
isSubagent,
allowDynamicPreset: state.extraPresets.has(presetId),
customPrompt: state.promptBlock,
})
if (fused.issues !== undefined) {
state.runtime.set(presetId, fused.issues)
@@ -481,7 +507,11 @@ export function apply(ctx, config) {
const unwatch = ctx.on('loader/volatile-update', () => {
const nextConfig = config.get()
const enabled = Boolean(nextConfig.enabled)
const nextCustomPrompt = normalizePromptText(nextConfig.customPrompt)
state.stripHostIdentity = Boolean(nextConfig.stripHostIdentity)
state.customPrompt = nextCustomPrompt
state.promptBlock = resolveExecutionModeBlock(nextCustomPrompt)
state.fusedMinimal = fusedMinimalPrompt('', state.promptBlock)
state.extraPresets = new Set(nextConfig.extraPresets ?? [])
if (enabled === state.enabled) return
state.enabled = enabled
+28 -4
View File
@@ -101,14 +101,36 @@ function appendOnce(text, suffix) {
return text.endsWith(suffix) ? text : text + suffix
}
/**
* Normalize line endings so YAML and browser edits compare identically across platforms.
* @param {unknown} text
* @returns {string}
*/
export function normalizePromptText(text) {
return typeof text === 'string' ? text.replace(/\r\n?/g, '\n') : ''
}
/**
* Resolve the effective execution-mode block from an optional user override.
* Blank or whitespace-only overrides fall back to the built-in default block.
* @param {unknown} [customPrompt]
* @returns {string}
*/
export function resolveExecutionModeBlock(customPrompt) {
const normalized = normalizePromptText(customPrompt)
return normalized.trim() === '' ? EXECUTION_MODE_BLOCK : normalized
}
/**
* The fused minimal prompt: the persona sentence, the pointer, the mode
* section, and optional structured-output guidance when a structured subagent
* runs under minimal.
* @param {string} [structuredText] - optional original `tool:structured_output` section text.
* @param {string} [customPrompt] - optional user-edited execution-mode block.
*/
export function fusedMinimalPrompt(structuredText = '') {
const base = ANCHORS.personaMinimal + PERSONA_POINTER + '\n\n' + EXECUTION_MODE_BLOCK
export function fusedMinimalPrompt(structuredText = '', customPrompt = '') {
const block = resolveExecutionModeBlock(customPrompt)
const base = ANCHORS.personaMinimal + PERSONA_POINTER + '\n\n' + block
const trimmed = structuredText.trim()
if (trimmed === '') return base
return base + '\n\n' + appendOnce(trimmed, STRUCTURED_OUTPUT_NOTE)
@@ -206,16 +228,18 @@ export function stripHostIdentityFromAssembly(assembly) {
* @param presetId - the composed preset id (must be in PRESETS or enabled via allowDynamicPreset).
* @param options.isSubagent - tolerate an absent persona on delegated subagents.
* @param options.allowDynamicPreset - allow fusing presets outside PRESET_RULES.
* @param options.customPrompt - optional user-edited execution-mode block.
* @returns `{ sections }` with the fusion applied, or `{ issues }` with a
* structured error code when the preset is unsupported or lacks a persona.
*/
export function fuseSections(sections, presetId, { isSubagent = false, allowDynamicPreset = false } = {}) {
export function fuseSections(sections, presetId, { isSubagent = false, allowDynamicPreset = false, customPrompt = '' } = {}) {
const rules = PRESET_RULES[presetId] ?? (allowDynamicPreset ? { plan: true, ptcOnly: true } : undefined)
if (rules === undefined) return { issues: ['unsupported-preset'] }
if (sections.some(section => section.name === BLOCK_SECTION)) {
return { sections }
}
const blockText = resolveExecutionModeBlock(customPrompt)
const byName = new Map(sections.map(section => [section.name, section]))
const persona = byName.get('deployment:persona-prefix')
let fusedPersona = undefined
@@ -254,6 +278,6 @@ export function fuseSections(sections, presetId, { isSubagent = false, allowDyna
const insertAt = personaIndex >= 0 ? personaIndex + 1 : (identityIndex >= 0 ? identityIndex + 1 : 0)
const anchor = personaIndex >= 0 ? fused[personaIndex] : (identityIndex >= 0 ? fused[identityIndex] : undefined)
const blockOrder = typeof anchor?.order === 'number' && Number.isFinite(anchor.order) ? anchor.order + 1 : 101
fused.splice(insertAt, 0, { name: BLOCK_SECTION, order: blockOrder, text: EXECUTION_MODE_BLOCK })
fused.splice(insertAt, 0, { name: BLOCK_SECTION, order: blockOrder, interpolate: false, text: blockText })
return { sections: fused }
}
+66 -2
View File
@@ -3,10 +3,17 @@ import test from 'node:test'
import { createUnrestrictedController } from '../src/client/controller.ts'
const settle = () => new Promise(setImmediate)
const status = (version, enabled = true) => ({ enabled, version, modes: {} })
const DEFAULT_PROMPT = '## Default execution contract'
const status = (version, enabled = true, extra = {}) => ({
enabled,
defaultPrompt: DEFAULT_PROMPT,
version,
modes: {},
...extra,
})
/** 保留真实控制器,仅控制设置提交、配置事件和 RPC 的完成时序。 */
async function fixture() {
async function fixture({ supportsUnset = true } = {}) {
let value = { enabled: true }
const subscribers = new Set()
const events = new Map()
@@ -15,6 +22,7 @@ async function fixture() {
recheck: [],
preview: [],
write: [],
unset: [],
}
function defer(endpoint, payload) {
return new Promise((resolve, reject) => pending[endpoint].push({ payload, resolve, reject }))
@@ -26,6 +34,7 @@ async function fixture() {
return () => subscribers.delete(listener)
},
set: (field, next) => defer('write', { field, next }),
...(supportsUnset ? { unset: field => defer('unset', { field }) } : {}),
}
const ctx = {
get: () => ({
@@ -174,3 +183,58 @@ test('切换隐藏宿主品牌标识立即使旧预览失效并在提交后同
assert.equal(f.view().busy, false)
assert.equal(f.view().status.stripHostIdentity, true)
})
test('保存与重置自定义提示词:规范换行、清理预览并在恢复默认时卸载字段', async () => {
const f = await fixture()
assert.equal(f.view().defaultPrompt, DEFAULT_PROMPT)
assert.equal(f.view().customPrompt, '')
assert.equal(f.view().isCustomPrompt, false)
const preview = f.face.loadPreview('standard')
f.answer(f.take('preview'), { available: true, text: 'default preview' })
await preview
assert.equal(f.view().previews.standard.preview.text, 'default preview')
const saving = f.face.setCustomPrompt('## Custom\r\nLine 2')
const writeRequest = f.take('write')
assert.deepEqual(writeRequest.payload, { field: 'customPrompt', next: '## Custom\nLine 2' })
f.commitSettings({ customPrompt: '## Custom\nLine 2' })
assert.equal(f.view().customPrompt, '## Custom\nLine 2')
assert.equal(f.view().isCustomPrompt, true)
assert.equal(f.view().previews.standard, undefined)
f.answer(f.take('status'), status('0.2.17', true, { customPrompt: '## Custom\nLine 2', isCustomPrompt: true }))
writeRequest.resolve(true)
await settle()
f.answer(f.take('status'), status('0.2.17', true, { customPrompt: '## Custom\nLine 2', isCustomPrompt: true }))
assert.equal(await saving, true)
assert.equal(f.view().busy, false)
// 保存与内置默认一致的内容时直接 unset,恢复默认状态。
const matchingDefault = f.face.setCustomPrompt(`${DEFAULT_PROMPT}\r`.replace('\r', ''))
const unsetRequest = f.take('unset')
assert.deepEqual(unsetRequest.payload, { field: 'customPrompt' })
f.commitSettings({ customPrompt: '' })
assert.equal(f.view().isCustomPrompt, false)
f.answer(f.take('status'), status('0.2.17', true, { customPrompt: '', isCustomPrompt: false }))
unsetRequest.resolve(true)
await settle()
f.answer(f.take('status'), status('0.2.17', true, { customPrompt: '', isCustomPrompt: false }))
assert.equal(await matchingDefault, true)
})
test('缺少 settings.unset 时重置自定义提示词回退为空串,写入拒绝或异常返回 false', async () => {
const f = await fixture({ supportsUnset: false })
const resetting = f.face.resetCustomPrompt()
const writeRequest = f.take('write')
assert.deepEqual(writeRequest.payload, { field: 'customPrompt', next: '' })
writeRequest.resolve(false)
await settle()
f.answer(f.take('status'), status('0.2.17', true))
assert.equal(await resetting, false)
const failing = f.face.setCustomPrompt('## Fail case')
f.take('write').reject(new Error('disk full'))
assert.equal(await failing, false)
assert.equal(f.view().message, 'disk full')
})
+30 -2
View File
@@ -13,8 +13,9 @@ import assert from 'node:assert/strict'
import {
ANCHORS, BLOCK_SECTION, EXECUTION_MODE_BLOCK,
HOST_IDENTITY_CONTEXTS, HOST_IDENTITY_SECTIONS, PRESETS,
contractAdditions, fuseSections, fusedMinimalPrompt, renderPreview,
sanitizeSectionBrandText, stripHostIdentityFromAssembly,
contractAdditions, fuseSections, fusedMinimalPrompt, normalizePromptText,
renderPreview, resolveExecutionModeBlock, sanitizeSectionBrandText,
stripHostIdentityFromAssembly,
} from '../src/rules.js'
const FIXTURES = fileURLToPath(new URL('./fixtures/', import.meta.url))
@@ -455,3 +456,30 @@ test('fuseSections supports dynamic extra presets only when allowDynamicPreset i
const ptcSection = allowed.sections.find(s => s.name === 'tools:ptc-only')
assert.ok(ptcSection.text.endsWith(contractAdditions('ptc').ptcNote))
})
test('custom execution prompt overrides default block safely, normalizes line endings, and disables interpolation', async () => {
assert.equal(normalizePromptText('a\r\nb\rc'), 'a\nb\nc')
assert.equal(resolveExecutionModeBlock(''), EXECUTION_MODE_BLOCK)
assert.equal(resolveExecutionModeBlock(' \r\n\t '), EXECUTION_MODE_BLOCK)
const custom = '## Custom rules\r\nKeep {{char}} and {{user}} literal.'
assert.equal(resolveExecutionModeBlock(custom), '## Custom rules\nKeep {{char}} and {{user}} literal.')
const sections = await sectionsOf('standard')
const fused = fuseSections(sections, 'standard', { customPrompt: custom })
assert.equal(fused.issues, undefined)
const block = fused.sections.find(s => s.name === BLOCK_SECTION)
assert.ok(block)
assert.equal(block.text, '## Custom rules\nKeep {{char}} and {{user}} literal.')
assert.equal(Number.isFinite(block.order), true)
assert.equal(block.interpolate, false)
const minimalCustom = fusedMinimalPrompt('', custom)
assert.ok(minimalCustom.startsWith(ANCHORS.personaMinimal))
assert.ok(minimalCustom.includes('## Custom rules\nKeep {{char}} and {{user}} literal.'))
assert.ok(!minimalCustom.includes(EXECUTION_MODE_BLOCK))
const minimalStructured = fusedMinimalPrompt(ANCHORS.structuredOutputFull, custom)
assert.ok(minimalStructured.includes('## Custom rules\nKeep {{char}} and {{user}} literal.'))
assert.ok(minimalStructured.includes(ANCHORS.structuredOutputFull))
})
+44 -1
View File
@@ -476,8 +476,51 @@ try {
}
}
console.log('custom prompt editing')
const customBlock = '## Custom local execution mode\n\nPreserve literal {{char}} and {{user}} tokens without interpolation errors.'
await updateSettings({ enabled: true, stripHostIdentity: false, customPrompt: customBlock })
await until('custom prompt propagation', async () =>
(await assemblePrompt(await presetAgent('standard'))).text.includes(customBlock))
for (const id of ['standard', 'ptc', 'cordis', 'minimal']) {
const customAssembled = await assemblePrompt(await presetAgent(id))
check(`customPrompt applies to ${id} live assembly with literal {{...}} intact`,
customAssembled.text.includes(customBlock) && !customAssembled.text.includes(rules.EXECUTION_MODE_BLOCK))
}
const customMinimalChildPrompt = await assemblePrompt(customMinimal)
check('customPrompt applies to minimal custom subagent',
customMinimalChildPrompt.text.includes(customBlock) && !customMinimalChildPrompt.text.includes(rules.EXECUTION_MODE_BLOCK))
const customStatusRpc = await callSharedRpc('status')
check('status RPC reports customPrompt, defaultPrompt, and isCustomPrompt=true',
customStatusRpc.status === 200
&& customStatusRpc.body?.result?.ok === true
&& customStatusRpc.body.result.value?.customPrompt === customBlock
&& customStatusRpc.body.result.value?.defaultPrompt === rules.EXECUTION_MODE_BLOCK
&& customStatusRpc.body.result.value?.isCustomPrompt === true)
for (const id of ['standard', 'minimal']) {
const customPreviewRpc = await callSharedRpc('preview', { presetId: id })
check(`preview RPC for ${id} renders customPrompt`,
customPreviewRpc.status === 200
&& customPreviewRpc.body?.result?.ok === true
&& customPreviewRpc.body.result.value?.available === true
&& customPreviewRpc.body.result.value.text.includes(customBlock))
}
await updateSettings({ customPrompt: '' })
await until('custom prompt reset to default', async () =>
(await assemblePrompt(await presetAgent('standard'))).text.includes(rules.EXECUTION_MODE_BLOCK))
const minimalReset = await assemblePrompt(await presetAgent('minimal'))
check('clearing customPrompt restores default block on minimal too',
minimalReset.text === expectedMinimal)
const resetStatusRpc = await callSharedRpc('status')
check('status RPC reports isCustomPrompt=false after reset',
resetStatusRpc.status === 200
&& resetStatusRpc.body?.result?.ok === true
&& resetStatusRpc.body.result.value?.isCustomPrompt === false)
console.log('toggle off')
await updateSettings({ enabled: false, stripHostIdentity: false })
await updateSettings({ enabled: false, stripHostIdentity: false, customPrompt: '' })
for (const id of ['standard', 'ptc', 'cordis', 'minimal']) {
const off = await until(`${id} restore`, async () => {
const prompt = await assemblePrompt(await presetAgent(id))