Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(ssh): 让 Agent 能添加 SSH 主机并重新读取配置

Dash8e9a6026d290
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index 223908039b..08c786182b 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -612,6 +612,14 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
getPool: async () => (await loadRemoteSsh()).getRemoteSshPoolHydrated(),
ensureReady: async (id: string) =>
(await loadRemoteSsh()).ensureRemoteHostReady(id),
+ // 与设置页「添加」「重新读取」同一实现,Agent 与用户写的是同一份配置。
+ addHost: async (input) => {
+ await (await loadRemoteSsh()).addRemoteSshHost(input);
+ },
+ reloadConfig: async () => {
+ const result = await (await loadRemoteSsh()).reloadRemoteSshConfig();
+ return { diagnostic: result.diagnostic?.kind ?? null, warningCount: result.warningCount };
+ },
redactSensitiveText: (snapshot, text) => {
if (!redactSshText) throw new Error('SSH redactor is not initialized');
return redactSshText(snapshot, text);
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationContract.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationContract.test.ts
index 6085415550..a79fac58b9 100644
--- a/apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationContract.test.ts
+++ b/apps/desktop/src/main/remote-ssh/__tests__/remoteHostMutationContract.test.ts
@@ -13,6 +13,15 @@ function handlerBody(channel: string, nextChannel: string): string {
return source.slice(start, end);
}
+/** Settings ADD and the Agent's ssh_add_host share this implementation. */
+function addHostBody(): string {
+ const start = source.indexOf('export async function addRemoteSshHost(');
+ const end = source.indexOf('export async function reloadRemoteSshConfig(', start + 1);
+ expect(start).toBeGreaterThan(-1);
+ expect(end).toBeGreaterThan(start);
+ return source.slice(start, end);
+}
+
describe('remote SSH managed-host mutation contract', () => {
it('validates the app renderer before remote Codex discovery can start a daemon', () => {
const body = handlerBody('LIST_CODEX_MODELS', 'CHECK_CODEX_AUTH');
@@ -30,14 +39,21 @@ describe('remote SSH managed-host mutation contract', () => {
...[
body.indexOf('ensureHydrated()'),
body.indexOf('hydrateRemoteHosts()'),
+ body.indexOf('reloadRemoteSshConfig()'),
].filter((index) => index >= 0),
);
expect(guard).toBeGreaterThan(-1);
expect(guard).toBeLessThan(read);
});
+ it('ADD validates the app renderer before delegating to the shared add flow', () => {
+ const body = handlerBody('ADD', 'UPDATE');
+ const guard = body.indexOf('assertTrustedAppRendererEvent(event);');
+ expect(guard).toBeGreaterThan(-1);
+ expect(guard).toBeLessThan(body.indexOf('return addRemoteSshHost(rawHost);'));
+ });
+
it.each([
- ['ADD', 'UPDATE'],
['UPDATE', 'REMOVE'],
['REMOVE', 'CONNECT'],
])('%s validates the app renderer before parsing input', (channel, nextChannel) => {
@@ -54,8 +70,8 @@ describe('remote SSH managed-host mutation contract', () => {
});
it('serializes add, update, and remove with config reloads', () => {
+ expect(addHostBody()).toContain('return remoteHostHydrationQueue.run(async () => {');
for (const [channel, nextChannel] of [
- ['ADD', 'UPDATE'],
['UPDATE', 'REMOVE'],
['REMOVE', 'CONNECT'],
]) {
@@ -65,7 +81,7 @@ describe('remote SSH managed-host mutation contract', () => {
});
it('does not disconnect existing aliases when an add write or refresh fails', () => {
- const body = handlerBody('ADD', 'UPDATE');
+ const body = addHostBody();
const hostWrite = body.indexOf('await addManagedHostWithInclude(');
const hydrate = body.indexOf('await hydrateRemoteHostsUnqueued(new Set(), true, new Set([cfg.id]));');
const reloadError = body.indexOf("throwReloadRequired('新主机'");
@@ -88,7 +104,7 @@ describe('remote SSH managed-host mutation contract', () => {
expect(ownershipCheck).toBeGreaterThan(-1);
expect(ownershipCheck).toBeLessThan(poolPublish);
- const body = handlerBody('ADD', 'UPDATE');
+ const body = addHostBody();
const hydrate = body.indexOf('await hydrateRemoteHostsUnqueued(new Set(), true, new Set([cfg.id]));');
const rollback = body.indexOf('await addReceipt.rollback();');
const prefs = body.indexOf('patchSshHostPrefOrThrow(cfg.id');
diff --git a/apps/desktop/src/main/remote-ssh/index.ts b/apps/desktop/src/main/remote-ssh/index.ts
index 9f22d96b62..0d37d5a342 100644
--- a/apps/desktop/src/main/remote-ssh/index.ts
+++ b/apps/desktop/src/main/remote-ssh/index.ts
@@ -1119,6 +1119,118 @@ function patchSshHostPrefOrThrow(
}
}
+/**
+ * Add a Cindy-managed SSH host. Shared by Settings → 远程连接 and the Agent's
+ * `cindy_ssh` `ssh_add_host` tool so both write the same managed config and
+ * refresh the same pool.
+ */
+export async function addRemoteSshHost(rawHost: unknown): Promise<{ host: HostSnapshotWithPrefs }> {
+ const input = normalizeAddInput(rawHost);
+ await ensureHydrated();
+ return remoteHostHydrationQueue.run(async () => {
+ if (getPool().get(input.id)) {
+ throwIpcError('ALREADY_EXISTS', `host already exists: ${input.id}`);
+ }
+ const latest = await readLatestSshConfigOrThrow();
+ if (latest.hosts.some((host) => host.id === input.id)) {
+ throwIpcError('ALREADY_EXISTS', `host already exists: ${input.id}`);
+ }
+ const cfg: HostConfig = {
+ id: input.id,
+ hostname: input.hostname,
+ port: input.port ?? 22,
+ user: input.user,
+ authMethod: input.authMethod ?? 'agent',
+ identityFile: input.identityFile,
+ source: 'ssh-config',
+ managedByCindy: true,
+ };
+ let addReceipt: ManagedHostAddReceipt;
+ try {
+ addReceipt = await addManagedHostWithInclude(cfg, sshConfigPath, managedSshConfigPath);
+ } catch (err) {
+ log.warn('failed to write SSH config while adding host', { error: String(err) });
+ if ((err as { code?: string }).code === MANAGED_CONFIG_OWNERSHIP_REQUIRED_CODE) {
+ throwIpcError(
+ 'SSH_CONFIG_OWNERSHIP_REQUIRED',
+ 'The existing Cindy SSH config is not owned by Cindy; add the ownership marker or choose another file.',
+ );
+ }
+ throwIpcError('SSH_CONFIG_IO_FAILED', SSH_CONFIG_WRITE_FAILED_MESSAGE);
+ }
+ let refreshError: unknown;
+ try {
+ // ADD must not disconnect or repoint any existing alias. If an external
+ // editor changed one concurrently, keep the old pool and ask for an
+ // explicit reload. A collision on the newly-added alias is handled
+ // separately and conditionally rolls back Cindy's staged block.
+ await hydrateRemoteHostsUnqueued(new Set(), true, new Set([cfg.id]));
+ } catch (err) {
+ if (err instanceof SshHostOwnershipConflictError) {
+ let rolledBack = false;
+ let rollbackError: unknown;
+ try {
+ rolledBack = await addReceipt.rollback();
+ } catch (error) {
+ rollbackError = error;
+ }
+ log.warn('SSH host ownership changed while adding', {
+ hostId: cfg.id,
+ rolledBack,
+ ...(rollbackError !== undefined
+ ? {
+ rollbackError: rollbackError instanceof Error
+ ? rollbackError.message
+ : String(rollbackError),
+ }
+ : {}),
+ });
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'SSH configuration changed while adding the host; reload it and try again.',
+ );
+ }
+ refreshError = err;
+ }
+ // The managed host is already committed. Persist alias-local fields even
+ // when the in-memory refresh failed so the subsequent reload does not
+ // silently lose the form's display name or Agent Proxy choice.
+ patchSshHostPrefOrThrow(cfg.id, {
+ displayName: input.displayName,
+ ...(input.agentProxy !== undefined ? { agentProxy: input.agentProxy } : {}),
+ });
+ if (refreshError !== undefined) {
+ // ADD never disconnects existing aliases. The new host remains on disk
+ // and becomes visible after a successful explicit reload.
+ throwReloadRequired('新主机', refreshError);
+ }
+ const host = getPool().get(cfg.id);
+ if (!host) throwReloadRequired('新主机', new Error('host missing after refresh'));
+ log.info('audit: remote ssh host added', {
+ operation: 'remote_ssh_host_add',
+ hostId: cfg.id,
+ hostname: cfg.hostname,
+ user: cfg.user,
+ port: cfg.port,
+ authMethod: cfg.authMethod,
+ });
+ // Settings 与 Agent 添加共用这条推送:已打开的主机列表会就地插入新主机。
+ broadcastStatus(host.snapshot());
+ return { host: withPrefs(host.snapshot()) };
+ });
+}
+
+/** Re-read ~/.ssh/config into the pool, as Settings' reload button does. */
+export async function reloadRemoteSshConfig(): Promise<ReturnType<typeof currentRemoteSshListResult>> {
+ try {
+ await hydrateRemoteHosts();
+ } catch (err) {
+ log.warn('failed to reload SSH config', { error: String(err) });
+ }
+ for (const host of getPool().list()) broadcastStatus(host);
+ return currentRemoteSshListResult();
+}
+
export function registerRemoteSshIpc(): void {
if (registered) return;
registered = true;
@@ -1162,107 +1274,12 @@ export function registerRemoteSshIpc(): void {
ipcMain.handle(REMOTE_SSH_INVOKE.RELOAD_CONFIG, async (event) => {
assertTrustedAppRendererEvent(event);
- try {
- await hydrateRemoteHosts();
- } catch (err) {
- log.warn('failed to reload SSH config', { error: String(err) });
- }
- return currentRemoteSshListResult();
+ return reloadRemoteSshConfig();
});
ipcMain.handle(REMOTE_SSH_INVOKE.ADD, async (event, rawHost: unknown) => {
assertTrustedAppRendererEvent(event);
- const input = normalizeAddInput(rawHost);
- await ensureHydrated();
- return remoteHostHydrationQueue.run(async () => {
- if (getPool().get(input.id)) {
- throwIpcError('ALREADY_EXISTS', `host already exists: ${input.id}`);
- }
- const latest = await readLatestSshConfigOrThrow();
- if (latest.hosts.some((host) => host.id === input.id)) {
- throwIpcError('ALREADY_EXISTS', `host already exists: ${input.id}`);
- }
- const cfg: HostConfig = {
- id: input.id,
- hostname: input.hostname,
- port: input.port ?? 22,
- user: input.user,
- authMethod: input.authMethod ?? 'agent',
- identityFile: input.identityFile,
- source: 'ssh-config',
- managedByCindy: true,
- };
- let addReceipt: ManagedHostAddReceipt;
- try {
- addReceipt = await addManagedHostWithInclude(cfg, sshConfigPath, managedSshConfigPath);
- } catch (err) {
- log.warn('failed to write SSH config while adding host', { error: String(err) });
- if ((err as { code?: string }).code === MANAGED_CONFIG_OWNERSHIP_REQUIRED_CODE) {
- throwIpcError(
- 'SSH_CONFIG_OWNERSHIP_REQUIRED',
- 'The existing Cindy SSH config is not owned by Cindy; add the ownership marker or choose another file.',
- );
- }
- throwIpcError('SSH_CONFIG_IO_FAILED', SSH_CONFIG_WRITE_FAILED_MESSAGE);
- }
- let refreshError: unknown;
- try {
- // ADD must not disconnect or repoint any existing alias. If an external
- // editor changed one concurrently, keep the old pool and ask for an
- // explicit reload. A collision on the newly-added alias is handled
- // separately and conditionally rolls back Cindy's staged block.
- await hydrateRemoteHostsUnqueued(new Set(), true, new Set([cfg.id]));
- } catch (err) {
- if (err instanceof SshHostOwnershipConflictError) {
- let rolledBack = false;
- let rollbackError: unknown;
- try {
- rolledBack = await addReceipt.rollback();
- } catch (error) {
- rollbackError = error;
- }
- log.warn('SSH host ownership changed while adding', {
- hostId: cfg.id,
- rolledBack,
- ...(rollbackError !== undefined
- ? {
- rollbackError: rollbackError instanceof Error
- ? rollbackError.message
- : String(rollbackError),
- }
- : {}),
- });
- throwIpcError(
- 'PRECONDITION_FAILED',
- 'SSH configuration changed while adding the host; reload it and try again.',
- );
- }
- refreshError = err;
- }
- // The managed host is already committed. Persist alias-local fields even
- // when the in-memory refresh failed so the subsequent reload does not
- // silently lose the form's display name or Agent Proxy choice.
- patchSshHostPrefOrThrow(cfg.id, {
- displayName: input.displayName,
- ...(input.agentProxy !== undefined ? { agentProxy: input.agentProxy } : {}),
- });
- if (refreshError !== undefined) {
- // ADD never disconnects existing aliases. The new host remains on disk
- // and becomes visible after a successful explicit reload.
- throwReloadRequired('新主机', refreshError);
- }
- const host = getPool().get(cfg.id);
- if (!host) throwReloadRequired('新主机', new Error('host missing after refresh'));
- log.info('audit: remote ssh host added', {
- operation: 'remote_ssh_host_add',
- hostId: cfg.id,
- hostname: cfg.hostname,
- user: cfg.user,
- port: cfg.port,
- authMethod: cfg.authMethod,
- });
- return { host: withPrefs(host.snapshot()) };
- });
+ return addRemoteSshHost(rawHost);
});
ipcMain.handle(REMOTE_SSH_INVOKE.UPDATE, async (event, rawHost: unknown) => {
diff --git a/docs/product-rules/agent-user-parity.md b/docs/product-rules/agent-user-parity.md
index 1bf82a6284..6ebccf11bb 100644
--- a/docs/product-rules/agent-user-parity.md
+++ b/docs/product-rules/agent-user-parity.md
@@ -71,6 +71,8 @@
| 伙伴 | 夜间学习:暂停 / 恢复、立即运行(沿用伙伴自己的例行任务工具) | 有 | 无 |
| 伙伴 | 夜间学习:改频率、撤销 / 恢复整理改动、处理在观察的做法 | 无 | 无 |
| 社区插件贡献 | 当前安装快照准备、提交审核/当前进度、本人列表/详情/留存内容 | 有(2026-10-15) | 无 |
+| SSH 主机 | 列出、查状态、执行命令、添加主机、重新读取 ~/.ssh/config(与设置页同一实现;只用 ssh-agent/私钥,密码登录先用 `ssh-copy-id` 经终端代输入装公钥) | 有(添加与重读 2026-10-29) | 无 |
+| SSH 主机 | 编辑、删除、安装远端 Agent、Agent Proxy | 无 | 无 |
Worker 工具省略 working_dir 时保持继承 Lead 任务记录目录,不跟随之后 cd 进入的 worktree。
面板默认识别实际目录属于 UI 行为;Agent 通过显式 working_dir 共用已有 worktree,
diff --git a/packages/lizi-mcps/src/__tests__/cindy_sshMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/cindy_sshMcpServer.test.ts
index c811657527..9c6380e646 100644
--- a/packages/lizi-mcps/src/__tests__/cindy_sshMcpServer.test.ts
+++ b/packages/lizi-mcps/src/__tests__/cindy_sshMcpServer.test.ts
@@ -14,9 +14,11 @@ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
import { createSshMcpServer } from '../cindy_sshMcpServer.js';
import { SshToolRegistry } from '../ssh/registry.js';
import {
+ registerSshAddHostTool,
registerSshExecTool,
registerSshHostStatusTool,
registerSshListHostsTool,
+ registerSshReloadConfigTool,
} from '../ssh/index.js';
import { OUTPUT_CAP_CHARS } from '../ssh/_shared.js';
import type { SshHostSnapshotLike, SshMcpDeps, SshPoolLike } from '../types.js';
@@ -118,6 +120,8 @@ function makeDeps(
ensureReady: async (id) => {
ensureReadyCalls.push(id);
},
+ addHost: async () => {},
+ reloadConfig: async () => ({ diagnostic: null, warningCount: 0 }),
...overrides,
};
return { deps, ensureReadyCalls };
@@ -128,6 +132,8 @@ function makeRegistry(deps: SshMcpDeps): SshToolRegistry {
registerSshListHostsTool(registry, deps);
registerSshHostStatusTool(registry, deps);
registerSshExecTool(registry, deps);
+ registerSshAddHostTool(registry, deps);
+ registerSshReloadConfigTool(registry, deps);
return registry;
}
@@ -204,7 +210,7 @@ describe('ssh_list_hosts', () => {
expect(isError).toBe(false);
expect(payload.ok).toBe(true);
expect(payload.hosts).toEqual([]);
- expect(String(payload.hint)).toContain('远程连接');
+ expect(String(payload.hint)).toContain('ssh_add_host');
});
});
@@ -247,7 +253,7 @@ describe('host resolution', () => {
expect(isError).toBe(true);
expect(payload.errorCode).toBe('HOST_NOT_FOUND');
const data = payload.data as Record<string, unknown>;
- expect(String(data.hint)).toContain('远程连接');
+ expect(String(data.hint)).toContain('ssh_add_host');
const configured = data.configuredHosts as Array<Record<string, unknown>>;
expect(configured.map((h) => h.id)).toEqual(['web-1', 'web-2', 'web-2b']);
});
@@ -515,6 +521,85 @@ describe('ssh_exec', () => {
});
});
+// ── ssh_add_host / ssh_reload_config ────────────────────────────────────────
+
+describe('ssh_add_host', () => {
+ function makeAddDeps(overrides?: Partial<SshMcpDeps>) {
+ const hosts: SshHostSnapshotLike[] = [];
+ const { pool } = makeFakePool(hosts);
+ const added: unknown[] = [];
+ const { deps, ensureReadyCalls } = makeDeps(pool, {
+ addHost: async (input) => {
+ added.push(input);
+ hosts.push(snapshot({ id: input.id, hostname: input.hostname, status: 'disconnected' }));
+ },
+ ...overrides,
+ });
+ return { deps, added, ensureReadyCalls };
+ }
+
+ it('adds through the settings flow, then connects once', async () => {
+ const { deps, added, ensureReadyCalls } = makeAddDeps();
+ const { payload, isError } = await callParsed(makeRegistry(deps), 'ssh_add_host', {
+ alias: 'nas',
+ hostname: '192.168.68.51',
+ user: 'dash',
+ port: 2222,
+ });
+ expect(isError).toBe(false);
+ expect(added).toEqual([{ id: 'nas', hostname: '192.168.68.51', user: 'dash', port: 2222 }]);
+ expect(ensureReadyCalls).toEqual(['nas']);
+ expect(payload).toMatchObject({ added: true, connected: true, host: { id: 'nas' } });
+ });
+
+ it('keeps the host and reports auth failure with password-login guidance', async () => {
+ const { deps } = makeAddDeps({
+ ensureReady: async () => {
+ throw new Error('[SSH_AUTH_FAILED] SSH agent has no key the remote accepts.');
+ },
+ });
+ const { payload, isError } = await callParsed(makeRegistry(deps), 'ssh_add_host', {
+ alias: 'nas',
+ hostname: '192.168.68.51',
+ user: 'dash',
+ });
+ expect(isError).toBe(false);
+ expect(payload).toMatchObject({ added: true, connected: false });
+ const connectError = payload.connectError as { errorCode: string; hint: string };
+ expect(connectError.errorCode).toBe('SSH_AUTH_FAILED');
+ expect(connectError.hint).toContain('ssh-copy-id');
+ });
+
+ it('maps an existing alias to HOST_ALREADY_EXISTS without connecting', async () => {
+ const { deps, ensureReadyCalls } = makeAddDeps({
+ addHost: async () => {
+ throw new Error('[ALREADY_EXISTS] host already exists: nas');
+ },
+ });
+ const { payload, isError } = await callParsed(makeRegistry(deps), 'ssh_add_host', {
+ alias: 'nas',
+ hostname: '192.168.68.51',
+ user: 'dash',
+ });
+ expect(isError).toBe(true);
+ expect(payload.errorCode).toBe('HOST_ALREADY_EXISTS');
+ expect(ensureReadyCalls).toEqual([]);
+ });
+});
+
+describe('ssh_reload_config', () => {
+ it('returns the refreshed hosts and surfaces a config diagnostic', async () => {
+ const { pool } = makeFakePool([snapshot({ id: 'web-1' })]);
+ const { deps } = makeDeps(pool, {
+ reloadConfig: async () => ({ diagnostic: 'syntax', warningCount: 0 }),
+ });
+ const { payload, isError } = await callParsed(makeRegistry(deps), 'ssh_reload_config', {});
+ expect(isError).toBe(false);
+ expect((payload.hosts as Array<{ id: string }>).map((h) => h.id)).toEqual(['web-1']);
+ expect(payload.diagnostic).toBe('syntax');
+ });
+});
+
// ── registry-level 语义 ─────────────────────────────────────────────────────
describe('registry semantics', () => {
@@ -528,6 +613,8 @@ describe('registry semantics', () => {
'ssh_list_hosts',
'ssh_host_status',
'ssh_exec',
+ 'ssh_add_host',
+ 'ssh_reload_config',
]);
});
@@ -627,7 +714,7 @@ describe('cindy_ssh MCP server (in-process smoke)', () => {
(listResult.content as Array<{ type: string; text: string }>)[0].text,
) as { ok: boolean; categories: Array<{ name: string; tool_count: number }> };
expect(listPayload.ok).toBe(true);
- expect(listPayload.categories).toEqual([{ name: 'ssh', tool_count: 3 }]);
+ expect(listPayload.categories).toEqual([{ name: 'ssh', tool_count: 5 }]);
const callResult = await client.callTool({
name: 'call_tool',
diff --git a/packages/lizi-mcps/src/cindy_sshMcpServer.ts b/packages/lizi-mcps/src/cindy_sshMcpServer.ts
index 2455b41b15..beb2b3b42d 100644
--- a/packages/lizi-mcps/src/cindy_sshMcpServer.ts
+++ b/packages/lizi-mcps/src/cindy_sshMcpServer.ts
@@ -27,9 +27,11 @@ import { jsonObjectArg } from './json-object-arg.js';
import { SshToolRegistry } from './ssh/registry.js';
import { errorPayload } from './ssh/_shared.js';
import {
+ registerSshAddHostTool,
registerSshExecTool,
registerSshHostStatusTool,
registerSshListHostsTool,
+ registerSshReloadConfigTool,
} from './ssh/index.js';
import type { SshMcpDeps } from './types.js';
@@ -37,12 +39,16 @@ const D_LIST_TOOLS =
'探索 cindy_ssh 可用工具(渐进式发现入口)。不传 category → 返回所有类目+每个类目工具数量。' +
'传 category=ssh → 返回该类目下所有工具的名称和简介。' +
'用户要求 ssh 到某台机器执行命令 / 查看远端状态时,用本工具集(复用应用内已配置的 SSH 主机与认证),' +
- '不要用 Bash 手拼 ssh 命令行。获取工具名后用 call_tool({name, args}) 执行。';
+ '不要用 Bash 手拼 ssh 命令行。主机还没配置时也能在这里替用户添加到这台电脑的「设置 → 远程连接」。' +
+ '获取工具名后用 call_tool({name, args}) 执行。';
const D_CALL_TOOL =
'调用 cindy_ssh 中的某个具体工具。先用 list_tools 拿工具名 + 简介,再用本工具执行。' +
'错误码:' +
- '`HOST_NOT_FOUND` = 目标主机未配置(返回已配置清单,引导用户到「设置 → 远程连接」添加);' +
+ '`HOST_NOT_FOUND` = 目标主机未配置(返回已配置清单;需要时用 ssh_add_host 添加);' +
+ '`HOST_ALREADY_EXISTS` = 添加时别名已存在;' +
+ '`SSH_CONFIG_RELOAD_REQUIRED` = 配置已写入但未刷新,调用 ssh_reload_config;' +
+ '`SSH_CONFIG_WRITE_FAILED` = 写入 SSH 配置失败,把 hint 转告用户;' +
'`AMBIGUOUS_HOST` = hostname 命中多台,改用 alias;' +
'`SSH_AUTH_FAILED` = 认证失败(确定性错误,不要重试,把 hint 转告用户);' +
'`SSH_AGENT_UNAVAILABLE` = 本机 SSH Agent 不可用(启动 Agent / ssh-add 后再试);' +
@@ -137,6 +143,8 @@ export function createSshMcpServer(deps: SshMcpDeps): McpServer {
registerSshListHostsTool(registry, deps);
registerSshHostStatusTool(registry, deps);
registerSshExecTool(registry, deps);
+ registerSshAddHostTool(registry, deps);
+ registerSshReloadConfigTool(registry, deps);
registerListToolsEntry(server, registry);
registerCallToolEntry(server, registry);
diff --git a/packages/lizi-mcps/src/ssh/_shared.ts b/packages/lizi-mcps/src/ssh/_shared.ts
index 09d16e92e7..172a0e88ed 100644
--- a/packages/lizi-mcps/src/ssh/_shared.ts
+++ b/packages/lizi-mcps/src/ssh/_shared.ts
@@ -49,8 +49,21 @@ export type SshErrorCode =
| 'SSH_CONNECT_FAILED'
| 'EXEC_TIMEOUT'
| 'PLUGIN_DISABLED'
+ | 'HOST_ALREADY_EXISTS'
+ | 'INVALID_ARGS'
+ | 'SSH_CONFIG_RELOAD_REQUIRED'
+ | 'SSH_CONFIG_WRITE_FAILED'
| 'INTERNAL';
+/**
+ * 主机只能用密码登录时的标准做法。askpass 代输入:本机任务命令行里的 ssh 要口令时,
+ * Cindy 直接向用户弹卡片索取并交回 ssh,值不经过模型(docs/product-rules/input-handoff.md §5)。
+ */
+export const PASSWORD_LOGIN_HINT =
+ '主机目前只能用密码登录时,先在本机任务的命令行运行 `ssh-copy-id -i ~/.ssh/<公钥>.pub [-p 端口] 用户@主机` 装上公钥'
+ + '(没有密钥就先 ssh-keygen 生成):ssh 要密码时 Cindy 会直接弹卡片让用户输入,你看不到密码(macOS / Linux)。'
+ + '不要在聊天里向用户索要密码。';
+
// ── host resolution ─────────────────────────────────────────────────────────
/** ssh_list_hosts / HOST_NOT_FOUND 候选清单共用的精简视图。 */
@@ -122,7 +135,7 @@ export function resolveHost(
ok: false,
result: errorPayload(
'HOST_NOT_FOUND',
- `"${nameOrIp}" 不在已配置的 SSH 主机里。请告知用户到「设置 → 远程连接」添加该主机(或确认 ~/.ssh/config 里的 alias 拼写),不要退回手拼 ssh 命令。`,
+ `"${nameOrIp}" 不在已配置的 SSH 主机里。确认 alias 拼写;确实没配置时用 ssh_add_host 添加,不要退回手拼 ssh 命令。`,
{ configuredHosts: snapshots.map((snapshot) => hostBrief(snapshot, deps)) },
),
};
@@ -171,6 +184,13 @@ const EXEC_TIMEOUT_RE = / timed out after \d+ms$/;
/** desktop throwIpcError 的 `[CODE] message` 前缀编码。 */
const IPC_CODE_RE = /^\[([A-Z0-9_]+)\]\s*/;
+/** 拆出 desktop throwIpcError 的错误码与正文;无前缀时 code 为 undefined。 */
+export function splitIpcError(err: unknown): { code?: string; detail: string } {
+ const message = err instanceof Error ? err.message : String(err);
+ const match = IPC_CODE_RE.exec(message);
+ return match ? { code: match[1], detail: message.slice(match[0].length) } : { detail: message };
+}
+
export interface ClassifiedSshError {
errorCode: SshErrorCode;
hint: string;
@@ -198,9 +218,8 @@ export function classifySshError(
};
}
- const codeMatch = IPC_CODE_RE.exec(message);
- const detail = codeMatch ? message.slice(codeMatch[0].length) : message;
- switch (codeMatch?.[1]) {
+ const { code, detail } = splitIpcError(message);
+ switch (code) {
case 'SSH_HOST_NOT_FOUND':
return {
errorCode: 'HOST_NOT_FOUND',
@@ -209,7 +228,7 @@ export function classifySshError(
case 'SSH_AUTH_FAILED':
return {
errorCode: 'SSH_AUTH_FAILED',
- hint: `SSH 认证失败(确定性错误,重试无效,请把提示转告用户处理):${detail}`,
+ hint: `SSH 认证失败(确定性错误,重试无效):${detail}。${PASSWORD_LOGIN_HINT}`,
};
case 'SSH_KEY_FILE_NOT_FOUND':
return {
diff --git a/packages/lizi-mcps/src/ssh/add_host.ts b/packages/lizi-mcps/src/ssh/add_host.ts
new file mode 100644
index 0000000000..ad2d0640a3
--- /dev/null
+++ b/packages/lizi-mcps/src/ssh/add_host.ts
@@ -0,0 +1,105 @@
+/**
+ * ssh/add_host.ts — ssh_add_host tool
+ *
+ * 用户能在「设置 → 远程连接」添加主机,Agent 也能(agent-user-parity)。
+ * 写入流程、校验与连接池刷新全部复用 desktop 设置页的同一实现(deps.addHost),
+ * 这里只负责参数、错误分类,以及添加后试连一次让 Agent 知道认证是否可用。
+ */
+
+import { z } from 'zod';
+
+import type { SshMcpDeps } from '../types.js';
+import type { SshToolRegistry } from './registry.js';
+import {
+ PASSWORD_LOGIN_HINT,
+ classifySshError,
+ errorPayload,
+ hostBrief,
+ okPayload,
+ splitIpcError,
+} from './_shared.js';
+
+export function registerSshAddHostTool(
+ registry: SshToolRegistry,
+ deps: SshMcpDeps,
+): void {
+ registry.register({
+ name: 'ssh_add_host',
+ category: 'ssh',
+ description:
+ '把一台 SSH 主机添加到这台电脑的「设置 → 远程连接」(写入本机 ~/.ssh/cindy.conf,终端 `ssh <alias>` 同样可用),' +
+ '添加后自动试连一次并返回结果;之后 ssh_exec 和 SSH 远程任务都能使用它。' +
+ '认证只支持 ssh-agent(默认)或未加密的私钥文件,Cindy 不保存密码。' +
+ PASSWORD_LOGIN_HINT,
+ inputShape: {
+ alias: z.string().min(1).describe('主机别名(SSH Host 名),不能含空格或通配符,例如 "nas"'),
+ hostname: z.string().min(1).describe('IP 或域名'),
+ user: z.string().min(1).describe('登录用户名'),
+ port: z.number().int().min(1).max(65535).optional().describe('端口,默认 22'),
+ authMethod: z
+ .enum(['agent', 'key'])
+ .optional()
+ .describe('agent(默认):用本机 ssh-agent 里的密钥;key:直接读取 identityFile 指定的未加密私钥'),
+ identityFile: z
+ .string()
+ .min(1)
+ .optional()
+ .describe('私钥路径,支持 ~。authMethod=key 时必填;agent 时可选,用于只使用这把密钥'),
+ displayName: z.string().min(1).optional().describe('设置页显示的名称,默认同 alias'),
+ },
+ handler: async ({ alias, hostname, user, port, authMethod, identityFile, displayName }) => {
+ try {
+ await deps.addHost({
+ id: alias,
+ hostname,
+ user,
+ ...(port !== undefined ? { port } : {}),
+ ...(authMethod ? { authMethod } : {}),
+ ...(identityFile ? { identityFile } : {}),
+ ...(displayName ? { displayName } : {}),
+ });
+ } catch (err) {
+ const { code, detail } = splitIpcError(err);
+ deps.logger?.warn?.(`[cindy_ssh] ssh_add_host "${alias}" failed: ${code ?? 'UNKNOWN'}`);
+ switch (code) {
+ case 'ALREADY_EXISTS':
+ return errorPayload('HOST_ALREADY_EXISTS', `别名 "${alias}" 已存在。用 ssh_list_hosts 查看,或换一个别名。`);
+ case 'INVALID_PARAMS':
+ return errorPayload('INVALID_ARGS', `参数不合法:${detail}`);
+ case 'SSH_CONFIG_RELOAD_REQUIRED':
+ return errorPayload(
+ 'SSH_CONFIG_RELOAD_REQUIRED',
+ '主机已写入 SSH 配置,但 Cindy 刷新连接池失败。调用 ssh_reload_config 重新读取后再用。',
+ );
+ default:
+ return errorPayload('SSH_CONFIG_WRITE_FAILED', `添加主机失败:${detail}`);
+ }
+ }
+
+ let pool;
+ try {
+ pool = await deps.getPool();
+ } catch (err) {
+ return errorPayload('INTERNAL', `主机已添加,但读取连接池失败:${err instanceof Error ? err.message : String(err)}`);
+ }
+ const added = () => pool.list().find((s) => s.config.id === alias);
+ const before = added();
+ if (!before) {
+ return errorPayload('SSH_CONFIG_RELOAD_REQUIRED', '主机已写入 SSH 配置,但连接池里还没有它。调用 ssh_reload_config 后再试。');
+ }
+ try {
+ await deps.ensureReady(alias);
+ return okPayload({ added: true, connected: true, host: hostBrief(added() ?? before, deps) });
+ } catch (err) {
+ // 主机已保存(与设置页一致:连不上也保留),把试连结果交给 Agent 决定下一步。
+ const classified = classifySshError(err, deps, added() ?? before);
+ return okPayload({
+ added: true,
+ connected: false,
+ host: hostBrief(added() ?? before, deps),
+ connectError: { errorCode: classified.errorCode, hint: classified.hint },
+ });
+ }
+ },
+ });
+}
diff --git a/packages/lizi-mcps/src/ssh/index.ts b/packages/lizi-mcps/src/ssh/index.ts
index 5da6b55ade..198b710df9 100644
--- a/packages/lizi-mcps/src/ssh/index.ts
+++ b/packages/lizi-mcps/src/ssh/index.ts
@@ -8,6 +8,8 @@
export { registerSshListHostsTool } from './list_hosts.js';
export { registerSshHostStatusTool } from './host_status.js';
export { registerSshExecTool } from './exec.js';
+export { registerSshAddHostTool } from './add_host.js';
+export { registerSshReloadConfigTool } from './reload_config.js';
export { classifySshError, resolveHost, truncateOutput, wrapCwd } from './_shared.js';
export type { SshErrorCode } from './_shared.js';
diff --git a/packages/lizi-mcps/src/ssh/list_hosts.ts b/packages/lizi-mcps/src/ssh/list_hosts.ts
index 4a0089fb31..d427188b7a 100644
--- a/packages/lizi-mcps/src/ssh/list_hosts.ts
+++ b/packages/lizi-mcps/src/ssh/list_hosts.ts
@@ -29,7 +29,7 @@ export function registerSshListHostsTool(
...(hosts.length === 0
? {
hint:
- '当前没有配置任何 SSH 主机。请告知用户到「设置 → 远程连接」添加主机(支持 ~/.ssh/config 已有 alias 自动导入)。',
+ '当前没有配置任何 SSH 主机。用 ssh_add_host 添加;用户已在 ~/.ssh/config 写过的主机用 ssh_reload_config 导入。',
}
: {}),
});
diff --git a/packages/lizi-mcps/src/ssh/reload_config.ts b/packages/lizi-mcps/src/ssh/reload_config.ts
new file mode 100644
index 0000000000..163d1b0fa5
--- /dev/null
+++ b/packages/lizi-mcps/src/ssh/reload_config.ts
@@ -0,0 +1,43 @@
+/**
+ * ssh/reload_config.ts — ssh_reload_config tool
+ *
+ * 等同设置页「重新读取 ~/.ssh/config」。Agent 手动编辑 SSH 配置后用它让
+ * Cindy 立即看到改动,不用请用户去设置里点刷新。
+ */
+
+import type { SshMcpDeps } from '../types.js';
+import type { SshToolRegistry } from './registry.js';
+import { errorPayload, hostBrief, okPayload } from './_shared.js';
+
+export function registerSshReloadConfigTool(
+ registry: SshToolRegistry,
+ deps: SshMcpDeps,
+): void {
+ registry.register({
+ name: 'ssh_reload_config',
+ category: 'ssh',
+ description:
+ '重新读取这台电脑的 ~/.ssh/config(含 Include),刷新 Cindy 的 SSH 主机列表,等同设置页的刷新按钮。' +
+ '手动编辑过 SSH 配置后调用;返回刷新后的主机列表。',
+ inputShape: {},
+ handler: async () => {
+ try {
+ const { diagnostic, warningCount } = await deps.reloadConfig();
+ const pool = await deps.getPool();
+ return okPayload({
+ hosts: pool.list().map((snapshot) => hostBrief(snapshot, deps)),
+ ...(warningCount > 0 ? { warningCount } : {}),
+ ...(diagnostic
+ ? {
+ diagnostic,
+ hint: 'SSH 配置读取失败,主机列表仍是上次成功读取的结果。请检查 ~/.ssh/config 的语法、权限和 Include 路径。',
+ }
+ : {}),
+ });
+ } catch (err) {
+ deps.logger?.error?.(`[cindy_ssh] ssh_reload_config failed: ${String(err)}`);
+ return errorPayload('INTERNAL', `重新读取 SSH 配置失败:${err instanceof Error ? err.message : String(err)}`);
+ }
+ },
+ });
+}
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index facbc7baa4..6ebbe09a61 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -492,9 +492,24 @@ export interface SshPoolLike {
* - 插件启用策略由 host 在 Agent runtime / Codex thread 创建时冻结;这里不得
* 注入调用时读取设置的门控,否则工具暴露状态与执行权限会在运行中分叉。
*/
+/** 与「设置 → 远程连接」添加表单同一份字段。 */
+export interface SshAddHostInput {
+ id: string;
+ hostname: string;
+ port?: number;
+ user: string;
+ authMethod?: 'agent' | 'key';
+ identityFile?: string;
+ displayName?: string;
+}
+
export interface SshMcpDeps {
getPool(): Promise<SshPoolLike>;
ensureReady(id: string): Promise<void>;
+ /** 设置页同一添加流程:写入本机 SSH 配置并刷新连接池;失败以 `[CODE] message` 抛出。 */
+ addHost(input: SshAddHostInput): Promise<void>;
+ /** 设置页「重新读取 ~/.ssh/config」。读取失败时返回诊断类别,连接池保持上次成功的结果。 */
+ reloadConfig(): Promise<{ diagnostic: string | null; warningCount: number }>;
/** Host-owned synchronous boundary redactor. It must not retain its inputs. */
redactSensitiveText(snapshot: SshHostSnapshotLike, text: string): string;
logger?: LiziMcpLogger;