mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-16 12:01:13 +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>
242 lines
8.2 KiB
TypeScript
242 lines
8.2 KiB
TypeScript
import { startTransition, useCallback, useEffect, useRef, useState } from 'react';
|
|
import type { DiscoveredAgent, ExternalAgentConfig } from '../../infrastructure/ai/types';
|
|
import { getExternalAgentSdkBackend } from '../../infrastructure/ai/managedAgents';
|
|
|
|
interface NetcattyBridge {
|
|
aiDiscoverAgents(options?: { refreshShellEnv?: boolean; apiKeyPresent?: boolean }): Promise<DiscoveredAgent[]>;
|
|
}
|
|
|
|
function getBridge(): NetcattyBridge | undefined {
|
|
return (window as unknown as { netcatty?: NetcattyBridge }).netcatty;
|
|
}
|
|
|
|
const AGENT_DISCOVERY_CACHE_TTL_MS = 60_000;
|
|
let agentDiscoveryCache: {
|
|
agents: DiscoveredAgent[];
|
|
apiKeyPresent: boolean;
|
|
updatedAt: number;
|
|
} | null = null;
|
|
const agentDiscoveryPromises = new Map<string, Promise<DiscoveredAgent[]>>();
|
|
let agentDiscoveryWriteGeneration = 0;
|
|
|
|
export function useAgentDiscovery(
|
|
externalAgents: ExternalAgentConfig[],
|
|
setExternalAgents?: (value: ExternalAgentConfig[] | ((prev: ExternalAgentConfig[]) => ExternalAgentConfig[])) => void,
|
|
options?: {
|
|
enabled?: boolean;
|
|
schedule?: (task: () => void) => () => void;
|
|
},
|
|
) {
|
|
const enabled = options?.enabled ?? true;
|
|
const schedule = options?.schedule;
|
|
const [discoveredAgents, setDiscoveredAgents] = useState<DiscoveredAgent[]>(
|
|
() => agentDiscoveryCache?.agents ?? [],
|
|
);
|
|
const [isDiscovering, setIsDiscovering] = useState(false);
|
|
const discoverSeqRef = useRef(0);
|
|
const mountedRef = useRef(true);
|
|
const enabledRef = useRef(enabled);
|
|
|
|
enabledRef.current = enabled;
|
|
|
|
useEffect(() => () => {
|
|
mountedRef.current = false;
|
|
discoverSeqRef.current += 1;
|
|
}, []);
|
|
|
|
const cursorApiKeyPresent = externalAgents.some(
|
|
(agent) => agent.id === "discovered_cursor" && Boolean(agent.apiKey),
|
|
);
|
|
|
|
const discover = useCallback(async (discoverOptions?: { refreshShellEnv?: boolean }) => {
|
|
if (!enabledRef.current) return;
|
|
const bridge = getBridge();
|
|
if (!bridge) return;
|
|
|
|
const forceRefresh = discoverOptions?.refreshShellEnv === true;
|
|
const cacheFresh =
|
|
agentDiscoveryCache
|
|
&& agentDiscoveryCache.apiKeyPresent === cursorApiKeyPresent
|
|
&& Date.now() - agentDiscoveryCache.updatedAt < AGENT_DISCOVERY_CACHE_TTL_MS;
|
|
|
|
if (!forceRefresh && cacheFresh) {
|
|
startTransition(() => setDiscoveredAgents(agentDiscoveryCache?.agents ?? []));
|
|
return;
|
|
}
|
|
|
|
setIsDiscovering(true);
|
|
const discoverSeq = ++discoverSeqRef.current;
|
|
const writeGeneration = ++agentDiscoveryWriteGeneration;
|
|
const promiseKey = JSON.stringify({
|
|
apiKeyPresent: cursorApiKeyPresent,
|
|
refreshShellEnv: forceRefresh,
|
|
});
|
|
try {
|
|
let discoveryPromise = agentDiscoveryPromises.get(promiseKey) ?? null;
|
|
if (!discoveryPromise) {
|
|
const sharedPromise = bridge.aiDiscoverAgents({
|
|
...discoverOptions,
|
|
apiKeyPresent: cursorApiKeyPresent,
|
|
}).finally(() => {
|
|
if (agentDiscoveryPromises.get(promiseKey) === sharedPromise) {
|
|
agentDiscoveryPromises.delete(promiseKey);
|
|
}
|
|
});
|
|
agentDiscoveryPromises.set(promiseKey, sharedPromise);
|
|
discoveryPromise = sharedPromise;
|
|
}
|
|
const agents = await discoveryPromise;
|
|
if (
|
|
!mountedRef.current
|
|
|| !enabledRef.current
|
|
|| discoverSeq !== discoverSeqRef.current
|
|
|| writeGeneration !== agentDiscoveryWriteGeneration
|
|
) return;
|
|
agentDiscoveryCache = {
|
|
agents,
|
|
apiKeyPresent: cursorApiKeyPresent,
|
|
updatedAt: Date.now(),
|
|
};
|
|
startTransition(() => setDiscoveredAgents(agents));
|
|
} catch (err) {
|
|
console.error('Agent discovery failed:', err);
|
|
} finally {
|
|
if (mountedRef.current && discoverSeq === discoverSeqRef.current) {
|
|
setIsDiscovering(false);
|
|
}
|
|
}
|
|
}, [cursorApiKeyPresent]);
|
|
|
|
useEffect(() => {
|
|
discoverSeqRef.current += 1;
|
|
if (!enabled) {
|
|
setIsDiscovering(false);
|
|
}
|
|
}, [cursorApiKeyPresent, enabled]);
|
|
|
|
useEffect(() => {
|
|
if (!enabled) return;
|
|
|
|
let cancelled = false;
|
|
const runDiscover = () => {
|
|
if (!cancelled) void discover();
|
|
};
|
|
|
|
if (schedule) {
|
|
const cancel = schedule(runDiscover);
|
|
return () => {
|
|
cancelled = true;
|
|
cancel();
|
|
};
|
|
}
|
|
|
|
if (typeof requestIdleCallback === 'function') {
|
|
const idleId = requestIdleCallback(runDiscover);
|
|
return () => {
|
|
cancelled = true;
|
|
cancelIdleCallback(idleId);
|
|
};
|
|
}
|
|
|
|
const timeoutId = setTimeout(runDiscover, 0);
|
|
return () => {
|
|
cancelled = true;
|
|
clearTimeout(timeoutId);
|
|
};
|
|
}, [discover, enabled, schedule]);
|
|
|
|
// Auto-update args for already-configured discovered agents when
|
|
// the canonical args from discovery change (e.g. after an app update).
|
|
useEffect(() => {
|
|
if (!setExternalAgents || discoveredAgents.length === 0) return;
|
|
if (!enabled) return;
|
|
|
|
setExternalAgents((prev) => {
|
|
let changed = false;
|
|
const next = prev.map((ea) => {
|
|
// Only update agents that were auto-discovered (id starts with "discovered_")
|
|
if (!ea.id.startsWith('discovered_')) return ea;
|
|
|
|
const match = discoveredAgents.find(
|
|
(da) => ea.command === da.path || ea.command === da.command,
|
|
);
|
|
if (!match) return ea;
|
|
|
|
// Check if args, SDK backend, or managed SDK path env differ.
|
|
const currentArgs = JSON.stringify(ea.args || []);
|
|
const newArgs = JSON.stringify(match.args);
|
|
const backend = match.sdkBackend ?? match.command;
|
|
const backendChanged = getExternalAgentSdkBackend(ea) !== backend
|
|
|| Boolean(ea.acpCommand)
|
|
|| JSON.stringify(ea.acpArgs || []) !== JSON.stringify([]);
|
|
const matchPath = match.binPath || match.path;
|
|
const env = match.command === 'claude'
|
|
? { ...(ea.env ?? {}), CLAUDE_CODE_EXECUTABLE: matchPath }
|
|
: match.command === 'opencode'
|
|
? { ...(ea.env ?? {}), OPENCODE_BIN: matchPath }
|
|
: match.command === 'mimo'
|
|
? { ...(ea.env ?? {}), MIMOCODE_BIN: matchPath }
|
|
: ea.env;
|
|
const envChanged =
|
|
(match.command === 'claude' && ea.env?.CLAUDE_CODE_EXECUTABLE !== matchPath)
|
|
|| (match.command === 'opencode' && ea.env?.OPENCODE_BIN !== matchPath)
|
|
|| (match.command === 'mimo' && ea.env?.MIMOCODE_BIN !== matchPath);
|
|
const versionChanged = Boolean(match.version) && ea.cliVersion !== match.version;
|
|
if (currentArgs !== newArgs || backendChanged || envChanged || versionChanged) {
|
|
changed = true;
|
|
const { acpCommand: _legacyCommand, acpArgs: _legacyArgs, ...rest } = ea;
|
|
return {
|
|
...rest,
|
|
args: match.args,
|
|
sdkBackend: backend,
|
|
...(match.version ? { cliVersion: match.version } : {}),
|
|
...(env ? { env } : {}),
|
|
};
|
|
}
|
|
return ea;
|
|
});
|
|
return changed ? next : prev;
|
|
});
|
|
}, [discoveredAgents, enabled, setExternalAgents]);
|
|
|
|
// Filter out agents that are already configured as external agents
|
|
const unconfiguredAgents = discoveredAgents.filter(
|
|
(da) => !externalAgents.some(
|
|
(ea) => ea.command === da.command || ea.command === da.path,
|
|
),
|
|
);
|
|
|
|
// Build ExternalAgentConfig from a discovered agent
|
|
const enableAgent = useCallback(
|
|
(agent: DiscoveredAgent): ExternalAgentConfig => {
|
|
const backend = agent.sdkBackend ?? agent.command;
|
|
return {
|
|
id: `discovered_${agent.command}`,
|
|
name: agent.name,
|
|
command: agent.binPath || agent.path || agent.command,
|
|
args: agent.args,
|
|
icon: agent.icon,
|
|
enabled: true,
|
|
sdkBackend: backend,
|
|
...(agent.version ? { cliVersion: agent.version } : {}),
|
|
...(agent.command === 'claude'
|
|
? { env: { CLAUDE_CODE_EXECUTABLE: agent.binPath || agent.path || '' } }
|
|
: agent.command === 'opencode'
|
|
? { env: { OPENCODE_BIN: agent.binPath || agent.path || '' } }
|
|
: agent.command === 'mimo'
|
|
? { env: { MIMOCODE_BIN: agent.binPath || agent.path || '' } }
|
|
: {}),
|
|
};
|
|
},
|
|
[],
|
|
);
|
|
|
|
return {
|
|
discoveredAgents,
|
|
unconfiguredAgents,
|
|
isDiscovering,
|
|
rediscover: () => discover({ refreshShellEnv: true }),
|
|
enableAgent,
|
|
};
|
|
}
|