mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-24 00:50:44 +00:00
* feat(ai): add MiMo Code (mimo) agent support scaffolding
Registry/wiring only: discovery entry, managed-agent metadata, model presets, icon, i18n and Settings UI for Xiaomi's MiMo Code CLI (an OpenCode fork). The SDK driver is intentionally not wired yet - it depends on the pending @mimo-ai/sdk parity probe, so DRIVER_REGISTRY keeps a TODO and run-turn/list-models reject the mimo backend until then.
* feat(ai): add MiMo Code (mimo) agent support
Adds Xiaomi's MiMo Code CLI as a managed agent backend, mirroring the existing
OpenCode integration (discovery, managed-agent metadata, model presets, icon,
i18n, Settings UI) and adding the SDK driver that was left as a TODO in the
scaffolding commit.
Driver notes:
- New electron/bridges/aiBridge/sdk/mimoDriver.cjs reuses the pure translation
helpers exported by opencodeDriver.cjs (config/prompt building, event
translation, model mapping) because MiMo Code is an OpenCode fork and speaks
the same wire protocol.
- It does NOT use @mimo-ai/sdk's createOpencode(). On 0.1.15 that helper spawns
a binary named "opencode", waits for an "opencode server listening" banner,
and passes config via OPENCODE_CONFIG_CONTENT; the mimo CLI prints
"mimocode server listening on <url>", reads MIMOCODE_CONFIG_CONTENT, and ships
as "mimo"/"mimo.exe". So createOpencode() can only ever time out. The driver
runs "mimo serve" itself, parses the readiness URL, and attaches the SDK's
createOpencodeClient({ baseUrl }).
- Binary resolution honours binPath, MIMOCODE_BIN and MIMOCODE_BIN_PATH, then
falls back to PATH via resolveCliFromPath (the npm shim is mimo.cmd on
Windows, which Node cannot spawn directly).
- @mimo-ai/sdk ^0.1.15 added as a dependency.
Verified on Windows against mimo 0.1.15 + @mimo-ai/sdk 0.1.15:
- "mimo serve --port" boots and reports its URL; driver parses it.
- SDK symbols used all exist: createOpencodeClient, client.config.providers(),
client.global.event() (SSE stream), client.session.create/abort/promptAsync.
- Live provider catalog reads 2 providers (xiaomi, mimo); MIMO_MODEL_PRESETS
updated to the real lower-case provider-prefixed ids and its TODO removed.
- Server process is killed on close (taskkill tree kill), no orphan processes.
Not yet verified at runtime:
- A full end-to-end turn (no prompt was sent, so no tokens were spent): text /
reasoning / tool-part streaming and abort handling are untested against a
live model.
- MIMOCODE_CONFIG_CONTENT accepting the OpenCode config schema (permission,
mcp, model, share, autoupdate) end-to-end; only that the env var exists in
the binary has been confirmed.
- Whether the loopback server needs MIMOCODE_SERVER_PASSWORD when the API
client attaches.
- The placeholder public/ai/agents/mimo.svg still needs an official asset.
- Multi-turn resume (resumeSessionId) and MCP injection against the live CLI.
* feat(ai): inject MIMOCODE_BIN for discovered MiMo Code agents
Mirror the OpenCode OPENCODE_BIN handling so a discovered or re-detected
mimo binary path reaches the driver, and cover it with the same assertion
shape as the opencode managed-agent env test.
* fix(ai): use MiMo branding in the mimo driver
* test(ai): cover the mimo driver
Add a unit test file for the MiMo Code driver, matching the existing
opencode driver test in shape, runner (node:test via node --test) and
`.test.cjs` extension. It is the last driver in the registry without
one.
Coverage:
- spawn/launch: `mimo serve --hostname/--port` argv, binary resolution
(explicit binPath / MIMOCODE_BIN / MIMOCODE_BIN_PATH), pass-through
env and MIMOCODE_CONFIG_CONTENT; `child_process.spawn` is stubbed, so
no real `mimo` process is ever started.
- readiness: parsing of `mimocode server listening on <url>` from
stdout (including split chunks) and stderr, the OpenCode spelling,
and the MIMO_SERVE_TIMEOUT_MS timeout path (asserts the rejection and
that the child is killed).
- abort/cleanup: stopMimoProcess kill/idempotency/swallow, the Windows
taskkill tree kill, server.close() teardown, and abort mid-turn with
a throwing close().
- branding: OpenCode -> MiMo Code for the busy/idle/status, failed and
tool-failure fallback strings, with tool output and non-brand
technical errors left verbatim.
- happy path: session create -> streamed event translation -> done,
plus listMimoModels catalog mapping and the empty/aborted paths.
* fix(ai): filter MiMo events by session and stop the server behind the npm shim
Address review on #3500:
- The global SSE stream carries every session on the server, and
runMimoTurn translated all of them, so another session's text could leak
into the reply and its session.idle could end the turn early. Skip events
whose session id is not ours, reusing the OpenCode driver's
getOpenCodeSessionIdFromEvent (now exported). Covered by a test with
interleaved sessions.
- On macOS/Linux the official @mimo-ai/cli `mimo` is a Node shim that runs
the native binary through spawnSync, so killing the shim left the server
listening. `mimo serve` is now spawned detached on POSIX and
stopMimoProcess signals its whole process group (SIGTERM, then SIGKILL
after a grace period). Windows keeps taskkill /T.
Verified against the real @mimo-ai/cli@0.1.15 npm shim: on Linux (WSL
Ubuntu 22.04) the listener is the native .mimocode child; before this change
it was still listening 3s after close(), now the port is released within 1s
and no mimo process remains. On Windows the .cmd shim path also releases the
port within 1s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix: harden MiMo CLI integration before merge
* fix: wait for MiMo events and handle setup cancellation
* fix: finish MiMo stream handling and scope skill access
* fix: preflight MiMo skill paths before one server startup
* fix: scope MiMo skill reads to trusted roots
* fix: allow MiMo skills from ancestor project roots
* fix: honor MiMo observer and confirm command permissions
* fix: clear MiMo approval when its service exits
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
327 lines
13 KiB
JavaScript
327 lines
13 KiB
JavaScript
"use strict";
|
|
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
|
|
function normalizeOpenCodePath(targetPath, platform = process.platform) {
|
|
return platform === "win32"
|
|
? targetPath.replace(/\\/g, "/")
|
|
: targetPath;
|
|
}
|
|
|
|
function appendOpenCodePathPattern(baseDir, suffix) {
|
|
const trimmedSuffix = suffix.replace(/^\//, "");
|
|
return baseDir.endsWith("/")
|
|
? `${baseDir}${trimmedSuffix}`
|
|
: `${baseDir}/${trimmedSuffix}`;
|
|
}
|
|
|
|
function toOpenCodeDirectoryBase(dirPath, options = {}) {
|
|
if (!dirPath || typeof dirPath !== "string") return null;
|
|
const pathModule = options.pathModule || path;
|
|
const platform = options.platform || process.platform;
|
|
try {
|
|
const resolved = pathModule.resolve(dirPath);
|
|
let baseDir = resolved;
|
|
if (fs.existsSync(resolved) && fs.statSync(resolved).isFile()) {
|
|
baseDir = pathModule.dirname(resolved);
|
|
}
|
|
return normalizeOpenCodePath(baseDir, platform);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function toOpenCodeDirectoryGlob(dirPath, options = {}) {
|
|
const baseDir = toOpenCodeDirectoryBase(dirPath, options);
|
|
return baseDir ? appendOpenCodePathPattern(baseDir, "**") : null;
|
|
}
|
|
|
|
function toOpenCodeDirectoryPermissionPatterns(dirPath, options = {}) {
|
|
const baseDir = toOpenCodeDirectoryBase(dirPath, options);
|
|
return baseDir
|
|
? [
|
|
baseDir,
|
|
appendOpenCodePathPattern(baseDir, "*"),
|
|
appendOpenCodePathPattern(baseDir, "**"),
|
|
]
|
|
: [];
|
|
}
|
|
|
|
function toOpenCodeFileParentGlob(filePath, options = {}) {
|
|
if (!filePath || typeof filePath !== "string") return null;
|
|
const pathModule = options.pathModule || path;
|
|
try {
|
|
return toOpenCodeDirectoryGlob(pathModule.dirname(pathModule.resolve(filePath)), options);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function toOpenCodeFileParentPermissionPatterns(filePath, options = {}) {
|
|
if (!filePath || typeof filePath !== "string") return [];
|
|
const pathModule = options.pathModule || path;
|
|
try {
|
|
return toOpenCodeDirectoryPermissionPatterns(pathModule.dirname(pathModule.resolve(filePath)), options);
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function dedupePatterns(patterns) {
|
|
return [...new Set(patterns.filter(Boolean))];
|
|
}
|
|
|
|
// OpenCode discovers native agent skills from these well-known directories:
|
|
// its global config dirs (~/.opencode and ~/.config/opencode, both "skill"
|
|
// and "skills" spellings), Claude/agents-compatible dirs, project-level
|
|
// .opencode/.claude/.agents dirs, and the remote-skill download cache.
|
|
// Reads inside them must stay allowed even though Netcatty otherwise locks
|
|
// external directory access down, or loading a skill's reference files fails
|
|
// with an OpenCode permission error (issue #1939).
|
|
const OPENCODE_NATIVE_SKILL_DIR_SUFFIXES = [
|
|
".opencode/skill",
|
|
".opencode/skills",
|
|
".config/opencode/skill",
|
|
".config/opencode/skills",
|
|
".claude/skills",
|
|
".agents/skills",
|
|
".cache/opencode/skills",
|
|
];
|
|
const MIMO_NATIVE_SKILL_DIR_SUFFIXES = [
|
|
".mimocode/skill",
|
|
".mimocode/skills",
|
|
".config/mimocode/skill",
|
|
".config/mimocode/skills",
|
|
".cache/mimocode/skills",
|
|
".local/share/mimocode/builtin_skills",
|
|
".local/share/mimocode/compose",
|
|
];
|
|
|
|
function getNativeSkillSuffixes({ mimo = false, env = {} } = {}) {
|
|
if (!mimo) return OPENCODE_NATIVE_SKILL_DIR_SUFFIXES;
|
|
const enabled = (key) => {
|
|
const value = env[key]?.toLowerCase();
|
|
return value === "true" || value === "1";
|
|
};
|
|
const suffixes = [...MIMO_NATIVE_SKILL_DIR_SUFFIXES];
|
|
if (!enabled("MIMOCODE_DISABLE_AGENTS_SKILLS")) suffixes.push(".agents/skills");
|
|
if (enabled("MIMOCODE_ENABLE_CLAUDE_CODE_SKILLS")) suffixes.push(".claude/skills");
|
|
if (enabled("MIMOCODE_ENABLE_CODEX_SKILLS")) suffixes.push(".codex/skills");
|
|
if (enabled("MIMOCODE_ENABLE_OPENCODE_SKILLS")) {
|
|
suffixes.push(...OPENCODE_NATIVE_SKILL_DIR_SUFFIXES.filter((suffix) => suffix.includes("opencode") && !suffix.includes(".cache/")));
|
|
}
|
|
return suffixes;
|
|
}
|
|
|
|
function resolveMimoConfiguredSkillPath(item, { cwd, env = {}, pathModule = path } = {}) {
|
|
if (typeof item !== "string" || !item.trim()) return null;
|
|
const home = [env.HOME, env.USERPROFILE].find((value) => typeof value === "string" && pathModule.isAbsolute(value));
|
|
const expanded = item.startsWith("~/") && home ? pathModule.join(home, item.slice(2)) : item;
|
|
if (expanded.startsWith("~/")) return null;
|
|
return pathModule.isAbsolute(expanded) ? pathModule.resolve(expanded) : pathModule.resolve(cwd || process.cwd(), expanded);
|
|
}
|
|
|
|
function filterMimoTrustedSkillPaths(skillPaths, { cwd, env = {}, globalSkillPaths = [], pathModule = path } = {}) {
|
|
if (!Array.isArray(skillPaths)) return [];
|
|
const resolve = (item) => resolveMimoConfiguredSkillPath(item, { cwd, env, pathModule });
|
|
const globalRoots = new Set((Array.isArray(globalSkillPaths) ? globalSkillPaths : []).map(resolve).filter(Boolean));
|
|
let realCwd;
|
|
try { realCwd = fs.realpathSync(cwd || process.cwd()); } catch {}
|
|
return skillPaths.flatMap((item) => {
|
|
const resolved = resolve(item);
|
|
if (!resolved) return [];
|
|
try {
|
|
const canonical = fs.realpathSync(resolved);
|
|
if (globalRoots.has(resolved)) return [canonical];
|
|
if (!realCwd) return [];
|
|
const relative = pathModule.relative(realCwd, canonical);
|
|
return relative === "" || (relative !== ".." && !relative.startsWith(`..${pathModule.sep}`) && !pathModule.isAbsolute(relative))
|
|
? [canonical]
|
|
: [];
|
|
} catch {
|
|
return [];
|
|
}
|
|
});
|
|
}
|
|
|
|
function getMimoNativeSkillDirectories({ mimo = false, env = {}, pathModule = path, platform = process.platform, cwd, skillPaths = [] } = {}) {
|
|
if (!mimo) return [];
|
|
const absolute = (value) => typeof value === "string" && pathModule.isAbsolute(value) ? value : null;
|
|
const mimoHome = absolute(env.MIMOCODE_HOME);
|
|
const configDir = absolute(env.MIMOCODE_CONFIG_DIR);
|
|
const xdgConfig = absolute(env.XDG_CONFIG_HOME);
|
|
const xdgData = absolute(env.XDG_DATA_HOME);
|
|
const xdgCache = absolute(env.XDG_CACHE_HOME);
|
|
const macData = platform === "darwin" && absolute(env.HOME)
|
|
? pathModule.join(env.HOME, "Library", "Application Support", "mimocode")
|
|
: null;
|
|
const winData = platform === "win32" && absolute(env.LOCALAPPDATA)
|
|
? pathModule.join(env.LOCALAPPDATA, "mimocode")
|
|
: null;
|
|
const custom = (Array.isArray(skillPaths) ? skillPaths : [])
|
|
.map((item) => resolveMimoConfiguredSkillPath(item, { cwd, env, pathModule }))
|
|
.filter(Boolean);
|
|
const home = absolute(env.HOME) || absolute(env.USERPROFILE);
|
|
const nativeSuffixes = getNativeSkillSuffixes({ mimo: true, env });
|
|
const canonical = (base) => {
|
|
try { return fs.realpathSync(base); } catch { return null; }
|
|
};
|
|
const projectSuffixes = nativeSuffixes.filter((suffix) =>
|
|
!suffix.startsWith(".config/") && !suffix.startsWith(".cache/") && !suffix.startsWith(".local/"));
|
|
const projectBases = new Set();
|
|
for (const base of [cwd, cwd && canonical(cwd)]) {
|
|
if (typeof base !== "string" || !pathModule.isAbsolute(base)) continue;
|
|
for (let current = pathModule.resolve(base); !projectBases.has(current); current = pathModule.dirname(current)) {
|
|
projectBases.add(current);
|
|
}
|
|
}
|
|
const scopedDirs = [
|
|
...[...projectBases].flatMap((base) => projectSuffixes.map((suffix) => pathModule.join(base, suffix))),
|
|
...[home, home && canonical(home)]
|
|
.filter((base) => typeof base === "string" && pathModule.isAbsolute(base))
|
|
.flatMap((base) => nativeSuffixes.map((suffix) => pathModule.join(base, suffix))),
|
|
];
|
|
return [
|
|
...scopedDirs,
|
|
...(mimoHome ? [
|
|
pathModule.join(mimoHome, "config", "skill"),
|
|
pathModule.join(mimoHome, "config", "skills"),
|
|
pathModule.join(mimoHome, "data", "builtin_skills"),
|
|
pathModule.join(mimoHome, "data", "compose"),
|
|
pathModule.join(mimoHome, "cache", "skills"),
|
|
] : []),
|
|
...(configDir ? [pathModule.join(configDir, "skill"), pathModule.join(configDir, "skills")] : []),
|
|
...(xdgConfig ? [pathModule.join(xdgConfig, "mimocode", "skill"), pathModule.join(xdgConfig, "mimocode", "skills")] : []),
|
|
...(xdgData ? [pathModule.join(xdgData, "mimocode", "builtin_skills"), pathModule.join(xdgData, "mimocode", "compose")] : []),
|
|
...(xdgCache ? [pathModule.join(xdgCache, "mimocode", "skills")] : []),
|
|
...(macData ? [pathModule.join(macData, "builtin_skills"), pathModule.join(macData, "compose")] : []),
|
|
...(winData ? [pathModule.join(winData, "builtin_skills"), pathModule.join(winData, "compose")] : []),
|
|
...custom,
|
|
];
|
|
}
|
|
|
|
function getMimoRelativeSkillDirectory(dir, options = {}) {
|
|
const pathModule = options.pathModule || path;
|
|
const base = toOpenCodeDirectoryBase(dir, options);
|
|
if (!base) return null;
|
|
const cwd = options.cwd || process.cwd();
|
|
const relative = pathModule.relative(pathModule.resolve(cwd), pathModule.resolve(dir));
|
|
return normalizeOpenCodePath(relative || ".", options.platform || process.platform);
|
|
}
|
|
|
|
// OpenCode's `read` permission checks match worktree-relative paths (e.g.
|
|
// "../../.opencode/skills/foo/references/doc.md") while `external_directory`
|
|
// checks match absolute directory globs ("C:/Users/me/.opencode/skills/foo/*").
|
|
// OpenCode's suffix rules predate MiMo. MiMo uses concrete project and user
|
|
// roots below, so an unrelated folder named .mimocode/skills is not trusted.
|
|
function buildOpenCodeNativeSkillPermissionPatterns(options = {}) {
|
|
return (options.mimo ? [] : getNativeSkillSuffixes(options)).flatMap((suffix) => [
|
|
`*${suffix}`,
|
|
`*${suffix}/*`,
|
|
`*${suffix}/**`,
|
|
]).concat(getMimoNativeSkillDirectories(options).flatMap((dir) => toOpenCodeDirectoryPermissionPatterns(dir, options)));
|
|
}
|
|
|
|
// OpenCode's default rules gate `.env` secret files behind approval. The
|
|
// broad skill-directory read allows above would win over those defaults
|
|
// (last matching rule wins), so re-deny dot-env files inside skill dirs
|
|
// after the allow entries to keep secret-file protection intact.
|
|
function buildOpenCodeNativeSkillEnvDenyPatterns(options = {}) {
|
|
const suffixRules = (options.mimo ? [] : getNativeSkillSuffixes(options)).flatMap((suffix) => [
|
|
`*${suffix}/**.env`,
|
|
`*${suffix}/**.env.*`,
|
|
]);
|
|
const directoryRules = getMimoNativeSkillDirectories(options).flatMap((dir) => {
|
|
const base = toOpenCodeDirectoryBase(dir, options);
|
|
const relative = getMimoRelativeSkillDirectory(dir, options);
|
|
return base && relative
|
|
? [`${base}/**.env`, `${base}/**.env.*`, `${relative}/**.env`, `${relative}/**.env.*`]
|
|
: [];
|
|
});
|
|
return suffixRules.concat(directoryRules);
|
|
}
|
|
|
|
// Base rules shared by every tool-integration mode so OpenCode's native
|
|
// skills keep working: allow loading skills and reading their files while
|
|
// still denying all other external directory access.
|
|
function buildOpenCodeNativeSkillsPermissionRules(options = {}) {
|
|
const external_directory = { "*": "deny" };
|
|
const read = {};
|
|
for (const pattern of buildOpenCodeNativeSkillPermissionPatterns(options)) {
|
|
external_directory[pattern] = "allow";
|
|
read[pattern] = "allow";
|
|
}
|
|
for (const dir of getMimoNativeSkillDirectories(options)) {
|
|
const relative = getMimoRelativeSkillDirectory(dir, options);
|
|
if (!relative) continue;
|
|
for (const pattern of [relative, `${relative}/*`, `${relative}/**`]) {
|
|
read[pattern] = "allow";
|
|
}
|
|
}
|
|
for (const pattern of buildOpenCodeNativeSkillEnvDenyPatterns(options)) {
|
|
read[pattern] = "deny";
|
|
}
|
|
return {
|
|
skill: "allow",
|
|
read,
|
|
external_directory,
|
|
};
|
|
}
|
|
|
|
function buildNetcattySkillsOpenCodePathAllowlist({
|
|
launcherPath,
|
|
cliScriptPath,
|
|
skillPath,
|
|
discoveryFilePath,
|
|
cliStateDir,
|
|
runtimeBinaryPath,
|
|
tempDir,
|
|
extraFilePaths,
|
|
} = {}, options = {}) {
|
|
const filePaths = [
|
|
launcherPath,
|
|
cliScriptPath,
|
|
skillPath,
|
|
discoveryFilePath,
|
|
runtimeBinaryPath,
|
|
...(Array.isArray(extraFilePaths) ? extraFilePaths : []),
|
|
];
|
|
return dedupePatterns([
|
|
...filePaths.flatMap((filePath) => toOpenCodeFileParentPermissionPatterns(filePath, options)),
|
|
...(cliStateDir ? toOpenCodeDirectoryPermissionPatterns(cliStateDir, options) : []),
|
|
...(tempDir ? toOpenCodeDirectoryPermissionPatterns(tempDir, options) : []),
|
|
]);
|
|
}
|
|
|
|
function buildOpenCodeSkillsPermissionRules(pathAllowlist = [], nativeSkillOptions = {}) {
|
|
const { read, external_directory } = buildOpenCodeNativeSkillsPermissionRules(nativeSkillOptions);
|
|
for (const pattern of pathAllowlist) {
|
|
external_directory[pattern] = "allow";
|
|
read[pattern] = "allow";
|
|
}
|
|
|
|
return {
|
|
bash: "allow",
|
|
read,
|
|
list: "deny",
|
|
glob: "deny",
|
|
grep: "deny",
|
|
skill: "allow",
|
|
external_directory,
|
|
};
|
|
}
|
|
|
|
module.exports = {
|
|
buildNetcattySkillsOpenCodePathAllowlist,
|
|
buildOpenCodeNativeSkillEnvDenyPatterns,
|
|
buildOpenCodeNativeSkillPermissionPatterns,
|
|
buildOpenCodeNativeSkillsPermissionRules,
|
|
buildOpenCodeSkillsPermissionRules,
|
|
filterMimoTrustedSkillPaths,
|
|
toOpenCodeDirectoryPermissionPatterns,
|
|
toOpenCodeDirectoryGlob,
|
|
toOpenCodeFileParentPermissionPatterns,
|
|
toOpenCodeFileParentGlob,
|
|
};
|