Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(remote-agent): 分享来的 Codex 供应商在慢链路下也能开起任务,项目 Skill 不再被当成写入拒掉
Lizie971a22e94f3
diff --git a/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts b/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.tsindex ca4a195b27..0444775d5c 100644--- a/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/execServerRelayConsent.test.ts@@ -121,3 +121,43 @@ describe('exec-server relay with confirmation on this computer', () => {expect(sentIds()).toEqual([]);});});++describe('exec-server relay summary (#5764)', () => {+ function relayWith(opts: { allow: boolean; pushMs: number }) {+ let clock = 0;+ const warn = vi.fn();+ const relay = new ExecServerRelay({+ codexPath: 'codex',+ cwd: root,+ workspace: new ExecutorWorkspace({ workingDir: root }),+ authorize: (): ExecutorGateDecision => (opts.allow ? { ok: true } : { ok: false, reason: 'outside the workspace' }),+ push: async () => {+ clock += opts.pushMs;+ },+ now: () => clock,+ log: { warn },+ });+ relay.handle({ t: 'ws', connId: 'c1', kind: 'open', path: '/ws/exec-server' });+ const send = (message: Record<string, unknown>) =>+ relay.handle({ t: 'ws', connId: 'c1', kind: 'message', data: JSON.stringify(message) });+ return { relay, warn, send };+ }++ it('logs the first slow push right away and a summary with refusals when the task ends', async () => {+ const { relay, warn, send } = relayWith({ allow: false, pushMs: 2_500 });+ send({ id: 1, method: 'fs/walk', params: { path: path.join(root, '..', 'skills') } });+ await vi.waitFor(() => expect(relay.stats().pushes).toBe(1));+ expect(warn).toHaveBeenCalledWith('remote agent: exec-server push slow', { pushMs: 2_500, frames: 1 });+ relay.close();+ expect(relay.stats()).toEqual({ requests: 1, rejected: 1, pushes: 1, pushMaxMs: 2_500, pushAvgMs: 2_500, slowPushes: 1 });+ expect(warn).toHaveBeenLastCalledWith('remote agent: exec-server relay summary', relay.stats());+ });++ it('stays quiet when the link was fast and nothing was refused', () => {+ const { relay, warn, send } = relayWith({ allow: true, pushMs: 10 });+ send({ id: 1, method: 'fs/readFile', params: { path: path.join(root, 'a.txt') } });+ relay.close();+ expect(relay.stats()).toMatchObject({ requests: 1, rejected: 0, slowPushes: 0 });+ expect(warn).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/remote-agent/__tests__/linkActivity.test.ts b/apps/desktop/src/main/remote-agent/__tests__/linkActivity.test.tsnew file mode 100644index 0000000000..806d4e27c3--- /dev/null+++ b/apps/desktop/src/main/remote-agent/__tests__/linkActivity.test.ts@@ -0,0 +1,69 @@+/**+ * 任务隧道的往来记录(#5764):托管 Codex 的线程启动经设备互联逐个读项目文件,Codex 据这里的+ * 最近往来时间判断慢启动是否仍在推进,超时时用这里的计数说明停在哪一步。+ */+import { describe, expect, it } from 'vitest';++import { TunnelLinkActivity, rpcEnvelope } from '../host/linkActivity';++describe('tunnel link activity', () => {+ it('reads JSON-RPC ids and methods, including error replies with the id last and large messages', () => {+ expect(rpcEnvelope('{"id":2,"method":"fs/readFile","params":{}}')).toEqual({ id: '2', method: 'fs/readFile' });+ // exec-server 的错误回复把 id 放在最后。+ expect(rpcEnvelope('{"error":{"code":-32004,"message":"x"},"id":3}')).toEqual({ id: '3' });+ expect(rpcEnvelope('{"method":"initialized","params":{}}')).toEqual({ method: 'initialized' });+ // 数字与字符串 id 不混淆。+ expect(rpcEnvelope('{"id":"3","result":{}}')).toEqual({ id: '"3"' });+ // 整段文件内容只看开头。+ expect(rpcEnvelope(`{"id":7,"result":{"dataBase64":"${'A'.repeat(100_000)}"}}`)).toEqual({ id: '7' });+ expect(rpcEnvelope(`{"id":8,"method":"fs/writeFile","params":{"dataBase64":"${'A'.repeat(100_000)}"}}`))+ .toEqual({ id: '8', method: 'fs/writeFile' });+ expect(rpcEnvelope('not json')).toBeNull();+ });++ it('counts requests, replies, round trips and the oldest unanswered request', () => {+ let now = 1_000;+ const activity = new TunnelLinkActivity(() => now);+ expect(activity.snapshot()).toEqual({+ lastActivityAt: null,+ execRequests: 0,+ execResponses: 0,+ execMaxInFlight: 0,+ httpInFlight: 0,+ });++ activity.connection('c1', false);+ activity.agentMessage('c1', '{"id":1,"method":"fs/walk","params":{}}');+ activity.agentMessage('c1', '{"method":"initialized","params":{}}');+ now += 100;+ activity.agentMessage('c1', '{"id":2,"method":"fs/readFile","params":{}}');+ now += 400;+ activity.environmentMessage('c1', '{"id":1,"result":{}}');+ activity.environmentMessage('c1', '{"method":"process/output","params":{}}');+ // 另一条连接上同 id 的回复不算这条连接的。+ activity.environmentMessage('c2', '{"id":2,"result":{}}');+ now += 1_000;+ // 执行环境主动推的通知(后台命令输出)不算往来:Agent 卡住时它们照样会来。+ activity.environmentMessage('c1', '{"method":"process/output","params":{}}');+ expect(activity.snapshot()).toEqual({+ lastActivityAt: 1_500,+ execRequests: 2,+ execResponses: 1,+ execMaxInFlight: 2,+ execOldestPending: { method: 'fs/readFile', waitedMs: 1_400 },+ execRoundTripAvgMs: 500,+ execRoundTripMaxMs: 500,+ httpInFlight: 0,+ });++ // 连接关掉后,它上面没等到的回复不会再来。+ activity.connection('c1', true);+ expect(activity.snapshot().execOldestPending).toBeUndefined();++ activity.httpStarted();+ expect(activity.snapshot()).toMatchObject({ httpInFlight: 1, lastActivityAt: 2_500 });+ activity.httpFinished();+ activity.httpFinished();+ expect(activity.snapshot().httpInFlight).toBe(0);+ });+});diff --git a/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts b/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.tsindex b2e451a1d6..dd9b7913cd 100644--- a/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts+++ b/apps/desktop/src/main/remote-agent/__tests__/plumbing.test.ts@@ -1,6 +1,7 @@import fs from 'node:fs';import os from 'node:os';import path from 'node:path';+import { pathToFileURL } from 'node:url';import { MAIN_OWNED_SEND_CONTEXT } from '@cindy/maker-core';import { afterEach, beforeEach, describe, expect, it } from 'vitest';@@ -13,6 +14,7 @@ import { approvalActionsFor, createRemoteAgentHandle, innerShellScript } from '.import type { RemoteAgentRunClient } from '../controller/runClient';import { credentialConfirmation, takeGroupSwitchState } from '../controller/startRemote';import { EventLog, LineSplitter } from '../eventLog';+import { ExecutorGate } from '../executor/gate';import { ExecutorWorkspace } from '../executor/workspace';import { createRunTunnel } from '../host/tunnel';import { decodeOpenPayload, decodeSendOptions, encodeSendOptions, isSafeProjectFilePath } from '../wire';@@ -78,6 +80,8 @@ describe('tunnel', () => {expect((await fetch(`${tunnel.url}/mcp/a?q=1`, { headers: { authorization: `Bearer ${tunnel.token}` } })).status).toBe(200);expect((await fetch(`${tunnel.url}/t/${tunnel.token}/mcp/b`)).status).toBe(200);expect(seen).toEqual(['/mcp/a?q=1', '/mcp/b']);+ // Cindy 工具请求也算链路往来,结束后不再计入在途。+ expect(tunnel.linkActivity()).toMatchObject({ httpInFlight: 0, lastActivityAt: expect.any(Number) });} finally {await tunnel.close();}@@ -102,12 +106,17 @@ describe('tunnel', () => {const good = new WebSocket(`${wsUrl}/ws/exec-server`, { headers: { authorization: `Bearer ${tunnel.token}` } });const echoed = new Promise<string>((resolve) => good.on('message', (data) => resolve(String(data))));await new Promise<void>((resolve) => good.on('open', () => resolve()));- good.send('{"id":1}');+ good.send('{"id":1,"method":"fs/readFile","params":{}}');await new Promise((resolve) => setTimeout(resolve, 50));expect(opened).toEqual(['c1:/ws/exec-server']);- expect(messages).toEqual(['{"id":1}']);- tunnel.sendWs('c1', '{"result":true}');- expect(await echoed).toBe('{"result":true}');+ expect(messages).toEqual(['{"id":1,"method":"fs/readFile","params":{}}']);+ expect(tunnel.linkActivity()).toMatchObject({ execRequests: 1, execResponses: 0, execOldestPending: { method: 'fs/readFile' } });+ tunnel.sendWs('c1', '{"id":1,"result":true}');+ expect(await echoed).toBe('{"id":1,"result":true}');+ // 隧道两个方向的帧都记进往来(托管 Codex 据此判断慢启动仍在推进)。+ expect(tunnel.linkActivity()).toMatchObject({ execRequests: 1, execResponses: 1 });+ expect(tunnel.linkActivity().execOldestPending).toBeUndefined();+ expect(tunnel.linkActivity().lastActivityAt).toEqual(expect.any(Number));good.close();} finally {await tunnel.close();@@ -166,6 +175,37 @@ describe('exec-server relay gate', () => {.toEqual([{ kind: 'read', path: path.join(root, '.env') }]);expect(execServerActions('fs/getMetadata', { path: `file://${root}/.git` }, '/w')).toEqual([]);expect(execServerActions('initialize', {}, '/w')).toEqual([]);+ // 只读操作按读取:walk 是目录级读取,open 只开只读句柄,canonicalize 只解析路径。+ const skills = path.join(root, '.agents', 'skills');+ expect(execServerActions('fs/walk', { path: pathToFileURL(skills).href, options: { maxDepth: 6 } }, '/w'))+ .toEqual([{ kind: 'read', path: skills, scope: 'tree' }]);+ expect(execServerActions('fs/open', { handleId: 'h1', path: pathToFileURL(path.join(root, 'a.png')).href }, '/w'))+ .toEqual([{ kind: 'read', path: path.join(root, 'a.png') }]);+ expect(execServerActions('fs/canonicalize', { path: pathToFileURL(skills).href }, '/w')).toEqual([]);+ // 不认识的 fs 方法仍从严按写入。+ expect(execServerActions('fs/futureMethod', { path: pathToFileURL(skills).href }, '/w'))+ .toEqual([{ kind: 'write', path: skills }]);+ });++ it('lets read-only exec-server operations follow the read rules (#5764)', () => {+ const project = path.join(root, 'game');+ const client = path.join(project, 'client');+ fs.mkdirSync(client, { recursive: true });+ const skills = pathToFileURL(path.join(project, '.agents', 'skills')).href;+ const agentsMd = pathToFileURL(path.join(project, 'AGENTS.md')).href;+ const decide = (gate: ExecutorGate, method: string, params: Record<string, unknown>) =>+ execServerActions(method, params, '/w').map((action) => gate.authorize(action).ok);++ // 计划模式:工作区里的 Skill 遍历与只读打开不再算写入。+ const plan = new ExecutorGate(new ExecutorWorkspace({ workingDir: project }), 'plan');+ expect(decide(plan, 'fs/walk', { path: skills })).toEqual([true]);+ expect(decide(plan, 'fs/open', { handleId: 'h1', path: agentsMd })).toEqual([true]);++ // 任务在子目录:上级目录的单文件读取照读取规则放行,递归遍历仍要本机确认。+ const sub = new ExecutorGate(new ExecutorWorkspace({ workingDir: client }), 'normal');+ expect(decide(sub, 'fs/open', { handleId: 'h1', path: agentsMd })).toEqual([true]);+ expect(decide(sub, 'fs/walk', { path: skills })).toEqual([false]);+ expect(decide(sub, 'fs/canonicalize', { path: skills })).toEqual([]);});it('matches Codex and Claude Code confirmations to the commands and files that later run', () => {diff --git a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts b/apps/desktop/src/main/remote-agent/controller/execServerRelay.tsindex 7a1633842d..a90cae0d1b 100644--- a/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts+++ b/apps/desktop/src/main/remote-agent/controller/execServerRelay.ts@@ -30,6 +30,8 @@ export const EXEC_SERVER_WS_PATH = '/ws/exec-server';const MAX_LINE_CHARS = 48 * 1024 * 1024;/** 单帧数据上限,留出 JSON 包装余量。 */const FRAME_CHARS = REMOTE_AGENT_MAX_INLINE_PAYLOAD_CHARS - 1024;+/** 一次回推超过这么久算慢链路(每个 Codex 文件请求都要等一次回推)。 */+const SLOW_PUSH_MS = 2_000;export interface ExecServerRelayDeps {codexPath: string;@@ -41,6 +43,21 @@ export interface ExecServerRelayDeps {push(frames: RemoteAgentPushFrame[]): Promise<void>;env?: NodeJS.ProcessEnv;log?: { warn(message: string, meta?: Record<string, unknown>): void };+ now?: () => number;+}++/**+ * 中继的往来统计(只含计数与耗时)。任务结束时有慢回推或闸门拒绝就记一条日志:前者说明链路慢+ * (托管 Codex 启动要等几十次回推,#5764),后者说明 Agent 有文件或命令没拿到(如任务在子目录时+ * 上级目录的 Skill 遍历)。+ */+export interface ExecServerRelayStats {+ requests: number;+ rejected: number;+ pushes: number;+ pushMaxMs: number;+ pushAvgMs: number;+ slowPushes: number;}interface Connection {@@ -73,9 +90,16 @@ function fromFileUrl(value: unknown, base: string): string | null {return path.isAbsolute(value) ? value : path.resolve(base, value);}-const READ_METHODS = new Set(['fs/readFile', 'fs/readDirectory', 'fs/readDir', 'fs/listDirectory']);-/** 只看元数据、不读内容的操作不过闸门。 */-const METADATA_METHODS = new Set(['fs/getMetadata', 'fs/exists', 'fs/stat']);+// exec-server 的只读操作按读取过闸门;不在下面几组里的 `fs/` 方法一律按写入处理(新版 Codex 新增的+// 方法先从严)。`fs/walk`、`fs/canonicalize`、`fs/open` 曾落进写入:计划模式下工作区里的项目 Skill+// 加载被拒,工作区外的单文件读取也被当成区外写入拒掉(#5764)。++/** 读单个文件或单层目录(`fs/open` 只开只读句柄,内容随后经 `fs/readBlock` 按句柄读取)。 */+const READ_METHODS = new Set(['fs/readFile', 'fs/open', 'fs/readDirectory', 'fs/readDir', 'fs/listDirectory']);+/** 递归遍历:按目录级读取过闸门,根在工作区外与本机任务的搜索一样要本机确认。 */+const TREE_READ_METHODS = new Set(['fs/walk']);+/** 只看元数据、不读内容的操作不过闸门(`fs/canonicalize` 只解析真实路径)。 */+const METADATA_METHODS = new Set(['fs/getMetadata', 'fs/exists', 'fs/stat', 'fs/canonicalize']);/** 把一个 exec-server 请求换成要过闸门的操作。 */export function execServerActions(method: string, params: unknown, cwd: string): ExecutorAction[] {@@ -89,6 +113,7 @@ export function execServerActions(method: string, params: unknown, cwd: string):const paths = ['path', 'sourcePath', 'destinationPath', 'source', 'destination', 'from', 'to', 'target'].map((key) => fromFileUrl(record[key], cwd)).filter((value): value is string => !!value);+ if (TREE_READ_METHODS.has(method)) return paths.map((target) => ({ kind: 'read', path: target, scope: 'tree' }));const kind = READ_METHODS.has(method) ? 'read' : 'write';return paths.map((target) => ({ kind, path: target }) as ExecutorAction);}@@ -156,9 +181,15 @@ export class ExecServerRelay {private outbox: RemoteAgentPushFrame[] = [];private flushing: Promise<void> | null = null;private closed = false;+ private readonly counts = { requests: 0, rejected: 0, pushes: 0, pushTotalMs: 0, pushMaxMs: 0, slowPushes: 0 };constructor(private readonly deps: ExecServerRelayDeps) {}+ stats(): ExecServerRelayStats {+ const { requests, rejected, pushes, pushTotalMs, pushMaxMs, slowPushes } = this.counts;+ return { requests, rejected, pushes, pushMaxMs, pushAvgMs: pushes ? Math.round(pushTotalMs / pushes) : 0, slowPushes };+ }+handle(item: Extract<RemoteAgentStreamItem, { t: 'ws' }>): void {if (this.closed) return;switch (item.kind) {@@ -178,6 +209,8 @@ export class ExecServerRelay {if (this.closed) return;this.closed = true;for (const connId of [...this.connections.keys()]) this.dropConnection(connId, false);+ const stats = this.stats();+ if (stats.slowPushes > 0 || stats.rejected > 0) this.deps.log?.warn('remote agent: exec-server relay summary', { ...stats });}private open(connId: string, wsPath: string): void {@@ -233,6 +266,7 @@ export class ExecServerRelay {}let actions: ExecutorAction[] = [];if (message && typeof message.method === 'string' && message.id !== undefined) {+ this.counts.requests += 1;message.params = mapExecServerParams(message.params, this.deps.workspace, message.method);data = JSON.stringify(message);actions = execServerActions(message.method, message.params, this.deps.cwd);@@ -282,6 +316,7 @@ export class ExecServerRelay {}private reject(connId: string, id: unknown, decision: ExecutorGateDecision): void {+ this.counts.rejected += 1;this.sendMessage(connId, JSON.stringify({id,error: { code: -32001, message: this.deps.workspace.mapTextForAgent(decision.reason ?? 'Not allowed in this workspace.') },@@ -346,8 +381,19 @@ export class ExecServerRelay {batch.push(this.outbox.shift()!);size += length;}+ const now = this.deps.now ?? Date.now;+ const startedAt = now();try {await this.deps.push(batch);+ const elapsed = now() - startedAt;+ this.counts.pushes += 1;+ this.counts.pushTotalMs += elapsed;+ this.counts.pushMaxMs = Math.max(this.counts.pushMaxMs, elapsed);+ if (elapsed >= SLOW_PUSH_MS) {+ this.counts.slowPushes += 1;+ // 第一次慢就记一条(任务可能要很久才结束,汇总那条来得晚)。+ if (this.counts.slowPushes === 1) this.deps.log?.warn('remote agent: exec-server push slow', { pushMs: elapsed, frames: batch.length });+ }} catch (error) {// 批次已从 outbox 取出但交付失败(push 同序号重试耗尽):不能只记日志就继续发后续帧// ——远端 Codex 会永久缺这条 JSON-RPC 回复卡住,丢失的中间分片还会把后续分片拼成diff --git a/apps/desktop/src/main/remote-agent/host/linkActivity.ts b/apps/desktop/src/main/remote-agent/host/linkActivity.tsnew file mode 100644index 0000000000..2086eec005--- /dev/null+++ b/apps/desktop/src/main/remote-agent/host/linkActivity.ts@@ -0,0 +1,136 @@+/**+ * 任务隧道的往来记录(运行 Agent 的电脑,一个任务一份)。+ *+ * Agent 经隧道访问任务所在电脑的执行环境(Codex exec-server 的 WebSocket)与 Cindy 工具(HTTP),每一次+ * 都要过设备互联。这里记下最近一次往来的时间、exec-server 请求的计数与往返耗时:Codex 据此判断慢链路+ * 上的线程启动是否仍在推进(有往来就顺延关键 RPC 的上限),超时时说明停在哪一步(#5764)。+ * 只记方法名、计数与耗时,不记路径与内容。+ */+import type { DeviceHostedLinkActivity } from '@cindy/maker-core';++/** 不超过这个长度的消息完整解析出 id / method;更长的(整段文件内容)只看开头。 */+const ENVELOPE_PARSE_LIMIT = 64 * 1024;+/** 长消息只在开头找 id / method:请求与成功回复都把它们放在 params / result 之前。 */+const ENVELOPE_HEAD_CHARS = 512;+const HEAD_ID = /^\s*\{\s*(?:"jsonrpc"\s*:\s*"[^"]*"\s*,\s*)?"id"\s*:\s*(-?\d+|"(?:[^"\\]|\\.)*")/;+const HEAD_METHOD = /"method"\s*:\s*"((?:[^"\\]|\\.)*)"/;+/** 在等回复的请求最多记这么多条(回复认不出来时不无限累积)。 */+const MAX_PENDING = 4096;+/** 往返耗时只统计最近这么多次。 */+const ROUND_TRIP_WINDOW = 256;++interface RpcEnvelope {+ /** JSON 编码后的 id(数字与字符串 id 不混淆);通知没有 id。 */+ id?: string;+ method?: string;+}++/** 取 JSON-RPC 消息的 id 与 method;不是 JSON 对象时返回 null。 */+export function rpcEnvelope(data: string): RpcEnvelope | null {+ if (data.length <= ENVELOPE_PARSE_LIMIT) {+ let value: unknown;+ try {+ value = JSON.parse(data);+ } catch {+ return null;+ }+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const record = value as { id?: unknown; method?: unknown };+ return {+ ...(typeof record.id === 'number' || typeof record.id === 'string' ? { id: JSON.stringify(record.id) } : {}),+ ...(typeof record.method === 'string' ? { method: record.method } : {}),+ };+ }+ const head = data.slice(0, ENVELOPE_HEAD_CHARS);+ const id = HEAD_ID.exec(head)?.[1];+ if (id === undefined) return null;+ const method = HEAD_METHOD.exec(head)?.[1];+ return { id, ...(method !== undefined ? { method } : {}) };+}++/** 一个任务隧道上的往来计数。 */+export class TunnelLinkActivity {+ private lastActivityAt: number | null = null;+ private execRequests = 0;+ private execResponses = 0;+ private execMaxInFlight = 0;+ /** 在等回复的请求,键为「连接 + id」,按发出顺序(Map 保持插入顺序,最早的在前)。 */+ private readonly pending = new Map<string, { method: string; sentAt: number }>();+ private readonly roundTrips: number[] = [];+ private httpInFlight = 0;++ constructor(private readonly now: () => number = Date.now) {}++ /** Agent 发给执行环境的一条 WebSocket 消息。 */+ agentMessage(connId: string, data: string): void {+ this.touch();+ const envelope = rpcEnvelope(data);+ // 通知(没有 id)与回复执行环境发起的请求(没有 method)不算请求。+ if (envelope?.id === undefined || envelope.method === undefined) return;+ this.execRequests += 1;+ this.pending.set(`${connId}\0${envelope.id}`, { method: envelope.method, sentAt: this.now() });+ if (this.pending.size > MAX_PENDING) this.pending.delete(this.pending.keys().next().value as string);+ this.execMaxInFlight = Math.max(this.execMaxInFlight, this.pending.size);+ }++ /**+ * 执行环境发给 Agent 的一条 WebSocket 消息。只有回复算往来:执行环境主动推的通知(如后台命令的+ * process/output)不说明 Agent 还在推进,Agent 卡住时它们照样会来。+ */+ environmentMessage(connId: string, data: string): void {+ const envelope = rpcEnvelope(data);+ if (envelope?.method !== undefined) return;+ this.touch();+ if (envelope?.id === undefined) return;+ const key = `${connId}\0${envelope.id}`;+ const sent = this.pending.get(key);+ if (!sent) return;+ this.pending.delete(key);+ this.execResponses += 1;+ this.roundTrips.push(this.now() - sent.sentAt);+ if (this.roundTrips.length > ROUND_TRIP_WINDOW) this.roundTrips.shift();+ }++ /** 连接打开或关闭;关闭时这条连接上没等到的回复不会再来。 */+ connection(connId: string, closed: boolean): void {+ this.touch();+ if (!closed) return;+ const prefix = `${connId}\0`;+ for (const key of [...this.pending.keys()]) if (key.startsWith(prefix)) this.pending.delete(key);+ }++ /** Cindy 工具的 HTTP 请求开始 / 结束(回包或失败)。 */+ httpStarted(): void {+ this.touch();+ this.httpInFlight += 1;+ }++ httpFinished(): void {+ this.touch();+ this.httpInFlight = Math.max(0, this.httpInFlight - 1);+ }++ snapshot(): DeviceHostedLinkActivity {+ const now = this.now();+ const oldest = this.pending.values().next().value as { method: string; sentAt: number } | undefined;+ const roundTripTotal = this.roundTrips.reduce((sum, value) => sum + value, 0);+ return {+ lastActivityAt: this.lastActivityAt,+ execRequests: this.execRequests,+ execResponses: this.execResponses,+ execMaxInFlight: this.execMaxInFlight,+ ...(oldest ? { execOldestPending: { method: oldest.method, waitedMs: Math.max(0, now - oldest.sentAt) } } : {}),+ ...(this.roundTrips.length+ ? {+ execRoundTripAvgMs: Math.round(roundTripTotal / this.roundTrips.length),+ execRoundTripMaxMs: Math.max(...this.roundTrips),+ }+ : {}),+ httpInFlight: this.httpInFlight,+ };+ }++ private touch(): void {+ this.lastActivityAt = this.now();+ }+}diff --git a/apps/desktop/src/main/remote-agent/host/runHost.ts b/apps/desktop/src/main/remote-agent/host/runHost.tsindex 6f35d8b820..db291c32cd 100644--- a/apps/desktop/src/main/remote-agent/host/runHost.ts+++ b/apps/desktop/src/main/remote-agent/host/runHost.ts@@ -42,7 +42,7 @@ import {type RemoteAgentReverseRequest,type RemoteAgentTeardownReason,} from '@cindy/device-link';-import type { AgentEvent, AgentSessionHandle, InteractionRequest } from '@cindy/maker-core';+import type { AgentEvent, AgentSessionHandle, DeviceHostedLinkActivity, InteractionRequest } from '@cindy/maker-core';import { RemoteAgentRunClient, type RemoteAgentInvoke, type RemoteAgentPoller } from '../controller/runClient';import { EventLog, waitForAny } from '../eventLog';@@ -129,7 +129,8 @@ export interface HostedStartInput {personalInstructions?: string;options: RemoteAgentWireStartOptions;workspace: RemoteAgentWireWorkspace;- tunnel: { url: string; token: string };+ /** linkActivity:隧道上的往来记录,Codex 据此判断慢启动是否仍在推进。 */+ tunnel: { url: string; token: string; linkActivity?: () => DeviceHostedLinkActivity };mcpServers: string[];onInvalidResumeSession?: (expectedSdkSessionId: string) => Promise<boolean>;/** 控制端是其他账号(供应商分享的受邀者):Agent 不加载本机的个人化配置与可执行配置。 */@@ -990,7 +991,7 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {...(payload.personal.instructions ? { personalInstructions: projectText(payload.personal.instructions) } : {}),options: Object.fromEntries(Object.entries(payload.options).map(([key, value]) => [key, typeof value === 'string' ? projectText(value) : value])) as unknown as RemoteAgentWireStartOptions,workspace: payload.workspace,- tunnel: { url: tunnel.url, token: tunnel.token },+ tunnel: { url: tunnel.url, token: tunnel.token, linkActivity: () => tunnel.linkActivity() },mcpServers: payload.mcpServers,...(run.trust === 'guest' ? { guest: true, ...(guestHome ? { guestHome } : {}), ...(guestProvider ? { guestProvider } : {}) } : {}),...(payload.options.invalidResumeCallbackdiff --git a/apps/desktop/src/main/remote-agent/host/service.ts b/apps/desktop/src/main/remote-agent/host/service.tsindex 655ea7ae5c..b215fa04be 100644--- a/apps/desktop/src/main/remote-agent/host/service.ts+++ b/apps/desktop/src/main/remote-agent/host/service.ts@@ -71,6 +71,7 @@ export function hostedStartOptions(input: HostedStartInput): StartSessionOptionshomeDir: undefined,tunnelUrl: input.tunnel.url,tunnelToken: input.tunnel.token,+ ...(input.tunnel.linkActivity ? { linkActivity: input.tunnel.linkActivity } : {}),mcpServers: [...input.mcpServers],mirrorRoot: input.mirrorRoot,...(input.personalInstructions ? { personalInstructions: input.personalInstructions } : {}),diff --git a/apps/desktop/src/main/remote-agent/host/tunnel.ts b/apps/desktop/src/main/remote-agent/host/tunnel.tsindex 6e46e4ea92..422f7df953 100644--- a/apps/desktop/src/main/remote-agent/host/tunnel.ts+++ b/apps/desktop/src/main/remote-agent/host/tunnel.ts@@ -9,8 +9,11 @@ import { randomBytes, timingSafeEqual } from 'node:crypto';import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';import type { AddressInfo, Socket } from 'node:net';+import type { DeviceHostedLinkActivity } from '@cindy/maker-core';import { WebSocketServer, type WebSocket } from 'ws';+import { TunnelLinkActivity } from './linkActivity';+/** 单个请求体上限(与反向请求载荷上限一致)。 */export const TUNNEL_MAX_BODY_BYTES = 48 * 1024 * 1024;const MAX_WS_CONNECTIONS = 16;@@ -42,6 +45,8 @@ export interface RunTunnel {token: string;sendWs(connId: string, data: string): void;closeWs(connId: string): void;+ /** 这条隧道上的往来记录(见 linkActivity.ts)。 */+ linkActivity(): DeviceHostedLinkActivity;close(): Promise<void>;}@@ -108,6 +113,7 @@ export async function createRunTunnel(handlers: TunnelHandlers): Promise<RunTunnconst connections = new Map<string, WebSocket>();let nextConn = 0;let closed = false;+ const activity = new TunnelLinkActivity();const server: Server = createServer((req: IncomingMessage, res: ServerResponse) => {void (async () => {@@ -133,6 +139,7 @@ export async function createRunTunnel(handlers: TunnelHandlers): Promise<RunTunnif (!FORWARDED_HEADERS.has(name) || value === undefined) continue;headers.push([name, Array.isArray(value) ? value.join(', ') : value]);}+ activity.httpStarted();try {const response = await handlers.http({method: req.method ?? 'GET',@@ -152,6 +159,8 @@ export async function createRunTunnel(handlers: TunnelHandlers): Promise<RunTunn: 'The task has ended on the computer where it runs.';res.writeHead(502, { 'content-type': 'application/json' });res.end(JSON.stringify({ error: { code: 'REMOTE_AGENT_TUNNEL', message } }));+ } finally {+ activity.httpFinished();}})();});@@ -172,13 +181,18 @@ export async function createRunTunnel(handlers: TunnelHandlers): Promise<RunTunnnextConn += 1;const connId = `c${nextConn}`;connections.set(connId, ws);+ activity.connection(connId, false);handlers.wsOpen(connId, wsPath ?? '/');ws.on('message', (data, isBinary) => {if (isBinary) return;- handlers.wsMessage(connId, data.toString());+ const text = data.toString();+ activity.agentMessage(connId, text);+ handlers.wsMessage(connId, text);});ws.on('close', () => {- if (connections.delete(connId)) handlers.wsClose(connId);+ if (!connections.delete(connId)) return;+ activity.connection(connId, true);+ handlers.wsClose(connId);});ws.on('error', () => ws.terminate());});@@ -198,14 +212,18 @@ export async function createRunTunnel(handlers: TunnelHandlers): Promise<RunTunntoken,sendWs(connId, data) {const ws = connections.get(connId);- if (ws && ws.readyState === ws.OPEN) ws.send(data);+ if (!ws || ws.readyState !== ws.OPEN) return;+ activity.environmentMessage(connId, data);+ ws.send(data);},closeWs(connId) {const ws = connections.get(connId);if (!ws) return;connections.delete(connId);+ activity.connection(connId, true);ws.close();},+ linkActivity: () => activity.snapshot(),async close() {if (closed) return;closed = true;diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex ccf07fe020..d476a0dd5d 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -583,7 +583,10 @@ handler 无 sender 依赖;不加入共享任务访客白名单,不进入自隧道每个任务一个随机令牌,只监听 127.0.0.1。- **Codex 依赖**:B 的 Codex 通过 app-server 的实验接口 `environment/add` + `environments` 把 A 注册为exec-server 执行环境,A 为每条连接起本机 `codex exec-server --listen stdio://`。该接口随 Codex 版本- 可能变化,升级 Codex 时需回归 `remote-agent/__tests__/codexHosted.e2e.test.ts`。+ 可能变化,升级 Codex 时需回归 `remote-agent/__tests__/codexHosted.e2e.test.ts`。A 的中继按方法语义+ 过本机闸门(`controller/execServerRelay.ts`):`fs/readFile`、`fs/open` 与目录读取按读取,`fs/walk` 按+ 目录级读取,`fs/getMetadata`、`fs/canonicalize` 等只看元数据的不过闸门,其余 `fs/` 方法按写入;+ 升级 Codex 后核对 exec-server 新增的方法,只读的要显式归类,否则会被当成写入拒掉(#5764)。- **影子目录与配置同步**:`open` 载荷除项目说明文件(含 `.claude/CLAUDE.md`、`.claude/rules`、`.codex/skills`)外还带 `ancestorFiles`(项目上级目录里的`CLAUDE.md` / `CLAUDE.local.md` / `AGENTS.md` / `AGENTS.override.md`,按层级 `up`,最多 24 级)与diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex 2be5319d94..4ce9e8e291 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -83,6 +83,18 @@ relay 以 close 1013 `inbound backpressure` 主动断连,此时任何「立即12 个在途配额;被控端连续立即返回空结果时控制端放慢到 1s 一次,防止空转。2 台控制端共享被控端、其中一台静默的回归仍需在双实例实机验证中补测。+**托管 Codex 的关键线程 RPC**(#5764):Agent 所在电脑上的 Codex 经 exec-server 逐个读任务所在电脑的+项目说明与 Skill,`thread/start` 实测约 35 轮串行往返,耗时 ≈ 轮数 × 链路往返,慢链路下合法地超过+`CRITICAL_THREAD_RPC_TIMEOUT_MS`(60s)。`thread/start`、`thread/resume`、`turn/start` 因此在任务隧道+还有往来(Agent 发出的 exec-server 消息、执行环境的回复或 Cindy 工具请求;执行环境主动推的后台命令+输出不算,Agent 卡住时它照样会来)时顺延,隧道连续 30s 没有往来或从发出起满 5 分钟仍按超时收口;+没有往来记录的会话(非托管、旧接线)保持固定 60s。只作用于这一个任务的这一次等待,不重试、不重放、+不动 link 与其它任务。诊断:超时错误末尾带 exec-server 请求/回复数、最早未回复请求与等待时长、+往返均值与峰值、最近一次往来距今多久(Agent 所在电脑的隧道记录,`host/linkActivity.ts`);任务所在+电脑的中继在首次回推超过 2s 时记一条日志,任务结束时有慢回推或闸门拒绝再记汇总+(`controller/execServerRelay.ts`)。回归见 `codex/app-server/client.test.ts`、+`codex/__tests__/device-hosted-guest.test.ts` 与 `remote-agent/__tests__/linkActivity.test.ts`。+## 协同远端 Worker 的轮询与恢复协议见 [`protocol-compatibility.md`](protocol-compatibility.md)「协同远端 Worker」,实现见diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex b23946ff47..b5b4f8591e 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -1783,6 +1783,36 @@ export interface DeviceHostedSession {* Pi / Codex 子代理与按模型分流的路由也只保留这个供应商。*/guestProvider?: DeviceHostedGuestProvider;+ /**+ * 任务隧道的往来记录。托管会话里 Codex 每读一个项目文件都要过一次设备互联,慢链路下线程启动会+ * 合法地超过关键 RPC 的固定上限(#5764):链路上还有往来就顺延等待,超时时把这里的计数写进错误说明。+ * 不提供时按固定上限。+ */+ linkActivity?: () => DeviceHostedLinkActivity;+}++/**+ * 设备托管会话的链路往来快照(运行 Agent 的电脑上、任务隧道记下的)。只含方法名、计数与耗时,+ * 可以写进日志与错误说明。+ */+export interface DeviceHostedLinkActivity {+ /**+ * 最近一次往来的时间(Date.now 毫秒):Agent 发给执行环境的消息、执行环境的回复或 Cindy 工具请求;+ * 执行环境主动推的通知(后台命令输出等)不算。还没有往来时为 null。+ */+ lastActivityAt: number | null;+ /** Agent 发给执行环境(Codex exec-server)的请求数,与其中已收到回复的数量。 */+ execRequests: number;+ execResponses: number;+ /** 同时在等回复的执行环境请求数的峰值。 */+ execMaxInFlight: number;+ /** 还在等回复的执行环境请求里最早的一个:方法名与已等时长(毫秒)。 */+ execOldestPending?: { method: string; waitedMs: number };+ /** 最近若干次执行环境往返的平均与最大耗时(毫秒);还没有完成的往返时缺省。 */+ execRoundTripAvgMs?: number;+ execRoundTripMaxMs?: number;+ /** 正在经隧道处理的 Cindy 工具(HTTP)请求数。 */+ httpInFlight: number;}/** 受邀者会话的供应商边界,见 DeviceHostedSession.guestProvider。 */diff --git a/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.test.ts b/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.test.tsindex 4c339f95b9..5a3f5d2974 100644--- a/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.test.ts+++ b/packages/maker-core/src/agents/codex/__tests__/device-hosted-guest.test.ts@@ -53,6 +53,8 @@ interface Fixture {providerId?: string;/** app-server 不给功能清单(旧版本或出错)。 */noFeatureList?: boolean;+ /** 宿主提供的任务隧道往来记录。 */+ linkActivity?: DeviceHostedSession['linkActivity'];}/** app-server 的功能清单,分两页返回。 */@@ -237,6 +239,7 @@ async function startHosted(fixture: Fixture) {mirrorRoot,...(fixture.guest ? { guest: true, guestProvider: SHARED_PROVIDER } : {}),...(guestHome ? { guestHome } : {}),+ ...(fixture.linkActivity ? { linkActivity: fixture.linkActivity } : {}),};const started = agent.startSession({sessionId: 'hosted-session',@@ -260,6 +263,11 @@ function threadParams(request: ReturnType<typeof vi.fn>, method: string): Recordreturn params;}+/** host.request 的第三个参数(超时与顺延设置)。 */+function requestOptions(request: ReturnType<typeof vi.fn>, method: string): Record<string, unknown> | undefined {+ return request.mock.calls.find(([called]) => called === method)?.[2] as Record<string, unknown> | undefined;+}+afterEach(async () => {await Promise.all(agents.splice(0).map((agent) => agent.dispose().catch(() => undefined)));vi.restoreAllMocks();@@ -414,6 +422,38 @@ describe('Codex device-hosted guest sessions', () => {await handle.close();});+ it.each([false, true])('lets thread requests keep waiting while the tunnel still has traffic (#5764, resume: %s)', async (resume) => {+ const linkActivity = vi.fn(() => ({+ lastActivityAt: 1_234,+ execRequests: 4,+ execResponses: 3,+ execMaxInFlight: 2,+ httpInFlight: 0,+ }));+ const fixture = await startHosted({ guest: true, resume, linkActivity });+ const handle = await fixture.started;+ const optionsOf = (method: string) => requestOptions(fixture.request, method) as {+ timeoutMs?: number;+ extendWhileProgress?: { lastProgressAt(): number | null; idleMs: number; maxMs: number; describe?(): string };+ } | undefined;+ const thread = optionsOf(resume ? Method.ThreadResume : Method.ThreadStart);+ expect(thread).toMatchObject({ timeoutMs: 60_000, extendWhileProgress: { idleMs: 30_000, maxMs: 300_000 } });+ expect(thread?.extendWhileProgress?.lastProgressAt()).toBe(1_234);+ expect(thread?.extendWhileProgress?.describe?.()).toContain('execution environment answered 3/4 requests');+ await handle.send({ type: 'user', content: 'hi' });+ expect(optionsOf(Method.TurnStart)).toMatchObject({ timeoutMs: 60_000, extendWhileProgress: { idleMs: 30_000 } });+ await handle.close();+ });++ it('keeps the fixed limit when the host provides no tunnel activity', async () => {+ const fixture = await startHosted({ guest: false });+ const handle = await fixture.started;+ const options = requestOptions(fixture.request, Method.ThreadStart);+ expect(options).toMatchObject({ timeoutMs: 60_000 });+ expect(options).not.toHaveProperty('extendWhileProgress');+ await handle.close();+ });+it('refuses a shared user on a provider other than the shared one', async () => {const fixture = await startHosted({ guest: true, providerId: 'openai' });await expect(fixture.started).rejects.toThrow(/^\[REMOTE_AGENT_PROVIDER_NOT_ALLOWED\]/);diff --git a/packages/maker-core/src/agents/codex/app-server/client.test.ts b/packages/maker-core/src/agents/codex/app-server/client.test.tsindex 049a8f6e27..48834174ac 100644--- a/packages/maker-core/src/agents/codex/app-server/client.test.ts+++ b/packages/maker-core/src/agents/codex/app-server/client.test.ts@@ -405,6 +405,89 @@ describe('AppServerClient request timeout', () => {vi.useRealTimers();}});++ describe('extendWhileProgress (#5764)', () => {+ function started() {+ const transport = new FakeTransport();+ const client = new AppServerClient({ createTransport: () => transport, logger });+ client.start();+ const lastId = () => (JSON.parse(transport.lines.at(-1)!) as { id: number }).id;+ return { transport, client, lastId };+ }++ it('keeps waiting past the base timeout while the link still has traffic', async () => {+ vi.useFakeTimers();+ try {+ const { transport, client, lastId } = started();+ let lastProgressAt: number | null = Date.now();+ const request = client.request('thread/start', {}, {+ timeoutMs: 50,+ extendWhileProgress: { lastProgressAt: () => lastProgressAt, idleMs: 30, maxMs: 1_000 },+ });+ for (let elapsed = 0; elapsed < 200; elapsed += 10) {+ lastProgressAt = Date.now();+ await vi.advanceTimersByTimeAsync(10);+ }+ transport.emitLine({ id: lastId(), result: { thread: { id: 't1' } } });+ await expect(request).resolves.toEqual({ thread: { id: 't1' } });+ } finally {+ vi.useRealTimers();+ }+ });++ it('times out once the link goes quiet and reports how long it waited and why', async () => {+ vi.useFakeTimers();+ try {+ const { client } = started();+ let lastProgressAt: number | null = Date.now();+ const request = client.request('thread/start', {}, {+ timeoutMs: 50,+ extendWhileProgress: {+ lastProgressAt: () => lastProgressAt,+ idleMs: 30,+ maxMs: 1_000,+ describe: () => 'execution environment answered 3/4 requests',+ },+ });+ const rejection = expect(request).rejects.toThrow(+ 'codex app-server thread/start timed out after 100ms (execution environment answered 3/4 requests)',+ );+ // 往来持续到 70ms 后停止:50ms 时顺延,最后一次往来后 30ms(100ms)结束。+ for (let elapsed = 0; elapsed < 70; elapsed += 10) {+ lastProgressAt = Date.now() + 10;+ await vi.advanceTimersByTimeAsync(10);+ }+ await vi.advanceTimersByTimeAsync(30);+ await rejection;+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps the base timeout when there is no recent traffic, and stops at maxMs even if traffic continues', async () => {+ vi.useFakeTimers();+ try {+ const { client } = started();+ const quiet = client.request('thread/start', {}, {+ timeoutMs: 50,+ extendWhileProgress: { lastProgressAt: () => null, idleMs: 30, maxMs: 1_000 },+ });+ const quietRejection = expect(quiet).rejects.toThrow('codex app-server thread/start timed out after 50ms');+ await vi.advanceTimersByTimeAsync(50);+ await quietRejection;++ const busy = client.request('thread/start', {}, {+ timeoutMs: 50,+ extendWhileProgress: { lastProgressAt: () => Date.now(), idleMs: 30, maxMs: 200 },+ });+ const busyRejection = expect(busy).rejects.toThrow('codex app-server thread/start timed out after 200ms');+ await vi.advanceTimersByTimeAsync(200);+ await busyRejection;+ } finally {+ vi.useRealTimers();+ }+ });+ });});describe('AppServerClient server requests', () => {diff --git a/packages/maker-core/src/agents/codex/app-server/client.ts b/packages/maker-core/src/agents/codex/app-server/client.tsindex 7db23ca29a..575656c772 100644--- a/packages/maker-core/src/agents/codex/app-server/client.ts+++ b/packages/maker-core/src/agents/codex/app-server/client.ts@@ -45,12 +45,28 @@ export class AppServerRequestTimeoutError extends Error {constructor(public readonly method: string,public readonly timeoutMs: number,+ /** 超时时的诊断(只含计数与耗时),附在消息末尾。 */+ detail?: string,) {- super(`codex app-server ${method} timed out after ${timeoutMs}ms`);+ super(`codex app-server ${method} timed out after ${timeoutMs}ms${detail ? ` (${detail})` : ''}`);this.name = 'AppServerRequestTimeoutError';}}+/**+ * 有进展就顺延的请求上限:到 timeoutMs 时若最近 idleMs 内仍有进展就继续等,直到连续 idleMs 没有+ * 进展,或从发出起等满 maxMs。用于设备托管会话:线程启动要经设备互联逐个读项目文件,慢链路下+ * 合法地超过固定上限(#5764);真正卡住(没有任何往来)时仍按原上限结束。+ */+export interface RequestProgressDeadline {+ /** 最近一次有进展的时间(Date.now 毫秒);没有记录时为 null。 */+ lastProgressAt(): number | null;+ idleMs: number;+ maxMs: number;+ /** 超时时附在错误消息里的诊断。 */+ describe?(): string;+}+/*** Keep a small bounded correlation window for writes that rejected after the* transport may already have handed bytes to the OS / websocket buffer.@@ -357,11 +373,12 @@ export class AppServerClient {/*** 发送一个 JSON-RPC request, 等待对应 id 的 response。* server 返回 error 时 reject 一个携带 code+message 的 Error。+ * `extendWhileProgress` 只在给了 timeoutMs 时生效(见 RequestProgressDeadline)。*/request<R = unknown>(method: string,params?: unknown,- opts?: { timeoutMs?: number },+ opts?: { timeoutMs?: number; extendWhileProgress?: RequestProgressDeadline },): Promise<R> {if (this.closed) {return Promise.reject(new Error(`AppServerClient.request(${method}) after close()`));@@ -400,11 +417,39 @@ export class AppServerClient {};this.pending.set(id, pending);if (timeoutMs !== undefined) {- pending.timeoutId = setTimeout(() => {+ const progress = opts?.extendWhileProgress;+ const startedAt = Date.now();+ let extended = false;+ const expire = (): void => {if (this.pending.get(id) !== pending) return;+ if (progress) {+ const now = Date.now();+ let last: number | null = null;+ try {+ last = progress.lastProgressAt();+ } catch {+ last = null;+ }+ const idleLeft = last === null ? 0 : progress.idleMs - (now - last);+ const capLeft = progress.maxMs - (now - startedAt);+ if (idleLeft > 0 && capLeft > 0) {+ extended = true;+ pending.timeoutId = setTimeout(expire, Math.min(idleLeft, capLeft));+ pending.timeoutId.unref?.();+ return;+ }+ }this.pending.delete(id);- reject(new AppServerRequestTimeoutError(method, timeoutMs));- }, timeoutMs);+ let detail: string | undefined;+ try {+ detail = progress?.describe?.();+ } catch {+ detail = undefined;+ }+ // 没顺延过时照旧报配置的上限;顺延过报实际等了多久。+ reject(new AppServerRequestTimeoutError(method, extended ? Date.now() - startedAt : timeoutMs, detail));+ };+ pending.timeoutId = setTimeout(expire, timeoutMs);pending.timeoutId.unref?.();}transport.writeLine(payload).then(undefined, (err: Error) => {diff --git a/packages/maker-core/src/agents/codex/app-server/host.ts b/packages/maker-core/src/agents/codex/app-server/host.tsindex d4ee0e19fe..1e26df27ee 100644--- a/packages/maker-core/src/agents/codex/app-server/host.ts+++ b/packages/maker-core/src/agents/codex/app-server/host.ts@@ -27,7 +27,7 @@ import { randomUUID } from 'node:crypto';import type { Logger } from '../../../interfaces/logger.js';import type { CodexSessionMcpConfigInput, CodexSubagentRoutingProfile } from '../../base-agent.js';-import { AppServerClient } from './client.js';+import { AppServerClient, type RequestProgressDeadline } from './client.js';import { CODEX_EXTERNAL_AUTH_REFRESH, CodexExternalAuthSession, assertCodexEphemeralAuth, type CodexExternalAuth } from './external-auth.js';import type { Transport } from './transport.js';import {@@ -895,11 +895,12 @@ export class AppServerHost {* `opts.timeoutMs` 按需传入: 裸 RPC 默认**无超时** (协议上 response 可能任意晚),* 但 turn/start 这类「daemon 失联就永远挂住」的关键路径应显式给上限 —* 超时 reject 后上层按 turn 启动失败收口, 而不是让 UI 无限 generating。+ * `extendWhileProgress` 只顺延请求本身的等待, startup 仍按 timeoutMs 计。*/async request<R = unknown>(method: string,params?: unknown,- opts?: { timeoutMs?: number; beforeDispatch?: () => void },+ opts?: { timeoutMs?: number; beforeDispatch?: () => void; extendWhileProgress?: RequestProgressDeadline },): Promise<R> {// 冷启动 / transport 重建时 ensureStarted 本身也可能永不返回 (远端 daemon// bootstrap 挂死 / SSH 通道无响应) — 调用方显式给 timeoutMs 时同样给它diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 5c2e2cc570..abf64a6b4e 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -21,6 +21,7 @@*/import {+ describeDeviceHostedLinkActivity,deviceHostedEnvironmentNote,deviceHostedGuestSessionRoot,isInsideDeviceHostedRoot,@@ -215,7 +216,7 @@ import { resolveForkTurnAnchor } from './fork-turn-anchor.js';import { parseReconnectAttemptMessage } from '../shared/network-error.js';import { extractNonSecretErrorSignals } from '@cindy/maker-shared/error-redaction';import { AppServerHost, CodexNativeInitializationStoppedError, type ThreadEventHandlers, type ThreadSubscription } from './app-server/host.js';-import { AppServerRequestTimeoutError } from './app-server/client.js';+import { AppServerRequestTimeoutError, type RequestProgressDeadline } from './app-server/client.js';import { useCodexHistoryHome, type CodexExternalAuth } from './app-server/external-auth.js';import {isTerminalRateLimitRetryExhaustion,@@ -1201,6 +1202,11 @@ const CODEX_BROWSER_USE_READINESS_PROBE_ATTEMPTS = 2;// (terminal error + Done status)。注意: 超时只代表**我们不再等**, server 侧// 可能实际已建 thread/turn — 迟到事件按 stale turn 丢弃, 不影响 UI 复位。const CRITICAL_THREAD_RPC_TIMEOUT_MS = 60_000;+// 设备托管会话(项目在另一台电脑)的上述 RPC 在任务隧道还有往来时顺延(#5764): 线程启动经设备+// 互联逐个读项目说明与 Skill, 实测约 35 轮串行往返, 慢链路下合法地超过 60s。隧道连续 30s 没有+// 往来、或从发出起等满 5 分钟, 仍按超时收口(错误里带链路计数)。+const HOSTED_THREAD_RPC_IDLE_MS = 30_000;+const HOSTED_THREAD_RPC_MAX_MS = 5 * 60_000;/*** upstream-response-idle watchdog 阈值 — codex 侧对齐 claude-code 的同名机制@@ -6396,6 +6402,24 @@ assertRouteCurrent();};}+ /**+ * thread/start、thread/resume、turn/start 的等待上限。设备托管且宿主提供了隧道往来记录时,链路上+ * 还有往来就顺延(见 HOSTED_THREAD_RPC_IDLE_MS);其它会话保持固定 60s。+ */+ function criticalThreadRpcOptions(): { timeoutMs: number; extendWhileProgress?: RequestProgressDeadline } {+ const linkActivity = hosted?.linkActivity;+ if (!linkActivity) return { timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS };+ return {+ timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS,+ extendWhileProgress: {+ lastProgressAt: () => linkActivity().lastActivityAt,+ idleMs: HOSTED_THREAD_RPC_IDLE_MS,+ maxMs: HOSTED_THREAD_RPC_MAX_MS,+ describe: () => describeDeviceHostedLinkActivity(linkActivity()),+ },+ };+ }+function currentThreadWorkspaceConfig(contextLimit = currentContextLimit()): Pick<ThreadStartParams,| 'approvalPolicy'@@ -6959,7 +6983,7 @@ assertRouteCurrent();const resp = await withMcpDiscoveryContext(() => {assertCurrentHost('thread/start dispatch');return host.request<ThreadStartResponse>(Method.ThreadStart, params, {- timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS,+ ...criticalThreadRpcOptions(),beforeDispatch: () => {assertCurrentHost('thread/start write');startup.threadDispatched = true;@@ -7101,7 +7125,7 @@ assertRouteCurrent();const resp = await withMcpDiscoveryContext(() => {assertCurrentHost('thread/resume dispatch');return host.request<ThreadResumeResponse>(Method.ThreadResume, params, {- timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS,+ ...criticalThreadRpcOptions(),beforeDispatch: () => {assertCurrentHost('thread/resume write');startup.threadDispatched = true;@@ -13452,7 +13476,7 @@ assertRouteCurrent();// 且无人可解(review #844 codex P1)。与正常 turn/start 同款边界。const resp = await host.request<TurnStartResponse>(Method.TurnStart,{ ...turnParams, threadId, ...(continueNativeHistory ? { input: [] } : {}) }, {- timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS,+ ...criticalThreadRpcOptions(),});// **发出后再复检**:RPC 在途期间 Stop / close / 撤单都拦不住它——// 计时器早已清空,cancelOverloadRetry 无从取消;abort() 又因为@@ -13553,7 +13577,7 @@ assertRouteCurrent();let initialStartSettledByCancel = false;try {const resp = await host.request<TurnStartResponse>(Method.TurnStart, turnParams, {- timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS,+ ...criticalThreadRpcOptions(),});markTurnConfigAccepted();adoptUnidentifiedDeadTurn(resp, initialStartSeq);@@ -13599,7 +13623,7 @@ assertRouteCurrent();...(developerInstructions && !useProxyChannel ? { developerInstructions } : {}),};const resumeResp = await host.request<ThreadResumeResponse>(Method.ThreadResume, resumeParams, {- timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS,+ ...criticalThreadRpcOptions(),});if (mutableModel === resumeModel && resumeModel === 'gpt-5' && resumeResp.model) {mutableModel = resumeResp.model;@@ -13655,7 +13679,7 @@ assertRouteCurrent();}log.info('thread/resume after stale daemon ok, retrying turn/start', { threadId });const resp = await host.request<TurnStartResponse>(Method.TurnStart, turnParams, {- timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS,+ ...criticalThreadRpcOptions(),});markTurnConfigAccepted();adoptUnidentifiedDeadTurn(resp, initialStartSeq);diff --git a/packages/maker-core/src/agents/shared/device-hosted.test.ts b/packages/maker-core/src/agents/shared/device-hosted.test.tsindex c65bdee3b2..9dbd27a2be 100644--- a/packages/maker-core/src/agents/shared/device-hosted.test.ts+++ b/packages/maker-core/src/agents/shared/device-hosted.test.ts@@ -8,6 +8,7 @@ import type { DeviceHostedSession } from '../base-agent.js';import {DEVICE_HOSTED_DISALLOWED_CLAUDE_TOOLS,DEVICE_HOSTED_GUEST_CLAUDE_TOOLS,+ describeDeviceHostedLinkActivity,deviceHostedBuiltinToolName,deviceHostedClaudeNote,deviceHostedEnvironmentNote,@@ -268,3 +269,28 @@ describe('device-hosted guest Claude tools', () => {expect(deviceHostedClaudeNote(hosted({ guest: true }), '/local')).not.toContain('WebFetch');});});++describe('describeDeviceHostedLinkActivity (#5764)', () => {+ it('tells a slow but moving link from a stuck request and from no traffic at all', () => {+ expect(describeDeviceHostedLinkActivity({+ lastActivityAt: 9_700,+ execRequests: 169,+ execResponses: 165,+ execMaxInFlight: 81,+ execOldestPending: { method: 'fs/readFile', waitedMs: 1_250 },+ execRoundTripAvgMs: 1_600,+ execRoundTripMaxMs: 4_210,+ httpInFlight: 2,+ }, 10_000)).toBe(+ 'execution environment answered 165/169 requests, oldest unanswered fs/readFile waiting 1.3s, '+ + 'round trip avg 1.6s max 4.2s, peak in flight 81, 2 tool requests in flight, last link activity 0.3s ago',+ );+ expect(describeDeviceHostedLinkActivity({+ lastActivityAt: null,+ execRequests: 0,+ execResponses: 0,+ execMaxInFlight: 0,+ httpInFlight: 0,+ }, 10_000)).toBe('execution environment answered 0/0 requests, peak in flight 0, no link activity yet');+ });+});diff --git a/packages/maker-core/src/agents/shared/device-hosted.ts b/packages/maker-core/src/agents/shared/device-hosted.tsindex b05fef83c0..c279134625 100644--- a/packages/maker-core/src/agents/shared/device-hosted.ts+++ b/packages/maker-core/src/agents/shared/device-hosted.ts@@ -5,11 +5,32 @@import { realpathSync } from 'node:fs';import path from 'node:path';-import type { DeviceHostedSession, PiExtraSpawnConfig } from '../base-agent.js';+import type { DeviceHostedLinkActivity, DeviceHostedSession, PiExtraSpawnConfig } from '../base-agent.js';/** 交给 Pi 内 cindy-bridge 的托管配置(隧道地址、令牌、Agent 主机上的工作目录)。 */export const DEVICE_HOSTED_PI_ENV = 'CINDY_PI_HOSTED';+/**+ * 链路往来写成一句诊断,附在托管会话关键 RPC 的超时错误里:分得清「请求一直在走、只是链路慢」+ * (回复数在涨、往返耗时长)、「某个请求卡住」(最早未回复的请求等了很久)与「链路上根本没有往来」。+ */+export function describeDeviceHostedLinkActivity(activity: DeviceHostedLinkActivity, now = Date.now()): string {+ const seconds = (ms: number) => `${(ms / 1000).toFixed(1)}s`;+ const parts = [`execution environment answered ${activity.execResponses}/${activity.execRequests} requests`];+ if (activity.execOldestPending) {+ parts.push(`oldest unanswered ${activity.execOldestPending.method} waiting ${seconds(activity.execOldestPending.waitedMs)}`);+ }+ if (activity.execRoundTripAvgMs !== undefined && activity.execRoundTripMaxMs !== undefined) {+ parts.push(`round trip avg ${seconds(activity.execRoundTripAvgMs)} max ${seconds(activity.execRoundTripMaxMs)}`);+ }+ parts.push(`peak in flight ${activity.execMaxInFlight}`);+ if (activity.httpInFlight > 0) parts.push(`${activity.httpInFlight} tool requests in flight`);+ parts.push(activity.lastActivityAt === null+ ? 'no link activity yet'+ : `last link activity ${seconds(Math.max(0, now - activity.lastActivityAt))} ago`);+ return parts.join(', ');+}+/*** 去掉结尾的斜杠。不用正则:`x+$` 这类模式在不可控输入上是多项式回溯(CodeQL* “Polynomial regular expression used on uncontrolled data”)。diff --git a/packages/maker-core/src/index.ts b/packages/maker-core/src/index.tsindex 4548161d77..c9b8262732 100644--- a/packages/maker-core/src/index.ts+++ b/packages/maker-core/src/index.ts@@ -51,6 +51,8 @@ export type {} from './agents/pi/transport.js';// pi 远端 agentHome 文件操作原语(host 经 SSH 实现)。export type { PiRemoteFileOps } from './agents/base-agent.js';+// 设备托管会话的链路往来快照(host 的任务隧道记录)。+export type { DeviceHostedLinkActivity } from './agents/base-agent.js';// coreexport * from './session.js';