Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(maker-remote-ssh): RemoteHost 支持 remote port forwarding (ssh -R)
yan2de4c4c7b147
diff --git a/packages/maker-remote-ssh/src/RemoteHost.ts b/packages/maker-remote-ssh/src/RemoteHost.tsindex abed758396..ef0528154e 100644--- a/packages/maker-remote-ssh/src/RemoteHost.ts+++ b/packages/maker-remote-ssh/src/RemoteHost.ts@@ -16,7 +16,8 @@*/import { EventEmitter } from 'node:events';-import { Client, type ConnectConfig, type ClientChannel } from 'ssh2';+import net from 'node:net';+import { Client, type ConnectConfig, type ClientChannel, type TcpConnectionDetails } from 'ssh2';import type { HostConfig, HostSnapshot, RemoteStatus } from './types.js';import { resolveAuth } from './credentials.js';@@ -85,6 +86,59 @@ export interface ExecStreamOpts {env?: Record<string, string>;}+// ── Remote TCP forwarding (OpenSSH `ssh -R` 等价物) ─────────────────────────+//+// 用途: 让远端进程 (codex daemon / claude CLI) 把 HTTPS_PROXY 指向远端+// 127.0.0.1 上的一个端口, 该端口的连接经**同一条 SSH 连接**的多路复用通道+// 转回本机, 再 pipe 到用户自己的本地 Proxy (如 127.0.0.1:7890)。Cindy 不提供+// Proxy, 只提供这条隧道。+//+// 为什么复用同一条 ssh2 Client 而不起第二条连接: SSH 协议按 channel id 解+// 复用, forwardIn 的 tcp-forward channel 与 exec channel 在同一条连接上互+// 不干扰 —— 消息不会"打乱"。多路复用是 SSH 的原生能力。+//+// 端口策略: 用**固定首选端口**而不是 port 0, 这样断线重连后隧道口不变,+// 远端 daemon env (HTTPS_PROXY=http://127.0.0.1:<port>) 不用跟着重写。+// 首选端口被占用时向后探测少量候选; 真换端口时通过 onRearmed 通知上层+// (上层在下次 session start 时重写远端 env marker 并重启 daemon, 自愈)。++/** 首选远端绑定端口基数; 被占用时向后探测 PORT_SCAN_SPAN 个候选。 */+export const DEFAULT_REMOTE_FORWARD_PORT_BASE = 17893;+const REMOTE_FORWARD_PORT_SCAN_SPAN = 8;++export interface RemoteForwardSpec {+ /** 本机 (运行 Cindy 的机器) 转发目标 — 用户本地 Proxy 的监听地址。 */+ localHost: string;+ localPort: number;+ /** 远端 127.0.0.1 首选绑定端口; 缺省 DEFAULT_REMOTE_FORWARD_PORT_BASE。 */+ preferredRemotePort?: number;+ /** 断线重连后端口被重绑到不同值时回调一次 (首次绑定不回调)。 */+ onRearmed?: (remotePort: number) => void;+}++export interface RemoteForward {+ /** 当前实际绑定的远端端口 (重连后可能变化)。 */+ readonly remotePort: number;+ /** 停止转发并释放登记。幂等。 */+ close(): Promise<void>;+}++interface ForwardRecord {+ spec: RemoteForwardSpec;+ remotePort: number;+ /** forwardIn 已在当前 live client 上注册成功。 */+ armed: boolean;+ /** 进行中的 arm, 去重 ensureRemoteForward 与 rearmForwards 的并发竞争。 */+ arming?: Promise<void>;+ /** 本地 Proxy 连接失败的节流日志状态。 */+ lastLocalErrorAt: number;+ localErrorCount: number;+}++function forwardKey(spec: Pick<RemoteForwardSpec, 'localHost' | 'localPort'>): string {+ return `${spec.localHost}:${spec.localPort}`;+}+export interface ExecStreamHandle {write(data: string | Buffer): void;end(data?: string | Buffer): void;@@ -226,6 +280,13 @@ export class RemoteHost {* Reset at the start of every connect attempt.*/private hostKeyError: string | null = null;+ /**+ * 已登记的 remote forwarding 愿望清单 (key = localHost:localPort)。+ * 连接断开不清空 — 重连成功后 doConnect 会逐个 re-arm, 尽量绑回原端口。+ */+ private forwards = new Map<string, ForwardRecord>();+ /** 'tcp connection' 是按 client 实例挂的, 每次 doConnect 新建 client 都要重挂。 */+ private forwardListenerClient: Client | null = null;constructor(config: HostConfig, deps: RemoteHostDeps) {this.id = config.id;@@ -305,6 +366,7 @@ export class RemoteHost {async disconnect(): Promise<void> {this.userDisconnected = true;this.clearReconnectTimer();+ this.markForwardsDisarmed();if (this.client) {try {this.client.end();@@ -434,6 +496,250 @@ export class RemoteHost {});}+ // ── remote TCP forwarding (ssh -R) ────────────────────────────────────────++ /**+ * 登记并 (若已连接) 立即建立一条 remote forwarding: 远端 127.0.0.1:<port>+ * 进来的 TCP 连接经本 SSH 连接转回, pipe 到本机 spec.localHost:localPort。+ *+ * 幂等: 同 (localHost, localPort) 重复调用返回同一条 forward。+ * 未连接时只登记愿望, 下次 connect 成功后自动 arm (doConnect → rearmForwards)。+ *+ * 安全约束: 远端只绑 127.0.0.1 — 隧道口仅远端本机进程可达, 不对远端所在+ * 网络暴露 (即不要 GatewayPorts 语义)。本地目标由调用方 (用户 pref) 显式+ * 指定, 通常是 127.0.0.1 上的 Proxy 端口。+ */+ async ensureRemoteForward(spec: RemoteForwardSpec): Promise<RemoteForward> {+ if (!spec.localHost || /\s/.test(spec.localHost)) {+ throw new Error(`ensureRemoteForward: invalid localHost "${spec.localHost}"`);+ }+ if (!Number.isInteger(spec.localPort) || spec.localPort < 1 || spec.localPort > 65535) {+ throw new Error(`ensureRemoteForward: invalid localPort ${spec.localPort}`);+ }+ const key = forwardKey(spec);+ const existing = this.forwards.get(key);+ if (existing) {+ // 已登记但未 arm (连接刚建好 / 上次 arm 失败) — 趁 ready 补一次。+ if (!existing.armed && this.status === 'ready') {+ await this.armForwardDeduped(existing);+ }+ return this.forwardHandle(key, existing);+ }++ const record: ForwardRecord = {+ spec,+ remotePort: spec.preferredRemotePort ?? DEFAULT_REMOTE_FORWARD_PORT_BASE,+ armed: false,+ lastLocalErrorAt: 0,+ localErrorCount: 0,+ };+ this.forwards.set(key, record);+ if (this.status === 'ready') {+ await this.armForwardDeduped(record);+ }+ return this.forwardHandle(key, record);+ }++ /**+ * 当前登记的 forward 列表 (诊断 / snapshot 用)。armed=false 表示愿望已+ * 登记但当前没在转发 (未连接 / arm 失败待重连)。+ */+ listRemoteForwards(): Array<{ localHost: string; localPort: number; remotePort: number; armed: boolean }> {+ return Array.from(this.forwards.values()).map((r) => ({+ localHost: r.spec.localHost,+ localPort: r.spec.localPort,+ remotePort: r.remotePort,+ armed: r.armed,+ }));+ }++ /** 关闭并清除所有已登记 forward (pref 关闭路径)。连接断开时是纯本地清理。 */+ async closeAllRemoteForwards(): Promise<void> {+ const keys = Array.from(this.forwards.keys());+ for (const key of keys) {+ const record = this.forwards.get(key);+ if (!record) continue;+ await this.forwardHandle(key, record).close();+ }+ }++ private forwardHandle(key: string, record: ForwardRecord): RemoteForward {+ return {+ get remotePort() {+ return record.remotePort;+ },+ close: async () => {+ if (!this.forwards.delete(key)) return;+ record.armed = false;+ // 连接活着就显式 unforward; 断线时服务端侧随连接消失, 无需操作。+ if (this.status === 'ready' && this.client) {+ await new Promise<void>((resolve) => {+ try {+ this.client!.unforwardIn('127.0.0.1', record.remotePort, () => resolve());+ } catch {+ resolve();+ }+ });+ }+ },+ };+ }++ /**+ * 在当前 client 上注册 forwardIn。端口冲突 / sshd 拒绝时按候选序列重试,+ * 全部失败抛错 (调用方决定是登记愿望待重试还是直接失败)。+ *+ * 每次 forwardIn 带 10s 看门狗: 连接在请求在飞时断开的话, ssh2 对+ * outstanding global request 的回调不保证触发, 裸 await 会永久挂起。+ */+ private async armForward(record: ForwardRecord): Promise<void> {+ const client = this.requireReady();+ this.attachForwardListener(client);++ const base = record.spec.preferredRemotePort ?? DEFAULT_REMOTE_FORWARD_PORT_BASE;+ const errors: string[] = [];+ for (let i = 0; i < REMOTE_FORWARD_PORT_SCAN_SPAN; i++) {+ const port = base + i;+ const bound = await new Promise<number | null>((resolve) => {+ const timer = setTimeout(() => {+ errors.push(`${port}: forwardIn timed out after 10s`);+ resolve(null);+ }, 10_000);+ timer.unref?.();+ try {+ client.forwardIn('127.0.0.1', port, (err, boundPort) => {+ clearTimeout(timer);+ if (err) {+ errors.push(`${port}: ${err.message}`);+ resolve(null);+ } else {+ resolve(boundPort || port);+ }+ });+ } catch (err) {+ clearTimeout(timer);+ errors.push(`${port}: ${(err as Error).message}`);+ resolve(null);+ }+ });+ if (bound == null) continue;+ record.remotePort = bound;+ record.armed = true;+ this.log.info('ssh remote forward armed', {+ id: this.id,+ remotePort: bound,+ localTarget: forwardKey(record.spec),+ });+ return;+ }+ throw new Error(+ `remote port forwarding failed on ${this.id} (tried 127.0.0.1:${base}–${base + REMOTE_FORWARD_PORT_SCAN_SPAN - 1}). ` ++ `The remote sshd may disallow remote forwarding (AllowTcpForwarding) or the ports are busy. ` ++ errors.slice(0, 3).join('; '),+ );+ }++ /** connect 成功后重挂所有已登记 forward; 端口变了通知上层。 */+ private async rearmForwards(): Promise<void> {+ for (const record of this.forwards.values()) {+ const prevPort = record.remotePort;+ record.armed = false;+ try {+ await this.armForwardDeduped(record);+ } catch (err) {+ // arm 失败不阻断连接 — 记日志, 下次 reconnect 再试; session 路径+ // (ensureRemoteForward on ready host) 会显式重试并拿到错误。+ this.log.warn('ssh remote forward re-arm failed', {+ id: this.id,+ localTarget: forwardKey(record.spec),+ error: (err as Error).message,+ });+ continue;+ }+ if (record.remotePort !== prevPort) {+ this.log.warn('ssh remote forward re-bound to a different port', {+ id: this.id,+ prevPort,+ remotePort: record.remotePort,+ });+ try {+ record.spec.onRearmed?.(record.remotePort);+ } catch { /* listener must not throw */ }+ }+ }+ }++ /** 同一条 forward 的并发 arm 共享一个 in-flight promise。 */+ private armForwardDeduped(record: ForwardRecord): Promise<void> {+ if (record.armed) return Promise.resolve();+ if (!record.arming) {+ record.arming = this.armForward(record).finally(() => {+ record.arming = undefined;+ });+ }+ return record.arming;+ }++ /** 每个 client 实例挂一次 'tcp connection' 分发器。 */+ private attachForwardListener(client: Client): void {+ if (this.forwardListenerClient === client) return;+ this.forwardListenerClient = client;+ client.on('tcp connection', (details: TcpConnectionDetails, accept, reject) => {+ this.handleForwardedConnection(details, accept, reject);+ });+ }++ private handleForwardedConnection(+ details: TcpConnectionDetails,+ accept: () => ClientChannel,+ reject: () => void,+ ): void {+ let record: ForwardRecord | undefined;+ for (const r of this.forwards.values()) {+ if (r.armed && r.remotePort === details.destPort) {+ record = r;+ break;+ }+ }+ if (!record) {+ reject();+ return;+ }+ const rec = record;+ const channel = accept();+ const sock = net.connect({ host: rec.spec.localHost, port: rec.spec.localPort });++ sock.on('error', (err) => {+ // 本地 Proxy 没起 / 拒连 — 远端 agent 会看到连接立刻被断, 错误在+ // agent 侧浮现 (proxy connect failed)。这里只做节流日志。+ rec.localErrorCount += 1;+ const now = Date.now();+ if (now - rec.lastLocalErrorAt > 30_000) {+ rec.lastLocalErrorAt = now;+ this.log.warn('ssh remote forward: local target unreachable', {+ id: this.id,+ localTarget: forwardKey(rec.spec),+ error: err.message,+ suppressedCount: rec.localErrorCount,+ });+ }+ try { channel.close(); } catch { /* already gone */ }+ });+ channel.on('error', () => {+ sock.destroy();+ });+ // 远端关掉转发 channel → 本地到 Proxy 的 socket 同步销毁; 否则本地+ // Proxy 侧会积一堆半开连接 (pipe 的 end 只处理正常 EOF, 不覆盖 destroy)。+ channel.on('close', () => {+ sock.destroy();+ });+ sock.on('close', () => {+ try { channel.close(); } catch { /* already gone */ }+ });+ channel.pipe(sock);+ sock.pipe(channel);+ }+// ── internals ────────────────────────────────────────────────────────────/** Guard for channel ops. */@@ -565,6 +871,9 @@ export class RemoteHost {this.reconnectAttempts = 0;this.setStatus('ready');this.log.info('ssh ready', { id: this.id, auth: auth.label });+ // 后台重挂已登记的 remote forwards; 不阻塞 connect 返回 (session+ // 路径会自己 await ensureRemoteForward 拿到 arm 错误)。+ void this.rearmForwards();resolve();};@@ -634,6 +943,7 @@ export class RemoteHost {private handlePostReadyClose(): void {this.client = null;+ this.markForwardsDisarmed();if (this.userDisconnected) {this.setStatus('disconnected');return;@@ -692,6 +1002,13 @@ export class RemoteHost {}}+ /** 连接断了后服务端侧的转发监听随之消失; 愿望保留, 等下次 ready 重挂。 */+ private markForwardsDisarmed(): void {+ for (const record of this.forwards.values()) {+ record.armed = false;+ }+ }+private setStatus(next: RemoteStatus): void {if (this.status === next) return;this.status = next;diff --git a/packages/maker-remote-ssh/src/__tests__/remoteHostForward.test.ts b/packages/maker-remote-ssh/src/__tests__/remoteHostForward.test.tsnew file mode 100644index 0000000000..75855c748c--- /dev/null+++ b/packages/maker-remote-ssh/src/__tests__/remoteHostForward.test.ts@@ -0,0 +1,299 @@+/**+ * RemoteHost remote forwarding (ssh -R 等价物) 测试。+ *+ * 用 fake ssh2 Client (EventEmitter + forwardIn/unforwardIn) 注入私有字段,+ * 本地端用真实 net server (127.0.0.1 回环) 验证字节 pipe:+ * - 首选端口绑定 / 端口冲突顺延 / 全部失败时报错提及 AllowTcpForwarding+ * - 'tcp connection' 分发到正确的 forward 并双向 pipe+ * - 本地目标不可达时只断 channel 不炸进程+ * - ensure 幂等 / close 调 unforwardIn+ * - 断线重连 re-arm: 愿望保留、端口变化触发 onRearmed+ */++import { describe, it, expect } from 'vitest';+import { EventEmitter } from 'node:events';+import { Duplex, PassThrough } from 'node:stream';+import net from 'node:net';++import { RemoteHost, DEFAULT_REMOTE_FORWARD_PORT_BASE } from '../RemoteHost.js';+import type { HostConfig } from '../types.js';++const HOST_CONFIG: HostConfig = {+ id: 'test-host',+ hostname: '10.0.0.1',+ port: 22,+ user: 'deploy',+ authMethod: 'agent',+ source: 'manual',+};++const noopLogger = {+ debug: () => {},+ info: () => {},+ warn: () => {},+ error: () => {},+};++interface ForwardInCall { addr: string; port: number }++/** 可按端口决定成败的 fake ssh2 Client。 */+class FakeClient extends EventEmitter {+ forwardInCalls: ForwardInCall[] = [];+ unforwardInCalls: ForwardInCall[] = [];+ /** 返回 false 的端口 forwardIn 失败 (模拟被占用 / sshd 拒绝)。 */+ constructor(private readonly allowPort: (port: number) => boolean = () => true) {+ super();+ }+ forwardIn(addr: string, port: number, cb: (err: Error | undefined, port: number) => void): void {+ this.forwardInCalls.push({ addr, port });+ queueMicrotask(() => {+ if (this.allowPort(port)) cb(undefined, port);+ else cb(new Error('Unable to bind'), 0);+ });+ }+ unforwardIn(addr: string, port: number, cb: () => void): void {+ this.unforwardInCalls.push({ addr, port });+ queueMicrotask(() => cb());+ }+}++interface FakeChannelBundle {+ channel: Duplex & { close: () => void };+ /** test 写入 → channel readable → 本地 sock (模拟远端发来的字节)。 */+ fromRemote: PassThrough;+ /** 本地 sock 写入 → test 读出 (模拟要送回远端的字节)。 */+ toRemote: PassThrough;+ closed: () => boolean;+}++function makeFakeChannel(): FakeChannelBundle {+ const fromRemote = new PassThrough();+ const toRemote = new PassThrough();+ let closed = false;+ // 手工拼 Duplex (@types/node 没有 {readable,writable} pair overload 的类型):+ // readable 侧由 fromRemote 推, writable 侧落进 toRemote 供断言。+ const channel = new Duplex({+ read() {},+ write(chunk: Buffer, _enc: BufferEncoding, cb: (err?: Error | null) => void) {+ if (toRemote.write(chunk)) cb();+ else toRemote.once('drain', () => cb());+ },+ }) as Duplex & { close: () => void };+ fromRemote.on('data', (chunk: Buffer) => channel.push(chunk));+ fromRemote.on('end', () => channel.push(null));+ channel.close = () => {+ if (closed) return;+ closed = true;+ channel.destroy();+ };+ return { channel, fromRemote, toRemote, closed: () => closed };+}++function makeReadyHost(client: FakeClient): RemoteHost {+ const host = new RemoteHost(HOST_CONFIG, { logger: noopLogger });+ (host as unknown as { status: string }).status = 'ready';+ (host as unknown as { client: unknown }).client = client;+ return host;+}++async function flush(): Promise<void> {+ await new Promise((r) => setTimeout(r, 10));+}++/** 起一个在 127.0.0.1 随机端口的 echo server, 返回端口与关闭函数。 */+async function startEchoServer(): Promise<{ port: number; close: () => Promise<void> }> {+ const server = net.createServer((sock) => sock.pipe(sock));+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ const port = (server.address() as net.AddressInfo).port;+ return {+ port,+ close: () => new Promise<void>((resolve) => server.close(() => resolve())),+ };+}++describe('RemoteHost remote forwarding', () => {+ it('arms forwardIn on the preferred port and lists it as armed', async () => {+ const client = new FakeClient();+ const host = makeReadyHost(client);+ const fwd = await host.ensureRemoteForward({ localHost: '127.0.0.1', localPort: 7890 });++ expect(fwd.remotePort).toBe(DEFAULT_REMOTE_FORWARD_PORT_BASE);+ expect(client.forwardInCalls).toEqual([+ { addr: '127.0.0.1', port: DEFAULT_REMOTE_FORWARD_PORT_BASE },+ ]);+ expect(host.listRemoteForwards()).toEqual([+ {+ localHost: '127.0.0.1',+ localPort: 7890,+ remotePort: DEFAULT_REMOTE_FORWARD_PORT_BASE,+ armed: true,+ },+ ]);+ });++ it('falls back to the next candidate port when the preferred one is taken', async () => {+ const client = new FakeClient((port) => port !== DEFAULT_REMOTE_FORWARD_PORT_BASE);+ const host = makeReadyHost(client);+ const fwd = await host.ensureRemoteForward({ localHost: '127.0.0.1', localPort: 7890 });++ expect(fwd.remotePort).toBe(DEFAULT_REMOTE_FORWARD_PORT_BASE + 1);+ expect(client.forwardInCalls.map((c) => c.port)).toEqual([+ DEFAULT_REMOTE_FORWARD_PORT_BASE,+ DEFAULT_REMOTE_FORWARD_PORT_BASE + 1,+ ]);+ });++ it('throws an actionable error when every candidate port fails', async () => {+ const client = new FakeClient(() => false);+ const host = makeReadyHost(client);+ await expect(+ host.ensureRemoteForward({ localHost: '127.0.0.1', localPort: 7890 }),+ ).rejects.toThrow(/AllowTcpForwarding/);+ });++ it('rejects invalid local targets before touching ssh', async () => {+ const host = makeReadyHost(new FakeClient());+ await expect(+ host.ensureRemoteForward({ localHost: 'bad host', localPort: 7890 }),+ ).rejects.toThrow(/localHost/);+ await expect(+ host.ensureRemoteForward({ localHost: '127.0.0.1', localPort: 0 }),+ ).rejects.toThrow(/localPort/);+ });++ it('is idempotent for the same local target (no duplicate forwardIn)', async () => {+ const client = new FakeClient();+ const host = makeReadyHost(client);+ const a = await host.ensureRemoteForward({ localHost: '127.0.0.1', localPort: 7890 });+ const b = await host.ensureRemoteForward({ localHost: '127.0.0.1', localPort: 7890 });+ expect(a.remotePort).toBe(b.remotePort);+ expect(client.forwardInCalls).toHaveLength(1);+ });++ it('pipes a forwarded connection to the local target and back', async () => {+ const echo = await startEchoServer();+ try {+ const client = new FakeClient();+ const host = makeReadyHost(client);+ const fwd = await host.ensureRemoteForward({ localHost: '127.0.0.1', localPort: echo.port });++ const fake = makeFakeChannel();+ client.emit(+ 'tcp connection',+ { srcIP: '127.0.0.1', srcPort: 55000, destIP: '127.0.0.1', destPort: fwd.remotePort },+ () => fake.channel,+ () => { throw new Error('unexpected reject'); },+ );+ fake.fromRemote.write('ping-through-tunnel');+ await flush();++ // echo server 原样弹回 → 应出现在要送回远端的流里。+ expect(fake.toRemote.read()?.toString()).toBe('ping-through-tunnel');+ fake.channel.close();+ } finally {+ await echo.close();+ }+ });++ it('closes the channel (no crash) when the local target is unreachable', async () => {+ // 先占一个端口再释放, 拿到一个几乎必然拒连的端口。+ const probe = await startEchoServer();+ const deadPort = probe.port;+ await probe.close();++ const client = new FakeClient();+ const host = makeReadyHost(client);+ const fwd = await host.ensureRemoteForward({ localHost: '127.0.0.1', localPort: deadPort });++ const fake = makeFakeChannel();+ client.emit(+ 'tcp connection',+ { srcIP: '127.0.0.1', srcPort: 55001, destIP: '127.0.0.1', destPort: fwd.remotePort },+ () => fake.channel,+ () => { throw new Error('unexpected reject'); },+ );+ // ECONNREFUSED 是异步的; 等它发生。+ await flush();+ expect(fake.closed()).toBe(true);+ });++ it('rejects connections to unknown destPorts', async () => {+ const client = new FakeClient();+ const host = makeReadyHost(client);+ await host.ensureRemoteForward({ localHost: '127.0.0.1', localPort: 7890 });++ let rejected = false;+ client.emit(+ 'tcp connection',+ { srcIP: '127.0.0.1', srcPort: 55002, destIP: '127.0.0.1', destPort: 1 },+ () => { throw new Error('unexpected accept'); },+ () => { rejected = true; },+ );+ expect(rejected).toBe(true);+ });++ it('close() unforwards on the live client and drops the record', async () => {+ const client = new FakeClient();+ const host = makeReadyHost(client);+ const fwd = await host.ensureRemoteForward({ localHost: '127.0.0.1', localPort: 7890 });+ await fwd.close();++ expect(client.unforwardInCalls).toEqual([+ { addr: '127.0.0.1', port: DEFAULT_REMOTE_FORWARD_PORT_BASE },+ ]);+ expect(host.listRemoteForwards()).toEqual([]);+ });++ it('re-arms on reconnect and reports a changed port via onRearmed', async () => {+ const client1 = new FakeClient();+ const host = makeReadyHost(client1);+ let rearmed: number | null = null;+ const fwd = await host.ensureRemoteForward({+ localHost: '127.0.0.1',+ localPort: 7890,+ onRearmed: (port) => { rearmed = port; },+ });+ expect(fwd.remotePort).toBe(DEFAULT_REMOTE_FORWARD_PORT_BASE);++ // 模拟断线重连: 标记 disarm (handlePostReadyClose 路径) 并换上新 client,+ // 新连接上原端口已被别人占 → 应顺延并回调 onRearmed。+ (host as unknown as { markForwardsDisarmed(): void }).markForwardsDisarmed();+ const client2 = new FakeClient((port) => port !== DEFAULT_REMOTE_FORWARD_PORT_BASE);+ (host as unknown as { client: unknown }).client = client2;+ await (host as unknown as { rearmForwards(): Promise<void> }).rearmForwards();++ expect(fwd.remotePort).toBe(DEFAULT_REMOTE_FORWARD_PORT_BASE + 1);+ expect(rearmed).toBe(DEFAULT_REMOTE_FORWARD_PORT_BASE + 1);+ expect(host.listRemoteForwards()[0]?.armed).toBe(true);+ });++ it('keeps the wish when re-arm fails, without throwing (logged only)', async () => {+ const client1 = new FakeClient();+ const host = makeReadyHost(client1);+ await host.ensureRemoteForward({ localHost: '127.0.0.1', localPort: 7890 });++ (host as unknown as { markForwardsDisarmed(): void }).markForwardsDisarmed();+ const client2 = new FakeClient(() => false);+ (host as unknown as { client: unknown }).client = client2;+ await (host as unknown as { rearmForwards(): Promise<void> }).rearmForwards();++ const listed = host.listRemoteForwards();+ expect(listed).toHaveLength(1);+ expect(listed[0]?.armed).toBe(false);+ });++ it('defers arming until connect when the host is not ready', async () => {+ const client = new FakeClient();+ const host = new RemoteHost(HOST_CONFIG, { logger: noopLogger });+ // disconnected 状态: 只登记愿望, 不碰 ssh。+ const fwdPromise = host.ensureRemoteForward({ localHost: '127.0.0.1', localPort: 7890 });+ await expect(fwdPromise).resolves.toBeDefined();+ expect(client.forwardInCalls).toHaveLength(0);++ // 连接建立 → doConnect onReady 路径的 rearmForwards 把它挂上。+ (host as unknown as { status: string }).status = 'ready';+ (host as unknown as { client: unknown }).client = client;+ await (host as unknown as { rearmForwards(): Promise<void> }).rearmForwards();+ expect(client.forwardInCalls).toHaveLength(1);+ });+});diff --git a/packages/maker-remote-ssh/src/constants.ts b/packages/maker-remote-ssh/src/constants.tsindex 648541073b..11fda76002 100644--- a/packages/maker-remote-ssh/src/constants.ts+++ b/packages/maker-remote-ssh/src/constants.ts@@ -5,3 +5,16 @@ export const REMOTE_CC_MGR_LOG_PATH = `${REMOTE_CC_MGR_DIR}/cc-mgr.log`;export const REMOTE_CC_MGR_PID_PATH = `${REMOTE_CC_MGR_DIR}/cc-mgr.pid`;export const REMOTE_XDT_NODE_PATH = '$HOME/.xdt-server/v1/node/bin/node';export const REMOTE_CLAUDE_SHIM_PATH = '$HOME/.xdt-server/v1/node_modules/.bin/claude';++/**+ * 远端 install root (codex-home / node / cc-manager 的公共父目录)。+ * codex-remote-transport 的 daemon wrapper 与 agent-proxy 的 env marker+ * 都以它为基准; 改这里要同步两端。+ */+export const REMOTE_INSTALL_ROOT = '$HOME/.xdt-server/v1';+/**+ * Agent Proxy 隧道 env marker: 远端 shell 片段 (export HTTPS_PROXY=...),+ * codex daemon wrapper 启动前 source 它。删文件 = 关闭代理。路径在+ * install root 而非 CODEX_HOME 内, 避免被 codex 自己的目录管理误删。+ */+export const REMOTE_AGENT_PROXY_ENV_PATH = `${REMOTE_INSTALL_ROOT}/agent-proxy.env`;diff --git a/packages/maker-remote-ssh/src/index.ts b/packages/maker-remote-ssh/src/index.tsindex 8a524e4156..02a0db3013 100644--- a/packages/maker-remote-ssh/src/index.ts+++ b/packages/maker-remote-ssh/src/index.ts@@ -6,7 +6,7 @@* claude/codex over an exec channel + session ingest.*/-export { RemoteHost, isAuthFailure, authFailureHint } from './RemoteHost.js';+export { RemoteHost, isAuthFailure, authFailureHint, DEFAULT_REMOTE_FORWARD_PORT_BASE } from './RemoteHost.js';export type {RemoteHostDeps,StatusListener,@@ -14,6 +14,8 @@ export type {ExecResult,ExecStreamOpts,ExecStreamHandle,+ RemoteForward,+ RemoteForwardSpec,} from './RemoteHost.js';export {@@ -59,6 +61,8 @@ export {REMOTE_CC_MGR_PID_PATH,REMOTE_XDT_NODE_PATH,REMOTE_CLAUDE_SHIM_PATH,+ REMOTE_INSTALL_ROOT,+ REMOTE_AGENT_PROXY_ENV_PATH,} from './constants.js';export { ConnectionPool } from './ConnectionPool.js';