fingerprint 0.1.0: a page that checks whether a model answers like the one it claims to be (#516)

Adds the Fingerprint page plugin (packages/fingerprint): it checks whether a model behind the local magpie gateway answers like the model it claims to be.

Reviewed at 531ca11f4 (KaranocaVe). Run at that head merged with main 848497c, through mote-run on the Mac mini with Bun 1.4.2:
- bun run rebuild from the committed bun.lock (frozen, --ignore-scripts): typecheck, 30/30 tests, build; diff -r against the committed dist/ is empty.
- HOME=$(mktemp -d) bun test: 3838 pass, 0 fail. bun scripts/check.mjs: exit 0.
- Offline preload refusing every non-loopback fetch/socket: 30/30, nothing refused.
- Broken by hand, each red: ensureDetector() in bootstrap, dropping ttl: Infinity, validating the job after the download.

Maintainer decision: the reference data comes from two third-party hosts (lm.ikale.io, cdn.jsdmirror.com), only on an explicit Download or a valid job, and both are named on the page, in registry.json and the READMEs. It is data used locally to rank candidates and is sent nowhere; the @latest fallback has no pinned hash, so a bad snapshot would rank wrongly, which the page states.

Not on npm yet (E404): magpie installs it from the dist branch until an owner publishes the first version.
This commit is contained in:
KaranocaVe
2026-10-31 02:00:33 +08:00
committed by GitHub
parent 9d4c7ce558
commit 00f4d84b8f
65 changed files with 10141 additions and 0 deletions
+1
View File
@@ -118,6 +118,7 @@ These add a page to magpie's window, in the app and in `magpie web`, under Plugi
| [powercontext](packages/powercontext) | Connection settings for an independently deployed PowerContext service | None |
| [nowledge-mem](packages/nowledge-mem) | Connection settings, recall and capture switches, a real connection test, and the scope of what is sent | None |
| [agent-office](packages/agent-office) | What are my agents doing: live sessions as workers in a voxel office (3D/2D) or a list, with status, current step and resume commands | no `magpie.read`; its host part reads the local session files of Claude Code, Codex, dsh, Gemini CLI, Qwen Code, Pi, omp, Qoder, WorkBuddy and CodeBuddy, including prompts, replies and tool commands (`text:false` keeps statuses and tool names only) |
| [fingerprint](packages/fingerprint) | Numeric response fingerprints to investigate suspected model substitution across providers, with shared challenges, candidate rankings, local evidence and JSON export | none (its local service calls magpie’s gateway; sampling uses provider quota) |
| [chat](packages/chat) | Chat with magpie's models, your MCP servers, instructions and skills, by Magic_zero ([Magiczerowxy](https://github.com/Magiczerowxy)). Has a host part: a local service the page goes to | none (its service calls magpie's gateway) |
```sh
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 KaranocaVe
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+86
View File
@@ -0,0 +1,86 @@
# Magpie Fingerprint
[简体中文](README.zh-CN.md) · [Magpie](https://github.com/yetone/magpie) · [lm-detector](https://github.com/Ikaleio/lm-detector)
Investigate suspected model substitution directly in Magpie. Compare numeric
response fingerprints across providers or repeat a run after a service changes.
The page reuses Magpie’s configured models and gateway; the pinned
`lmfpd-sdk` detector ranks nearby reference-bank models. Rankings are evidence
for investigation, not proof of model identity.
![Fingerprint workspace (explicit demo data)](docs/preview.png)
- Select up to 24 models across providers, with the same three challenges per batch.
- Reuse Magpie authentication and native endpoint metadata; optionally pin an account.
- Follow live sample counts, cancel work, and inspect the actual response route.
- Compare ranked candidates, including partial and unscorable outcomes.
- Keep raw replies and data versions in local history; export or copy JSON.
- Magpie's native page bridge, controls and design tokens; follows the host's theme and language.
- Compact model lists, keyboard-accessible view tabs, and narrow-screen layouts.
## Install
Install **Fingerprint** from **Plugins → Discover**, or use the CLI. Requires
a current Magpie release with `page.service` support and Bun 1.4.2+:
```sh
magpie plugin add @magpie-community/page-fingerprint
```
Open **Fingerprint** in the sidebar, or choose **Fingerprint** from a provider's menu.
Starting a detection sends three requests per selected model and uses that provider's quota.
## Development
Run these commands from `packages/fingerprint/`. Source, tests and the built
`dist/` assets are checked in. Installation and the offline tests do not need
package downloads: `vendor/lmfpd-sdk` pins the MIT SDK at 0.2.0. Only rebuilding
the UI and running the type checker require the development dependencies.
Direct build-tool versions are exact in `package.json`; `bun.lock` fixes the
complete dependency graph using `registry.npmjs.org`. Builds use Bun 1.4.4.
There are no install/pack lifecycle scripts. After a source change, rebuild
and commit the resulting `dist/` files.
The standalone project and release history are at
[KaranocaVe/magpie-fingerprint](https://github.com/KaranocaVe/magpie-fingerprint).
```sh
bun run rebuild
bun start
```
`rebuild` installs with `--frozen-lockfile --ignore-scripts` in an isolated
copy, runs typecheck/tests/build, and copies `dist/` back. This avoids Bun
resolving the parent monorepo's workspaces; its temporary directory is removed
on completion. In a standalone copy of this package, `bun install
--frozen-lockfile --registry https://registry.npmjs.org` and `bun run check`
produce the same build.
The plugin page service listens on `3488` by default and uses Magpie's gateway
at `http://127.0.0.1:3425`. Opening or refreshing the page never downloads
reference data. **Download reference data** explicitly fetches a fresh snapshot;
starting a run downloads one only when no usable snapshot is cached. There is
no background refresh. The default primary source is
`https://lm.ikale.io/data/`; its fallback is
`https://cdn.jsdmirror.com/npm/lmfpd-data@latest/`. These hosts see the client's
IP address. Reference downloads carry no provider credentials, model ids,
prompts or replies. Only an explicitly started job sends sampling prompts
through the configured gateway. See [integration.md](integration.md) for gateway
authentication, `magpie web`, environment variables, local reference sources,
and the explicit `--demo` fixture.
## Scope and limits
The first release supports numeric fingerprinting. Each run retains its loaded
reference snapshot and records its `builtAt` value. The remote reference data
is not version-pinned or authenticated by a locally pinned hash; the fallback
uses `@latest`. Runs use three shared challenges per batch, bounded work, and
cancellation. It records proposed, observed, and failed evidence separately;
it does not prove provider identity, authenticate a model, or infer hidden
tokenizers. `--demo` runs an isolated illustrative workflow without model calls.
Magpie middleware and protocol adapters still apply. A changed actual provider/model
invalidates that target's aggregate score. Account pinning is optional; it does not
turn a routed channel into an upstream identity guarantee. Tokenizer probing is deferred.
MIT licensed. Third-party notices are in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
+47
View File
@@ -0,0 +1,47 @@
# Magpie Fingerprint
[English](README.md) · [Magpie](https://github.com/yetone/magpie) · [lm-detector](https://github.com/Ikaleio/lm-detector)
在 Magpie 内检查疑似模型替换:比较不同渠道的同名模型,或在服务变化后重新采样。复用已有登录与网关配置,基于 `lmfpd-sdk` 的数字指纹展示参考库中的相近候选,为核查保留证据。候选排名不能单独证明模型身份。
![检测界面,图中为明确标识的示例数据](docs/preview.png)
- 一批最多选择 24 个模型,共用三个挑战,便于横向比较。
- 实时显示采样数量与状态,支持取消、总超时和并发设置。
- 保存实际路由、原始回答、推理参数与参考库版本。
- 展示候选排名、模型家族和部分样本等状态。
- 复用 Magpie 原生页面桥接、控件样式与设计变量,主题和语言跟随宿主。
- 本地历史、JSON 导出与复制;紧凑列表、键盘切换与窄屏布局。
## 安装
在 Magpie 的 **Plugins → Discover** 中安装 **Fingerprint**,也可执行:
```sh
magpie plugin add @magpie-community/page-fingerprint
```
需要支持 `page.service` 的当前 Magpie 版本和 Bun 1.4.2+。启用后,从侧栏「模型指纹」或 provider 菜单「检测指纹」进入。点击开始会为每个模型发送三条采样请求,消耗对应通道的额度。
## 开发
在 `packages/fingerprint/` 中运行以下命令。源码、测试和可安装的 `dist/` 均纳入版本控制;MIT SDK 0.2.0 固定在 `vendor/lmfpd-sdk/`。安装插件及运行离线测试无需下载包,仅重建 UI、执行类型检查需要开发依赖。直接构建依赖在 `package.json` 中固定为精确版本,`bun.lock` 锁定完整依赖树并使用 `registry.npmjs.org`,构建使用 Bun 1.4.4;源码更新后重建并提交 `dist/`,不依赖安装或打包时执行脚本。
独立项目及发布记录见 [KaranocaVe/magpie-fingerprint](https://github.com/KaranocaVe/magpie-fingerprint)。
```sh
bun run rebuild
bun start
```
`rebuild` 在隔离副本中使用 `--frozen-lockfile --ignore-scripts` 安装,完成类型检查、测试和构建,再复制 `dist/` 回来并清理临时目录,避免 Bun 使用父级 monorepo 的 workspace 配置。
页面服务默认监听 `3488`,通过 `http://127.0.0.1:3425` 使用 Magpie 网关。打开、刷新页面不会下载参考库,也没有后台刷新。点击「下载参考数据」会下载新快照;启动检测时仅在没有可用缓存时下载。主源为 `https://lm.ikale.io/data/`,备用源为 `https://cdn.jsdmirror.com/npm/lmfpd-data@latest/`。这两个域名会看到客户端 IP;下载请求不携带 provider 凭证、模型标识、提示词或回答。仅主动开始任务才会通过网关发送采样提示。网关认证、`magpie web`、环境变量和离线数据源见 [integration.md](integration.md)。
## 范围与限制
首版实现数字指纹,分词器探测留待后续。每批任务保留其已加载的数据快照并记录 `builtAt`;远程参考库没有固定发布版本,也没有本地预置的哈希校验,备用源使用 `@latest`。概率只在参考库候选中分配,不能当成模型身份的证明。Magpie 的 middleware 和协议适配仍会生效;检测到实际 provider/model 变化时,该目标停止评分。固定账号可选,支持填写账号标识;已缓存的订阅账号可供补全。
`bun start --demo` 提供独立的示例模式,不调用真实模型。任务被宿主重启打断后会标为「已中断」,保留已收到的回答。
采用 MIT 许可证。第三方声明见 [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)。
+148
View File
@@ -0,0 +1,148 @@
# Third-party notices
The committed distribution bundles the following MIT-licensed software. Reference data is downloaded separately from lm-detector and retains its upstream provenance.
## lmfpd-sdk 0.2.0
```text
MIT License
Copyright (c) 2026 xqy2006
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
## React and React DOM
```text
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
## Phosphor Icons
```text
MIT License
Copyright (c) 2020 Phosphor Icons
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
## fzstd 0.1.1 (bundled by lmfpd-sdk)
```text
MIT License
Copyright (c) 2020 Arjun Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
## Magpie native page UI
The page bridge and selected UI styles are vendored from [yetone/magpie](https://github.com/yetone/magpie/tree/d80d75f300274fe13866d4fbf5599c13870b43ac), revision `d80d75f300274fe13866d4fbf5599c13870b43ac`.
Sources: `internal/gui/pagebridge.js`, `internal/gui/assets/app.css`, and `internal/gui/assets/plugins/library/library.css`.
```text
MIT License
Copyright (c) 2026 yetone
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
## Vendored detector SDK provenance
`vendor/lmfpd-sdk/index.js`, `types/`, `LICENSE`, `README.md` and `package.json`
are copied unchanged from the npm `lmfpd-sdk@0.2.0` package, published from
[Ikaleio/lm-detector](https://github.com/Ikaleio/lm-detector) commit
`1e58ed83c1cde17f88cba89560ad4d083042ae92`. `index.d.ts` is a local re-export
of the upstream declarations. Its runtime bundle includes `fzstd`; both MIT
notices are preserved above. The SDK is vendored so repository tests and plugin
installation require no dependency installation. The reference bank is fetched
only on explicit download or an uncached run, or supplied locally with `bankSource`.
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,24 @@
(()=>{const d=new Map;let b=0;const g=[];let c=null;const m=[];function i(e,t){const r=++b;return new Promise((n,l)=>{d.set(r,{resolve:n,reject:l}),parent.postMessage({magpie:1,id:r,method:e,params:t},"*")})}function h(e){const t=document.documentElement;t.dataset.theme=e.dark?"dark":"light",t.style.colorScheme=e.dark?"dark":"light",t.lang=e.lang||"en";for(const[r,n]of Object.entries(e.tokens||{}))t.style.setProperty("--magpie-"+r,n)}addEventListener("message",e=>{if(e.source!==parent)return;const t=e.data;if(!t||t.magpie!==1)return;if(t.event==="theme"){o.theme=t.data,h(t.data);for(const n of g)try{n(t.data)}catch(l){a(l)}return}if(t.event==="action"){c?u(t.data):m.push(t.data);return}const r=d.get(t.id);r&&(d.delete(t.id),t.error?r.reject(new Error(t.error)):r.resolve(t.result))});function a(e){parent.postMessage({magpie:1,method:"error",params:{message:String(e?.message||e)}},"*")}let s=!1;addEventListener("error",e=>{if(/ResizeObserver loop/.test(e.message)||s&&!e.error&&!e.filename){e.preventDefault();return}a(e.error||(e.message==="Script error."?"":e.message))}),addEventListener("unhandledrejection",e=>a(e.reason));function u(e){try{Promise.resolve(c(e)).catch(a)}catch(t){a(t)}}const o={theme:null,context:{},service:"",onTheme(e){g.push(e)},onAction(e){c=e;for(const t of m.splice(0))u(t)},options:{get:()=>i("options.get"),set:e=>i("options.set",{options:e})},read:(e,t)=>i("read",{name:e,params:t})};o.ready=i("hello").then(({context:e,service:t,...r})=>{o.theme=r,o.context=e||{},o.service="";try{t&&(o.service=new URL(t,location.href).href)}catch{}return h(r),r});let f=-1;const x=()=>{const e=Math.ceil(document.documentElement.getBoundingClientRect().height);e!==f&&(f=e,parent.postMessage({magpie:1,method:"size",params:{height:e}},"*"))},v=()=>{new ResizeObserver(()=>{s||(s=!0,setTimeout(()=>{s=!1})),x()}).observe(document.documentElement),x()};document.readyState==="loading"?addEventListener("DOMContentLoaded",v):v();const p=document.createElement("style");p.dataset.magpie="base",p.textContent=`
:where(html) { background: var(--magpie-bg, Canvas); color: var(--magpie-fg, CanvasText); font: 13px/1.45 var(--magpie-font, -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif); -webkit-font-smoothing: antialiased; }
:where(body) { margin: 0; padding: 20px 24px; }
:where(h1, h2, h3, h4) { font-weight: 600; margin: 0 0 8px; letter-spacing: -.01em; }
:where(h1) { font-size: 20px; } :where(h2) { font-size: 15px; } :where(h3, h4) { font-size: 13px; }
:where(p) { margin: 0 0 8px; }
:where(small, .muted) { color: var(--magpie-muted, GrayText); }
:where(a) { color: var(--magpie-accent, LinkText); text-decoration: none; }
:where(a:hover) { text-decoration: underline; }
:where(button, input, textarea, select) { font: inherit; color: inherit; }
:where(button) { background: var(--magpie-card, ButtonFace); border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 6px; padding: 3px 10px; }
:where(button:hover:not(:disabled)) { border-color: var(--magpie-muted, ButtonBorder); }
:where(button[aria-pressed="true"], button[aria-selected="true"]) { background: var(--magpie-accent-soft, Highlight); border-color: transparent; color: var(--magpie-accent, HighlightText); }
:where(button:disabled) { opacity: .5; }
:where(input, textarea, select) { background: var(--magpie-card, Field); border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 6px; padding: 4px 8px; }
:where(:focus-visible) { outline: 2px solid var(--magpie-accent, Highlight); outline-offset: 1px; }
:where(table) { border-collapse: collapse; width: 100%; }
:where(th) { text-align: left; font-weight: 500; font-size: 12px; color: var(--magpie-muted, GrayText); }
:where(th, td) { padding: 6px 8px; border-bottom: 1px solid var(--magpie-line, ButtonBorder); }
:where(code, kbd, pre) { font-family: var(--magpie-code, ui-monospace, Menlo, monospace); font-size: 12px; }
:where(pre) { background: var(--magpie-card, Canvas); border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 8px; padding: 8px 10px; overflow: auto; }
:where(hr) { border: 0; border-top: 1px solid var(--magpie-line, ButtonBorder); margin: 12px 0; }
:where(::selection) { background: var(--magpie-accent-soft, Highlight); }
`,(document.head||document.documentElement).prepend(p),window.magpie=o})();
+14
View File
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#f7f7f5" />
<title>Magpie · 模型指纹</title>
<script type="module" crossorigin src="./assets/index-BguzqVWK.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-C9z1QhHD.css">
</head>
<body>
<div id="root"></div>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

+120
View File
@@ -0,0 +1,120 @@
# Magpie integration
## Plugin contract
The package is a Magpie page plugin. Its manifest declares `page.file` as
`page/index.html`, a local service on port `3488` (configurable through the
`port` option), and one provider-menu action named `fingerprint`. Magpie sends
the action as `{ id, provider: { id, name } }` to the page frame. The page boot
document captures this event before navigating to the service, so the selected
provider is preserved across the service navigation.
A current Magpie release with `page.service` support is required. The service is bound to loopback. In a
desktop window it is reached at `http://127.0.0.1:<port>`; in `magpie web`,
Magpie supplies `magpie.service`, a tokenized reverse-proxy URL. The service
does not expose the gateway listener. Its authenticated API accepts its local
page and the opaque `Origin: null` used by Magpie's sandbox, and rejects unrelated origins.
The page CSP explicitly allows connections to the validated local listener and,
when proxied, the HTTP(S) origin supplied by the page launcher. Opaque sandbox
frames cannot reliably match `connect-src 'self'`. The launcher origin changes
only the document policy; the API bearer token and Host/Origin checks still apply.
## UI integration
The service page reconnects to Magpie using the upstream page bridge, vendored
with its MIT notice. Magpie supplies live theme tokens and language through
`hello` and `theme` messages. The interface uses the upstream base control
styles and a small selection of Magpie's list, group and segmented-control CSS.
It adds no sidebar or duplicate application header inside the plugin frame.
Standalone mode keeps its own theme and language controls.
The iframe remains isolated: the bridge exchanges messages with its parent;
it does not access the parent DOM or load private host scripts. The pinned
upstream revision is documented in `THIRD_PARTY_NOTICES.md`.
## Gateway reads
The service reads `GET /v1/models` for the text model catalog and
`GET /v1/magpie/quotas?kept=1` for cached subscription account labels. The
`kept=1` form does not ask vendors for a fresh quota reading. Account rows are
projected to provider, user id, and display name only; upstream credentials,
balances, and raw quota records are never sent to the browser.
Gateway authentication uses `Authorization: Bearer <key>` when an API key is
configured. Loopback Magpie normally needs no key. A remote gateway must be
shared and requires its enabled gateway key. `X-Magpie-Account` can pin a
gateway request to one account id or signed-in user, but is only meaningful to
Magpie and is never forwarded upstream.
## Local development
```sh
bun run rebuild
bun start
```
The default gateway is `http://127.0.0.1:3425`. Set
`MAGPIE_FINGERPRINT_GATEWAY` (or `MAGPIE_ADDR`) when Magpie listens elsewhere.
Set `MAGPIE_FINGERPRINT_API_KEY` only when that gateway requires a key. The
service port is controlled by `MAGPIE_FINGERPRINT_PORT`; data defaults to
`~/.config/magpie/fingerprint`.
The standalone illustrative fixture is opt-in:
```sh
bun src/cli.ts --demo
```
Demo mode never calls a real gateway or model. Numeric first-release detection
uses the pinned `lmfpd-sdk` 0.2.0 request/analyze flow; the SDK has no public
tokenizer API. Each job retains its loaded reference snapshot and records
`builtAt`; remote data is not version-pinned or verified against a locally
pinned hash. Jobs use three common challenges per batch, bounded concurrency,
and explicit cancellation/limits.
The detector reports model-family evidence, not identity authentication.
## Options and persistence
Plugin options accept `port`, `gateway`, `apiKey`, `dataDir`, and `bankSource`.
Keep the API key in the service environment when possible. `MAGPIE_FINGERPRINT_DATA_DIR`
overrides persistence; `MAGPIE_FINGERPRINT_BANK_SOURCE` can point to a local bank
directory for fully offline scoring. Each batch retains its loaded detector instance.
Opening/refreshing the page reads only the configured gateway and local history.
`POST /api/bank/download` is the explicit download/refresh action; a valid
`POST /api/jobs` also loads data if none is usable. Cached snapshots have no
background refresh, including after the SDK default 24-hour TTL. Downloads use
`https://lm.ikale.io/data/`, falling back to
`https://cdn.jsdmirror.com/npm/lmfpd-data@latest/`. These hosts see the client IP
but receive no provider credentials, model ids, prompts or replies. A custom
`bankSource` replaces these defaults.
Jobs are stored as atomic JSON files with owner-only permissions. The current limit
is 200 batches, 24 targets per batch, three concurrent targets and three concurrent
samples per target. The batch deadline is 10–900 seconds. Restarted unfinished jobs
become `interrupted`; already received raw replies remain available.
The SDK's `requestSample` does not accept a transport or external abort signal.
A second loopback-only listener provides one-shot, authenticated, job-bound sample
URLs. It forwards only the prescribed model/protocol to the configured gateway,
adds session/account headers, records provenance, and binds upstream fetches to
the job controller. It cannot be reached through the page service proxy.
The page's relative asset/API URLs also work under Magpie's remote proxy prefix.
Exports provide JSON text and clipboard/manual-copy fallback because Magpie's
iframe sandbox can block downloads. Standalone browser users can download a file.
## Multiple Magpie hosts
Desktop and `magpie web` can share a listener when their service protocol and
configuration match. The remaining host takes over if the owner exits. Different
configurations or unrelated applications on the port are rejected. The public
health digest uses HMAC-SHA256 with an owner-only, random per-install key; the
gateway API key still participates in matching. If the install cannot persist
that key, processes refuse to share a listener. After upgrading, turn Fingerprint
off and back on once to release an older listener.
For OpenAI-compatible chat streams, a clean EOF after an explicit `stop` is
normalized with `[DONE]` when the gateway omitted that sentinel. The raw response
text is unchanged, and provenance records `streamNormalization: chat-done-after-stop`.
Incomplete finishes, errors, and disconnected streams are never repaired.
+97
View File
@@ -0,0 +1,97 @@
{
"name": "@magpie-community/page-fingerprint",
"version": "0.2.0",
"description": "Check for suspected model substitution with numeric response fingerprints in Magpie, powered by lm-detector.",
"type": "module",
"license": "MIT",
"main": "dist/plugin.js",
"files": [
"dist",
"page",
"README.md",
"README.zh-CN.md",
"LICENSE",
"integration.md",
"THIRD_PARTY_NOTICES.md"
],
"engines": {
"bun": ">=1.4.2"
},
"scripts": {
"dev": "bun --watch src/cli.ts",
"start": "bun src/cli.ts",
"build": "bun scripts/build.ts",
"typecheck": "tsc --noEmit",
"test": "bun test",
"check": "bun run typecheck && bun run test && bun run build",
"format": "prettier --write src web scripts tests page *.json *.ts *.md",
"rebuild": "bun scripts/rebuild.ts"
},
"magpie": {
"page": {
"title": "Fingerprint",
"titles": {
"zh": "模型指纹",
"zh-TW": "模型指紋",
"ja": "モデル指紋",
"de": "Modell-Fingerabdruck"
},
"file": "page/index.html",
"service": {
"port": 3488,
"option": "port"
}
},
"actions": [
{
"id": "fingerprint",
"menu": "provider",
"title": "Fingerprint",
"titles": {
"zh": "检测指纹",
"zh-TW": "檢測指紋",
"ja": "指紋を検査",
"de": "Fingerabdruck prüfen"
}
}
],
"options": {
"port": 3488
},
"permissions": []
},
"devDependencies": {
"react": "19.3.1",
"react-dom": "19.3.1",
"@phosphor-icons/react": "2.1.10",
"@types/bun": "1.4.4",
"@types/react": "19.3.0",
"@types/react-dom": "19.3.0",
"@vitejs/plugin-react": "5.2.0",
"prettier": "3.9.10",
"typescript": "5.9.3",
"vite": "7.3.7"
},
"repository": {
"type": "git",
"url": "git+https://github.com/magpie-community/plugins.git",
"directory": "packages/fingerprint"
},
"bugs": {
"url": "https://github.com/magpie-community/plugins/issues"
},
"author": "KaranocaVe (https://github.com/KaranocaVe)",
"homepage": "https://github.com/KaranocaVe/magpie-fingerprint#readme",
"keywords": [
"magpie",
"magpie-page",
"magpie-plugin",
"llm",
"fingerprint",
"model-detection"
],
"publishConfig": {
"access": "public"
},
"packageManager": "bun@1.4.4"
}
+98
View File
@@ -0,0 +1,98 @@
(() => {
const messages = {
en: {
title: 'Fingerprint',
connecting: 'Connecting to Fingerprint…',
remote:
'Upgrade Magpie for remote plugin services, or forward the service port to this computer over SSH.',
invalidPort: 'Invalid Fingerprint service port.',
failed: 'Could not connect',
},
'zh-Hans': {
title: '模型指纹',
connecting: '正在连接模型指纹服务…',
remote: '请升级 Magpie 以支持远程插件服务,或将服务器的服务端口通过 SSH 转发到本机。',
invalidPort: '模型指纹服务端口无效。',
failed: '连接失败',
},
'zh-Hant': {
title: '模型指紋',
connecting: '正在連線至模型指紋服務…',
remote: '請升級 Magpie 以支援遠端外掛服務,或透過 SSH 將伺服器的服務連接埠轉送至本機。',
invalidPort: '模型指紋服務連接埠無效。',
failed: '連線失敗',
},
ja: {
title: 'モデル指紋',
connecting: 'モデル指紋サービスに接続中…',
remote:
'リモートプラグインサービスを利用するには、Magpie を更新するか、SSH でサービスポートをこのコンピューターに転送してください。',
invalidPort: 'モデル指紋サービスのポートが無効です。',
failed: '接続できませんでした',
},
de: {
title: 'Modell-Fingerabdruck',
connecting: 'Verbindung zum Fingerabdruck-Dienst wird hergestellt…',
remote:
'Aktualisieren Sie Magpie für entfernte Plugin-Dienste oder leiten Sie den Dienstport per SSH an diesen Computer weiter.',
invalidPort: 'Ungültiger Port für den Fingerabdruck-Dienst.',
failed: 'Verbindung fehlgeschlagen',
},
};
let text = messages.en;
const status = document.getElementById('status');
function followLanguage(theme) {
const language = String(theme?.lang || 'en')
.toLowerCase()
.replaceAll('_', '-');
const parts = language.split('-');
const key =
parts[0] === 'zh'
? parts.includes('hant') ||
(!parts.includes('hans') && parts.some((part) => ['tw', 'hk', 'mo'].includes(part)))
? 'zh-Hant'
: 'zh-Hans'
: parts[0];
text = messages[key] || messages.en;
document.documentElement.lang = messages[key] ? key : 'en';
document.title = text.title;
document.getElementById('title').textContent = text.title;
status.textContent = text.connecting;
}
return (async () => {
const theme = await window.magpie?.ready;
followLanguage(theme);
window.magpie?.onTheme?.(followLanguage);
const config = (await window.magpie?.options?.get?.()) || {};
const port = Number(config.port ?? 3488);
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(text.invalidPort);
let service = window.magpie?.service;
if (!service) {
const local =
!location.hostname || ['localhost', '127.0.0.1', '::1'].includes(location.hostname);
if (!local) {
status.textContent = text.remote;
return;
}
service = `http://127.0.0.1:${port}/`;
}
const url = new URL(service, location.href);
// Opaque Magpie web frames need the concrete proxy origin in connect-src.
url.searchParams.set('uiOrigin', url.origin);
if (theme) {
url.searchParams.set('theme', theme.dark ? 'dark' : 'light');
if (theme.lang) url.searchParams.set('lang', theme.lang);
}
const context = window.magpie?.context?.provider;
if (context?.id) url.searchParams.set('provider', context.id);
window.magpie?.onAction((action) => {
if (action?.provider?.id) {
url.searchParams.set('provider', action.provider.id);
location.replace(url.href);
}
});
location.replace(url.href);
})().catch((error) => {
status.textContent = `${text.failed}: ${String(error?.message || error)}`;
});
})();
+41
View File
@@ -0,0 +1,41 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Fingerprint</title>
<style>
:root {
color-scheme: light dark;
}
body {
margin: 0;
min-height: 100vh;
display: grid;
place-content: center;
font:
14px/1.7 -apple-system,
BlinkMacSystemFont,
system-ui,
sans-serif;
background: var(--magpie-bg, Canvas);
color: var(--magpie-fg, CanvasText);
}
main {
max-width: 440px;
padding: 32px;
}
p {
color: var(--magpie-muted, GrayText);
}
</style>
</head>
<body>
<main>
<strong id="title">Fingerprint</strong>
<p id="status">Connecting to Fingerprint…</p>
</main>
<script src="_magpie/bridge.js"></script>
<script src="boot.js"></script>
</body>
</html>
+16
View File
@@ -0,0 +1,16 @@
import { mkdir, rm } from 'node:fs/promises';
import { build as viteBuild } from 'vite';
await rm('dist', { recursive: true, force: true });
await mkdir('dist', { recursive: true });
await viteBuild();
const result = await Bun.build({
entrypoints: ['src/plugin.ts', 'src/cli.ts'],
outdir: 'dist',
target: 'bun',
minify: true,
packages: 'bundle',
});
if (!result.success) {
console.error(result.logs);
process.exit(1);
}
+41
View File
@@ -0,0 +1,41 @@
// Bun resolves the parent monorepo's workspaces during install. Build in an
// isolated copy so this package's own frozen lockfile controls every dependency.
import { cp, mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { basename, join, resolve } from 'node:path';
const root = resolve(import.meta.dir, '..');
const staging = await mkdtemp(join(tmpdir(), 'fingerprint-rebuild-'));
try {
await cp(root, staging, {
recursive: true,
filter: (path) => !['node_modules', 'dist', '.git'].includes(basename(path)),
});
for (const args of [
[
'install',
'--frozen-lockfile',
'--ignore-scripts',
'--registry',
'https://registry.npmjs.org',
],
['run', 'check'],
]) {
const process = Bun.spawn([Bun.argv[0], ...args], {
cwd: staging,
stdin: 'inherit',
stdout: 'inherit',
stderr: 'inherit',
env: {
...Bun.env,
PATH: `${resolve(Bun.argv[0], '..')}:${Bun.env.PATH || ''}`,
},
});
const code = await process.exited;
if (code !== 0) throw new Error(`bun ${args.join(' ')} exited ${code}`);
}
await rm(join(root, 'dist'), { recursive: true, force: true });
await cp(join(staging, 'dist'), join(root, 'dist'), { recursive: true });
} finally {
await rm(staging, { recursive: true, force: true });
}
+21
View File
@@ -0,0 +1,21 @@
import { startServer } from './server';
const argv = process.argv.slice(2);
if (argv.includes('--help')) {
console.log(
'Magpie Fingerprint\n bun start [--demo] [--port 3488]\nEnvironment: MAGPIE_FINGERPRINT_GATEWAY, MAGPIE_FINGERPRINT_API_KEY, MAGPIE_FINGERPRINT_DATA_DIR, MAGPIE_FINGERPRINT_BANK_SOURCE',
);
process.exit(0);
}
const at = argv.indexOf('--port');
const service = await startServer({
demo: argv.includes('--demo'),
...(at >= 0 ? { port: Number(argv[at + 1]) } : {}),
});
console.log(
`Magpie Fingerprint: http://127.0.0.1:${service.port}${service.demo ? ' (demo; no provider requests)' : ''}`,
);
for (const event of ['SIGINT', 'SIGTERM'] as const)
process.on(event, async () => {
await service.close();
process.exit(0);
});
+47
View File
@@ -0,0 +1,47 @@
import { homedir } from 'node:os';
import { join } from 'node:path';
export interface Options {
port?: number;
gateway?: string;
apiKey?: string;
dataDir?: string;
bankSource?: string;
demo?: boolean;
uiDir?: string;
}
export function options(
input: Options = {},
): Required<Omit<Options, 'bankSource' | 'uiDir'>> & Pick<Options, 'bankSource' | 'uiDir'> {
const addr = process.env.MAGPIE_ADDR?.replace(/^(0\.0\.0\.0|\[::\]):/, '127.0.0.1:');
const gateway = (
input.gateway ||
process.env.MAGPIE_FINGERPRINT_GATEWAY ||
(addr ? `http://${addr}` : 'http://127.0.0.1:3425')
).replace(/\/+$/, '');
const url = new URL(gateway);
if (
!['http:', 'https:'].includes(url.protocol) ||
url.username ||
url.password ||
url.search ||
url.hash ||
(url.pathname !== '/' && url.pathname !== '')
)
throw new Error(
'Gateway must be an HTTP(S) origin without credentials, path, query or fragment.',
);
const port = input.port ?? Number(process.env.MAGPIE_FINGERPRINT_PORT || 3488);
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('Invalid service port.');
return {
port,
gateway,
apiKey: input.apiKey || process.env.MAGPIE_FINGERPRINT_API_KEY || '',
dataDir:
input.dataDir ||
process.env.MAGPIE_FINGERPRINT_DATA_DIR ||
join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'magpie', 'fingerprint'),
bankSource: input.bankSource || process.env.MAGPIE_FINGERPRINT_BANK_SOURCE,
demo: input.demo ?? false,
uiDir: input.uiDir,
};
}
+124
View File
@@ -0,0 +1,124 @@
import type { Analysis, Job, Model, RunConfig } from './types';
import { generateChallenges } from '../vendor/lmfpd-sdk/index.js';
export const demoModels: Model[] = [
{
id: 'anthropic/claude-sonnet-4.6',
name: 'Claude Sonnet 4.6',
provider: 'anthropic',
efforts: ['low', 'medium', 'high'],
nativeEndpoints: ['/v1/messages'],
},
{
id: 'openai/gpt-5.5',
name: 'GPT-5.5',
provider: 'openai',
efforts: ['low', 'medium', 'high'],
nativeEndpoints: ['/v1/responses'],
},
{
id: 'relay/claude-opus-4.7',
name: 'Claude Opus 4.7',
provider: 'relay',
efforts: ['low', 'medium', 'high'],
nativeEndpoints: ['/v1/messages'],
},
{
id: 'google/gemini-3.1-pro',
name: 'Gemini 3.1 Pro',
provider: 'google',
efforts: [],
nativeEndpoints: [],
},
];
export function demoAnalysis(model: string): Analysis {
const id = model.split('/').slice(1).join('/');
const candidates = [id, 'claude-sonnet-4.6', 'gpt-5.4', 'gemini-3.1-pro', 'deepseek-v3.2'].filter(
(v, i, a) => a.indexOf(v) === i,
);
return {
decision: 'scored',
prediction: id,
prediction_name: id,
family_prediction: id.split('-')[0],
family_prediction_name: id.split('-')[0],
results: candidates.map((v, i) => ({
model: v,
display_name: v,
family: v.split('-')[0],
family_name: v.split('-')[0],
score: 1 - i * 0.17,
probability: i === 0 ? 0.87 : 0.13 / (candidates.length - 1),
})),
ranking_score: 1,
probability: 0.87,
probability_status: 'reference_calibrated',
probability_scope: 'Reference bank candidates only (illustrative demo)',
calibration: null,
used_outputs: 3,
diagnostics: [0, 1, 2].map((index) => ({
index,
parsed_numbers: 300,
minimum_numbers: 165,
accepted: true,
raw_out_of_range_count: 0,
})),
sequence: null,
method: 'Illustrative demo; no measurement',
model_version: { base_sha256: 'demo-not-measured' },
evidence: {
insufficient: false,
label: 'Demo',
reason: 'Illustrative data only',
threshold: null,
method: 'demo',
},
};
}
export function demoHistory(): Job {
const createdAt = new Date(Date.now() - 3600_000).toISOString();
const config: RunConfig = {
targets: demoModels.slice(0, 2).map((m) => ({ model: m.id })),
api: 'auto',
effort: '',
serviceTier: 'default',
strict: false,
targetParallel: 1,
sampleParallel: 3,
deadlineSeconds: 300,
};
return {
id: 'demo-example',
createdAt,
finishedAt: createdAt,
state: 'completed',
config,
challenges: generateChallenges(),
bank: { builtAt: 'Demo reference data', sdk: '0.2.0' },
demo: true,
results: config.targets.map((target, i) => ({
id: `demo-${i}`,
target,
api: i ? 'responses' : 'messages',
state: 'completed',
samples: [0, 1, 2].map(() => ({
state: 'complete',
text: '137, 42, 291, 65, 188',
raw_text: '137, 42, 291, 65, 188 (illustrative excerpt)',
count: 300,
expected_count: 300,
first_byte_ms: 650,
response_model: target.model.split('/')[1],
response_id: 'demo',
error: null,
})),
provenance: [0, 1, 2].map((n) => ({
session: `demo-${n}`,
requestedModel: target.model,
provider: target.model.split('/')[0],
model: target.model,
})),
analysis: demoAnalysis(target.model),
error: null,
})),
};
}
+266
View File
@@ -0,0 +1,266 @@
import {
generateChallenges,
requestSample,
type Detector,
type DetectConfig,
type Sample,
} from '../vendor/lmfpd-sdk/index.js';
import type { Api, Challenge, Job, Model, RunConfig, TargetResult } from './types.js';
const APIS: Api[] = ['responses', 'chat_completions', 'messages'];
const SDK_VERSION = '0.2.0';
type SampleRequest = (
config: DetectConfig,
challenge: Challenge,
signal?: AbortSignal,
) => Promise<Sample>;
export interface RunDeps {
detector: Detector;
signal: AbortSignal;
sampleEndpoint: (result: TargetResult, index: number) => { baseUrl: string; apiKey: string };
onUpdate: () => void | Promise<void>;
/** Test hook; production uses the SDK requestSample implementation. */
sample?: SampleRequest;
/** Wait for proxy route/provenance collection after a sample response. */
afterSample?: (result: TargetResult, index: number) => void | Promise<void>;
}
function fail(message: string): never {
throw new Error(message);
}
function validate(config: RunConfig, models: Model[]): void {
if (!Array.isArray(config.targets) || config.targets.length < 1 || config.targets.length > 24)
fail('targets must contain 1 to 24 items');
const keys = config.targets.map((target) => `${target.model}\0${target.account ?? ''}`);
if (new Set(keys).size !== keys.length) fail('duplicate targets are not allowed');
if (
!Number.isInteger(config.targetParallel) ||
config.targetParallel < 1 ||
config.targetParallel > 3
)
fail('targetParallel must be 1 to 3');
if (
!Number.isInteger(config.sampleParallel) ||
config.sampleParallel < 1 ||
config.sampleParallel > 3
)
fail('sampleParallel must be 1 to 3');
if (
!Number.isFinite(config.deadlineSeconds) ||
config.deadlineSeconds < 10 ||
config.deadlineSeconds > 900
)
fail('deadlineSeconds must be 10 to 900');
if (typeof config.effort !== 'string' || config.effort.length > 64)
fail('effort must be at most 64 characters');
if (typeof config.strict !== 'boolean') fail('strict must be boolean');
if (!['default', 'flex', 'fast', 'ultrafast'].includes(config.serviceTier))
fail('unknown service tier');
if (!['auto', ...APIS].includes(config.api)) fail('unknown API');
for (const target of config.targets) {
if (typeof target.model !== 'string' || !target.model.trim()) fail('target model must be text');
if (
target.account !== undefined &&
(typeof target.account !== 'string' || target.account.length > 256)
)
fail('account must be at most 256 characters');
const model = models.find((candidate) => candidate.id === target.model);
if (!model) fail(`unknown model: ${target.model}`);
}
}
function chooseApi(configured: RunConfig['api'], model: Model): Api {
if (configured !== 'auto') return configured;
const endpoints = (model.nativeEndpoints ?? []).map((value) => value.toLowerCase());
for (const api of APIS) {
if (
endpoints.some(
(endpoint) =>
endpoint === api ||
endpoint.includes(`/${api === 'chat_completions' ? 'chat/completions' : api}`) ||
endpoint.includes(api),
)
)
return api;
}
return 'chat_completions';
}
function queuedSample(challenge: Challenge): Sample {
return {
state: 'queued',
text: '',
raw_text: '',
count: 0,
expected_count: challenge.expected_count,
first_byte_ms: null,
response_model: null,
response_id: null,
error: null,
};
}
export function createJob(config: RunConfig, models: Model[], builtAt: string): Job {
validate(config, models);
const normalizedConfig: RunConfig = {
targets: config.targets.map((target) => ({
model: target.model,
...(target.account === undefined ? {} : { account: target.account }),
})),
api: config.api,
effort: config.effort,
serviceTier: config.serviceTier,
strict: config.strict,
targetParallel: config.targetParallel,
sampleParallel: config.sampleParallel,
deadlineSeconds: config.deadlineSeconds,
};
const challenges = generateChallenges(3);
const results: TargetResult[] = normalizedConfig.targets.map((target, index) => {
const model = models.find((candidate) => candidate.id === target.model)!;
return {
id: `target-${index + 1}-${crypto.randomUUID()}`,
target,
api: chooseApi(config.api, model),
state: 'queued',
samples: challenges.map(queuedSample),
provenance: challenges.map(() => ({ session: '', requestedModel: target.model })),
analysis: null,
error: null,
};
});
return {
id: crypto.randomUUID(),
createdAt: new Date().toISOString(),
state: 'queued',
config: normalizedConfig,
challenges,
results,
bank: { builtAt, sdk: SDK_VERSION },
};
}
function cancelledSample(
challenge: Challenge,
message = 'Cancelled. This round was not scored.',
): Sample {
return { ...queuedSample(challenge), state: 'cancelled', error: message };
}
async function update(deps: RunDeps): Promise<void> {
await deps.onUpdate();
}
export async function runJob(job: Job, deps: RunDeps): Promise<void> {
job.state = 'running';
await update(deps);
const sampleFn = deps.sample ?? ((config, challenge) => requestSample(config, challenge));
let cursor = 0;
const targetWorker = async () => {
while (true) {
const index = cursor++;
if (index >= job.results.length) return;
const result = job.results[index];
result.state = 'running';
await update(deps);
let sampleCursor = 0;
const sampleWorker = async () => {
while (true) {
const sampleIndex = sampleCursor++;
if (sampleIndex >= job.challenges.length) return;
const challenge = job.challenges[sampleIndex];
if (deps.signal.aborted) {
result.samples[sampleIndex] = cancelledSample(challenge);
await update(deps);
continue;
}
try {
// Credentials and the proxy route are scoped to each target/challenge.
const endpoint = deps.sampleEndpoint(result, sampleIndex);
const baseConfig: DetectConfig = {
baseUrl: endpoint.baseUrl,
apiKey: endpoint.apiKey,
model: result.target.model,
api: result.api,
effort: job.config.effort,
serviceTier: job.config.serviceTier,
strict: job.config.strict,
count: 3,
parallel: 1,
stream: true,
};
result.samples[sampleIndex] = { ...result.samples[sampleIndex], state: 'waiting' };
await update(deps);
const sample = await sampleFn(baseConfig, challenge, deps.signal);
result.samples[sampleIndex] = sample;
if (deps.afterSample) await deps.afterSample(result, sampleIndex);
await update(deps);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
result.samples[sampleIndex] = {
...result.samples[sampleIndex],
state: deps.signal.aborted ? 'cancelled' : 'failed',
error: message,
};
result.error ??= message;
await update(deps);
}
}
};
await Promise.all(
Array.from(
{ length: Math.min(job.config.sampleParallel, job.challenges.length) },
sampleWorker,
),
);
const cancelled = result.samples.some((sample) => sample.state === 'cancelled');
const aborted = deps.signal.aborted;
const mismatch = result.provenance.some((item) => item.mismatch);
const scoreable = result.samples.filter(
(sample) =>
sample.state === 'complete' || (!job.config.strict && sample.state === 'truncated'),
);
const strictInvalid =
job.config.strict &&
(result.samples.length !== 3 ||
result.samples.some((sample) => sample.state !== 'complete'));
if (!aborted && !cancelled && !mismatch && !strictInvalid && scoreable.length > 0) {
result.analysis = deps.detector.analyze(
scoreable.map((sample) => ({ text: sample.text, expected_count: sample.expected_count })),
{ strict: job.config.strict },
);
} else if (aborted || cancelled) {
result.error =
deps.signal.reason instanceof Error
? deps.signal.reason.message
: 'Cancelled. This round was not scored.';
} else if (mismatch) {
result.error =
'Provider/model response does not match the requested target; result was not scored.';
} else if (strictInvalid) {
result.error = 'Strict mode requires three complete, untruncated samples.';
}
result.state =
aborted || cancelled
? 'cancelled'
: mismatch || result.samples.some((sample) => sample.state === 'failed') || strictInvalid
? 'failed'
: 'completed';
await update(deps);
}
};
await Promise.all(
Array.from({ length: Math.min(job.config.targetParallel, job.results.length) }, targetWorker),
);
job.finishedAt = new Date().toISOString();
if (deps.signal.aborted || job.results.some((result) => result.state === 'cancelled')) {
job.state = 'cancelled';
if (deps.signal.aborted)
job.error = deps.signal.reason instanceof Error ? deps.signal.reason.message : 'Cancelled';
} else if (job.results.some((result) => result.state === 'failed')) job.state = 'failed';
else job.state = 'completed';
await update(deps);
}
+114
View File
@@ -0,0 +1,114 @@
import type { Account, Model, Provenance } from './types';
import { boundedText } from './http';
export class Gateway {
constructor(
readonly url: string,
private key = '',
) {}
headers(extra: Record<string, string> = {}) {
return {
'content-type': 'application/json',
...(this.key ? { authorization: `Bearer ${this.key}` } : {}),
...extra,
};
}
redact(message: unknown) {
return String(message instanceof Error ? message.message : message)
.replaceAll(this.key || '\u0000', '[redacted]')
.slice(0, 500);
}
async catalog(): Promise<{ models: Model[]; accounts: Account[] }> {
const res = await fetch(`${this.url}/v1/models`, {
headers: this.headers(),
signal: AbortSignal.timeout(5000),
redirect: 'error',
});
if (!res.ok) {
await res.body?.cancel();
throw new Error(`Magpie model catalog returned HTTP ${res.status}.`);
}
const data = JSON.parse(await boundedText(res, 4 * 1024 * 1024)) as {
data?: Record<string, any>[];
};
const models = (data.data || [])
.filter((m) => {
if (typeof m.id !== 'string' || !m.id.includes('/') || m.id.startsWith('group/'))
return false;
if (/^(embedding|image|audio)(_|$)/.test(m.type || '')) return false;
if (Array.isArray(m.modalities?.output) && !m.modalities.output.includes('text'))
return false;
const native = Array.isArray(m.native_endpoints) ? m.native_endpoints : [];
return (
!native.length ||
!native.every(
(endpoint: unknown) =>
typeof endpoint === 'string' && /\/(images|embeddings|audio)\b/.test(endpoint),
)
);
})
.map((m) => ({
id: m.id,
name: String(m.display_name || m.name || m.id),
provider: m.id.split('/')[0],
efforts: (Array.isArray(m.reasoning_levels)
? m.reasoning_levels
: (m.supported_reasoning_levels || []).map((v: any) => v.effort)
).filter((v: unknown) => typeof v === 'string'),
nativeEndpoints: Array.isArray(m.native_endpoints)
? m.native_endpoints.filter((v: unknown) => typeof v === 'string')
: [],
}));
// kept=1 reads Magpie's cached report; opening this page must never probe
// upstream accounts just to populate a selector.
const accounts: Account[] = [];
try {
const quotas = await fetch(`${this.url}/v1/magpie/quotas?kept=1`, {
headers: this.headers(),
signal: AbortSignal.timeout(2500),
redirect: 'error',
});
if (quotas.ok) {
const report = JSON.parse(await boundedText(quotas, 1024 * 1024));
for (const item of report.data || [])
if (
typeof item.provider === 'string' &&
typeof item.user === 'string' &&
item.user &&
(!item.kind || item.kind === 'subscription')
) {
if (!accounts.some((a) => a.provider === item.provider && a.id === item.user))
accounts.push({
id: item.user,
name: String(item.name || item.user),
provider: item.provider,
});
}
} else {
await quotas.body?.cancel();
}
} catch {
/* Account enumeration is optional and may be denied by a scoped key. */
}
return { models, accounts };
}
async route(provenance: Provenance) {
try {
const res = await fetch(
`${this.url}/v1/magpie/route?session=${encodeURIComponent(provenance.session)}`,
{ headers: this.headers(), signal: AbortSignal.timeout(2500), redirect: 'error' },
);
if (!res.ok) {
await res.body?.cancel();
throw new Error(`Route metadata HTTP ${res.status}`);
}
provenance.route = JSON.parse(await boundedText(res, 256 * 1024));
const route = (provenance.route as any)?.route ?? (provenance.route as any);
if (route?.model && typeof route.model === 'string') {
provenance.model ??= route.model;
if (route.model !== provenance.requestedModel) provenance.mismatch = true;
}
} catch (e) {
provenance.routeError = this.redact(e);
}
}
}
+27
View File
@@ -0,0 +1,27 @@
export class BodyTooLargeError extends Error {}
/** Read a body incrementally so chunked requests cannot bypass size limits. */
export async function boundedText(input: Request | Response, limit: number) {
if (Number(input.headers.get('content-length') || 0) > limit) {
await input.body?.cancel();
throw new BodyTooLargeError('Body exceeds the size limit.');
}
if (!input.body) return '';
const reader = input.body.getReader();
const chunks: Uint8Array[] = [];
let bytes = 0;
try {
while (true) {
const part = await reader.read();
if (part.done) break;
bytes += part.value.byteLength;
if (bytes > limit) {
await reader.cancel();
throw new BodyTooLargeError('Body exceeds the size limit.');
}
chunks.push(part.value);
}
return Buffer.concat(chunks).toString('utf8');
} finally {
reader.releaseLock();
}
}
@@ -0,0 +1,89 @@
import { options, type Options } from './config';
import { boundedText } from './http';
import { startServer } from './server';
import { serviceIdentity } from './service-identity';
/** Hosts with identical settings share one listener. An attached host takes over
* when its owner exits; no detached daemon survives the Magpie hosts. */
export async function startManagedService(input: Options = {}, pollMs = 1000) {
const opt = options(input);
const identity = serviceIdentity(opt);
let owned: Awaited<ReturnType<typeof startServer>> | undefined;
let closed = false;
let checking: Promise<void> | undefined;
let lastError = '';
const probe = async () => {
if (!opt.port) return false;
let response: Response;
try {
response = await fetch(`http://127.0.0.1:${opt.port}/_fingerprint/health`, {
signal: AbortSignal.timeout(1000),
redirect: 'error',
});
} catch {
return false;
}
try {
const peer = JSON.parse(await boundedText(response, 4096));
if (
response.ok &&
peer.app === identity.app &&
peer.protocol === identity.protocol &&
peer.configuration === identity.configuration
)
return true;
} catch {
/* An occupied port is never assumed to be our service. */
}
throw new Error(
`Port ${opt.port} belongs to an incompatible Fingerprint service or another application. Use another port, or turn Fingerprint off and on after upgrading.`,
);
};
const acquire = async () => {
if (closed || owned || (await probe())) return;
try {
owned = await startServer(opt);
} catch (error) {
// Another host may have won between discovery and bind.
if ((error as NodeJS.ErrnoException).code === 'EADDRINUSE' && (await probe())) return;
throw error;
}
if (closed) {
await owned.close();
owned = undefined;
}
};
const reconcile = () =>
(checking ??= acquire().finally(() => {
checking = undefined;
}));
await reconcile();
const timer = setInterval(() => {
void reconcile()
.then(() => {
lastError = '';
})
.catch((error) => {
const message = error instanceof Error ? error.message : String(error);
if (message !== lastError) console.warn(`Fingerprint service recovery: ${message}`);
lastError = message;
});
}, pollMs);
timer.unref();
return {
get port() {
return owned?.port ?? opt.port;
},
get role() {
return owned ? ('owner' as const) : ('attached' as const);
},
async close() {
if (closed) return;
closed = true;
clearInterval(timer);
await checking;
await owned?.close();
owned = undefined;
},
};
}
+14
View File
@@ -0,0 +1,14 @@
import { startManagedService } from './managed-service';
import type { Options } from './config';
let instance: ReturnType<typeof startManagedService> | undefined;
export default {
id: 'magpie-fingerprint',
server: async (_input: unknown, opts: Options = {}) => {
instance ??= startManagedService(opts).catch((error) => {
instance = undefined;
throw error;
});
await instance;
return {};
},
};
+737
View File
@@ -0,0 +1,737 @@
import { randomBytes, timingSafeEqual } from 'node:crypto';
import { readFile, mkdir, rename, unlink, access } from 'node:fs/promises';
import { join, resolve, extname } from 'node:path';
import { loadDetector, parseNumbers, type Detector } from '../vendor/lmfpd-sdk/index.js';
import { options, type Options } from './config';
import { Gateway } from './gateway';
import { Store } from './store';
import { boundedText, BodyTooLargeError } from './http';
import { normalizeChatStream } from './sse';
import { serviceIdentity, VERSION } from './service-identity';
import { createJob, runJob } from './detector';
import { demoModels, demoHistory, demoAnalysis } from './demo';
import type { Job, Model, Provenance, TargetResult, RunConfig } from './types';
const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
const json = (data: unknown, status = 200, headers: HeadersInit = {}) =>
Response.json(data, { status, headers });
const equal = (a: string, b: string) =>
a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
const isTerminal = (job: Job) => !['queued', 'running'].includes(job.state);
const uuid = () => crypto.randomUUID();
type SampleTicket = {
job: Job;
result: TargetResult;
index: number;
secret: string;
controller: AbortController;
used: boolean;
done: Promise<void>;
finish: () => void;
};
export async function startServer(input: Options = {}) {
const opt = options(input);
const gateway = new Gateway(opt.gateway, opt.apiKey);
const store = new Store(join(opt.dataDir, opt.demo ? 'demo-jobs' : 'jobs'));
const token = randomBytes(32).toString('hex');
const active = new Map<string, AbortController>();
const tickets = new Map<string, SampleTicket>();
const listeners = new Map<string, Set<(job: Job) => void>>();
let detector: Detector | undefined,
bankError = '',
loading: Promise<Detector | undefined> | undefined;
let models: Model[] = [],
catalogError = '';
let closed = false,
creatingJob = false;
let modelCount: number | undefined;
const emit = (job: Job) => {
for (const fn of listeners.get(job.id) || []) fn(job);
};
const persist = async (job: Job) => {
emit(job);
await store.save(job);
};
async function ensureDetector(force = false) {
if (opt.demo) return undefined;
if (detector && !force) return detector;
if (loading) return loading;
loading = (async () => {
try {
await mkdir(opt.dataDir, { recursive: true, mode: 0o700 });
const cache = join(
opt.dataDir,
force && (!opt.bankSource || /^https?:\/\//i.test(opt.bankSource))
? `reference-refresh-${uuid()}.bin`
: 'reference.bin',
);
try {
const next = await loadDetector({
...(opt.bankSource ? { source: opt.bankSource } : {}),
cache,
// Cached data never schedules the SDK's background refresh.
// Only an explicit download action replaces the cached snapshot.
ttl: Infinity,
});
if (force && cache !== join(opt.dataDir, 'reference.bin'))
await rename(cache, join(opt.dataDir, 'reference.bin'));
detector = next;
try {
const bytes = await readFile(join(opt.dataDir, 'reference.bin'));
modelCount = JSON.parse(bytes.subarray(4, 4 + bytes.readUInt32LE(0)).toString()).models
?.length;
} catch {
/* Local reference directories need no downloaded cache. */
}
} finally {
if (force && cache !== join(opt.dataDir, 'reference.bin'))
await unlink(cache).catch(() => {});
}
bankError = '';
return detector;
} catch (e) {
bankError = gateway.redact(e);
return undefined;
} finally {
loading = undefined;
}
})();
return loading;
}
function bankInfo() {
return opt.demo
? { builtAt: 'Demo reference data', modelCount: 64 }
: detector
? { builtAt: detector.builtAt, modelCount }
: null;
}
async function bankStatus() {
if (opt.demo || detector) return { state: 'ready' as const };
const localSource = opt.bankSource && !/^https?:\/\//i.test(opt.bankSource);
const file = localSource
? join(opt.bankSource!, 'unified_bank.json')
: join(opt.dataDir, 'reference.bin');
const cached = await access(file).then(
() => true,
() => false,
);
return { state: cached ? ('cached' as const) : ('missing' as const) };
}
async function catalog() {
if (opt.demo) {
models = demoModels;
return { models, accounts: [] };
}
try {
const result = await gateway.catalog();
models = result.models;
catalogError = '';
return result;
} catch (e) {
catalogError = gateway.redact(e);
return { models: [], accounts: [] };
}
}
// The SDK talks only to this private, one-shot, job-bound transport. It is
// never exposed through Magpie's page service and cannot select a URL/model.
const transport = Bun.serve({
hostname: '127.0.0.1',
port: 0,
idleTimeout: 0,
async fetch(req) {
const url = new URL(req.url);
if (req.headers.get('host') !== url.host || url.hostname !== '127.0.0.1')
return new Response('Forbidden', { status: 403 });
const match = url.pathname.match(
/^\/sample\/([\w-]+)\/v1\/(responses|chat\/completions|messages)$/,
);
const ticket = match ? tickets.get(match[1]) : undefined;
if (!ticket || req.method !== 'POST' || ticket.used || ticket.controller.signal.aborted)
return new Response('Unknown sample', { status: 404 });
const key =
req.headers.get('authorization')?.replace(/^Bearer /, '') ||
req.headers.get('x-api-key') ||
'';
if (!equal(key, ticket.secret)) return new Response('Unauthorized', { status: 401 });
ticket.used = true;
const { job, result, index, controller } = ticket;
const provenance: Provenance = {
session: `fp-${uuid()}`,
requestedModel: result.target.model,
};
result.provenance[index] = provenance;
let finishing: Promise<void> | undefined;
const finish = () =>
(finishing ??= (async () => {
try {
await gateway.route(provenance);
emit(job);
} finally {
ticket.finish();
}
})());
try {
const payload = await boundedText(req, 16384);
if (payload.length > 16384) throw new Error('Sample request too large.');
const body = JSON.parse(payload);
if (body.model !== result.target.model)
throw new Error('Sample model does not match its job.');
const expected = {
responses: 'responses',
chat_completions: 'chat/completions',
messages: 'messages',
}[result.api];
if (match![2] !== expected) throw new Error('Sample protocol does not match its job.');
const startedAt = Date.now();
const headers = gateway.headers({
'X-Magpie-Session': provenance.session,
...(result.target.account ? { 'X-Magpie-Account': result.target.account } : {}),
});
for (const name of ['anthropic-version', 'anthropic-beta', 'accept']) {
const value = req.headers.get(name);
if (value) (headers as Record<string, string>)[name] = value;
}
const upstream = await fetch(`${gateway.url}/v1/${expected}`, {
method: 'POST',
headers,
body: payload,
signal: controller.signal,
redirect: 'error',
timeout: false,
});
provenance.provider = upstream.headers.get('X-Magpie-Provider') || undefined;
provenance.model = upstream.headers.get('X-Magpie-Model') || undefined;
provenance.mismatch = !!(
(provenance.model && provenance.model !== result.target.model) ||
(provenance.provider && provenance.provider !== result.target.model.split('/')[0])
);
if (!upstream.ok || !upstream.body) {
await upstream.body?.cancel();
await finish();
return json(
{
error: {
message: `Magpie returned HTTP ${upstream.status}. Inspect Magpie's request log for details.`,
},
},
upstream.ok ? 502 : upstream.status,
);
}
let ended = false,
text = '',
lineBuffer = '',
totalBytes = 0;
const responseBody =
result.api === 'chat_completions' &&
upstream.headers.get('content-type')?.includes('text/event-stream')
? normalizeChatStream(upstream.body, () => {
provenance.streamNormalization = 'chat-done-after-stop';
})
: upstream.body;
const reader = responseBody.getReader();
let lastEmit = 0;
const decoder = new TextDecoder();
const recordChunk = (bytes: Uint8Array) => {
const sample = result.samples[index];
if (!sample) return;
totalBytes += bytes.byteLength;
if (totalBytes > 2 * 1024 * 1024)
throw new Error('Sample exceeded the 2 MiB response limit.');
sample.state = 'streaming';
sample.first_byte_ms ??= Date.now() - startedAt;
lineBuffer += decoder.decode(bytes, { stream: true });
let newline: number;
while ((newline = lineBuffer.indexOf('\n')) >= 0) {
const line = lineBuffer.slice(0, newline).trim();
lineBuffer = lineBuffer.slice(newline + 1);
if (!line.startsWith('data:')) continue;
try {
const event = JSON.parse(line.slice(5));
const delta =
event.choices?.[0]?.delta?.content ??
(event.type === 'response.output_text.delta' ? event.delta : undefined) ??
(event.type === 'content_block_delta' ? event.delta?.text : undefined);
if (typeof delta === 'string') text += delta;
} catch {
/* SSE metadata and [DONE] are not sample text. */
}
}
if (text.length > 100000 || lineBuffer.length > 100000)
throw new Error('Sample text exceeded the response limit.');
sample.raw_text = text;
sample.count = parseNumbers(text).length;
if (Date.now() - lastEmit > 150) {
lastEmit = Date.now();
emit(job);
}
};
const stream = new ReadableStream<Uint8Array>({
async pull(out) {
try {
const chunk = await reader.read();
if (chunk.done) {
ended = true;
await finish();
out.close();
} else {
recordChunk(chunk.value);
out.enqueue(chunk.value);
}
} catch (e) {
await reader.cancel().catch(() => {});
if (!ended) {
ended = true;
await finish();
}
out.error(e);
}
},
async cancel() {
if (!ended) {
ended = true;
await reader.cancel().catch(() => {});
await finish();
}
},
});
return new Response(stream, {
headers: {
'content-type': upstream.headers.get('content-type') || 'text/event-stream',
'cache-control': 'no-store',
},
});
} catch (e) {
await finish();
return json(
{
error: {
message: controller.signal.aborted
? 'Detection cancelled or deadline exceeded.'
: gateway.redact(e),
},
},
502,
);
}
},
});
async function launch(job: Job, engine?: Detector) {
const controller = new AbortController();
active.set(job.id, controller);
const timer = setTimeout(
() => controller.abort(new Error('Job deadline exceeded')),
job.config.deadlineSeconds * 1000,
);
try {
if (opt.demo) {
job.demo = true;
job.state = 'running';
await persist(job);
for (const r of job.results) {
r.state = 'running';
for (let i = 0; i < 3; i++) {
if (controller.signal.aborted) break;
r.samples[i] = {
state: 'streaming',
text: '',
raw_text: '',
count: 0,
expected_count: job.challenges[i].expected_count,
first_byte_ms: 650,
response_model: r.target.model.split('/')[1],
response_id: 'demo',
error: null,
};
emit(job);
await Bun.sleep(350);
r.samples[i] = {
...r.samples[i],
state: 'complete',
text: '137, 42, 291, 65, 188',
raw_text: '137, 42, 291, 65, 188 (illustrative excerpt)',
count: job.challenges[i].expected_count,
};
r.provenance[i] = {
session: `demo-${i}`,
requestedModel: r.target.model,
model: r.target.model,
provider: r.target.model.split('/')[0],
};
emit(job);
}
r.state = controller.signal.aborted ? 'cancelled' : 'completed';
r.analysis = controller.signal.aborted ? null : demoAnalysis(r.target.model);
await persist(job);
if (controller.signal.aborted) break;
}
job.state = controller.signal.aborted ? 'cancelled' : 'completed';
job.finishedAt = new Date().toISOString();
} else {
if (!engine) throw new Error(bankError || 'Reference data is not loaded.');
await runJob(job, {
detector: engine,
signal: controller.signal,
sampleEndpoint: (result, index) => {
const id = uuid();
let finish!: () => void;
const done = new Promise<void>((r) => {
finish = r;
});
const ticket: SampleTicket = {
job,
result,
index,
secret: randomBytes(32).toString('hex'),
controller,
used: false,
done,
finish,
};
tickets.set(id, ticket);
return {
baseUrl: `http://127.0.0.1:${transport.port}/sample/${id}/v1`,
apiKey: ticket.secret,
};
},
afterSample: async (result, index) => {
const entry = [...tickets.values()].find(
(t) => t.job === job && t.result === result && t.index === index,
);
if (entry?.used) await Promise.race([entry.done, Bun.sleep(3500)]);
},
onUpdate: () => persist(job),
});
}
} catch (e) {
job.state = controller.signal.aborted ? 'cancelled' : 'failed';
job.error = gateway.redact(e);
job.finishedAt = new Date().toISOString();
} finally {
clearTimeout(timer);
active.delete(job.id);
if (controller.signal.aborted && !job.error)
job.error = errorText(controller.signal.reason || 'Cancelled');
for (const [id, t] of tickets)
if (t.job === job) {
t.finish();
tickets.delete(id);
}
for (const r of job.results)
if (r.state === 'running' || r.state === 'queued') {
r.state = 'cancelled';
r.analysis = null;
}
await persist(job);
}
}
const uiDir =
opt.uiDir || resolve(import.meta.dir, import.meta.dir.endsWith('/src') ? '../dist/ui' : 'ui');
let server: ReturnType<typeof Bun.serve>;
let initialized = Promise.resolve();
try {
server = Bun.serve({
hostname: '127.0.0.1',
port: opt.port,
idleTimeout: 0,
async fetch(req) {
const url = new URL(req.url);
const own = `127.0.0.1:${server.port}`;
const host = req.headers.get('host');
if (host !== own && host !== `localhost:${server.port}`)
return new Response('Invalid host', { status: 403 });
const origin = req.headers.get('origin');
if (
origin &&
origin !== 'null' &&
origin !== `http://${own}` &&
origin !== `http://localhost:${server.port}`
)
return new Response('Invalid origin', { status: 403 });
const cors: Record<string, string> = {
'access-control-allow-origin': origin || '*',
'access-control-allow-headers': 'Authorization, Content-Type',
'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
vary: 'Origin',
'cache-control': 'no-store',
};
if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: cors });
if (url.pathname === '/_fingerprint/health' && req.method === 'GET')
return json(serviceIdentity(opt), 200, cors);
await initialized;
const api = url.pathname.startsWith('/api/');
if (api && !equal(req.headers.get('authorization')?.replace(/^Bearer /, '') || '', token))
return json({ error: 'Unauthorized' }, 401, cors);
try {
let response: Response;
if (api) {
const path = url.pathname;
if (path === '/api/bootstrap' && req.method === 'GET') {
const cat = await catalog();
response = json({
version: VERSION,
demo: opt.demo,
...cat,
jobs: store.list(),
bank: bankInfo(),
bankStatus: await bankStatus(),
gateway: {
url: opt.gateway,
reachable: opt.demo || !catalogError,
...(catalogError ? { error: catalogError } : {}),
},
...(bankError ? { bankError } : {}),
});
} else if (path === '/api/models' && req.method === 'GET')
response = json(await catalog());
else if (path === '/api/jobs' && req.method === 'GET') response = json(store.list());
else if (path === '/api/jobs' && req.method === 'POST') {
if (active.size || creatingJob)
return json({ error: 'A detection batch is already running.' }, 409, cors);
creatingJob = true;
try {
if (store.jobs.size >= 200)
return json(
{
error:
'History limit reached (200 batches). Export and delete older batches first.',
},
409,
cors,
);
if (Number(req.headers.get('content-length') || 0) > 16384)
return json({ error: 'Request too large' }, 413, cors);
const text = await boundedText(req, 16384);
const config = JSON.parse(text) as RunConfig;
await catalog();
// Reject malformed targets before allowing any reference download.
const job = createJob(config, models, '');
const engine = await ensureDetector();
if (!opt.demo && !engine)
return json({ error: bankError || 'Reference data unavailable' }, 503, cors);
job.bank.builtAt = opt.demo ? 'Demo reference data' : engine!.builtAt;
if (opt.demo) job.demo = true;
store.jobs.set(job.id, job);
await store.save(job);
void launch(job, engine).catch((e) => {
job.state = 'failed';
job.error = `Could not save task history: ${gateway.redact(e)}`;
emit(job);
});
response = json(job, 202);
} finally {
creatingJob = false;
}
} else if (
(path === '/api/bank/download' || path === '/api/reload-data') &&
req.method === 'POST'
) {
await ensureDetector(true);
response = json(
{
bank: bankInfo(),
bankStatus: await bankStatus(),
error: bankError || undefined,
},
bankError ? 503 : 200,
);
} else {
const m = path.match(/^\/api\/jobs\/([\w-]+)(?:\/(cancel|events|export))?$/);
const job = m ? store.jobs.get(m[1]) : undefined;
if (!job) return json({ error: 'Job not found' }, 404, cors);
if (m![2] === 'cancel' && req.method === 'POST') {
active.get(job.id)?.abort(new Error('Cancelled by user'));
response = json(job);
} else if (m![2] === 'export' && req.method === 'GET')
response = new Response(
JSON.stringify({ schema: 'magpie-fingerprint/v1', ...job }, null, 2),
{
headers: {
'content-type': 'application/json',
'content-disposition': `attachment; filename="fingerprint-${job.id}.json"`,
},
},
);
else if (m![2] === 'events' && req.method === 'GET') {
if ((listeners.get(job.id)?.size || 0) >= 6)
return json({ error: 'Too many event subscribers.' }, 429, cors);
const encoder = new TextEncoder();
let release = () => {};
const stream = new ReadableStream<Uint8Array>({
start(out) {
let finished = false;
let beat: ReturnType<typeof setInterval> | undefined;
const send = (j: Job) => {
if (finished || ((out.desiredSize ?? 0) <= 0 && !isTerminal(j))) return;
try {
out.enqueue(
encoder.encode(`event: snapshot\ndata: ${JSON.stringify(j)}\n\n`),
);
if (isTerminal(j)) {
finished = true;
release();
out.close();
}
} catch {
finished = true;
release();
}
};
const set = listeners.get(job.id) || new Set();
set.add(send);
listeners.set(job.id, set);
release = () => {
if (beat) clearInterval(beat);
set.delete(send);
if (!set.size) listeners.delete(job.id);
};
beat = setInterval(() => {
if (!finished && (out.desiredSize ?? 0) > 0)
try {
out.enqueue(encoder.encode(': heartbeat\n\n'));
} catch {
finished = true;
release();
}
}, 15000);
req.signal.addEventListener(
'abort',
() => {
finished = true;
release();
try {
out.close();
} catch {}
},
{ once: true },
);
send(job);
},
cancel() {
release();
},
});
response = new Response(stream, {
headers: {
'content-type': 'text/event-stream',
'x-accel-buffering': 'no',
},
});
} else if (!m![2] && req.method === 'GET') response = json(job);
else if (!m![2] && req.method === 'DELETE') {
if (active.has(job.id))
return json({ error: 'Cancel the running batch before deleting it.' }, 409, cors);
await store.remove(job.id);
response = json({ ok: true });
} else response = json({ error: 'Method not allowed' }, 405);
}
for (const [k, v] of Object.entries(cors)) response.headers.set(k, v);
return response;
}
if (req.method !== 'GET' && req.method !== 'HEAD')
return new Response('Method not allowed', { status: 405 });
if (url.pathname === '/' || url.pathname === '/index.html') {
const uiOrigin = url.searchParams.get('uiOrigin');
if (uiOrigin) {
const parsed = new URL(uiOrigin);
if (
!['http:', 'https:'].includes(parsed.protocol) ||
parsed.hostname.includes('*') ||
parsed.origin !== uiOrigin
)
throw new Error('Invalid UI origin.');
}
const connectSources = [
...new Set([`http://${host}`, ...(uiOrigin ? [uiOrigin] : [])]),
];
let html = await readFile(join(uiDir, 'index.html'), 'utf8').catch(
() =>
'<!doctype html><title>Build required</title><p>Run bun run build to create the Fingerprint interface.</p>',
);
const boot = JSON.stringify({
token,
initialProvider: url.searchParams.get('provider') || '',
theme: url.searchParams.get('theme') || '',
lang: url.searchParams.get('lang') || '',
}).replaceAll('<', '\\u003c');
const nonce = randomBytes(16).toString('base64');
html = html.replace(
'</head>',
`<script nonce="${nonce}">window.__FINGERPRINT__=${boot}</script></head>`,
);
return new Response(html, {
headers: {
'content-type': 'text/html; charset=utf-8',
'cache-control': 'no-store',
'referrer-policy': 'no-referrer',
'x-content-type-options': 'nosniff',
// Opaque sandbox origins cannot reliably match 'self'. The
// launcher supplies the HTTP(S) origin of Magpie's proxy;
// it affects this document's CSP only, never API admission.
'content-security-policy': `default-src 'self'; connect-src 'self' ${connectSources.join(' ')}; script-src 'self' 'nonce-${nonce}'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; object-src 'none'; base-uri 'none'; form-action 'none'`,
},
});
}
const decoded = decodeURIComponent(url.pathname);
const file = resolve(uiDir, `.${decoded}`);
if (!file.startsWith(`${resolve(uiDir)}/`) || decoded.includes('..'))
return new Response('Not found', { status: 404 });
const asset = Bun.file(file);
if (!(await asset.exists())) return new Response('Not found', { status: 404 });
const mime: Record<string, string> = {
'.js': 'text/javascript',
'.css': 'text/css',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.woff2': 'font/woff2',
};
return new Response(asset, {
headers: {
'content-type': mime[extname(file)] || 'application/octet-stream',
'access-control-allow-origin': '*',
'x-content-type-options': 'nosniff',
},
});
} catch (e) {
return json(
{ error: gateway.redact(e) },
e instanceof BodyTooLargeError ? 413 : 400,
cors,
);
}
},
});
} catch (e) {
transport.stop(true);
throw e;
}
initialized = (async () => {
// Only the process that owns the listening port may repair persisted jobs.
await store.load();
if (opt.demo && !store.jobs.size) {
const job = demoHistory();
store.jobs.set(job.id, job);
}
})();
try {
await initialized;
} catch (error) {
server.stop(true);
transport.stop(true);
throw error;
}
return {
port: server.port,
demo: opt.demo,
async close() {
if (closed) return;
closed = true;
for (const c of active.values()) c.abort(new Error('Plugin service stopped'));
while (active.size) await Bun.sleep(20);
await store.flush();
server.stop(true);
transport.stop(true);
},
};
}
@@ -0,0 +1,105 @@
import { createHmac, randomBytes } from 'node:crypto';
import {
chmodSync,
closeSync,
fsyncSync,
linkSync,
mkdirSync,
openSync,
readFileSync,
rmSync,
writeSync,
} from 'node:fs';
import { join, resolve } from 'node:path';
import { options, type Options } from './config';
export const VERSION = '0.2.0';
// The health endpoint is public, so the configuration digest must not be a
// plain hash of a low-entropy gateway key. Keep the salt beside the install's
// data, while retaining an in-process fallback for read-only or unavailable
// data directories.
const SALT_FILE = '.service-identity-salt';
const SALT_BYTES = 32;
const salts = new Map<string, Buffer>();
const readSalt = (path: string) => {
try {
const salt = readFileSync(path);
return salt.length === SALT_BYTES ? salt : undefined;
} catch {
return undefined;
}
};
const writeSalt = (path: string, salt: Buffer) => {
let fd: number | undefined;
const temporary = `${path}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
try {
// Publish only after the complete salt is fsynced. A competing process
// either sees no file or the complete 32-byte file, never an empty one.
fd = openSync(temporary, 'wx', 0o600);
let offset = 0;
while (offset < salt.length) offset += writeSync(fd, salt, offset);
fsyncSync(fd);
closeSync(fd);
fd = undefined;
// linkSync is atomic and never replaces a salt another process published.
linkSync(temporary, path);
return true;
} catch {
return false;
} finally {
if (fd !== undefined) closeSync(fd);
rmSync(temporary, { force: true });
}
};
function identitySalt(dataDir: string) {
const directory = resolve(dataDir);
const cached = salts.get(directory);
if (cached) return cached;
const path = join(directory, SALT_FILE);
let salt = readSalt(path);
if (!salt) {
try {
mkdirSync(directory, { recursive: true, mode: 0o700 });
salt = readSalt(path);
if (!salt) {
const candidate = randomBytes(SALT_BYTES);
if (writeSalt(path, candidate)) salt = readSalt(path) || candidate;
else salt = readSalt(path);
}
if (salt) chmodSync(path, 0o600);
} catch {
// A read-only or inaccessible data directory cannot persist a salt.
// Keep one random value in memory so health and managed probes agree.
}
}
salt ??= randomBytes(SALT_BYTES);
salts.set(directory, salt);
return salt;
}
export function serviceIdentity(input: Options = {}) {
const opt = options(input);
const configuration = {
gateway: opt.gateway,
apiKey: opt.apiKey,
dataDir: resolve(opt.dataDir),
bankSource: opt.bankSource || null,
demo: opt.demo,
uiDir: opt.uiDir ? resolve(opt.uiDir) : null,
};
return {
app: 'magpie-fingerprint',
protocol: 1,
version: VERSION,
// HMAC keeps the public digest from being an offline API-key oracle while
// preserving exact matching when the key changes.
configuration: createHmac('sha256', identitySalt(opt.dataDir))
.update(JSON.stringify(configuration))
.digest('hex'),
};
}
+60
View File
@@ -0,0 +1,60 @@
/** Preserve upstream bytes; supply the SDK's sentinel only after an explicit
* successful finish and a clean EOF. Some OpenAI-compatible gateways omit it. */
export function normalizeChatStream(
body: ReadableStream<Uint8Array>,
onRepair: () => void,
): ReadableStream<Uint8Array> {
const decoder = new TextDecoder();
let buffer = '',
finish = '',
done = false,
invalid = false;
const frame = (value: string) => {
const data = value
.split(/\r\n|\r|\n/)
.filter((line) => line.startsWith('data:'))
.map((line) => line.slice(5).replace(/^ /, ''))
.join('\n');
if (!data) return;
if (data.trim() === '[DONE]') {
done = true;
return;
}
try {
const event = JSON.parse(data);
if (event.error || event.type === 'error') invalid = true;
const choice =
event.choices?.find((c: { index?: number }) => c.index === 0) ?? event.choices?.[0];
if (choice?.delta?.refusal) invalid = true;
if (choice?.finish_reason) finish = choice.finish_reason;
} catch {
invalid = true;
}
};
const consume = () => {
let boundary: RegExpExecArray | null;
while ((boundary = /\r\n\r\n|\n\n|\r\r/.exec(buffer))) {
frame(buffer.slice(0, boundary.index));
buffer = buffer.slice(boundary.index + boundary[0].length);
}
if (buffer.length > 100000) throw new Error('SSE frame exceeded the response limit.');
};
return body.pipeThrough(
new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, out) {
buffer += decoder.decode(chunk, { stream: true });
consume();
out.enqueue(chunk);
},
flush(out) {
buffer += decoder.decode();
consume();
if (buffer.trim()) frame(buffer);
if (!done && !invalid && finish === 'stop') {
onRepair();
out.enqueue(new TextEncoder().encode('\n\ndata: [DONE]\n\n'));
}
},
}),
);
}
+54
View File
@@ -0,0 +1,54 @@
import { mkdir, readdir, readFile, rename, writeFile, unlink } from 'node:fs/promises';
import { join } from 'node:path';
import type { Job } from './types';
export class Store {
readonly jobs = new Map<string, Job>();
private writing = Promise.resolve();
constructor(readonly dir: string) {}
async load() {
await mkdir(this.dir, { recursive: true, mode: 0o700 });
for (const name of await readdir(this.dir)) {
if (!/^[\w-]+\.json$/.test(name)) continue;
try {
const job = JSON.parse(await readFile(join(this.dir, name), 'utf8')) as Job;
if (!job.id || !Array.isArray(job.results) || name !== `${job.id}.json`) continue;
if (job.state === 'running' || job.state === 'queued') {
job.state = 'interrupted';
job.error = 'The plugin service restarted before this job finished.';
job.finishedAt = new Date().toISOString();
for (const r of job.results)
if (r.state === 'running' || r.state === 'queued') {
r.state = 'cancelled';
r.analysis = null;
}
await this.save(job);
}
this.jobs.set(job.id, job);
} catch {
/* Ignore damaged files; never replace them with invented results. */
}
}
}
list() {
return [...this.jobs.values()].sort((a, b) => b.createdAt.localeCompare(a.createdAt));
}
save(job: Job) {
const contents = JSON.stringify(job);
const path = join(this.dir, `${job.id}.json`);
const next = this.writing.then(async () => {
const temp = `${path}.tmp`;
await writeFile(temp, contents, { mode: 0o600 });
await rename(temp, path);
});
this.writing = next.catch(() => {});
return next;
}
async remove(id: string) {
await this.writing;
await unlink(join(this.dir, `${id}.json`));
this.jobs.delete(id);
}
async flush() {
await this.writing;
}
}
+71
View File
@@ -0,0 +1,71 @@
import type { Analysis, Challenge, Sample, Api } from '../vendor/lmfpd-sdk/index.js';
export type { Analysis, Challenge, Sample, Api };
export interface Model {
id: string;
name: string;
provider: string;
efforts: string[];
nativeEndpoints: string[];
}
export interface Account {
id: string;
name: string;
provider: string;
}
export interface Target {
model: string;
account?: string;
}
export interface RunConfig {
targets: Target[];
api: Api | 'auto';
effort: string;
serviceTier: 'default' | 'flex' | 'fast' | 'ultrafast';
strict: boolean;
targetParallel: number;
sampleParallel: number;
deadlineSeconds: number;
}
export interface Provenance {
session: string;
requestedModel: string;
provider?: string;
model?: string;
route?: unknown;
routeError?: string;
mismatch?: boolean;
streamNormalization?: 'chat-done-after-stop';
}
export interface TargetResult {
id: string;
target: Target;
api: Api;
state: 'queued' | 'running' | 'completed' | 'failed' | 'cancelled';
samples: Sample[];
provenance: Provenance[];
analysis: Analysis | null;
error: string | null;
}
export interface Job {
id: string;
createdAt: string;
finishedAt?: string;
state: 'queued' | 'running' | 'completed' | 'cancelled' | 'failed' | 'interrupted';
config: RunConfig;
challenges: Challenge[];
results: TargetResult[];
bank: { builtAt: string; sdk: string };
error?: string;
demo?: boolean;
}
export interface Bootstrap {
version: string;
demo: boolean;
models: Model[];
accounts: Account[];
jobs: Job[];
bank: { builtAt: string; modelCount?: number } | null;
bankStatus: { state: 'missing' | 'cached' | 'ready' };
gateway: { url: string; reachable: boolean; error?: string };
bankError?: string;
}
+211
View File
@@ -0,0 +1,211 @@
import { expect, test } from 'bun:test';
import { createHash } from 'node:crypto';
import { mkdtemp, mkdir, writeFile, utimes, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { startServer } from '../src/server';
const config = {
targets: [{ model: 'vendor/model' }],
api: 'auto',
effort: '',
serviceTier: 'default',
strict: false,
targetParallel: 1,
sampleParallel: 3,
deadlineSeconds: 10,
};
// An empty, internally consistent SDK reference fixture, never used for scoring.
function cacheFixture() {
const detector = Buffer.from(
JSON.stringify({
schema: 'shared-detector-v2',
bank_built_at: 'test-snapshot',
model_ids: [],
response_counts: [],
}),
);
const detectorHeader = Buffer.alloc(Math.ceil((4 + detector.length) / 4) * 4);
detectorHeader.writeUInt32LE(detector.length);
detector.copy(detectorHeader, 4);
const bank = Buffer.from(
JSON.stringify({
schema: 'lmfpd-data-v1',
detector_schema: 'shared-detector-v2',
built_at: 'test-snapshot',
models: [],
files: {
'shared_detector.bin': {
sha256: createHash('sha256').update(detectorHeader).digest('hex'),
parts: ['fixture.zst'],
},
},
}),
);
const length = Buffer.alloc(4);
length.writeUInt32LE(bank.length);
return Buffer.concat([length, bank, detectorHeader]);
}
async function fixture(cached = false, downloadable = false) {
const dir = await mkdtemp(join(tmpdir(), 'fingerprint-bank-test-'));
const downloads: Request[] = [];
let samples = 0;
const source = Bun.serve({
hostname: '127.0.0.1',
port: 0,
fetch(req) {
downloads.push(req);
if (downloadable) {
const cache = cacheFixture();
const bankLength = cache.readUInt32LE(0);
if (new URL(req.url).pathname.endsWith('/bundle.json'))
return new Response(cache.subarray(4, 4 + bankLength));
const bytes = cache.subarray(4 + bankLength);
// A single-segment Zstandard frame containing one uncompressed block.
const header = Buffer.from([0x28, 0xb5, 0x2f, 0xfd, 0x20, bytes.length, 0, 0, 0]);
header.writeUIntLE((bytes.length << 3) | 1, 6, 3);
return new Response(Buffer.concat([header, bytes]));
}
return new Response('Unavailable', { status: 503 });
},
});
const gateway = Bun.serve({
hostname: '127.0.0.1',
port: 0,
fetch(req) {
const path = new URL(req.url).pathname;
if (path === '/v1/models') return Response.json({ data: [{ id: 'vendor/model' }] });
if (req.method === 'POST') samples++;
return Response.json(
{ error: { message: 'Test gateway does not sample' }, data: [] },
{ status: req.method === 'POST' ? 503 : 200 },
);
},
});
let service: Awaited<ReturnType<typeof startServer>> | undefined;
try {
await mkdir(join(dir, 'ui'));
await writeFile(join(dir, 'ui/index.html'), '<head></head>');
if (cached) {
await writeFile(join(dir, 'reference.bin'), cacheFixture());
await utimes(join(dir, 'reference.bin'), new Date(0), new Date(0));
}
service = await startServer({
port: 0,
dataDir: dir,
uiDir: join(dir, 'ui'),
gateway: `http://127.0.0.1:${gateway.port}`,
apiKey: 'gateway-secret',
bankSource: `http://127.0.0.1:${source.port}/`,
demo: false,
});
const base = `http://127.0.0.1:${service.port}`;
const html = await (await fetch(base)).text();
const token = JSON.parse(html.match(/window\.__FINGERPRINT__=(.*?)<\/script>/)![1]).token;
return {
base,
downloads,
cachedBytes: () => Bun.file(join(dir, 'reference.bin')).arrayBuffer(),
samples: () => samples,
api: (path: string, init: RequestInit = {}) =>
fetch(`${base}/api/${path}`, {
...init,
headers: {
authorization: `Bearer ${token}`,
'content-type': 'application/json',
},
}),
async close() {
await service?.close();
source.stop(true);
gateway.stop(true);
await rm(dir, { recursive: true, force: true });
},
};
} catch (error) {
await service?.close();
source.stop(true);
gateway.stop(true);
await rm(dir, { recursive: true, force: true });
throw error;
}
}
test('opening, refreshing and invalid jobs never download reference data; explicit actions do', async () => {
const f = await fixture();
try {
for (let i = 0; i < 2; i++) {
const boot = await (await f.api('bootstrap')).json();
expect(boot.bank).toBeNull();
expect(boot.bankStatus.state).toBe('missing');
}
expect((await fetch(`${f.base}/api/bank/download`, { method: 'POST' })).status).toBe(401);
expect((await f.api('jobs', { method: 'POST', body: 'null' })).status).toBe(400);
expect(f.downloads).toHaveLength(0);
expect(f.samples()).toBe(0);
expect((await f.api('bank/download', { method: 'POST' })).status).toBe(503);
expect(f.downloads).toHaveLength(1);
expect(f.downloads[0].headers.has('authorization')).toBe(false);
expect((await f.api('bootstrap')).status).toBe(200);
expect(f.downloads).toHaveLength(1);
expect((await f.api('jobs', { method: 'POST', body: JSON.stringify(config) })).status).toBe(
503,
);
expect(f.downloads).toHaveLength(2);
expect(f.samples()).toBe(0);
} finally {
await f.close();
}
});
test('an old cached snapshot is reused without background network refresh', async () => {
const f = await fixture(true);
try {
expect((await (await f.api('bootstrap')).json()).bankStatus.state).toBe('cached');
const created = await f.api('jobs', {
method: 'POST',
body: JSON.stringify(config),
});
expect(created.status).toBe(202);
const job = await created.json();
expect(job.bank.builtAt).toBe('test-snapshot');
for (let i = 0; i < 100; i++) {
const current = await (await f.api(`jobs/${job.id}`)).json();
if (!['queued', 'running'].includes(current.state)) break;
await Bun.sleep(10);
}
expect(f.downloads).toHaveLength(0);
expect((await (await f.api('bootstrap')).json()).bankStatus.state).toBe('ready');
expect((await f.api('bank/download', { method: 'POST' })).status).toBe(503);
expect(f.downloads).toHaveLength(1);
expect((await (await f.api('bootstrap')).json()).bank.builtAt).toBe('test-snapshot');
expect(f.downloads).toHaveLength(1);
} finally {
await f.close();
}
});
test('an explicit download installs a usable snapshot without sending model requests', async () => {
const f = await fixture(false, true);
try {
expect((await (await f.api('bootstrap')).json()).bankStatus.state).toBe('missing');
const response = await f.api('bank/download', { method: 'POST' });
expect(response.status).toBe(200);
expect(await response.json()).toEqual({
bank: { builtAt: 'test-snapshot', modelCount: 0 },
bankStatus: { state: 'ready' },
});
expect(Buffer.from(await f.cachedBytes())).toEqual(cacheFixture());
expect(f.downloads.map((req) => new URL(req.url).pathname)).toEqual([
'/bundle.json',
'/chunks/fixture.zst',
]);
expect(f.samples()).toBe(0);
await f.api('bootstrap');
expect(f.downloads).toHaveLength(2);
} finally {
await f.close();
}
});
+69
View File
@@ -0,0 +1,69 @@
import { expect, test } from 'bun:test';
import { readFile } from 'node:fs/promises';
import { runInNewContext } from 'node:vm';
const source = await readFile(new URL('../page/boot.js', import.meta.url), 'utf8');
async function boot(lang?: string, remote = false, port = 3488) {
const elements = {
status: { textContent: 'Connecting to Fingerprint…' },
title: { textContent: 'Fingerprint' },
};
const document = {
title: 'Fingerprint',
documentElement: { lang: 'en' },
getElementById: (id: keyof typeof elements) => elements[id],
};
let destination: URL | undefined;
const service = remote ? '' : 'http://127.0.0.1:3488/';
await runInNewContext(source, {
URL,
document,
window: {
magpie: {
ready: Promise.resolve({ dark: true, ...(lang ? { lang } : {}) }),
service,
context: { provider: { id: 'vendor' } },
options: { get: async () => ({ port }) },
onAction() {},
onTheme() {},
},
},
location: {
hostname: remote ? 'magpie.example' : '127.0.0.1',
href: 'http://127.0.0.1/boot/index.html',
replace: (url: string) => {
destination = new URL(url);
},
},
});
return { document, elements, destination };
}
test('boot defaults to English and follows host languages before navigation', async () => {
for (const [lang, htmlLang, status] of [
[undefined, 'en', 'Connecting'],
['fr', 'en', 'Connecting'],
['zh-CN', 'zh-Hans', '正在连接'],
['zh-TW', 'zh-Hant', '正在連線'],
['zh-Hant-HK', 'zh-Hant', '正在連線'],
['zh_HK', 'zh-Hant', '正在連線'],
['ja', 'ja', '接続中'],
['de-DE', 'de', 'Verbindung'],
]) {
const result = await boot(lang);
expect(result.document.documentElement.lang).toBe(htmlLang!);
expect(result.elements.status.textContent).toContain(status!);
expect(result.destination?.searchParams.get('provider')).toBe('vendor');
expect(result.destination?.searchParams.get('uiOrigin')).toBe('http://127.0.0.1:3488');
expect(result.destination?.searchParams.get('lang')).toBe(lang || null);
}
});
test('boot localizes remote-service guidance and invalid-port errors', async () => {
const remote = await boot('zh-TW', true);
expect(remote.destination).toBeUndefined();
expect(remote.elements.status.textContent).toContain('遠端外掛');
const invalid = await boot('de', false, -1);
expect(invalid.destination).toBeUndefined();
expect(invalid.elements.status.textContent).toContain('Ungültiger Port');
});
+157
View File
@@ -0,0 +1,157 @@
import { describe, expect, test } from 'bun:test';
import { createJob, runJob } from '../src/detector.js';
import type { Model, RunConfig } from '../src/types.js';
const model: Model = {
id: 'm1',
name: 'Model 1',
provider: 'p',
efforts: ['default'],
nativeEndpoints: ['/v1/responses', '/v1/chat/completions'],
};
const config: RunConfig = {
targets: [{ model: 'm1' }, { model: 'm1', account: 'a' }],
api: 'auto',
effort: 'default',
serviceTier: 'default',
strict: false,
targetParallel: 2,
sampleParallel: 2,
deadlineSeconds: 30,
};
const sample = (expected_count: number) => ({
state: 'complete' as const,
text: '1, 2, 3',
raw_text: '1, 2, 3',
count: 3,
expected_count,
first_byte_ms: 1,
response_model: 'm1',
response_id: 'r',
error: null,
});
describe('detector jobs', () => {
test('generates one shared challenge batch and resolves auto API', () => {
const job = createJob(config, [model], '2026-01-01');
expect(job.challenges).toHaveLength(3);
expect(job.results[0].api).toBe('responses');
expect(job.results[0].samples.map((s) => s.expected_count)).toEqual(
job.challenges.map((c) => c.expected_count),
);
expect(job.results[1].samples.map((s) => s.expected_count)).toEqual(
job.results[0].samples.map((s) => s.expected_count),
);
});
test('uses per-sample endpoint and scores injected samples', async () => {
const job = createJob({ ...config, targets: [{ model: 'm1' }] }, [model], 'build');
const indexes: number[] = [];
let analyzed = 0;
let seenStrictCount = 0;
await runJob(job, {
detector: {
analyze: (outputs: unknown[]) => {
analyzed = outputs.length;
return { decision: 'partial' } as never;
},
} as never,
signal: new AbortController().signal,
sampleEndpoint: (_result, index) => {
indexes.push(index);
return { baseUrl: 'https://proxy.test', apiKey: 'secret' };
},
sample: async (requestConfig, challenge) => {
seenStrictCount = requestConfig.count ?? 0;
return sample(challenge.expected_count);
},
onUpdate: () => {},
});
expect(indexes.sort()).toEqual([0, 1, 2]);
expect(analyzed).toBe(3);
expect(seenStrictCount).toBe(3);
expect(job.state).toBe('completed');
expect(job.results[0].analysis?.decision).toBe('partial');
});
test('keeps partial evidence when one sample fails', async () => {
const job = createJob({ ...config, targets: [{ model: 'm1' }] }, [model], 'build');
let analyzed = 0;
await runJob(job, {
detector: {
analyze: (outputs: unknown[]) => {
analyzed = outputs.length;
return {} as never;
},
} as never,
signal: new AbortController().signal,
sampleEndpoint: () => ({ baseUrl: 'https://proxy.test', apiKey: 'secret' }),
sample: async (_config, challenge) =>
challenge.expected_count === job.challenges[0].expected_count
? { ...sample(challenge.expected_count), state: 'failed', error: 'upstream' }
: sample(challenge.expected_count),
onUpdate: () => {},
});
expect(analyzed).toBe(2);
expect(job.results[0].state).toBe('failed');
});
test('honors proxy mismatch and does not overwrite provenance with vendor alias', async () => {
const job = createJob({ ...config, targets: [{ model: 'm1' }] }, [model], 'build');
job.results[0].provenance[0] = {
session: 'proxy-session',
requestedModel: 'm1',
model: 'm1',
provider: 'p',
};
job.results[0].provenance[1] = {
session: 'proxy-session',
requestedModel: 'm1',
model: 'other',
mismatch: true,
};
let analyzed = false;
await runJob(job, {
detector: {
analyze: () => {
analyzed = true;
return {} as never;
},
} as never,
signal: new AbortController().signal,
sampleEndpoint: () => ({ baseUrl: 'https://proxy.test', apiKey: 'secret' }),
sample: async (_config, challenge) => ({
...sample(challenge.expected_count),
response_model: 'vendor-alias',
}),
onUpdate: () => {},
});
expect(analyzed).toBe(false);
expect(job.results[0].provenance[0].session).toBe('proxy-session');
expect(job.results[0].provenance[0].model).toBe('m1');
expect(job.results[0].state).toBe('failed');
expect(job.state).toBe('failed');
});
test('does not score cancelled queued samples', async () => {
const job = createJob({ ...config, targets: [{ model: 'm1' }] }, [model], 'build');
const controller = new AbortController();
controller.abort();
let analyzed = false;
await runJob(job, {
detector: {
analyze: () => {
analyzed = true;
return {} as never;
},
} as never,
signal: controller.signal,
sampleEndpoint: () => ({ baseUrl: 'https://proxy.test', apiKey: 'secret' }),
sample: async (_config, challenge) => sample(challenge.expected_count),
onUpdate: () => {},
});
expect(analyzed).toBe(false);
expect(job.state).toBe('cancelled');
expect(job.results[0].samples.every((item) => item.state === 'cancelled')).toBe(true);
});
});
@@ -0,0 +1,47 @@
import { expect, test } from 'bun:test';
import { Gateway } from '../src/gateway';
test('catalog reads cached local and remote subscription accounts without leaking quota data', async () => {
const paths: string[] = [];
const server = Bun.serve({
hostname: '127.0.0.1',
port: 0,
fetch(req) {
const url = new URL(req.url);
paths.push(url.pathname + url.search);
return Response.json(
url.pathname === '/v1/models'
? { data: [{ id: 'vendor/model' }] }
: {
data: [
{
provider: 'vendor',
user: 'local-account',
name: 'Local',
balance: '$42',
secret: 'excluded',
},
{
provider: 'vendor',
user: 'remote-account',
name: 'Remote',
kind: 'subscription',
},
{ provider: 'vendor', user: 'key-card', name: 'Key', kind: 'balance' },
{ provider: 'vendor', kind: 'subscription' },
],
},
);
},
});
try {
const { accounts } = await new Gateway(`http://127.0.0.1:${server.port}`).catalog();
expect(paths).toContain('/v1/magpie/quotas?kept=1');
expect(accounts).toEqual([
{ provider: 'vendor', id: 'local-account', name: 'Local' },
{ provider: 'vendor', id: 'remote-account', name: 'Remote' },
]);
} finally {
server.stop(true);
}
});
+15
View File
@@ -0,0 +1,15 @@
import { expect, test } from 'bun:test';
import { boundedText } from '../src/http';
test('bounded JSON reader cancels oversized streaming gateway responses', async () => {
let cancelled = false;
const stream = new ReadableStream({
pull(out) {
out.enqueue(new Uint8Array(512));
},
cancel() {
cancelled = true;
},
});
await expect(boundedText(new Response(stream), 1000)).rejects.toThrow('size limit');
expect(cancelled).toBe(true);
});
+11
View File
@@ -0,0 +1,11 @@
import { expect, test } from 'bun:test';
import { localeFor } from '../web/locale';
test('unsupported host languages fall back to English and Chinese respects script and region', () => {
for (const value of [undefined, '', 'en', 'en-US', 'ja', 'de', 'fr', 'zho'])
expect(localeFor(value)).toBe('en');
for (const value of ['zh', 'zh-CN', 'zh-SG', 'zh-Hans', 'zh-Hans-TW', 'zh_Hans_CN'])
expect(localeFor(value)).toBe('zh-Hans');
for (const value of ['zh-TW', 'zh-HK', 'zh-MO', 'zh-Hant', 'zh-Hant-CN', 'zh_Hant_HK'])
expect(localeFor(value)).toBe('zh-Hant');
});
+22
View File
@@ -0,0 +1,22 @@
import { expect, test } from 'bun:test';
import { normalizeTheme } from '../web/magpie';
test('normalizes a host theme while retaining only string tokens', () => {
expect(
normalizeTheme({
dark: true,
lang: 'zh-CN',
tokens: { bg: '#101114', fg: '#fff', radius: 6, nested: { value: 1 } },
}),
).toEqual({ dark: true, lang: 'zh-CN', tokens: { bg: '#101114', fg: '#fff' } });
});
test('rejects malformed theme envelopes and supplies a language fallback', () => {
expect(normalizeTheme(null)).toBeNull();
expect(normalizeTheme({ dark: 'yes' })).toBeNull();
expect(normalizeTheme({ dark: false, tokens: null })).toEqual({
dark: false,
lang: 'en',
tokens: {},
});
});
@@ -0,0 +1,140 @@
import { expect, test } from 'bun:test';
import { createHash } from 'node:crypto';
import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { startManagedService } from '../src/managed-service';
const waitFor = async (check: () => boolean) => {
for (let i = 0; i < 100; i++) {
if (check()) return;
await Bun.sleep(20);
}
throw new Error('Timed out waiting for host takeover');
};
test('two hosts share one compatible service and the survivor takes over', async () => {
const dir = await mkdtemp(join(tmpdir(), 'fingerprint-hosts-'));
const opts = { demo: true, dataDir: dir, uiDir: join(dir, 'ui') };
await mkdir(opts.uiDir);
await writeFile(join(opts.uiDir, 'index.html'), '<head></head>');
const a = await startManagedService({ ...opts, port: 0 }, 20);
let b: Awaited<ReturnType<typeof startManagedService>> | undefined;
let c: Awaited<ReturnType<typeof startManagedService>> | undefined;
try {
const port = a.port;
b = await startManagedService({ ...opts, port }, 20);
expect(a.role).toBe('owner');
expect(b.role).toBe('attached');
await a.close();
await waitFor(() => b!.role === 'owner');
expect(b.port).toBe(port);
c = await startManagedService({ ...opts, port }, 20);
expect(c.role).toBe('attached');
await c.close();
expect((await fetch(`http://127.0.0.1:${port}/_fingerprint/health`)).ok).toBe(true);
await expect(
startManagedService({ ...opts, dataDir: join(dir, 'different'), port }),
).rejects.toThrow('incompatible');
} finally {
await a.close();
await b?.close();
await c?.close();
await rm(dir, { recursive: true, force: true });
}
});
test('identity hides the gateway key but still rejects a changed key', async () => {
const dir = await mkdtemp(join(tmpdir(), 'fingerprint-identity-'));
const gateway = 'http://127.0.0.1:3425';
const oldKey = 'old-key';
const opts = { dataDir: dir, demo: true, gateway };
let owner: Awaited<ReturnType<typeof startManagedService>> | undefined;
let attached: Awaited<ReturnType<typeof startManagedService>> | undefined;
try {
owner = await startManagedService({ ...opts, apiKey: oldKey, port: 0 }, 20);
const health = await (await fetch(`http://127.0.0.1:${owner.port}/_fingerprint/health`)).json();
const legacy = createHash('sha256')
.update(
JSON.stringify({
gateway,
apiKey: oldKey,
dataDir: dir,
bankSource: null,
demo: true,
uiDir: null,
}),
)
.digest('hex');
expect(health.configuration).not.toBe(legacy);
expect((await readFile(join(dir, '.service-identity-salt'))).length).toBe(32);
await expect(
startManagedService({ ...opts, apiKey: 'new-key', port: owner.port }),
).rejects.toThrow('incompatible');
attached = await startManagedService({ ...opts, apiKey: oldKey, port: owner.port }, 20);
expect(attached.role).toBe('attached');
} finally {
await owner?.close();
await attached?.close();
await rm(dir, { recursive: true, force: true });
}
});
test('concurrent first starts publish one persistent identity salt', async () => {
const dir = await mkdtemp(join(tmpdir(), 'fingerprint-identity-race-'));
const source = join(import.meta.dir, '../src/service-identity.ts');
const input = JSON.stringify({
dataDir: dir,
demo: true,
gateway: 'http://127.0.0.1:3425',
apiKey: 'race-key',
});
const script = `import { serviceIdentity } from ${JSON.stringify(source)}; process.stdout.write(serviceIdentity(${input}).configuration);`;
try {
const children = Array.from({ length: 2 }, () =>
Bun.spawn([process.execPath, '-e', script], { stdout: 'pipe', stderr: 'pipe' }),
);
const outputs = await Promise.all(
children.map(async (child) => {
const output = await new Response(child.stdout).text();
expect(await child.exited).toBe(0);
return output;
}),
);
expect(outputs[0]).toBe(outputs[1]);
expect((await readFile(join(dir, '.service-identity-salt'))).length).toBe(32);
} finally {
await rm(dir, { recursive: true, force: true });
}
});
test('simultaneous hosts elect one owner without touching another application', async () => {
const dir = await mkdtemp(join(tmpdir(), 'fingerprint-election-'));
const reservation = Bun.serve({
hostname: '127.0.0.1',
port: 0,
fetch: () => new Response('not fingerprint'),
});
const port = reservation.port!;
try {
await expect(startManagedService({ port, dataDir: dir, demo: true })).rejects.toThrow(
'incompatible',
);
expect(await (await fetch(`http://127.0.0.1:${port}`)).text()).toBe('not fingerprint');
} finally {
reservation.stop(true);
}
const hosts: Awaited<ReturnType<typeof startManagedService>>[] = [];
try {
const results = await Promise.allSettled(
Array.from({ length: 3 }, () => startManagedService({ port, dataDir: dir, demo: true }, 20)),
);
for (const result of results) if (result.status === 'fulfilled') hosts.push(result.value);
expect(results.every((result) => result.status === 'fulfilled')).toBe(true);
expect(hosts.filter((host) => host.role === 'owner')).toHaveLength(1);
} finally {
await Promise.all(hosts.map((host) => host.close()));
await rm(dir, { recursive: true, force: true });
}
});
+181
View File
@@ -0,0 +1,181 @@
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { startServer } from '../src/server';
import { Store } from '../src/store';
import { demoHistory } from '../src/demo';
let dir: string, base: string, token: string, service: Awaited<ReturnType<typeof startServer>>;
const api = (path: string, init: RequestInit = {}) =>
fetch(`${base}/api/${path}`, {
...init,
headers: {
authorization: `Bearer ${token}`,
'content-type': 'application/json',
...init.headers,
},
});
beforeAll(async () => {
dir = await mkdtemp(join(tmpdir(), 'magpie-fingerprint-test-'));
await mkdir(join(dir, 'ui'));
await writeFile(join(dir, 'ui/index.html'), '<!doctype html><head></head><body>Test</body>');
service = await startServer({ port: 0, dataDir: dir, uiDir: join(dir, 'ui'), demo: true });
base = `http://127.0.0.1:${service.port}`;
const html = await (await fetch(base)).text();
token = JSON.parse(html.match(/window\.__FINGERPRINT__=(.*?)<\/script>/)![1]).token;
});
afterAll(async () => {
await service?.close();
await rm(dir, { recursive: true, force: true });
});
test('requires bearer token and rejects cross-site origins and rebinding hosts', async () => {
expect((await fetch(`${base}/api/bootstrap`)).status).toBe(401);
expect((await fetch(base, { headers: { origin: 'https://attacker.example' } })).status).toBe(403);
expect((await fetch(base, { headers: { host: 'attacker.example' } })).status).toBe(403);
expect((await api('bootstrap', { headers: { origin: 'null' } })).status).toBe(200);
expect(
(
await fetch(`${base}/api/jobs`, { method: 'OPTIONS', headers: { origin: 'null' } })
).headers.get('access-control-allow-headers'),
).toContain('Authorization');
});
test('allows the native WebKit sandbox to connect only to the validated listener', async () => {
for (const host of [`127.0.0.1:${service.port}`, `localhost:${service.port}`]) {
const page = await fetch(base, { headers: { host } });
const policy = page.headers.get('content-security-policy')!;
expect(policy.split(';').map((part) => part.trim())).toContain(
`connect-src 'self' http://${host}`,
);
expect(policy).not.toContain('allow-same-origin');
}
const preflight = await fetch(`${base}/api/bootstrap`, {
method: 'OPTIONS',
headers: {
origin: 'null',
'access-control-request-method': 'GET',
'access-control-request-headers': 'authorization',
},
});
expect(preflight.status).toBe(204);
expect(preflight.headers.get('access-control-allow-origin')).toBe('null');
expect((await api('bootstrap', { headers: { origin: 'null' } })).status).toBe(200);
expect(
(await fetch(base, { headers: { host: 'attacker.example' } })).headers.has(
'content-security-policy',
),
).toBe(false);
});
test('demo is explicitly identified; catalog and history never pretend to be measurements', async () => {
const boot = await (await api('bootstrap')).json();
expect(boot.demo).toBe(true);
expect(boot.models.length).toBeGreaterThan(0);
expect(boot.jobs.every((j: any) => j.demo === true)).toBe(true);
});
test('names the Magpie web proxy origin in sandbox CSP without accepting policy injection', async () => {
const proxy = 'https://magpie.example:9443';
const page = await fetch(`${base}/?uiOrigin=${encodeURIComponent(proxy)}`);
expect(page.headers.get('content-security-policy')).toContain(
`connect-src 'self' http://127.0.0.1:${service.port} ${proxy}`,
);
for (const invalid of [
'not-an-origin',
'http://*',
'https://*.example.com',
'https://example.com; script-src *',
'https://example.com/path',
'https://u:p@example.com',
'data:text/html,hello',
'https://example.com/?x=1',
]) {
expect((await fetch(`${base}/?uiOrigin=${encodeURIComponent(invalid)}`)).status).toBe(400);
}
expect((await api('bootstrap', { headers: { origin: proxy } })).status).toBe(403);
});
test('creates one batch, streams snapshots, cancels, exports and deletes it', async () => {
const config = {
targets: [{ model: 'openai/gpt-5.5' }],
api: 'auto',
effort: '',
serviceTier: 'default',
strict: false,
targetParallel: 1,
sampleParallel: 3,
deadlineSeconds: 10,
};
const created = await api('jobs', { method: 'POST', body: JSON.stringify(config) });
expect(created.status).toBe(202);
const job = await created.json();
expect((await api('jobs', { method: 'POST', body: JSON.stringify(config) })).status).toBe(409);
const events = await api(`jobs/${job.id}/events`);
expect(events.headers.get('content-type')).toContain('text/event-stream');
const reader = events.body!.getReader();
expect(new TextDecoder().decode((await reader.read()).value)).toContain('event: snapshot');
await reader.cancel();
expect((await api(`jobs/${job.id}/cancel`, { method: 'POST' })).status).toBe(200);
let finished: any;
for (let i = 0; i < 50; i++) {
finished = await (await api(`jobs/${job.id}`)).json();
if (finished.state === 'cancelled') break;
await Bun.sleep(30);
}
expect(finished.state).toBe('cancelled');
expect(finished.results[0].analysis).toBeNull();
const exported = await (await api(`jobs/${job.id}/export`)).json();
expect(exported.schema).toBe('magpie-fingerprint/v1');
expect(exported.demo).toBe(true);
expect((await api(`jobs/${job.id}`, { method: 'DELETE' })).status).toBe(200);
expect((await api(`jobs/${job.id}`)).status).toBe(404);
});
test('restart marks unfinished persisted tasks as interrupted and preserves original evidence', async () => {
const storeDir = join(dir, 'interrupted');
const a = new Store(storeDir);
await a.load();
const j = demoHistory();
j.id = 'unfinished';
j.state = 'running';
j.results[0].state = 'running';
await a.save(j);
const b = new Store(storeDir);
await b.load();
const recovered = b.jobs.get(j.id)!;
expect(recovered.state).toBe('interrupted');
expect(recovered.results[0].analysis).toBeNull();
expect(recovered.results[0].samples[0].raw_text).toBe(j.results[0].samples[0].raw_text);
});
test('validation fails before starting malformed jobs', async () => {
expect((await api('jobs', { method: 'POST', body: 'null' })).status).toBe(400);
expect(
(
await api('jobs', {
method: 'POST',
body: JSON.stringify({ targets: [{ model: 'unknown/model' }] }),
})
).status,
).toBe(400);
});
test('bounds chunked request bodies without trusting Content-Length', async () => {
const body = new ReadableStream({
start(out) {
out.enqueue(new TextEncoder().encode('x'.repeat(20000)));
out.close();
},
});
const response = await api('jobs', { method: 'POST', body });
expect(response.status).toBe(413);
});
test('a second host cannot repair jobs belonging to the active service', async () => {
const job = demoHistory();
job.id = 'active-owner-job';
job.state = 'running';
const path = join(dir, 'demo-jobs', `${job.id}.json`);
await writeFile(path, JSON.stringify(job));
try {
await expect(
startServer({ port: service.port, dataDir: dir, uiDir: join(dir, 'ui'), demo: true }),
).rejects.toThrow();
expect(JSON.parse(await readFile(path, 'utf8')).state).toBe('running');
} finally {
await rm(path, { force: true });
}
});
+74
View File
@@ -0,0 +1,74 @@
import { expect, test } from 'bun:test';
import { generateChallenges, requestSample } from '../vendor/lmfpd-sdk/index.js';
import { normalizeChatStream } from '../src/sse';
test('real SDK accepts a clean chat stop without sentinel, but still rejects incomplete endings', async () => {
const challenge = generateChallenges(1)[0];
const text = Array.from({ length: challenge.expected_count }, (_, i) => (i % 355) + 1).join(', ');
let ending = 'stop',
repaired = 0;
const server = Bun.serve({
hostname: '127.0.0.1',
port: 0,
fetch() {
const data = `data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: text }, finish_reason: ending || null }] })}\n\n`;
const source = new ReadableStream<Uint8Array>({
start(out) {
out.enqueue(new TextEncoder().encode(data));
out.close();
},
});
return new Response(
normalizeChatStream(source, () => repaired++),
{ headers: { 'content-type': 'text/event-stream' } },
);
},
});
try {
const sample = () =>
requestSample(
{
baseUrl: `http://127.0.0.1:${server.port}/v1`,
apiKey: 'test',
model: 'test',
api: 'chat_completions',
strict: true,
stream: true,
},
challenge,
);
const complete = await sample();
expect(complete.state).toBe('complete');
expect(complete.count).toBe(challenge.expected_count);
expect(repaired).toBe(1);
for (ending of ['length', '']) {
expect((await sample()).state).toBe('failed');
expect(repaired).toBe(1);
}
} finally {
server.stop(true);
}
});
test('chat sentinel is preserved and a broken stream after stop is never repaired', async () => {
let repaired = false;
const data =
'data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n';
const source = new Response(data).body!;
expect(await new Response(normalizeChatStream(source, () => (repaired = true))).text()).toBe(
data,
);
expect(repaired).toBe(false);
const broken = new ReadableStream<Uint8Array>({
start(out) {
out.enqueue(new TextEncoder().encode(data.split('data: [DONE]')[0]));
},
pull(out) {
out.error(new Error('upstream disconnected'));
},
});
await expect(
new Response(normalizeChatStream(broken, () => (repaired = true))).text(),
).rejects.toThrow('upstream disconnected');
expect(repaired).toBe(false);
});
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"skipLibCheck": true,
"types": ["bun"],
"lib": ["ES2022", "DOM", "DOM.Iterable"]
},
"include": ["src", "web", "scripts", "tests", "vite.config.ts"]
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 xqy2006
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+78
View File
@@ -0,0 +1,78 @@
# lmfpd-sdk
TypeScript SDK for [lmfpd](https://lm.ikale.io), the language-model fingerprint detector. It scores saved replies to
the number challenge, generates challenges, and runs one live detection round against an OpenAI Responses, Chat
Completions, or Anthropic Messages API. Rust, Go, and Python SDKs with the same results live beside this package.
The results are a closed-set ranking within the reference bank. They are not identity confirmation.
Documentation: https://lm.ikale.io/docs/en/sdk
```sh
npm install lmfpd-sdk # Node 22+ or Bun 1.4.2+
```
```ts
import { loadDetector } from 'lmfpd-sdk'
const detector = await loadDetector()
const analysis = detector.analyze([
{ text: '17, 203, 88, …', expected_count: 300 },
{ text: '…', expected_count: 311 },
{ text: '…', expected_count: 296 },
])
console.log(analysis.decision, analysis.prediction, analysis.probability)
const result = await detector.detect({ baseUrl: 'https://api.openai.com/v1', apiKey: process.env.API_KEY!, model: 'gpt-5' })
console.log(result.analysis?.prediction ?? result.error)
```
## Reference data
The package contains no reference data. `loadDetector()` downloads the detector (about 3.6 MB compressed) from the
first working source in `DEFAULT_DATA_URLS`:
1. `https://lm.ikale.io/data/`
2. `https://cdn.jsdmirror.com/npm/lmfpd-data@latest/`, a mirror in mainland China
The data is cached in one file, `<OS cache directory>/lmfpd/data.bin` by default (`cache` sets another). A load with
a cache returns at once; when the cache was last checked `ttl` seconds ago or earlier (default 86400; 0 checks on every
load), it also refreshes the cache in the
background for the next load. Without a cache the data is downloaded before `loadDetector` returns. A single `source`
that is not an http(s) URL is a local directory: `loadDetector({ source: './data' })` reads `unified_bank.json` and
`shared_detector.bin` from it without network access.
Bun reads `HTTPS_PROXY` for every request. Node reads it only with `NODE_USE_ENV_PROXY=1`.
## API
| Export | Description |
|---|---|
| `loadDetector({ source?, cache?, ttl? })` | Loads the reference data from URLs through the cache file, or from a local directory. |
| `detector.builtAt` | Build time of the reference bank. |
| `detector.analyze(outputs, { strict? })` | Scores one to three replies. Three valid replies give a calibrated ranking; fewer give a partial ranking unless `strict`. |
| `detector.detect(config, { signal?, onSample? })` | Generates `config.count` challenges, sends them to the model API, and scores the replies. |
| `generateChallenges(count = 3)` | One to three random challenges, each asking for a distinct count from 292 to 332. |
| `parseNumbers(text)` | The numbers 1 to 355 of the longest run in a reply. |
| `buildRequest(config, prompt)` | The URL, headers, and body `detect` sends, or `{ error }`. |
| `requestSample(config, challenge)` | Sends one challenge and returns the checked reply. |
| `DEFAULT_DATA_URLS` | The default data sources. |
`DetectConfig` takes `baseUrl`, `apiKey`, and `model`, plus `api` (`responses`, `chat_completions`, or `messages`),
`effort`, `serviceTier`, `stream` (default true), `strict`, `count` (default 3), `parallel` (default 3), and `timeout`
in seconds (default 120, 0 disables).
`onSample(index, sample)` receives a copy of a sample each time it changes: `queued` for every sample first, then
`waiting` once its request is sent, `streaming` with a growing `count` as SSE text arrives, and finally `complete`,
`truncated`, `failed`, or `cancelled`. `index` is the sample's position in the result. Calls never overlap, and a
thrown error is reported as an uncaught exception without affecting the detection. `sample.first_byte_ms` is the time
to the first SSE body data, or to the whole JSON response.
```ts
const result = await detector.detect(config, {
onSample: (index, sample) => console.log(index, sample.state, `${sample.count}/${sample.expected_count}`),
})
```
`Analysis.decision` is `scored`, `partial`, `unscorable`, or `not_model`. `results` lists the candidates by ranking
score; `probability` is the closed-set probability of the top candidate and is null without three valid replies.
+1
View File
@@ -0,0 +1 @@
export * from './types/sdk/ts/src/index.js';
File diff suppressed because it is too large Load Diff
+38
View File
@@ -0,0 +1,38 @@
{
"name": "lmfpd-sdk",
"description": "Language model fingerprint detection: score saved replies or run a live detection round",
"type": "module",
"license": "MIT",
"homepage": "https://lm.ikale.io",
"repository": {
"type": "git",
"url": "git+https://github.com/Ikaleio/lm-detector.git"
},
"bugs": {
"url": "https://github.com/Ikaleio/lm-detector/issues"
},
"exports": {
".": {
"types": "./types/sdk/ts/src/index.d.ts",
"import": "./index.js"
}
},
"files": [
"index.js",
"types",
"README.md",
"LICENSE"
],
"engines": {
"node": ">=22",
"bun": ">=1.4.2"
},
"keywords": [
"llm",
"fingerprint",
"model-detection",
"sdk"
],
"version": "0.2.0",
"gitHead": "1e58ed83c1cde17f88cba89560ad4d083042ae92"
}
@@ -0,0 +1,9 @@
import { type SharedDetector } from '@fingerpoint/shared/shared-detector';
import type { Analysis as CoreAnalysis, Bank } from '@fingerpoint/shared/types';
import type { Analysis, Output } from './types.js';
export declare const SCORING_FAILED = "Scoring failed. Check that the reference bank and detector files are valid.";
/** Fills the keys the core omits, so every SDK returns the same key set. */
export declare function canonicalAnalysis(a: CoreAnalysis): Analysis;
export declare function score(outputs: Output[], bank: Bank, detector: SharedDetector, strict: boolean): Analysis;
/** Scores saved replies like `fpd --input`: extra numbers are cut in relaxed mode, short replies count as missing. */
export declare function analyzeOutputs(outputs: Output[], bank: Bank, detector: SharedDetector, strict: boolean): Analysis;
@@ -0,0 +1,4 @@
import { type DetectionOptions } from '@fingerpoint/shared/detect-request';
import type { DetectConfig } from './types.js';
/** Validates an SDK config and fills the detection options with the SDK defaults. Throws on an invalid config. */
export declare function detectOptions(input: DetectConfig): DetectionOptions;
@@ -0,0 +1,12 @@
import { type SharedDetector } from '@fingerpoint/shared/shared-detector';
import type { Bank } from '@fingerpoint/shared/types';
export interface ReferenceData {
bank: Bank;
detector: SharedDetector;
}
/**
* A single source that is not an http(s) URL is a local directory, read as is. For URLs, answers from the cache file
* when there is one (stale-while-revalidate): a cache last checked `ttl` seconds ago or earlier is refreshed in the
* background for the next load. Without a cache it downloads.
*/
export declare function loadData(source?: string | readonly string[], cachePath?: string, ttl?: number): Promise<ReferenceData>;
@@ -0,0 +1,41 @@
import type { Analysis, Challenge, DetectConfig, DetectOptions, DetectResult, LoadOptions, Output, Sample } from './types.js';
export type * from './types.js';
export { DEFAULT_DATA_URLS } from './types.js';
/** A loaded reference bank and detector. Create one with `loadDetector()`. */
export declare class Detector {
#private;
/** `built_at` of the reference bank, which identifies the data build. */
readonly builtAt: string;
private constructor();
/**
* Scores one to three saved replies. Three valid replies give a calibrated ranking; fewer give a partial ranking
* unless `strict` is set.
*/
analyze(outputs: Output[], options?: {
strict?: boolean;
}): Analysis;
/**
* Sends one round of challenges to the model API and scores the replies. Throws only on an invalid config.
* `onSample` sees every change of a sample: first `queued` for each index, then its request until the final state.
*/
detect(config: DetectConfig, { signal, onSample }?: DetectOptions): Promise<DetectResult>;
}
/**
* Loads the reference data from a local directory, or from URLs through a cache file: an existing cache answers at once
* and is refreshed in the background once it is `ttl` seconds old; without one the data is downloaded.
*/
export declare function loadDetector(options?: LoadOptions): Promise<Detector>;
/** Random challenges in one of five languages, each asking for a distinct count from 292 to 332. */
export declare function generateChallenges(count?: number): Challenge[];
/** The numbers 1 to 355 of the longest run in a reply; letters between numbers split runs. */
export declare function parseNumbers(text: string): number[];
/** The HTTP request `detect` sends for one prompt, or the config error. */
export declare function buildRequest(config: DetectConfig, prompt: string): {
url: string;
headers: Record<string, string>;
body: Record<string, unknown>;
} | {
error: string;
};
/** Sends one challenge and returns the checked reply. Request failures are reported in `error`. */
export declare function requestSample(config: DetectConfig, challenge: Challenge): Promise<Sample>;
@@ -0,0 +1,135 @@
/** One model reply and the number count its challenge asked for. */
export interface Output {
text: string;
expected_count: number;
}
export interface Challenge {
id: string;
expected_count: number;
prompt: string;
}
export type Api = 'responses' | 'chat_completions' | 'messages';
export type ServiceTier = 'flex' | 'default' | 'fast' | 'ultrafast';
export interface DetectConfig {
baseUrl: string;
apiKey: string;
model: string;
/** Default `responses`. */
api?: Api;
/** Reasoning effort sent to the model. Empty sends none; `none` disables thinking on Messages. */
effort?: string;
/** Default `default`, which sends no tier field. */
serviceTier?: ServiceTier;
/** Default true. */
stream?: boolean;
/** Require three complete replies and no truncation. Needs `count` 3. Default false. */
strict?: boolean;
/** Challenges per round, 1 to 3. Default 3. */
count?: number;
/** Concurrent requests, 1 to 3, capped at `count`. Default 3. */
parallel?: number;
/** Seconds to wait for the first SSE byte or the whole JSON response; 0 disables the timer. Default 120. */
timeout?: number;
}
export interface AnalysisResult {
model: string;
display_name: string;
family: string;
family_name: string;
score: number;
probability: number | null;
}
export interface Diagnostic {
index: number;
parsed_numbers: number;
minimum_numbers: number;
accepted: boolean;
raw_out_of_range_count: number;
}
/** Every key is always present, so the shape matches the Rust, Go, and Python SDKs. */
export interface Analysis {
decision: 'scored' | 'partial' | 'unscorable' | 'not_model';
prediction: string;
prediction_name: string;
family_prediction: string;
family_prediction_name: string;
/** Candidates by ranking score, best first. Empty unless the decision is `scored` or `partial`. */
results: AnalysisResult[];
ranking_score: number | null;
/** Closed-set probability of the top candidate within the reference bank. Null without calibration or three replies. */
probability: number | null;
probability_status: 'unavailable' | 'reference_calibrated';
probability_scope: string | null;
calibration: {
method: string;
run: string;
tau: number;
sha256: string | null;
} | null;
used_outputs: number;
diagnostics: Diagnostic[];
sequence: {
autocorrelation: number;
small_step_share: number;
model_like: boolean;
} | null;
method: string;
model_version: {
base_sha256: string;
};
evidence: {
insufficient: boolean;
label: string;
reason: string;
threshold: null;
method: string;
};
}
export interface Sample {
state: 'complete' | 'truncated' | 'failed' | 'cancelled' | 'queued' | 'waiting' | 'streaming';
/** The numbers used for scoring; capped at `expected_count` when the reply had more. */
text: string;
raw_text: string;
count: number;
expected_count: number;
/**
* Milliseconds from sending the request to the first SSE body byte, or to the whole JSON response. Null until then,
* and when the request failed before it.
*/
first_byte_ms: number | null;
response_model: string | null;
response_id: string | null;
error: string | null;
}
export interface DetectOptions {
/** Cancels the round; samples that have not started become `cancelled` and the round is not scored. */
signal?: AbortSignal;
/**
* Called with a copy of a sample each time it changes. Calls never overlap. A thrown error is reported as an uncaught
* exception and does not affect the detection.
*/
onSample?: (index: number, sample: Sample) => void;
}
export interface DetectResult {
challenges: Challenge[];
samples: Sample[];
analysis: Analysis | null;
/** Why the round has no ranking, or null when it has one. */
error: string | null;
}
export interface LoadOptions {
/**
* Base URLs of the published data, each ending in `/`, tried in order. A single source that is not an http(s) URL is
* a local directory holding `unified_bank.json` and `shared_detector.bin`, read as is. Default `DEFAULT_DATA_URLS`.
*/
source?: string | readonly string[];
/** Cache file for downloaded data. Default `<OS cache directory>/lmfpd/data.bin`. */
cache?: string;
/** Seconds after a check before the cache is refreshed in the background; 0 checks on every load. Default 86400. */
ttl?: number;
}
/**
* Data sources, tried in order. The mirror is JSDMirror, a jsDelivr mirror in mainland China, serving the `lmfpd-data`
* npm package, which has the same layout as the site's `/data/`.
*/
export declare const DEFAULT_DATA_URLS: readonly string[];
+9
View File
@@ -0,0 +1,9 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
root: 'web',
base: './',
plugins: [react()],
build: { outDir: '../dist/ui', emptyOutDir: true },
});
+154
View File
@@ -0,0 +1,154 @@
import { useEffect, useId, useRef, useState } from 'react';
import type { KeyboardEvent } from 'react';
export type AppMenuOption = { value: string; label: string };
type AppMenuProps = {
label: string;
value: string;
options: AppMenuOption[];
onChange: (value: string) => void;
disabled?: boolean;
};
/** A Magpie-style listbox trigger, with native keyboard semantics. */
export function AppMenu({ label, value, options, onChange, disabled = false }: AppMenuProps) {
const id = useId();
const listId = `app-menu-${id.replace(/:/g, '')}`;
const root = useRef<HTMLDivElement>(null);
const button = useRef<HTMLButtonElement>(null);
const list = useRef<HTMLDivElement>(null);
const [open, setOpen] = useState(false);
const selected = Math.max(
0,
options.findIndex((option) => option.value === value),
);
const [active, setActive] = useState(selected);
useEffect(() => setActive(selected), [selected]);
useEffect(() => {
if (open) list.current?.focus();
}, [open]);
useEffect(() => {
if (!open) return;
const closeOutside = (event: MouseEvent | PointerEvent) => {
if (!root.current?.contains(event.target as Node)) setOpen(false);
};
document.addEventListener('pointerdown', closeOutside);
return () => document.removeEventListener('pointerdown', closeOutside);
}, [open]);
const choose = (next: number) => {
const option = options[next];
if (!option) return;
setActive(next);
onChange(option.value);
setOpen(false);
button.current?.focus();
};
const move = (delta: number) => {
if (!options.length) return;
setActive((current) => (current + delta + options.length) % options.length);
};
const onListKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (event.key === 'Escape') {
event.preventDefault();
setOpen(false);
button.current?.focus();
return;
}
if (event.key === 'ArrowDown' || event.key === 'ArrowRight') {
event.preventDefault();
move(1);
} else if (event.key === 'ArrowUp' || event.key === 'ArrowLeft') {
event.preventDefault();
if (!open) setOpen(true);
move(-1);
} else if (event.key === 'Home') {
event.preventDefault();
setActive(0);
} else if (event.key === 'End') {
event.preventDefault();
setActive(Math.max(0, options.length - 1));
} else if (event.key === 'Tab') {
setOpen(false);
} else if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
choose(active);
}
};
return (
<div className="app-menu" ref={root}>
<button
ref={button}
type="button"
className="app-menu-trigger"
aria-label={label}
aria-haspopup="listbox"
aria-controls={listId}
aria-expanded={open}
disabled={disabled}
onClick={() => {
setActive(selected);
setOpen((current) => !current);
}}
onKeyDown={(event) => {
if (
event.key === 'ArrowDown' ||
event.key === 'ArrowUp' ||
event.key === 'Enter' ||
event.key === ' '
) {
event.preventDefault();
setActive(selected);
setOpen(true);
} else if (event.key === 'Escape') {
setOpen(false);
}
}}
>
<span>{options.find((option) => option.value === value)?.label ?? value}</span>
<span className="app-menu-chevron" aria-hidden="true">
⌄
</span>
</button>
<div
id={listId}
ref={list}
className="app-menu-list"
role="listbox"
aria-label={label}
aria-activedescendant={`${listId}-option-${active}`}
tabIndex={open ? 0 : -1}
hidden={!open}
onKeyDown={onListKeyDown}
onBlur={(event) => {
if (!root.current?.contains(event.relatedTarget as Node)) setOpen(false);
}}
>
{options.map((option, index) => (
<button
key={option.value}
id={`${listId}-option-${index}`}
type="button"
role="option"
aria-selected={option.value === value}
className={[option.value === value ? 'selected' : '', index === active ? 'active' : '']
.filter(Boolean)
.join(' ')}
tabIndex={-1}
onMouseEnter={() => setActive(index)}
onClick={() => choose(index)}
>
<span>{option.label}</span>
{option.value === value && <span aria-hidden="true">✓</span>}
</button>
))}
</div>
</div>
);
}
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#f7f7f5" />
<title>Magpie · 模型指纹</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/main.tsx"></script>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
export type Locale = 'en' | 'zh-Hans' | 'zh-Hant';
/** English is the fallback; Chinese scripts take precedence over regions. */
export function localeFor(value?: string): Locale {
const parts = (value || '').toLowerCase().replaceAll('_', '-').split('-');
if (parts[0] !== 'zh') return 'en';
if (parts.includes('hans')) return 'zh-Hans';
if (parts.includes('hant') || parts.some((part) => ['tw', 'hk', 'mo'].includes(part)))
return 'zh-Hant';
return 'zh-Hans';
}
+92
View File
@@ -0,0 +1,92 @@
export type MagpieTheme = {
dark: boolean;
lang: string;
tokens: Record<string, string>;
};
type ThemeListener = (theme: MagpieTheme) => void;
type MagpieBridge = {
theme?: unknown;
ready?: Promise<unknown>;
onTheme?: (listener: (theme: unknown) => void) => void;
};
declare global {
interface Window {
magpie?: MagpieBridge;
}
}
/** True only when the page is hosted in Magpie's iframe. */
export const embedded = typeof window !== 'undefined' && window.parent !== window;
/** Keep host data at the narrow boundary used by the page. */
export function normalizeTheme(value: unknown): MagpieTheme | null {
if (!value || typeof value !== 'object') return null;
const candidate = value as { dark?: unknown; lang?: unknown; tokens?: unknown };
if (typeof candidate.dark !== 'boolean') return null;
const tokens: Record<string, string> = {};
if (candidate.tokens && typeof candidate.tokens === 'object') {
for (const [key, token] of Object.entries(candidate.tokens)) {
if (typeof token === 'string') tokens[key] = token;
}
}
return {
dark: candidate.dark,
lang: typeof candidate.lang === 'string' && candidate.lang ? candidate.lang : 'en',
tokens,
};
}
const listeners = new Set<ThemeListener>();
let bridgeWired = false;
let bridgeWiring = false;
let latestTheme: MagpieTheme | null = null;
const bridgeLoaded =
typeof window !== 'undefined' && typeof document !== 'undefined'
? import('./vendor/magpie-bridge.js').catch(() => undefined)
: Promise.resolve(undefined);
function bridge(): MagpieBridge | undefined {
return typeof window === 'undefined' ? undefined : window.magpie;
}
function publish(value: unknown) {
const theme = normalizeTheme(value);
if (!theme) return;
latestTheme = theme;
// The CSS bridge owns the token values; this marker lets the page opt into
// aliases only after a real host theme has arrived.
document.documentElement.dataset.magpie = 'connected';
for (const listener of listeners) {
try {
listener(theme);
} catch {
// A page listener must not break delivery to the other listeners.
}
}
}
function wireBridge() {
if (bridgeWired || bridgeWiring || !embedded) return;
bridgeWiring = true;
void bridgeLoaded.then(() => {
const api = bridge();
if (!api) return;
bridgeWired = true;
api.onTheme?.(publish);
// `ready` is intentionally observed without awaiting it here: standalone
// pages may never receive a parent hello response.
api.ready?.then(publish, () => undefined);
if (api.theme) publish(api.theme);
});
}
/** Subscribe to host theme changes. Returns a cleanup function. */
export function subscribeTheme(listener: ThemeListener): () => void {
if (!embedded) return () => undefined;
listeners.add(listener);
if (latestTheme) listener(latestTheme);
wireBridge();
return () => listeners.delete(listener);
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
/** The upstream bridge installs window.magpie; it exports no module values. */
export {};
+173
View File
@@ -0,0 +1,173 @@
// The page's side of a plugin page's messages to magpie's window
// (docs/subsystems/plugin-runtime.md, P4). A plugin's page loads it with
// <script src="_magpie/bridge.js"></script>; it is served beside every
// page's own files.
//
// await magpie.ready the window's theme, once it has answered
// magpie.theme { dark, lang, tokens: { bg, fg, … } }
// magpie.onTheme(fn) fn(theme) on each change of it
// await magpie.options.get() the plugin's own options (plugins.json)
// await magpie.options.set(o) sets them, and answers with them
// await magpie.read(name, p) a read its package.json's
// magpie.permissions declares
// magpie.context where a panel is (P5): { provider: {
// id, name } } in a provider's editor,
// else {}; set once magpie.ready is
// magpie.service the address of the page's local service
// (package.json's magpie.page.service)
// through magpie, set once magpie.ready
// is, on a page a browser opened through
// magpie web; "" where 127.0.0.1 is the
// service's own computer (the app's
// window) or magpie is older
// magpie.onAction(fn) fn({ id, provider | agent: { id, name } })
// when one of its magpie.actions is picked
// in a row's menu (P6); one picked before
// fn was given waits for it
//
// A panel (magpie.panels) is as tall as what it draws: the window is told
// its height as it changes.
//
// What the page leaves unstyled takes magpie's look: the bridge adds a
// stylesheet of no weight (:where()) for the font, colours, headings,
// buttons, fields and tables, and the theme's colours are the page's
// --magpie-<token> variables.
//
// The page can't reach the network or magpie's API itself: everything goes
// through the window, which answers only what the package declared. An
// error the page doesn't catch shows the window's "This page stopped
// working" in its place.
(() => {
const waiting = new Map();
let next = 0;
const themed = [];
let acting = null;
const acted = [];
function call(method, params) {
const id = ++next;
return new Promise((resolve, reject) => {
waiting.set(id, { resolve, reject });
parent.postMessage({ magpie: 1, id, method, params }, "*");
});
}
function paint(theme) {
const root = document.documentElement;
root.dataset.theme = theme.dark ? "dark" : "light";
// the frame's canvas matches the window's, not a white sheet in dark
root.style.colorScheme = theme.dark ? "dark" : "light";
root.lang = theme.lang || "en";
for (const [k, v] of Object.entries(theme.tokens || {})) root.style.setProperty("--magpie-" + k, v);
}
addEventListener("message", (e) => {
if (e.source !== parent) return;
const m = e.data;
if (!m || m.magpie !== 1) return;
if (m.event === "theme") {
api.theme = m.data;
paint(m.data);
for (const fn of themed) { try { fn(m.data); } catch (err) { report(err); } }
return;
}
if (m.event === "action") {
if (acting) act(m.data); else acted.push(m.data);
return;
}
const w = waiting.get(m.id);
if (!w) return;
waiting.delete(m.id);
if (m.error) w.reject(new Error(m.error)); else w.resolve(m.result);
});
function report(err) {
parent.postMessage({ magpie: 1, method: "error", params: { message: String(err?.message || err) } }, "*");
}
// a script's error reaches a sandboxed page only as "Script error." (its
// files are another origin's to it); the window then says "The page hit
// an error" in the reader's language, and the console has the rest
//
// The size watch below can be told its own "ResizeObserver loop
// completed with undelivered notifications" when the window resizes the
// frame in the same frame of drawing; that is no error of the page's,
// and WebKit hands it to a sandboxed page as a bare "Script error." with
// no file, so one that comes while the watch has just run is let go
let measuring = false;
addEventListener("error", (e) => {
if (/ResizeObserver loop/.test(e.message) || (measuring && !e.error && !e.filename)) { e.preventDefault(); return; }
report(e.error || (e.message === "Script error." ? "" : e.message));
});
addEventListener("unhandledrejection", (e) => report(e.reason));
function act(data) {
try { Promise.resolve(acting(data)).catch(report); } catch (err) { report(err); }
}
const api = {
theme: null,
context: {},
service: "",
onTheme(fn) { themed.push(fn); },
onAction(fn) {
acting = fn;
for (const d of acted.splice(0)) act(d);
},
options: {
get: () => call("options.get"),
set: (options) => call("options.set", { options }),
},
read: (name, params) => call("read", { name, params }),
};
api.ready = call("hello").then(({ context, service, ...theme }) => {
api.theme = theme;
api.context = context || {};
api.service = "";
try { if (service) api.service = new URL(service, location.href).href; } catch { /* none */ }
paint(theme);
return theme;
});
// how tall the page draws, for a panel's frame; a page's frame fills its
// view, and the window doesn't heed it there
let told = -1;
const size = () => {
const h = Math.ceil(document.documentElement.getBoundingClientRect().height);
if (h === told) return;
told = h;
parent.postMessage({ magpie: 1, method: "size", params: { height: h } }, "*");
};
const watch = () => {
new ResizeObserver(() => {
if (!measuring) { measuring = true; setTimeout(() => { measuring = false; }); }
size();
}).observe(document.documentElement);
size();
};
if (document.readyState === "loading") addEventListener("DOMContentLoaded", watch); else watch();
// magpie's look for what the page leaves unstyled: its font, colours,
// headings, buttons, fields and tables, so a page with no stylesheet of
// its own reads as part of the window, not a browser's default sheet.
// Every rule is :where(), of no weight: any rule of the page's wins.
const base = document.createElement("style");
base.dataset.magpie = "base";
base.textContent = `
:where(html) { background: var(--magpie-bg, Canvas); color: var(--magpie-fg, CanvasText); font: 13px/1.45 var(--magpie-font, -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif); -webkit-font-smoothing: antialiased; }
:where(body) { margin: 0; padding: 20px 24px; }
:where(h1, h2, h3, h4) { font-weight: 600; margin: 0 0 8px; letter-spacing: -.01em; }
:where(h1) { font-size: 20px; } :where(h2) { font-size: 15px; } :where(h3, h4) { font-size: 13px; }
:where(p) { margin: 0 0 8px; }
:where(small, .muted) { color: var(--magpie-muted, GrayText); }
:where(a) { color: var(--magpie-accent, LinkText); text-decoration: none; }
:where(a:hover) { text-decoration: underline; }
:where(button, input, textarea, select) { font: inherit; color: inherit; }
:where(button) { background: var(--magpie-card, ButtonFace); border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 6px; padding: 3px 10px; }
:where(button:hover:not(:disabled)) { border-color: var(--magpie-muted, ButtonBorder); }
:where(button[aria-pressed="true"], button[aria-selected="true"]) { background: var(--magpie-accent-soft, Highlight); border-color: transparent; color: var(--magpie-accent, HighlightText); }
:where(button:disabled) { opacity: .5; }
:where(input, textarea, select) { background: var(--magpie-card, Field); border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 6px; padding: 4px 8px; }
:where(:focus-visible) { outline: 2px solid var(--magpie-accent, Highlight); outline-offset: 1px; }
:where(table) { border-collapse: collapse; width: 100%; }
:where(th) { text-align: left; font-weight: 500; font-size: 12px; color: var(--magpie-muted, GrayText); }
:where(th, td) { padding: 6px 8px; border-bottom: 1px solid var(--magpie-line, ButtonBorder); }
:where(code, kbd, pre) { font-family: var(--magpie-code, ui-monospace, Menlo, monospace); font-size: 12px; }
:where(pre) { background: var(--magpie-card, Canvas); border: 1px solid var(--magpie-line, ButtonBorder); border-radius: 8px; padding: 8px 10px; overflow: auto; }
:where(hr) { border: 0; border-top: 1px solid var(--magpie-line, ButtonBorder); margin: 12px 0; }
:where(::selection) { background: var(--magpie-accent-soft, Highlight); }
`;
(document.head || document.documentElement).prepend(base);
window.magpie = api;
})();
+196
View File
@@ -0,0 +1,196 @@
/* Magpie UI excerpts. MIT, Copyright (c) 2026 yetone.
* Source: https://github.com/yetone/magpie/tree/d80d75f300274fe13866d4fbf5599c13870b43ac
* Original files: internal/gui/assets/app.css and plugins/library/library.css.
* Full license: THIRD_PARTY_NOTICES.md. No host layout or application JS.
*/
/* magpie — one quiet surface, real logos, controls that read as pop-up buttons. */
:root {
--ease: cubic-bezier(.2, .8, .2, 1);
--bg: #f4f4f6;
--card: #ffffff;
--card-2: #f9f9fb; /* expanded editor */
--pill: #f1f1f4;
--pill-hover: #e9e9ee;
/* the header's view switch: its track and the thumb on the view shown, the
track a shade deeper than a pill so the white thumb stands off it (#477) */
--seg-track: #e6e6eb;
--seg-thumb: var(--card);
--seg-edge: 0 1px 2px rgba(0, 0, 0, .14), 0 0 0 .5px rgba(0, 0, 0, .08);
/* a control's quiet text (the switch's other views, a text button): darker
than --muted, so it reads at 4.5:1 or better on every surface it sits on */
--ctl-fg: #63636b;
--line: #e3e3e8;
--line-2: #ececf0;
--fg: #1c1c21;
--fg-2: #4b4b53;
--muted: #85858d;
--faint: #b9b9c2;
--accent: #4f46e5;
--accent-soft: #eeedfd;
--accent-fg: #ffffff;
--sel: #ecebfb;
--green: #189a58;
--green-soft: #e4f6ec;
--red: #d64545;
--red-soft: #fbe9e9;
--amber: #b45309;
--amber-soft: #fbf0df;
/* an agent magpie set up that no longer goes through it */
--drift: #ce2c31;
--drift-soft: #feebec;
--pop-bg: rgba(255, 255, 255, .94);
--shadow: 0 16px 44px rgba(20, 22, 30, .16), 0 2px 8px rgba(20, 22, 30, .06), 0 0 0 .5px rgba(20, 22, 30, .1);
--font: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", system-ui, sans-serif;
--code: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
--logo-invert: 0;
--tk-s: #1a7f45; --tk-k: #7c3aed; --tk-f: #1d4ed8; --tk-n: #b45309; --tk-v: #0e7490; --tk-o: #a21caf; --tk-c: #85858d;
/* what a chart tells apart: providers, agents, models */
--c1: #4f46e5; --c2: #0ea5e9; --c3: #10b981; --c4: #f59e0b; --c5: #ec4899; --c6: #8b5cf6; --c7: #64748b;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #1a1a1e;
--card: #232327;
--card-2: #1f1f23;
--pill: #2d2d33;
--pill-hover: #36363d;
--seg-track: rgba(255, 255, 255, .035);
--seg-thumb: rgba(255, 255, 255, .15);
--seg-edge: inset 0 .5px 0 rgba(255, 255, 255, .08), 0 1px 2px rgba(0, 0, 0, .3);
--line: #333339;
--line-2: #2c2c32;
--fg: #ededf1;
--fg-2: #b9b9c1;
--muted: #8b8b94;
--faint: #56565f;
--ctl-fg: #a1a1aa;
--accent: #a5b4fc;
--accent-soft: #2b2c47;
--accent-fg: #14142a;
--sel: #33345a;
--green: #6fd99b;
--green-soft: #1e3a2b;
--red: #f28b82;
--red-soft: #45272a;
--amber: #f2b544;
--amber-soft: #3f3220;
--drift: #ff9592;
--drift-soft: #3b1219;
--pop-bg: rgba(38, 38, 43, .96);
--shadow: 0 16px 44px rgba(0, 0, 0, .55), 0 2px 8px rgba(0, 0, 0, .3), 0 0 0 .5px rgba(255, 255, 255, .1);
--logo-invert: 1;
--tk-s: #98d8a4; --tk-k: #c4b5fd; --tk-f: #93c5fd; --tk-n: #f2b544; --tk-v: #67e8f9; --tk-o: #f0abfc; --tk-c: #8b8b94;
--c1: #a5b4fc; --c2: #7dd3fc; --c3: #6ee7b7; --c4: #fcd34d; --c5: #f9a8d4; --c6: #c4b5fd; --c7: #94a3b8;
}
}
:root[data-theme="dark"] {
--bg: #1a1a1e; --card: #232327; --card-2: #1f1f23; --pill: #2d2d33; --pill-hover: #36363d;
--seg-track: rgba(255, 255, 255, .035); --seg-thumb: rgba(255, 255, 255, .15); --seg-edge: inset 0 .5px 0 rgba(255, 255, 255, .08), 0 1px 2px rgba(0, 0, 0, .3);
--line: #333339; --line-2: #2c2c32; --fg: #ededf1; --fg-2: #b9b9c1; --muted: #8b8b94; --faint: #56565f; --ctl-fg: #a1a1aa;
--accent: #a5b4fc; --accent-soft: #2b2c47; --accent-fg: #14142a; --sel: #33345a;
--green: #6fd99b; --green-soft: #1e3a2b; --red: #f28b82; --red-soft: #45272a; --amber: #f2b544; --amber-soft: #3f3220;
--drift: #ff9592; --drift-soft: #3b1219;
--pop-bg: rgba(38, 38, 43, .96);
--shadow: 0 16px 44px rgba(0, 0, 0, .55), 0 2px 8px rgba(0, 0, 0, .3), 0 0 0 .5px rgba(255, 255, 255, .1);
--logo-invert: 1;
--tk-s: #98d8a4; --tk-k: #c4b5fd; --tk-f: #93c5fd; --tk-n: #f2b544; --tk-v: #67e8f9; --tk-o: #f0abfc; --tk-c: #8b8b94;
--c1: #a5b4fc; --c2: #7dd3fc; --c3: #6ee7b7; --c4: #fcd34d; --c5: #f9a8d4; --c6: #c4b5fd; --c7: #94a3b8;
}
/* Okabe–Ito qualitative series (#2073): adjacent series stay apart in hue and
lightness in both light and dark themes */
:root[data-colorblind="1"] {
--c1: #0072b2; --c2: #e69f00; --c3: #009e73; --c4: #d55e00; --c5: #cc79a7; --c6: #56b4e9; --c7: #64748b;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"])[data-colorblind="1"] {
--c1: #56b4e9; --c2: #fbbf24; --c3: #2dd4bf; --c4: #fb7185; --c5: #e879f9; --c6: #f0e442; --c7: #94a3b8;
}
}
:root[data-theme="dark"][data-colorblind="1"] {
--c1: #56b4e9; --c2: #fbbf24; --c3: #2dd4bf; --c4: #fb7185; --c5: #e879f9; --c6: #f0e442; --c7: #94a3b8;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
button { font: inherit; color: inherit; background: none; border: 0; cursor: default; appearance: none; -webkit-appearance: none; text-align: center; }
button:focus-visible, input:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
input { font: inherit; color: var(--fg); }
.icon {
width: 26px; height: 26px; border-radius: 7px;
display: inline-flex; align-items: center; justify-content: center;
color: var(--muted);
transition: background .12s, color .12s;
}
.icon:hover, .icon.on { background: var(--pill); color: var(--fg); }
.list { background: var(--card); border: 1px solid var(--line); border-radius: 12px; overflow: hidden; flex: none; }
.row { display: flex; align-items: center; gap: 9px; min-height: 40px; padding: 5px 9px 5px 11px; }
.row + .row, .editor + .row, .row + .editor { border-top: 1px solid var(--line-2); }
.row .who { min-width: 0; flex: 1 1 auto; }
.row .name { font-weight: 500; letter-spacing: -.005em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
.row .sub { font-size: 11.5px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 1px; }
.row.model:hover { background: var(--card-2); }
.row.model.selected { background: var(--sel); }
.segs { position: relative; display: inline-flex; padding: 2px; border-radius: 7px; background: var(--pill); align-self: flex-start; }
.opt { position: relative; z-index: 1; white-space: nowrap; height: 22px; padding: 0 10px; border-radius: 5px; font-size: 12px; color: var(--muted); transition: color .18s var(--ease), transform .14s var(--ease); }
.opt.on { color: var(--fg); }
.opt:hover:not(.on) { color: var(--fg-2); }
.text { font-size: 12px; color: var(--ctl-fg); padding: 3px 7px; border-radius: 6px; transition: background .12s, color .12s; white-space: nowrap; }
.text.primary { color: var(--accent-fg); background: var(--accent); font-weight: 500; }
.text.primary:hover { filter: brightness(1.08); }
input[type="checkbox"] {
appearance: none; -webkit-appearance: none;
width: 14px; height: 14px; flex: none;
display: inline-grid; place-content: center; vertical-align: middle;
border: 1px solid var(--faint); border-radius: 4px;
background: var(--card); color: var(--accent-fg);
}
input[type="checkbox"]:hover:not(:disabled) { border-color: var(--muted); }
input[type="checkbox"]:checked, input[type="checkbox"]:indeterminate { background: var(--accent); border-color: var(--accent); }
input[type="checkbox"]::before {
content: ""; width: 10px; height: 10px; background: currentColor; transform: scale(0);
-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Cpath d='M2 5.2l2 2L8 3' fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / contain no-repeat;
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'%3E%3Cpath d='M2 5.2l2 2L8 3' fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center / contain no-repeat;
}
input[type="checkbox"]:checked::before { transform: scale(1); }
input[type="checkbox"]:indeterminate::before { transform: scale(1); -webkit-mask: none; mask: none; width: 8px; height: 1.6px; border-radius: 1px; }
input[type="checkbox"]:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
input[type="checkbox"]:disabled { opacity: .45; }
.lib-switch { flex: none; position: relative; width: 32px; height: 19px; border-radius: 10px; background: var(--line); transition: background .2s var(--ease); }
.lib-switch i { position: absolute; top: 2px; left: 2px; width: 15px; height: 15px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px rgba(0, 0, 0, .25); transition: transform .22s var(--ease); }
.lib-switch.on { background: var(--fg); }
.lib-switch.on i { transform: translateX(13px); background: var(--card); }
:root[data-theme="dark"] .lib-switch.on i { background: var(--bg); }
+2
View File
@@ -100,6 +100,8 @@
{"package": "@magpie-community/tools-layerfs", "name": "LayerFS", "kind": "tools", "community": true, "summary": {"en": "LayerFS workspaces for every agent: deduplicated checkpoints and branches behind stable filesystem paths, instead of a fresh copy of the tree for every agent.", "zh": "给每个 agent 的 LayerFS 工作区:稳定的文件系统路径背后是可去重的检查点与分支,而不是每个 agent 各复制一棵项目树。"}},
{ "package": "@magpie-community/page-usage", "name": "Usage Glance", "kind": "page", "community": true,
"summary": { "en": "A page in magpie's window with calls, errors, tokens and cost for today, 7 or 30 days, and the models behind them. Reads only your usage summary.", "zh": "在 magpie 窗口里一眼看到今天、7 天或 30 天的调用、错误、token、费用和对应模型。只读取用量汇总。" } },
{ "package": "@magpie-community/page-fingerprint", "name": "Fingerprint", "kind": "page", "community": true,
"summary": { "en": "Check for suspected model substitution by comparing response fingerprints across Magpie providers. Uses lm-detector with shared challenges, local evidence history and JSON export; sampling uses provider quota. Reference data is downloaded on demand from lm.ikale.io, falling back to cdn.jsdmirror.com.", "zh": "在 Magpie 内检测响应指纹,为疑似模型替换提供核查线索。基于 lm-detector,支持跨渠道共享挑战、保留本地证据与 JSON 导出;采样会消耗模型额度。参考库按需从 lm.ikale.io 下载,备用源为 cdn.jsdmirror.com。" } },
{ "package": "@magpie-community/page-chat", "name": "Chat", "kind": "page", "community": true,
"summary": { "en": "A chat page in magpie's window by Magic_zero: talk to magpie's own models with your MCP servers, instructions and skills, images and LaTeX. Runs a local service on 127.0.0.1 that only its own page can use.", "zh": "Magic_zero 做的 magpie 窗口内「对话」页面:用 magpie 自己的模型聊天,带上你的 MCP 服务器、指令和技能,支持图片与 LaTeX。本地服务只在 127.0.0.1,只给自己的页面用。" } },
{ "package": "@magpie-community/page-agent-office", "name": "Agent Office", "kind": "page", "community": true,