diff --git a/README.md b/README.md index c3549dc..0ecf581 100644 --- a/README.md +++ b/README.md @@ -266,6 +266,7 @@ it off puts the config back. | Package | Agent | |---|---| | [aider](packages/aider) | [Aider](https://aider.chat): `~/.aider.conf.yml`, through litellm's `openai/` prefix | +| [nanobot](packages/nanobot) | [nanobot](https://github.com/HKUDS/nanobot): Magpie's model becomes nanobot's default preset, and Library gives it MCP servers and default-workspace skills; restart nanobot after MCP changes | | [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) | | [kilo](packages/kilo) | [Kilo Code](https://kilo.ai): `~/.config/kilo/kilo.jsonc`, through an OpenAI-compatible provider | diff --git a/packages/nanobot/README.md b/packages/nanobot/README.md new file mode 100644 index 0000000..2c4e95b --- /dev/null +++ b/packages/nanobot/README.md @@ -0,0 +1,84 @@ +# agent-nanobot + +`@magpie-community/agent-nanobot` adds [nanobot](https://github.com/HKUDS/nanobot) to Magpie's Agents page. Pick one of Magpie's models in its row and Magpie writes it into nanobot's configuration; Library gives it MCP servers and workspace skills. Upstream credentials stay in Magpie. This is an unofficial integration and implies no endorsement by the nanobot project. + +The original integration was tested on Windows with Magpie 0.1.3384 and 0.1.3373, and nanobot 0.4.1. The parent-symlink and exit-lifecycle changes have been regression-tested on Linux x86_64 with Bun 1.4.2, including a symlinked `TMPDIR`; they have not yet been retested in a full Magpie/nanobot installation. Full integration on Linux, macOS and WSL, and other nanobot versions, remains untested. + +## Installation + +```sh +uv tool install --python 3.12 nanobot-ai +nanobot onboard + +magpie plugin add @magpie-community/agent-nanobot +``` + +## Use + +1. Pick a model in the **nanobot** row on Magpie's Agents page. It becomes nanobot's default preset, so a session started afterwards begins on it. A session already running may keep its own. +2. In Library → MCP, tick nanobot for the servers it should have. Restart nanobot to load them. +3. In Library → Skills, tick the skills it should have. Prefer **Copy** for nanobot in Library's **How** setting: with workspace restrictions, a per-skill link can keep `read_file` from opening the skill's bundled files. + +## What Magpie manages + +In `~/.nanobot/config.json`: `providers.magpie`, `modelPresets.magpie` and `agents.defaults.modelPreset`. In `tools.mcpServers`: the entries for ticked servers, plus the exact loopback address a server at `127.0.0.1` or `::1` needs, which nanobot blocks otherwise. Everything else in the file is left alone. + +A same-name entry you wrote yourself is refused rather than taken over. Editing a managed field by hand pauses synchronisation and keeps a recovery record. A journal is written before every change, so an interrupted run is replayed instead of half-applied. + +Parent directories may be symlinks, including the home directory, `~/.nanobot` and `~/.config`. The final configuration, control, state, journal and lock files must be regular files; links at those file paths, including dangling links, are refused. + +## Disconnect + +Turn the agent off in Magpie, or run `magpie nanobot default`, to restore the managed model fields to their previous values (or remove them if they did not exist). MCP assignments and skills are independent: untick them separately in Library. Removing managed MCP servers also removes loopback exemptions introduced by this adapter when no remaining server needs them. Restart nanobot to load MCP changes; existing sessions may keep their selected model. + +Before disabling or uninstalling the plugin, disconnect the model and remove any Library assignments you no longer want. Let the adapter finish synchronizing while it is still running. + +Normal exit, including an update or shared-host restart, does not itself disconnect nanobot. The owning adapter synchronizes the current control files once before releasing its lock: connected model and MCP settings remain in place, while a model disconnect or MCP deselection that has not reached the next polling tick is applied. Ownership records remain available for the next host to resume. Retaining configuration does not keep the Magpie gateway online; models using it still require a running gateway. + +For an explicit restore, or if Magpie is killed before a requested disconnect is applied, run the one-shot fallback `node cli.mjs restore` from this package. It restores managed fields and pauses unchanged inputs so a running adapter does not immediately reconnect them. + +## Status and recovery + +From this package directory: + +```sh +node cli.mjs status # Inspect recorded status and pending recovery; no config writes. +node cli.mjs sync # Synchronize the current model and MCP inputs once. +node cli.mjs restore # Restore managed fields and pause unchanged inputs. +``` + +`sync` respects an existing pause; it does not force reconnection after `restore`. Changing the model or MCP input lets synchronization resume. Skills are managed by Library and are not removed by `restore`. + +If status reports `conflict`, inspect its `code` and resolve the underlying configuration or path issue before retrying `sync`. Keep the ownership and pending-journal files: they are needed to restore managed fields or finish an interrupted transaction. Status output omits configuration contents, gateway URLs and keys. Commands exit with code 1 on a conflict or operational error, and 2 for invalid arguments. + +## Development + +From `packages/nanobot` in a checkout of the community plugins repository: + +```sh +bun test nanobot.test.mjs +``` + +The repository's `scripts/check.mjs` skips Agent packages; `nanobot.test.mjs` covers the descriptor, the published-package contract and what `connect()` returns. + +Linux x86_64 / Bun 1.4.2 validation: `bun test packages/nanobot` from the repository root passes 60 tests (312 assertions), both with the default temporary directory and with `TMPDIR` pointing to a directory symlink. This covers apply/restore, journal replay, first-run state-directory creation, refusal of final-file links (including dangling links), reserved-file collisions through directory aliases, configuration retention across host restarts, pending disconnects on exit, paused restores, invalid inputs and lost ownership. Recovery-status tests check early parse failures without trusting invalid or foreign ownership records. Isolated subprocesses load the actual plugin entry and exit naturally to verify its exit hook, final synchronization and lock release; only the home-directory lookup is substituted. `bun scripts/check.mjs` also passes. + +## 中文 + +把 [nanobot](https://github.com/HKUDS/nanobot) 加到 Magpie 的 Agent 页。在 **nanobot** 一行选 Magpie 的模型,Magpie 会写进 nanobot 的配置;资源库里可以为它勾选 MCP 服务和技能。上游凭证仍留在 Magpie。这是非官方集成。 + +先装 nanobot 并执行 `nanobot onboard`,再执行 `magpie plugin add @magpie-community/agent-nanobot`。选中的模型就是 nanobot 的默认 preset,之后启动的会话从它开始;已在运行的会话可能保留自己的模型。MCP 变更后要重启 nanobot。资源库的 **How** 建议仅对 nanobot 设为 Copy,避免工作区限制读不到技能附带文件。 + +受管字段只有配置里的 `providers.magpie`、`modelPresets.magpie`、`agents.defaults.modelPreset`,以及勾选服务的 `tools.mcpServers` 条目和相应的 loopback 白名单。手写的同名条目不会被接管;手改受管字段会暂停同步并保留恢复记录。 + +关闭 Agent 或执行 `magpie nanobot default` 只还原受管模型字段。MCP 和技能分别在资源库取消;移除受管 MCP 时,适配器添加且已无服务需要的 loopback 豁免也会移除。禁用或卸载插件前,先断开模型、取消不再需要的资源库分配,并等待仍在运行的适配器完成同步。 + +原始集成在 Windows 上验证过。本次父目录符号链接和退出行为变更已通过 Linux x86_64 / Bun 1.4.2 回归测试(60 项测试、312 个断言,普通临时目录和符号链接 `TMPDIR` 均通过),尚未在完整 Magpie/nanobot 安装中复测。Linux 完整集成、macOS 和 WSL 尚未验证。 + +主目录、`~/.nanobot` 和 `~/.config` 等父目录可以是符号链接;配置、控制、状态、日志和锁文件本身必须是普通文件,文件位置上的符号链接(包括悬空链接)仍会被拒绝。 + +Magpie 正常退出、更新或共享宿主重启本身不会断开 nanobot。持有锁的适配器会在退出前按当前控制文件同步一次,再释放锁:仍连接的模型和 MCP 配置保留;刚断开模型或取消 MCP、尚未被轮询处理的操作会在此时生效。所有权记录保留,下一次启动可继续管理。保留配置不代表网关仍在线,使用 Magpie 网关的模型仍需要网关运行。 + +在包目录中运行 `node cli.mjs status` 可查看已记录的状态和待恢复事务,不会写入配置;`node cli.mjs sync` 按当前输入同步一次;`node cli.mjs restore` 主动还原受管字段并暂停未变化的输入,适用于手动还原或 Magpie 在执行断开操作前被强制结束的情况。`restore` 不会移除资源库管理的技能。 + +`sync` 会遵守已有的暂停状态,不会强制重新连接;修改模型或 MCP 输入后可恢复同步。遇到 `conflict` 时先根据 `code` 排查配置或路径问题,再重试。保留所有权记录和待恢复日志,以便还原字段或完成中断的事务。状态输出不包含配置正文、网关地址或密钥;冲突或运行错误的退出码为 1,参数错误为 2。 diff --git a/packages/nanobot/bridge.mjs b/packages/nanobot/bridge.mjs new file mode 100644 index 0000000..e324ed0 --- /dev/null +++ b/packages/nanobot/bridge.mjs @@ -0,0 +1,422 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import crypto from 'node:crypto'; +import net from 'node:net'; + +const VERSION = 1; +// The one provider ID this adapter creates. The paths it lives under, the +// preset that names it and every reference check below derive from this +// constant: if the name in a path and the name in a value drifted apart, the +// provider would be written without an owner able to restore it. Exported so +// the tests can assert that link instead of restating the literal. +export const PROVIDER = 'magpie'; +const own = (o, k) => Object.hasOwn(o, k); +const object = v => v !== null && typeof v === 'object' && !Array.isArray(v); +const clone = v => structuredClone(v); +const canonical = v => JSON.stringify(v, (_, x) => object(x) ? Object.fromEntries(Object.keys(x).sort().map(k => [k, x[k]])) : x); +const equal = (a, b) => canonical(a) === canonical(b); +const absent = () => ({ exists: false }); +const valueOf = value => ({ exists: true, value: clone(value) }); +const fail = code => { throw Object.assign(new Error(code), { code }); }; + +export function pathsFor({ home = os.homedir(), stateDir, configPath } = {}) { + const directory = path.resolve(stateDir || path.join(home, '.config', 'magpie-nanobot')); + return { directory, control: path.join(directory, 'connection.json'), mcp: path.join(directory, 'mcp.json'), + config: path.resolve(configPath || path.join(home, '.nanobot', 'config.json')), + state: path.join(directory, 'state.json'), pending: path.join(directory, 'pending.json'), + lock: path.join(directory, 'bridge.lock'), pause: path.join(directory, 'paused.json'), status: path.join(directory, 'status.json') }; +} + +// System and home/config directories may be links (e.g. macOS /var). +// Resolve those directories, but never follow the final file, even a dangling +// link. This is a local writer guard, not an OS sandbox or a race-proof walk. +function regular(file, directory = false) { + const absolute = path.resolve(file); + try { + const resolved = directory ? fs.realpathSync(absolute) + : path.join(fs.realpathSync(path.dirname(absolute)), path.basename(absolute)); + const st = fs.lstatSync(resolved); + if (st.isSymbolicLink()) fail('symlink_refused'); + if (directory ? !st.isDirectory() : !st.isFile()) fail('not_regular_file'); + return true; + } catch (error) { + if (error.code === 'ENOENT') return false; + if (error.code === 'ENOTDIR') fail('parent_not_directory'); + throw error; + } +} +// Compare aliases even before the state directory has been created. Resolve +// existing parents only: resolving the leaf would hide a forbidden file link. +function fileIdentity(file) { + let parent = path.dirname(path.resolve(file)); + const suffix = [path.basename(file)]; + for (;;) { + try { return path.join(fs.realpathSync(parent), ...suffix); } + catch (error) { + if (error.code !== 'ENOENT' || parent === path.dirname(parent)) throw error; + suffix.unshift(path.basename(parent)); + parent = path.dirname(parent); + } + } +} +function read(file, required = false) { + if (!regular(file)) { if (required) fail('required_file_missing'); return null; } + const text = fs.readFileSync(file, 'utf8'); + let data; + try { data = JSON.parse(text); } catch { fail('invalid_json'); } + if (!object(data)) fail('json_object_required'); + return { text, data }; +} +function atomic(file, data, { text = false } = {}) { + regular(path.dirname(file), true); + fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + regular(path.dirname(file), true); + regular(file); + const temp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`; + try { + fs.writeFileSync(temp, text ? data : `${JSON.stringify(data, null, 2)}\n`, { flag: 'wx', mode: 0o600 }); + regular(file); + fs.renameSync(temp, file); + } finally { if (fs.existsSync(temp)) fs.unlinkSync(temp); } +} +function remove(file) { if (regular(file)) fs.unlinkSync(file); } +function get(doc, keys) { + let v = doc; + for (const key of keys) { if (!object(v) || !own(v, key)) return absent(); v = v[key]; } + return valueOf(v); +} +function put(doc, keys, entry) { + let o = doc; + for (const key of keys.slice(0, -1)) { + if (!own(o, key)) Object.defineProperty(o, key, { value: {}, enumerable: true, writable: true, configurable: true }); + if (!object(o[key])) fail('config_parent_not_object'); + o = o[key]; + } + const key = keys.at(-1); + if (entry.exists) Object.defineProperty(o, key, { value: clone(entry.value), enumerable: true, writable: true, configurable: true }); + else delete o[key]; +} +function prune(doc, parents) { + for (const keys of [...parents].sort((a, b) => b.length - a.length)) { + const v = get(doc, keys); + if (v.exists && object(v.value) && Object.keys(v.value).length === 0) put(doc, keys, absent()); + } +} +const MODEL_PATHS = { provider: ['providers', PROVIDER], preset: ['modelPresets', PROVIDER], selector: ['agents', 'defaults', 'modelPreset'] }; +function recordPath(id) { + if (own(MODEL_PATHS, id)) return MODEL_PATHS[id]; + if (id.startsWith('mcp:') && id.length > 4) return ['tools', 'mcpServers', id.slice(4)]; + fail('invalid_state_record'); +} +// nanobot's own model_dump fills these defaults during an unrelated WebUI +// save. Only these exact schema defaults are equivalent to omission; +// arbitrary extra fields, auth overrides, proxies and tool filters still conflict. +const SCHEMA_DEFAULTS = { + provider: { extraHeaders: null, extraBody: null, extraQuery: null, useProxy: false, thinkingStyle: null }, + preset: { extraHeaders: null, extraQuery: null, extraBody: null, maxTokens: 8192, contextWindowTokens: 200000, temperature: 0.1, reasoningEffort: null, api: null }, + mcp: { auth: null, command: '', args: [], env: {}, cwd: '', url: '', headers: {}, useProxy: false, toolTimeout: 30, enabledTools: ['*'] }, +}; +function sameEntry(a, b, id) { + if (equal(a, b)) return true; + if (!a.exists || !b.exists || !object(a.value) || !object(b.value)) return false; + const defaults = SCHEMA_DEFAULTS[id.startsWith('mcp:') ? 'mcp' : id]; + return !!defaults && equal({ ...defaults, ...a.value }, { ...defaults, ...b.value }); +} +function validEntry(v) { return object(v) && typeof v.exists === 'boolean' && (!v.exists || own(v, 'value')); } +function validateState(data, config) { + if (!object(data) || data.version !== VERSION || data.configPath !== config || !Array.isArray(data.records) || !Array.isArray(data.addedWhitelist) || !Array.isArray(data.parents)) fail('invalid_or_wrong_target_state'); + const seen = new Set(); + for (const r of data.records) { + if (!object(r) || typeof r.id !== 'string' || !validEntry(r.before) || !validEntry(r.applied) || seen.has(r.id)) fail('invalid_state_record'); + recordPath(r.id); seen.add(r.id); + } + if (!data.addedWhitelist.every(x => typeof x === 'string' && /^(127\.(?:\d{1,3}\.){2}\d{1,3}\/32|::1\/128)$/.test(x))) fail('invalid_state_whitelist'); + const allowed = [['providers'], ['modelPresets'], ['agents'], ['agents', 'defaults'], ['tools'], ['tools', 'mcpServers']]; + if (!data.parents.every(p => allowed.some(a => equal(a, p)))) fail('invalid_state_parents'); + if (data.whitelistBefore !== undefined && !validEntry(data.whitelistBefore)) fail('invalid_state_whitelist'); + return data; +} +function emptyState(config) { return { version: VERSION, configPath: config, records: [], addedWhitelist: [], parents: [] }; } +function active(st) { return st.records.length > 0 || st.addedWhitelist.length > 0; } +function aliases(doc, model, mcp) { + if (model && (own(doc, 'model_presets') || own(doc.agents?.defaults || {}, 'model_preset'))) fail('snake_case_alias_conflict'); + if (mcp && (own(doc.tools || {}, 'mcp_servers') || own(doc.tools || {}, 'ssrf_whitelist'))) fail('snake_case_alias_conflict'); +} +function parseControl(source) { + if (!source) return null; + const d = source.data, keys = ['model', 'baseURL', 'gatewayKey']; + if (keys.every(k => !own(d, k))) { + if (own(d, 'modelInfo') && Object.keys(d.modelInfo || {}).length) fail('incomplete_control'); + return null; + } + if (!keys.every(k => typeof d[k] === 'string' && d[k].trim().length > 0)) fail('incomplete_control'); + let u; try { u = new URL(d.baseURL); } catch { fail('invalid_gateway_url'); } + if (!['http:', 'https:'].includes(u.protocol) || u.username || u.password || u.search || u.hash) fail('invalid_gateway_url'); + if (d.modelInfo !== undefined && !object(d.modelInfo)) fail('invalid_model_info'); + for (const k of ['context', 'output']) if (d.modelInfo?.[k] !== undefined && (!Number.isSafeInteger(d.modelInfo[k]) || d.modelInfo[k] < 0)) fail('invalid_model_info'); + if (d.modelInfo?.images !== undefined && typeof d.modelInfo.images !== 'boolean') fail('invalid_model_info'); + return d; +} +function stringMap(v) { return object(v) && Object.values(v).every(x => typeof x === 'string'); } +function parseMCP(source) { + if (!source) return null; // Unknown is distinct from an explicit empty map. + const d = source.data; + if (!own(d, 'mcpServers')) { if (Object.keys(d).length === 0) return {}; fail('invalid_mcp_staging'); } + if (!object(d.mcpServers)) fail('invalid_mcp_staging'); + const result = Object.create(null); + for (const [name, s] of Object.entries(d.mcpServers)) { + if (!name || !object(s) || !['stdio', 'http', 'sse'].includes(s.type)) fail('invalid_mcp_server'); + const v = { type: s.type === 'http' ? 'streamableHttp' : s.type }; + if (s.type === 'stdio') { + if (typeof s.command !== 'string' || !s.command.trim() || (s.args !== undefined && (!Array.isArray(s.args) || !s.args.every(x => typeof x === 'string'))) || (s.env !== undefined && !stringMap(s.env))) fail('invalid_mcp_stdio'); + v.command = s.command; if (s.args !== undefined) v.args = clone(s.args); if (s.env !== undefined) v.env = clone(s.env); + } else { + let u; try { u = new URL(s.url); } catch { fail('invalid_mcp_url'); } + if (!['http:', 'https:'].includes(u.protocol) || u.username || u.password) fail('invalid_mcp_url'); + if (s.headers !== undefined && !stringMap(s.headers)) fail('invalid_mcp_headers'); + v.url = s.url; if (s.headers !== undefined) v.headers = clone(s.headers); + } + Object.defineProperty(result, name, { value: v, enumerable: true }); + } + return result; +} +function loopbacks(server) { + // Native nanobot entries may omit type and infer HTTP/SSE from the URL. + if (!server?.url || (server.type != null && !['http', 'streamableHttp', 'sse'].includes(server.type))) return []; + let host; try { host = new URL(server.url).hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, ''); } catch { return []; } + if (host === 'localhost') return ['127.0.0.1/32', '::1/128']; + if (host === '::1') return ['::1/128']; + return net.isIP(host) === 4 && host.startsWith('127.') ? [`${host}/32`] : []; +} +function acquire(paths) { + regular(paths.directory, true); fs.mkdirSync(paths.directory, { recursive: true, mode: 0o700 }); regular(paths.directory, true); + const token = crypto.randomUUID(); + const create = () => fs.writeFileSync(paths.lock, JSON.stringify({ pid: process.pid, token }), { flag: 'wx', mode: 0o600 }); + const release = () => { const current = read(paths.lock); if (current?.data.token === token) remove(paths.lock); }; + regular(paths.lock); + try { create(); return release; } catch (error) { if (error.code !== 'EEXIST') throw error; } + // Serialize stale-owner reclamation itself. Without a separate exclusive + // guard, two processes can both observe a dead PID and one can unlink the + // other's freshly created lock between its final read and unlink. + const guard = `${paths.lock}.reclaim`; + regular(guard); + try { fs.writeFileSync(guard, JSON.stringify({ pid: process.pid, token }), { flag: 'wx', mode: 0o600 }); } + catch (error) { if (error.code === 'EEXIST') fail('lock_reclaim_in_progress'); throw error; } + try { + const held = read(paths.lock)?.data; + if (held) { + if (!Number.isSafeInteger(held.pid) || held.pid <= 0 || typeof held.token !== 'string') fail('invalid_lock'); + try { process.kill(held.pid, 0); fail('writer_locked'); } catch (error) { if (error.code !== 'ESRCH') throw error; } + paths.__fault?.('dead-lock-guarded'); + if (!equal(read(paths.lock)?.data, held)) fail('writer_locked'); + remove(paths.lock); + } + paths.__fault?.('before-lock-recreate'); + // A new normal wx acquisition can win after removal. In that case stop; + // never loop back and delete the winning owner's lock. + try { create(); } catch (error) { if (error.code === 'EEXIST') fail('writer_locked'); throw error; } + return release; + } finally { + try { if (read(guard)?.data.token === token) remove(guard); } catch { /* Leave an uncertain guard for diagnosis. */ } + } +} +function safeStatus(paths, state, extras = {}) { + return { state, servers: [], restartRequired: false, recoveryPending: false, configPath: path.resolve(paths.config), ...extras }; +} +function references(doc) { + const fallbackRef = p => [p?.fallbackModels, p?.fallback_models].some(list => Array.isArray(list) && list.some(x => x === PROVIDER || (object(x) && (x.provider === PROVIDER || x.modelPreset === PROVIDER || x.model_preset === PROVIDER)))); + const other = Object.entries(doc.modelPresets || {}).some(([name, p]) => name !== PROVIDER && object(p) && (p.provider === PROVIDER || p.modelPreset === PROVIDER || p.model_preset === PROVIDER || fallbackRef(p))); + const defaults = doc.agents?.defaults || {}; + // The owned defaults.modelPreset selector is restored separately. Other + // references created while connected must keep their provider/preset alive. + return other || defaults.provider === PROVIDER || fallbackRef(defaults) + || defaults.dream?.modelOverride === PROVIDER || defaults.dream?.model_override === PROVIDER; +} +function modelValues(control) { + const provider = { apiBase: control.baseURL, apiKey: control.gatewayKey, api: { supportedApis: ['chat_completions'], preferredApi: 'chat_completions' } }; + const preset = { model: control.model.startsWith(`${PROVIDER}/`) ? `${PROVIDER}/${control.model}` : control.model, provider: PROVIDER }; + const { context, output } = control.modelInfo || {}; + if (context > 0) preset.contextWindowTokens = context; + if (output > 0) preset.maxTokens = context > 0 ? Math.min(context, output) : output; + else if (context > 0) preset.maxTokens = Math.min(8192, context); + return { provider, preset, selector: PROVIDER }; +} +function validatePending(p, config) { + if (!object(p) || p.version !== VERSION || p.configPath !== config || !Array.isArray(p.patches) || !Array.isArray(p.cleanupParents)) fail('invalid_or_wrong_target_pending'); + validateState(p.nextState, config); + const seen = new Set(); + for (const patch of p.patches) { + if (!object(patch) || typeof patch.id !== 'string' || !validEntry(patch.before) || !validEntry(patch.after) || seen.has(patch.id)) fail('invalid_pending_patch'); + if (patch.id !== 'whitelist') recordPath(patch.id); + seen.add(patch.id); + } + validateState({ ...emptyState(config), parents: p.cleanupParents }, config); + return p; +} +function patchPath(id) { return id === 'whitelist' ? ['tools', 'ssrfWhitelist'] : recordPath(id); } +function commit(paths, document, transaction) { + // A pending journal is an intent, not permission to ignore references added + // since it was prepared. Recheck against the latest native document on every + // replay, before removing either named object. + if (transaction.patches.some(p => ['provider', 'preset'].includes(p.id) && !p.after.exists) && references(document.data)) fail('pending_named_object_still_referenced'); + const next = clone(document.data); + for (const patch of transaction.patches) { + const current = get(next, patchPath(patch.id)); + if (!sameEntry(current, patch.before, patch.id) && !sameEntry(current, patch.after, patch.id)) fail('pending_patch_conflict'); + put(next, patchPath(patch.id), patch.after); + } + const permissionPatch = transaction.patches.find(p => p.id === 'whitelist'); + if (permissionPatch) { + const removed = (permissionPatch.before.value || []).filter(ip => !(permissionPatch.after.value || []).includes(ip)); + const stillRequired = new Set(Object.values(next.tools?.mcpServers || {}).flatMap(loopbacks)); + if (removed.some(ip => stillRequired.has(ip))) fail('pending_whitelist_still_required'); + } + prune(next, transaction.cleanupParents); + paths.__fault?.('before-config'); + const latest = read(paths.config, true); + if (latest.text !== document.text) fail('config_changed_before_write'); + const changed = !equal(document.data, next); + if (changed) atomic(paths.config, `${JSON.stringify(next, null, 2)}\n`, { text: true }); + paths.__fault?.('after-config'); + if (active(transaction.nextState)) atomic(paths.state, transaction.nextState); else remove(paths.state); + paths.__fault?.('after-state'); + remove(paths.pending); + return changed; +} + +export function reconcile(paths, { restore = false, pause = false } = {}) { + let release, st; + try { + paths = { ...paths, config: path.resolve(paths.config) }; + const configIdentity = fileIdentity(paths.config); + if ([...['control', 'mcp', 'state', 'pending', 'lock', 'pause', 'status'].map(k => paths[k]), `${paths.lock}.reclaim`].some(file => fileIdentity(file) === configIdentity)) fail('reserved_config_path'); + release = acquire(paths); + regular(paths.status); + // Validate every source before performing even a pending target write. + const controlSource = read(paths.control), mcpSource = read(paths.mcp); + const control = parseControl(controlSource), mcp = parseMCP(mcpSource); + let document = read(paths.config, true); + st = read(paths.state)?.data || emptyState(paths.config); validateState(st, paths.config); + const pending = read(paths.pending)?.data; + const paused = read(paths.pause)?.data; + if (paused && (paused.version !== VERSION || paused.configPath !== paths.config || typeof paused.hash !== 'string')) fail('invalid_or_wrong_target_pause'); + const hash = crypto.createHash('sha256').update(canonical({ config: paths.config, control: controlSource?.data ?? null, mcp: mcpSource?.data ?? null })).digest('hex'); + aliases(document.data, !!control || st.records.some(r => own(MODEL_PATHS, r.id)) || !!pending, mcp !== null || st.records.some(r => r.id.startsWith('mcp:')) || st.addedWhitelist.length > 0 || !!pending); + let changed = false; + if (pending) { + validatePending(pending, paths.config); + changed = commit(paths, document, pending); + st = pending.nextState; document = read(paths.config, true); + } + if (pause) atomic(paths.pause, { version: VERSION, configPath: paths.config, hash }); + if (!restore && (pause || paused?.hash === hash)) { + const result = safeStatus(paths, 'paused', { servers: st.records.filter(r => r.id.startsWith('mcp:')).map(r => r.id.slice(4)), recoveryPending: active(st), restartRequired: changed }); + atomic(paths.status, result); return result; + } + if (paused && paused.hash !== hash && !pause) remove(paths.pause); + const doc = document.data, nextState = clone(st), desired = new Map(); + if (!restore && control) for (const [id, value] of Object.entries(modelValues(control))) desired.set(id, valueOf(value)); + if (!restore && mcp !== null) for (const [name, value] of Object.entries(mcp)) desired.set(`mcp:${name}`, valueOf(value)); + if (!restore && mcp === null) for (const r of st.records.filter(r => r.id.startsWith('mcp:'))) desired.set(r.id, r.applied); + const records = new Map(st.records.map(r => [r.id, r])); + // Do not delete a provider now used by a user's later preset/default. + if (records.has('provider') && !desired.has('provider') && references(doc)) fail('managed_provider_still_referenced'); + if (records.has('preset') && !desired.has('preset')) { + const defaults = doc.agents?.defaults; + const selector = records.get('selector'); + if (defaults?.modelPreset === PROVIDER && (!selector || !equal(get(doc, MODEL_PATHS.selector), selector.applied))) fail('managed_preset_still_referenced'); + } + const patches = [], after = clone(doc), nextRecords = []; + for (const id of new Set([...records.keys(), ...desired.keys()])) { + const previous = records.get(id), current = get(doc, recordPath(id)); + if (previous && !sameEntry(current, previous.applied, id) && !(!desired.has(id) && sameEntry(current, previous.before, id))) fail('managed_field_changed'); + if (!previous && current.exists && id !== 'selector') fail('unowned_name_collision'); + const target = desired.has(id) ? desired.get(id) : previous.before; + if (!sameEntry(current, target, id)) patches.push({ id, before: current, after: target }); + put(after, recordPath(id), target); + if (desired.has(id)) nextRecords.push({ id, before: previous?.before || current, applied: target }); + } + nextState.records = nextRecords; + const parentCandidates = [['providers'], ['modelPresets'], ['agents'], ['agents', 'defaults'], ['tools'], ['tools', 'mcpServers']]; + for (const p of parentCandidates) if (!get(doc, p).exists && get(after, p).exists && !nextState.parents.some(x => equal(x, p))) nextState.parents.push(p); + const whitelistCurrent = get(doc, ['tools', 'ssrfWhitelist']); + if (whitelistCurrent.exists && (!Array.isArray(whitelistCurrent.value) || !whitelistCurrent.value.every(x => typeof x === 'string'))) fail('invalid_ssrf_whitelist'); + const required = new Set(); + // All remaining services count, including non-managed services which depend + // on a loopback member introduced by this bridge. + const remaining = get(after, ['tools', 'mcpServers']); + if (remaining.exists && !object(remaining.value)) fail('invalid_native_mcp_map'); + for (const s of Object.values(remaining.value || {})) for (const ip of loopbacks(s)) required.add(ip); + const managedRequired = new Set(); + for (const r of nextRecords.filter(r => r.id.startsWith('mcp:'))) for (const ip of loopbacks(r.applied.value)) managedRequired.add(ip); + const previousAdded = new Set(st.addedWhitelist); + let whitelist = [...(whitelistCurrent.value || [])]; + if ([...managedRequired].some(ip => previousAdded.has(ip) && !whitelist.includes(ip))) fail('managed_whitelist_removed'); + for (const ip of previousAdded) if (!required.has(ip)) whitelist = whitelist.filter(x => x !== ip); + const added = new Set([...previousAdded].filter(x => whitelist.includes(x))); + for (const ip of managedRequired) if (!whitelist.includes(ip)) { whitelist.push(ip); added.add(ip); } + nextState.addedWhitelist = [...added]; + if (!st.whitelistBefore && added.size) nextState.whitelistBefore = whitelistCurrent; + const beforeWhitelist = st.whitelistBefore || nextState.whitelistBefore; + let whitelistAfter = valueOf(whitelist); + if (whitelist.length === 0 && beforeWhitelist && !beforeWhitelist.exists) whitelistAfter = absent(); + if (!equal(whitelistCurrent, whitelistAfter) && (st.addedWhitelist.length > 0 || managedRequired.size > 0)) { + patches.push({ id: 'whitelist', before: whitelistCurrent, after: whitelistAfter }); + put(after, ['tools', 'ssrfWhitelist'], whitelistAfter); + } + if (!nextState.addedWhitelist.length) delete nextState.whitelistBefore; + const transaction = { version: VERSION, configPath: paths.config, patches, nextState, cleanupParents: nextState.parents }; + if (patches.length || !equal(st, nextState)) { + atomic(paths.pending, transaction); + paths.__fault?.('after-pending'); + changed = commit(paths, document, transaction) || changed; + } + const servers = nextRecords.filter(r => r.id.startsWith('mcp:')).map(r => r.id.slice(4)); + const result = safeStatus(paths, active(nextState) ? 'file-applied' : 'disconnected', { + ...(control && !restore ? { model: control.model } : {}), servers, + restartRequired: changed || active(nextState), recoveryPending: nextState.addedWhitelist.some(x => !managedRequired.has(x)), + ...(nextState.addedWhitelist.length ? { networkNotice: 'Exact loopback IP exemptions affect nanobot network policy globally, not only these MCP endpoints.' } : {}), + }); + atomic(paths.status, result); return result; + } catch (error) { + if (error?.__bridgeFault) throw error; + const known = new Set(['symlink_refused', 'parent_not_directory', 'not_regular_file', 'required_file_missing', 'invalid_json', 'json_object_required', 'config_parent_not_object', 'invalid_state_record', 'invalid_or_wrong_target_state', 'invalid_state_whitelist', 'invalid_state_parents', 'snake_case_alias_conflict', 'incomplete_control', 'invalid_gateway_url', 'invalid_model_info', 'invalid_mcp_staging', 'invalid_mcp_server', 'invalid_mcp_stdio', 'invalid_mcp_url', 'invalid_mcp_headers', 'invalid_lock', 'writer_locked', 'invalid_or_wrong_target_pending', 'invalid_pending_patch', 'pending_patch_conflict', 'config_changed_before_write', 'invalid_or_wrong_target_pause', 'managed_provider_still_referenced', 'managed_preset_still_referenced', 'managed_field_changed', 'unowned_name_collision', 'invalid_ssrf_whitelist', 'invalid_native_mcp_map', 'managed_whitelist_removed', 'reserved_config_path', 'pending_named_object_still_referenced', 'pending_whitelist_still_required', 'lock_reclaim_in_progress']); + const code = known.has(error?.code) ? error.code : 'bridge_io_error'; + // Control/config parsing can fail before ownership is loaded. Consult a + // valid record for this target without masking the original failure or + // treating an unreadable/foreign record as permission to change anything. + let recoveryState = st; + if (!recoveryState) { + try { + const saved = read(paths.state)?.data; + if (saved) recoveryState = validateState(saved, path.resolve(paths.config)); + } catch { /* Keep the original conflict; recovery files are left intact. */ } + } + const hasOwnership = (Array.isArray(recoveryState?.records) && recoveryState.records.length > 0) || (Array.isArray(recoveryState?.addedWhitelist) && recoveryState.addedWhitelist.length > 0); + const result = safeStatus(paths, 'conflict', { code, recoveryPending: hasOwnership || fs.existsSync(paths.pending) }); + // Only this lock's owner may publish diagnostics. Failure to publish must + // never hide the original conflict or modify the target configuration. + if (release) { try { atomic(paths.status, result); } catch { /* Keep the conflict return usable. */ } } + return result; + } finally { try { release?.(); } catch { /* Never unlink a lock replaced by another writer. */ } } +} + +export function inspect(paths) { + // Never return journal/control values, raw parse errors, URLs, or credentials. + try { + const pending = read(paths.pending)?.data; + if (pending) { + validatePending(pending, path.resolve(paths.config)); + return safeStatus(paths, 'recovery-pending', { recoveryPending: true, restartRequired: true, servers: pending.nextState.records.filter(r => r.id.startsWith('mcp:')).map(r => r.id.slice(4)) }); + } + const status = read(paths.status)?.data; + if (!status) return safeStatus(paths, 'disconnected'); + if (status.configPath !== path.resolve(paths.config)) return safeStatus(paths, 'conflict', { code: 'status_target_mismatch' }); + const result = safeStatus(paths, typeof status.state === 'string' ? status.state : 'conflict'); + for (const key of ['model', 'code', 'networkNotice']) if (typeof status[key] === 'string') result[key] = status[key]; + if (Array.isArray(status.servers) && status.servers.every(x => typeof x === 'string')) result.servers = status.servers; + result.restartRequired = status.restartRequired === true; result.recoveryPending = status.recoveryPending === true; + return result; + } catch { return safeStatus(paths, 'conflict', { code: 'status_unreadable' }); } +} diff --git a/packages/nanobot/cli.mjs b/packages/nanobot/cli.mjs new file mode 100644 index 0000000..a0d7142 --- /dev/null +++ b/packages/nanobot/cli.mjs @@ -0,0 +1,28 @@ +#!/usr/bin/env node +import path from "node:path" +import { pathsFor, reconcile, inspect } from "./bridge.mjs" +import { resolvePaths } from "./runtime.mjs" + +const args = process.argv.slice(2) +const action = args.shift() || "status" +const options = {} +let invalid = false +while (args.length) { + const flag = args.shift() + if (!["--config", "--state-dir"].includes(flag) || !args.length) { invalid = true; break } + options[flag === "--config" ? "configPath" : "stateDir"] = path.resolve(args.shift()) +} +if (invalid || !["status", "sync", "restore"].includes(action)) { + console.error("Usage: magpie-nanobot [--config ] [--state-dir ]") + process.exitCode = 2 +} else { + try { + const p = options.stateDir ? pathsFor(options) : resolvePaths(options) + const result = action === "status" ? inspect(p) : reconcile(p, action === "restore" ? { restore: true, pause: true } : {}) + console.log(JSON.stringify(result, null, 2)) + if (result.state === "conflict") process.exitCode = 1 + } catch { + console.error("nanobot adapter could not complete the operation. Check target path, JSON syntax, file permissions and recovery records. Configuration contents and keys are omitted.") + process.exitCode = 1 + } +} diff --git a/packages/nanobot/index.mjs b/packages/nanobot/index.mjs new file mode 100644 index 0000000..7cfaa40 --- /dev/null +++ b/packages/nanobot/index.mjs @@ -0,0 +1,23 @@ +import { resolvePaths, startRuntime } from "./runtime.mjs" + +const instance = Symbol.for("magpie.nanobot.adapter.v1") + +// Magpie treats every exported function in main as a plugin. Keep helpers in +// their own modules, and never terminate or take signals from its shared host. +export default async function NanobotAgent(input, options = {}) { + if (!globalThis[instance]) { + const runtime = startRuntime(resolvePaths(options), { + onStatus(status) { + const level = status.state === "conflict" ? "warn" : "info" + const message = `nanobot adapter: ${status.state}; MCP changes require a nanobot restart. Run magpie-nanobot status for details.` + try { void input?.client?.app?.log?.({ body: { service: "nanobot-agent", level, message } })?.catch?.(() => {}) } catch {} + }, + }) + globalThis[instance] = runtime + // Flush any pending disconnect; normal host exit keeps connected inputs. + process.once("exit", () => { + try { runtime.stop() } catch { console.error("nanobot final sync paused; retain the adapter recovery files and run magpie-nanobot status.") } + }) + } + return {} +} diff --git a/packages/nanobot/nanobot.agent.js b/packages/nanobot/nanobot.agent.js new file mode 100644 index 0000000..7c7e8ab --- /dev/null +++ b/packages/nanobot/nanobot.agent.js @@ -0,0 +1,30 @@ +// Magpie runs this descriptor in moejs. The Bun companion applies its intent +// to nanobot's config and consumes the Library's separate MCP output. +export const agent = { + id: "nanobot", + name: "nanobot", + // Official app mark; Magpie fetches and caches this URL, as for PiG. + icon: "https://raw.githubusercontent.com/HKUDS/nanobot/main/webui/public/brand/nanobot_mark.svg", + bin: "nanobot", + dir: "~/.nanobot", + config: "~/.config/magpie-nanobot/connection.json", + format: "json", + model: "model", + ua: ["nanobot"], + notice: "Keep Magpie running and wait for the adapter. Restart nanobot to load MCP changes; existing sessions may keep their own model. 保持 Magpie 运行并等待同步;MCP 变更后重启 nanobot,已有会话可能保留自己的模型。", + library: { + mcp: "~/.config/magpie-nanobot/mcp.json", + mcpFormat: "claude", + // nanobot loads workspace/skills; Library owns linking/copying and removal. + skills: "~/.nanobot/workspace/skills", + }, +} + +export function connect({ gateway, model }) { + if (!gateway?.v1 || !gateway?.key || !model?.id) throw new Error("Choose a Magpie model with an available gateway.") + const info = {} + if (Number.isSafeInteger(model.context) && model.context > 0) info.context = model.context + if (Number.isSafeInteger(model.output) && model.output > 0) info.output = model.context > 0 ? Math.min(model.output, model.context) : model.output + if (typeof model.images === "boolean") info.images = model.images + return { baseURL: gateway.v1, gatewayKey: gateway.key, modelInfo: info } +} diff --git a/packages/nanobot/nanobot.test.mjs b/packages/nanobot/nanobot.test.mjs new file mode 100644 index 0000000..e6f3970 --- /dev/null +++ b/packages/nanobot/nanobot.test.mjs @@ -0,0 +1,595 @@ +// Behaviour is judged from the outside: Magpie's control files in, the native +// nanobot configuration out. Every test gets its own temporary home, so the +// real ~/.nanobot and ~/.config/magpie-nanobot are never read or written. +import { afterEach, expect, test } from 'bun:test'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { spawnSync } from 'node:child_process'; +import { PROVIDER, inspect, pathsFor, reconcile } from './bridge.mjs'; +import { startRuntime } from './runtime.mjs'; +import { agent, connect as connectAgent } from './nanobot.agent.js'; + +const roots = []; +afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); + +function sandbox(baseline = {}, linkedParent) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'nanobot-bridge-')); + roots.push(root); + let home = root; + if (linkedParent) { + const target = path.join(root, 'real-parent'); + const link = path.join(root, linkedParent); + fs.mkdirSync(target); + fs.mkdirSync(path.dirname(link), { recursive: true }); + fs.symlinkSync(target, link, 'junction'); + if (linkedParent === 'home') home = link; + } + const paths = pathsFor({ home }); + fs.mkdirSync(path.dirname(paths.config), { recursive: true }); + fs.mkdirSync(paths.directory, { recursive: true }); + fs.writeFileSync(paths.config, `${JSON.stringify(baseline, null, 2)}\n`); + return { root, paths, baseline }; +} +const write = (file, value) => fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`); +const readJson = file => JSON.parse(fs.readFileSync(file, 'utf8')); +const control = (values = {}) => ({ model: 'deepseek/deepseek-flash', baseURL: 'https://gateway.example/v1', gatewayKey: 'test-key', ...values }); +function applyModel(paths, values = {}) { + write(paths.control, control(values)); + return reconcile(paths); +} + +test.each(['home', '.nanobot', '.config', '.config/magpie-nanobot'])('applies and restores through a symlinked %s directory', linkedParent => { + const { paths, baseline } = sandbox({ userSetting: 'keep' }, linkedParent); + write(paths.control, control()); + write(paths.mcp, { mcpServers: { probe: { type: 'http', url: 'http://127.0.0.1:7345/mcp' } } }); + const { handle, statuses } = runtimeFor(paths); + try { + handle.tick(); handle.tick(); + expect(statuses.at(-1).state).toBe('file-applied'); + expect(readJson(paths.config).modelPresets[PROVIDER].model).toBe('deepseek/deepseek-flash'); + expect(readJson(paths.config).tools.ssrfWhitelist).toEqual(['127.0.0.1/32']); + expect(inspect(paths).state).toBe('file-applied'); + expect(handle.stop({ restore: true }).state).toBe('disconnected'); + expect(readJson(paths.config)).toEqual(baseline); + expect(fs.existsSync(paths.state)).toBe(false); + expect(fs.existsSync(paths.pending)).toBe(false); + expect(fs.existsSync(paths.lock)).toBe(false); + expect(fs.existsSync(runtimeLock(paths))).toBe(false); + } finally { handle.stop(); } +}); + +test.each(['config', 'control', 'mcp', 'state', 'pending', 'lock', 'pause', 'status'])('still refuses a symlinked %s file under a symlinked parent', key => { + for (const dangling of [false, true]) { + const { root, paths } = sandbox({}, 'home'); + write(paths.control, control()); + const target = path.join(root, dangling ? 'missing-target.json' : 'target.json'); + if (!dangling) write(target, { untouched: true }); + // Use a new leaf so no fixture file needs to be removed or replaced. + paths[key] = path.join(path.dirname(paths[key]), `linked-${path.basename(paths[key])}`); + fs.symlinkSync(target, paths[key], 'file'); + expect(reconcile(paths)).toMatchObject({ state: 'conflict', code: 'symlink_refused' }); + expect(fs.lstatSync(paths[key]).isSymbolicLink()).toBe(true); + if (dangling) expect(fs.existsSync(target)).toBe(false); + else expect(readJson(target)).toEqual({ untouched: true }); + if (key !== 'config') expect(readJson(paths.config)).toEqual({}); + } +}); + +test.each(['control', 'mcp', 'state', 'pending', 'lock', 'pause', 'status', 'reclaim'])('rejects a config alias of the reserved %s file without changing it', key => { + const { root, paths } = sandbox({}, '.config'); + const reserved = key === 'reclaim' ? `${paths.lock}.reclaim` : paths[key]; + write(reserved, { untouched: true }); + const before = fs.readFileSync(reserved, 'utf8'); + paths.config = path.join(root, 'real-parent', 'magpie-nanobot', path.basename(reserved)); + expect(reconcile(paths)).toMatchObject({ state: 'conflict', code: 'reserved_config_path' }); + expect(fs.readFileSync(reserved, 'utf8')).toBe(before); +}); + +test('creates a missing state directory beneath a symlinked config directory', () => { + const { root } = sandbox({}, '.config'); + const paths = pathsFor({ home: root, stateDir: path.join(root, '.config', 'new-adapter', 'state') }); + expect(reconcile(paths).state).toBe('disconnected'); + expect(fs.statSync(paths.directory).isDirectory()).toBe(true); + expect(inspect(paths).state).toBe('disconnected'); + expect(applyModel(paths).state).toBe('file-applied'); + expect(reconcile(paths, { restore: true }).state).toBe('disconnected'); + expect(readJson(paths.config)).toEqual({}); +}); + +test('replays an interrupted transaction through a symlinked home', () => { + const { paths, baseline } = sandbox({}, 'home'); + write(paths.control, control()); + paths.__fault = point => { if (point === 'before-config') crash(point); }; + expect(() => reconcile(paths)).toThrow('injected at before-config'); + expect(inspect(paths).state).toBe('recovery-pending'); + expect(readJson(paths.config)).toEqual(baseline); + delete paths.__fault; + expect(reconcile(paths).state).toBe('file-applied'); + expect(fs.existsSync(paths.pending)).toBe(false); + expect(reconcile(paths, { restore: true }).state).toBe('disconnected'); + expect(readJson(paths.config)).toEqual(baseline); +}); + +// The invariant PiG 0.1.1 added a test for: the provider ID a descriptor writes +// must be the same one everything else derives from. Here one constant feeds +// the provider path, the preset's provider field, the selector value and every +// reference check; a drift between them would write a provider that restore +// cannot find again. +test('one provider name drives the path, the preset, the selector and the records', () => { + const { paths } = sandbox(); + const result = applyModel(paths); + expect(result.state).toBe('file-applied'); + const config = readJson(paths.config); + expect(Object.keys(config.providers)).toEqual([PROVIDER]); + expect(Object.keys(config.modelPresets)).toEqual([PROVIDER]); + expect(config.modelPresets[PROVIDER].provider).toBe(PROVIDER); + expect(config.agents.defaults.modelPreset).toBe(PROVIDER); + expect(readJson(paths.state).records.map(r => r.id).sort()).toEqual(['preset', 'provider', 'selector']); + expect(readJson(paths.state).configPath).toBe(path.resolve(paths.config)); +}); + +test('the row model reaches the preset nanobot starts a session from', () => { + const { paths } = sandbox(); + applyModel(paths, { modelInfo: { context: 1_048_576, output: 393_216 } }); + const preset = readJson(paths.config).modelPresets[PROVIDER]; + expect(preset.model).toBe('deepseek/deepseek-flash'); + expect(preset.provider).toBe(PROVIDER); + expect(preset.contextWindowTokens).toBe(1_048_576); + expect(preset.maxTokens).toBe(393_216); +}); + +test('a raw model id that already starts with the provider name is escaped once', () => { + const { paths } = sandbox(); + applyModel(paths, { model: `${PROVIDER}/deepseek/deepseek-flash` }); + // nanobot strips a leading provider prefix of its own; doubling keeps the + // gateway ID intact instead of collapsing it to deepseek/deepseek-flash. + expect(readJson(paths.config).modelPresets[PROVIDER].model).toBe(`${PROVIDER}/${PROVIDER}/deepseek/deepseek-flash`); +}); + +test('reported limits are clamped, and an unstated limit is left out entirely', () => { + const clamped = sandbox(); + applyModel(clamped.paths, { modelInfo: { context: 1000, output: 5000 } }); + const preset = readJson(clamped.paths.config).modelPresets[PROVIDER]; + expect(preset.maxTokens).toBe(1000); + expect(preset.contextWindowTokens).toBe(1000); + + // Omission, not zero: an older Magpie that sends no modelInfo leaves nanobot + // its own schema defaults (200000 context, 8192 output) rather than a + // preset that claims zero room. + const bare = sandbox(); + applyModel(bare.paths); + const plain = readJson(bare.paths.config).modelPresets[PROVIDER]; + expect(plain.contextWindowTokens).toBeUndefined(); + expect(plain.maxTokens).toBeUndefined(); +}); + +test('a hand-written entry with the managed name is refused, not taken over', () => { + const { paths } = sandbox({ providers: { [PROVIDER]: { apiBase: 'https://mine.example/v1', apiKey: 'mine' } } }); + const before = fs.readFileSync(paths.config, 'utf8'); + const result = applyModel(paths); + expect(result.state).toBe('conflict'); + expect(result.code).toBe('unowned_name_collision'); + expect(fs.readFileSync(paths.config, 'utf8')).toBe(before); +}); + +test('disconnecting the model returns the native config to the shape it started in', () => { + const { paths, baseline } = sandbox(); + applyModel(paths, { modelInfo: { context: 4096, output: 1024 } }); + expect(readJson(paths.config)).not.toEqual(baseline); + fs.rmSync(paths.control); + const result = reconcile(paths); + expect(result.state).toBe('disconnected'); + expect(readJson(paths.config)).toEqual(baseline); + expect(fs.existsSync(paths.state)).toBe(false); +}); + +test('an explicit restore pauses the same intent instead of reapplying it', () => { + const { paths, baseline } = sandbox(); + applyModel(paths); + const restored = reconcile(paths, { restore: true, pause: true }); + expect(restored.state).toBe('disconnected'); + expect(readJson(paths.config)).toEqual(baseline); + // Unchanged inputs stay paused: a live host must not reconnect what restore + // just took out. + expect(reconcile(paths).state).toBe('paused'); + expect(readJson(paths.config)).toEqual(baseline); + // A new choice permits coordination again. + expect(applyModel(paths, { model: 'codex/gpt-6.1-sol' }).state).toBe('file-applied'); + expect(readJson(paths.config).modelPresets[PROVIDER].model).toBe('codex/gpt-6.1-sol'); +}); + +test('a managed loopback MCP server adds only its exact address and takes it back', () => { + const { paths } = sandbox(); + write(paths.mcp, { mcpServers: { probe: { type: 'http', url: 'http://127.0.0.1:7345/mcp' } } }); + const applied = reconcile(paths); + expect(applied.servers).toEqual(['probe']); + // nanobot blocks loopback HTTP MCP unless the exact IP is exempt. + expect(readJson(paths.config).tools.ssrfWhitelist).toEqual(['127.0.0.1/32']); + expect(readJson(paths.state).addedWhitelist).toEqual(['127.0.0.1/32']); + expect(applied.networkNotice).toContain('globally'); + + write(paths.mcp, { mcpServers: {} }); + const removed = reconcile(paths); + expect(removed.servers).toEqual([]); + // The exemption existed only for that server, and the whole map it lived in + // was created by this bridge, so both go away with it. + expect(readJson(paths.config).tools).toBeUndefined(); + expect(fs.existsSync(paths.state)).toBe(false); +}); + +test('status never carries the gateway key or the URL', () => { + const { paths } = sandbox(); + applyModel(paths); + const seen = JSON.stringify([inspect(paths), readJson(paths.status)]); + expect(seen).toContain('deepseek/deepseek-flash'); + expect(seen).not.toContain('test-key'); + expect(seen).not.toContain('gateway.example'); +}); + +test('the descriptor declares the fields this adapter relies on, and no startup block', () => { expect(agent).toMatchObject({ + id: 'nanobot', bin: 'nanobot', dir: '~/.nanobot', + config: '~/.config/magpie-nanobot/connection.json', format: 'json', model: 'model', + }); + expect(agent.library).toEqual({ mcp: '~/.config/magpie-nanobot/mcp.json', mcpFormat: 'claude', skills: '~/.nanobot/workspace/skills' }); + // Deliberately absent: PiG 0.1.1 uses `startup` to have Magpie write its + // native settings.json. nanobot's startup state is a nested preset object + // that this bridge owns as one writer; a second writer would race it. + expect(agent.startup).toBeUndefined(); +}); + +test('the descriptor clamps its output limit to the context it reports', () => { + const out = connectAgent({ gateway: { v1: 'https://gw.example/v1', key: 'k' }, model: { id: 'deepseek/deepseek-flash', context: 1000, output: 5000, images: true } }); + expect(out).toEqual({ baseURL: 'https://gw.example/v1', gatewayKey: 'k', modelInfo: { context: 1000, output: 1000, images: true } }); + expect(() => connectAgent({ gateway: {}, model: { id: 'x' } })).toThrow(); +}); + +test('declares the standard community Agent entry and ships every module it loads', () => { + const dir = path.dirname(fileURLToPath(import.meta.url)); + const pkg = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), 'utf8')); + expect(pkg.name).toBe('@magpie-community/agent-nanobot'); + expect(pkg.type).toBe('module'); + expect(pkg.magpie.agent).toBe('./nanobot.agent.js'); + expect(pkg.magpie.icon).toBe(agent.icon); + expect(pkg.dependencies).toBeUndefined(); + expect(pkg.scripts?.preinstall).toBeUndefined(); + expect(pkg.scripts?.postinstall).toBeUndefined(); + // A runtime module is allowed for an agent (kimi-desktop and reasonix-desktop + // ship one). npm packs by files[], so every file listed must exist and every + // module the main loads must be listed, or the published package is broken. + expect(pkg.main).toBe('./index.mjs'); + const shipped = new Set(pkg.files); + expect([...shipped].every(file => fs.existsSync(path.join(dir, file)))).toBe(true); + expect(shipped.has('nanobot.agent.js')).toBe(true); + // The helper is a one-shot fallback, as reasonix-desktop's is: the bin it + // declares must therefore be in the published package too. + expect(pkg.bin).toEqual({ 'magpie-nanobot': './cli.mjs' }); + expect(shipped.has('cli.mjs')).toBe(true); + const loaded = new Set(); + for (const file of ['index.mjs', 'runtime.mjs', 'bridge.mjs', 'cli.mjs']) { + if (!shipped.has(file)) continue; + for (const match of fs.readFileSync(path.join(dir, file), 'utf8').matchAll(/from\s+["'](\.\/[^"']+)["']/g)) loaded.add(match[1].slice(2)); + } + expect([...loaded].sort()).toEqual(['bridge.mjs', 'runtime.mjs']); + expect([...loaded].every(file => shipped.has(file))).toBe(true); + // Tests are development artifacts and are not published. + expect(shipped.has('nanobot.test.mjs')).toBe(false); +}); + +// --------------------------------------------------------------------------- +// Recovery: a journal that outlives a crash, and a lock that outlives a host. +// The writer is expected to lose power; the contract is that the next pass can +// tell what was written without reading the half-done state and guessing. +// --------------------------------------------------------------------------- + +const crash = point => { throw Object.assign(new Error(`injected at ${point}`), { __bridgeFault: true }); }; + +function deadPid() { + // A pid the OS itself reports as gone. Probed rather than hard-coded, so the + // test does not depend on a magic number being dead on this machine. + for (let pid = 2_000_000_000; pid > 1_999_999_000; pid--) { + try { process.kill(pid, 0); } catch (error) { if (error.code === 'ESRCH') return pid; } + } + throw new Error('no dead pid available on this machine'); +} + +test('a transaction interrupted before the target write is replayed from its journal', () => { + const { paths, baseline } = sandbox(); + write(paths.control, control()); + paths.__fault = point => { if (point === 'before-config') crash(point); }; + expect(() => reconcile(paths)).toThrow('injected at before-config'); + // The journal is the durable record; the native file was never touched. + expect(fs.existsSync(paths.pending)).toBe(true); + expect(readJson(paths.config)).toEqual(baseline); + expect(inspect(paths).state).toBe('recovery-pending'); + delete paths.__fault; + expect(reconcile(paths).state).toBe('file-applied'); + expect(fs.existsSync(paths.pending)).toBe(false); + expect(readJson(paths.config).modelPresets[PROVIDER].model).toBe('deepseek/deepseek-flash'); +}); + +test('a replay after the target write completes the ownership record instead of rewriting it', () => { + const { paths } = sandbox(); + write(paths.control, control()); + paths.__fault = point => { if (point === 'after-config') crash(point); }; + expect(() => reconcile(paths)).toThrow('injected at after-config'); + // Config written, records not: without the replay nothing would own the keys. + expect(fs.existsSync(paths.pending)).toBe(true); + expect(fs.existsSync(paths.state)).toBe(false); + delete paths.__fault; + expect(reconcile(paths).state).toBe('file-applied'); + expect(fs.existsSync(paths.pending)).toBe(false); + expect(readJson(paths.state).records.map(r => r.id).sort()).toEqual(['preset', 'provider', 'selector']); +}); + +test('a journal whose target changed underneath is kept, not forced over it', () => { + const { paths } = sandbox(); + write(paths.control, control()); + paths.__fault = point => { if (point === 'before-config') crash(point); }; + expect(() => reconcile(paths)).toThrow(); + delete paths.__fault; + // Something else claimed the same managed name while the journal waited. + write(paths.config, { providers: { [PROVIDER]: { apiBase: 'https://someone-else.example/v1' } } }); + const result = reconcile(paths); + expect(result.state).toBe('conflict'); + expect(result.code).toBe('pending_patch_conflict'); + expect(result.recoveryPending).toBe(true); + expect(fs.existsSync(paths.pending)).toBe(true); + expect(readJson(paths.config).providers[PROVIDER].apiBase).toBe('https://someone-else.example/v1'); +}); + +test('a lock held by a live writer is refused and left in place', () => { + const { paths } = sandbox(); + write(paths.control, control()); + write(paths.lock, { pid: process.pid, token: 'other-owner' }); + const result = reconcile(paths); + expect(result.state).toBe('conflict'); + expect(result.code).toBe('writer_locked'); + // Someone is writing: the lock is theirs to drop, not ours to reclaim. + expect(readJson(paths.lock).token).toBe('other-owner'); + expect(readJson(paths.config)).toEqual({}); +}); + +test('a lock left by a dead writer is reclaimed without leaving a second lock', () => { + const { paths } = sandbox(); + write(paths.control, control()); + write(paths.lock, { pid: deadPid(), token: 'stale' }); + expect(reconcile(paths).state).toBe('file-applied'); + expect(fs.existsSync(paths.lock)).toBe(false); + expect(fs.existsSync(`${paths.lock}.reclaim`)).toBe(false); +}); + +test('a leftover reclaim guard fails closed rather than guessing', () => { + const { paths } = sandbox(); + write(paths.control, control()); + write(paths.lock, { pid: deadPid(), token: 'stale' }); + write(`${paths.lock}.reclaim`, { pid: 1, token: 'abandoned' }); + const result = reconcile(paths); + expect(result.state).toBe('conflict'); + expect(result.code).toBe('lock_reclaim_in_progress'); + // A reclaimer may be mid-flight: nothing is deleted while that is unknown. + expect(readJson(paths.lock).token).toBe('stale'); + expect(fs.existsSync(`${paths.lock}.reclaim`)).toBe(true); +}); + +const runtimeLock = paths => path.join(paths.directory, 'runtime.lock'); +function runtimeFor(paths) { + const statuses = []; + // No real timers: each test drives tick() itself, so nothing races. + const handle = startRuntime(paths, { interval: 100, schedule: () => ({}), cancel: () => {}, onStatus: status => statuses.push(status) }); + return { handle, statuses }; +} + +test('a second host stays standby and never restores the resident configuration', () => { + const { paths } = sandbox(); + applyModel(paths); + const applied = readJson(paths.config); + write(runtimeLock(paths), { pid: process.pid, nonce: 'resident-host' }); + const { handle, statuses } = runtimeFor(paths); + handle.tick(); + expect(statuses.at(-1)).toMatchObject({ state: 'standby', recoveryPending: false }); + expect(readJson(runtimeLock(paths)).nonce).toBe('resident-host'); + // A standby host owns nothing, so stopping it must not put anything back. + expect(handle.stop()).toBeUndefined(); + expect(readJson(paths.config)).toEqual(applied); +}); + +test('the owner applies only once the input holds still, then honors an explicit restore on stop', () => { + const { paths, baseline } = sandbox(); + write(paths.control, control()); + const { handle, statuses } = runtimeFor(paths); + handle.tick(); + // One full stable period is required: the first tick only records the input. + expect(statuses).toHaveLength(0); + expect(readJson(paths.config)).toEqual(baseline); + handle.tick(); + expect(statuses.at(-1).state).toBe('file-applied'); + expect(readJson(paths.config).modelPresets[PROVIDER].model).toBe('deepseek/deepseek-flash'); + expect(handle.stop({ restore: true }).state).toBe('disconnected'); + expect(readJson(paths.config)).toEqual(baseline); + expect(fs.existsSync(runtimeLock(paths))).toBe(false); +}); + +test('normal exit preserves model and MCP configuration and a new host resumes ownership', () => { + const { paths } = sandbox(); + write(paths.control, control()); + write(paths.mcp, { mcpServers: { + local: { type: 'stdio', command: 'test-mcp' }, + http: { type: 'http', url: 'http://127.0.0.1:7345/mcp' }, + } }); + const { handle } = runtimeFor(paths); + handle.tick(); handle.tick(); + const config = fs.readFileSync(paths.config, 'utf8'); + const state = fs.readFileSync(paths.state, 'utf8'); + expect(handle.stop().state).toBe('file-applied'); + expect(fs.readFileSync(paths.config, 'utf8')).toBe(config); + expect(fs.readFileSync(paths.state, 'utf8')).toBe(state); + expect(fs.existsSync(runtimeLock(paths))).toBe(false); + expect(fs.existsSync(paths.lock)).toBe(false); + expect(handle.stop()).toBeUndefined(); + const next = runtimeFor(paths); + try { + next.handle.tick(); next.handle.tick(); + expect(next.statuses.at(-1).state).toBe('file-applied'); + expect(fs.readFileSync(paths.config, 'utf8')).toBe(config); + expect(fs.readFileSync(paths.state, 'utf8')).toBe(state); + } finally { next.handle.stop(); } +}); + +test.each(['model', 'mcp', 'both'])('exit flushes a pending %s disconnect independently', disconnected => { + const { paths, baseline } = sandbox(); + write(paths.control, control()); + write(paths.mcp, { mcpServers: { local: { type: 'stdio', command: 'test-mcp' } } }); + const { handle } = runtimeFor(paths); + handle.tick(); handle.tick(); + // No tick after the user's change: shutdown must flush it itself. + if (disconnected !== 'mcp') write(paths.control, {}); + if (disconnected !== 'model') write(paths.mcp, { mcpServers: {} }); + expect(handle.stop().state).toBe(disconnected === 'both' ? 'disconnected' : 'file-applied'); + const config = readJson(paths.config); + expect(config.modelPresets?.[PROVIDER] !== undefined).toBe(disconnected === 'mcp'); + expect(config.tools?.mcpServers?.local !== undefined).toBe(disconnected === 'model'); + if (disconnected === 'both') { + expect(config).toEqual(baseline); + expect(fs.existsSync(paths.state)).toBe(false); + } + expect(fs.existsSync(runtimeLock(paths))).toBe(false); +}); + +test('exit keeps an explicit restore paused instead of reconnecting it', () => { + const { paths, baseline } = sandbox(); + write(paths.control, control()); + const { handle } = runtimeFor(paths); + handle.tick(); handle.tick(); + expect(reconcile(paths, { restore: true, pause: true }).state).toBe('disconnected'); + expect(handle.stop().state).toBe('paused'); + expect(readJson(paths.config)).toEqual(baseline); + expect(fs.existsSync(paths.pause)).toBe(true); + expect(fs.existsSync(runtimeLock(paths))).toBe(false); +}); + +test('exit with invalid control retains configuration and recovery records and releases its lock', () => { + const { paths } = sandbox(); + write(paths.control, control()); + const { handle } = runtimeFor(paths); + handle.tick(); handle.tick(); + const config = fs.readFileSync(paths.config, 'utf8'); + const state = fs.readFileSync(paths.state, 'utf8'); + fs.writeFileSync(paths.control, '{'); + expect(handle.stop()).toMatchObject({ state: 'conflict', code: 'invalid_json', recoveryPending: true }); + expect(fs.readFileSync(paths.config, 'utf8')).toBe(config); + expect(fs.readFileSync(paths.state, 'utf8')).toBe(state); + expect(fs.existsSync(runtimeLock(paths))).toBe(false); +}); + +test.each(['control', 'mcp', 'config'])('invalid %s still reports existing ownership as recovery pending', key => { + const { paths } = sandbox(); + expect(applyModel(paths).state).toBe('file-applied'); + fs.writeFileSync(paths[key], '{'); + const config = fs.readFileSync(paths.config, 'utf8'); + const state = fs.readFileSync(paths.state, 'utf8'); + expect(reconcile(paths)).toMatchObject({ state: 'conflict', code: 'invalid_json', recoveryPending: true }); + expect(inspect(paths)).toMatchObject({ state: 'conflict', code: 'invalid_json', recoveryPending: true }); + expect(fs.readFileSync(paths.config, 'utf8')).toBe(config); + expect(fs.readFileSync(paths.state, 'utf8')).toBe(state); +}); + +test.each(['missing', 'invalid', 'foreign', 'empty'])('%s ownership records do not invent recovery work or mask the input error', kind => { + const { paths } = sandbox(); + if (kind === 'invalid') fs.writeFileSync(paths.state, '{'); + if (kind === 'foreign' || kind === 'empty') { + applyModel(paths); + const state = readJson(paths.state); + if (kind === 'foreign') state.configPath = path.join(path.dirname(paths.config), 'other.json'); + else state.records = []; + write(paths.state, state); + } + fs.writeFileSync(paths.control, '{'); + const before = fs.existsSync(paths.state) ? fs.readFileSync(paths.state, 'utf8') : null; + expect(reconcile(paths)).toMatchObject({ state: 'conflict', code: 'invalid_json', recoveryPending: false }); + expect(fs.existsSync(paths.state) ? fs.readFileSync(paths.state, 'utf8') : null).toBe(before); +}); + +test.each(['connected', 'disconnect'])('the actual plugin exit hook flushes %s intent and releases locks', intent => { + const { root, paths, baseline } = sandbox(); + write(paths.control, control()); + write(paths.mcp, { mcpServers: { local: { type: 'stdio', command: 'test-mcp' } } }); + // Only the home-directory lookup is substituted. The child loads the real + // plugin entry and runtime, then exits naturally without calling stop(). + const source = ` + import { mock } from 'bun:test'; + import os from 'node:os'; + import fs from 'node:fs'; + import assert from 'node:assert/strict'; + const root = ${JSON.stringify(root)}; + const paths = ${JSON.stringify(paths)}; + mock.module('node:os', () => ({ ...os, homedir: () => root, default: { ...os, homedir: () => root } })); + const isolatedOS = await import('node:os'); + assert.equal(isolatedOS.homedir(), root); + assert.equal(isolatedOS.default.homedir(), root); + const { default: plugin } = await import(${JSON.stringify(new URL('./index.mjs', import.meta.url).href)}); + await plugin(); + const runtime = globalThis[Symbol.for('magpie.nanobot.adapter.v1')]; + runtime.tick(); runtime.tick(); + assert.equal(JSON.parse(fs.readFileSync(paths.status, 'utf8')).state, 'file-applied'); + if (${JSON.stringify(intent)} === 'disconnect') { + fs.writeFileSync(paths.control, '{}'); + fs.writeFileSync(paths.mcp, '{"mcpServers":{}}'); + } + `; + const child = spawnSync(process.execPath, ['--eval', source], { encoding: 'utf8', timeout: 10_000 }); + expect(child.error).toBeUndefined(); + expect(child.signal).toBeNull(); + expect(child.stderr).toBe(''); + expect(child.status).toBe(0); + expect(fs.existsSync(runtimeLock(paths))).toBe(false); + expect(fs.existsSync(paths.lock)).toBe(false); + if (intent === 'connected') { + expect(readJson(paths.config).modelPresets[PROVIDER].model).toBe('deepseek/deepseek-flash'); + expect(readJson(paths.config).tools.mcpServers.local.command).toBe('test-mcp'); + expect(readJson(paths.state).records).toHaveLength(4); + expect(inspect(paths).state).toBe('file-applied'); + } else { + expect(readJson(paths.config)).toEqual(baseline); + expect(fs.existsSync(paths.state)).toBe(false); + expect(inspect(paths).state).toBe('disconnected'); + } +}, 15_000); + +test('an owner whose runtime lock was replaced cannot flush on exit', () => { + const { paths } = sandbox(); + write(paths.control, control()); + const { handle } = runtimeFor(paths); + handle.tick(); handle.tick(); + const config = fs.readFileSync(paths.config, 'utf8'); + write(paths.control, {}); + write(runtimeLock(paths), { pid: process.pid, nonce: 'replacement-owner' }); + expect(handle.stop()).toBeUndefined(); + expect(fs.readFileSync(paths.config, 'utf8')).toBe(config); + expect(readJson(runtimeLock(paths)).nonce).toBe('replacement-owner'); +}); + +test('a changed input waits for its own full period before it is applied', () => { + const { paths } = sandbox(); + write(paths.control, control()); + const { handle } = runtimeFor(paths); + handle.tick(); handle.tick(); + write(paths.control, control({ model: 'codex/gpt-6.1-sol' })); + handle.tick(); + expect(readJson(paths.config).modelPresets[PROVIDER].model).toBe('deepseek/deepseek-flash'); + handle.tick(); + expect(readJson(paths.config).modelPresets[PROVIDER].model).toBe('codex/gpt-6.1-sol'); + handle.stop(); +}); + +test('a runtime lock left by a dead host is reclaimed', () => { + const { paths } = sandbox(); + write(paths.control, control()); + write(runtimeLock(paths), { pid: deadPid(), nonce: 'dead-host' }); + const { handle, statuses } = runtimeFor(paths); + handle.tick(); handle.tick(); + expect(statuses.at(-1).state).toBe('file-applied'); + expect(readJson(runtimeLock(paths)).nonce).not.toBe('dead-host'); + handle.stop(); +}); diff --git a/packages/nanobot/package.json b/packages/nanobot/package.json new file mode 100644 index 0000000..b9b8a46 --- /dev/null +++ b/packages/nanobot/package.json @@ -0,0 +1,19 @@ +{ + "name": "@magpie-community/agent-nanobot", + "version": "0.1.1", + "description": "nanobot (HKUDS/nanobot) as a magpie agent: pick one of magpie's models for it on the Agents page, with Library MCP servers and skills", + "type": "module", + "main": "./index.mjs", + "files": ["nanobot.agent.js", "index.mjs", "runtime.mjs", "bridge.mjs", "cli.mjs", "README.md"], + "bin": { "magpie-nanobot": "./cli.mjs" }, + "scripts": { "test": "bun test nanobot.test.mjs" }, + "engines": { "node": ">=20" }, + "keywords": ["magpie", "magpie-agent", "nanobot", "mcp"], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/nanobot" + }, + "magpie": { "name": "nanobot", "agent": "./nanobot.agent.js", "icon": "https://raw.githubusercontent.com/HKUDS/nanobot/main/webui/public/brand/nanobot_mark.svg" } +} diff --git a/packages/nanobot/runtime.mjs b/packages/nanobot/runtime.mjs new file mode 100644 index 0000000..ce99240 --- /dev/null +++ b/packages/nanobot/runtime.mjs @@ -0,0 +1,129 @@ +import fs from "node:fs" +import path from "node:path" +import { createHash, randomUUID } from "node:crypto" +import { pathsFor, reconcile, inspect } from "./bridge.mjs" + +function configFile(file) { + try { + const stat = fs.lstatSync(file) + if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) throw new Error("invalid-adapter-settings") + const value = JSON.parse(fs.readFileSync(file, "utf8")) + if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid-adapter-settings") + return value + } catch (error) { + if (error.code === "ENOENT") return {} + throw new Error("invalid-adapter-settings") + } +} + +export function resolvePaths(options = {}) { + const defaults = pathsFor() + const settings = { ...configFile(path.join(defaults.directory, "adapter.json")), ...options } + if (settings.configPath !== undefined && (typeof settings.configPath !== "string" || !path.isAbsolute(settings.configPath))) throw new Error("configPath-must-be-absolute") + return pathsFor({ configPath: settings.configPath }) +} + +function signature(p) { + const hash = createHash("sha256") + for (const file of [p.control, p.mcp]) { + try { + const stat = fs.lstatSync(file) + if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) throw new Error("invalid-control-file") + hash.update(fs.readFileSync(file)) + } catch (error) { + if (error.code !== "ENOENT") throw error + hash.update("") + } + hash.update("\0") + } + return hash.digest("hex") +} + +function claimRuntime(p) { + const file = path.join(p.directory, "runtime.lock") + fs.mkdirSync(p.directory, { recursive: true, mode: 0o700 }) + const owner = { pid: process.pid, nonce: randomUUID() } + const readOwner = () => { + const stat = fs.lstatSync(file) + if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024) throw new Error("invalid-runtime-lock") + const value = JSON.parse(fs.readFileSync(file, "utf8")) + if (!Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.nonce !== "string") throw new Error("invalid-runtime-lock") + return value + } + try { fs.writeFileSync(file, JSON.stringify(owner), { mode: 0o600, flag: "wx" }) } + catch (error) { + if (error.code !== "EEXIST") throw error + const previous = readOwner() + try { process.kill(previous.pid, 0); return null } + catch (probe) { if (probe.code !== "ESRCH") return null } + // Serialize stale reclamation separately. Re-reading a nonce alone is not + // a compare-and-delete: another reclaimer could create a live lock between + // the read and unlink. A leftover guard fails closed for manual inspection. + const guard = file + ".reclaim" + try { fs.writeFileSync(guard, owner.nonce, { mode: 0o600, flag: "wx" }) } + catch (guardError) { if (guardError.code === "EEXIST") return null; throw guardError } + try { + let current + try { current = readOwner() } catch (probe) { if (probe.code !== "ENOENT") throw probe } + if (current) { + try { process.kill(current.pid, 0); return null } + catch (probe) { if (probe.code !== "ESRCH") return null } + fs.unlinkSync(file) + } + try { fs.writeFileSync(file, JSON.stringify(owner), { mode: 0o600, flag: "wx" }) } + catch (retry) { if (retry.code === "EEXIST") return null; throw retry } + } finally { + if (fs.readFileSync(guard, "utf8") === owner.nonce) fs.unlinkSync(guard) + } + } + const release = () => { + try { if (readOwner().nonce === owner.nonce) fs.unlinkSync(file) } + catch (error) { if (error.code !== "ENOENT") throw error } + } + release.owns = () => { try { return readOwner().nonce === owner.nonce } catch { return false } } + return release +} + +// No backend request or nanobot process starts here. Each input must remain +// stable for one complete polling period before a target write is attempted. +export function startRuntime(p, { interval = 750, onStatus = () => {}, schedule = setInterval, cancel = clearInterval } = {}) { + if (!Number.isSafeInteger(interval) || interval < 100 || interval > 60000) throw new Error("invalid-poll-interval") + let previous = null, lastStatus = "", stopped = false, release = null + const report = (status) => { + const value = JSON.stringify(status) + if (value !== lastStatus) { lastStatus = value; onStatus(status) } + return status + } + const tick = () => { + if (stopped) return + try { + if (release && !release.owns()) release = null + if (!release) { + release = claimRuntime(p) + if (!release) return report({ state: "standby", recoveryPending: false, message: "Another Magpie host owns this adapter." }) + } + const current = signature(p) + if (current !== previous) { previous = current; return } + return report(reconcile(p)) + } catch { + return report({ state: "conflict", recoveryPending: true, message: "Adapter paused; inspect the control files and recovery status. Configuration contents are omitted." }) + } + } + const timer = schedule(tick, interval) + timer.unref?.() + return { + tick, + status: () => inspect(p), + stop({ restore = false } = {}) { + if (stopped) return + stopped = true + cancel(timer) + // Flush the current intent synchronously before releasing ownership. + // Host exit alone is not a disconnect, but a control-file disconnect + // may still be waiting for the next polling tick. A standby never writes. + if (!release) return + try { return release.owns() ? report(reconcile(p, { restore })) : undefined } + finally { release(); release = null } + }, + } +} diff --git a/registry.json b/registry.json index 480edd0..baa9155 100644 --- a/registry.json +++ b/registry.json @@ -112,6 +112,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 的工具结果在词边界处截断;正在发送的这一轮原样不动。" } }, { "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 的模型,关掉即恢复它原来的配置。" } }, + { "package": "@magpie-community/agent-nanobot", "name": "nanobot", "kind": "agent", "community": true, "icon": "https://raw.githubusercontent.com/HKUDS/nanobot/main/webui/public/brand/nanobot_mark.svg", + "summary": { "en": "nanobot (HKUDS/nanobot) on magpie's Agents page: pick one of magpie's models for it, give it Library MCP servers and skills, and switch it off to put its config back.", "zh": "把 nanobot(HKUDS/nanobot)加到 magpie 的 Agent 页:给它选 magpie 的模型、勾选资源库的 MCP 服务与技能,关掉即恢复它原来的配置。" } }, { "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,