reasonix-desktop 0.1.0: Reasonix 1.x in Discover → Agents (#700)

Adds Reasonix 1.x (Desktop and CLI) to Plugins → Discover → Agents as
`@magpie-community/agent-reasonix-desktop`, agent id `reasonix-desktop`,
separate from magpie's built-in `reasonix` adapter (Studio 2.x and native
1.39). A JSON agent descriptor plus a Bun-host companion (the kimi-desktop
pattern) adds one `magpie-agent` provider to Reasonix's global config.toml
and keeps only the assigned gateway key in its .env, with a journal, a
lock and byte-exact restore on disconnect.

Review commit on the branch: the registry entry's icon was `reasonix`, a
mask name with no icons/reasonix.svg, so Discover would show the generic
mark; it is `reasonix-color` now.

Run at the reviewed head 6cb328f090d8b66e6cf590a69aa4e7b18144c684 (mote):
- packages/reasonix-desktop `bun test`: 12 pass, 0 fail.
- acceptance.mjs with a real Reasonix 1.38.10 (npm) and a magpie built
  from origin/main 4ca55c6b6, sandbox HOME: magpie installs and discovers
  the plugin and bridges the selected model; unchanged Reasonix sends its
  selected model and assigned key to the local API; disconnect restores
  the original selection and credentials.
- resident-acceptance.mjs (a running `magpie serve` follows the switch):
  passed.
