privacy-gate: middleware settings page (#1145)

The ShyPie plugin page gets a Middleware settings tab, so privacy-gate's
ctx.options can be set from the page instead of the CLI only. Options are
grouped as Protection, Advanced inspection and Diagnostics; the Agents view
is unchanged and both share one Save.

- Lists are validated (shape, count); a malformed allowModels blocks the
  save instead of turning into an allow-everything list.
- Numbers are floored and clamped to the middleware's own numOpt ranges,
  so a save that only flips an agent keeps the limit that actually runs
  (maxDepth 500 stays 200, not the page default 40).
- An unknown binaryPolicy is reported and blocks the save.
- A save re-reads the options and reports a conflict when another surface
  changed a managed field; options outside the form are kept.
- logEveryRows has one cap, 100000, in resolvedOptions and onUsage.
- privacy-gate 0.4.1.

Run at 9bb381bf on WSL (Ubuntu 24.04, Bun 1.4.2): bun test in
packages/privacy-gate 77 pass, 0 fail; scripts/check.mjs privacy-gate
clean. Broken by hand: page.test.mjs with 7c119f16's settings.js fails
(maxDepth Expected 200, Received 40). The diff adds no network call.
Not tried: the page in a running magpie.

Co-authored-by: siml1169 <siml1169@users.noreply.github.com>
This commit is contained in:
Muyang
2026-11-14 22:28:47 +08:00
committed by GitHub
co-authored by siml1169
parent 1c3c58be56
commit 9f02ad545f
10 changed files with 634 additions and 45 deletions
+31 -2
View File
@@ -13,7 +13,7 @@
</p>
<p align="center">
<img alt="version 0.4.0" src="https://img.shields.io/badge/version-0.4.0-0D4B4E">
<img alt="version 0.4.1" src="https://img.shields.io/badge/version-0.4.1-0D4B4E">
<img alt="license MIT" src="https://img.shields.io/badge/license-MIT-F2B35A">
</p>
@@ -52,7 +52,7 @@ Codex, Cursor, Claude Code and scripts.
| **Default policy** | `binaryPolicy: fail` — binary part for a non-local model → **403** |
| **Alternative** | `binaryPolicy: guide` — withholds bytes, injects type/media/size metadata + a neutral local-tool prompt |
| **Text masking** | **Not here.** Use Magpie **Settings → Privacy** |
| **Tests** | 72 middleware cases + 4 page/policy checks through the repository harness |
| **Tests** | 72 middleware cases + 5 page/policy/settings checks through the repository harness |
## Install
@@ -147,6 +147,24 @@ read-only, and it seeds custom disabled ids so their bypass is visible. The page
warns before a request can leave without protection; saving its switches updates
the same `ctx.options` the middleware reads, with no restart.
## Middleware settings page
The **Middleware settings** tab on the plugin page edits the same `ctx.options`
that previously required `magpie plugin options`, grouped by privacy impact:
- **Protection:** `binaryPolicy`, `allowUnknownProtocol`, `allowModels`,
`localModels`, `localProviders` and the blob thresholds
- **Advanced inspection:** `scanChars`, `maxNodes`, `maxDepth`
- **Diagnostics:** `guideTools`, `logMaxLines`, `logEveryRows`
The form validates list shape and numeric ranges and preserves options it does
not own. Numeric values outside the middleware's range are displayed as the
effective clamped value (floor, then `[min, max]`) rather than being replaced by
a page default; an unknown select value is reported as invalid. A malformed
existing `allowModels` is reported and blocks saving rather than being silently
replaced by an empty, allow-everything list. Saving re-reads the current options
and reports a conflict if another surface changed a managed field.
## Configuration
All settings are one JSON object, stored as `ctx.options`:
@@ -375,6 +393,17 @@ flowchart LR
`ctx.agent` 的请求)才会跳过防护。页面会在请求可能失去保护时提示;保存开关
会更新中间件读取的同一份 `ctx.options`,无需重启。
## 中间件设置页面
插件页面的 **中间件设置** 标签可直接编辑此前只能用 `magpie plugin options`
设置的 `ctx.options`:`binaryPolicy`、`allowUnknownProtocol`、`allowModels`、
`localModels`、`localProviders`、`guideTools`、两个 blob 阈值、`scanChars`、
`maxNodes`、`maxDepth`、`logMaxLines` 和 `logEveryRows`。
表单会校验列表和数值范围,并保留页面不管理的选项。已有的 `allowModels`
如果格式错误会阻止保存,而不会被静默替换成允许全部模型的空列表。保存前会
重新读取当前配置;其他位置修改了受管字段时会提示冲突。
## 配置
所有配置都在一个 JSON 对象中,即 `ctx.options`:
+10 -3
View File
@@ -185,8 +185,15 @@ policy selection:
globs and values the UI cannot represent are kept verbatim, shown read-only,
and merged back on save. The page seeds custom exact ids from
`disabledAgents` so a custom bypass is not invisible.
- Saving starts from freshly read options and changes only the three page-owned
fields. A concurrent change to those fields is reported instead of overwritten;
- The page's **Middleware settings** tab groups the options by privacy impact:
Protection (binary policy, protocol, model/provider and blob controls),
Advanced inspection (`scanChars`, `maxNodes`, `maxDepth`) and Diagnostics
(`guideTools`, log settings). It validates list shape, displays numeric values
clamped to the middleware's effective range, reports an unknown select as
invalid, preserves options it does not own, and blocks a malformed
`allowModels` rather than replacing it with an allow-everything empty list.
- Saving starts from freshly read options and changes only the page-owned fields.
A concurrent change to those fields is reported instead of overwritten;
controls are disabled while a write is pending.
- `ctx.agent` is host-classified metadata, never a User-Agent header. Session
ids and working directories are not used for UI policy.
@@ -194,7 +201,7 @@ policy selection:
## Verification
- 72 cases in `cases.json`, run through `scripts/middleware.mjs` using the same
hook calls Magpie performs.
hook calls Magpie performs, plus 5 page/policy/settings checks.
- The package has no network, timers, Node APIs or imports; the middleware file
is one plain JavaScript module.
- The tests cover fail/guide mode, malformed options, all four protocols,
+11
View File
@@ -83,6 +83,17 @@ you to reload rather than overwriting the newer values.
A bypassed agent is intentionally unprotected, including binary parts and
encoded blobs. Use it only for an agent whose traffic you have chosen to trust.
## Middleware settings page
The page's **Middleware settings** tab edits the same options as
`magpie plugin options`, grouped as **Protection**, **Advanced inspection** and
**Diagnostics**. Ranges and list shape are checked before saving. Numeric
out-of-range values are shown at the effective clamped value the middleware
uses; an unknown select is reported as invalid. Options outside the form are
preserved. A malformed existing `allowModels` blocks saving instead of being
replaced by an empty, allow-everything list; fix it in the form or with
`magpie plugin options`.
## Troubleshooting
### I get a 403 for an image
+10 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/middleware-privacy-gate",
"version": "0.4.0",
"version": "0.4.1",
"description": "Structural egress gate for Magpie: withholds or rejects image/file/audio parts, encoded blobs and disallowed models, and guides agents toward local extraction when Magpie cannot mask text. Companion to ShyPie for DeepSeek Harness.",
"type": "module",
"files": [
@@ -32,7 +32,9 @@
"icon": "https://raw.githubusercontent.com/magpie-community/plugins/main/packages/privacy-gate/assets/shypie-icon.svg",
"page": {
"title": "ShyPie Filter",
"titles": { "zh": "ShyPie 防护" },
"titles": {
"zh": "ShyPie 防护"
},
"file": "page/index.html",
"icon": "page/icon.svg"
},
@@ -41,7 +43,9 @@
"slot": "agents",
"file": "page/agents-panel.html",
"title": "ShyPie protection",
"titles": { "zh": "ShyPie 防护" }
"titles": {
"zh": "ShyPie 防护"
}
}
],
"actions": [
@@ -49,7 +53,9 @@
"id": "shypie-protection",
"menu": "agent",
"title": "ShyPie protection",
"titles": { "zh": "ShyPie 防护" }
"titles": {
"zh": "ShyPie 防护"
}
}
],
"permissions": [],
+49 -1
View File
@@ -21,6 +21,7 @@ test('page and panel use only the released bridge and make no network calls', ()
const panel = read('panel.js')
const agents = read('agents.js')
const policy = read('policy.js')
const settings = read('settings.js')
const page = read('index.html')
const panelPage = read('agents-panel.html')
const allowed = ['ready', 'options.get', 'options.set', 'onAction']
@@ -29,6 +30,7 @@ test('page and panel use only the released bridge and make no network calls', ()
expect(safePageScript(panel, allowed)).toBe(true)
expect(safePageScript(agents, [])).toBe(true)
expect(safePageScript(policy, [])).toBe(true)
expect(safePageScript(settings, [])).toBe(true)
for (const source of [app, panel]) {
expect(safePageScript(`${source}\nfetch('https://evil.example/x')`, allowed)).toBe(false)
expect(safePageScript(`${source}\nmagpie.read?.('secrets')`, allowed)).toBe(false)
@@ -44,6 +46,7 @@ test('page and panel use only the released bridge and make no network calls', ()
expect(sources).toContain('_magpie/bridge.js')
expect(sources).toContain('agents.js')
expect(sources).toContain('policy.js')
if (html === page) expect(sources).toContain('settings.js')
expect(sources).toContain(html === page ? 'app.js' : 'panel.js')
expect(tags).toHaveLength(sources.length)
}
@@ -86,6 +89,51 @@ test('a glob policy survives an options save and unrelated options are kept', ()
)).toBe(false)
})
test('middleware settings are validated, merged and detect stale values', () => {
const sandbox = {}
sandbox.globalThis = sandbox
runInNewContext(read('settings.js'), sandbox)
const S = sandbox.ShyPieSettings
const parsed = S.fromOptions({
binaryPolicy: 'guide',
allowModels: ['safe/*'],
blobBase64Chars: 400,
future: 'keep',
})
expect(Array.from(parsed.values.allowModels)).toEqual(['safe/*'])
expect(parsed.invalid).toEqual([])
expect(Array.from(S.parseList('a/*, b/*\nc/*'))).toEqual(['a/*', 'b/*', 'c/*'])
expect(S.fromOptions({ allowModels: { bad: true } }).invalid).toEqual(['allowModels'])
expect(S.fromOptions({ allowModels: [null] }).invalid).toEqual(['allowModels'])
const clamped = S.fromOptions({ maxDepth: 500, scanChars: 500, maxNodes: 40000.5 })
expect(clamped.values.maxDepth).toBe(200)
expect(clamped.values.scanChars).toBe(1000)
expect(clamped.values.maxNodes).toBe(40000)
const savedClamped = S.apply(
{ maxDepth: 500, scanChars: 500, maxNodes: 40000.5, disabledAgents: ['codex'] },
clamped.values,
)
expect(savedClamped.maxDepth).toBe(200)
expect(savedClamped.scanChars).toBe(1000)
expect(savedClamped.maxNodes).toBe(40000)
expect(S.fromOptions({ binaryPolicy: 'Guide' }).invalid).toEqual(['binaryPolicy'])
expect(S.validate({ ...parsed.values, maxDepth: 0 }).map((error) => error.key)).toEqual(['maxDepth'])
const many = Array.from({ length: 201 }, (_, i) => `model/${i}`)
expect(S.parseList(many)).toHaveLength(201)
expect(S.validate({ ...parsed.values, allowModels: many }).map((error) => error.key)).toEqual(['allowModels'])
const rawSnapshot = S.snapshot({ ...parsed.values })
expect(S.same({ allowModels: null }, S.snapshot({ allowModels: [] }))).toBe(false)
const merged = S.apply(
{ binaryPolicy: 'fail', future: 'keep' },
{ ...parsed.values, binaryPolicy: 'guide', localProviders: ['ollama'] },
)
expect(merged.binaryPolicy).toBe('guide')
expect(Array.from(merged.localProviders)).toEqual(['ollama'])
expect(merged.future).toBe('keep')
expect(S.same({ ...parsed.values }, rawSnapshot)).toBe(true)
expect(S.same({ ...parsed.values, blobBase64Chars: 500 }, rawSnapshot)).toBe(false)
})
test('the shared agent catalogue validates ids and keeps custom agents', () => {
const sandbox = {}
sandbox.globalThis = sandbox
@@ -100,7 +148,7 @@ test('the shared agent catalogue validates ids and keeps custom agents', () => {
test('package declares the page, Agents panel and agent action', () => {
const pkg = JSON.parse(read('../package.json'))
expect(pkg.version).toBe('0.4.0')
expect(pkg.version).toBe('0.4.1')
expect(pkg.files).toContain('page')
expect(pkg.magpie.page.file).toBe('page/index.html')
expect(pkg.magpie.page.icon).toBe('page/icon.svg')
+127 -7
View File
@@ -3,13 +3,16 @@
var A = window.ShyPieAgents
var P = window.ShyPiePolicy
var S = window.ShyPieSettings
var $ = function (id) { return document.getElementById(id) }
var COPY = {
en: {
kicker: 'ShyPie Filter',
title: 'Per-agent protection',
lede: 'Choose which Magpie agents ShyPie protects. A disabled agent bypasses the gate entirely.',
title: 'Middleware settings',
lede: 'Choose which agents ShyPie protects and how its Magpie middleware behaves.',
settingsFailed: 'Could not read the middleware settings.',
settingsInvalid: 'Fix the malformed options before saving.',
search: 'Search agents',
reload: 'Reload',
save: 'Save changes',
@@ -40,8 +43,10 @@
},
zh: {
kicker: 'ShyPie 防护',
title: '按 Agent 保护',
lede: '选择哪些 Magpie Agent 受 ShyPie 保护。关闭的 Agent 会完全绕过防护。',
title: '中间件设置',
lede: '选择哪些 Agent 受 ShyPie 保护,以及 Magpie 中间件如何工作。',
settingsFailed: '无法读取中间件设置。',
settingsInvalid: '请先修复格式错误的选项再保存。',
search: '搜索 Agent',
reload: '重新加载',
save: '保存更改',
@@ -87,7 +92,11 @@
error: '',
loaded: { disabledAgents: [], protectUnknownAgent: true, extraAgents: [] },
pendingAction: null,
lang: 'en'
lang: 'en',
tab: 'settings',
settings: {},
settingsLoaded: {},
settingsInvalidKeys: []
}
function t(key) {
@@ -145,6 +154,78 @@
return true
}
var SETTING_IDS = {
binaryPolicy: 'opt-binary-policy',
allowUnknownProtocol: 'opt-allow-unknown',
allowModels: 'opt-allow-models',
localModels: 'opt-local-models',
localProviders: 'opt-local-providers',
guideTools: 'opt-guide-tools',
blobBase64Chars: 'opt-blob-base64',
blobHexChars: 'opt-blob-hex',
scanChars: 'opt-scan-chars',
maxNodes: 'opt-max-nodes',
maxDepth: 'opt-max-depth',
logMaxLines: 'opt-log-max-lines',
logEveryRows: 'opt-log-every-rows'
}
function numberInput(raw) {
var text = String(raw == null ? '' : raw).trim()
if (text === '' || !/^-?\d+$/.test(text)) return NaN
return Number(text)
}
function readSettingsForm() {
var values = {}
values.binaryPolicy = $('opt-binary-policy').value
values.allowUnknownProtocol = $('opt-allow-unknown').checked
values.allowModels = S.parseList($('opt-allow-models').value)
values.localModels = S.parseList($('opt-local-models').value)
values.localProviders = S.parseList($('opt-local-providers').value)
values.guideTools = S.parseList($('opt-guide-tools').value)
values.blobBase64Chars = numberInput($('opt-blob-base64').value)
values.blobHexChars = numberInput($('opt-blob-hex').value)
values.scanChars = numberInput($('opt-scan-chars').value)
values.maxNodes = numberInput($('opt-max-nodes').value)
values.maxDepth = numberInput($('opt-max-depth').value)
values.logMaxLines = numberInput($('opt-log-max-lines').value)
values.logEveryRows = numberInput($('opt-log-every-rows').value)
return { values: values, errors: S.validate(values) }
}
function fillSettingsForm(values) {
$('opt-binary-policy').value = values.binaryPolicy
$('opt-allow-unknown').checked = values.allowUnknownProtocol === true
$('opt-allow-models').value = (values.allowModels || []).join('\n')
$('opt-local-models').value = (values.localModels || []).join('\n')
$('opt-local-providers').value = (values.localProviders || []).join('\n')
$('opt-guide-tools').value = (values.guideTools || []).join('\n')
$('opt-blob-base64').value = values.blobBase64Chars
$('opt-blob-hex').value = values.blobHexChars
$('opt-scan-chars').value = values.scanChars
$('opt-max-nodes').value = values.maxNodes
$('opt-max-depth').value = values.maxDepth
$('opt-log-max-lines').value = values.logMaxLines
$('opt-log-every-rows').value = values.logEveryRows
}
function showSettingsError(text) {
var el = $('settings-error')
if (!el) return
el.textContent = text || ''
el.hidden = !text
}
function setTab(tab) {
state.tab = tab === 'agents' ? 'agents' : 'settings'
$('agents-view').hidden = state.tab !== 'agents'
$('settings-view').hidden = state.tab !== 'settings'
$('tab-agents').setAttribute('aria-selected', state.tab === 'agents' ? 'true' : 'false')
$('tab-settings').setAttribute('aria-selected', state.tab === 'settings' ? 'true' : 'false')
$('count').hidden = state.tab !== 'agents'
}
function configure(options) {
state.options = options && typeof options === 'object' ? options : {}
var split = P.split(state.options.disabledAgents)
@@ -159,6 +240,12 @@
protectUnknownAgent: state.protectUnknown,
extraAgents: P.rawList(state.options.extraAgents)
}
var parsed = S.fromOptions(state.options)
state.settings = parsed.values
state.settingsLoaded = S.snapshot(state.options)
state.settingsInvalidKeys = parsed.invalid.slice()
fillSettingsForm(state.settings)
showSettingsError(state.settingsInvalidKeys.length > 0 ? t('settingsInvalid') : '')
}
function patternFor(id) {
@@ -287,6 +374,7 @@
var counts = protectedCount()
setText('count', counts.on + ' / ' + counts.total + ' ' + t('protected'))
$('count').hidden = state.tab !== 'agents'
var warning = $('warning')
if (counts.on === 0) {
warning.textContent = t('warningAll')
@@ -301,6 +389,10 @@
$('reload').disabled = state.busy
$('add-agent').disabled = state.busy
$('add-id').disabled = state.busy
Object.keys(SETTING_IDS).forEach(function (key) {
var control = $(SETTING_IDS[key])
if (control) control.disabled = state.busy
})
var status = $('status')
if (state.error) {
status.textContent = state.error
@@ -379,6 +471,12 @@
function save() {
if (state.busy || !state.dirty) return
var form = readSettingsForm()
if (state.settingsInvalidKeys.length > 0 || form.errors.length > 0) {
setTab('settings')
showSettingsError(state.settingsInvalidKeys.length > 0 ? t('settingsInvalid') : form.errors[0].message)
return
}
state.busy = true
clearError()
render()
@@ -389,18 +487,20 @@
extra: state.extra
}
Promise.resolve(magpie.options.get()).then(function (current) {
if (!P.sameAgentFields(current, state.loaded)) {
if (!P.sameAgentFields(current, state.loaded) || !S.same(current, state.settingsLoaded)) {
var conflict = new Error('options changed elsewhere')
conflict.conflict = true
throw conflict
}
return magpie.options.set(P.mergeOptions(current, edit))
var next = P.mergeOptions(current, edit)
return magpie.options.set(S.apply(next, form.values))
}).then(function (saved) {
configure(saved)
state.busy = false
state.dirty = false
state.saved = true
clearError()
showSettingsError('')
render()
}).catch(function (error) {
state.busy = false
@@ -416,6 +516,7 @@
var id = A.normalizeId(agent.id)
if (!id) return
var added = ensureExtra(id)
setTab('agents')
state.rows = A.allRows(state.extra)
state.search = ''
$('search').value = ''
@@ -464,6 +565,25 @@
if (event.key === 'Enter' && !state.busy) addAgent()
})
$('save').addEventListener('click', save)
$('tab-agents').addEventListener('click', function () { setTab('agents') })
$('tab-settings').addEventListener('click', function () { setTab('settings') })
function settingsTouched(key) {
state.settingsInvalidKeys = state.settingsInvalidKeys.filter(function (item) { return item !== key })
state.dirty = true
clearError()
showSettingsError('')
render()
}
Object.keys(SETTING_IDS).forEach(function (key) {
var el = $(SETTING_IDS[key])
if (!el) return
el.addEventListener('input', function () { settingsTouched(key) })
el.addEventListener('change', function () { settingsTouched(key) })
})
setTab('settings')
if (typeof magpie.onAction === 'function') {
magpie.onAction(function (action) {
+126 -27
View File
@@ -12,41 +12,139 @@
<img class="logo" src="icon.svg" width="56" height="56" alt="">
<div class="hero-copy">
<p class="kicker" id="kicker">ShyPie Filter</p>
<h1 id="title">Per-agent protection</h1>
<p class="lede" id="lede">Choose which Magpie agents ShyPie protects. A disabled agent bypasses the gate entirely.</p>
<h1 id="title">Middleware settings</h1>
<p class="lede" id="lede">Choose which agents ShyPie protects and how its Magpie middleware behaves.</p>
</div>
<p class="count" id="count" aria-live="polite"></p>
</header>
<section class="toolbar" aria-label="Agent filter">
<label class="search">
<span class="sr-only" id="search-label">Search agents</span>
<input id="search" type="search" autocomplete="off" spellcheck="false" placeholder="Search agents">
</label>
<button id="reload" class="secondary" type="button">Reload</button>
<nav class="tabs" role="tablist" aria-label="ShyPie sections">
<button id="tab-agents" class="tab" role="tab" type="button" aria-selected="false" aria-controls="agents-view">Agents</button>
<button id="tab-settings" class="tab" role="tab" type="button" aria-selected="true" aria-controls="settings-view">Middleware settings</button>
</nav>
<section id="agents-view" class="view" role="tabpanel" aria-labelledby="tab-agents" hidden>
<section class="toolbar" aria-label="Agent filter">
<label class="search">
<span class="sr-only" id="search-label">Search agents</span>
<input id="search" type="search" autocomplete="off" spellcheck="false" placeholder="Search agents">
</label>
<button id="reload" class="secondary" type="button">Reload</button>
</section>
<div class="warning" id="warning" role="status" hidden></div>
<section class="list" id="list" aria-label="Agents"></section>
<p class="empty" id="empty" hidden>No agents match that search.</p>
<section class="patterns" id="patterns" aria-labelledby="patterns-title" hidden>
<h2 id="patterns-title">Policy patterns</h2>
<p class="hint" id="patterns-hint">Raw entries in disabledAgents that this page cannot show as a switch. They are preserved on save; edit them with the JSON options or CLI.</p>
<ul class="pattern-list" id="pattern-list"></ul>
</section>
<section class="add" aria-labelledby="add-title">
<div>
<h2 id="add-title">Add another agent id</h2>
<p class="hint" id="add-hint">For a plugin-added or not-yet-listed agent. You can also use the agent row menu on the Agents page.</p>
</div>
<div class="add-row">
<label class="sr-only" for="add-id">Agent id</label>
<input id="add-id" type="text" autocomplete="off" spellcheck="false" placeholder="e.g. my-agent" maxlength="64">
<button id="add-agent" class="secondary" type="button">Add</button>
</div>
<p class="form-error" id="add-error" role="alert" hidden></p>
</section>
</section>
<div class="warning" id="warning" role="status" hidden></div>
<section class="list" id="list" aria-label="Agents"></section>
<p class="empty" id="empty" hidden>No agents match that search.</p>
<section id="settings-view" class="view" role="tabpanel" aria-labelledby="tab-settings">
<p class="view-lede" id="settings-lede">Grouped by privacy impact. Fields not shown here are preserved unchanged.</p>
<p class="form-error" id="settings-error" role="alert" hidden></p>
<section class="patterns" id="patterns" aria-labelledby="patterns-title" hidden>
<h2 id="patterns-title">Policy patterns</h2>
<p class="hint" id="patterns-hint">Raw entries in disabledAgents that this page cannot show as a switch. They are preserved on save; edit them with the JSON options or CLI.</p>
<ul class="pattern-list" id="pattern-list"></ul>
</section>
<section class="settings-card" aria-labelledby="policy-title">
<h2 id="policy-title">Protection</h2>
<div class="field">
<label for="opt-binary-policy">Binary content</label>
<select id="opt-binary-policy">
<option value="fail">fail — reject the request with 403</option>
<option value="guide">guide — withhold bytes and ask for local processing</option>
</select>
<p class="hint">fail is the strict default; guide keeps the model in the loop without forwarding bytes.</p>
</div>
<div class="field checkbox-field">
<label class="checkbox-label"><input id="opt-allow-unknown" type="checkbox"> Allow unknown protocols</label>
<p class="hint">Off rejects protocols outside chat / responses / anthropic / gemini.</p>
</div>
<div class="field">
<label for="opt-allow-models">Allowed models</label>
<textarea id="opt-allow-models" rows="3" spellcheck="false" placeholder="one glob per line; empty allows every model"></textarea>
<p class="hint">Globs such as deepseek/* or copilot/*, one per line. Empty means every model is allowed.</p>
</div>
<div class="field">
<label for="opt-local-models">Local models</label>
<textarea id="opt-local-models" rows="2" spellcheck="false" placeholder="one glob per line"></textarea>
<p class="hint">Models that may receive binary parts because they run locally. Leave empty to withhold every binary part.</p>
</div>
<div class="field">
<label for="opt-local-providers">Local providers</label>
<textarea id="opt-local-providers" rows="2" spellcheck="false" placeholder="one provider id per line"></textarea>
<p class="hint">Must agree with local models; onProvider checks the real provider id.</p>
</div>
<div class="grid-2">
<div class="field">
<label for="opt-blob-base64">Base64 blob threshold</label>
<input id="opt-blob-base64" type="number" min="64" max="1000000" step="1">
<p class="hint">64–1,000,000 characters. Raising this lets larger encoded documents through.</p>
</div>
<div class="field">
<label for="opt-blob-hex">Hex blob threshold</label>
<input id="opt-blob-hex" type="number" min="64" max="1000000" step="1">
<p class="hint">64–1,000,000 characters. Raising this lets larger encoded documents through.</p>
</div>
</div>
</section>
<section class="settings-card" aria-labelledby="limits-title">
<h2 id="limits-title">Advanced inspection</h2>
<div class="field">
<label for="opt-scan-chars">Scan characters</label>
<input id="opt-scan-chars" type="number" min="1000" max="5000000" step="1">
<p class="hint">1,000–5,000,000.</p>
</div>
<div class="field">
<label for="opt-max-nodes">Max nodes</label>
<input id="opt-max-nodes" type="number" min="1000" max="5000000" step="1">
<p class="hint">1,000–5,000,000.</p>
</div>
<div class="field">
<label for="opt-max-depth">Max depth</label>
<input id="opt-max-depth" type="number" min="1" max="200" step="1">
<p class="hint">1–200.</p>
</div>
</div>
</section>
<section class="settings-card" aria-labelledby="diagnostics-title">
<h2 id="diagnostics-title">Diagnostics</h2>
<p class="hint">These settings affect prompt guidance and logging, not what content can leave the gate.</p>
<div class="field">
<label for="opt-guide-tools">Guide-mode tools</label>
<textarea id="opt-guide-tools" rows="2" spellcheck="false" placeholder="one tool name per line"></textarea>
<p class="hint">Only used with binaryPolicy guide; names are included in the local-processing prompt.</p>
</div>
<div class="grid-2">
<div class="field">
<label for="opt-log-max-lines">Max log lines</label>
<input id="opt-log-max-lines" type="number" min="0" max="500" step="1">
<p class="hint">0–500; 0 silences the log self-cap.</p>
</div>
<div class="field">
<label for="opt-log-every-rows">Log every rows</label>
<input id="opt-log-every-rows" type="number" min="1" max="100000" step="1">
<p class="hint">1–100,000 usage rows.</p>
</div>
</div>
</section>
<section class="add" aria-labelledby="add-title">
<div>
<h2 id="add-title">Add another agent id</h2>
<p class="hint" id="add-hint">For a plugin-added or not-yet-listed Magpie agent. You can also use an agent's row menu on the Agents page.</p>
</div>
<div class="add-row">
<label class="sr-only" for="add-id">Agent id</label>
<input id="add-id" type="text" autocomplete="off" spellcheck="false" placeholder="e.g. my-agent" maxlength="64">
<button id="add-agent" class="secondary" type="button">Add</button>
</div>
<p class="form-error" id="add-error" role="alert" hidden></p>
</section>
<footer class="actions">
@@ -57,6 +155,7 @@
<script src="_magpie/bridge.js"></script>
<script src="agents.js"></script>
<script src="policy.js"></script>
<script src="settings.js"></script>
<script src="app.js" defer></script>
</body>
</html>
+164
View File
@@ -0,0 +1,164 @@
/* Middleware settings shared by the ShyPie page.
*
* The page owns only the options listed here. Everything else in the plugin's
* options object is preserved. No network, no imports. */
(function (root) {
'use strict'
var FIELDS = [
{ key: 'binaryPolicy', type: 'select', options: ['fail', 'guide'], default: 'fail' },
{ key: 'allowUnknownProtocol', type: 'bool', default: false },
{ key: 'allowModels', type: 'list', default: [] },
{ key: 'localModels', type: 'list', default: [] },
{ key: 'localProviders', type: 'list', default: [] },
{ key: 'guideTools', type: 'list', default: [] },
{ key: 'blobBase64Chars', type: 'number', min: 64, max: 1000000, default: 400 },
{ key: 'blobHexChars', type: 'number', min: 64, max: 1000000, default: 400 },
{ key: 'scanChars', type: 'number', min: 1000, max: 5000000, default: 200000 },
{ key: 'maxNodes', type: 'number', min: 1000, max: 5000000, default: 40000 },
{ key: 'maxDepth', type: 'number', min: 1, max: 200, default: 40 },
{ key: 'logMaxLines', type: 'number', min: 0, max: 500, default: 40 },
{ key: 'logEveryRows', type: 'number', min: 1, max: 100000, default: 50 }
]
var BY_KEY = {}
for (var i = 0; i < FIELDS.length; i++) BY_KEY[FIELDS[i].key] = FIELDS[i]
function parseList(value) {
if (Array.isArray(value)) value = value.join('\n')
if (typeof value !== 'string') return []
var parts = value.split(/[\n,]+/)
var out = []
for (var i = 0; i < parts.length; i++) {
var item = parts[i].trim()
if (item !== '' && out.indexOf(item) === -1) out.push(item)
}
return out
}
function numberValue(raw, field) {
if (typeof raw === 'number' && Number.isInteger(raw)) return raw
var text = String(raw == null ? '' : raw).trim()
if (text === '' || !/^-?\d+$/.test(text)) return null
var value = Number(text)
return Number.isSafeInteger(value) ? value : null
}
function fromOptions(options) {
var source = options && typeof options === 'object' ? options : {}
var values = {}
var invalid = []
for (var i = 0; i < FIELDS.length; i++) {
var field = FIELDS[i]
var raw = source[field.key]
if (field.type === 'list') {
if (raw === undefined) values[field.key] = []
else if (Array.isArray(raw)) {
var listOk = raw.length <= 200
for (var j = 0; j < raw.length; j++) {
if (typeof raw[j] !== 'string' || raw[j].length === 0 || raw[j].length >= 200) listOk = false
}
values[field.key] = parseList(raw)
if (!listOk) invalid.push(field.key)
} else {
values[field.key] = []
invalid.push(field.key)
}
} else if (field.type === 'bool') {
values[field.key] = typeof raw === 'boolean' ? raw : field.default
} else if (field.type === 'select') {
if (raw === undefined) values[field.key] = field.default
else if (field.options.indexOf(raw) !== -1) values[field.key] = raw
else {
values[field.key] = field.default
invalid.push(field.key)
}
} else if (typeof raw === 'number' && isFinite(raw)) {
var effective = Math.floor(raw)
if (effective < field.min) effective = field.min
if (effective > field.max) effective = field.max
values[field.key] = effective
} else {
values[field.key] = field.default
}
}
return { values: values, invalid: invalid }
}
function validate(values) {
var errors = []
for (var i = 0; i < FIELDS.length; i++) {
var field = FIELDS[i]
var value = values[field.key]
if (field.type === 'list') {
if (!Array.isArray(value) || value.length > 200) {
errors.push({ key: field.key, message: 'Use at most 200 entries.' })
continue
}
for (var j = 0; j < value.length; j++) {
if (typeof value[j] !== 'string' || value[j].length === 0 || value[j].length >= 200) {
errors.push({ key: field.key, message: 'Each entry must be a non-empty string under 200 characters.' })
break
}
}
} else if (field.type === 'select') {
if (field.options.indexOf(value) === -1) errors.push({ key: field.key, message: 'Choose fail or guide.' })
} else if (field.type === 'bool') {
if (typeof value !== 'boolean') errors.push({ key: field.key, message: 'Choose on or off.' })
} else {
var n = numberValue(value, field)
if (n === null || n < field.min || n > field.max) {
errors.push({ key: field.key, message: 'Use a whole number from ' + field.min + ' to ' + field.max + '.' })
} else {
values[field.key] = n
}
}
}
return errors
}
function apply(current, values) {
var next = Object.assign({}, current && typeof current === 'object' ? current : {})
for (var i = 0; i < FIELDS.length; i++) {
var field = FIELDS[i]
var value = values[field.key]
if (field.type === 'list') next[field.key] = parseList(value)
else if (field.type === 'bool') next[field.key] = value === true
else if (field.type === 'select') next[field.key] = field.options.indexOf(value) !== -1 ? value : field.default
else {
var n = numberValue(value, field)
next[field.key] = n === null ? field.default : n
}
}
return next
}
function snapshot(options) {
var source = options && typeof options === 'object' ? options : {}
var out = {}
for (var i = 0; i < FIELDS.length; i++) {
var key = FIELDS[i].key
out[key] = Object.prototype.hasOwnProperty.call(source, key)
? { present: true, value: source[key] }
: { present: false }
}
return out
}
function same(current, savedSnapshot) {
if (!savedSnapshot || typeof savedSnapshot !== 'object') return false
return JSON.stringify(snapshot(current)) === JSON.stringify(savedSnapshot)
}
root.ShyPieSettings = {
FIELDS: FIELDS,
BY_KEY: BY_KEY,
parseList: parseList,
fromOptions: fromOptions,
validate: validate,
apply: apply,
snapshot: snapshot,
same: same
}
})(typeof globalThis !== 'undefined' ? globalThis : this)
+105
View File
@@ -275,6 +275,109 @@ button:disabled {
.status[data-error="true"] { color: var(--shy-danger); }
.tabs {
display: flex;
gap: 4px;
margin: 0 0 14px;
border-bottom: 1px solid var(--shy-line);
}
.tab {
position: relative;
min-height: 34px;
padding: 6px 10px;
border: 0;
border-radius: 7px 7px 0 0;
background: transparent;
color: var(--shy-muted);
font: inherit;
font-weight: 600;
}
.tab[aria-selected="true"] {
color: var(--shy-fg);
box-shadow: inset 0 -2px 0 var(--shy-gold);
}
.tab:focus-visible { outline: 2px solid var(--shy-gold); outline-offset: -2px; }
.view-lede {
margin: 0 0 14px;
color: var(--shy-muted);
}
.settings-card {
margin: 0 0 14px;
padding: 16px;
border: 1px solid var(--shy-line);
border-radius: var(--shy-radius);
background: var(--shy-card);
}
.settings-card h2 {
margin-bottom: 12px;
font-size: 15px;
}
.field {
display: flex;
flex-direction: column;
gap: 5px;
margin-top: 12px;
}
.field:first-of-type { margin-top: 0; }
.field > label,
.checkbox-label {
font-weight: 600;
font-size: 13px;
}
.checkbox-field { margin-top: 12px; }
.checkbox-label {
display: flex;
align-items: center;
gap: 7px;
cursor: pointer;
}
select,
textarea,
input[type="number"] {
width: 100%;
min-height: 34px;
padding: 7px 9px;
border: 1px solid var(--shy-line);
border-radius: 8px;
background: transparent;
color: inherit;
font: inherit;
}
textarea {
resize: vertical;
min-height: 54px;
font-family: var(--magpie-mono, ui-monospace, SFMono-Regular, Consolas, monospace);
font-size: 12px;
line-height: 1.45;
}
select { cursor: pointer; }
input[type="checkbox"] { accent-color: var(--shy-accent); }
.grid-2 {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 4px 18px;
}
@media (max-width: 560px) {
.grid-2 { grid-template-columns: 1fr; }
}
.empty {
margin: 16px 14px;
color: var(--shy-muted);
@@ -310,6 +413,8 @@ button:disabled {
.add-row input { max-width: 240px; }
.form-error { grid-column: 1 / -1; color: var(--shy-danger); }
#settings-error { margin: 0 0 12px; }
.actions {
display: flex;
align-items: center;
@@ -1134,7 +1134,7 @@ export function onUsage(row, options) {
if (status >= 500) usage.errors++;
else if (row && (row.errorType || row.error_type)) usage.errors++;
var every = numOpt(opts, "logEveryRows", DEFAULTS.logEveryRows, 1, 10000);
var every = numOpt(opts, "logEveryRows", DEFAULTS.logEveryRows, 1, 100000);
if (usage.rows === 1 || usage.rows % every === 0) {
logLine(
"privacy-gate: usage rows=" + usage.rows +