Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

feat(coding-agent): direct session transport between TUI and worker (ENG-5817) (#1926)

Sebastian Müller173d845a56f6
diff --git a/packages/coding-agent/.changes/eng-5817-direct-session-transport.md b/packages/coding-agent/.changes/eng-5817-direct-session-transport.md
new file mode 100644
index 0000000000..2d49f720b0
--- /dev/null
+++ b/packages/coding-agent/.changes/eng-5817-direct-session-transport.md
@@ -0,0 +1,2 @@
+- Added a direct session transport: the TUI now talks to its session's worker over a supervisor-issued single-use ticket, falls back to supervisor routing on any direct-path failure, and keeps the session streaming while a lost supervisor socket reconnects in the background.
+- Workers bind their identity to a fresh per-process instance id, enforced only when the authenticating supervisor presents one, so a downgraded supervisor can still adopt live workers.
diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.ts
index 3c1a744f57..e90b2e5dcc 100644
--- a/packages/coding-agent/src/main.ts
+++ b/packages/coding-agent/src/main.ts
@@ -78,6 +78,7 @@ import { DaemonSessionCreateError, deserializeDaemonCreateError } from "./modes/
import { collectDaemonClientEnv, collectDaemonLaunchEnv } from "./modes/daemon/daemon-protocol.js";
import {
DAEMON_WORKER_ACTIVE_SESSION_ID_ENV,
+ daemonWorkerInstanceId,
isDaemonWorkerProcess,
requireDaemonWorkerAuthenticationToken,
waitForDaemonWorkerStartupGate,
@@ -1330,6 +1331,7 @@ export async function main(args: string[], options?: MainOptions) {
createRuntime,
worker: {
authenticationToken: requireDaemonWorkerAuthenticationToken(),
+ workerInstanceId: daemonWorkerInstanceId(),
restoreActiveSessionId: process.env[DAEMON_WORKER_ACTIVE_SESSION_ID_ENV],
},
});
diff --git a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
index 11486c17f3..722c2895be 100644
--- a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
+++ b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts
@@ -23,7 +23,7 @@ import type { SessionStats } from "../../core/session-stats.js";
import { AgentsViewRosterStore, STALE_ROSTER_DAEMON_MESSAGE } from "../agents-view/roster-store.js";
import {
DaemonCapabilityUnavailableError,
- type DaemonClient,
+ type DaemonTransportClient,
getDaemonSocketCloseReason,
} from "../daemon/daemon-client.js";
import { deserializeDaemonError } from "../daemon/daemon-errors.js";
@@ -39,6 +39,12 @@ import {
type DaemonSessionSnapshot,
isUnknownDaemonCommandError,
} from "../daemon/daemon-protocol.js";
+import {
+ createDaemonSessionTransport,
+ DaemonControlPlaneTransportError,
+ DaemonDirectTransportClosedError,
+ DaemonRoutedClient,
+} from "../daemon/daemon-routed-client.js";
import type { SessionSummary } from "../daemon/daemon-session-list.js";
import { listDaemonHeartbeats } from "../daemon/heartbeat-catalog.js";
import {
@@ -113,7 +119,7 @@ const UPDATE_RECONNECT_TIMEOUT_MS = 120000;
const UPDATE_RECONNECT_RETRY_MS = 100;
const MAX_COMPLETED_SNAPSHOTS = 128;
const OWNED_SESSION_DISPOSE_RECONNECT_WAIT_MS = 10_000;
-const updateTransportReconnects = new WeakMap<DaemonClient, Promise<void>>();
+const updateTransportReconnects = new WeakMap<DaemonTransportClient, Promise<void>>();
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
@@ -127,7 +133,7 @@ function formatErrorSentence(error: unknown): string {
return /[.!?]$/.test(message) ? message : `${message}.`;
}
-function reconnectDaemonTransportAfterUpdate(client: DaemonClient): Promise<void> {
+function reconnectDaemonTransportAfterUpdate(client: DaemonTransportClient): Promise<void> {
const existing = updateTransportReconnects.get(client);
if (existing) {
return existing;
@@ -159,6 +165,8 @@ function reconnectDaemonTransportAfterUpdate(client: DaemonClient): Promise<void
export interface DaemonAgentConnectionOptions {
closeClientOnDispose?: boolean;
+ /** Secondary watchers pass false to stay on the shared control-plane socket. */
+ directTransport?: boolean;
/** Restart/probe the detached supervisor after a transient socket loss. */
recoverDaemon?: () => Promise<void>;
/** Bound supervisor recovery before surfacing a fatal connection error. */
@@ -242,12 +250,14 @@ export class DaemonAgentConnection implements AgentConnection {
private readonly ignoredSnapshotIds = new Set<string>();
private rosterStore: AgentsViewRosterStore | undefined;
private reconnectPromise?: Promise<void>;
+ private initialAttachPending = false;
+ private initialControlPlaneClose?: Error;
private readonly definitiveRequestErrors = new WeakSet<Error>();
private disposing = false;
private disposed = false;
constructor(
- private readonly client: DaemonClient,
+ private readonly client: DaemonTransportClient,
private activeSessionId: string,
private readonly options: DaemonAgentConnectionOptions = {},
) {
@@ -267,52 +277,97 @@ export class DaemonAgentConnection implements AgentConnection {
});
});
this.captureDaemonLogPath();
- this.unsubscribeDaemonClose = this.client.onClose((error) => {
- const invalidatedInputPause = this.sessionInputPauses.size > 0;
+ this.unsubscribeDaemonClose = this.client.onClose((error) => this.handleTransportClose(error));
+ }
+
+ private handleTransportClose(error: Error): void {
+ const directSessionSurvives =
+ this.client instanceof DaemonRoutedClient &&
+ this.client.hasDirectTransport &&
+ !(error instanceof DaemonDirectTransportClosedError);
+ const invalidatedInputPause = !directSessionSurvives && this.sessionInputPauses.size > 0;
+ if (!directSessionSurvives) {
this.sessionInputPauses.clear();
this.sessionInputPauseGeneration++;
this.rejectSnapshotAssemblies(error);
- if (this.disposed || this.terminalCloseEmitted) {
- return;
- }
- if (invalidatedInputPause) {
- this.terminalCloseEmitted = true;
- void this.emit({
- type: "closed",
- error: "Daemon connection closed while session input was paused; the fence was invalidated.",
- });
- return;
- }
- const closeReason = getDaemonSocketCloseReason(error);
- if (closeReason === "shutdown") {
- this.terminalCloseEmitted = true;
- void this.emit({ type: "closed", error: this.formatDaemonSessionClosedError("shutdown") });
- return;
- }
- if ((this.updateRestartPending || closeReason === "update") && !this.updateReconnectFailed) {
- this.updateRestartPending = true;
- void this.reconnectAfterUpdate();
- return;
- }
- if (this.options.recoverDaemon) {
- void this.reconnect(error);
- return;
- }
+ }
+ if (this.initialAttachPending) {
+ // attach() owns failure handling until the initial attach settles.
+ if (directSessionSurvives) this.initialControlPlaneClose = error;
+ return;
+ }
+ if (this.disposed || this.terminalCloseEmitted) {
+ return;
+ }
+ // A lost direct link invalidates the fence (holders learn via the generation bump) yet the session falls back.
+ if (invalidatedInputPause && !(error instanceof DaemonDirectTransportClosedError)) {
this.terminalCloseEmitted = true;
- void this.emit({ type: "closed", error: this.formatDaemonConnectionClosedError(error) });
- });
+ void this.emit({
+ type: "closed",
+ error: "Daemon connection closed while session input was paused; the fence was invalidated.",
+ });
+ return;
+ }
+ // An authoritative shutdown/update reason outranks the surviving direct link.
+ const closeReason = getDaemonSocketCloseReason(error);
+ if (closeReason === "shutdown") {
+ this.terminalCloseEmitted = true;
+ void this.emit({ type: "closed", error: this.formatDaemonSessionClosedError("shutdown") });
+ return;
+ }
+ if ((this.updateRestartPending || closeReason === "update") && !this.updateReconnectFailed) {
+ this.updateRestartPending = true;
+ void this.reconnectAfterUpdate();
+ return;
+ }
+ // A direct-transport loss is never itself a session loss: fall back through a supervisor re-attach.
+ if (directSessionSurvives || error instanceof DaemonDirectTransportClosedError || this.options.recoverDaemon) {
+ void this.reconnect(error);
+ return;
+ }
+ this.terminalCloseEmitted = true;
+ void this.emit({ type: "closed", error: this.formatDaemonConnectionClosedError(error) });
}
static async attach(
- client: DaemonClient,
+ client: DaemonTransportClient,
activeSessionId: string,
options?: DaemonAgentConnectionOptions,
): Promise<DaemonAgentConnection> {
- const connection = new DaemonAgentConnection(client, activeSessionId, options);
+ const transport = await createDaemonSessionTransport(
+ client,
+ activeSessionId,
+ options?.ownedSession === true || options?.directTransport === false,
+ );
+ const connection = new DaemonAgentConnection(transport, activeSessionId, options);
+ connection.initialAttachPending = true;
try {
- await connection.attach();
+ try {
+ await connection.attach();
+ } catch (error) {
+ if (!(transport instanceof DaemonRoutedClient)) throw error;
+ transport.fallbackToSupervisor();
+ try {
+ // This retry owns its failure; a parked request would pend the attach forever.
+ await connection.attach({ recoverable: false });
+ } catch (retryError) {
+ // A control-plane close saved during the window is the authoritative cause.
+ throw connection.initialControlPlaneClose ?? retryError;
+ }
+ }
+ connection.initialAttachPending = false;
+ const initialControlPlaneClose = connection.initialControlPlaneClose;
+ connection.initialControlPlaneClose = undefined;
+ if (initialControlPlaneClose) {
+ // No listeners exist yet: a terminal close rejects the attach; the rest replays through the one handler.
+ if (getDaemonSocketCloseReason(initialControlPlaneClose) === "shutdown") {
+ throw initialControlPlaneClose;
+ }
+ connection.handleTransportClose(initialControlPlaneClose);
+ }
return connection;
} catch (error) {
+ connection.initialAttachPending = false;
await connection.dispose();
throw error;
}
@@ -1318,6 +1373,9 @@ export class DaemonAgentConnection implements AgentConnection {
launchEnv: this.options.ownedSession ? collectDaemonLaunchEnv() : undefined,
telemetryDisabled: this.options.telemetryDisabled,
});
+ // Reattach rebinds the connection (and drops any direct link); pauses on the old session are gone.
+ this.sessionInputPauses.clear();
+ this.sessionInputPauseGeneration++;
reattached = true;
this.activeSessionId = result.activeSessionId;
this.activeSideQuestionIds.clear();
@@ -1449,7 +1507,12 @@ export class DaemonAgentConnection implements AgentConnection {
// attach() rejects for an unknown/exited session — treat that as unreachable.
let connection: DaemonAgentConnection;
try {
- connection = await DaemonAgentConnection.attach(this.client, activeSessionId, { closeClientOnDispose: false });
+ const watchClient =
+ this.client instanceof DaemonRoutedClient ? this.client.controlPlaneTransport : this.client;
+ connection = await DaemonAgentConnection.attach(watchClient, activeSessionId, {
+ closeClientOnDispose: false,
+ directTransport: false,
+ });
} catch {
return undefined;
}
@@ -1521,10 +1584,21 @@ export class DaemonAgentConnection implements AgentConnection {
}
this.reconnectPromise = (async () => {
void this.emit({ type: "connection_status", status: "reconnecting", error: cause.message });
- const deadline = Date.now() + (this.options.reconnectTimeoutMs ?? DAEMON_RECONNECT_TIMEOUT_MS);
+ const timeoutMs = this.options.reconnectTimeoutMs ?? DAEMON_RECONNECT_TIMEOUT_MS;
+ let deadline: number | undefined;
let attempt = 0;
let lastError: Error = cause;
- while (!this.disposed && Date.now() < deadline) {
+ while (!this.disposed) {
+ // A held direct link owns session liveness: control-plane recovery retries unbounded,
+ // and the bounded session-plane deadline arms only once the direct link is gone.
+ const directSessionHeld = this.client instanceof DaemonRoutedClient && this.client.hasDirectTransport;
+ if (directSessionHeld) {
+ deadline = undefined;
+ } else {
+ deadline ??= Date.now() + timeoutMs;
+ if (Date.now() >= deadline) break;
+ }
+ let controlPlaneHandshakeComplete = false;
try {
await this.options.recoverDaemon?.();
if (this.disposed) {
@@ -1532,6 +1606,23 @@ export class DaemonAgentConnection implements AgentConnection {
}
await this.client.connect(1000);
await this.client.waitForHello(3000);
+ controlPlaneHandshakeComplete = true;
+ if (directSessionHeld) {
+ // The roster subscription is a control-plane accessory; its usual rebind seam (attach) is skipped while held.
+ if (this.rosterStore) await this.rosterStore.attach(this.client).catch(() => undefined);
+ // One check after the last await, against the close handler's own dispatch outputs:
+ // terminal closes set terminalCloseEmitted, update closes set updateRestartPending
+ // (restoration owns the client), and recoverable closes joined this loop.
+ if (this.disposed || this.terminalCloseEmitted || this.updateRestartPending) {
+ return;
+ }
+ if (this.client instanceof DaemonRoutedClient && this.client.hasDirectTransport) {
+ void this.emit({ type: "connection_status", status: "connected" });
+ return;
+ }
+ // The direct link died mid-recovery: rerun as a bounded session-plane reconnect.
+ continue;
+ }
// This loop owns the retry: a socket close must reject these instead of parking them behind a hello it can never produce.
await this.attach({ recoverable: false });
if (!this.disposed) {
@@ -1545,17 +1636,28 @@ export class DaemonAgentConnection implements AgentConnection {
if (this.disposed) {
return;
}
- this.client.resetTransportForReconnect();
- const remainingMs = deadline - Date.now();
- if (remainingMs <= 0) {
+ // A direct-half failure must not tear down a control-plane socket with a completed handshake.
+ const shouldResetControlPlane =
+ !(this.client instanceof DaemonRoutedClient) ||
+ !controlPlaneHandshakeComplete ||
+ error instanceof DaemonControlPlaneTransportError ||
+ !this.client.isControlPlaneReady;
+ if (shouldResetControlPlane) this.client.resetTransportForReconnect();
+ if (deadline !== undefined && deadline - Date.now() <= 0) {
break;
}
- const delayMs = Math.min(remainingMs, 2000, 100 * 2 ** Math.min(attempt, 5));
+ const delayMs = Math.min(
+ ...(deadline !== undefined ? [deadline - Date.now()] : []),
+ 2000,
+ 100 * 2 ** Math.min(attempt, 5),
+ );
attempt++;
await new Promise((resolveDelay) => setTimeout(resolveDelay, delayMs));
}
}
if (!this.disposed) {
+ this.sessionInputPauses.clear();
+ this.sessionInputPauseGeneration++;
this.client.close();
await this.emit({ type: "closed", error: `Daemon reconnection failed: ${lastError.message}` });
}
@@ -1572,7 +1674,7 @@ export class DaemonAgentConnection implements AgentConnection {
private async requestData<T>(
command: DaemonCommandBody,
timeoutMs?: number,
- options?: Parameters<DaemonClient["request"]>[2],
+ options?: Parameters<DaemonTransportClient["request"]>[2],
): Promise<T> {
const response = await this.client.request(command, timeoutMs, options);
if (!response.success) {
diff --git a/packages/coding-agent/src/modes/agents-view/roster-store.ts b/packages/coding-agent/src/modes/agents-view/roster-store.ts
index 694e1cde6f..901a3a2c91 100644
--- a/packages/coding-agent/src/modes/agents-view/roster-store.ts
+++ b/packages/coding-agent/src/modes/agents-view/roster-store.ts
@@ -1,6 +1,6 @@
import type { AgentRosterEntry } from "../daemon/agent-roster.js";
import { sessionSummaryFromRosterEntry } from "../daemon/agent-roster.js";
-import type { DaemonClient, DaemonHello } from "../daemon/daemon-client.js";
+import type { DaemonHello, DaemonTransportClient } from "../daemon/daemon-client.js";
import type { DaemonOutbound } from "../daemon/daemon-protocol.js";
import type { SessionSummary } from "../daemon/daemon-session-list.js";
@@ -10,14 +10,14 @@ export const STALE_ROSTER_DAEMON_MESSAGE =
export class AgentsViewRosterStore {
private readonly entries = new Map<string, AgentRosterEntry>();
private readonly listeners = new Set<() => void>();
- private client: DaemonClient | undefined;
+ private client: DaemonTransportClient | undefined;
private unsubscribeMessage: (() => void) | undefined;
private emitScheduled = false;
private subscribed = false;
private subscribedHello: DaemonHello | undefined;
private attachChain: Promise<unknown> = Promise.resolve();
- async attach(client: DaemonClient): Promise<boolean> {
+ async attach(client: DaemonTransportClient): Promise<boolean> {
// Serialized: a stale attempt settling late must not detach a newer subscription's listener.
const run = () => this.attachToClient(client);
const chained = this.attachChain.then(run, run);
@@ -25,7 +25,7 @@ export class AgentsViewRosterStore {
return chained;
}
- private async attachToClient(client: DaemonClient): Promise<boolean> {
+ private async attachToClient(client: DaemonTransportClient): Promise<boolean> {
if (client.isConnected && client.hello === undefined) await client.waitForHello();
if (!client.supportsServerCapability("agent_roster")) {
this.detachFromClient();
@@ -44,7 +44,7 @@ export class AgentsViewRosterStore {
if (pendingUpdates) pendingUpdates.push(message);
else this.applyUpdate(message.changed, message.removed, message.resync);
});
- let response: Awaited<ReturnType<DaemonClient["request"]>>;
+ let response: Awaited<ReturnType<DaemonTransportClient["request"]>>;
try {
// Not parkable: the awaiting reconnect loop must see a close as a rejection.
response = await client.request({ type: "roster_subscribe" }, 30000, { recoverable: false });
diff --git a/packages/coding-agent/src/modes/daemon/active-session-state.ts b/packages/coding-agent/src/modes/daemon/active-session-state.ts
index 02a5427d4a..f71711831a 100644
--- a/packages/coding-agent/src/modes/daemon/active-session-state.ts
+++ b/packages/coding-agent/src/modes/daemon/active-session-state.ts
@@ -22,6 +22,7 @@ export interface DaemonSocketClient {
/** A push hit backpressure; one full-roster resync goes out on drain. */
rosterResyncPending?: boolean;
authenticated?: boolean;
+ authenticationRole?: "supervisor" | "session_client";
transport?: "jsonl" | "private-framed";
snapshotStreaming?: boolean;
snapshotActiveSessionIds?: Set<string>;
diff --git a/packages/coding-agent/src/modes/daemon/agent-roster.ts b/packages/coding-agent/src/modes/daemon/agent-roster.ts
index 800c865069..6fd855cb4d 100644
--- a/packages/coding-agent/src/modes/daemon/agent-roster.ts
+++ b/packages/coding-agent/src/modes/daemon/agent-roster.ts
@@ -89,6 +89,7 @@ export function passivatedWorkerRosterEntry(
): WorkerRosterEntry {
const {
activeSessionId,
+ directAttachedClients,
hasActiveHeartbeat,
hasRegisteredHeartbeat,
hasRegisteredCronJob,
diff --git a/packages/coding-agent/src/modes/daemon/daemon-client.ts b/packages/coding-agent/src/modes/daemon/daemon-client.ts
index fdfd6255e6..b5ded67982 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-client.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-client.ts
@@ -18,11 +18,12 @@ import {
type DaemonServerCapability,
getDaemonCommandCompatibilities,
isDaemonMutatingCommand,
+ meetsDaemonCommandCompatibility,
} from "./daemon-protocol.js";
import type { DaemonWorkerCommand, DaemonWorkerCommandBody } from "./daemon-worker-protocol.js";
type DistributiveOmit<T, K extends keyof T> = T extends unknown ? Omit<T, K> : never;
-type DaemonCommandBody = DistributiveOmit<DaemonCommand, "id">;
+export type DaemonCommandBody = DistributiveOmit<DaemonCommand, "id">;
type DaemonWireCommandBody = DaemonCommandBody | DaemonWorkerCommandBody;
@@ -106,6 +107,26 @@ export interface DaemonClientReconnectOptions {
onStatus?: (status: DaemonClientReconnectStatus) => void;
}
+export interface DaemonTransportClient {
+ readonly hello: DaemonHello | undefined;
+ readonly isConnected: boolean;
+ supportsServerCapability(capability: DaemonServerCapability): boolean;
+ waitForHello(timeoutMs?: number): Promise<DaemonHello>;
+ connect(timeoutMs?: number): Promise<void>;
+ reconnect(timeoutMs?: number): Promise<void>;
+ disconnectForReconnect(reason: DaemonClosingReason): void;
+ resetTransportForReconnect(): void;
+ onMessage(listener: DaemonClientMessageListener): () => void;
+ onClose(listener: DaemonClientCloseListener): () => void;
+ enableRequestRecovery(): void;
+ request(
+ command: DaemonCommandBody,
+ timeoutMs?: number,
+ options?: DaemonClientRequestOptions,
+ ): Promise<DaemonResponse>;
+ close(): void;
+}
+
const DEFAULT_RECONNECT_TIMEOUT_MS = 60_000;
const RECONNECT_CONNECT_TIMEOUT_MS = 1000;
const RECONNECT_HELLO_TIMEOUT_MS = 3000;
@@ -310,7 +331,7 @@ export class DaemonClient {
const hello = this.helloMessage ?? (await this.waitForHello());
const compatibilities = getDaemonCommandCompatibilities(command);
const missingCompatibility = compatibilities.find(
- (compatibility) => !this.meetsCommandCompatibility(hello, compatibility),
+ (compatibility) => !meetsDaemonCommandCompatibility(hello, compatibility),
);
if (missingCompatibility) {
throw new DaemonCapabilityUnavailableError(command.type, missingCompatibility.capability);
@@ -325,16 +346,6 @@ export class DaemonClient {
);
}
- private meetsCommandCompatibility(hello: DaemonHello, compatibility: DaemonCommandCompatibility): boolean {
- return (
- hello.protocol.version >= compatibility.minProtocol &&
- (compatibility.minSchemaRevision === undefined ||
- (hello.schemaRevision ?? 0) >= compatibility.minSchemaRevision) &&
- (compatibility.capability === undefined ||
- hello.serverCapabilities?.includes(compatibility.capability) === true)
- );
- }
-
async authenticateWorker(token: string, timeoutMs = 3000): Promise<void> {
const legacyAuthentication = { type: "worker_auth", token } as DaemonWorkerCommandBody;
const response = await this.requestWire(legacyAuthentication, timeoutMs);
@@ -450,7 +461,7 @@ export class DaemonClient {
}
pending.awaitingReconnect = false;
const missingCompatibility = pending.compatibilities.find(
- (compatibility) => !this.meetsCommandCompatibility(message, compatibility),
+ (compatibility) => !meetsDaemonCommandCompatibility(message, compatibility),
);
if (missingCompatibility) {
this.pendingRequests.delete(id);
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index 45f5af4653..1fb2dbdac0 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -7,7 +7,7 @@
*/
import { spawn } from "node:child_process";
-import { createHash, randomUUID } from "node:crypto";
+import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { stat } from "node:fs/promises";
import { createConnection, createServer, type Server, type Socket } from "node:net";
@@ -160,6 +160,7 @@ import {
isDaemonCommandEnvelope,
isDaemonDialogExtensionUiRequest,
isDaemonMutatingCommand,
+ isSessionPlaneDaemonCommand,
salvageDaemonCommandId,
success,
UPDATE_RESTART_DRAIN_COMMANDS,
@@ -188,6 +189,7 @@ import {
import { assertDaemonSupervisorOwnerCurrent, isDaemonShutdownAdmissionActive } from "./daemon-supervisor-ownership.js";
import {
DAEMON_WORKER_ACTIVE_SESSION_ID_ENV,
+ DAEMON_WORKER_PEER_TRANSPORT_CAPABILITY,
DAEMON_WORKER_RECOVERY_JOURNAL_ENV,
DAEMON_WORKER_ROLE_ENV,
DAEMON_WORKER_ROSTER_CAPABILITY,
@@ -195,6 +197,7 @@ import {
DAEMON_WORKER_TOKEN_ENV,
type DaemonWorkerCommand,
type DaemonWorkerFrameHeader,
+ type DaemonWorkerPeerGrant,
type DaemonWorkerRosterOutbound,
isDaemonWorkerFrameHeader,
ROSTER_HEARTBEAT_INTERVAL_MS,
@@ -230,6 +233,7 @@ export interface DaemonModeOptions {
createRuntime: CreateAgentSessionRuntimeFactory;
worker?: {
authenticationToken: string;
+ workerInstanceId?: string;
restoreActiveSessionId?: string;
};
}
@@ -392,6 +396,10 @@ interface BoundSupervisorGenerationClaim {
ownerFingerprint: string;
}
+const PEER_GRANT_TTL_LIMIT_MS = 30_000;
+// Only the supervisor registers grants, so the cap is a tripwire, never an eviction policy.
+const PEER_GRANT_LIMIT = 1024;
+
const RLM_SUBAGENT_REGISTRY_FILE = "rlm-subagents.jsonl";
/**
@@ -536,6 +544,9 @@ export class AgentDaemon {
private supervisorFenceTimer?: ReturnType<typeof setTimeout>;
private supervisorLaunchInProgress = false;
private readonly supervisorClaims = new Map<DaemonSocketClient, BoundSupervisorGenerationClaim>();
+ private readonly peerGrants = new Map<string, DaemonWorkerPeerGrant>();
+ private readonly peerClaims = new Map<DaemonSocketClient, DaemonWorkerPeerGrant>();
+ private peerAdmissionsFenced = false;
private agentMessagesPaused = false;
private readonly summarizer = new DaemonSessionSummarizer(
() => [...this.sessions.values()],
@@ -740,6 +751,18 @@ export class AgentDaemon {
return true;
}
+ /** Burn every outstanding grant and end direct peers; admissions stay fenced until an update cancel. */
+ private fencePeerTransports(closingReason?: DaemonClosingReason): void {
+ this.peerAdmissionsFenced = true;
+ this.peerGrants.clear();
+ for (const client of [...this.peerClaims.keys()]) {
+ this.peerClaims.delete(client);
+ // The reason reaches the client before FIN so its close maps to shutdown/update, not a transport loss.
+ if (closingReason) this.write(client, { type: "daemon_closing", reason: closingReason });
+ client.socket.end();
+ }
+ }
+
private clearSupervisorAvailabilityCheck(): void {
if (this.supervisorMonitorTimer) {
clearTimeout(this.supervisorMonitorTimer);
@@ -3225,10 +3248,12 @@ export class AgentDaemon {
this.detachClient(client);
client.detachInput();
this.clients.delete(client);
- const wasAuthenticated = client.authenticated === true;
+ this.peerClaims.delete(client);
+ // The fence check revokes a stale claim before ending the socket; the role survives.
+ const wasSupervisor = client.authenticationRole === "supervisor";
this.revokeSupervisorClaim(client);
const supervisorSocketPath = this.supervisorSocketPathFromEnv();
- if (this.options.worker && wasAuthenticated && supervisorSocketPath) {
+ if (this.options.worker && wasSupervisor && supervisorSocketPath) {
this.scheduleSupervisorAvailabilityCheck(supervisorSocketPath, 100);
}
};
@@ -3290,6 +3315,9 @@ export class AgentDaemon {
id?: unknown;
type?: unknown;
token?: unknown;
+ grantId?: unknown;
+ workerInstanceId?: unknown;
+ purpose?: unknown;
supervisorGeneration?: unknown;
supervisorPid?: unknown;
supervisorProcessStartId?: unknown;
@@ -3319,9 +3347,52 @@ export class AgentDaemon {
// Public supervisor authentication has already bound this socket's identity.
if (this.options.worker && client.authenticated !== true) {
const commandId = typeof parsed.id === "string" ? parsed.id : undefined;
+ if (parsed.type === "peer_auth") {
+ // Single use: the grant is burned before its token is checked.
+ const grant = typeof parsed.grantId === "string" ? this.peerGrants.get(parsed.grantId) : undefined;
+ if (typeof parsed.grantId === "string") this.peerGrants.delete(parsed.grantId);
+ const presentedTokenHash =
+ typeof parsed.token === "string" ? createHash("sha256").update(parsed.token).digest() : undefined;
+ const expectedTokenHash = grant ? createHash("sha256").update(grant.token).digest() : undefined;
+ const expiresAt = grant ? Date.parse(grant.expiresAt) : Number.NaN;
+ if (
+ this.peerAdmissionsFenced ||
+ !grant ||
+ !presentedTokenHash ||
+ !expectedTokenHash ||
+ !timingSafeEqual(presentedTokenHash, expectedTokenHash) ||
+ parsed.workerInstanceId !== grant.workerInstanceId ||
+ parsed.purpose !== grant.purpose ||
+ !Number.isFinite(expiresAt) ||
+ expiresAt <= Date.now()
+ ) {
+ clearParsedAdmission();
+ this.write(client, failure(commandId, "peer_auth", "Peer authentication failed"));
+ client.socket.end();
+ return;
+ }
+ client.authenticated = true;
+ client.authenticationRole = "session_client";
+ this.peerClaims.set(client, grant);
+ this.write(client, {
+ id: commandId,
+ type: "response",
+ command: "peer_auth",
+ success: true,
+ data: {
+ workerInstanceId: grant.workerInstanceId,
+ activeSessionId: grant.activeSessionId,
+ purpose: grant.purpose,
+ },
+ });
+ return;
+ }
if (
parsed.type !== "worker_auth" ||
parsed.token !== this.options.worker.authenticationToken ||
+ // Enforced only when presented: a downgraded (pre-instance-id) supervisor must still adopt live workers.
+ (parsed.workerInstanceId !== undefined &&
+ parsed.workerInstanceId !== this.options.worker.workerInstanceId) ||
typeof parsed.supervisorGeneration !== "string" ||
!Number.isInteger(parsed.supervisorPid) ||
(parsed.supervisorPid as number) <= 0 ||
@@ -3356,6 +3427,7 @@ export class AgentDaemon {
}
}
client.authenticated = true;
+ client.authenticationRole = "supervisor";
this.supervisorClaims.set(client, { claim, ownerFingerprint });
this.clearSupervisorAvailabilityCheck();
this.scheduleSupervisorFenceCheck();
@@ -3364,13 +3436,42 @@ export class AgentDaemon {
type: "response",
command: "worker_auth",
success: true,
- data: { capabilities: [DAEMON_WORKER_ROSTER_CAPABILITY] },
+ data: {
+ capabilities: [
+ DAEMON_WORKER_ROSTER_CAPABILITY,
+ ...(this.options.worker.workerInstanceId !== undefined
+ ? [DAEMON_WORKER_PEER_TRANSPORT_CAPABILITY]
+ : []),
+ ],
+ },
});
this.rosterReporter.snapshotPending = true;
this.scheduleRosterFlush();
return;
}
- if (this.options.worker) {
+ const peerClaim = this.options.worker ? this.peerClaims.get(client) : undefined;
+ if (peerClaim) {
+ const commandId = typeof parsed.id === "string" ? parsed.id : undefined;
+ const commandName = typeof parsed.type === "string" ? parsed.type : "unknown";
+ // Reachable only through shutdown, which fences admissions without ending live peers.
+ if (this.peerAdmissionsFenced) {
+ clearParsedAdmission();
+ this.write(client, failure(commandId, commandName, "Direct peer transport is fenced"));
+ return;
+ }
+ if (
+ typeof parsed.type !== "string" ||
+ !isSessionPlaneDaemonCommand(parsed.type) ||
+ parsed.activeSessionId !== peerClaim.activeSessionId
+ ) {
+ clearParsedAdmission();
+ this.write(
+ client,
+ failure(commandId, commandName, "Command is not allowed on this direct peer transport"),
+ );
+ return;
+ }
+ } else if (this.options.worker) {
const boundClaim = this.supervisorClaims.get(client);
if (!boundClaim) {
clearParsedAdmission();
@@ -3509,6 +3610,35 @@ export class AgentDaemon {
case "worker_auth":
this.write(client, failure(command.id, command.type, "Worker is already authenticated"));
return;
+ case "worker_register_peer_transport": {
+ const grant = command.grant;
+ const boundClaim = this.supervisorClaims.get(client);
+ const expiresAt = Date.parse(grant.expiresAt);
+ const now = Date.now();
+ for (const [grantId, pending] of this.peerGrants) {
+ if (Date.parse(pending.expiresAt) < now) this.peerGrants.delete(grantId);
+ }
+ if (
+ this.peerAdmissionsFenced ||
+ !boundClaim ||
+ grant.issuerGeneration !== boundClaim.claim.supervisorGeneration ||
+ grant.purpose !== "session_client" ||
+ !grant.grantId ||
+ !grant.token ||
+ grant.workerInstanceId !== this.options.worker?.workerInstanceId ||
+ !this.sessions.has(grant.activeSessionId) ||
+ this.peerGrants.size >= PEER_GRANT_LIMIT ||
+ !Number.isFinite(expiresAt) ||
+ expiresAt <= now ||
+ expiresAt - now > PEER_GRANT_TTL_LIMIT_MS
+ ) {
+ this.write(client, failure(command.id, command.type, "Peer transport grant is invalid"));
+ return;
+ }
+ this.peerGrants.set(grant.grantId, grant);
+ this.writeWorkerSuccess(client, command);
+ return;
+ }
case "worker_subscribe": {
const state = this.getBoundSessionState(command.activeSessionId);
setDaemonClientSessionCapabilities(
@@ -3528,9 +3658,11 @@ export class AgentDaemon {
return;
}
case "worker_archive_and_shutdown": {
+ // Close sessions first so direct peers read session_closed "killed", not a daemon shutdown.
for (const state of [...this.sessions.values()]) {
await this.closeSession(state, "killed");
}
+ this.fencePeerTransports();
this.writeWorkerSuccess(client, command);
setImmediate(() => void this.shutdown(0));
return;
@@ -3552,6 +3684,7 @@ export class AgentDaemon {
return;
}
case "worker_prepare_update": {
+ this.fencePeerTransports("update");
const transaction = this.beginUpdateRestartTransaction(client);
const manifest = await this.runUpdateRestartPreparation(transaction);
this.writeWorkerSuccess(client, command, manifest);
@@ -3593,6 +3726,7 @@ export class AgentDaemon {
throw new Error("Daemon update checkpoint is already committing");
}
if (transaction) this.cancelPreparedUpdateRestart(transaction.id);
+ this.peerAdmissionsFenced = false;
this.writeWorkerSuccess(client, command);
return;
}
@@ -3760,6 +3894,8 @@ export class AgentDaemon {
}
state.clients.add(client);
client.attachedActiveSessionIds.add(state.activeSessionId);
+ // Carrier-less mutation: a direct viewer changes directAttachedClients with no session event.
+ if (client.authenticationRole === "session_client") this.scheduleRosterFlush();
if (deferClientEnv && clientEnv) {
this.updateRestart?.deferredClientEnv.push({
client,
@@ -5850,6 +5986,7 @@ export class AgentDaemon {
this.abortSideQuestionsFor(client, state.activeSessionId);
abortClientSnapshotStreaming(client, state.activeSessionId);
detachClientFromActiveSession(client, state);
+ if (client.authenticationRole === "session_client") this.scheduleRosterFlush();
this.write(client, {
type: "session_detached",
activeSessionId: state.activeSessionId,
@@ -6131,7 +6268,10 @@ export class AgentDaemon {
transaction.deferredClientEnv.length = 0;
for (const pause of this.updateRestartQueuePauses.values()) pause.release();
this.updateRestartQueuePauses.clear();
- if (!this.shuttingDown) this.cronScheduler.start();
+ if (!this.shuttingDown) {
+ this.peerAdmissionsFenced = false;
+ this.cronScheduler.start();
+ }
}
private async prepareUpdateRestart(): Promise<DaemonUpdateRestartManifest> {
@@ -7028,7 +7168,11 @@ export class AgentDaemon {
}
private write(client: DaemonSocketClient, message: DaemonOutbound): boolean {
- const compactDelta = client.transport === "private-framed" ? createCompactAssistantDelta(message) : undefined;
+ // Direct session peers decode plain jsonl payloads only; compact deltas are a supervisor optimization.
+ const compactDelta =
+ client.transport === "private-framed" && client.authenticationRole !== "session_client"
+ ? createCompactAssistantDelta(message)
+ : undefined;
return this.writeSerialized(
client,
serializeJsonLine(compactDelta ?? message),
@@ -7119,6 +7263,8 @@ export class AgentDaemon {
process.exit(exitCode);
}
this.shuttingDown = true;
+ this.peerAdmissionsFenced = true;
+ this.peerGrants.clear();
if (this.supervisorMonitorTimer) {
clearTimeout(this.supervisorMonitorTimer);
this.supervisorMonitorTimer = undefined;
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index 66da67042a..707009989f 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -69,8 +69,9 @@ export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 7;
// Revision 21 adds capability-gated, session-scoped ACP MCP server replacement.
// Revision 23 lets workers query the supervisor agent roster on demand.
// Revision 24 adds the capability-gated agent-roster subscription and push.
-export const DAEMON_SCHEMA_REVISION = 24;
-export const DAEMON_SCHEMA_ID = "protocol-7-schema-24-75f88f1a91df";
+// Revision 25 adds capability-gated direct worker peer transport discovery.
+export const DAEMON_SCHEMA_REVISION = 25;
+export const DAEMON_SCHEMA_ID = "protocol-7-schema-25-585ef1102921";
export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;
export type DaemonProtocolVersion = number;
@@ -116,7 +117,8 @@ export type DaemonServerCapability =
| "rlm_quiescence_barrier"
| "session_input_pause"
| "owned_prompt_cancellation"
- | "acp_mcp_servers";
+ | "acp_mcp_servers"
+ | "direct_peer_transport";
export type DaemonReplayStatus = "complete" | "partial" | "unavailable";
@@ -163,6 +165,19 @@ export const DAEMON_DEFAULT_SERVER_CAPABILITIES: readonly DaemonServerCapability
"acp_mcp_servers",
];
+/** Single-use short-lived credential for one direct TUI connection to one worker process incarnation. */
+export interface DaemonPeerTransportTicket {
+ purpose: "session_client";
+ socketPath: string;
+ /** Filesystem identity of the worker socket at issue time; re-checked by the client before connecting. */
+ socketIdentity: { dev: number; ino: number };
+ workerInstanceId: string;
+ activeSessionId: string;
+ grantId: string;
+ token: string;
+ expiresAt: string;
+}
+
export interface DaemonRuntimeIdentity {
buildId: string;
executablePath: string;
@@ -381,6 +396,7 @@ export type DaemonCommand =
}
| DaemonSavedSessionListCommand
| { id?: string; type: "list_agent_peers"; workerToken: string }
+ | { id?: string; type: "get_direct_worker_transport"; activeSessionId: string }
| { id?: string; type: "roster_subscribe" }
| { id?: string; type: "roster_unsubscribe" }
| ({
@@ -719,12 +735,18 @@ const SESSION_INPUT_PAUSE_COMMAND = {
capability: "session_input_pause",
} as const;
const AGENT_PEER_LIST_COMMAND = { minProtocol: 7, minSchemaRevision: 23 } as const;
+const DIRECT_PEER_TRANSPORT_COMMAND = {
+ minProtocol: 7,
+ minSchemaRevision: 25,
+ capability: "direct_peer_transport",
+} as const;
export const DAEMON_COMMAND_COMPATIBILITY = {
ack_result: LEGACY_DAEMON_COMMAND,
list: LEGACY_DAEMON_COMMAND,
list_saved_sessions: LEGACY_DAEMON_COMMAND,
list_agent_peers: AGENT_PEER_LIST_COMMAND,
+ get_direct_worker_transport: DIRECT_PEER_TRANSPORT_COMMAND,
create: LEGACY_DAEMON_COMMAND,
attach: LEGACY_DAEMON_COMMAND,
reattach: LEGACY_DAEMON_COMMAND,
@@ -828,6 +850,128 @@ export const DAEMON_COMMAND_COMPATIBILITY = {
shutdown: LEGACY_DAEMON_COMMAND,
} as const satisfies Record<DaemonCommandName, DaemonCommandCompatibility>;
+/**
+ * Which endpoint serves each command when a client holds both a supervisor
+ * (control-plane) and a direct worker (session-plane) connection. Session is
+ * the default for session-addressed commands; "control" marks supervisor
+ * semantics: worker lifecycle, cross-worker targeting, daemon-global
+ * registries, and names a worker resolves differently (a worker's "list" is
+ * only its own sessions). Total over DaemonCommand["type"], so an
+ * unclassified command is a compile error and never routes direct.
+ */
+export const DAEMON_COMMAND_PLANE = {
+ ack_result: "control",
+ list: "control",
+ list_saved_sessions: "control",
+ list_agent_peers: "control",
+ get_direct_worker_transport: "control",
+ create: "control",
+ attach: "session",
+ reattach: "control",
+ detach: "session",
+ complete_owned_session: "control",
+ promote_owned_session: "control",
+ kill: "control",
+ rename: "control",
+ prompt: "session",
+ cancel_prompt_admission: "session",
+ prompt_and_wait: "session",
+ steer: "session",
+ follow_up: "session",
+ restore_next_turn: "session",
+ restore_actions: "session",
+ append_custom_message: "session",
+ resume_queue: "session",
+ send_message: "control",
+ agent_messages_status: "control",
+ agent_messages_pause: "control",
+ agent_messages_resume: "control",
+ agent_messages_clear: "control",
+ abort: "session",
+ start_side_question: "session",
+ abort_side_question: "session",
+ execute_bash: "session",
+ abort_bash: "session",
+ cancel_rlm_child: "session",
+ delete_rlm_subagent: "session",
+ wait_for_idle: "session",
+ wait_for_headless_completion: "session",
+ get_session_header: "session",
+ get_state: "session",
+ get_connection_state: "session",
+ get_messages: "session",
+ get_rlm_children: "session",
+ get_session_stats: "session",
+ get_context_tree: "session",
+ get_commands: "session",
+ get_resource_snapshot: "session",
+ replace_acp_mcp_servers: "session",
+ get_model_catalog: "session",
+ get_available_models: "session",
+ get_queue: "session",
+ mutate_queued_message: "session",
+ clear_queue: "session",
+ abort_and_clear_queue: "session",
+ acquire_session_input_pause: "session",
+ release_session_input_pause: "session",
+ cron_list: "control",
+ heartbeats_list: "control",
+ roster_subscribe: "control",
+ roster_unsubscribe: "control",
+ heartbeat_manage: "control",
+ cron_add: "control",
+ cron_cancel: "control",
+ heartbeat_get: "control",
+ heartbeat_set: "control",
+ heartbeat_update: "control",
+ set_model: "session",
+ cycle_model: "session",
+ set_scoped_models: "session",
+ set_thinking_level: "session",
+ set_service_tier: "session",
+ cycle_thinking_level: "session",
+ set_transport: "session",
+ set_steering_mode: "session",
+ set_follow_up_mode: "session",
+ set_auto_compaction: "session",
+ set_auto_retry: "session",
+ compact: "session",
+ refine: "session",
+ abort_compaction: "session",
+ abort_branch_summary: "session",
+ abort_retry: "session",
+ execute_bash_and_wait: "session",
+ reload: "session",
+ new_session: "session",
+ switch_session: "session",
+ fork: "session",
+ navigate_tree: "session",
+ import_jsonl: "session",
+ export_html: "session",
+ export_jsonl: "session",
+ set_session_name: "control",
+ get_rlm_max_depth_status: "session",
+ set_rlm_max_depth: "session",
+ rename_saved_session: "control",
+ delete_saved_session: "control",
+ get_session_context: "session",
+ get_session_tree: "session",
+ get_user_messages_for_forking: "session",
+ get_last_assistant_text: "session",
+ get_system_prompt: "session",
+ get_tool_definition: "session",
+ set_session_entry_label: "session",
+ extension_ui_response: "session",
+ prepare_update_restart: "control",
+ retry_worker: "control",
+ restart: "control",
+ shutdown: "control",
+} as const satisfies Record<DaemonCommandName, "session" | "control">;
+
+export function isSessionPlaneDaemonCommand(type: string): boolean {
+ return (DAEMON_COMMAND_PLANE as Record<string, "session" | "control" | undefined>)[type] === "session";
+}
+
export function getDaemonCommandCompatibilities(command: DaemonCommand): readonly DaemonCommandCompatibility[] {
const requirements: DaemonCommandCompatibility[] = [];
if ((command.type === "attach" || command.type === "reattach") && command.recoveryConfig !== undefined) {
@@ -849,6 +993,22 @@ export function getDaemonCommandCompatibilities(command: DaemonCommand): readonl
return [...requirements, DAEMON_COMMAND_COMPATIBILITY[command.type]];
}
+export function meetsDaemonCommandCompatibility(
+ hello: {
+ protocol: DaemonProtocolInfo;
+ schemaRevision?: number;
+ serverCapabilities?: readonly DaemonServerCapability[];
+ },
+ compatibility: DaemonCommandCompatibility,
+): boolean {
+ return (
+ hello.protocol.version >= compatibility.minProtocol &&
+ (compatibility.minSchemaRevision === undefined ||
+ (hello.schemaRevision ?? 0) >= compatibility.minSchemaRevision) &&
+ (compatibility.capability === undefined || hello.serverCapabilities?.includes(compatibility.capability) === true)
+ );
+}
+
export type DaemonResponse =
| { id?: string; type: "response"; command: string; success: true; data?: unknown }
| {
@@ -1119,6 +1279,7 @@ const READ_ONLY_DAEMON_COMMANDS: ReadonlySet<DaemonCommand["type"]> = new Set([
"list",
"list_saved_sessions",
"list_agent_peers",
+ "get_direct_worker_transport",
"attach",
"reattach",
"roster_subscribe",
diff --git a/packages/coding-agent/src/modes/daemon/daemon-routed-client.ts b/packages/coding-agent/src/modes/daemon/daemon-routed-client.ts
new file mode 100644
index 0000000000..54bc512899
--- /dev/null
+++ b/packages/coding-agent/src/modes/daemon/daemon-routed-client.ts
@@ -0,0 +1,275 @@
+import {
+ DaemonCapabilityUnavailableError,
+ type DaemonClientCloseListener,
+ type DaemonClientMessageListener,
+ type DaemonClientRequestOptions,
+ type DaemonCommandBody,
+ type DaemonHello,
+ DaemonSocketClosedError,
+ type DaemonTransportClient,
+ getDaemonSocketCloseReason,
+} from "./daemon-client.js";
+import {
+ type DaemonClosingReason,
+ type DaemonCommand,
+ type DaemonPeerTransportTicket,
+ type DaemonResponse,
+ type DaemonServerCapability,
+ getDaemonCommandCompatibilities,
+ isSessionPlaneDaemonCommand,
+ meetsDaemonCommandCompatibility,
+} from "./daemon-protocol.js";
+import { getDaemonSocketIdentity } from "./daemon-socket.js";
+import { DaemonWorkerClient } from "./daemon-worker-client.js";
+
+export class DaemonDirectTransportClosedError extends DaemonSocketClosedError {
+ constructor(cause: Error) {
+ super("direct-worker", getDaemonSocketCloseReason(cause), cause.message);
+ this.name = "DaemonDirectTransportClosedError";
+ }
+}
+
+export class DaemonControlPlaneTransportError extends Error {
+ constructor(cause: Error) {
+ super(`Daemon control-plane transport failed: ${cause.message}`, { cause });
+ this.name = "DaemonControlPlaneTransportError";
+ }
+}
+
+/**
+ * One logical daemon connection over two sockets: session-plane commands go direct to the worker,
+ * the rest to the supervisor. Any direct-path loss degrades silently to supervisor routing; an
+ * established direct link keeps serving the session while the supervisor reconnects.
+ */
+export class DaemonRoutedClient implements DaemonTransportClient {
+ private direct?: DaemonWorkerClient;
+ private readonly messageListeners = new Set<DaemonClientMessageListener>();
+ private readonly closeListeners = new Set<DaemonClientCloseListener>();
+ private readonly unsubscribeSupervisorMessage: () => void;
+ private readonly unsubscribeSupervisorClose: () => void;
+ private unsubscribeDirectMessage?: () => void;
+ private unsubscribeDirectClose?: () => void;
+ private closed = false;
+
+ constructor(
+ private readonly supervisor: DaemonTransportClient,
+ direct: DaemonWorkerClient,
+ ) {
+ this.direct = direct;
+ this.unsubscribeSupervisorMessage = supervisor.onMessage((message) => this.emitMessage(message));
+ this.unsubscribeSupervisorClose = supervisor.onClose((error) => {
+ if (!this.closed) this.emitClose(error);
+ });
+ this.bindDirect(direct);
+ }
+
+ get hello(): DaemonHello | undefined {
+ return this.supervisor.hello ?? this.direct?.hello;
+ }
+
+ get isConnected(): boolean {
+ return this.supervisor.isConnected || this.direct?.isConnected === true;
+ }
+
+ get hasDirectTransport(): boolean {
+ return this.direct?.isConnected === true;
+ }
+
+ get controlPlaneTransport(): DaemonTransportClient {
+ return this.supervisor;
+ }
+
+ get isControlPlaneReady(): boolean {
+ return this.supervisor.isConnected && this.supervisor.hello !== undefined;
+ }
+
+ supportsServerCapability(capability: DaemonServerCapability): boolean {
+ return (
+ this.supervisor.supportsServerCapability(capability) ||
+ this.direct?.supportsServerCapability(capability) === true
+ );
+ }
+
+ waitForHello(timeoutMs = 3000): Promise<DaemonHello> {
+ return this.supervisor.waitForHello(timeoutMs);
+ }
+
+ async connect(timeoutMs = 3000): Promise<void> {
+ if (!this.supervisor.isConnected) await this.supervisor.connect(timeoutMs);
+ }
+
+ async reconnect(timeoutMs = 3000): Promise<void> {
+ if (!this.supervisor.isConnected) await this.supervisor.reconnect(timeoutMs);
+ }
+
+ disconnectForReconnect(reason: DaemonClosingReason): void {
+ this.fallbackToSupervisor();
+ this.supervisor.disconnectForReconnect(reason);
+ }
+
+ resetTransportForReconnect(): void {
+ this.supervisor.resetTransportForReconnect();
+ }
+
+ onMessage(listener: DaemonClientMessageListener): () => void {
+ this.messageListeners.add(listener);
+ return () => this.messageListeners.delete(listener);
+ }
+
+ onClose(listener: DaemonClientCloseListener): () => void {
+ this.closeListeners.add(listener);
+ return () => this.closeListeners.delete(listener);
+ }
+
+ enableRequestRecovery(): void {
+ this.supervisor.enableRequestRecovery();
+ }
+
+ request(
+ command: DaemonCommandBody,
+ timeoutMs = 30_000,
+ options: DaemonClientRequestOptions = {},
+ ): Promise<DaemonResponse> {
+ if (command.type === "reattach") {
+ // Reattach may land on a different worker; the direct link to the old one is stale on success.
+ return this.requestControlPlane(command, timeoutMs, options).then((response) => {
+ if (response.success) this.fallbackToSupervisor();
+ return response;
+ });
+ }
+ const direct = this.direct;
+ if (direct?.isConnected && this.servesDirect(direct, command)) {
+ return direct.request(command, timeoutMs, options);
+ }
+ return this.requestControlPlane(command, timeoutMs, options);
+ }
+
+ private servesDirect(direct: DaemonWorkerClient, command: DaemonCommandBody): boolean {
+ if (!isSessionPlaneDaemonCommand(command.type)) return false;
+ const hello = direct.hello;
+ if (!hello) return false;
+ return getDaemonCommandCompatibilities(command as DaemonCommand).every((compatibility) =>
+ meetsDaemonCommandCompatibility(hello, compatibility),
+ );
+ }
+
+ private requestControlPlane(
+ command: DaemonCommandBody,
+ timeoutMs: number,
+ options: DaemonClientRequestOptions,
+ ): Promise<DaemonResponse> {
+ return this.supervisor.request(command, timeoutMs, options).catch((error: unknown) => {
+ if (error instanceof DaemonCapabilityUnavailableError) throw error;
+ throw new DaemonControlPlaneTransportError(error instanceof Error ? error : new Error(String(error)));
+ });
+ }
+
+ fallbackToSupervisor(): void {
+ const direct = this.direct;
+ if (!direct) return;
+ this.direct = undefined;
+ this.unsubscribeDirectMessage?.();
+ this.unsubscribeDirectMessage = undefined;
+ this.unsubscribeDirectClose?.();
+ this.unsubscribeDirectClose = undefined;
+ direct.close();
+ }
+
+ close(): void {
+ if (this.closed) return;
+ this.closed = true;
+ this.fallbackToSupervisor();
+ this.unsubscribeSupervisorMessage();
+ this.unsubscribeSupervisorClose();
+ this.supervisor.close();
+ this.messageListeners.clear();
+ this.closeListeners.clear();
+ }
+
+ private bindDirect(direct: DaemonWorkerClient): void {
+ this.unsubscribeDirectMessage = direct.onMessage((message) => this.emitMessage(message));
+ this.unsubscribeDirectClose = direct.onClose((error) => {
+ if (this.closed || this.direct !== direct) return;
+ this.direct = undefined;
+ this.unsubscribeDirectMessage?.();
+ this.unsubscribeDirectMessage = undefined;
+ this.unsubscribeDirectClose = undefined;
+ this.emitClose(new DaemonDirectTransportClosedError(error));
+ });
+ }
+
+ private emitMessage(message: Parameters<DaemonClientMessageListener>[0]): void {
+ for (const listener of [...this.messageListeners]) listener(message);
+ }
+
+ private emitClose(error: Error): void {
+ for (const listener of [...this.closeListeners]) listener(error);
+ }
+}
+
+/** Upgrade a supervisor connection with a direct worker link; every failure returns the supervisor unchanged. */
+export async function createDaemonSessionTransport(
+ supervisor: DaemonTransportClient,
+ activeSessionId: string,
+ directDisabled: boolean,
+): Promise<DaemonTransportClient> {
+ if (
+ directDisabled ||
+ supervisor instanceof DaemonRoutedClient ||
+ !supervisor.supportsServerCapability("direct_peer_transport")
+ ) {
+ return supervisor;
+ }
+ let direct: DaemonWorkerClient | undefined;
+ try {
+ // recoverable:false — this caller owns the fallback; a parked ticket request would pend the attach forever.
+ const response = await supervisor.request({ type: "get_direct_worker_transport", activeSessionId }, 5000, {
+ recoverable: false,
+ });
+ if (!response.success) return supervisor;
+ const ticket = readSessionTransportTicket(response.data);
+ if (!ticket || ticket.activeSessionId !== activeSessionId || Date.parse(ticket.expiresAt) <= Date.now()) {
+ return supervisor;
+ }
+ const currentIdentity = getDaemonSocketIdentity(ticket.socketPath);
+ if (
+ !currentIdentity ||
+ currentIdentity.dev !== ticket.socketIdentity.dev ||
+ currentIdentity.ino !== ticket.socketIdentity.ino
+ ) {
+ return supervisor;
+ }
+ direct = new DaemonWorkerClient(ticket.socketPath);
+ await direct.connect(1000);
+ await direct.waitForHello(1000);
+ await direct.authenticatePeer(ticket, 1000);
+ return new DaemonRoutedClient(supervisor, direct);
+ } catch {
+ direct?.close();
+ return supervisor;
+ }
+}
+
+function readSessionTransportTicket(value: unknown): DaemonPeerTransportTicket | undefined {
+ if (!value || typeof value !== "object") return undefined;
+ const candidate = value as Partial<DaemonPeerTransportTicket>;
+ if (
+ candidate.purpose !== "session_client" ||
+ typeof candidate.socketPath !== "string" ||
+ typeof candidate.workerInstanceId !== "string" ||
+ typeof candidate.activeSessionId !== "string" ||
+ typeof candidate.grantId !== "string" ||
+ typeof candidate.token !== "string" ||
+ typeof candidate.expiresAt !== "string"
+ ) {
+ return undefined;
+ }
+ if (
+ !candidate.socketIdentity ||
+ typeof candidate.socketIdentity.dev !== "number" ||
+ typeof candidate.socketIdentity.ino !== "number"
+ ) {
+ return undefined;
+ }
+ return candidate as DaemonPeerTransportTicket;
+}
diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
index 72989daf28..6155d703f6 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
@@ -58,6 +58,8 @@ export interface SessionSummary {
/** True while the agent is streaming with tool calls pending; drives the "running tools" label. */
isRunningTools?: boolean;
attachedClients: number;
+ /** Clients attached over the direct worker transport; the supervisor adds these to its own count. */
+ directAttachedClients?: number;
messageCount: number;
unfinishedActionCount?: number;
sessionActions: SessionActionSnapshot;
@@ -231,6 +233,9 @@ export function summaryForActiveSession(
}
}
+ const directAttachedClients = [...activeSession.clients].filter(
+ (client) => client.authenticationRole === "session_client",
+ ).length;
return {
id: activeSession.activeSessionId,
lifecycle: activeLifecycleForSession(activeSession),
@@ -256,6 +261,7 @@ export function summaryForActiveSession(
hasRunningRlmChildren: session.hasRunningRlmChildren(),
isRunningTools: session.isStreaming && session.state.pendingToolCalls.size > 0,
attachedClients: activeSession.clients.size,
+ ...(directAttachedClients > 0 ? { directAttachedClients } : {}),
messageCount: session.messages.length,
unfinishedActionCount: session.unfinishedActionCount,
sessionActions: session.getSessionActionSnapshot(),
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index 4462381ab4..fb6549bde1 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -86,6 +86,7 @@ import {
type DaemonClosingReason,
type DaemonCommand,
type DaemonOutbound,
+ type DaemonPeerTransportTicket,
type DaemonResponse,
type DaemonServerCapability,
type DaemonUpdateRestartManifest,
@@ -125,6 +126,8 @@ import {
import { DaemonWorkerClient } from "./daemon-worker-client.js";
import {
DAEMON_WORKER_ACTIVE_SESSION_ID_ENV,
+ DAEMON_WORKER_INSTANCE_ID_ENV,
+ DAEMON_WORKER_PEER_TRANSPORT_CAPABILITY,
DAEMON_WORKER_RECOVERY_JOURNAL_ENV,
DAEMON_WORKER_ROLE_ENV,
DAEMON_WORKER_ROSTER_CAPABILITY,
@@ -164,7 +167,9 @@ const ROSTER_STALE_AFTER_MS = 3 * ROSTER_HEARTBEAT_INTERVAL_MS;
const SUPERVISOR_SERVER_CAPABILITIES: readonly DaemonServerCapability[] = [
...DAEMON_DEFAULT_SERVER_CAPABILITIES,
"agent_roster",
+ "direct_peer_transport",
];
+const PEER_TRANSPORT_GRANT_TTL_MS = 10_000;
const WORKER_REQUEST_TIMEOUT_MS = 24 * 60 * 60 * 1000;
const INPUT_PAUSE_CLEANUP_TIMEOUT_MS = 5_000;
const UPDATE_RESTART_MUTATION_DRAIN_TIMEOUT_MS = 80_000;
@@ -195,6 +200,7 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set([
"ack_result",
"list",
"list_agent_peers",
+ "get_direct_worker_transport",
"roster_subscribe",
"roster_unsubscribe",
"list_saved_sessions",
@@ -322,6 +328,8 @@ interface ResidentWorker {
updateRestartPrepareClient?: DaemonWorkerClient;
lastFrameAt?: number;
rosterStale?: boolean;
+ /** worker_auth advertised peer-transport support; absent on workers from older builds. */
+ peerTransportCapable?: boolean;
/** In-flight replacement connection during authentication; an allowed frame source alongside client. */
pendingClient?: DaemonWorkerClient;
/** Bumped per applied roster frame; a summaries pull that straddles a frame must not gap-fill. */
@@ -497,6 +505,7 @@ function isDaemonWorkerDescriptor(value: unknown, socketPath: string): value is
(descriptor.ownerClientId === undefined || typeof descriptor.ownerClientId === "string") &&
typeof descriptor.socketPath === "string" &&
typeof descriptor.authenticationToken === "string" &&
+ (descriptor.workerInstanceId === undefined || typeof descriptor.workerInstanceId === "string") &&
typeof descriptor.rootActiveSessionId === "string" &&
typeof descriptor.createdAt === "string" &&
typeof descriptor.updatedAt === "string" &&
@@ -515,6 +524,12 @@ function workerAuthAdvertisesRoster(data: unknown): boolean {
return Array.isArray(capabilities) && capabilities.includes(DAEMON_WORKER_ROSTER_CAPABILITY);
}
+function workerAuthAdvertisesPeerTransport(data: unknown): boolean {
+ if (typeof data !== "object" || data === null) return false;
+ const capabilities = (data as { capabilities?: unknown }).capabilities;
+ return Array.isArray(capabilities) && capabilities.includes(DAEMON_WORKER_PEER_TRANSPORT_CAPABILITY);
+}
+
function sessionSummariesFromResponse(response: DaemonResponse): SessionSummary[] {
if (!response.success || !response.data || typeof response.data !== "object" || !("sessions" in response.data)) {
throw new Error("Session worker returned an invalid list response");
@@ -841,9 +856,7 @@ export class DaemonSupervisor {
const activeSessionId = summary.activeSessionId ?? summary.id;
return {
isSessionActive: isSessionSummaryBusy(summary),
- attachedClients: [...this.clients].filter((client) =>
- client.attachedActiveSessionIds.has(activeSessionId),
- ).length,
+ attachedClients: this.attachedClientCount(summary, activeSessionId),
hasRegisteredHeartbeat: summary.hasRegisteredHeartbeat === true,
hasRegisteredCronJob: summary.hasRegisteredCronJob === true,
lastActivityAt: Date.parse(summary.lastActivityAt ?? ""),
@@ -1670,6 +1683,14 @@ export class DaemonSupervisor {
});
return success(command.id, command.type, { peers });
}
+ case "get_direct_worker_transport": {
+ const match = await this.findWorkerForClient(client, command.activeSessionId);
+ if (match.worker.descriptor.ownerClientId !== undefined) {
+ throw new Error("Direct transport is unavailable for client-owned workers");
+ }
+ const ticket = await this.issuePeerTransport(match.worker, match.summary);
+ return success(command.id, command.type, ticket);
+ }
case "list_saved_sessions":
return this.handleSavedSessionList(client, command);
case "create": {
@@ -2716,6 +2737,8 @@ export class DaemonSupervisor {
const rootActiveSessionId = existing?.descriptor.rootActiveSessionId ?? createActiveSessionId();
const socketPath = existing?.descriptor.socketPath ?? workerSocketPath(this.socketPath, workerId);
const token = existing?.descriptor.authenticationToken ?? randomBytes(32).toString("base64url");
+ // Fresh per incarnation: peer transport grants must never survive a worker restart.
+ const workerInstanceId = randomUUID();
const now = new Date().toISOString();
const descriptorPath = existing?.descriptorPath ?? join(this.descriptorDir, `${workerId}.json`);
const recoveryJournalPath =
@@ -2728,6 +2751,7 @@ export class DaemonSupervisor {
...launchEnv,
[DAEMON_WORKER_ROLE_ENV]: "1",
[DAEMON_WORKER_TOKEN_ENV]: token,
+ [DAEMON_WORKER_INSTANCE_ID_ENV]: workerInstanceId,
[DAEMON_WORKER_ACTIVE_SESSION_ID_ENV]: rootActiveSessionId,
[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV]: this.socketPath,
[DAEMON_WORKER_RECOVERY_JOURNAL_ENV]: recoveryJournalPath,
@@ -2798,6 +2822,7 @@ export class DaemonSupervisor {
orphanProcessJournalPath,
supervisorSocketPath: this.socketPath,
authenticationToken: token,
+ workerInstanceId,
rootActiveSessionId,
ownerClientId: existing?.descriptor.ownerClientId ?? ownerClientId,
sessionDir: createCommand.config?.sessionDir,
@@ -2969,13 +2994,19 @@ export class DaemonSupervisor {
try {
const authResponse = await client.authenticateWorker(
worker.descriptor.authenticationToken,
- this.supervisorAuthenticationClaim(),
+ {
+ ...this.supervisorAuthenticationClaim(),
+ ...(worker.descriptor.workerInstanceId !== undefined
+ ? { workerInstanceId: worker.descriptor.workerInstanceId }
+ : {}),
+ },
1000,
);
await this.assertRecoveryAllowed();
if (!workerAuthAdvertisesRoster(authResponse.data)) {
throw new PreRosterWorkerError("Session worker predates the roster protocol and must be restarted");
}
+ worker.peerTransportCapable = workerAuthAdvertisesPeerTransport(authResponse.data);
worker.lastFrameAt = Date.now();
worker.client?.close();
worker.client = client;
@@ -4229,6 +4260,72 @@ export class DaemonSupervisor {
return worker.client;
}
+ private async issuePeerTransport(
+ worker: ResidentWorker,
+ summary: SessionSummary,
+ ): Promise<DaemonPeerTransportTicket> {
+ await this.assertCurrentOwnership();
+ if (!worker.peerTransportCapable) {
+ throw new Error("Session worker does not support direct peer transport");
+ }
+ await this.refreshWorkerSummaries(worker);
+ const workerClient = this.requireAvailableWorkerClient(worker);
+ const activeSessionId = summary.activeSessionId ?? summary.id;
+ const currentSummary = this.findSummaryInWorker(worker, activeSessionId);
+ if (!currentSummary) {
+ throw new Error("Direct transport target changed during admission");
+ }
+ const workerInstanceId = worker.descriptor.workerInstanceId;
+ const workerProcessStartId = worker.descriptor.processStartId;
+ if (!workerInstanceId || !workerProcessStartId) {
+ throw new Error("Direct transport requires an exact worker process identity");
+ }
+ if (this.processIdentity(worker.descriptor.pid, workerProcessStartId) !== "current") {
+ throw new Error("Direct transport worker process identity is not current");
+ }
+ let socketIdentity: DaemonSocketIdentity | undefined;
+ try {
+ socketIdentity = getDaemonSocketIdentity(worker.descriptor.socketPath);
+ } catch {
+ socketIdentity = undefined;
+ }
+ if (!socketIdentity) {
+ throw new Error("Direct transport requires an exact worker socket identity");
+ }
+ const grantId = randomUUID();
+ const token = randomBytes(32).toString("base64url");
+ const expiresAt = new Date(Date.now() + PEER_TRANSPORT_GRANT_TTL_MS).toISOString();
+ const resolvedActiveSessionId = currentSummary.activeSessionId ?? currentSummary.id;
+ const registration = await workerClient.requestWorker(
+ {
+ type: "worker_register_peer_transport",
+ grant: {
+ grantId,
+ token,
+ expiresAt,
+ purpose: "session_client",
+ workerInstanceId,
+ activeSessionId: resolvedActiveSessionId,
+ issuerGeneration: this.generation,
+ },
+ },
+ 3000,
+ );
+ if (!registration.success) {
+ throw deserializeDaemonError(registration);
+ }
+ return {
+ purpose: "session_client",
+ socketPath: worker.descriptor.socketPath,
+ socketIdentity,
+ workerInstanceId,
+ activeSessionId: resolvedActiveSessionId,
+ grantId,
+ token,
+ expiresAt,
+ };
+ }
+
private familyCatalogEntry(summary: SessionSummary): AgentFamilyCatalogEntry {
const depth = summary.rlmDepth ?? (summary.parentSessionPath ? 1 : 0);
return {
@@ -4267,12 +4364,18 @@ export class DaemonSupervisor {
};
}
+ private attachedClientCount(summary: SessionSummary, activeSessionId: string): number {
+ return (
+ (summary.directAttachedClients ?? 0) +
+ [...this.clients].filter((client) => client.attachedActiveSessionIds.has(activeSessionId)).length
+ );
+ }
+
private publicSummary(worker: ResidentWorker, summary: SessionSummary): SessionSummary {
const activeSessionId = summary.activeSessionId ?? summary.id;
return {
...summary,
- attachedClients: [...this.clients].filter((client) => client.attachedActiveSessionIds.has(activeSessionId))
- .length,
+ attachedClients: this.attachedClientCount(summary, activeSessionId),
workerState: this.effectiveWorkerState(worker),
workerPid: worker.descriptor.pid,
};
diff --git a/packages/coding-agent/src/modes/daemon/daemon-worker-client.ts b/packages/coding-agent/src/modes/daemon/daemon-worker-client.ts
index 85ceea0994..16f4751ce0 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-worker-client.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-worker-client.ts
@@ -1,8 +1,22 @@
import { createConnection, type Socket } from "node:net";
import { serializeJsonLine } from "../rpc/jsonl.js";
import { type PrivateFrame, PrivateFramedChannel } from "../session-worker/private-framing.js";
-import type { DaemonCommand, DaemonOutbound, DaemonResponse } from "./daemon-protocol.js";
import {
+ type DaemonClientMessageListener,
+ type DaemonClientRequestOptions,
+ DaemonSocketClosedError,
+} from "./daemon-client.js";
+import type {
+ DaemonClosingReason,
+ DaemonCommand,
+ DaemonOutbound,
+ DaemonPeerTransportTicket,
+ DaemonResponse,
+ DaemonServerCapability,
+} from "./daemon-protocol.js";
+import {
+ type DaemonPeerCommand,
+ type DaemonPeerCommandBody,
type DaemonWorkerCommand,
type DaemonWorkerCommandBody,
type DaemonWorkerFrameHeader,
@@ -11,8 +25,8 @@ import {
type DistributiveOmit<T, K extends keyof T> = T extends unknown ? Omit<T, K> : never;
type DaemonCommandBody = DistributiveOmit<DaemonCommand, "id">;
-type DaemonWorkerWireCommandBody = DaemonCommandBody | DaemonWorkerCommandBody;
-type DaemonWorkerWireCommand = DaemonCommand | DaemonWorkerCommand;
+type DaemonWorkerWireCommandBody = DaemonCommandBody | DaemonWorkerCommandBody | DaemonPeerCommandBody;
+type DaemonWorkerWireCommand = DaemonCommand | DaemonWorkerCommand | DaemonPeerCommand;
type DaemonWorkerAuthentication = Omit<Extract<DaemonWorkerCommand, { type: "worker_auth" }>, "id" | "type" | "token">;
export type DaemonWorkerFrameListener = (frame: PrivateFrame<DaemonWorkerFrameHeader>) => void;
@@ -23,6 +37,7 @@ export class DaemonWorkerClient {
private socket?: Socket;
private channel?: PrivateFramedChannel<DaemonWorkerFrameHeader>;
private readonly frameListeners = new Set<DaemonWorkerFrameListener>();
+ private readonly messageListeners = new Set<DaemonClientMessageListener>();
private readonly closeListeners = new Set<DaemonWorkerCloseListener>();
private readonly pending = new Map<
string,
@@ -33,7 +48,9 @@ export class DaemonWorkerClient {
}
>();
private requestId = 0;
- private hello?: DaemonHello;
+ private helloMessage?: DaemonHello;
+ private directPeer = false;
+ private directClosingReason?: DaemonClosingReason;
private readonly helloWaiters = new Set<{
resolve: (hello: DaemonHello) => void;
reject: (error: Error) => void;
@@ -42,6 +59,18 @@ export class DaemonWorkerClient {
constructor(private readonly socketPath: string) {}
+ get hello(): DaemonHello | undefined {
+ return this.helloMessage;
+ }
+
+ get isConnected(): boolean {
+ return this.socket !== undefined && !this.socket.destroyed;
+ }
+
+ supportsServerCapability(capability: DaemonServerCapability): boolean {
+ return this.helloMessage?.serverCapabilities?.includes(capability) === true;
+ }
+
async connect(timeoutMs = 3000): Promise<void> {
if (this.socket) {
throw new Error("Daemon worker client is already connected");
@@ -74,13 +103,15 @@ export class DaemonWorkerClient {
socket.once("error", onError);
});
- socket.on("error", (error) => this.notifyClosed(socket, error));
- socket.on("close", () => this.notifyClosed(socket, new Error("Daemon worker socket closed")));
+ socket.on("error", (error) => this.notifyClosed(socket, this.directCloseError(error)));
+ socket.on("close", () =>
+ this.notifyClosed(socket, this.directCloseError(new Error("Daemon worker socket closed"))),
+ );
}
waitForHello(timeoutMs = 3000): Promise<DaemonHello> {
- if (this.hello) {
- return Promise.resolve(this.hello);
+ if (this.helloMessage) {
+ return Promise.resolve(this.helloMessage);
}
if (!this.socket || this.socket.destroyed) {
return Promise.reject(new Error("Daemon worker client is not connected"));
@@ -103,12 +134,22 @@ export class DaemonWorkerClient {
return () => this.frameListeners.delete(listener);
}
+ onMessage(listener: DaemonClientMessageListener): () => void {
+ this.messageListeners.add(listener);
+ return () => this.messageListeners.delete(listener);
+ }
+
onClose(listener: DaemonWorkerCloseListener): () => void {
this.closeListeners.add(listener);
return () => this.closeListeners.delete(listener);
}
- request(command: DaemonCommandBody, timeoutMs = 30_000): Promise<DaemonResponse> {
+ request(
+ command: DaemonCommandBody,
+ timeoutMs = 30_000,
+ // Progress/recovery options are supervisor-transport features; a direct request fails fast instead of replaying (no double execution).
+ _options: DaemonClientRequestOptions = {},
+ ): Promise<DaemonResponse> {
return this.requestWire(command, timeoutMs);
}
@@ -128,12 +169,31 @@ export class DaemonWorkerClient {
return response;
}
+ async authenticatePeer(ticket: DaemonPeerTransportTicket, timeoutMs = 3000): Promise<void> {
+ const response = await this.requestWire(
+ {
+ type: "peer_auth",
+ grantId: ticket.grantId,
+ token: ticket.token,
+ workerInstanceId: ticket.workerInstanceId,
+ purpose: ticket.purpose,
+ },
+ timeoutMs,
+ );
+ if (!response.success) {
+ throw new Error(response.error);
+ }
+ this.directPeer = true;
+ }
+
close(): void {
this.rejectAll(new Error("Daemon worker client closed"));
this.channel?.close();
this.channel = undefined;
this.socket?.destroy();
this.socket = undefined;
+ this.directPeer = false;
+ this.directClosingReason = undefined;
}
private async requestWire(command: DaemonWorkerWireCommandBody, timeoutMs: number): Promise<DaemonResponse> {
@@ -193,7 +253,7 @@ export class DaemonWorkerClient {
try {
const parsed = JSON.parse(frame.payload.toString("utf8")) as DaemonOutbound;
if (parsed.type === "daemon_hello") {
- this.hello = parsed;
+ this.helloMessage = parsed;
for (const waiter of [...this.helloWaiters]) {
clearTimeout(waiter.timeout);
this.helloWaiters.delete(waiter);
@@ -207,6 +267,45 @@ export class DaemonWorkerClient {
for (const listener of this.frameListeners) {
listener(frame);
}
+ if (this.directPeer && frame.header.outboundType !== "daemon_hello" && frame.header.outboundType !== "response") {
+ this.emitDirectOutbound(frame);
+ }
+ }
+
+ /** A malformed outbound frame closes the direct link (the routed client falls back) instead of throwing into consumers. */
+ private emitDirectOutbound(frame: PrivateFrame<DaemonWorkerFrameHeader>): void {
+ if (frame.header.kind !== "outbound") return;
+ let message: DaemonOutbound;
+ try {
+ if (frame.header.payloadEncoding !== undefined && frame.header.payloadEncoding !== "jsonl") {
+ throw new Error(`Direct worker sent an unsupported payload encoding: ${frame.header.payloadEncoding}`);
+ }
+ const parsed = JSON.parse(frame.payload.toString("utf8")) as unknown;
+ if (!parsed || typeof parsed !== "object" || typeof (parsed as { type?: unknown }).type !== "string") {
+ throw new Error("Direct worker sent an invalid outbound payload");
+ }
+ message = parsed as DaemonOutbound;
+ } catch (error) {
+ const socket = this.socket;
+ const directError = this.directCloseError(error instanceof Error ? error : new Error(String(error)));
+ if (socket) {
+ this.notifyClosed(socket, directError);
+ socket.destroy(directError);
+ }
+ return;
+ }
+ if (message.type === "daemon_closing") {
+ this.directClosingReason = message.reason;
+ }
+ for (const listener of [...this.messageListeners]) {
+ listener(message);
+ }
+ }
+
+ private directCloseError(cause: Error): Error {
+ return this.directPeer
+ ? new DaemonSocketClosedError(this.socketPath, this.directClosingReason, cause.message)
+ : cause;
}
private rejectAll(error: Error): void {
@@ -228,6 +327,8 @@ export class DaemonWorkerClient {
}
this.socket = undefined;
this.channel = undefined;
+ this.directPeer = false;
+ this.directClosingReason = undefined;
this.rejectAll(error);
for (const listener of [...this.closeListeners]) {
listener(error);
diff --git a/packages/coding-agent/src/modes/daemon/daemon-worker-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-worker-protocol.ts
index e5c23334d0..3b14dc7e1e 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-worker-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-worker-protocol.ts
@@ -9,6 +9,7 @@ import type { DaemonClientCapability, DaemonCommand, DaemonOutbound } from "./da
export const DAEMON_WORKER_ROLE_ENV = "PRIME_AGENT_INTERNAL_DAEMON_WORKER";
export const DAEMON_WORKER_TOKEN_ENV = "PRIME_AGENT_INTERNAL_DAEMON_WORKER_TOKEN";
+export const DAEMON_WORKER_INSTANCE_ID_ENV = "PRIME_AGENT_INTERNAL_DAEMON_WORKER_INSTANCE_ID";
export const DAEMON_WORKER_ACTIVE_SESSION_ID_ENV = "PRIME_AGENT_INTERNAL_DAEMON_WORKER_ACTIVE_SESSION_ID";
export const DAEMON_WORKER_SUPERVISOR_SOCKET_ENV = "PRIME_AGENT_INTERNAL_DAEMON_SUPERVISOR_SOCKET";
export const DAEMON_WORKER_RECOVERY_JOURNAL_ENV = "PRIME_AGENT_INTERNAL_DAEMON_WORKER_RECOVERY_JOURNAL";
@@ -29,6 +30,9 @@ export type DaemonWorkerRosterOutbound =
/** Advertised by new workers in the worker_auth response; absent on legacy workers. */
export const DAEMON_WORKER_ROSTER_CAPABILITY = "agent_roster";
+/** Advertised in the worker_auth response by workers that accept peer transport grants. */
+export const DAEMON_WORKER_PEER_TRANSPORT_CAPABILITY = "peer_transport";
+
/** Idle keepalive cadence for worker->supervisor roster frames; the supervisor staleness threshold derives from it. */
export const ROSTER_HEARTBEAT_INTERVAL_MS = 15_000;
@@ -65,11 +69,40 @@ export function durableDaemonCreateCommand(command: DaemonCreateCommand): Durabl
};
}
+/**
+ * A single-use, worker-memory-only admission for one direct peer, scoped to one active-session
+ * slot (stable across switch_session/new_session/fork) of one worker incarnation. The session pin
+ * is a routing/accident guard, not a privilege boundary: ticket holders already hold supervisor
+ * access, which can attach to, switch, or kill any session.
+ */
+export interface DaemonWorkerPeerGrant {
+ grantId: string;
+ token: string;
+ expiresAt: string;
+ purpose: "session_client";
+ workerInstanceId: string;
+ activeSessionId: string;
+ issuerGeneration: string;
+}
+
+/** Commands a direct peer may send before it holds an authenticated session role. */
+export type DaemonPeerCommand = {
+ id?: string;
+ type: "peer_auth";
+ grantId: string;
+ token: string;
+ workerInstanceId: string;
+ purpose: "session_client";
+};
+
+export type DaemonPeerCommandBody = Omit<DaemonPeerCommand, "id">;
+
export type DaemonWorkerCommand =
| {
id?: string;
type: "worker_auth";
token: string;
+ workerInstanceId?: string;
supervisorGeneration: string;
supervisorPid: number;
supervisorProcessStartId?: string;
@@ -83,6 +116,7 @@ export type DaemonWorkerCommand =
supportsExtensionUi?: boolean;
}
| { id?: string; type: "worker_unsubscribe"; activeSessionId: string }
+ | { id?: string; type: "worker_register_peer_transport"; grant: DaemonWorkerPeerGrant }
| { id?: string; type: "worker_archive_and_shutdown" }
| {
id?: string;
@@ -119,6 +153,7 @@ export interface DaemonWorkerDescriptor {
orphanProcessJournalPath?: string;
supervisorSocketPath: string;
authenticationToken: string;
+ workerInstanceId?: string;
rootActiveSessionId: string;
/** Stable protocol client that owns this worker. Omitted for resident sessions. */
ownerClientId?: string;
@@ -163,6 +198,7 @@ export function durableDaemonWorkerDescriptor(descriptor: DaemonWorkerDescriptor
: {}),
supervisorSocketPath: descriptor.supervisorSocketPath,
authenticationToken: descriptor.authenticationToken,
+ ...(descriptor.workerInstanceId !== undefined ? { workerInstanceId: descriptor.workerInstanceId } : {}),
rootActiveSessionId: descriptor.rootActiveSessionId,
...(descriptor.ownerClientId !== undefined ? { ownerClientId: descriptor.ownerClientId } : {}),
...(descriptor.rootSessionId !== undefined ? { rootSessionId: descriptor.rootSessionId } : {}),
@@ -206,6 +242,10 @@ export function waitForDaemonWorkerStartupGate(environment: NodeJS.ProcessEnv =
}
}
+export function daemonWorkerInstanceId(environment: NodeJS.ProcessEnv = process.env): string | undefined {
+ return environment[DAEMON_WORKER_INSTANCE_ID_ENV] || undefined;
+}
+
export function requireDaemonWorkerAuthenticationToken(environment: NodeJS.ProcessEnv = process.env): string {
const token = environment[DAEMON_WORKER_TOKEN_ENV];
if (!token) {
diff --git a/packages/coding-agent/src/modes/daemon/heartbeat-catalog.ts b/packages/coding-agent/src/modes/daemon/heartbeat-catalog.ts
index f61aa4ec03..7d9eb8f4f2 100644
--- a/packages/coding-agent/src/modes/daemon/heartbeat-catalog.ts
+++ b/packages/coding-agent/src/modes/daemon/heartbeat-catalog.ts
@@ -1,10 +1,10 @@
import type { AgentConnectionHeartbeat } from "../agent-connection/types.js";
-import type { DaemonClient } from "./daemon-client.js";
+import type { DaemonTransportClient } from "./daemon-client.js";
import { deserializeDaemonError } from "./daemon-errors.js";
import { isUnknownDaemonCommandError } from "./daemon-protocol.js";
export async function listDaemonHeartbeats(
- client: DaemonClient,
+ client: DaemonTransportClient,
activeSessionId?: string,
): Promise<AgentConnectionHeartbeat[]> {
if (!client.hello) await client.waitForHello();
diff --git a/packages/coding-agent/src/modes/daemon/saved-session-catalog.ts b/packages/coding-agent/src/modes/daemon/saved-session-catalog.ts
index 6b22b1143a..5a1d251f11 100644
--- a/packages/coding-agent/src/modes/daemon/saved-session-catalog.ts
+++ b/packages/coding-agent/src/modes/daemon/saved-session-catalog.ts
@@ -4,7 +4,7 @@ import type {
AgentConnectionSavedSessionScope,
AgentConnectionSessionListCallbacks,
} from "../agent-connection/types.js";
-import type { DaemonClient } from "./daemon-client.js";
+import type { DaemonTransportClient } from "./daemon-client.js";
import { deserializeDaemonError } from "./daemon-errors.js";
import type {
DaemonCommand,
@@ -19,7 +19,7 @@ export { deserializeSavedSessionInfo } from "./saved-session-info.js";
export type DaemonSavedSessionCatalogContext = { activeSessionId: string } | { cwd: string; sessionDir?: string };
export async function listDaemonSavedSessions(
- client: DaemonClient,
+ client: DaemonTransportClient,
context: DaemonSavedSessionCatalogContext,
scope: AgentConnectionSavedSessionScope,
callbacks?: AgentConnectionSessionListCallbacks,
@@ -45,7 +45,7 @@ export async function listDaemonSavedSessions(
}
export async function renameDaemonSavedSession(
- client: DaemonClient,
+ client: DaemonTransportClient,
context: DaemonSavedSessionCatalogContext,
sessionPath: string,
name: string,
@@ -61,7 +61,7 @@ export async function renameDaemonSavedSession(
}
export async function deleteDaemonSavedSession(
- client: DaemonClient,
+ client: DaemonTransportClient,
context: DaemonSavedSessionCatalogContext,
sessionPath: string,
): Promise<DeleteSessionFileResult> {
diff --git a/packages/coding-agent/test/agent-connection-daemon.test.ts b/packages/coding-agent/test/agent-connection-daemon.test.ts
index 6b22dbb500..a0ebd66557 100644
--- a/packages/coding-agent/test/agent-connection-daemon.test.ts
+++ b/packages/coding-agent/test/agent-connection-daemon.test.ts
@@ -16,12 +16,12 @@ import type {
import {
DaemonCapabilityUnavailableError,
- type DaemonClient,
type DaemonClientCloseListener,
type DaemonClientMessageListener,
type DaemonClientRequestOptions,
type DaemonHello,
DaemonSocketClosedError,
+ type DaemonTransportClient,
} from "../src/modes/daemon/daemon-client.js";
import {
DAEMON_PROTOCOL_INFO,
@@ -31,6 +31,8 @@ import {
type DaemonOutbound,
type DaemonResponse,
} from "../src/modes/daemon/daemon-protocol.js";
+import { DaemonRoutedClient } from "../src/modes/daemon/daemon-routed-client.js";
+import type { DaemonWorkerClient } from "../src/modes/daemon/daemon-worker-client.js";
class FakeDaemonClient {
readonly requests: DaemonCommand[] = [];
@@ -386,6 +388,8 @@ class FakeDaemonClient {
limits: { maxContinuations: 0 },
},
};
+ case "roster_subscribe":
+ return { type: "response", command: command.type, success: true, data: { roster: [] } };
case "wait_for_idle":
case "set_scoped_models":
case "rename_saved_session":
@@ -567,6 +571,10 @@ class FakeDaemonClient {
this.connected = true;
}
+ get isConnected(): boolean {
+ return this.connected;
+ }
+
getMessageListenerCount(): number {
return this.messageListeners.size;
}
@@ -590,8 +598,8 @@ class FakeDaemonClient {
}
}
-function asDaemonClient(client: FakeDaemonClient): DaemonClient {
- return client as unknown as DaemonClient;
+function asDaemonClient(client: FakeDaemonClient): DaemonTransportClient {
+ return client as unknown as DaemonTransportClient;
}
function createConnectionState(activeSessionId: string, sessionId: string): AgentConnectionState {
@@ -757,6 +765,690 @@ function emitSequencedQueueUpdate(client: FakeDaemonClient, activeSessionId: str
}
describe("DaemonAgentConnection", () => {
+ it("falls back to the supervisor when the direct socket closes during initial attach", async () => {
+ const supervisor = new FakeDaemonClient();
+ const closeListeners = new Set<(error: Error) => void>();
+ let directConnected = true;
+ const direct = {
+ get isConnected() {
+ return directConnected;
+ },
+ onMessage: () => () => {},
+ onClose: (listener: (error: Error) => void) => {
+ closeListeners.add(listener);
+ return () => closeListeners.delete(listener);
+ },
+ request: async () => {
+ directConnected = false;
+ const error = new Error("direct attach socket closed");
+ for (const listener of [...closeListeners]) listener(error);
+ throw error;
+ },
+ close: () => {
+ directConnected = false;
+ },
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+
+ const connection = await DaemonAgentConnection.attach(routed, "active-1");
+
+ await expect(connection.getInitialSnapshot()).resolves.toMatchObject({
+ state: { activeSessionId: "active-1" },
+ });
+ expect(supervisor.requests.filter((request) => request.type === "attach")).toHaveLength(1);
+ await connection.dispose();
+ });
+
+ it("keeps serving the session on the direct link and reconnects a lost supervisor socket", async () => {
+ const supervisor = new FakeDaemonClient();
+ const directRequests: DaemonCommand["type"][] = [];
+ let closeSent = false;
+ const direct = {
+ isConnected: true,
+ hello: supervisor.hello,
+ supportsServerCapability: (capability: string) => supervisor.supportsServerCapability(capability),
+ onMessage: () => () => {},
+ onClose: () => () => {},
+ request: async (command: DaemonCommand) => {
+ directRequests.push(command.type);
+ if (!closeSent) {
+ closeSent = true;
+ supervisor.connected = false;
+ supervisor.emitClose(new Error("supervisor closed during direct attach"));
+ }
+ return {
+ type: "response" as const,
+ command: command.type,
+ success: true as const,
+ data:
+ command.type === "attach"
+ ? createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12)
+ : undefined,
+ };
+ },
+ close: () => {},
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+
+ const connection = await DaemonAgentConnection.attach(routed, "active-1");
+ await vi.waitFor(() => expect(supervisor.reconnectCount).toBe(1));
+
+ expect(routed.hasDirectTransport).toBe(true);
+ // Held-direct recovery is control-plane only: no re-attach crosses either socket.
+ expect(directRequests.filter((type) => type === "attach")).toHaveLength(1);
+ expect(supervisor.requests.filter((request) => request.type === "attach")).toHaveLength(0);
+ await connection.dispose();
+ });
+
+ it("rejects the fallback attach with the authoritative shutdown instead of parking it", async () => {
+ const supervisor = new FakeDaemonClient();
+ const attachOptions: (DaemonClientRequestOptions | undefined)[] = [];
+ const originalRequest = supervisor.request.bind(supervisor);
+ supervisor.request = async (command: DaemonCommand, timeoutMs?: number, options?: DaemonClientRequestOptions) => {
+ if (command.type === "attach") {
+ attachOptions.push(options);
+ throw new Error("supervisor socket is gone");
+ }
+ return originalRequest(command, timeoutMs ?? 30000, options ?? {});
+ };
+ const closeListeners = new Set<(error: Error) => void>();
+ let directConnected = true;
+ const direct = {
+ get isConnected() {
+ return directConnected;
+ },
+ hello: supervisor.hello,
+ supportsServerCapability: (capability: string) => supervisor.supportsServerCapability(capability),
+ onMessage: () => () => {},
+ onClose: (listener: (error: Error) => void) => {
+ closeListeners.add(listener);
+ return () => closeListeners.delete(listener);
+ },
+ request: async () => {
+ // The authoritative stop lands while the direct link is still up; then the direct attach dies.
+ supervisor.connected = false;
+ supervisor.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "shutdown"));
+ directConnected = false;
+ const error = new Error("direct attach socket closed");
+ for (const listener of [...closeListeners]) listener(error);
+ throw error;
+ },
+ close: () => {
+ directConnected = false;
+ },
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+
+ await expect(DaemonAgentConnection.attach(routed, "active-1")).rejects.toThrow("Reason: shutdown");
+ expect(attachOptions).toEqual([{ recoverable: false }]);
+ });
+
+ it("absorbs a direct loss inside the held roster re-attach into a session-plane reattach", async () => {
+ const supervisor = new FakeDaemonClient();
+ supervisor.serverCapabilities.add("agent_roster");
+ const closeListeners = new Set<(error: Error) => void>();
+ let directConnected = true;
+ let rosterSubscribes = 0;
+ const originalRequest = supervisor.request.bind(supervisor);
+ supervisor.request = async (command: DaemonCommand, timeoutMs?: number, options?: DaemonClientRequestOptions) => {
+ if (command.type === "roster_subscribe") {
+ rosterSubscribes++;
+ if (rosterSubscribes === 2) {
+ directConnected = false;
+ for (const listener of [...closeListeners]) listener(new Error("direct worker socket died"));
+ }
+ }
+ return originalRequest(command, timeoutMs ?? 30000, options ?? {});
+ };
+ const direct = {
+ get isConnected() {
+ return directConnected;
+ },
+ hello: supervisor.hello,
+ supportsServerCapability: (capability: string) => supervisor.supportsServerCapability(capability),
+ onMessage: () => () => {},
+ onClose: (listener: (error: Error) => void) => {
+ closeListeners.add(listener);
+ return () => closeListeners.delete(listener);
+ },
+ request: async (command: Extract<DaemonCommand, { type: "attach" }>) => ({
+ type: "response" as const,
+ command: "attach" as const,
+ success: true as const,
+ data: createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12),
+ }),
+ close: () => {
+ directConnected = false;
+ },
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+ const connection = await DaemonAgentConnection.attach(routed, "active-1");
+ await connection.subscribeAgentRoster(() => {});
+ const events: AgentConnectionEvent[] = [];
+ connection.subscribe(async (event) => {
+ events.push(event);
+ });
+ supervisor.hello = { ...supervisor.hello! };
+
+ supervisor.connected = false;
+ supervisor.emitClose(new Error("supervisor socket lost"));
+
+ await vi.waitFor(() => expect(events.filter((event) => event.type === "session_resynced")).toHaveLength(1));
+ expect(events.some((event) => event.type === "closed")).toBe(false);
+ expect(supervisor.requests.filter((request) => request.type === "attach")).toHaveLength(1);
+ await connection.dispose();
+ });
+
+ it("never emits connected after a shutdown that lands inside the held roster re-attach", async () => {
+ const supervisor = new FakeDaemonClient();
+ supervisor.serverCapabilities.add("agent_roster");
+ let rosterSubscribes = 0;
+ const originalRequest = supervisor.request.bind(supervisor);
+ supervisor.request = async (command: DaemonCommand, timeoutMs?: number, options?: DaemonClientRequestOptions) => {
+ if (command.type === "roster_subscribe") {
+ rosterSubscribes++;
+ if (rosterSubscribes === 2) {
+ supervisor.connected = false;
+ supervisor.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "shutdown"));
+ }
+ }
+ return originalRequest(command, timeoutMs ?? 30000, options ?? {});
+ };
+ const direct = {
+ isConnected: true,
+ hello: supervisor.hello,
+ supportsServerCapability: (capability: string) => supervisor.supportsServerCapability(capability),
+ onMessage: () => () => {},
+ onClose: () => () => {},
+ request: async (command: Extract<DaemonCommand, { type: "attach" }>) => ({
+ type: "response" as const,
+ command: "attach" as const,
+ success: true as const,
+ data: createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12),
+ }),
+ close: () => {},
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+ const connection = await DaemonAgentConnection.attach(routed, "active-1");
+ await connection.subscribeAgentRoster(() => {});
+ const events: AgentConnectionEvent[] = [];
+ connection.subscribe(async (event) => {
+ events.push(event);
+ });
+ supervisor.hello = { ...supervisor.hello! };
+
+ supervisor.connected = false;
+ supervisor.emitClose(new Error("supervisor socket lost"));
+
+ await vi.waitFor(() => expect(events.some((event) => event.type === "closed")).toBe(true));
+ expect(events.filter((event) => event.type === "closed")).toHaveLength(1);
+ expect(events.some((event) => event.type === "connection_status" && event.status === "connected")).toBe(false);
+ await connection.dispose();
+ });
+
+ it("stands down for update restoration when the update close lands inside the held roster re-attach", async () => {
+ const supervisor = new FakeDaemonClient();
+ supervisor.serverCapabilities.add("agent_roster");
+ supervisor.updateRestartSessions = [
+ {
+ id: "active-restored",
+ activeSessionId: "active-restored",
+ sessionId: "session-current",
+ sessionFile: "/tmp/session-current.jsonl",
+ },
+ ];
+ let rosterSubscribes = 0;
+ const originalRequest = supervisor.request.bind(supervisor);
+ supervisor.request = async (command: DaemonCommand, timeoutMs?: number, options?: DaemonClientRequestOptions) => {
+ if (command.type === "roster_subscribe") {
+ rosterSubscribes++;
+ if (rosterSubscribes === 2) {
+ supervisor.connected = false;
+ supervisor.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "update"));
+ }
+ }
+ return originalRequest(command, timeoutMs ?? 30000, options ?? {});
+ };
+ const direct = {
+ isConnected: true,
+ hello: supervisor.hello,
+ supportsServerCapability: (capability: string) => supervisor.supportsServerCapability(capability),
+ onMessage: () => () => {},
+ onClose: () => () => {},
+ request: async (command: Extract<DaemonCommand, { type: "attach" }>) => ({
+ type: "response" as const,
+ command: "attach" as const,
+ success: true as const,
+ data: createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12),
+ }),
+ close: () => {},
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+ // A short deadline would abort the restore if the held loop wrongly stayed its owner.
+ const connection = await DaemonAgentConnection.attach(routed, "active-1", { reconnectTimeoutMs: 30 });
+ await connection.subscribeAgentRoster(() => {});
+ const events: AgentConnectionEvent[] = [];
+ connection.subscribe(async (event) => {
+ events.push(event);
+ });
+ supervisor.hello = { ...supervisor.hello! };
+
+ supervisor.connected = false;
+ supervisor.emitClose(new Error("supervisor socket lost"));
+
+ await vi.waitFor(() => expect(events.some((event) => event.type === "session_resynced")).toBe(true), {
+ timeout: 5000,
+ });
+ expect(events.find((event) => event.type === "session_resynced")).toMatchObject({
+ snapshot: { state: { activeSessionId: "active-restored" } },
+ });
+ expect(events.some((event) => event.type === "closed")).toBe(false);
+ await connection.dispose();
+ });
+
+ it("rebinds the roster subscription onto the recovered supervisor socket while the direct link holds", async () => {
+ const supervisor = new FakeDaemonClient();
+ supervisor.serverCapabilities.add("agent_roster");
+ const direct = {
+ isConnected: true,
+ hello: supervisor.hello,
+ supportsServerCapability: (capability: string) => supervisor.supportsServerCapability(capability),
+ onMessage: () => () => {},
+ onClose: () => () => {},
+ request: async (command: Extract<DaemonCommand, { type: "attach" }>) => ({
+ type: "response" as const,
+ command: "attach" as const,
+ success: true as const,
+ data: createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12),
+ }),
+ close: () => {},
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+ const connection = await DaemonAgentConnection.attach(routed, "active-1");
+ await connection.subscribeAgentRoster(() => {});
+ // A reconnect delivers a fresh hello object; the roster store keys its subscription on it.
+ supervisor.hello = { ...supervisor.hello! };
+
+ supervisor.connected = false;
+ supervisor.emitClose(new Error("supervisor socket lost"));
+
+ await vi.waitFor(() =>
+ expect(supervisor.requests.filter((request) => request.type === "roster_subscribe")).toHaveLength(2),
+ );
+ expect(routed.hasDirectTransport).toBe(true);
+ expect(supervisor.requests.filter((request) => request.type === "attach")).toHaveLength(0);
+ await connection.dispose();
+ });
+
+ it("resets a half-open supervisor handshake without closing the healthy direct socket", async () => {
+ const supervisor = new FakeDaemonClient();
+ const direct = {
+ isConnected: true,
+ hello: supervisor.hello,
+ supportsServerCapability: (capability: string) => supervisor.supportsServerCapability(capability),
+ onMessage: () => () => {},
+ onClose: () => () => {},
+ request: async (command: Extract<DaemonCommand, { type: "attach" }>) => ({
+ type: "response" as const,
+ command: "attach" as const,
+ success: true as const,
+ data: createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12),
+ }),
+ close: () => {},
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+ const connection = await DaemonAgentConnection.attach(routed, "active-1");
+ const events: AgentConnectionEvent[] = [];
+ connection.subscribe(async (event) => {
+ events.push(event);
+ });
+ let helloAttempts = 0;
+ supervisor.waitForHello = vi.fn(async () => {
+ helloAttempts++;
+ if (helloAttempts === 1) throw new Error("hello timed out on half-open socket");
+ return supervisor.hello!;
+ });
+ supervisor.connected = false;
+ supervisor.emitClose(new Error("supervisor socket closed"));
+
+ await vi.waitFor(() =>
+ expect(events.some((event) => event.type === "connection_status" && event.status === "connected")).toBe(true),
+ );
+
+ expect(supervisor.reconnectCount).toBe(2);
+ expect(supervisor.resetTransportCount).toBe(1);
+ expect(routed.hasDirectTransport).toBe(true);
+ await connection.dispose();
+ });
+
+ it("keeps a parent direct transport intact when watching another session", async () => {
+ const supervisor = new FakeDaemonClient();
+ const directRequests: DaemonCommand[] = [];
+ const direct = {
+ isConnected: true,
+ hello: supervisor.hello,
+ supportsServerCapability: (capability: string) => supervisor.supportsServerCapability(capability),
+ onMessage: () => () => {},
+ onClose: () => () => {},
+ request: async (command: DaemonCommand) => {
+ directRequests.push(command);
+ if (command.type === "attach") {
+ return {
+ type: "response" as const,
+ command: "attach" as const,
+ success: true as const,
+ data: createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12),
+ };
+ }
+ return { type: "response" as const, command: command.type, success: true as const };
+ },
+ close: () => {},
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+ const parent = await DaemonAgentConnection.attach(routed, "source-active");
+
+ const watcher = await parent.watchSession("target-active");
+
+ expect(watcher).toBeDefined();
+ await expect(parent.getState()).resolves.toMatchObject({ activeSessionId: "source-active" });
+ expect(routed.hasDirectTransport).toBe(true);
+ expect(
+ directRequests.some((request) => request.type === "attach" && request.activeSessionId === "target-active"),
+ ).toBe(false);
+ await watcher?.close();
+ await parent.dispose();
+ });
+
+ it("keeps a clean daemon stop terminal even while the direct link is healthy", async () => {
+ const supervisor = new FakeDaemonClient();
+ const direct = {
+ isConnected: true,
+ hello: supervisor.hello,
+ supportsServerCapability: (capability: string) => supervisor.supportsServerCapability(capability),
+ onMessage: () => () => {},
+ onClose: () => () => {},
+ request: async (command: Extract<DaemonCommand, { type: "attach" }>) => ({
+ type: "response" as const,
+ command: "attach" as const,
+ success: true as const,
+ data: createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12),
+ }),
+ close: () => {},
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+ const connection = await DaemonAgentConnection.attach(routed, "active-1", {
+ recoverDaemon: async () => {},
+ });
+ const events: AgentConnectionEvent[] = [];
+ connection.subscribe(async (event) => {
+ events.push(event);
+ });
+
+ supervisor.connected = false;
+ supervisor.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "shutdown"));
+ await vi.waitFor(() => expect(events.some((event) => event.type === "closed")).toBe(true));
+
+ expect(events.find((event) => event.type === "closed")).toMatchObject({
+ error: expect.stringContaining("daemon shut down"),
+ });
+ expect(supervisor.reconnectCount).toBe(0);
+ await connection.dispose();
+ });
+
+ it("routes an update close through update restoration and drops the stale direct link", async () => {
+ const supervisor = new FakeDaemonClient();
+ supervisor.updateRestartSessions = [
+ {
+ id: "active-restored",
+ activeSessionId: "active-restored",
+ sessionId: "session-current",
+ sessionFile: "/tmp/session-current.jsonl",
+ },
+ ];
+ const direct = {
+ isConnected: true,
+ hello: supervisor.hello,
+ supportsServerCapability: (capability: string) => supervisor.supportsServerCapability(capability),
+ onMessage: () => () => {},
+ onClose: () => () => {},
+ request: async (command: Extract<DaemonCommand, { type: "attach" }>) => ({
+ type: "response" as const,
+ command: "attach" as const,
+ success: true as const,
+ data: createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12),
+ }),
+ close: () => {},
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+ const connection = await DaemonAgentConnection.attach(routed, "active-1");
+ const restored = new Promise<AgentConnectionEvent>((resolve) => {
+ connection.subscribe(async (event) => {
+ if (event.type === "session_resynced") resolve(event);
+ });
+ });
+
+ supervisor.connected = false;
+ supervisor.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "update"));
+
+ await expect(restored).resolves.toMatchObject({ type: "session_resynced" });
+ expect(routed.hasDirectTransport).toBe(false);
+ await connection.dispose();
+ });
+
+ it("falls back to the supervisor when the direct socket dies mid-session without recoverDaemon", async () => {
+ const supervisor = new FakeDaemonClient();
+ const closeListeners = new Set<(error: Error) => void>();
+ let directConnected = true;
+ const direct = {
+ get isConnected() {
+ return directConnected;
+ },
+ hello: supervisor.hello,
+ supportsServerCapability: (capability: string) => supervisor.supportsServerCapability(capability),
+ onMessage: () => () => {},
+ onClose: (listener: (error: Error) => void) => {
+ closeListeners.add(listener);
+ return () => closeListeners.delete(listener);
+ },
+ request: async (command: Extract<DaemonCommand, { type: "attach" }>) => ({
+ type: "response" as const,
+ command: "attach" as const,
+ success: true as const,
+ data: createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12),
+ }),
+ close: () => {
+ directConnected = false;
+ },
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+ const connection = await DaemonAgentConnection.attach(routed, "active-1");
+ const events: AgentConnectionEvent[] = [];
+ connection.subscribe(async (event) => {
+ events.push(event);
+ });
+ supervisor.serverCapabilities.add("session_input_pause");
+ const pause = await connection.acquireSessionInputPause("lease-1");
+
+ directConnected = false;
+ for (const listener of [...closeListeners]) listener(new Error("direct worker socket died"));
+
+ await vi.waitFor(() => expect(events.filter((event) => event.type === "session_resynced")).toHaveLength(1));
+ expect(events.some((event) => event.type === "closed")).toBe(false);
+ expect(supervisor.requests.filter((request) => request.type === "attach")).toHaveLength(1);
+ // The fence died with the direct link; its holder learns on release while the session lives on.
+ await expect(pause.release()).rejects.toThrow("invalidated by a daemon reconnect");
+ await connection.dispose();
+ });
+
+ it("keeps a shutdown during initial direct attach terminal instead of respawning the daemon", async () => {
+ const supervisor = new FakeDaemonClient();
+ const recoverDaemon = vi.fn(async () => {});
+ let closeSent = false;
+ const direct = {
+ isConnected: true,
+ hello: supervisor.hello,
+ supportsServerCapability: (capability: string) => supervisor.supportsServerCapability(capability),
+ onMessage: () => () => {},
+ onClose: () => () => {},
+ request: async (command: Extract<DaemonCommand, { type: "attach" }>) => {
+ if (!closeSent) {
+ closeSent = true;
+ supervisor.connected = false;
+ supervisor.emitClose(new DaemonSocketClosedError("/tmp/prime-agent.sock", "shutdown"));
+ }
+ return {
+ type: "response" as const,
+ command: "attach" as const,
+ success: true as const,
+ data: createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12),
+ };
+ },
+ close: () => {},
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+
+ // No listener can exist during construction, so the terminal close must reject the attach.
+ await expect(DaemonAgentConnection.attach(routed, "active-1", { recoverDaemon })).rejects.toThrow(
+ "Reason: shutdown",
+ );
+ await new Promise((resolveSettle) => setImmediate(resolveSettle));
+ expect(recoverDaemon).not.toHaveBeenCalled();
+ expect(supervisor.reconnectCount).toBe(0);
+ });
+
+ it("takes update restoration when the direct link closes for an update while a pause is held", async () => {
+ const supervisor = new FakeDaemonClient();
+ supervisor.serverCapabilities.add("session_input_pause");
+ supervisor.updateRestartSessions = [
+ {
+ id: "active-restored",
+ activeSessionId: "active-restored",
+ sessionId: "session-current",
+ sessionFile: "/tmp/session-current.jsonl",
+ },
+ ];
+ const closeListeners = new Set<(error: Error) => void>();
+ let directConnected = true;
+ const direct = {
+ get isConnected() {
+ return directConnected;
+ },
+ hello: supervisor.hello,
+ supportsServerCapability: (capability: string) => supervisor.supportsServerCapability(capability),
+ onMessage: () => () => {},
+ onClose: (listener: (error: Error) => void) => {
+ closeListeners.add(listener);
+ return () => closeListeners.delete(listener);
+ },
+ request: async (command: Extract<DaemonCommand, { type: "attach" }>) => ({
+ type: "response" as const,
+ command: "attach" as const,
+ success: true as const,
+ data: createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12),
+ }),
+ close: () => {
+ directConnected = false;
+ },
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+ const connection = await DaemonAgentConnection.attach(routed, "active-1");
+ const events: AgentConnectionEvent[] = [];
+ connection.subscribe(async (event) => {
+ events.push(event);
+ });
+ await connection.acquireSessionInputPause("lease-1");
+
+ directConnected = false;
+ for (const listener of [...closeListeners]) {
+ listener(new DaemonSocketClosedError("/tmp/worker.sock", "update"));
+ }
+
+ await vi.waitFor(() => expect(events.some((event) => event.type === "session_resynced")).toBe(true));
+ expect(events.some((event) => event.type === "closed")).toBe(false);
+ await connection.dispose();
+ });
+
+ it("outlives the reconnect deadline while the direct link streams, then bounds recovery once it dies", async () => {
+ const supervisor = new FakeDaemonClient();
+ const closeListeners = new Set<(error: Error) => void>();
+ let directConnected = true;
+ const direct = {
+ get isConnected() {
+ return directConnected;
+ },
+ hello: supervisor.hello,
+ supportsServerCapability: (capability: string) => supervisor.supportsServerCapability(capability),
+ onMessage: () => () => {},
+ onClose: (listener: (error: Error) => void) => {
+ closeListeners.add(listener);
+ return () => closeListeners.delete(listener);
+ },
+ request: async (command: Extract<DaemonCommand, { type: "attach" }>) => ({
+ type: "response" as const,
+ command: "attach" as const,
+ success: true as const,
+ data: createAttachResult(command.activeSessionId, command.clientId, command.capabilities, 12),
+ }),
+ close: () => {
+ directConnected = false;
+ },
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+ const connection = await DaemonAgentConnection.attach(routed, "active-1", { reconnectTimeoutMs: 60 });
+ const events: AgentConnectionEvent[] = [];
+ connection.subscribe(async (event) => {
+ events.push(event);
+ });
+
+ supervisor.connected = false;
+ supervisor.reconnectError = new Error("supervisor is down");
+ supervisor.emitClose(new Error("supervisor socket lost"));
+ // Three failed control-plane attempts span well past the 60ms deadline.
+ await vi.waitFor(() => expect(supervisor.resetTransportCount).toBeGreaterThanOrEqual(3));
+
+ expect(events.some((event) => event.type === "closed")).toBe(false);
+ expect(supervisor.requests.filter((request) => request.type === "attach")).toHaveLength(0);
+
+ directConnected = false;
+ for (const listener of [...closeListeners]) listener(new Error("direct worker socket died"));
+
+ await vi.waitFor(() => expect(events.some((event) => event.type === "closed")).toBe(true), { timeout: 8000 });
+ expect(events.find((event) => event.type === "closed")).toMatchObject({
+ error: expect.stringContaining("Daemon reconnection failed"),
+ });
+ expect(events.filter((event) => event.type === "session_resynced")).toHaveLength(0);
+ await connection.dispose();
+ }, 10_000);
+
+ it("keeps the source direct socket when a cross-worker reattach is rejected", async () => {
+ const supervisor = new FakeDaemonClient();
+ supervisor.request = vi.fn(async (command: DaemonCommand) => ({
+ type: "response" as const,
+ command: command.type,
+ success: false as const,
+ error: "target disappeared",
+ }));
+ const close = vi.fn();
+ const direct = {
+ isConnected: true,
+ onMessage: () => () => {},
+ onClose: () => () => {},
+ close,
+ } as unknown as DaemonWorkerClient;
+ const routed = new DaemonRoutedClient(asDaemonClient(supervisor), direct);
+
+ const response = await routed.request({
+ type: "reattach",
+ activeSessionId: "source-active",
+ targetActiveSessionId: "missing-target",
+ });
+
+ expect(response.success).toBe(false);
+ expect(close).not.toHaveBeenCalled();
+ expect(routed.hasDirectTransport).toBe(true);
+ routed.close();
+ });
+
it("carries an opt-out-only telemetry policy on attach", async () => {
const fakeClient = new FakeDaemonClient();
const connection = new DaemonAgentConnection(asDaemonClient(fakeClient), "active-1", {
@@ -2143,10 +2835,14 @@ describe("DaemonAgentConnection", () => {
reconnectTimeoutMs: 2000,
});
const statuses: string[] = [];
+ let resyncs = 0;
connection.subscribe((event) => {
if (event.type === "connection_status") {
statuses.push(event.status);
}
+ if (event.type === "session_resynced") {
+ resyncs++;
+ }
});
await connection.attach();
@@ -2159,6 +2855,7 @@ describe("DaemonAgentConnection", () => {
expect(fakeClient.reconnectCount).toBe(2);
expect(fakeClient.resetTransportCount).toBe(1);
expect(fakeClient.requests.filter((request) => request.type === "attach")).toHaveLength(3);
+ expect(resyncs).toBe(1);
});
it("does not reconnect after disposal while daemon recovery is pending", async () => {
diff --git a/packages/coding-agent/test/daemon-client.test.ts b/packages/coding-agent/test/daemon-client.test.ts
index 2a28c47da3..f7614733fa 100644
--- a/packages/coding-agent/test/daemon-client.test.ts
+++ b/packages/coding-agent/test/daemon-client.test.ts
@@ -248,6 +248,21 @@ describe("DaemonClient", () => {
await expect(request).rejects.toThrow("closed before the operation completed");
});
+ it("does not send direct transport discovery to a daemon without the capability", async () => {
+ const client = new DaemonClient("/tmp/prime-agent.sock");
+ const connect = client.connect();
+ const socket = netMock.sockets[0]!;
+ socket.emit("connect");
+ await connect;
+ emitHello(socket, DAEMON_PROTOCOL_VERSION, [], DAEMON_SCHEMA_REVISION);
+
+ await expect(
+ client.request({ type: "get_direct_worker_transport", activeSessionId: "active-1" }),
+ ).rejects.toThrow("does not support direct_peer_transport");
+ expect(socket.writes).toEqual([]);
+ client.close();
+ });
+
it("rejects an old daemon before requesting session state", async () => {
const client = new DaemonClient("/tmp/prime-agent.sock");
const connect = client.connect();
diff --git a/packages/coding-agent/test/daemon-peer-transport.test.ts b/packages/coding-agent/test/daemon-peer-transport.test.ts
new file mode 100644
index 0000000000..da785ef18d
--- /dev/null
+++ b/packages/coding-agent/test/daemon-peer-transport.test.ts
@@ -0,0 +1,477 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { createServer, type Socket } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it, vi } from "vitest";
+import { getProcessStartId } from "../src/core/session-lease.js";
+import type { ActiveSessionState, DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";
+import { AgentRoster, workerRosterEntryFromSummary } from "../src/modes/daemon/agent-roster.js";
+import { AgentDaemon } from "../src/modes/daemon/daemon-mode.js";
+import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";
+import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";
+import type { DaemonWorkerCommand, DaemonWorkerPeerGrant } from "../src/modes/daemon/daemon-worker-protocol.js";
+
+interface WorkerInternals {
+ handleLine(client: DaemonSocketClient, line: string): Promise<void>;
+ handleWorkerCommand(client: DaemonSocketClient, command: DaemonWorkerCommand): Promise<void>;
+ supervisorClaims: Map<DaemonSocketClient, { claim: { supervisorGeneration: string }; ownerFingerprint: string }>;
+ peerGrants: Map<string, DaemonWorkerPeerGrant>;
+ peerClaims: Map<DaemonSocketClient, DaemonWorkerPeerGrant>;
+ sessions: Map<string, ActiveSessionState>;
+ fencePeerTransports(closingReason?: "shutdown" | "update"): void;
+ closeSession(state: ActiveSessionState, reason: string): Promise<void>;
+ shutdown(exitCode: number): Promise<never>;
+}
+
+interface FakePeerSocket {
+ client: DaemonSocketClient;
+ responses: { type?: string; reason?: string; command?: string; success?: boolean; error?: string }[];
+ endMock: ReturnType<typeof vi.fn>;
+}
+
+function makeWorkerDaemon(): WorkerInternals {
+ const daemon = new AgentDaemon("/tmp/prime-agent-peer-test.sock", {
+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-peer-test-agent", cwd: "/tmp" },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ worker: { authenticationToken: "worker-token", workerInstanceId: "instance-1" },
+ });
+ return daemon as unknown as WorkerInternals;
+}
+
+function makeSocketClient(id: string, authenticated: boolean): FakePeerSocket {
+ const responses: FakePeerSocket["responses"] = [];
+ const endMock = vi.fn();
+ const socket = {
+ destroyed: false,
+ write: (data: string | Buffer) => {
+ responses.push(JSON.parse(String(data)) as FakePeerSocket["responses"][number]);
+ return true;
+ },
+ end: endMock,
+ } as unknown as Socket;
+ return {
+ client: {
+ id,
+ socket,
+ attachedActiveSessionIds: new Set(),
+ authenticated,
+ transport: "jsonl",
+ detachInput: () => {},
+ supportsExtensionUi: false,
+ capabilities: new Set(),
+ },
+ responses,
+ endMock,
+ };
+}
+
+function makeGrant(overrides: Partial<DaemonWorkerPeerGrant> = {}): DaemonWorkerPeerGrant {
+ return {
+ grantId: "grant-1",
+ token: "peer-token",
+ expiresAt: new Date(Date.now() + 10_000).toISOString(),
+ purpose: "session_client",
+ workerInstanceId: "instance-1",
+ activeSessionId: "active-1",
+ issuerGeneration: "gen-1",
+ ...overrides,
+ };
+}
+
+async function registerGrant(
+ internals: WorkerInternals,
+ supervisor: FakePeerSocket,
+ grant: DaemonWorkerPeerGrant,
+): Promise<{ success?: boolean; error?: string }> {
+ await internals.handleWorkerCommand(supervisor.client, {
+ id: `register-${grant.grantId}`,
+ type: "worker_register_peer_transport",
+ grant,
+ });
+ return supervisor.responses.at(-1)!;
+}
+
+function makeSupervisor(internals: WorkerInternals): FakePeerSocket {
+ const supervisor = makeSocketClient("supervisor-1", true);
+ supervisor.client.authenticationRole = "supervisor";
+ internals.supervisorClaims.set(supervisor.client, {
+ claim: { supervisorGeneration: "gen-1" },
+ ownerFingerprint: "fp",
+ });
+ return supervisor;
+}
+
+async function authenticatePeer(
+ internals: WorkerInternals,
+ peer: FakePeerSocket,
+ overrides: Record<string, unknown> = {},
+): Promise<{ success?: boolean; error?: string }> {
+ await internals.handleLine(
+ peer.client,
+ JSON.stringify({
+ id: "auth-1",
+ type: "peer_auth",
+ grantId: "grant-1",
+ token: "peer-token",
+ workerInstanceId: "instance-1",
+ purpose: "session_client",
+ ...overrides,
+ }),
+ );
+ return peer.responses.at(-1)!;
+}
+
+describe("daemon worker peer transport", () => {
+ it("admits exactly one peer_auth per registered grant and burns the grant before checking it", async () => {
+ const internals = makeWorkerDaemon();
+ const supervisor = makeSupervisor(internals);
+ internals.sessions.set("active-1", {} as ActiveSessionState);
+ expect(await registerGrant(internals, supervisor, makeGrant())).toMatchObject({ success: true });
+
+ const peer = makeSocketClient("peer-1", false);
+ expect(await authenticatePeer(internals, peer)).toMatchObject({ success: true });
+ expect(peer.client.authenticationRole).toBe("session_client");
+ expect(internals.peerClaims.get(peer.client)).toMatchObject({ activeSessionId: "active-1" });
+ expect(internals.peerGrants.size).toBe(0);
+
+ const replay = makeSocketClient("peer-2", false);
+ expect(await authenticatePeer(internals, replay)).toMatchObject({
+ success: false,
+ error: expect.stringContaining("Peer authentication failed"),
+ });
+ expect(replay.endMock).toHaveBeenCalled();
+ });
+
+ it("rejects invalid grants at registration time", async () => {
+ const internals = makeWorkerDaemon();
+ const supervisor = makeSupervisor(internals);
+ internals.sessions.set("active-1", {} as ActiveSessionState);
+ const invalidGrants = [
+ makeGrant({ issuerGeneration: "stale-gen" }),
+ makeGrant({ workerInstanceId: "instance-2" }),
+ makeGrant({ activeSessionId: "active-9" }),
+ makeGrant({ expiresAt: new Date(Date.now() - 1).toISOString() }),
+ makeGrant({ expiresAt: new Date(Date.now() + 60_000).toISOString() }),
+ ];
+ for (const grant of invalidGrants) {
+ expect(await registerGrant(internals, supervisor, grant)).toMatchObject({
+ success: false,
+ error: expect.stringContaining("Peer transport grant is invalid"),
+ });
+ }
+ expect(internals.peerGrants.size).toBe(0);
+ });
+
+ it("rejects an expired grant on presentation and ends the socket", async () => {
+ const internals = makeWorkerDaemon();
+ internals.peerGrants.set("grant-1", makeGrant({ expiresAt: new Date(Date.now() - 1).toISOString() }));
+
+ const peer = makeSocketClient("peer-1", false);
+ expect(await authenticatePeer(internals, peer)).toMatchObject({ success: false });
+ expect(peer.endMock).toHaveBeenCalled();
+ expect(internals.peerGrants.size).toBe(0);
+ });
+
+ it("rejects a peer_auth whose presented instance id does not match the grant", async () => {
+ const internals = makeWorkerDaemon();
+ internals.peerGrants.set("grant-1", makeGrant());
+
+ const peer = makeSocketClient("peer-1", false);
+ expect(await authenticatePeer(internals, peer, { workerInstanceId: "instance-2" })).toMatchObject({
+ success: false,
+ });
+ expect(peer.endMock).toHaveBeenCalled();
+ });
+
+ it("ends a pre-auth socket that sends anything but an authentication command", async () => {
+ const internals = makeWorkerDaemon();
+ const stranger = makeSocketClient("stranger-1", false);
+ await internals.handleLine(stranger.client, JSON.stringify({ id: "l1", type: "list" }));
+ expect(stranger.responses.at(-1)).toMatchObject({ success: false });
+ expect(stranger.endMock).toHaveBeenCalled();
+ expect(stranger.client.authenticated).toBe(false);
+ });
+
+ it("scopes an authenticated peer to the session plane of its granted session", async () => {
+ const internals = makeWorkerDaemon();
+ internals.peerGrants.set("grant-1", makeGrant());
+ const peer = makeSocketClient("peer-1", false);
+ expect(await authenticatePeer(internals, peer)).toMatchObject({ success: true });
+
+ const rejected = [
+ { id: "other-session", type: "get_state", activeSessionId: "active-2" },
+ { id: "control-plane", type: "list" },
+ { id: "worker-control", type: "worker_subscribe", activeSessionId: "active-1" },
+ { id: "unknown-command", type: "no_such_command", activeSessionId: "active-1" },
+ ];
+ for (const command of rejected) {
+ await internals.handleLine(peer.client, JSON.stringify(command));
+ expect(peer.responses.at(-1)).toMatchObject({
+ success: false,
+ error: expect.stringContaining("not allowed on this direct peer transport"),
+ });
+ }
+
+ // An in-scope session-plane command passes admission (and then fails only
+ // because this fixture has no live session behind the id).
+ await internals.handleLine(
+ peer.client,
+ JSON.stringify({ id: "in-scope", type: "wait_for_idle", activeSessionId: "active-1" }),
+ );
+ expect(peer.responses.at(-1)?.error ?? "").not.toContain("not allowed on this direct peer transport");
+ });
+
+ it("fences grants and live peers during worker update preparation until the update is cancelled", async () => {
+ const internals = makeWorkerDaemon();
+ const supervisor = makeSupervisor(internals);
+ internals.sessions.set("active-1", {} as ActiveSessionState);
+ internals.peerGrants.set("grant-1", makeGrant());
+ const peer = makeSocketClient("peer-1", false);
+ expect(await authenticatePeer(internals, peer)).toMatchObject({ success: true });
+
+ internals.fencePeerTransports("update");
+
+ expect(peer.endMock).toHaveBeenCalled();
+ // The update reason reaches the peer before FIN so its close never looks like a transport loss.
+ expect(peer.responses.at(-1)).toMatchObject({ type: "daemon_closing", reason: "update" });
+ expect(internals.peerClaims.size).toBe(0);
+ expect(await registerGrant(internals, supervisor, makeGrant({ grantId: "grant-2" }))).toMatchObject({
+ success: false,
+ });
+
+ await internals.handleWorkerCommand(supervisor.client, { id: "cancel-1", type: "worker_cancel_update" });
+ expect(supervisor.responses.at(-1)).toMatchObject({ success: true });
+ expect(await registerGrant(internals, supervisor, makeGrant({ grantId: "grant-3" }))).toMatchObject({
+ success: true,
+ });
+ });
+
+ it("delivers session_closed to direct peers before the archive shutdown ends their sockets", async () => {
+ const internals = makeWorkerDaemon();
+ const supervisor = makeSupervisor(internals);
+ internals.sessions.set("active-1", {} as ActiveSessionState);
+ internals.peerGrants.set("grant-1", makeGrant());
+ const peer = makeSocketClient("peer-1", false);
+ expect(await authenticatePeer(internals, peer)).toMatchObject({ success: true });
+ let peerEndedWhenSessionClosed: boolean | undefined;
+ (internals as { closeSession: unknown }).closeSession = vi.fn(async () => {
+ peerEndedWhenSessionClosed = peer.endMock.mock.calls.length > 0;
+ });
+ (internals as { shutdown: unknown }).shutdown = vi.fn(async () => undefined);
+
+ await internals.handleWorkerCommand(supervisor.client, { id: "archive-1", type: "worker_archive_and_shutdown" });
+
+ expect(peerEndedWhenSessionClosed).toBe(false);
+ expect(peer.endMock).toHaveBeenCalled();
+ });
+
+ it("authenticates a downgraded supervisor that presents no worker instance id", async () => {
+ const makeAuthDaemon = () =>
+ Object.assign(Object.create(AgentDaemon.prototype), {
+ options: { worker: { authenticationToken: "worker-token", workerInstanceId: "instance-1" } },
+ supervisorClaims: new Map(),
+ peerClaims: new Map(),
+ peerGrants: new Map(),
+ clearSupervisorAvailabilityCheck: vi.fn(),
+ scheduleSupervisorFenceCheck: vi.fn(),
+ scheduleRosterFlush: vi.fn(),
+ rosterReporter: { snapshotPending: false },
+ assertSupervisorClaimCurrent: vi.fn(async () => "fingerprint"),
+ }) as unknown as WorkerInternals;
+ const auth = (workerInstanceId?: string) =>
+ JSON.stringify({
+ id: "auth-1",
+ type: "worker_auth",
+ token: "worker-token",
+ ...(workerInstanceId !== undefined ? { workerInstanceId } : {}),
+ supervisorGeneration: "gen-1",
+ supervisorPid: 123,
+ supervisorSocketPath: "/tmp/supervisor.sock",
+ });
+
+ const legacySupervisor = makeSocketClient("legacy", false);
+ await makeAuthDaemon().handleLine(legacySupervisor.client, auth());
+ expect(legacySupervisor.responses.at(-1)).toMatchObject({ success: true });
+ expect(legacySupervisor.client.authenticationRole).toBe("supervisor");
+
+ const staleSupervisor = makeSocketClient("stale", false);
+ await makeAuthDaemon().handleLine(staleSupervisor.client, auth("instance-0"));
+ expect(staleSupervisor.responses.at(-1)).toMatchObject({ success: false });
+ expect(staleSupervisor.endMock).toHaveBeenCalled();
+ });
+
+ it("flushes the roster when a direct viewer attaches or detaches without other session activity", async () => {
+ const internals = makeWorkerDaemon() as WorkerInternals & {
+ scheduleRosterFlush: ReturnType<typeof vi.fn>;
+ createAttachResult: ReturnType<typeof vi.fn>;
+ handleCommand(
+ client: DaemonSocketClient,
+ command: { type: string; activeSessionId: string },
+ ): Promise<unknown>;
+ detachClientFromSession(client: DaemonSocketClient, state: ActiveSessionState): void;
+ };
+ internals.scheduleRosterFlush = vi.fn();
+ internals.createAttachResult = vi.fn(async () => ({
+ activeSessionId: "active-1",
+ snapshot: {},
+ lastEventSequence: 0,
+ }));
+ const state = {
+ activeSessionId: "active-1",
+ clients: new Set(),
+ pendingAttaches: 0,
+ lastEventSequence: 0,
+ extensionUiRequests: new Map(),
+ runtime: { metadata: { kind: "top-level", createdAt: 1 } },
+ } as unknown as ActiveSessionState;
+ internals.sessions.set("active-1", state);
+ const peer = makeSocketClient("peer-1", true);
+ peer.client.authenticationRole = "session_client";
+
+ await internals.handleCommand(peer.client, { type: "attach", activeSessionId: "active-1" });
+ expect(internals.scheduleRosterFlush).toHaveBeenCalledTimes(1);
+
+ internals.detachClientFromSession(peer.client, state);
+ expect(internals.scheduleRosterFlush).toHaveBeenCalledTimes(2);
+
+ // Supervisor-relayed viewers keep their event-driven cadence; only direct peers are carrier-less.
+ const relayed = makeSocketClient("relayed-1", true);
+ await internals.handleCommand(relayed.client, { type: "attach", activeSessionId: "active-1" });
+ expect(internals.scheduleRosterFlush).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe("supervisor direct transport issuance", () => {
+ interface SupervisorInternals {
+ issuePeerTransport(
+ worker: unknown,
+ summary: SessionSummary,
+ ): Promise<{
+ purpose: string;
+ socketPath: string;
+ socketIdentity?: { dev: number; ino: number };
+ workerInstanceId: string;
+ activeSessionId: string;
+ grantId: string;
+ token: string;
+ expiresAt: string;
+ }>;
+ workerEvictionSnapshot(worker: unknown): { sessions: { attachedClients: number }[] };
+ }
+
+ function makeIssuingSupervisor(
+ requestWorker: ReturnType<typeof vi.fn>,
+ summary: SessionSummary,
+ ): SupervisorInternals {
+ return Object.assign(Object.create(DaemonSupervisor.prototype), {
+ generation: "gen-1",
+ assertCurrentOwnership: vi.fn(async () => undefined),
+ refreshWorkerSummaries: vi.fn(async () => undefined),
+ requireAvailableWorkerClient: vi.fn(() => ({ requestWorker })),
+ findSummaryInWorker: vi.fn(() => summary),
+ processIdentity: vi.fn(() => "current"),
+ }) as unknown as SupervisorInternals;
+ }
+
+ it("issues a dev/ino-bound single-use ticket only after the worker accepted the grant", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-agent-peer-ticket-"));
+ const socketPath = join(directory, "worker.sock");
+ const server = createServer();
+ await new Promise<void>((resolveListen) => server.listen(socketPath, resolveListen));
+ try {
+ const summary = { id: "target-1", activeSessionId: "target-1" } as unknown as SessionSummary;
+ const requestWorker = vi.fn(async (_command: unknown) => ({
+ type: "response",
+ command: "attach",
+ success: true,
+ }));
+ const supervisor = makeIssuingSupervisor(requestWorker, summary);
+ const worker = {
+ peerTransportCapable: true,
+ descriptor: {
+ workerId: "worker-1",
+ workerInstanceId: "instance-1",
+ pid: process.pid,
+ processStartId: getProcessStartId(process.pid),
+ socketPath,
+ rootActiveSessionId: "target-1",
+ },
+ };
+
+ const ticket = await supervisor.issuePeerTransport(worker, summary);
+
+ expect(ticket).toMatchObject({
+ purpose: "session_client",
+ socketPath,
+ workerInstanceId: "instance-1",
+ activeSessionId: "target-1",
+ });
+ expect(ticket.socketIdentity).toEqual(
+ expect.objectContaining({ dev: expect.any(Number), ino: expect.any(Number) }),
+ );
+ expect(requestWorker).toHaveBeenCalledOnce();
+ expect(requestWorker.mock.calls[0]?.[0]).toMatchObject({
+ type: "worker_register_peer_transport",
+ grant: {
+ grantId: ticket.grantId,
+ token: ticket.token,
+ expiresAt: ticket.expiresAt,
+ purpose: "session_client",
+ workerInstanceId: "instance-1",
+ activeSessionId: "target-1",
+ issuerGeneration: "gen-1",
+ },
+ });
+ } finally {
+ await new Promise<void>((resolveClose) => server.close(() => resolveClose()));
+ rmSync(directory, { recursive: true, force: true });
+ }
+ });
+
+ it("refuses tickets for workers that predate peer transport", async () => {
+ const summary = { id: "target-1", activeSessionId: "target-1" } as unknown as SessionSummary;
+ const requestWorker = vi.fn();
+ const supervisor = makeIssuingSupervisor(requestWorker, summary);
+ const worker = {
+ peerTransportCapable: false,
+ descriptor: {
+ workerId: "worker-1",
+ workerInstanceId: "instance-1",
+ pid: process.pid,
+ processStartId: getProcessStartId(process.pid),
+ socketPath: "/tmp/prime-agent-peer-missing.sock",
+ },
+ };
+
+ await expect(supervisor.issuePeerTransport(worker, summary)).rejects.toThrow(
+ "does not support direct peer transport",
+ );
+ expect(requestWorker).not.toHaveBeenCalled();
+ });
+
+ it("counts worker-reported direct attachments in idle-eviction snapshots", () => {
+ const summary = {
+ id: "target-1",
+ activeSessionId: "target-1",
+ sessionId: "session-target",
+ directAttachedClients: 1,
+ attachedClients: 2,
+ isStreaming: false,
+ isSessionActive: false,
+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },
+ } as unknown as SessionSummary;
+ const roster = new AgentRoster((path) => path);
+ roster.write(workerRosterEntryFromSummary(summary), "worker-1");
+ const supervisor = Object.assign(Object.create(DaemonSupervisor.prototype), {
+ clients: new Set(),
+ rosterStore: roster,
+ updateRestartPhase: undefined,
+ isWorkerStopping: vi.fn(() => false),
+ }) as unknown as SupervisorInternals;
+ const worker = { descriptor: { workerId: "worker-1", lifecycle: "ready" }, client: {} };
+
+ expect(supervisor.workerEvictionSnapshot(worker).sessions[0]?.attachedClients).toBe(1);
+ });
+});
diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.ts
index ef8079c91b..1cdde72a54 100644
--- a/packages/coding-agent/test/daemon-protocol.test.ts
+++ b/packages/coding-agent/test/daemon-protocol.test.ts
@@ -9,6 +9,7 @@ import {
createDaemonEventMeta,
createDaemonReplayInfo,
DAEMON_COMMAND_COMPATIBILITY,
+ DAEMON_COMMAND_PLANE,
DAEMON_DEFAULT_SERVER_CAPABILITIES,
DAEMON_OUTBOUND_COMPATIBILITY,
DAEMON_PROTOCOL_INFO,
@@ -20,6 +21,7 @@ import {
getDaemonCommandCompatibilities,
isDaemonCommandEnvelope,
isDaemonMutatingCommand,
+ isSessionPlaneDaemonCommand,
salvageDaemonCommandId,
} from "../src/modes/daemon/daemon-protocol.js";
import {
@@ -39,6 +41,7 @@ describe("daemon protocol helpers", () => {
orphanProcessJournalPath: "/state/orphans.jsonl",
supervisorSocketPath: "/tmp/supervisor.sock",
authenticationToken: "local-worker-token",
+ workerInstanceId: "instance-1",
rootActiveSessionId: "active",
sessionFile: "/sessions/root.jsonl",
createdAt: "2026-01-01T00:00:00.000Z",
@@ -68,6 +71,7 @@ describe("daemon protocol helpers", () => {
expect(durable.createCommand).toEqual({ type: "create", sessionPath: "/sessions/root.jsonl" });
expect(durable).toMatchObject({
workerId: "worker",
+ workerInstanceId: "instance-1",
sessionFile: "/sessions/root.jsonl",
sessionDir: "/legacy/sessions",
telemetryDisabled: true,
@@ -380,6 +384,24 @@ describe("daemon protocol helpers", () => {
).toBe(true);
});
+ it("capability-gates direct worker transport discovery as a supervisor-only surface", () => {
+ expect(DAEMON_COMMAND_COMPATIBILITY.get_direct_worker_transport).toEqual({
+ minProtocol: 7,
+ minSchemaRevision: 25,
+ capability: "direct_peer_transport",
+ });
+ // Only the supervisor issues tickets; workers and standalone daemons must not advertise it.
+ expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).not.toContain("direct_peer_transport");
+ expect(isDaemonMutatingCommand({ type: "get_direct_worker_transport" })).toBe(false);
+ });
+
+ it("classifies every command plane and never defaults unknown commands to the session plane", () => {
+ // A worker "list" means only that worker's sessions; the supervisor list is authoritative.
+ expect(DAEMON_COMMAND_PLANE.list).toBe("control");
+ expect(DAEMON_COMMAND_PLANE.prompt).toBe("session");
+ expect(isSessionPlaneDaemonCommand("no_such_command")).toBe(false);
+ });
+
it("reports replay availability from resume cursors", () => {
expect(createDaemonReplayInfo(undefined, 5, "generation-1")).toEqual({
status: "complete",
diff --git a/packages/coding-agent/test/daemon-routed-client.test.ts b/packages/coding-agent/test/daemon-routed-client.test.ts
new file mode 100644
index 0000000000..592e5de659
--- /dev/null
+++ b/packages/coding-agent/test/daemon-routed-client.test.ts
@@ -0,0 +1,155 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { createServer, type Socket } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it, vi } from "vitest";
+import {
+ DAEMON_PROTOCOL_INFO,
+ DAEMON_SCHEMA_REVISION,
+ type DaemonOutbound,
+ type DaemonPeerTransportTicket,
+ type DaemonResponse,
+} from "../src/modes/daemon/daemon-protocol.js";
+import { createDaemonSessionTransport, DaemonRoutedClient } from "../src/modes/daemon/daemon-routed-client.js";
+import { getDaemonSocketIdentity } from "../src/modes/daemon/daemon-socket.js";
+import { DaemonWorkerClient } from "../src/modes/daemon/daemon-worker-client.js";
+
+const HELLO = {
+ type: "daemon_hello",
+ socketPath: "/tmp/fake.sock",
+ protocol: DAEMON_PROTOCOL_INFO,
+ schemaRevision: DAEMON_SCHEMA_REVISION,
+ clientId: "client-1",
+ serverCapabilities: ["session_input_admission", "direct_peer_transport"],
+} as const;
+
+function makeFakeEndpoint(hello: unknown = HELLO) {
+ const requests: { type: string }[] = [];
+ return {
+ requests,
+ client: {
+ hello,
+ isConnected: true,
+ supportsServerCapability: (capability: string) =>
+ Array.isArray((hello as { serverCapabilities?: string[] })?.serverCapabilities) &&
+ (hello as { serverCapabilities: string[] }).serverCapabilities.includes(capability),
+ onMessage: () => () => {},
+ onClose: () => () => {},
+ request: async (command: { type: string }): Promise<DaemonResponse> => {
+ requests.push(command);
+ return { type: "response", command: command.type, success: true };
+ },
+ close: () => {},
+ },
+ };
+}
+
+describe("DaemonRoutedClient routing", () => {
+ it("routes only session-plane commands the worker's own hello serves to the direct socket", async () => {
+ const supervisor = makeFakeEndpoint();
+ const direct = makeFakeEndpoint({ ...HELLO, serverCapabilities: [] });
+ const routed = new DaemonRoutedClient(supervisor.client as never, direct.client as unknown as DaemonWorkerClient);
+
+ await routed.request({ type: "abort", activeSessionId: "active-1" });
+ expect(direct.requests.map((request) => request.type)).toEqual(["abort"]);
+
+ // A worker "list" would mean something different; control-plane commands never go direct.
+ await routed.request({ type: "list" });
+ // The worker hello lacks session_input_admission, so prompt falls back to the supervisor.
+ await routed.request({ type: "prompt", activeSessionId: "active-1", message: "hi" });
+ expect(direct.requests.map((request) => request.type)).toEqual(["abort"]);
+ expect(supervisor.requests.map((request) => request.type)).toEqual(["list", "prompt"]);
+ routed.close();
+ });
+});
+
+describe("createDaemonSessionTransport", () => {
+ it("never asks an old supervisor for a ticket", async () => {
+ const supervisor = makeFakeEndpoint({ ...HELLO, serverCapabilities: [] });
+
+ const transport = await createDaemonSessionTransport(supervisor.client as never, "active-1", false);
+
+ expect(transport).toBe(supervisor.client);
+ expect(supervisor.requests).toEqual([]);
+ });
+
+ it("falls back to the supervisor when the worker socket identity does not match the ticket", async () => {
+ const directory = mkdtempSync(join(tmpdir(), "prime-agent-routed-ticket-"));
+ const socketPath = join(directory, "worker.sock");
+ const server = createServer();
+ await new Promise<void>((resolveListen) => server.listen(socketPath, resolveListen));
+ try {
+ const identity = getDaemonSocketIdentity(socketPath)!;
+ const ticket: DaemonPeerTransportTicket = {
+ purpose: "session_client",
+ socketPath,
+ socketIdentity: { dev: identity.dev, ino: identity.ino + 1 },
+ workerInstanceId: "instance-1",
+ activeSessionId: "active-1",
+ grantId: "grant-1",
+ token: "token-1",
+ expiresAt: new Date(Date.now() + 10_000).toISOString(),
+ };
+ const supervisor = makeFakeEndpoint();
+ supervisor.client.request = async (command: { type: string }): Promise<DaemonResponse> => ({
+ type: "response",
+ command: command.type,
+ success: true,
+ data: ticket,
+ });
+
+ const transport = await createDaemonSessionTransport(supervisor.client as never, "active-1", false);
+
+ expect(transport).toBe(supervisor.client);
+ } finally {
+ await new Promise<void>((resolveClose) => server.close(() => resolveClose()));
+ rmSync(directory, { recursive: true, force: true });
+ }
+ });
+});
+
+describe("DaemonWorkerClient direct decoding", () => {
+ function makeDirectClient() {
+ const destroyed = vi.fn();
+ const client = new DaemonWorkerClient("/tmp/prime-agent-direct.sock");
+ const internals = client as unknown as {
+ socket: Socket;
+ directPeer: boolean;
+ handleFrame(frame: { header: Record<string, unknown>; payload: Buffer }): void;
+ };
+ internals.socket = { destroyed: false, destroy: destroyed } as unknown as Socket;
+ internals.directPeer = true;
+ return { client, internals, destroyed };
+ }
+
+ it("emits decoded outbound frames to message listeners", () => {
+ const { client, internals } = makeDirectClient();
+ const messages: DaemonOutbound[] = [];
+ client.onMessage((message) => messages.push(message));
+
+ internals.handleFrame({
+ header: { kind: "outbound", outboundType: "session_detached", payloadEncoding: "jsonl" },
+ payload: Buffer.from(JSON.stringify({ type: "session_detached", activeSessionId: "active-1" })),
+ });
+
+ expect(messages).toEqual([{ type: "session_detached", activeSessionId: "active-1" }]);
+ });
+
+ it("closes the direct link on a malformed frame instead of throwing into consumers", () => {
+ const { client, internals, destroyed } = makeDirectClient();
+ const messages: DaemonOutbound[] = [];
+ const closes: Error[] = [];
+ client.onMessage((message) => messages.push(message));
+ client.onClose((error) => closes.push(error));
+
+ internals.handleFrame({
+ header: { kind: "outbound", outboundType: "session_event", payloadEncoding: "jsonl" },
+ payload: Buffer.from("{not json"),
+ });
+
+ expect(messages).toEqual([]);
+ expect(destroyed).toHaveBeenCalledOnce();
+ expect(closes).toHaveLength(1);
+ expect(closes[0]?.name).toBe("DaemonSocketClosedError");
+ });
+});
diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.ts
index 7b6f9cc46b..df7ab94ddd 100644
--- a/packages/coding-agent/test/daemon-session-list.test.ts
+++ b/packages/coding-agent/test/daemon-session-list.test.ts
@@ -5,6 +5,7 @@ import type { RlmChildAgentSnapshot } from "../src/core/agent-session.js";
import type { AgentCronJob } from "../src/core/cron-jobs.js";
import type { SessionInfo } from "../src/core/session-manager.js";
import type { ActiveSessionState, DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";
+import { passivatedWorkerRosterEntry, workerRosterEntryFromSummary } from "../src/modes/daemon/agent-roster.js";
import {
buildRlmChildSnapshots,
buildSessionList,
@@ -57,6 +58,20 @@ describe("buildSessionList", () => {
]);
});
+ it("counts direct peers separately so the supervisor can add them to its own attachment count", () => {
+ const state = makeState({ activeSessionId: "direct", sessionFile: "/tmp/direct.jsonl" });
+ state.clients.add({ id: "supervisor", authenticationRole: "supervisor" } as unknown as DaemonSocketClient);
+ state.clients.add({ id: "peer", authenticationRole: "session_client" } as unknown as DaemonSocketClient);
+
+ const [summary] = buildSessionList([state], []);
+
+ expect(summary).toMatchObject({ attachedClients: 2, directAttachedClients: 1 });
+ // Passivated roster rows describe a session without a runtime; the live-only count must not survive.
+ expect(
+ passivatedWorkerRosterEntry(workerRosterEntryFromSummary(summary!)).summary.directAttachedClients,
+ ).toBeUndefined();
+ });
+
it("uses the stable session header time for active rows without a saved catalog entry", () => {
const state = makeState({ activeSessionId: "active", sessionFile: "/tmp/active.jsonl" });
const first = summaryForActiveSession(state);
diff --git a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
index 17c21a96b9..ebc6e7f14a 100644
--- a/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-monitor.test.ts
@@ -355,6 +355,7 @@ describe("daemon worker supervisor monitoring", () => {
internals.handleConnection(socket);
const client = [...internals.clients][0]!;
client.authenticated = true;
+ client.authenticationRole = "supervisor";
internals.supervisorClaims.set(client, {
claim: {},
ownerFingerprint: "old",
@@ -442,6 +443,7 @@ describe("daemon worker supervisor monitoring", () => {
const daemon = Object.assign(Object.create(AgentDaemon.prototype), {
options: { worker: { authenticationToken: "token" } },
supervisorClaims: new Map([[client, oldClaim]]),
+ peerClaims: new Map(),
updateRestart: transaction,
handleWorkerCommand: vi.fn(async () => undefined),
assertSupervisorClaimCurrent: vi.fn(async () => {
@@ -483,6 +485,7 @@ describe("daemon worker supervisor monitoring", () => {
const daemon = Object.assign(Object.create(AgentDaemon.prototype), {
options: { worker: { authenticationToken: "token" } },
supervisorClaims: new Map(),
+ peerClaims: new Map(),
clients: new Set(),
sessions: new Map(),
cronStore: { list: () => [] },
diff --git a/packages/coding-agent/test/daemon-supervisor-process.test.ts b/packages/coding-agent/test/daemon-supervisor-process.test.ts
index a425b18fd6..765a9edc26 100644
--- a/packages/coding-agent/test/daemon-supervisor-process.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-process.test.ts
@@ -1546,7 +1546,8 @@ describe("daemon supervisor resident workers", () => {
await new Promise((resolveDelay) => setTimeout(resolveDelay, 25));
}
expect(connectionEvents).toContain("connection_status:reconnecting");
- expect(connectionEvents).toContain("session_resynced");
+ // The direct worker link held through the supervisor swap, so no resync is warranted.
+ expect(connectionEvents).not.toContain("session_resynced");
expect(connectionEvents).toContain("connection_status:connected");
expect(connectionEvents).not.toContain("closed");
await expect(connection.getState()).resolves.toMatchObject({
diff --git a/packages/coding-agent/test/suite/regressions/4656-resume-active-session.test.ts b/packages/coding-agent/test/suite/regressions/4656-resume-active-session.test.ts
index 0903122698..7508b2014d 100644
--- a/packages/coding-agent/test/suite/regressions/4656-resume-active-session.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4656-resume-active-session.test.ts
@@ -102,6 +102,10 @@ class ResumeDaemonClient {
throw new Error(`Unexpected command: ${command.type}`);
}
+ supportsServerCapability(): boolean {
+ return false;
+ }
+
onMessage(listener: DaemonClientMessageListener): () => void {
this.messageListeners.add(listener);
return () => this.messageListeners.delete(listener);