Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/architecture/delegation-worktrees.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# 委派的独立 Git worktree


原生 Codex 子会话沿用父会话工作目录时,也沿用父会话已登记的项目 ID。指定其他工作目录或创建独立 worktree 时,由目标工作区决定项目归属。委派给外部 Harness 时,子会话沿用选定的工作目录,项目 ID 不从父会话继承。

`delegate start --worktree <branch>` 在 CLI 所在机器创建分支和 Git worktree,将新路径作为该次委派的 `cwd`。HTTP `POST /v1/delegate/start` 和 MCP `delegate_start` 使用 `worktree`、可选 `base` 在接收请求的 Host 上创建。CLI 和 Host 共用 `delegation-worktree.ts` 的创建与失败处理逻辑。这不是 Harness 原生隔离选项,也不改变未指定 worktree 的委派行为。

```sh
Expand Down
2 changes: 2 additions & 0 deletions docs/platforms/remote/remote-ssh-host.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ If you only use Codex's built-in remote coding features, you do not need codexho

If Desktop or Web uses a custom Host data directory, run `codexhost remote install --shared-data /absolute/path/to/host-data` on that computer, then restart the SSH listener. Installation captures `CODEXHOST_SHARED_DATA_DIR` (or a non-SSH `CODEXHOST_DATA_DIR`) when no option is supplied and preserves the saved selection on reinstall. This shared directory is stored in the remote manifest and SSH profile; it never replaces the separate SSH-only data directory. Native agents use the shared owner for delegation reads, sends, cancellation and waits too; historical SSH-owned parents keep their local delegation owner.

To run native Codex on the same Host as local Desktop and Web, run `codexhost remote install --native-host shared` on the remote machine and restart the SSH listener. Both runtimes must support the native relay. Each viewer attaches to the same native backend. If the shared Host is unavailable, native requests fail until it is ready. Historical SSH-only external Threads keep their existing owner.

### Image and file attachments

External Harnesses continue to receive text and file paths, not Harness-specific image inputs. Ordinary files use Desktop's native upload and remote path references. Reading files, interpreting images, and parsing their formats depend on the Harness's tools and the selected model.
Expand Down
2 changes: 2 additions & 0 deletions docs/platforms/remote/remote-ssh-host.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ Windows 原生 codexhost 不会发现 WSL 内安装的 Harness。如果本地连

如果 Desktop 或 Web 使用自定义 Host 数据目录,在该机器执行 `codexhost remote install --shared-data /绝对路径/host-data`,然后重启 SSH 监听器。未传选项时,安装会读取 `CODEXHOST_SHARED_DATA_DIR` 或非 SSH 环境中的 `CODEXHOST_DATA_DIR`;重新安装会保留已保存的选择。共享目录写入远程 manifest 和 SSH profile,不覆盖独立的 SSH 专用数据目录。原生 Agent 对共享会话的委派读取、发送、取消和等待也路由到共享执行方;历史 SSH 会话作为父会话时仍保留原有委派归属。

如需让 SSH 项目中的原生 Codex 与本机 Desktop、Web 共用执行方,在远端执行 `codexhost remote install --native-host shared`,然后重启 SSH 监听器。两端运行时都需支持原生转发。每个客户端独立接入同一个原生后端。共享 Host 不可用时,原生请求会报错,历史 SSH 专用外部会话保留原归属。

### 图片与文件附件

外部 Harness 继续接收文字及文件路径,不通过各 Harness 的专用图片接口发送。普通文件沿用 Desktop 原生上传和远程路径引用;能否读取文件、理解图片或解析其格式,由 Harness 的工具及所选模型决定。
Expand Down
50 changes: 37 additions & 13 deletions packages/host-runtime/src/app-server-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1347,10 +1347,23 @@ export class AppServerHost {
),
sendOfficial: (input) => this.#sendOfficialDelegationThread(input),
cancelOfficial: (input) => this.#cancelOfficialDelegationThread(input),
startOfficial: (input, resolveConfiguration) =>
this.#startOfficialDelegation(input, resolveConfiguration),
startOfficial: (input, resolveConfiguration, readParent) =>
this.#startOfficialDelegation(input, resolveConfiguration, readParent),
listOfficial: (input) => this.#listDelegationThreads(input),
officialThreadMetadata: (threadId) => this.#readOfficialThreadMetadata(threadId),
officialThreadMetadata: (threadId) => this.#readThreadMetadata(threadId),
sharedParentMetadata: async (threadId) => {
const bridge = options.sharedThreads;
if (!bridge?.options.delegateCreates) return null;
const harnessId = (await bridge.ownership([threadId])).get(threadId);
if (!harnessId) return null;
const parent = await this.#readThreadMetadata(threadId, bridge);
if (!parent)
throw new DelegationControlError(
"DELEGATION_FAILED",
"Unable to read the shared parent Thread before delegation",
);
return { ...parent, harnessId };
},
activeOfficialParents: () => [...this.#activeOfficialTurns.keys()],
externalThreadBusy: (thread) => this.#externalThreadBusy(thread),
externalQueueWaiting: (thread) => this.#externalQueue.has(thread.id),
Expand Down Expand Up @@ -3072,16 +3085,23 @@ export class AppServerHost {
return thread !== null || childDelegation !== null || delegation !== null;
}

async #readOfficialThreadMetadata(threadId: string): Promise<{ cwd?: string; title?: string }> {
const response = await this.#requestOfficial("thread/read", { threadId, includeTurns: false });
if (isRecord(response.error)) return {};
async #readThreadMetadata(
threadId: string,
owner?: SharedThreadBridge,
): Promise<{ cwd?: string; title?: string; projectId?: string } | null> {
const params = { threadId, includeTurns: false };
const response = owner
? await owner.request("thread/read", params)
: await this.#requestOfficial("thread/read", params);
const result = isRecord(response.result) ? response.result : null;
const thread = result && isRecord(result.thread) ? result.thread : null;
if (!thread) return {};
if (!thread) return null;
const title =
typeof thread.name === "string" && thread.name.trim() ? thread.name : thread.preview;
const projectId = typeof thread.projectId === "string" ? thread.projectId.trim() : undefined;
return {
...(typeof thread.cwd === "string" && thread.cwd.trim() ? { cwd: thread.cwd } : {}),
...(projectId ? { projectId } : {}),
...(typeof title === "string" && title.trim() ? { title } : {}),
};
}
Expand Down Expand Up @@ -3195,6 +3215,7 @@ export class AppServerHost {
model: HarnessModelRef | undefined,
inspected?: HarnessInspectResult,
) => ReturnType<typeof resolveDelegationConfiguration>,
readParent: () => Promise<{ harnessId: string; projectId?: string }>,
): Promise<DelegationStartResult> {
let inspected: HarnessInspectResult | undefined;
const requestedModel = input.officialModelArgument ?? input.model;
Expand Down Expand Up @@ -3256,18 +3277,22 @@ export class AppServerHost {
turnId: turnId ?? "pending",
harnessId: "codex",
deepLink: `codex://threads/${existing.childHostThreadId}`,
cwd: path.resolve(input.cwd),
status: existing.status,
next: {
read: `codexhost thread read ${existing.childHostThreadId}`,
wait: `codexhost thread wait ${existing.childHostThreadId} --timeout-ms 30000`,
},
};
}
const parent = await readParent();
const selection = await resolveConfiguration(explicitModel, inspected);
const { model, thinkingOptionId } = selection;
const nativeSelection = model ? officialCodexModelSelection(model) : undefined;
const cwd = path.resolve(input.cwd);
const started = await this.#requestOfficial("thread/start", {
cwd: input.cwd,
cwd,
...(parent.projectId ? { projectId: parent.projectId } : {}),
...nativeSelection,
approvalPolicy: "never",
sandbox: "danger-full-access",
Expand All @@ -3284,12 +3309,11 @@ export class AppServerHost {
let turnId: string;
try {
// Persist the delegation lineage before turn/start so hop enforcement closes the first-turn window.
const source = await this.#repository.find(input.parentThreadId);
await this.#repository.createDelegation({
delegationId,
parentHostThreadId: hostThreadIdSchema.parse(input.parentThreadId),
childHostThreadId: hostThreadIdSchema.parse(threadId),
sourceHarnessId: source?.harnessId ?? harnessIdSchema.parse("codex"),
sourceHarnessId: harnessIdSchema.parse(parent.harnessId),
targetHarnessId: harnessIdSchema.parse("codex"),
status: "creating",
...(input.requestId ? { requestId: input.requestId } : {}),
Expand Down Expand Up @@ -3332,7 +3356,7 @@ export class AppServerHost {
harnessId: "codex",
deepLink: `codex://threads/${threadId}`,
status: pendingTerminal ?? "running",
cwd: thread && typeof thread.cwd === "string" ? thread.cwd : input.cwd,
cwd: thread && typeof thread.cwd === "string" ? thread.cwd : cwd,
...(model || thinkingOptionId
? {
configuration: {
Expand Down Expand Up @@ -4778,8 +4802,8 @@ export class AppServerHost {
}
let catalog: HarnessCommandCatalog;
try {
const metadata = await this.#readOfficialThreadMetadata(params.data.threadId);
if (!metadata.cwd) throw new Error("Codex Thread has no Skill workspace");
const metadata = await this.#readThreadMetadata(params.data.threadId);
if (!metadata?.cwd) throw new Error("Codex Thread has no Skill workspace");
const response = await this.#requestOfficial("skills/list", { cwds: [metadata.cwd] });
if (isRecord(response.error)) throw new Error(String(response.error.message));
catalog = nativeThreadCommands(isRecord(response.result) ? response.result : {});
Expand Down
28 changes: 19 additions & 9 deletions packages/host-runtime/src/client-channel-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,10 @@ export async function startClientChannelServer(options: {
environment: NodeJS.ProcessEnv;
directory?: string;
owner?: "service";
shutdown?: { runningTasks(): number; stop(): void };
shutdown?: { runningTasks(): number; stop(): void; isStopping?(): boolean };
/** When provided, advertises `capabilities.peerDelegation=1` and routes internal peer delegation exclusively here. */
peerDelegation?: (params: unknown) => Promise<{ result: JsonValue }>;
nativeSession?: (streams: RemoteAppServerSessionStreams) => RemoteAppServerSession;
externalSession?: (streams: RemoteAppServerSessionStreams) => RemoteAppServerSession;
desktopSession?: (
streams: RemoteAppServerSessionStreams,
Expand Down Expand Up @@ -149,22 +150,31 @@ export async function startClientChannelServer(options: {
const desktop = new WebSocketServer({ noServer: true, maxPayload: 128 * 1024 * 1024 });
const desktopSessions = new Set<ReturnType<typeof attachRemoteAppServerSession>>();
let closing: Promise<void> | undefined;
const routes = new Map<string, typeof options.desktopSession>([
["/v1/desktop", options.desktopSession],
["/v1/external", options.externalSession],
["/v1/native", options.nativeSession],
]);
server.on("upgrade", (request, socket, head) => {
const session =
request.url === "/v1/external"
? options.externalSession
: request.url === "/v1/desktop"
? options.desktopSession
: undefined;
if (closing || !session || !authorized(request)) {
const session = routes.get(request.url ?? "");
if (!authorized(request)) {
socket.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
return;
}
if (!session) {
socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n");
return;
}
if (closing || options.shutdown?.isStopping?.()) {
socket.end("HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n");
return;
}
desktop.handleUpgrade(request, socket, head, (connection) => {
try {
const binding = attachRemoteAppServerSession({
socket: connection,
framing: "ndjson",
framing: request.url === "/v1/native" ? "messages" : "ndjson",
drainInputOnDisconnect: request.url !== "/v1/native",
diagnosticOutput: process.stderr,
createSession: (streams) => session(streams, request),
});
Expand Down
20 changes: 17 additions & 3 deletions packages/host-runtime/src/codex-runtime/official-runtime-owner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ const object = (value: unknown): value is JsonObject =>
typeof value === "object" && value !== null && !Array.isArray(value);
const requestKey = (id: string | number): string => JSON.stringify([typeof id, id]);
class OfficialThreadRestorationError extends Error {}
export class RetiredOfficialServerRequestError extends Error {
constructor() {
super("Retired official server request");
}
}
const RESUME_FIELDS = new Set([
"model",
"modelProvider",
Expand Down Expand Up @@ -94,6 +99,10 @@ export class OfficialRuntimeOwner {
return this.#generation;
}

get activeThreadIds(): readonly string[] {
return [...this.#activeTurns];
}

get hasActiveWork(): boolean {
return this.gate.busy || this.#activeTurns.size > 0;
}
Expand Down Expand Up @@ -142,8 +151,12 @@ export class OfficialRuntimeOwner {
for (const client of clients) {
// Attach output immediately. Native notifications and early process
// failure must not be lost merely because Desktop initialize has not arrived.
await this.#connection(client);
if (client.initialization) await this.#initialize(client, client.initialization);
try {
await this.#connection(client);
if (client.initialization) await this.#initialize(client, client.initialization);
} catch (error) {
if (this.#clients.has(client)) throw error;
}
}
if (generation !== this.#generation || this.#phase !== "starting")
throw new OfficialAdmissionError("unavailable");
Expand Down Expand Up @@ -383,7 +396,7 @@ export class OfficialRuntimeOwner {
!client.runtime ||
client.runtime.generation !== this.#generation
)
throw new Error("Retired official server request");
throw new RetiredOfficialServerRequestError();
await client.runtime.send({ ...value, id: original });
client.serverRequests.delete(String(value.id));
return;
Expand Down Expand Up @@ -500,6 +513,7 @@ export class OfficialRuntimeOwner {
) {
client.threads.delete(params.threadId);
this.#threadModelSettings.delete(params.threadId);
if (method !== "thread/unsubscribe") this.#activeTurns.delete(params.threadId);
}
if (
!["thread/start", "thread/resume", "thread/fork"].includes(method) ||
Expand Down
Loading
Loading