- vendor.mjs rebuilt from its pinned sources: byte-identical.
- CI run 41773750085 on 6cb328f0: success.
Not tried: Reasonix Desktop's GUI app itself (the CLI reads the same
config files), Windows and Linux.
This commit is contained in:
SivanCola
2026-11-04 12:38:13 +08:00
committed by GitHub
parent db307844e7
commit 075cd237e2
18 changed files with 1209 additions and 0 deletions
+1
View File
@@ -234,6 +234,7 @@ it off puts the config back.
| Package | Agent | | Package | Agent |
|---|---| |---|---|
| [aider](packages/aider) | [Aider](https://aider.chat): `~/.aider.conf.yml`, through litellm's `openai/` prefix | | [aider](packages/aider) | [Aider](https://aider.chat): `~/.aider.conf.yml`, through litellm's `openai/` prefix |
| [reasonix-desktop](packages/reasonix-desktop) | [Reasonix 1.x](https://github.com/esengine/DeepSeek-Reasonix/tree/main-v2) Desktop and CLI: reversible global TOML/dotenv bridge; restart Reasonix after choosing a model. Separate from the built-in Studio 2.x adapter |
| [bub](packages/bub) | [Bub](https://bub.build): `~/.bub/config.yml`, as the `magpie:` provider (needs Bub 0.5.1 or later) | | [bub](packages/bub) | [Bub](https://bub.build): `~/.bub/config.yml`, as the `magpie:` provider (needs Bub 0.5.1 or later) |
| [kilo](packages/kilo) | [Kilo Code](https://kilo.ai): `~/.config/kilo/kilo.jsonc`, through an OpenAI-compatible provider | | [kilo](packages/kilo) | [Kilo Code](https://kilo.ai): `~/.config/kilo/kilo.jsonc`, through an OpenAI-compatible provider |
| [junie](packages/junie) | [Junie CLI](https://junie.jetbrains.com/): an explicit `/v1/models` seed for its full picker and Magpie's selected model as the launch default; no LiteLLM | | [junie](packages/junie) | [Junie CLI](https://junie.jetbrains.com/): an explicit `/v1/models` seed for its full picker and Magpie's selected model as the launch default; no LiteLLM |
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 SivanCola
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.
+23
View File
@@ -0,0 +1,23 @@
Copyright (c) 2015, Scott Motte
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Reasonix Contributors
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.
@@ -0,0 +1,24 @@
Copyright (c) Squirrel Chat et al., All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+96
View File
@@ -0,0 +1,96 @@
# Reasonix 1.x
Adds Reasonix 1.x Desktop and CLI to Magpie's Agents page as
**Reasonix 1.x**, ID `reasonix-desktop`. This is separate from Magpie's built-in
`reasonix` adapter for Reasonix Studio 2.x.
```sh
magpie plugin add @magpie-community/agent-reasonix-desktop
```
Choose a model on its Agent row, wait about a second with Magpie running, then
restart Reasonix and start a new conversation. Explicit project
`reasonix.toml`, CLI model flags and existing session selections retain their
own precedence.
## Configuration and restoration
The package includes an Agent descriptor plus a companion in Magpie's Bun
host, as the current generic Agent writer supports JSON/YAML/dotenv, not TOML
with a separate credential file. It works on unmodified Magpie and Reasonix;
no daemon installation, provider login, remote service or host patch is needed.
The parsing libraries are vendored at exact versions with their licenses.
The descriptor writes only `~/.reasonix/magpie-agent.json`. The host bridges
it into `~/.reasonix/config.toml`, adding the `magpie-agent` OpenAI Chat
Completions provider and its default model; the assigned gateway key goes
only into `~/.reasonix/.env` as `MAGPIE_REASONIX_DESKTOP_API_KEY`. Upstream
provider secrets remain in Magpie. Existing providers and other settings are
kept. Known context/output sizes and image support follow the chosen model.
Choose the Agent's default to disconnect, wait for the bridge, then restart
Reasonix. A normal Magpie host exit flushes a pending disconnect, including
when disabling the plugin while Magpie is running. For CLI-only operation,
finish restoration while the plugin is still enabled:
```sh
magpie reasonix-desktop default
magpie plugin list --json
# Remove only after restoration completes:
magpie plugin rm @magpie-community/agent-reasonix-desktop
```
The one-shot fallback is `node cli.mjs sync` from this package. After a forced
host kill, re-enable the plugin and disconnect to finish restoration.
Private backups and a replayable journal live in `~/.reasonix/.magpie-bridge/`.
They contain original credential-file contents; retain them if restoration
pauses. Writes use private files and atomic replacement. On disconnect,
untouched files return byte for byte; unrelated edits and Reasonix startup
migrations are merged and retained. TOML formatting/comments may change while
connected, and merged restoration cannot promise their original formatting.
Manual changes to managed fields pause synchronization rather than being
overwritten. Do not edit Reasonix model settings during a switch.
## Compatibility
Targets Reasonix 1.x with shared global `config.toml` and `.env` (v1.8.1+).
Verified with unmodified Magpie 0.1.2890 and Reasonix 1.38.10 against a local
model fixture. It does not target Studio 2.x. Disable an existing standalone
Reasonix plugin before enabling this package; both use `reasonix-desktop`.
Default paths target macOS/Linux. For Windows or a custom `REASONIX_HOME`,
install a local copy with the descriptor's `dir` and `config` changed to the
actual Reasonix home (Windows normally `%APPDATA%/reasonix`). The bridge derives
`config.toml` and `.env` from that config path; it cannot infer another
process's environment. Native Windows Reasonix acceptance is not claimed.
## Development
```sh
bun test ./packages/reasonix-desktop
bun scripts/check.mjs reasonix-desktop
MAGPIE_BIN=/path/to/magpie REASONIX_BIN=/path/to/reasonix node packages/reasonix-desktop/acceptance.mjs
MAGPIE_BIN=/path/to/magpie node packages/reasonix-desktop/resident-acceptance.mjs
```
Acceptance uses temporary config/state homes and a localhost model fixture.
It installs the actual package in Magpie, checks the Agent and selected model,
then optionally exercises an unchanged Reasonix binary and its assigned
credential. No real account, saved sign-in or paid request is used. See
[THIRD_PARTY.md](THIRD_PARTY.md) for source attribution and vendored code.
## 中文
把 **Reasonix 1.x** 桌面版和 CLI 加入 Magpie 的 Agent 页,ID 为
`reasonix-desktop`,与内置的 Reasonix Studio 2.x 分开。安装后选模型,
保持 Magpie 运行并等待约一秒,再重启 Reasonix、新建会话。
插件随包桥接 TOML 和独立 `.env`,不修改原程序、不安装额外守护进程。
原有供应商和无关设置保留,网关密钥只写入全局 `.env`。项目配置、CLI
参数及已有会话仍保留自己的优先级。备份含原始凭据文件,请妥善保管。
卸载前先选择 Agent 默认值完成恢复。仅用 CLI 时执行上面的 `default`
和 `plugin list --json` 两步,再卸载。Magpie 运行期间正常关闭插件宿主会
补做恢复;强制终止后需重新启用插件并断开。同步期间不要手工改动受管理
的供应商、默认模型和凭据。自定义目录及 Windows 请先按上述说明修改路径。
+31
View File
@@ -0,0 +1,31 @@
# Source and licenses
The Agent descriptor and bridge are adapted from
[SivanCola/magpie-agent-reasonix at 7f190e8](https://github.com/SivanCola/magpie-agent-reasonix/tree/7f190e801962e24cd791abaa70c8d2e7ac755a15),
MIT, copyright (c) 2026 SivanCola. See `LICENSE`.
The embedded PNG is Reasonix's unmodified 128 × 128 application icon from
[esengine/DeepSeek-Reasonix e81658d](https://github.com/esengine/DeepSeek-Reasonix/blob/e81658de81ab957d8f9f6277f6a7b48b8400261f/desktop/build/linux/icons/hicolor/128x128/apps/reasonix-desktop.png),
MIT, copyright (c) 2026 Reasonix Contributors. See `LICENSE-REASONIX`.
`vendor.mjs` bundles these exact parsing libraries so this Agent needs no
runtime dependency installation or build scripts:
- `smol-toml` 1.9.1, BSD-3-Clause (`LICENSE-SMOL-TOML`).
- `dotenv` 18.0.9, BSD-2-Clause (`LICENSE-DOTENV`). Only `parse` is exported;
the bridge never calls dotenv's environment-loading functions.
To regenerate in this package folder with Bun 1.4.4:
```sh
npm install --no-save --ignore-scripts --package-lock=false smol-toml@1.9.1 dotenv@18.0.9
bun build vendor-entry.mjs --target=node --format=esm --minify --outfile=vendor.mjs
```
No original Reasonix or Magpie source changes are needed to use this package.
## 中文
桥接与 Agent 入口改编自上述独立插件,图标来自上述 Reasonix 原始提交,
均保留 MIT 许可。TOML 与 dotenv 解析器以固定版本打包,保留 BSD 许可;
无需安装运行时依赖或执行构建脚本。插件不改动 Reasonix 或 Magpie 程序。
+104
View File
@@ -0,0 +1,104 @@
// Optional native acceptance. Everything uses disposable homes and a localhost
// model fixture: no user config, subscription credentials or paid model calls.
import assert from "node:assert/strict"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import http from "node:http"
import { execFile } from "node:child_process"
import { promisify } from "node:util"
import { fileURLToPath } from "node:url"
import { parseTOML as parse, stringify, parseEnv } from "./vendor.mjs"
const exec = promisify(execFile)
const root = fs.mkdtempSync(path.join(os.tmpdir(), "magpie-reasonix-native-"))
const repo = fileURLToPath(new URL(".", import.meta.url))
const magpie = process.env.MAGPIE_BIN || "magpie"
const reasonix = process.env.REASONIX_BIN
const native = false
const env = { ...process.env, HOME: root, USERPROFILE: root, XDG_CONFIG_HOME: path.join(root, ".config"), XDG_CACHE_HOME: path.join(root, ".cache"), XDG_STATE_HOME: path.join(root, ".state"), REASONIX_HOME: path.join(root, ".reasonix"), REASONIX_STATE_HOME: path.join(root, ".reasonix-state"), MAGPIE_NO_ACCOUNTS: "1" }
const dz = env.REASONIX_HOME
const config = path.join(dz, "config.toml")
const control = path.join(dz, "magpie-agent.json")
const run = async (bin, args) => exec(bin, args, { cwd: root, env, timeout: 120000, maxBuffer: 2 << 20 })
let requests = 0
let expectedKey = ""
const server = http.createServer(async (req, res) => {
let raw = ""
for await (const chunk of req) raw += chunk
if (req.method === "GET") {
res.setHeader("content-type", "application/json")
res.end(JSON.stringify({ object: "list", data: [{ id: "fixture/test-model", object: "model" }] }))
return
}
const body = JSON.parse(raw)
assert.equal(req.url, "/v1/chat/completions")
assert.equal(body.model, "fixture/test-model")
assert.equal(req.headers.authorization, `Bearer ${expectedKey}`)
requests++
if (body.stream) {
res.setHeader("content-type", "text/event-stream")
res.end(`data: ${JSON.stringify({ id: "fixture", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "bridge-ok" }, finish_reason: null }] })}\n\ndata: ${JSON.stringify({ id: "fixture", object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })}\n\ndata: [DONE]\n\n`)
} else {
res.setHeader("content-type", "application/json")
res.end(JSON.stringify({ id: "fixture", object: "chat.completion", choices: [{ index: 0, message: { role: "assistant", content: "bridge-ok" }, finish_reason: "stop" }], usage: { prompt_tokens: 10, completion_tokens: 2, total_tokens: 12 } }))
}
})
try {
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve))
const base = `http://127.0.0.1:${server.address().port}/v1`
fs.mkdirSync(dz, { recursive: true })
fs.mkdirSync(path.join(env.XDG_CONFIG_HOME, "magpie"), { recursive: true })
const original = '# native acceptance fixture\ndefault_model="mine/model"\n[[providers]]\nname="mine"\nkind="openai"\nbase_url="http://127.0.0.1:49998/v1"\nmodels=["model"]\n'
fs.writeFileSync(config, original)
fs.writeFileSync(path.join(dz, ".env"), "OTHER_KEY=fixture-original\n")
fs.writeFileSync(path.join(env.XDG_CONFIG_HOME, "magpie/providers.json"), JSON.stringify({ providers: [{ id: "fixture", name: "Fixture", key: "fixture-only", chat: base, models: ["test-model"] }] }))
await run(magpie, ["plugin", "add", native ? path.join(repo, "native") : repo])
const agents = await run(magpie, ["agents"])
assert.match(agents.stdout, /Reasonix 1\.x/)
await run(magpie, ["reasonix-desktop", "fixture/test-model"])
// Loading the real plugin host executes the companion bridge.
const loaded = await run(magpie, ["plugin", "list", "--json"])
assert.ok(!JSON.parse(loaded.stdout).loaded.some(plugin => plugin.error))
assert.equal(parse(fs.readFileSync(config, "utf8")).default_model, "magpie-agent/fixture/test-model")
console.log(`PASS: Magpie installs and discovers reasonix-desktop; ${native ? "native TOML support writes" : "its plugin host bridges"} the selected model`)
if (reasonix) {
expectedKey = parseEnv(fs.readFileSync(path.join(dz, ".env"))).MAGPIE_REASONIX_DESKTOP_API_KEY
assert.ok(expectedKey)
// Keep Magpie's selected ID and assigned key. Redirect only the isolated
// control file to a local API fixture so no live gateway account is used.
if (native) {
const cfg = parse(fs.readFileSync(config, "utf8"))
cfg.providers.find(p => p.name === "magpie-agent").base_url = base
fs.writeFileSync(config, stringify(cfg))
} else {
const cfg = JSON.parse(fs.readFileSync(control, "utf8"))
cfg.baseURL = base
fs.writeFileSync(control, JSON.stringify(cfg))
await run(process.execPath, [path.join(repo, "cli.mjs"), "sync"])
}
const result = await run(reasonix, ["-p", "Reply with bridge-ok", "--output-format", "json"])
assert.ok(requests > 0)
assert.match(result.stdout, /bridge-ok/)
console.log("PASS: unchanged Reasonix sends its selected model and assigned credential to the local API")
}
await run(magpie, ["reasonix-desktop", "default"])
if (!native) await run(process.execPath, [path.join(repo, "cli.mjs"), "sync"])
if (reasonix) {
// Reasonix may migrate its own config on startup. Those unrelated edits
// belong to Reasonix and must survive the bridge's disconnect.
const restored = parse(fs.readFileSync(config, "utf8"))
assert.equal(restored.default_model, "mine/model")
assert.deepEqual(restored.providers.map(p => p.name), ["mine"])
assert.equal(restored.providers[0].base_url, "http://127.0.0.1:49998/v1")
} else if (!native) {
assert.equal(fs.readFileSync(config, "utf8"), original)
}
assert.equal(fs.readFileSync(path.join(dz, ".env"), "utf8"), "OTHER_KEY=fixture-original\n")
console.log("PASS: disconnect restores the original selection and credentials, preserving Reasonix's own migrations")
} finally {
server.closeAllConnections()
await new Promise(resolve => server.close(resolve))
fs.rmSync(root, { recursive: true, force: true })
}
+217
View File
@@ -0,0 +1,217 @@
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { randomUUID } from "node:crypto"
import { isDeepStrictEqual } from "node:util"
import { parseTOML, stringify, parseEnv } from "./vendor.mjs"
import { agent } from "./reasonix-desktop.agent.js"
export const PROVIDER = "magpie-agent"
export const KEY = "MAGPIE_REASONIX_DESKTOP_API_KEY"
const active = new Map()
const parse = (text) => parseTOML(text || "", { integersAsBigInt: "asNeeded" })
export function pathsFor(home = os.homedir()) {
const control = agent.config.replace(/^~(?=\/|$)/, home)
if (!path.isAbsolute(control)) throw new Error("Agent config must name an absolute path or ~/ path")
const reasonix = path.dirname(control)
return {
control,
config: path.join(reasonix, "config.toml"),
env: path.join(reasonix, ".env"),
state: path.join(reasonix, ".magpie-bridge", "state.json"),
}
}
function read(file) {
try {
const st = fs.lstatSync(file)
if (!st.isFile() || st.isSymbolicLink()) throw new Error("Bridge refuses non-regular files")
return fs.readFileSync(file, "utf8")
} catch (e) {
if (e.code === "ENOENT") return null
throw e
}
}
function write(file, text) {
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
// Preserve the user's directory; all bridge-created files are private.
if (text === null) {
fs.rmSync(file, { force: true })
return
}
const temp = path.join(path.dirname(file), `.magpie-${randomUUID()}.tmp`)
try {
fs.writeFileSync(temp, text, { mode: 0o600, flag: "wx" })
fs.renameSync(temp, file)
} finally {
fs.rmSync(temp, { force: true })
}
}
function json(file) {
const raw = read(file)
return raw === null ? null : JSON.parse(raw)
}
function lock(file) {
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
try {
fs.writeFileSync(file, String(process.pid), { mode: 0o600, flag: "wx" })
} catch (e) {
if (e.code !== "EEXIST") throw e
const pid = Number(read(file))
if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error("Invalid bridge lock; inspect .magpie-bridge/lock")
try { process.kill(pid, 0) } catch (error) {
if (error.code !== "ESRCH") throw error
fs.unlinkSync(file)
return lock(file)
}
throw new Error("Another bridge operation is running")
}
return () => fs.unlinkSync(file)
}
// A durable journal precedes every multi-file change. Recovery accepts only
// the exact before/after states; concurrent edits are never overwritten.
function recover(p) {
const journalPath = p.state + ".pending"
const journal = json(journalPath)
if (!journal) return
for (const change of journal.changes) {
if (![p.config, p.env].includes(change.file)) throw new Error("Invalid bridge journal target")
const current = read(change.file)
if (current !== change.before && current !== change.after) throw new Error("Bridge recovery paused: configuration changed; retain .magpie-bridge for recovery")
}
for (const change of journal.changes) if (read(change.file) !== change.after) write(change.file, change.after)
write(p.state, journal.state === null ? null : JSON.stringify(journal.state))
fs.unlinkSync(journalPath)
}
function commit(p, changes, state) {
for (const change of changes) {
if (read(change.file) !== change.before) throw new Error("Configuration changed during bridge update; retry")
}
write(p.state + ".pending", JSON.stringify({ changes, state }))
recover(p)
}
function desired(control) {
if (!control?.gatewayKey && !control?.baseURL) return null
if (typeof control.model !== "string" || !control.model.trim() || typeof control.gatewayKey !== "string" || !control.gatewayKey || typeof control.baseURL !== "string") throw new Error("Incomplete Magpie connection; select its model again")
const url = new URL(control.baseURL)
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error("Invalid Magpie gateway URL")
if (/[\r\n'\\]/.test(control.gatewayKey)) throw new Error("Unsupported gateway key encoding")
const entry = {
name: PROVIDER, display_name: "Magpie", kind: "openai", base_url: control.baseURL,
models: [control.model], default: control.model, api_key_env: KEY,
}
const info = control.modelInfo || {}
if (Number.isSafeInteger(info.context) && info.context > 0) entry.context_window = info.context
if (Number.isSafeInteger(info.output) && info.output > 0) entry.max_output_tokens = info.output
if (typeof info.images === "boolean") entry.model_overrides = { [control.model]: { vision: info.images } }
return { entry, key: control.gatewayKey, ref: `${PROVIDER}/${control.model}` }
}
function patchKey(raw, value) {
const text = raw || ""
// Refuse ambiguous multiline assignments of the owned key instead of
// touching another credential's continuation lines.
const lines = text.split(/(?<=\n)/)
const pattern = new RegExp(`^\\s*(?:export\\s+)?${KEY}\\s*=`)
const found = lines.filter(line => pattern.test(line))
if (found.length > 1) throw new Error("Duplicate bridge credential assignments")
if (found.length && parseEnv(found[0])[KEY] !== parseEnv(text)[KEY]) throw new Error("Multiline bridge credentials are unsupported")
const eol = text.includes("\r\n") ? "\r\n" : "\n"
const assignment = value === undefined ? "" : `${KEY}='${value}'${eol}`
if (found.length) return lines.map(line => pattern.test(line) ? assignment : line).join("")
return value === undefined ? text : text + (text && !text.endsWith("\n") ? eol : "") + assignment
}
function assertOwned(cfg, env, state) {
const previous = parse(state.lastConfig)
if (!isDeepStrictEqual(cfg.providers?.find(p => p.name === PROVIDER), previous.providers?.find(p => p.name === PROVIDER))) throw new Error("Managed Magpie provider was edited; disconnect before reconnecting")
if (cfg.default_model !== previous.default_model) throw new Error("Default model was edited; disconnect before reconnecting")
if (parseEnv(env || "")[KEY] !== parseEnv(state.lastEnv || "")[KEY]) throw new Error("Bridge credential was edited; disconnect before reconnecting")
}
function restoredConfig(config, state) {
if (config === state.lastConfig) return state.originalConfig
const cfg = parse(config)
const original = parse(state.originalConfig)
const previous = parse(state.lastConfig)
const entry = cfg.providers?.find(p => p.name === PROVIDER)
if (entry && !isDeepStrictEqual(entry, previous.providers?.find(p => p.name === PROVIDER))) throw new Error("Managed provider changed; restore it before disconnecting (backup retained)")
cfg.providers = (cfg.providers || []).filter(p => p.name !== PROVIDER)
if (!cfg.providers.length && !Object.hasOwn(original, "providers")) delete cfg.providers
if (cfg.default_model === previous.default_model) {
if (Object.hasOwn(original, "default_model")) cfg.default_model = original.default_model
else delete cfg.default_model
}
if (Array.isArray(cfg.desktop?.provider_access) && !original.desktop?.provider_access?.includes(PROVIDER)) cfg.desktop.provider_access = cfg.desktop.provider_access.filter(name => name !== PROVIDER)
return stringify(cfg)
}
function restoredEnv(env, state) {
if (env === state.lastEnv) return state.originalEnv
const mine = parseEnv(state.lastEnv || "")[KEY]
return parseEnv(env || "")[KEY] === mine ? patchKey(env, parseEnv(state.originalEnv || "")[KEY]) : env
}
export function syncBridge(p = pathsFor()) {
if (read(p.control) === null && read(p.state) === null && read(p.state + ".pending") === null) return "disconnected"
const unlock = lock(path.join(path.dirname(p.state), "lock"))
try {
recover(p)
const state = json(p.state)
const control = json(p.control)
const want = desired(control)
if (!want && !state) return "disconnected"
const config = read(p.config)
const env = read(p.env)
const cfg = parse(config)
if (want) {
if (state) assertOwned(cfg, env, state)
else {
if (cfg.providers?.some(entry => entry.name === PROVIDER)) throw new Error("Provider magpie-agent already exists; rename it before connecting")
if (Object.hasOwn(parseEnv(env || ""), KEY) || cfg.providers?.some(entry => entry.api_key_env === KEY)) throw new Error("Bridge credential name already belongs to existing configuration")
}
const next = { ...cfg, default_model: want.ref, providers: [...(cfg.providers || []).filter(entry => entry.name !== PROVIDER), want.entry] }
if (Array.isArray(cfg.desktop?.provider_access)) next.desktop = { ...cfg.desktop, provider_access: [...new Set([...cfg.desktop.provider_access, PROVIDER])] }
const nextConfig = isDeepStrictEqual(cfg, next) ? config : stringify(next)
const nextEnv = parseEnv(env || "")[KEY] === want.key ? env : patchKey(env, want.key)
if (state && config === nextConfig && env === nextEnv) return "connected"
const nextState = {
version: 1,
originalConfig: state ? restoredConfig(config, state) : config,
originalEnv: state ? restoredEnv(env, state) : env,
lastConfig: nextConfig, lastEnv: nextEnv,
}
commit(p, [{ file: p.env, before: env, after: nextEnv }, { file: p.config, before: config, after: nextConfig }], nextState)
return "connected"
}
const nextConfig = restoredConfig(config, state)
const nextEnv = restoredEnv(env, state)
commit(p, [{ file: p.config, before: config, after: nextConfig }, { file: p.env, before: env, after: nextEnv }], null)
return "disconnected"
} finally { unlock() }
}
export function startBridge(p = pathsFor(), { interval = 750, onError = () => console.error("Reasonix bridge paused; run magpie-reasonix sync for details (configuration retained).") } = {}) {
if (active.has(p.state)) return active.get(p.state)
let previousError = ""
const tick = () => {
try { syncBridge(p); previousError = "" } catch (error) {
// Parser errors can contain a source line; never write those to logs.
if (error.message !== previousError) onError()
previousError = error.message
}
}
tick()
const timer = setInterval(tick, interval)
timer.unref?.()
const stop = () => { clearInterval(timer); active.delete(p.state) }
active.set(p.state, stop)
return stop
}
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env node
import { syncBridge } from "./bridge.mjs"
if (!process.argv[2] || process.argv[2] === "sync") {
try { console.log(`Reasonix bridge: ${syncBridge()}`) } catch {
console.error("Reasonix bridge could not synchronize. Check JSON/TOML syntax, reserved provider/credential conflicts, file permissions and .magpie-bridge recovery files. Source contents and keys are omitted.")
process.exitCode = 1
}
} else {
console.error("Usage: magpie-reasonix sync")
process.exitCode = 2
}
+22
View File
@@ -0,0 +1,22 @@
import { pathsFor, startBridge, syncBridge } from "./bridge.mjs"
const instance = Symbol.for("magpie.reasonix-desktop.bridge.v1")
// The Agent entry runs in moejs; this companion runs in the shared Bun host
// because current Magpie cannot edit TOML and a separate dotenv file there.
export default async function ReasonixDesktop() {
if (!globalThis[instance]) {
const paths = pathsFor()
const stop = startBridge(paths)
globalThis[instance] = { stop }
// Magpie restores the control JSON before closing the host on disable or
// removal. Flush it synchronously on normal exit, without taking over the
// shared host's signals or terminating other plugins.
process.once("exit", () => {
try { syncBridge(paths) } catch {
console.error("Reasonix bridge restoration paused; configuration and recovery files retained.")
}
})
}
return {}
}
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,237 @@
import assert from "node:assert/strict"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { test } from "node:test"
import { spawnSync } from "node:child_process"
import { parseTOML as parse, stringify, parseEnv } from "./vendor.mjs"
import { PROVIDER, KEY, syncBridge, startBridge } from "./bridge.mjs"
import { agent, connect } from "./reasonix-desktop.agent.js"
const originalConfig = `# User's comments and preferences
config_version = 12
default_model = "mine/model"
[agent]
compact_ratio = 0.8
[desktop]
provider_access = ["mine"]
[[providers]]
name = "mine"
kind = "openai"
base_url = "http://127.0.0.1:9999/v1"
models = ["model"]
api_key_env = "MY_API_KEY"
`
const originalEnv = "# existing secret\r\nMY_API_KEY=fixture-original\r\n"
function fixture(t) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "magpie-reasonix-"))
t.after(() => fs.rmSync(root, { recursive: true, force: true }))
const p = { control: path.join(root, "magpie-agent.json"), config: path.join(root, "config.toml"), env: path.join(root, ".env"), state: path.join(root, ".magpie-bridge/state.json") }
fs.writeFileSync(p.config, originalConfig)
fs.writeFileSync(p.env, originalEnv)
const select = (id = "vendor/model-v1", key = "fixture-gateway-key") => {
const model = { id, context: 200000, output: 16000, images: true }
fs.writeFileSync(p.control, JSON.stringify({ model: id, ...connect({ model, gateway: { v1: "http://127.0.0.1:3425/v1", key } }) }))
}
return { p, select, disconnect: () => fs.writeFileSync(p.control, "{}") }
}
test("agent descriptor and sandbox hook expose one selected model", () => {
assert.equal(agent.id, "reasonix-desktop")
assert.equal(agent.format, "json")
assert.equal(agent.model, "model")
assert.throws(() => connect({ gateway: {} }), /Choose a model/)
})
test("connect, switch, restart bridge, disconnect restores exact original bytes", t => {
const { p, select, disconnect } = fixture(t)
select()
assert.equal(syncBridge(p), "connected")
let cfg = parse(fs.readFileSync(p.config, "utf8"))
assert.equal(cfg.default_model, "magpie-agent/vendor/model-v1")
assert.equal(cfg.providers.length, 2)
assert.deepEqual(cfg.providers[0], parse(originalConfig).providers[0])
assert.equal(cfg.providers[1].model_overrides["vendor/model-v1"].vision, true)
assert.deepEqual(cfg.desktop.provider_access, ["mine", PROVIDER])
const env = parseEnv(fs.readFileSync(p.env))
assert.equal(env.MY_API_KEY, "fixture-original")
assert.equal(env[KEY], "fixture-gateway-key")
assert.ok(!fs.readFileSync(p.config, "utf8").includes("fixture-gateway-key"))
if (process.platform !== "win32") {
for (const file of [p.state, p.control, p.config, p.env]) {
if (file === p.control) continue // Magpie owns that file's permissions.
assert.equal(fs.statSync(file).mode & 0o777, 0o600)
}
}
const before = fs.statSync(p.config).mtimeMs
assert.equal(syncBridge(p), "connected")
assert.equal(fs.statSync(p.config).mtimeMs, before)
select("vendor/model-v2", "fixture-key-2")
assert.equal(syncBridge(p), "connected")
cfg = parse(fs.readFileSync(p.config, "utf8"))
assert.equal(cfg.default_model, "magpie-agent/vendor/model-v2")
assert.equal(cfg.providers.length, 2)
disconnect()
assert.equal(syncBridge(p), "disconnected")
assert.equal(fs.readFileSync(p.config, "utf8"), originalConfig)
assert.equal(fs.readFileSync(p.env, "utf8"), originalEnv)
assert.ok(!fs.existsSync(p.state))
})
test("first installation and disconnect leave originally absent files absent", t => {
const { p, select, disconnect } = fixture(t)
fs.unlinkSync(p.config)
fs.unlinkSync(p.env)
select()
syncBridge(p)
disconnect()
syncBridge(p)
assert.ok(!fs.existsSync(p.config))
assert.ok(!fs.existsSync(p.env))
})
test("unrelated edits during connection survive switching and disconnect", t => {
const { p, select, disconnect } = fixture(t)
select()
syncBridge(p)
const cfg = parse(fs.readFileSync(p.config, "utf8"))
cfg.language = "zh"
fs.writeFileSync(p.config, stringify(cfg))
fs.appendFileSync(p.env, "NEW_SECRET=fixture-new\n")
select("p/new")
syncBridge(p)
disconnect()
syncBridge(p)
assert.equal(parse(fs.readFileSync(p.config, "utf8")).language, "zh")
assert.equal(parseEnv(fs.readFileSync(p.env)).NEW_SECRET, "fixture-new")
assert.equal(parseEnv(fs.readFileSync(p.env)).MY_API_KEY, "fixture-original")
assert.ok(!Object.hasOwn(parseEnv(fs.readFileSync(p.env)), KEY))
})
test("manual default and key edits are not overwritten", t => {
const { p, select, disconnect } = fixture(t)
select()
syncBridge(p)
const cfg = parse(fs.readFileSync(p.config, "utf8"))
cfg.default_model = "mine/other"
fs.writeFileSync(p.config, stringify(cfg))
fs.appendFileSync(p.env, `${KEY}=manual-key\n`)
assert.throws(() => syncBridge(p), /Default model was edited/)
disconnect()
syncBridge(p)
assert.equal(parse(fs.readFileSync(p.config, "utf8")).default_model, "mine/other")
assert.equal(parseEnv(fs.readFileSync(p.env))[KEY], "manual-key")
})
test("a conflicting provider is refused without writes", t => {
const { p, select } = fixture(t)
fs.writeFileSync(p.config, `[[providers]]\nname="${PROVIDER}"\nmodels=["manual"]\n`)
const before = fs.readFileSync(p.config, "utf8")
select()
assert.throws(() => syncBridge(p), /already exists/)
assert.equal(fs.readFileSync(p.config, "utf8"), before)
assert.equal(fs.readFileSync(p.env, "utf8"), originalEnv)
})
test("existing bridge-named credentials and references are never taken over", t => {
const { p, select } = fixture(t)
select()
const conflict = originalEnv + `${KEY}=fixture-user-key\n`
fs.writeFileSync(p.env, conflict)
assert.throws(() => syncBridge(p), /credential name already belongs/)
assert.equal(fs.readFileSync(p.config, "utf8"), originalConfig)
assert.equal(fs.readFileSync(p.env, "utf8"), conflict)
fs.writeFileSync(p.env, originalEnv)
const cfg = parse(originalConfig)
cfg.providers[0].api_key_env = KEY
const referenced = stringify(cfg)
fs.writeFileSync(p.config, referenced)
assert.throws(() => syncBridge(p), /credential name already belongs/)
assert.equal(fs.readFileSync(p.config, "utf8"), referenced)
assert.equal(fs.readFileSync(p.env, "utf8"), originalEnv)
})
test("invalid TOML and incomplete connection do not touch configuration or credentials", t => {
const { p, select } = fixture(t)
select()
fs.writeFileSync(p.config, "default_model = [broken")
assert.throws(() => syncBridge(p))
assert.equal(fs.readFileSync(p.env, "utf8"), originalEnv)
assert.ok(!fs.existsSync(p.state))
fs.writeFileSync(p.config, originalConfig)
fs.writeFileSync(p.control, JSON.stringify({ baseURL: "http://localhost/v1" }))
assert.throws(() => syncBridge(p), /Incomplete/)
assert.equal(fs.readFileSync(p.config, "utf8"), originalConfig)
})
test("interrupted journal recovers, but external edits stop recovery before writes", t => {
const { p, select } = fixture(t)
select()
syncBridge(p)
const state = JSON.parse(fs.readFileSync(p.state, "utf8"))
const nextEnv = state.lastEnv + "EXTRA=ok\n"
const pending = { state: { ...state, lastEnv: nextEnv }, changes: [{ file: p.env, before: state.lastEnv, after: nextEnv }, { file: p.config, before: state.originalConfig, after: state.lastConfig }] }
fs.writeFileSync(p.state + ".pending", JSON.stringify(pending))
fs.writeFileSync(p.env, nextEnv)
syncBridge(p)
assert.ok(!fs.existsSync(p.state + ".pending"))
fs.writeFileSync(p.state + ".pending", JSON.stringify(pending))
fs.writeFileSync(p.config, "language='changed'\n")
assert.throws(() => syncBridge(p), /recovery paused/)
assert.equal(fs.readFileSync(p.config, "utf8"), "language='changed'\n")
})
test("symlinked target is refused", { skip: process.platform === "win32" }, t => {
const { p, select } = fixture(t)
fs.renameSync(p.config, p.config + ".real")
fs.symlinkSync(p.config + ".real", p.config)
select()
assert.throws(() => syncBridge(p), /non-regular/)
assert.equal(fs.readFileSync(p.config + ".real", "utf8"), originalConfig)
})
test("polling bridge follows selection and shuts down cleanly", async t => {
const { p, select, disconnect } = fixture(t)
let errors = 0
const stop = startBridge(p, { interval: 20, onError: () => errors++ })
t.after(stop)
select()
await new Promise(resolve => setTimeout(resolve, 80))
assert.equal(parse(fs.readFileSync(p.config, "utf8")).default_model, "magpie-agent/vendor/model-v1")
disconnect()
await new Promise(resolve => setTimeout(resolve, 80))
assert.equal(fs.readFileSync(p.config, "utf8"), originalConfig)
assert.equal(errors, 0)
})
test("normal host exit flushes a disconnect and leaves an active connection configured", t => {
const plugin = new URL("./index.mjs", import.meta.url).href
for (const disconnect of [true, false]) {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "reasonix-host-exit-"))
t.after(() => fs.rmSync(home, { recursive: true, force: true }))
const dir = path.join(home, ".reasonix")
fs.mkdirSync(dir)
const config = path.join(dir, "config.toml")
const envFile = path.join(dir, ".env")
const control = path.join(dir, "magpie-agent.json")
fs.writeFileSync(config, originalConfig)
fs.writeFileSync(envFile, originalEnv)
fs.writeFileSync(control, JSON.stringify({ model: "fixture/model", baseURL: "http://127.0.0.1:3425/v1", gatewayKey: "fixture-assigned-key" }))
const result = spawnSync(process.execPath, ["--input-type=module", "-e", `
import fs from "node:fs";
import plugin from ${JSON.stringify(plugin)};
await plugin();
${disconnect ? `fs.writeFileSync(${JSON.stringify(control)}, "{}");` : ""}
process.exit(0);
`], { env: { ...process.env, HOME: home, USERPROFILE: home }, timeout: 10000, encoding: "utf8" })
assert.equal(result.status, 0, result.stderr)
if (disconnect) {
assert.equal(fs.readFileSync(config, "utf8"), originalConfig)
assert.equal(fs.readFileSync(envFile, "utf8"), originalEnv)
} else {
assert.equal(parse(fs.readFileSync(config, "utf8")).default_model, "magpie-agent/fixture/model")
assert.equal(parseEnv(fs.readFileSync(envFile))[KEY], "fixture-assigned-key")
}
}
})
@@ -0,0 +1,67 @@
// Exercise normal plugin disable in a real resident Magpie host. No accounts,
// real agent configuration, or inference requests are used.
import assert from "node:assert/strict"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import net from "node:net"
import { spawn, execFile } from "node:child_process"
import { promisify } from "node:util"
import { fileURLToPath } from "node:url"
import { parseTOML } from "./vendor.mjs"
const exec = promisify(execFile)
const root = fs.mkdtempSync(path.join(os.tmpdir(), "reasonix-resident-"))
const repo = path.resolve(fileURLToPath(new URL(".", import.meta.url)))
const magpie = process.env.MAGPIE_BIN || "magpie"
const probe = net.createServer()
await new Promise(resolve => probe.listen(0, "127.0.0.1", resolve))
const port = probe.address().port
await new Promise(resolve => probe.close(resolve))
const addr = `127.0.0.1:${port}`
const env = { ...process.env, HOME: root, USERPROFILE: root, XDG_CONFIG_HOME: path.join(root, ".config"), XDG_CACHE_HOME: path.join(root, ".cache"), XDG_STATE_HOME: path.join(root, ".state"), REASONIX_HOME: path.join(root, ".reasonix"), REASONIX_STATE_HOME: path.join(root, ".reasonix-state"), MAGPIE_NO_ACCOUNTS: "1", MAGPIE_ADDR: addr }
const dir = env.REASONIX_HOME
const config = path.join(dir, "config.toml")
const credentials = path.join(dir, ".env")
const original = '# resident fixture\ndefault_model = "mine/model"\n'
const run = args => exec(magpie, args, { cwd: root, env, timeout: 120000, maxBuffer: 2 << 20 })
const until = async predicate => {
const deadline = Date.now() + 20000
while (Date.now() < deadline) {
if (await predicate()) return
await new Promise(resolve => setTimeout(resolve, 100))
}
throw new Error("Resident Magpie did not complete the expected state transition")
}
let child
let closed
try {
fs.mkdirSync(dir, { recursive: true })
fs.mkdirSync(path.join(env.XDG_CONFIG_HOME, "magpie"), { recursive: true })
fs.writeFileSync(config, original)
fs.writeFileSync(credentials, "OTHER_KEY=fixture-original\n")
fs.writeFileSync(path.join(env.XDG_CONFIG_HOME, "magpie/providers.json"), JSON.stringify({ providers: [{ id: "fixture", name: "Fixture", key: "fixture-only", chat: "http://127.0.0.1:9/v1", models: ["model"] }] }))
await run(["plugin", "add", repo])
await run(["reasonix-desktop", "fixture/model"])
child = spawn(magpie, ["serve"], { cwd: root, env, stdio: "ignore" })
closed = new Promise(resolve => child.once("exit", resolve))
await until(async () => {
try { return (await fetch(`http://${addr}/api/hello`, { signal: AbortSignal.timeout(500) })).ok } catch { return false }
})
await fetch(`http://${addr}/v1/models`, { signal: AbortSignal.timeout(10000) })
await until(() => parseTOML(fs.readFileSync(config, "utf8")).default_model === "magpie-agent/fixture/model")
await run(["plugin", "off", repo])
// Refreshing the catalog observes plugins.json and closes the old host.
await fetch(`http://${addr}/v1/models`, { signal: AbortSignal.timeout(10000) })
await until(() => fs.readFileSync(config, "utf8") === original)
assert.equal(fs.readFileSync(credentials, "utf8"), "OTHER_KEY=fixture-original\n")
console.log("PASS: disabling the plugin with resident Magpie restores TOML and credentials without a manual sync")
} finally {
if (child && child.exitCode === null) {
child.kill("SIGTERM")
const timer = setTimeout(() => child.kill("SIGKILL"), 3000)
await closed
clearTimeout(timer)
}
fs.rmSync(root, { recursive: true, force: true })
}
@@ -0,0 +1,3 @@
// Regenerate vendor.mjs with Bun 1.4.4; see THIRD_PARTY.md.
export { parse as parseTOML, stringify } from "smol-toml"
export { parse as parseEnv } from "dotenv"
+255
View File
@@ -0,0 +1,255 @@
import{createRequire as _e}from"node:module";var ke=Object.create;var{getPrototypeOf:De,defineProperty:pe,getOwnPropertyNames:$e}=Object;var de=Object.prototype.hasOwnProperty;function Se(e){return this[e]}var Ie,Ne,qe=(e,r,i)=>{var o=e!=null&&typeof e==="object";if(o){var l=r?Ie??=new WeakMap:Ne??=new WeakMap,n=l.get(e);if(n)return n}i=e!=null?ke(De(e)):{};let t=r||!e||!e.__esModule||!de.call(e,"default")?pe(i,"default",{value:e,enumerable:!0}):i;if(e&&typeof e==="object"||typeof e==="function"){for(let f of $e(e))if(!de.call(t,f))pe(t,f,{get:Se.bind(e,f),enumerable:!0})}if(o)l.set(e,t);return t};var Pe=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports);var P=_e(import.meta.url);var Oe=Pe(function(kr,Q){var ne=(e,r)=>()=>{try{return r||e((r={exports:{}}).exports,r),r.exports}catch(i){throw r=0,i}},ye=ne((e,r)=>{function i(l){return typeof l=="string"?!["false","0","no","off",""].includes(l.toLowerCase()):!!l}function o(l=process.env){let n={};for(let t of["ENCODING","PATH","QUIET","DEBUG","OVERRIDE","FAST"]){let f=l[`DOTENV_${t}`]!=null?l[`DOTENV_${t}`]:l[`DOTENV_CONFIG_${t}`];f!=null&&(n[t.toLowerCase()]=t==="ENCODING"||t==="PATH"?f:i(f))}return n}r.exports={parseBoolean:i,optionsFromEnv:o}}),Ee=ne((e,r)=>{var i=P("fs"),o=P("path"),l=P("os"),{URL:n,fileURLToPath:t}=P("url"),{parseBoolean:f,optionsFromEnv:v}=ye(),h=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg,p=new Uint8Array(256);for(let s=48;s<=57;s++)p[s]=1;for(let s=65;s<=90;s++)p[s]=1;for(let s=97;s<=122;s++)p[s]=1;p[45]=1,p[46]=1,p[95]=1;function c(s){let g={},a=s.toString();a=a.replace(/\r\n?/mg,`
`);let C;for(;(C=h.exec(a))!=null;){let u=C[1],y=C[2]||"";y=y.trim();let E=y[0];y=y.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),E==='"'&&(y=y.replace(/\\n/g,`
`),y=y.replace(/\\r/g,"\r")),g[u]=y}return g}function m(s){return s<=32?s===32||s>=9&&s<=13:s>=160&&(s===160||s===5760||s>=8192&&s<=8202||s===8232||s===8233||s===8239||s===8287||s===12288||s===65279)}function b(s){return s===10||s===8232||s===8233}function k(s){let g={},a=typeof s=="string"?s:s.toString();a.indexOf("\r")!==-1&&(a=a.replace(/\r\n?/g,`
`));let C=a.length,u=0;for(;u<C;){let y=a.charCodeAt(u);for(;u<C&&m(y);)u++,y=a.charCodeAt(u);if(u>=C)break;if(y===35){for(;u<C&&!b(a.charCodeAt(u));)u++;continue}let E=-1;if(y===101&&u+6<C&&a.charCodeAt(u+1)===120&&a.charCodeAt(u+2)===112&&a.charCodeAt(u+3)===111&&a.charCodeAt(u+4)===114&&a.charCodeAt(u+5)===116){let U=a.charCodeAt(u+6);if(m(U)){let O=u+7;for(;O<C&&m(a.charCodeAt(O));)O++;p[a.charCodeAt(O)]&&(E=u+6,u=O)}else y=a.charCodeAt(u)}let H=u,G=0;for(;u<C&&(G=a.charCodeAt(u),p[G]);)u++;if(u===H){for(;u<C&&!b(a.charCodeAt(u));)u++;continue}let oe=a.slice(H,u),ee=u;if(u>=C&&(G=0),m(G))do u++,G=u<C?a.charCodeAt(u):0;while(m(G));if(G===61)u++;else if(G===58&&u===ee&&u+1<C&&m(a.charCodeAt(u+1)))u+=2;else{for(u=E===-1?ee:E;u<C&&!b(a.charCodeAt(u));)u++;continue}let L=u,N=u;for(;N<C&&m(a.charCodeAt(N));)N++;let z=a.charCodeAt(N),q,le=!1;if(z===39||z===34||z===96){let U=a[N],O=a.indexOf(U,N+1),j=-1,B=-1;for(;O!==-1;){let K=a.charCodeAt(O-1)===92,Z=O+1;for(;Z<C&&!b(a.charCodeAt(Z))&&m(a.charCodeAt(Z));)Z++;if((Z===C||b(a.charCodeAt(Z))||a.charCodeAt(Z)===35)&&(j=O,B=Z),!K)break;O=a.indexOf(U,O+1)}if(j!==-1){if(q=a.slice(N+1,j),u=B,a.charCodeAt(u)===35)for(;u<C&&!b(a.charCodeAt(u));)u++;le=!0}}if(!le){let U=a.indexOf(`
`,L);U===-1&&(U=C);let O;if(C<4096)O=a.indexOf("#",L),(O===-1||O>U)&&(O=U);else for(O=L;O<U&&a.charCodeAt(O)!==35;)O++;let j=L,B=O;for(;j<B&&m(a.charCodeAt(j));)j++;for(;B>j&&m(a.charCodeAt(B-1));)B--;let K=a.charCodeAt(j);if(q=a.slice(j,B),q.includes("\u2028")||q.includes("\u2029")?q=q.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"):B-j>=2&&(K===39||K===34||K===96)&&a.charCodeAt(B-1)===K&&(q=a.slice(j+1,B-1)),u=O,O<U)for(;u<C&&!b(a.charCodeAt(u));)u++}z===34&&(le||N<u)&&q.indexOf("\\")!==-1&&(q=q.replace(/\\n/g,`
`).replace(/\\r/g,"\r")),g[oe]=q}return g}function A(s,g){return g&&f(g.fast)?k(s):c(s)}function T(s){console.log(`┆ ${s}`)}function w(s){console.error(`◇ ${s}`)}function S(s){return s[0]==="~"?o.join(l.homedir(),s.slice(1)):s}function V(s={}){let g={...s};for(let a of Object.keys(g))g[a]===void 0&&delete g[a];return{...v(),...g}}function M(s){s=V(s);let g=o.resolve(process.cwd(),".env"),a="utf8",C=process.env;s&&s.processEnv!=null&&(C=s.processEnv);let u=f(s&&s.debug);s&&s.encoding?a=s.encoding:u&&T("no encoding is specified (UTF-8 is used by default)");let y=[g];if(s&&s.path)if(!Array.isArray(s.path))y=[S(s.path)];else{y=[];for(let L of s.path)y.push(S(L))}let E,H={},G={fast:s.fast};for(let L of y)try{let N=I.parse(i.readFileSync(L,{encoding:a}),G);I.populate(H,N,s)}catch(N){u&&T(`failed to load ${L} ${N.message}`),E=N}let oe=I.populate(C,H,s),ee=f(Object.prototype.hasOwnProperty.call(s,"quiet")?s.quiet:v(C).quiet);if(u||!ee){let L=Object.keys(oe).length,N=[];for(let z of y)try{let q=o.relative(process.cwd(),z instanceof n?t(z):z);N.push(q)}catch(q){u&&T(`failed to load ${z} ${q.message}`),E=q}w(`injected env (${L}) from ${N.join(",")}`)}return E?{parsed:H,error:E}:{parsed:H}}function D(s){return I.configDotenv(s)}function F(s,g,a={}){let C=f(a&&a.debug),u=f(a&&a.override),y={};if(s===null||typeof s!="object"||g===null||typeof g!="object"){let E=Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw E.code="OBJECT_REQUIRED",E}for(let E of Object.keys(g))Object.prototype.hasOwnProperty.call(s,E)?(u===!0&&(s[E]=g[E],y[E]=g[E]),C&&T(u===!0?`"${E}" is already defined and WAS overwritten`:`"${E}" is already defined and was NOT overwritten`)):(s[E]=g[E],y[E]=g[E]);return y}var I={configDotenv:M,config:D,parse:A,populate:F};r.exports.configDotenv=I.configDotenv,r.exports.config=I.config,r.exports.parse=I.parse,r.exports.populate=I.populate,r.exports=I}),He=ne((e,r)=>{var i=P("child_process"),o=P("fs"),l=P("path");function n(p){let c=['"'],m=0;for(let b of p){if(b==="\\"){m++;continue}b==='"'?c.push("\\".repeat(m*2+1),'"'):c.push("\\".repeat(m),b),m=0}return c.push("\\".repeat(m*2),'"'),c.join("")}function t(p,c=1){for(let m=0;m<c;m++){let b=[];for(let k of p){let A=k.charCodeAt(0),T=A>=48&&A<=57||A>=65&&A<=90||A>=97&&A<=122,w="\\/:._-".includes(k);!T&&!w&&A<128&&b.push("^"),b.push(k)}p=b.join("")}return p}function f(p,c){let m=Object.keys(p).reverse().find((b)=>b.toUpperCase()===c);return m===void 0?void 0:p[m]}function v(p,c,m){let b=(f(c,"PATHEXT")||".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean),k=b.some((T)=>p.toLowerCase().endsWith(T.toLowerCase()))?["",...b]:[...b,""],A=/[\\/]/.test(p)?[m]:[m,...(f(c,"PATH")||"").split(";")];for(let T of A)for(let w of k){let S=l.resolve(m,T.replace(/^"|"$/g,""),p+w);try{if(o.statSync(S).isFile())return S}catch{}}}function h(p,c,m){if(process.platform!=="win32")return i.spawn(p,c,m);let b=m.env||process.env,k=v(p,b,m.cwd||process.cwd());if(k&&/\.(?:exe|com)$/i.test(k))return i.spawn(k,c,m);let A=/\.(?:bat|cmd)$/i.test(k||p),T=[t(l.normalize(k||p))];for(let S of c)T.push(t(n(S),A?2:1));let w=T.join(" ");return i.spawn(f(b,"COMSPEC")||"cmd.exe",["/d","/v:off","/s","/c",`"${w}"`],{...m,windowsVerbatimArguments:!0})}r.exports=h}),Ke=ne((e,r)=>{var i=P("fs"),o=P("os"),l=P("path"),n=P("child_process"),t=He(),f=Ee(),{optionsFromEnv:v}=ye();function h(){console.log(["Usage: dotenv run [--help] [-q|--quiet] [--debug] [--override] [--fast] [-f|--file <paths>] [--] <command> [args...]","","Run a command with environment variables from a .env file.","Place dotenv options before the command; all following arguments go to the command.","","Options:"," -f, --file <paths> .env paths, comma-separated or repeated (default: .env)"," -q, --quiet suppress the injected env message"," --debug enable debug logging"," --override override existing environment variables"," --fast use the faster character-scanner parser","","Environment variables (DOTENV_CONFIG_* names remain as fallbacks):"," DOTENV_PATH, DOTENV_ENCODING, DOTENV_QUIET,"," DOTENV_DEBUG, DOTENV_OVERRIDE,"," DOTENV_FAST"].join(`
`))}function p(A){let T=[],w=!1,S,V,M,D,F=-1;for(let s=0;s<A.length;s++){let g=A[s];if(g==="--"){F=s+1;break}if(g==="--help"||g==="-h")return{help:!0};if(g==="--quiet"||g==="-q"){S=!0;continue}if(g==="--debug"){V=!0;continue}if(g==="--override"){M=!0;continue}if(g==="--fast"){D=!0;continue}if(g==="-f"||g==="--file"||g.startsWith("-f=")||g.startsWith("--file=")){let a=g.indexOf("="),C=a===-1?g:g.slice(0,a),u=a===-1?A[++s]:g.slice(a+1);if(!u||u==="--")return{error:`${C} requires a path`};let y=u.split(",").map((E)=>E.trim()).filter(Boolean);if(y.length===0)return{error:`${C} requires a path`};T.push(...y),w=!0;continue}if(g.startsWith("-"))return{error:`unknown option: ${g}`};F=s;break}let I=F===-1?[]:A.slice(F);return{paths:T,pathSet:w,quiet:S,debug:V,override:M,fast:D,command:I}}function c(A){return A[0]==="~"?l.join(o.homedir(),A.slice(1)):A}function m(A){let T=v(),w={encoding:T.encoding||"utf8",quiet:T.quiet,debug:T.debug===!0,override:T.override===!0,fast:T.fast===!0,paths:[".env"],defaultPath:!0};return T.path&&(w.paths=[T.path],w.defaultPath=!1),A.pathSet&&(w.paths=A.paths,w.defaultPath=!1),A.quiet!=null&&(w.quiet=A.quiet),A.debug!=null&&(w.debug=A.debug),A.override!=null&&(w.override=A.override),A.fast!=null&&(w.fast=A.fast),w}function b(A){let T={},w=[],S={override:A.override,debug:A.debug};for(let V of A.paths){let M=l.resolve(process.cwd(),c(V));try{let D=f.parse(i.readFileSync(M,{encoding:A.encoding}),{fast:A.fast});f.populate(T,D,S),w.push(V)}catch(D){if(A.debug&&console.log(`┆ failed to load ${V} ${D.message}`),!(A.defaultPath&&D.code==="ENOENT"))throw D}}return{injected:f.populate(process.env,T,S),loadedPaths:w}}function k(A){let T=A[0];if(T==="--help"||T==="-h"){h();return}if(T!=="run"){h(),process.exitCode=1;return}let w=p(A.slice(1));if(w.help){h();return}if(w.error){console.error(`dotenv: ${w.error}`),h(),process.exitCode=1;return}if(w.command.length===0){h(),process.exitCode=1;return}let S=m(w);try{let a=b(S);if(!(S.quiet==null?v().quiet:S.quiet)){let C=`◇ injected env (${Object.keys(a.injected).length})`;a.loadedPaths.length>0&&(C+=` from ${a.loadedPaths.join(", ")}`),console.error(C)}}catch(a){console.error(`dotenv: ${a.message}`),process.exitCode=1;return}let V=!!process.stdin.isTTY,M=process.platform!=="win32"&&!V,D=t(w.command[0],w.command.slice(1),{stdio:"inherit",detached:M}),F=new Map,I=0;function s(a){if(!(!D.pid||D.exitCode!==null||D.signalCode!==null)){if(process.platform==="win32"){n.spawnSync("taskkill",["/pid",String(D.pid),"/T","/F"],{stdio:"ignore"});return}try{process.kill(M?-D.pid:D.pid,a)}catch(C){if(C.code!=="ESRCH")throw C}}}function g(){for(let[a,C]of F)process.removeListener(a,C)}for(let a of["SIGINT","SIGTERM","SIGHUP","SIGQUIT"]){let C=()=>{if(a==="SIGINT"){if(I++,V&&process.platform!=="win32"&&I===1)return;if(I>1){s(I===2?"SIGTERM":"SIGKILL");return}}s(a)};F.set(a,C),process.on(a,C)}D.on("error",function(a){g(),console.error(`dotenv: ${a.message}`),process.exitCode=1}),D.on("exit",function(a,C){g(),typeof a=="number"?process.exit(a):(setInterval(()=>{},1000),process.kill(process.pid,C))})}r.exports=k,r===P.main&&k(process.argv.slice(2))}),X=Ee(),Or=Ke();Q.exports=X;Q.exports.config=X.config;Q.exports.configDotenv=X.configDotenv;Q.exports.parse=X.parse;Q.exports.populate=X.populate});/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/function je(e,r){let i=e.slice(0,r).split(/\r?\n/);return[i.length,i.pop().length+1]}function Ve(e,r,i){let o=e.split(/\r?\n/),l="",n=(Math.log10(r+1)|0)+1;for(let t=r-1;t<=r+1;t++){let f=o[t-1];if(!f)continue;if(l+=t.toString().padEnd(n," "),l+=": ",l+=f,l+=`
`,t===r)l+=" ".repeat(n+i+2),l+=`^
`}return l}class d extends Error{line;column;codeblock;constructor(e,r){let[i,o]=je(r.toml,r.ptr),l=Ve(r.toml,i,o);super(`Invalid TOML document: ${e}
${l}`,r);this.line=i,this.column=o,this.codeblock=l}static x(e,r,i){throw new d(e,{toml:r.s,ptr:i??r.p})}}/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/function re(e){let r=e.p,i=e.s.charCodeAt(e.p++),o=i,l=i===39,n=i===e.s.charCodeAt(e.p)&&i===e.s.charCodeAt(e.p+1);if(n){if((i=e.s.charCodeAt(e.p+=2))===10)e.p++;else if(i===13&&e.s.charCodeAt(e.p+1)===10)e.p+=2}let t="",f=e.p,v=0;for(;e.p<e.s.length;e.p++)if(i=e.s.charCodeAt(e.p),n&&(i===10||i===13&&e.s.charCodeAt(e.p+1)===10))v=v&&3;else if(i<32&&i!==9||i===127)d.x("control characters are not allowed in strings",e);else if((!v||v===3)&&i===o&&(!n||e.s.charCodeAt(e.p+1)===o&&e.s.charCodeAt(e.p+2)===o)){if(n){if(e.s.charCodeAt(e.p+3)===o)e.p++;if(e.s.charCodeAt(e.p+3)===o)e.p++}if(!v){let h=e.s.slice(f,e.p);t=t?t+h:h}return e.p+=n?3:1,t}else if(!v){if(!l&&i===92)t+=e.s.slice(f,f=e.p),v=1}else if(v===1)if(i===120||i===117||i===85){let h=e.p++-1,p=0,c=i===120?2:i===117?4:8;for(let m=0;m<c;m++,e.p++){let b=e.s.charCodeAt(e.p),k=b>=48&&b<=57?b-48:b>=65&&b<=70?b-65+10:b>=97&&b<=102?b-97+10:-1;if(k<0)d.x("invalid non-hex character in unicode escape",e);p=p<<4|k}if(p<0||p>1114111||p>=55296&&p<=57343)d.x("invalid unicode escape",e,h);t+=String.fromCodePoint(p),f=e.p--,v=0}else if(n&&(i===32||i===9))v=2;else{if(i===98)t+="\b";else if(i===116)t+="\t";else if(i===110)t+=`
`;else if(i===102)t+="\f";else if(i===114)t+="\r";else if(i===101)t+="\x1B";else if(i===34)t+='"';else if(i===92)t+="\\";else d.x("unrecognised escape sequence",e);f=e.p+1,v=0}else if(i!==32&&i!==9){if(v===2)d.x("invalid escape: only line-ending whitespace may be escaped",e,f);v=!l&&i===92?1:0,f=e.p}d.x("unfinished string",e,r)}/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/var Le=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;class W extends Date{#r=!1;#t=!1;#e=null;constructor(e,r,i){let o=!0,l=!0,n="Z",t;if(typeof e==="string")if(r)e:{if(r<3){if(+e.slice(11,13)>23){e="";break e}if(r===2)n=null,e+="Z";else if((t=e.charCodeAt(e.length-1))!==90&&t!==122)n=e.slice(e.length-6);if(i)e=e.slice(0,10)+"T"+e.slice(11)}else if(r===4)e=+e.slice(0,2)>23?"":`0000-01-01T${e}Z`;o=r!==4,l=r!==3}else{let f=e.match(Le);if(f){if(!f[1])o=!1,e=`0000-01-01T${e}`;if(l=!!f[2],l&&e[10]===" "&&(e=e.replace(" ","T")),f[2]&&+f[2]>23)e="";else if(n=f[3]||null,!n&&l)e+="Z"}else e=""}super(e);if(!isNaN(this.getTime()))this.#r=o,this.#t=l,this.#e=n}isDateTime(){return this.#r&&this.#t}isLocal(){return!this.#r||!this.#t||!this.#e}isDate(){return this.#r&&!this.#t}isTime(){return this.#t&&!this.#r}isValid(){return this.#r||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z"||this.#e==="z")return e;let r=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return r=this.#e[0]==="-"?r:-r,new Date(this.getTime()-r*60000).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,r="Z"){let i=new W(e);return i.#e=r,i}static wrapAsLocalDateTime(e){let r=new W(e);return r.#e=null,r}static wrapAsLocalDate(e){let r=new W(e);return r.#t=!1,r.#e=null,r}static wrapAsLocalTime(e){let r=new W(e);return r.#r=!1,r.#e=null,r}}/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/function _(e,r=10){return r===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+r}function ae(e,r){return e===32||e===9||e===10||e===13||r&&(e===r||e===44)||e===35}function Y(e,r){let i=e.p,o=e.s.charCodeAt(e.p);if(o===91||o===123){e.d--||d.x("document contains excessively nested structures. aborting.",e);let l=o===91?me(e):ce(e);return e.d++,l}if(o===34||o===39)return re(e);if(o===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)d.x("invalid value",e,i);return e.p++,!0}if(o===102){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)d.x("invalid value",e,i);return e.p++,!1}if(o===43||o===45)return te(e,e.p,e.s.charCodeAt(++e.p),44-o,r);if(e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45)return Ue(e,o,r);if(e.s.charCodeAt(e.p+2)===58)return Be(e,o,r);return te(e,e.p,o,0,r)}function te(e,r,i,o,l){let n=i,t=0,f=!1;if(n===105){if(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)d.x("invalid value",e,r);return e.p++,(o||1)/0}if(n===110){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)d.x("invalid value",e,r);return e.p++,NaN}if(n===48){if(++e.p>=e.s.length||ae(n=e.s.charCodeAt(e.p),l))return e.bi===!0?0n:0;if(!o){if(n===120)return se(e,r,16,l);else if(n===98)return se(e,r,2,l);else if(n===111)return se(e,r,8,l)}if(n===46)t=2;else if(n===101||n===69)t=4;else d.x("illegal leading zero",e,r)}else if(!_(n))d.x("invalid value",e,r);while(++e.p<e.s.length&&(n=e.s.charCodeAt(e.p),!ae(n,l))){if(!t)t=1;if(n===95){if(!(t&1))d.x("illegal underscore",e);t+=11,f=!0}else if(t===1&&n===46)t=2;else if((t===1||t===3)&&(n===101||n===69))t=4;else if(t===4&&(n===43||n===45))t=6;else if(!_(n))d.x("illegal character in numeric literal",e);else if(t>9)t-=11;else if(!(t&1))t++}if(!t){let h=(i-48)*(o||1);return e.bi===!0?BigInt(h):h}if(!(t&1))d.x("unfinished numeric value",e,r);let v=e.s.slice(r,e.p);if(f)v=v.replaceAll("_","");return t>1?parseFloat(v):he(e,v,10,r)}function se(e,r,i,o){let l,n=1;while(++e.p<e.s.length&&(l=e.s.charCodeAt(e.p),!ae(l,o)))if(l===95){if(n&1)d.x("illegal underscore",e);n=3}else if(!_(l,i))d.x("illegal character in numeric literal",e);else if(n&1)n--;if(n&1)d.x("unfinished numeric value",e);let t=e.s.slice(r+2,e.p);if(n)t=t.replaceAll("_","");return he(e,t,i,r)}function he(e,r,i,o){if(e.bi!==!0)e:{let l=parseInt(r,i);if(!Number.isSafeInteger(l)){if(e.bi)break e;d.x("integer value cannot be represented losslessly",e,o)}return l}return i===10?BigInt(r):BigInt((i===2?"0b":i===8?"0o":"0x")+r)}function Ue(e,r,i){let o=e.p++,l;if(!_(r)||!_(e.s.charCodeAt(e.p++))||!_(e.s.charCodeAt(e.p++))||!_(e.s.charCodeAt(e.p++)))return te(e,e.p=o,r,0,i);if(e.p+=5,!_(e.s.charCodeAt(e.p++)))d.x("invalid date-time: date part is malformed",e,o);if(e.p>=e.s.length||((r=e.s.charCodeAt(e.p))!==32||(l=!0,!_(e.s.charCodeAt(e.p+1))))&&r!==84&&r!==116){let t=e.s.slice(o,e.p);return J(e,t,3,!1,o)}if(e.s.charCodeAt(e.p+=3)!==58)d.x("invalid date-time: time part is malformed",e,o);if(e.s.charCodeAt(e.p+=3)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(_(e.s.charCodeAt(++e.p)));if(r=e.s.charCodeAt(e.p)){if(r===90||r===122){let t=e.s.slice(o,++e.p);return J(e,t,1,l,o,"[+00:00]")}if(r===43||r===45){let t=e.s.slice(o,e.p+=6);return J(e,t,1,l,o,!e.ld&&"["+e.s.slice(e.p-6,e.p)+"]")}}let n=e.s.slice(o,e.p);return J(e,n,2,l,o)}function Be(e,r,i){let o=e.p;if(!_(r)||!_(e.s.charCodeAt(++e.p)))return te(e,--e.p,r,0,i);if(e.s.charCodeAt(e.p+=4)===58)e.p+=3;if(e.s.charCodeAt(e.p)===46)while(_(e.s.charCodeAt(++e.p)));let l=e.s.slice(o,e.p);return J(e,l,4,!1,o)}function J(e,r,i,o,l,n){if(e.ld){let t=new W(r,i,o);if(!t.isValid())d.x("invalid date",e,l);return t}try{if(n)r+=n;switch(i){case 1:return Temporal.ZonedDateTime.from(r);case 2:return Temporal.PlainDateTime.from(r);case 3:return Temporal.PlainDate.from(r);case 4:return Temporal.PlainTime.from(r)}}catch(t){d.x(t instanceof Error?t.message:""+t,e,l)}}/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/function Re(e){for(;e.p<e.s.length;e.p++){let r=e.s.charCodeAt(e.p);if(r===10)break;if(r===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(r<32&&r!==9||r===127)d.x("control characters are not allowed in comments",e)}}function R(e,r,i){let o;while(e.p<e.s.length){while(e.p<e.s.length&&((o=e.s.charCodeAt(e.p))===32||o===9||!r&&(o===10||o===13&&e.s.charCodeAt(e.p+1)===10)))e.p++;if(i||o!==35)break;Re(e)}}/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/function ie(e,r=61){let i,o=0,l=[],n,t=e.s.charCodeAt(i=e.p);do if(t===r){if(!o)d.x("unexpected end of key",e);if(o===1)l.push(e.s.slice(n,e.p));return e.p++,l}else if(t===46){if(!o)d.x("illegal empty bare key",e);if(o===1)l.push(e.s.slice(n,e.p));o=0}else if(!o&&(t===34||t===39)){if(t===e.s.charCodeAt(e.p+1)&&t===e.s.charCodeAt(e.p+2))d.x("illegal quoted key: multiline strings are not allowed",e);l.push(re(e)),o=2,e.p--}else if(t===32||t===9){if(o===1)l.push(e.s.slice(n,e.p)),o=2}else if(o===2||t<48&&t!==45||t>57&&t<65||t>90&&t<97&&t!==95||t>122)d.x("illegal character in key",e);else if(!o)o=1,n=e.p;while(t=e.s.charCodeAt(++e.p));d.x("incomplete key-value: cannot find end of key",e,i)}function ce(e){let r=e.p++,i=Object.create(null),o=new Set,l;while(e.p<e.s.length){if(R(e),(l=e.s.charCodeAt(e.p))===125)return e.p++,i;let n,t=i,f=!1,v=e.p,h=ie(e);for(let c=0;c<h.length;c++){if(c)t=f?t[n]:t[n]=Object.create(null);if(n=h[c],(f=Object.hasOwn(t,n))&&(typeof t[n]!=="object"||o.has(t[n])))d.x("trying to redefine an already defined value",e,v);let m=n==="__proto__";if(e.uk&&(m||n==="constructor")){t=e.uk!==1&&d.x("document contains an unsafe property",e,v);break}if(!f&&m)Object.defineProperty(t,n,{enumerable:!0,configurable:!0,writable:!0})}if(f)d.x("trying to redefine an already defined value",e,v);R(e,!0,!0);let p=Y(e,125);if(t&&typeof(t[n]=p)==="object")o.add(p);if(R(e),(l=e.s.charCodeAt(e.p++))===125)return i;if(l!==44)d.x("expected comma or end of structure",e,e.p-1)}d.x("unfinished table",e,r)}function me(e){let r=e.p++,i=[],o;while(e.p<e.s.length){if(R(e),(o=e.s.charCodeAt(e.p))===93)return e.p++,i;if(i.push(Y(e,93)),R(e),(o=e.s.charCodeAt(e.p++))===93)return i;if(o!==44)d.x("expected comma or end of structure",e,e.p-1)}d.x("unfinished array",e,r)}/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/function ge(e,r,i,o,l){let n=i,t=o,f,v=!1,h;for(let p=0;p<r.length;p++){if(p){if(n=v?n[f]:n[f]=Object.create(null),t=(h=t[f]).c,l===0&&(h.t===1||h.t===2))return null;if(h.t===2){let c=n.length-1;n=n[c],t=t[c].c}}if(f=r[p],(v=Object.hasOwn(n,f))&&t[f]?.t===0&&t[f]?.d)return null;if(!v){let c=f==="__proto__";if(e.uk&&(c||f==="constructor"))return!1;if(c)Object.defineProperty(n,f,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(t,f,{enumerable:!0,configurable:!0,writable:!0});t[f]={t:p<r.length-1&&l===2?3:l,d:!1,i:0,c:Object.create(null)}}}if(h=t[f],h.t!==l&&!(l===1&&h.t===3))return null;if(l===2){if(!h.d)h.d=!0,n[f]=[];n[f].push(n=Object.create(null)),h.c[h.i++]=h={t:1,d:!1,i:0,c:Object.create(null)}}if(h.d)return null;if(h.d=!0,l===1)n=v?n[f]:n[f]=Object.create(null);else if(l===0&&v)return null;return[f,n,h.c]}function Ce(e,r,i){if(r===null||e.uk===2)d.x(r===null?"trying to redefine an already defined table or value":"document contains an unsafe property",e,i)}function Ae(e,r={}){let i={s:e,p:0,d:r.maxDepth??1000,bi:r.integersAsBigInt??!1,ld:r.useLegacyDate??!0,uk:r.unsafeKeyBehaviour==="throw"?2:r.unsafeKeyBehaviour==="drop"?1:0},o=Object.create(null),l=Object.create(null),n,t=!1,f=o,v=l;if(e.charCodeAt(0)===65279)i.p++;R(i);while(i.p<e.length){if(e.charCodeAt(i.p)===91){let h=e.charCodeAt(++i.p)===91;n=i.p+=+h,t=!1;let p=ie(i,93);if(h){if(e.charCodeAt(i.p)!==93)d.x("expected end of table array declaration",i);i.p++}let c=ge(i,p,o,l,h?2:1);if(!c)Ce(i,c,n),t=!0;else v=c[2],f=c[1]}else{n=i.p;let h=ie(i),p=ge(i,h,f,v,0);if(!p&&!t)Ce(i,p,n);R(i,!0,!0);let c=Y(i,void 0);if(p&&!t)p[1][p[0]]=c}if(R(i,!0),i.p<e.length&&(n=e.charCodeAt(i.p))!==10&&(n!==13||e.charCodeAt(i.p+1)!==10))d.x("each key-value declaration must be followed by an end-of-line",i);R(i)}return o}/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/var Ge=/^[a-z0-9-_]+$/i,ve=!!"".isWellFormed;function x(e){let r=typeof e;if(r==="object"){if(Array.isArray(e))return"array";if(typeof e.getUTCDate==="function"&&e instanceof Date)return"date";if(globalThis.Temporal){if(e.until){if(e instanceof Temporal.ZonedDateTime)return"temporal/tz+uc";if(e instanceof Temporal.PlainDateTime||e instanceof Temporal.PlainDate)return"temporal/uc";if(e instanceof Temporal.PlainTime||e instanceof Temporal.Instant)return"temporal";if(e instanceof Temporal.PlainYearMonth)return"temporal/x"}else if(e.toPlainDate&&e instanceof Temporal.PlainMonthDay||e.negated&&e instanceof Temporal.Duration)return"temporal/x"}}return r}function Me(e){for(let r=0;r<e.length;r++)if(x(e[r])!=="object")return!1;return e.length!=0}function be(e){return JSON.stringify(e).replaceAll("","\\u007f")}function Fe(e){return be(ve?e.toWellFormed():e)}function Te(e){if(Ge.test(e))return e;if(ve&&!e.isWellFormed())throw RangeError("key contains illegal lone surrogates");return be(e)}function fe(e,r,i,o,l){if(i===0)throw Error("Could not stringify the object: maximum object depth exceeded");switch(r){case"number":if(isNaN(e))return"nan";if(e===1/0)return"inf";if(e===-1/0)return"-inf";if(Number.isInteger(e)&&(o||!Number.isSafeInteger(e)))return e.toFixed(1);case"bigint":case"boolean":case"temporal":return e.toString();case"string":return Fe(e);case"date":if(isNaN(e.getTime()))throw TypeError("cannot serialize invalid date");return e.toISOString();case"object":return ze(e,i,o,l);case"array":return Ze(e,i,o,l);case"temporal/tz+uc":if(l){let n=e.timeZoneId,t=n.charCodeAt(0);if(t!==43&&t!==45&&(t!==85&&t!==71&&t!==90&&t!==69||n!=="UTC"&&n!=="UCT"&&n!=="Universal"&&n!=="Zulu"&&!n.startsWith("GMT")&&n!=="Greenwich"&&!n.startsWith("Etc/")))throw TypeError("Temporal objects with an IANA timezone are not allowed in Temporal strict mode")}case"temporal/uc":if(l&&e.calendarId!=="iso8601")throw TypeError("Temporal objects with a non-default calendar are not allowed in Temporal strict mode");return e.toString({calendarName:"never",timeZoneName:"never"});case"temporal/x":throw TypeError("Unsupported "+e[Symbol.toStringTag])}}function ze(e,r,i,o){let l=Object.keys(e);if(l.length===0)return"{}";let n="{ ";for(let t=0;t<l.length;t++){let f=l[t];if(t)n+=", ";n+=Te(f)+" = "+fe(e[f],x(e[f]),r-1,i,o)}return n+" }"}function Ze(e,r,i,o){if(e.length===0)return"[]";let l="[ ";for(let n=0;n<e.length;n++){if(n)l+=", ";if(e[n]===null||e[n]===void 0)throw TypeError("arrays cannot contain null or undefined values");l+=fe(e[n],x(e[n]),r-1,i,o)}return l+" ]"}function We(e,r,i,o,l){if(i===0)throw Error("Could not stringify the object: maximum object depth exceeded");let n="";for(let t=0;t<e.length;t++)n+=`${n&&`
`}[[${r}]]
`,n+=ue(0,e[t],r,i,o,l);return n}function ue(e,r,i,o,l,n){if(o===0)throw Error("Could not stringify the object: maximum object depth exceeded");let t="",f="",v=Object.keys(r);for(let h=0;h<v.length;h++){let p=v[h];if(r[p]!==null&&r[p]!==void 0){let c=x(r[p]);if(c==="symbol"||c==="function")throw TypeError(`cannot serialize values of type '${c}'`);let m=Te(p);if(c==="array"&&Me(r[p]))f+=(f&&`
`)+We(r[p],i?`${i}.${m}`:m,o-1,l,n);else if(c==="object"){let b=i?`${i}.${m}`:m;f+=(f&&`
`)+ue(b,r[p],b,o-1,l,n)}else t+=m,t+=" = ",t+=fe(r[p],c,o,l,n),t+=`
`}}if(e&&(t||!f))t=t?`[${e}]
${t}`:`[${e}]`;return t&&f?`${t}
${f}`:t||f}function we(e,{maxDepth:r=1000,numbersAsFloat:i=!1,strictTemporal:o=!1}={}){if(x(e)!=="object")throw TypeError("stringify can only be called with an object");let l=ue(0,e,"",r,i,o);if(l[l.length-1]!==`
`)return l+`
`;return l}/*!
* Copyright (c) Squirrel Chat et al., All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/var Qe=qe(Oe(),1);var Ir=Qe.parse;export{Ir as parseEnv,Ae as parseTOML,we as stringify};
+2
View File
@@ -91,6 +91,8 @@
"summary": { "en": "Send a request's history smaller: fold a run of blank lines, drop a system prompt written twice and a message repeated right after itself, and cut a past tool result longer than maxToolLength at a word boundary. The turn being sent now is left whole.", "zh": "把请求的历史发得更小:折叠连续空行、去掉逐字重复的 system 提示与紧挨着重复的消息、把历史中超过 maxToolLength 的工具结果在词边界处截断;正在发送的这一轮原样不动。" } }, "summary": { "en": "Send a request's history smaller: fold a run of blank lines, drop a system prompt written twice and a message repeated right after itself, and cut a past tool result longer than maxToolLength at a word boundary. The turn being sent now is left whole.", "zh": "把请求的历史发得更小:折叠连续空行、去掉逐字重复的 system 提示与紧挨着重复的消息、把历史中超过 maxToolLength 的工具结果在词边界处截断;正在发送的这一轮原样不动。" } },
{ "package": "@magpie-community/agent-aider", "name": "Aider", "kind": "agent", "community": true, { "package": "@magpie-community/agent-aider", "name": "Aider", "kind": "agent", "community": true,
"summary": { "en": "Aider (aider.chat) on magpie's Agents page: pick one of magpie's models for it, and switch it off to put its config back.", "zh": "把 Aider(aider.chat)加到 magpie 的 Agent 页:给它选 magpie 的模型,关掉即恢复它原来的配置。" } }, "summary": { "en": "Aider (aider.chat) on magpie's Agents page: pick one of magpie's models for it, and switch it off to put its config back.", "zh": "把 Aider(aider.chat)加到 magpie 的 Agent 页:给它选 magpie 的模型,关掉即恢复它原来的配置。" } },
{ "package": "@magpie-community/agent-reasonix-desktop", "name": "Reasonix 1.x", "kind": "agent", "community": true, "icon": "reasonix-color",
"summary": { "en": "Reasonix 1.x Desktop and CLI on Magpie's models, preserving existing providers. Restart Reasonix after choosing a model; disconnect before uninstalling. Separate from the built-in Reasonix Studio 2.x adapter.", "zh": "为 Reasonix 1.x 桌面版和 CLI 选择 Magpie 模型,保留原有供应商;选模型后重启 Reasonix,卸载前先断开。与内置的 Reasonix Studio 2.x 适配器分开。" } },
{ "package": "@magpie-community/agent-pig", "name": "PiG", "kind": "agent", "community": true, { "package": "@magpie-community/agent-pig", "name": "PiG", "kind": "agent", "community": true,
"summary": { "en": "PiG (Pi in Go): add Magpie's endpoint and model catalog, choose models in PiG, and keep startup settings unchanged.", "zh": "为 PiG(Pi in Go)注入 Magpie 端点与模型列表,在 PiG 内选择模型,保持启动设置不变。" } }, "summary": { "en": "PiG (Pi in Go): add Magpie's endpoint and model catalog, choose models in PiG, and keep startup settings unchanged.", "zh": "为 PiG(Pi in Go)注入 Magpie 端点与模型列表,在 PiG 内选择模型,保持启动设置不变。" } },
{ "package": "@magpie-community/agent-bub", "name": "Bub", "kind": "agent", "community": true, { "package": "@magpie-community/agent-bub", "name": "Bub", "kind": "agent", "community": true,