mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-21 07:45:38 +00:00
fix(acp): keep Antigravity turn open while non-daemon background tools run (#10310)
* fix(acp): keep Antigravity turn open while non-daemon background tools run * fix(acp): address deferred turn steer, drain race, and echo scoping * fix(acp): serialize deferred steers, gate on end_turn, and lock canceled tool updates * fix(acp): unify deferred reply settlement and accept queued steers on send * fix(acp): keep Stop unblocked during queued steers and gate reply settlement on post-tool updates * fix(acp): ignore in-flight steer usage for settlement and deliver queued steers after RPC errors * fix(acp): keep deferred background job running when a steer rejects and honor Stop cancellation * fix(acp): settle deferred turn immediately on Stop even if a steer RPC is unanswered * fix(acp): bound Stop drain for in-flight steers and tear down wedged runtimes * fix(acp): terminate wedged child process on Stop timeout and reject prompts on closed sessions * fix(acp): reject replacement prompt if session retires during interrupt and preserve streaming reply id * fix(acp): always retire deferred ACP session cleanly on Stop and clear fallback id on steer start * fix(server): reopen retired plugin sessions before applying configuration changes * fix(acp): close deferred process before emitting cancel and synchronize mid-shutdown config changes * fix(acp): do not reset deferred settle timer on excluded daemon tool updates * fix(acp): release deferred turn when tool is reclassified as excluded * fix(acp): gate deferred settlement reset on open qualifying tool membership * fix(acp): decouple deferred reply tracking from open tool blockers * fix(acp): track post-end_turn wire order and preserve settled reply across tool completion * fix(acp): unify wire-order prompt response tracking and exclude daemon reclassification from crossedEndTurn * fix(acp): preserve settled background reply across steers that start no new tools * fix(acp): distinguish settled-with-open-tools reply state across steers * fix(acp): share close and deferred interrupt retirement across overlapping calls * fix(acp): make deferred retirement sole owner of prompt rejection and cancellation * fix(acp): centralize session retirement in retireSession so rejected prompts never suppress session.closed * fix(acp): bound session/cancel write in deferred retirement before teardown * fix(acp,server): force-abort stalled connectors on Stop timeout and bound cancel wait in AgentManager * fix(acp,server): enforce shutdown deadline on connector close and bound settings wait on queued Stop * fix(acp): scope connector shutdown deadline to deferred retirement and finalize on late close
This commit is contained in:
@@ -89,6 +89,9 @@ export async function createAcpProviderConnection(
|
||||
if (probe.agentCapabilities.loadSession) {
|
||||
supportedCapabilities.push("session.persistence");
|
||||
}
|
||||
if (options.acpOptions?.deferTurnOnRunningTools) {
|
||||
supportedCapabilities.push("prompt.steer");
|
||||
}
|
||||
await probe.close();
|
||||
const capabilities = negotiateProviderCapabilities(request.capabilities, supportedCapabilities);
|
||||
const listeners = new Set<(event: ProviderEvent) => void>();
|
||||
@@ -214,10 +217,13 @@ async function dispatch(input: ProviderInput, state: AcpConnectionState): Promis
|
||||
await mutateSession(session, () => session.runtime.prompt(input));
|
||||
return;
|
||||
}
|
||||
case "session.interrupt":
|
||||
await requireSession(state, input.sessionId).runtime.interrupt();
|
||||
case "session.interrupt": {
|
||||
const session = requireSession(state, input.sessionId);
|
||||
const retired = await session.runtime.interrupt();
|
||||
state.emit({ type: "request.completed", requestId: input.requestId });
|
||||
if (retired) retireSession(state, input.sessionId);
|
||||
return;
|
||||
}
|
||||
case "session.permission":
|
||||
requireSession(state, input.sessionId).runtime.respondToPermission(
|
||||
input.permissionId,
|
||||
@@ -304,6 +310,12 @@ async function listSessions(
|
||||
}
|
||||
}
|
||||
|
||||
function retireSession(state: AcpConnectionState, sessionId: string): void {
|
||||
if (state.sessions.delete(sessionId)) {
|
||||
state.emit({ type: "session.closed", sessionId });
|
||||
}
|
||||
}
|
||||
|
||||
async function openSession(
|
||||
input: Extract<ProviderInput, { type: "session.open" }>,
|
||||
state: AcpConnectionState,
|
||||
@@ -317,6 +329,7 @@ async function openSession(
|
||||
cwd: input.config.cwd,
|
||||
env: input.config.env,
|
||||
emit: state.emit,
|
||||
onRetired: () => retireSession(state, input.sessionId),
|
||||
});
|
||||
try {
|
||||
const capabilities = await runtime.open(input, state.capabilities);
|
||||
@@ -358,6 +371,7 @@ interface StartRuntimeOptions {
|
||||
cwd?: string;
|
||||
env: Readonly<Record<string, string>>;
|
||||
emit(event: ProviderEvent): void;
|
||||
onRetired?: () => void;
|
||||
}
|
||||
|
||||
interface PendingPermission {
|
||||
@@ -366,6 +380,33 @@ interface PendingPermission {
|
||||
resolve(response: RequestPermissionResponse): void;
|
||||
}
|
||||
|
||||
type DeferredTurnOutcome =
|
||||
| { type: "complete"; terminalizeTools: boolean }
|
||||
| { type: "cancel" }
|
||||
| { type: "fail"; error: { message: string } };
|
||||
|
||||
interface DeferredTurnState {
|
||||
timer: ReturnType<typeof setTimeout> | null;
|
||||
resolve(outcome: DeferredTurnOutcome): void;
|
||||
}
|
||||
|
||||
type DeferredReplyState = "idle" | "open" | "settled_with_open_tools" | "settled";
|
||||
|
||||
interface ActivePrompt {
|
||||
turnId: string;
|
||||
settled: Promise<void>;
|
||||
cancelling: boolean;
|
||||
wirePromptsInFlight: number;
|
||||
wirePromptLane: Promise<void>;
|
||||
lastPromptResponseWireSeq: number | null;
|
||||
crossedEndTurn: boolean;
|
||||
replyState: DeferredReplyState;
|
||||
deferred: DeferredTurnState | null;
|
||||
}
|
||||
|
||||
const DEFAULT_DEFERRED_SETTLE_DELAY_MS = 500;
|
||||
const DEFAULT_DEFERRED_QUIET_LIMIT_MS = 120_000;
|
||||
|
||||
class AcpRuntime {
|
||||
readonly connection: ClientSideConnection;
|
||||
agentCapabilities: AgentCapabilities = {};
|
||||
@@ -374,6 +415,8 @@ class AcpRuntime {
|
||||
private emit: (event: ProviderEvent) => void;
|
||||
private readonly messages = new Map<string, string>();
|
||||
private readonly toolCalls = new Map<string, AcpToolCallSnapshot>();
|
||||
private readonly liveOpenToolIds = new Set<string>();
|
||||
private readonly canceledToolCallIds = new Set<string>();
|
||||
// Running tool rows published by transformers; the turn's terminal closes any left open.
|
||||
private readonly vendorToolCalls = new Map<string, ToolCallTimelineItem>();
|
||||
private readonly pendingCompactions = new Set<string>();
|
||||
@@ -401,21 +444,33 @@ class AcpRuntime {
|
||||
private replayWindow: "replay" | "skip" | null = null;
|
||||
private lastLoadUpdateAt = 0;
|
||||
private closing = false;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
private deferredRetirement: Promise<boolean> | null = null;
|
||||
private deferredFinalized = false;
|
||||
private processFailed = false;
|
||||
private configTransaction = false;
|
||||
private stagedTransformerConfig: ProviderConfigState | null = null;
|
||||
private readonly closeConnector: () => Promise<void>;
|
||||
private readonly closeConnector: (options?: {
|
||||
force?: boolean;
|
||||
timeoutMs?: number;
|
||||
}) => Promise<void>;
|
||||
private readonly whenConnectorClosed: () => Promise<void> | null;
|
||||
private notificationLane: Promise<void> = Promise.resolve();
|
||||
private incomingWireSeq = 0;
|
||||
private readonly sessionUpdateWireSeqs: number[] = [];
|
||||
private autoAccept = false;
|
||||
private activePrompt: { turnId: string; settled: Promise<void>; cancelling: boolean } | null =
|
||||
null;
|
||||
private activePrompt: ActivePrompt | null = null;
|
||||
private lastUsage: ProviderUsage = {};
|
||||
|
||||
static async start(options: StartRuntimeOptions): Promise<AcpRuntime> {
|
||||
let child: ChildProcessWithoutNullStreams | null = null;
|
||||
let spawnFailure: Promise<never> | null = null;
|
||||
let stream: Stream;
|
||||
let closeConnector = async () => {};
|
||||
let closeConnector: (options?: {
|
||||
force?: boolean;
|
||||
timeoutMs?: number;
|
||||
}) => Promise<void> = async () => {};
|
||||
let whenConnectorClosed: () => Promise<void> | null = () => null;
|
||||
if (options.options.command) {
|
||||
// COMPAT(pluginProviderLaunch): added in v0.10.0, remove after 2027-03-29 once plugin host floor >= v0.10.0.
|
||||
// Standalone callers and older hosts do not send a daemon-resolved launch.
|
||||
@@ -438,8 +493,9 @@ class AcpRuntime {
|
||||
const owned = ownConnectorStream(await options.options.connector());
|
||||
stream = owned.stream;
|
||||
closeConnector = owned.close;
|
||||
whenConnectorClosed = owned.whenClosed;
|
||||
}
|
||||
const runtime = new AcpRuntime(stream, child, closeConnector, options);
|
||||
const runtime = new AcpRuntime(stream, child, closeConnector, whenConnectorClosed, options);
|
||||
try {
|
||||
const initialize = withTimeout(
|
||||
runtime.call(
|
||||
@@ -466,41 +522,51 @@ class AcpRuntime {
|
||||
private constructor(
|
||||
stream: Stream,
|
||||
child: ChildProcessWithoutNullStreams | null,
|
||||
closeConnector: () => Promise<void>,
|
||||
closeConnector: (options?: { force?: boolean; timeoutMs?: number }) => Promise<void>,
|
||||
whenConnectorClosed: () => Promise<void> | null,
|
||||
private readonly options: StartRuntimeOptions,
|
||||
) {
|
||||
this.child = child;
|
||||
this.closeConnector = closeConnector;
|
||||
this.whenConnectorClosed = whenConnectorClosed;
|
||||
this.emit = options.emit;
|
||||
this.transformers = options.options.transformers ?? [];
|
||||
const client: Client = {
|
||||
requestPermission: (request) => this.requestPermission(request),
|
||||
sessionUpdate: (notification) =>
|
||||
this.enqueueNotification(() => this.sessionUpdate(notification)),
|
||||
sessionUpdate: (notification) => {
|
||||
const wireSeq = this.sessionUpdateWireSeqs.shift() ?? ++this.incomingWireSeq;
|
||||
return this.enqueueNotification(() => this.sessionUpdate(notification, wireSeq));
|
||||
},
|
||||
};
|
||||
this.connection = new ClientSideConnection(
|
||||
() => client,
|
||||
routeVendorNotifications(stream, (method, params) => this.vendorNotification(method, params)),
|
||||
routeIncomingMessages(
|
||||
stream,
|
||||
(method, params) => this.vendorNotification(method, params),
|
||||
(message) => this.observeWireMessage(message),
|
||||
),
|
||||
);
|
||||
if (!child) void this.connection.closed.then(() => this.handleUnexpectedTransportClose());
|
||||
child?.on("error", (error) => {
|
||||
const message = describeError(error);
|
||||
this.processFailed = true;
|
||||
this.settlePendingWork();
|
||||
this.settlePendingWork(message);
|
||||
if (this.closing || !this.nativeSessionId) return;
|
||||
this.emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
error: { message: describeError(error) },
|
||||
error: { message },
|
||||
});
|
||||
});
|
||||
child?.once("close", (code, signal) => {
|
||||
if (this.closing || this.processFailed || !this.nativeSessionId) return;
|
||||
const message = `ACP process exited (${signal ?? code ?? "unknown"})`;
|
||||
this.processFailed = true;
|
||||
this.settlePendingWork();
|
||||
this.settlePendingWork(message);
|
||||
this.emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
error: { message: `ACP process exited (${signal ?? code ?? "unknown"})` },
|
||||
error: { message },
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -609,10 +675,31 @@ class AcpRuntime {
|
||||
}
|
||||
|
||||
async prompt(input: Extract<ProviderInput, { type: "session.prompt" }>): Promise<void> {
|
||||
if (this.closing || this.processFailed || this.deferredRetirement) {
|
||||
throw new Error("ACP session is closed");
|
||||
}
|
||||
if (input.prompt.delivery === "steer") {
|
||||
this.steerDeferredPrompt(input);
|
||||
return;
|
||||
}
|
||||
const active = this.activePrompt;
|
||||
if (active) {
|
||||
await this.interrupt();
|
||||
if (active.deferred && active.wirePromptsInFlight === 0) {
|
||||
// Wire session/prompt already resolved; finish the deferred turn without sending
|
||||
// session/cancel so running background tools stay alive into the follow-up turn.
|
||||
this.finishDeferredTurn(active, { type: "complete", terminalizeTools: false });
|
||||
} else {
|
||||
const retired = await this.interrupt();
|
||||
if (retired) {
|
||||
// Notify caller that the session closed before failing the replacement prompt.
|
||||
this.options.onRetired?.();
|
||||
throw new Error("ACP session retired after stopping deferred background work");
|
||||
}
|
||||
}
|
||||
await active.settled;
|
||||
if (this.closing || this.processFailed || this.deferredRetirement) {
|
||||
throw new Error("ACP session is closed");
|
||||
}
|
||||
}
|
||||
const prompt = toAcpPrompt(input.prompt);
|
||||
this.replayWindow = null;
|
||||
@@ -643,6 +730,17 @@ class AcpRuntime {
|
||||
turnId,
|
||||
state: "started",
|
||||
});
|
||||
const activePrompt: ActivePrompt = {
|
||||
turnId,
|
||||
settled: Promise.resolve(),
|
||||
cancelling: false,
|
||||
wirePromptsInFlight: 1,
|
||||
wirePromptLane: Promise.resolve(),
|
||||
lastPromptResponseWireSeq: null,
|
||||
crossedEndTurn: false,
|
||||
replyState: "idle",
|
||||
deferred: null,
|
||||
};
|
||||
// The SDK dispatches notifications without awaiting them, so the prompt response can resolve
|
||||
// while earlier session updates are still queued. Apply them before the turn ends.
|
||||
const settled = this.call(
|
||||
@@ -650,6 +748,7 @@ class AcpRuntime {
|
||||
).then(
|
||||
async (response): Promise<void> => {
|
||||
await this.drainNotifications();
|
||||
activePrompt.wirePromptsInFlight -= 1;
|
||||
if (response.usage) {
|
||||
this.lastUsage = {
|
||||
...this.lastUsage,
|
||||
@@ -665,47 +764,95 @@ class AcpRuntime {
|
||||
});
|
||||
}
|
||||
const state = response.stopReason === "cancelled" ? "canceled" : "completed";
|
||||
this.fallbackChunkIds.clear();
|
||||
this.terminalizeTransientItems(state);
|
||||
this.finishTurnPermissions(turnId);
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId,
|
||||
state,
|
||||
});
|
||||
if (response.stopReason === "end_turn" && this.shouldDeferTurn(activePrompt)) {
|
||||
await this.settleDeferredPrompt(activePrompt);
|
||||
return undefined;
|
||||
}
|
||||
this.finishPromptTurn(turnId, state);
|
||||
return undefined;
|
||||
},
|
||||
async (error): Promise<void> => {
|
||||
await this.drainNotifications();
|
||||
this.fallbackChunkIds.clear();
|
||||
this.terminalizeTransientItems("failed");
|
||||
this.finishTurnPermissions(turnId);
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId,
|
||||
state: "failed",
|
||||
error: { message: describeError(error) },
|
||||
});
|
||||
activePrompt.wirePromptsInFlight -= 1;
|
||||
this.finishPromptTurn(turnId, "failed", { message: describeError(error) });
|
||||
return undefined;
|
||||
},
|
||||
);
|
||||
this.activePrompt = { turnId, settled, cancelling: false };
|
||||
activePrompt.settled = settled;
|
||||
this.activePrompt = activePrompt;
|
||||
void settled.finally(() => {
|
||||
if (this.activePrompt?.turnId === turnId) this.activePrompt = null;
|
||||
});
|
||||
}
|
||||
|
||||
async interrupt(): Promise<void> {
|
||||
async interrupt(): Promise<boolean> {
|
||||
if (this.deferredRetirement) return this.deferredRetirement;
|
||||
const active = this.activePrompt;
|
||||
const deferredTurnId = active?.deferred ? active.turnId : null;
|
||||
if (active && deferredTurnId) {
|
||||
const retirement = this.retireDeferredTurn(active, deferredTurnId).catch((error) => {
|
||||
if (this.deferredRetirement === retirement) this.deferredRetirement = null;
|
||||
throw error;
|
||||
});
|
||||
this.deferredRetirement = retirement;
|
||||
return retirement;
|
||||
}
|
||||
if (active) active.cancelling = true;
|
||||
try {
|
||||
await this.call(this.connection.cancel({ sessionId: this.nativeSessionId }));
|
||||
} finally {
|
||||
// An agent may wait for its outstanding permission replies before ending the prompt.
|
||||
if (active) this.finishTurnPermissions(active.turnId);
|
||||
if (active) {
|
||||
this.finishTurnPermissions(active.turnId);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private finalizeDeferredTurn(deferredTurnId: string, emitRetired: boolean): void {
|
||||
if (this.deferredFinalized) return;
|
||||
this.deferredFinalized = true;
|
||||
this.finishPromptTurn(deferredTurnId, "canceled", undefined, {
|
||||
suppressTrailingToolEcho: true,
|
||||
});
|
||||
if (emitRetired) this.options.onRetired?.();
|
||||
}
|
||||
|
||||
private async retireDeferredTurn(active: ActivePrompt, deferredTurnId: string): Promise<boolean> {
|
||||
active.cancelling = true;
|
||||
// Record open tools owned by Stop before writing session/cancel so any failure
|
||||
// update arriving during cancel preserves their canceled state.
|
||||
for (const id of this.liveOpenToolIds) this.canceledToolCallIds.add(id);
|
||||
let cancelTimedOut = false;
|
||||
if (!this.closing) {
|
||||
try {
|
||||
await withTimeout(
|
||||
this.call(this.connection.cancel({ sessionId: this.nativeSessionId })),
|
||||
1_000,
|
||||
`ACP session ${this.nativeSessionId} did not accept cancel`,
|
||||
);
|
||||
} catch {
|
||||
cancelTimedOut = true;
|
||||
} finally {
|
||||
// An agent may wait for its outstanding permission replies before ending the prompt.
|
||||
this.finishTurnPermissions(active.turnId);
|
||||
}
|
||||
}
|
||||
// ACP v1 has no response or end boundary for session/cancel once session/prompt
|
||||
// already returned. Close the process first while the turn still appears running,
|
||||
// then emit the canceled turn synchronously before request.completed and session.closed
|
||||
// so queued work and config changes immediately observe the retired session.
|
||||
try {
|
||||
await this.close({ force: cancelTimedOut, timeoutMs: 1_000 });
|
||||
} catch (error) {
|
||||
void this.whenConnectorClosed()?.then(
|
||||
() => this.finalizeDeferredTurn(deferredTurnId, true),
|
||||
() => undefined,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
this.finalizeDeferredTurn(deferredTurnId, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
listSessions(cwd?: string) {
|
||||
@@ -758,6 +905,7 @@ class AcpRuntime {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
permissionId,
|
||||
});
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
async configure(
|
||||
@@ -833,11 +981,20 @@ class AcpRuntime {
|
||||
await this.close();
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.closing) return;
|
||||
close(options?: { force?: boolean; timeoutMs?: number }): Promise<void> {
|
||||
if (this.closePromise) return this.closePromise;
|
||||
this.closing = true;
|
||||
const promise = this.closeInternal(options).catch((error) => {
|
||||
if (this.closePromise === promise) this.closePromise = null;
|
||||
throw error;
|
||||
});
|
||||
this.closePromise = promise;
|
||||
return promise;
|
||||
}
|
||||
|
||||
private async closeInternal(options?: { force?: boolean; timeoutMs?: number }): Promise<void> {
|
||||
this.settlePendingWork();
|
||||
await this.closeConnector();
|
||||
await this.closeConnector(options);
|
||||
const child = this.child;
|
||||
if (!child || this.processFailed) return;
|
||||
if (child.exitCode !== null || child.signalCode !== null) return;
|
||||
@@ -1066,6 +1223,7 @@ class AcpRuntime {
|
||||
const permissionId = `permission:${request.toolCall.toolCallId}`;
|
||||
return new Promise((resolve) => {
|
||||
this.permissions.set(permissionId, { request, resolve, turnId: this.activePrompt?.turnId });
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
this.emit({
|
||||
type: "session.permission",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
@@ -1085,7 +1243,31 @@ class AcpRuntime {
|
||||
});
|
||||
}
|
||||
|
||||
private sessionUpdate(notification: SessionNotification): void {
|
||||
private observeWireMessage(message: unknown): void {
|
||||
if (typeof message !== "object" || message === null) return;
|
||||
const record = message as Record<string, unknown>;
|
||||
if (record.method === "session/update") {
|
||||
this.sessionUpdateWireSeqs.push(++this.incomingWireSeq);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!("method" in record) &&
|
||||
"id" in record &&
|
||||
typeof record.result === "object" &&
|
||||
record.result !== null &&
|
||||
typeof (record.result as Record<string, unknown>).stopReason === "string" &&
|
||||
this.activePrompt &&
|
||||
this.activePrompt.lastPromptResponseWireSeq === null
|
||||
) {
|
||||
this.activePrompt.lastPromptResponseWireSeq = ++this.incomingWireSeq;
|
||||
}
|
||||
}
|
||||
|
||||
private isPostWirePrompt(active: ActivePrompt, wireSeq: number): boolean {
|
||||
return active.lastPromptResponseWireSeq !== null && wireSeq > active.lastPromptResponseWireSeq;
|
||||
}
|
||||
|
||||
private sessionUpdate(notification: SessionNotification, wireSeq: number): void {
|
||||
if (notification.sessionId !== this.nativeSessionId) return;
|
||||
if (this.replayWindow) this.lastLoadUpdateAt = performance.now();
|
||||
if (this.replayWindow === "skip") {
|
||||
@@ -1096,7 +1278,7 @@ class AcpRuntime {
|
||||
update.sessionUpdate === "current_mode_update" ||
|
||||
update.sessionUpdate === "usage_update"
|
||||
) {
|
||||
this.reduceStateUpdate(update);
|
||||
this.reduceStateUpdate(update, wireSeq);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1107,10 +1289,10 @@ class AcpRuntime {
|
||||
this.reduceUserMessageChunk(notification.update);
|
||||
return;
|
||||
}
|
||||
this.reduceUpdate(notification.update);
|
||||
this.reduceUpdate(notification.update, wireSeq);
|
||||
}
|
||||
|
||||
private reduceUpdate(update: SessionUpdate): void {
|
||||
private reduceUpdate(update: SessionUpdate, wireSeq: number): void {
|
||||
if (
|
||||
update.sessionUpdate === "agent_message_chunk" ||
|
||||
update.sessionUpdate === "agent_thought_chunk" ||
|
||||
@@ -1144,15 +1326,16 @@ class AcpRuntime {
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
this.noteDeferredChunk(update.sessionUpdate, wireSeq);
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
|
||||
if (update.sessionUpdate === "tool_call") this.fallbackChunkIds.clear();
|
||||
this.reduceToolCall(update);
|
||||
this.reduceToolCall(update, wireSeq);
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "plan") this.fallbackChunkIds.clear();
|
||||
this.reduceStateUpdate(update);
|
||||
this.reduceStateUpdate(update, wireSeq);
|
||||
}
|
||||
|
||||
// Historical user messages arrive only as replayed chunks; a live prompt
|
||||
@@ -1196,7 +1379,7 @@ class AcpRuntime {
|
||||
return id;
|
||||
}
|
||||
|
||||
private reduceStateUpdate(update: SessionUpdate): void {
|
||||
private reduceStateUpdate(update: SessionUpdate, wireSeq: number): void {
|
||||
if (update.sessionUpdate === "plan") {
|
||||
this.emit({
|
||||
type: "timeline.item",
|
||||
@@ -1253,6 +1436,7 @@ class AcpRuntime {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
usage: this.lastUsage,
|
||||
});
|
||||
this.noteDeferredUsageUpdate(wireSeq);
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "compaction_update") {
|
||||
@@ -1267,12 +1451,20 @@ class AcpRuntime {
|
||||
status: update.status === "completed" ? "completed" : "loading",
|
||||
},
|
||||
});
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
}
|
||||
|
||||
private terminalizeTransientItems(state: "completed" | "failed" | "canceled"): void {
|
||||
private terminalizeTransientItems(
|
||||
state: "completed" | "failed" | "canceled",
|
||||
options?: { preserveQualifyingOpenTools?: boolean; suppressTrailingToolEcho?: boolean },
|
||||
): void {
|
||||
const preserve = options?.preserveQualifyingOpenTools === true;
|
||||
for (const [id, snapshot] of this.toolCalls) {
|
||||
if (snapshot.status !== "pending" && snapshot.status !== "in_progress") continue;
|
||||
if (preserve && this.liveOpenToolIds.has(id) && this.toolKeepsTurnOpen(snapshot)) continue;
|
||||
this.liveOpenToolIds.delete(id);
|
||||
if (options?.suppressTrailingToolEcho) this.canceledToolCallIds.add(id);
|
||||
const completed: AcpToolCallSnapshot = {
|
||||
...snapshot,
|
||||
status: state === "completed" ? "completed" : "failed",
|
||||
@@ -1302,18 +1494,42 @@ class AcpRuntime {
|
||||
this.pendingCompactions.clear();
|
||||
}
|
||||
|
||||
private reduceToolCall(update: ToolCall | ToolCallUpdate): void {
|
||||
private reduceToolCall(
|
||||
update: Extract<SessionUpdate, { sessionUpdate: "tool_call" | "tool_call_update" }>,
|
||||
wireSeq: number,
|
||||
): void {
|
||||
if (
|
||||
update.sessionUpdate === "tool_call_update" &&
|
||||
this.canceledToolCallIds.has(update.toolCallId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "tool_call") {
|
||||
this.canceledToolCallIds.delete(update.toolCallId);
|
||||
}
|
||||
const current = this.toolCalls.get(update.toolCallId);
|
||||
const wasOpenQualifying =
|
||||
current !== undefined &&
|
||||
this.liveOpenToolIds.has(current.id) &&
|
||||
this.toolKeepsTurnOpen(current);
|
||||
let snapshot = mergeToolCallSnapshot(update, current);
|
||||
const context = { sessionId: this.options.boundarySessionId };
|
||||
for (const transformer of this.transformers)
|
||||
snapshot = transformer.toolCall?.(snapshot, context) ?? snapshot;
|
||||
this.toolCalls.set(snapshot.id, snapshot);
|
||||
const isOpen = snapshot.status === "pending" || snapshot.status === "in_progress";
|
||||
if (this.replayWindow === null) {
|
||||
if (isOpen) this.liveOpenToolIds.add(snapshot.id);
|
||||
else this.liveOpenToolIds.delete(snapshot.id);
|
||||
}
|
||||
this.emit({
|
||||
type: "timeline.item",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
item: toolTimelineItem(snapshot),
|
||||
});
|
||||
const isOpenQualifying =
|
||||
this.liveOpenToolIds.has(snapshot.id) && this.toolKeepsTurnOpen(snapshot);
|
||||
this.noteDeferredToolTransition(wasOpenQualifying, isOpenQualifying, isOpen, snapshot, wireSeq);
|
||||
}
|
||||
|
||||
private vendorNotification(method: string, params: unknown): void {
|
||||
@@ -1376,25 +1592,306 @@ class AcpRuntime {
|
||||
|
||||
private handleUnexpectedTransportClose(): void {
|
||||
if (this.closing || this.processFailed) return;
|
||||
const message = "ACP transport closed unexpectedly";
|
||||
this.processFailed = true;
|
||||
this.settlePendingWork();
|
||||
this.settlePendingWork(message);
|
||||
if (!this.nativeSessionId) return;
|
||||
this.emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
error: { message: "ACP transport closed unexpectedly" },
|
||||
error: { message },
|
||||
});
|
||||
}
|
||||
|
||||
private settlePendingWork(): void {
|
||||
private settlePendingWork(failureMessage?: string): void {
|
||||
for (const permission of this.permissions.values()) {
|
||||
permission.resolve({ outcome: { outcome: "cancelled" } });
|
||||
}
|
||||
this.permissions.clear();
|
||||
if (this.activePrompt?.deferred) {
|
||||
this.finishDeferredTurn(
|
||||
this.activePrompt,
|
||||
failureMessage ? { type: "fail", error: { message: failureMessage } } : { type: "cancel" },
|
||||
);
|
||||
}
|
||||
this.commandWaiter?.();
|
||||
this.commandWaiter = null;
|
||||
}
|
||||
|
||||
private finishPromptTurn(
|
||||
turnId: string,
|
||||
state: "completed" | "failed" | "canceled",
|
||||
error?: { message: string },
|
||||
options?: { preserveQualifyingOpenTools?: boolean; suppressTrailingToolEcho?: boolean },
|
||||
): void {
|
||||
this.fallbackChunkIds.clear();
|
||||
this.terminalizeTransientItems(state, options);
|
||||
this.finishTurnPermissions(turnId);
|
||||
if (state === "failed") {
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId,
|
||||
state,
|
||||
error: error ?? { message: "ACP turn failed" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId,
|
||||
state,
|
||||
});
|
||||
}
|
||||
|
||||
private steerDeferredPrompt(input: Extract<ProviderInput, { type: "session.prompt" }>): void {
|
||||
const active = this.activePrompt;
|
||||
const deferred = active?.deferred;
|
||||
if (!active || !deferred || active.cancelling || this.closing || this.processFailed) {
|
||||
this.emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: {
|
||||
type: "failed",
|
||||
error: {
|
||||
message: "ACP session can only steer while waiting on deferred background tools",
|
||||
},
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (input.prompt.clearPendingPermissions) {
|
||||
this.finishTurnPermissions(active.turnId);
|
||||
}
|
||||
const prompt = toAcpPrompt(input.prompt);
|
||||
active.wirePromptsInFlight += 1;
|
||||
this.scheduleDeferredSettle();
|
||||
this.replayWindow = null;
|
||||
this.fallbackChunkIds.clear();
|
||||
this.emit({
|
||||
type: "timeline.item",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
item: {
|
||||
type: "user_message",
|
||||
id: input.prompt.clientMessageId,
|
||||
text: prompt
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => part.text)
|
||||
.join("\n"),
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
},
|
||||
});
|
||||
this.emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "steer", turnId: active.turnId },
|
||||
});
|
||||
const runSteer = async (): Promise<void> => {
|
||||
try {
|
||||
if (
|
||||
this.closing ||
|
||||
this.processFailed ||
|
||||
active.cancelling ||
|
||||
active.deferred !== deferred
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.fallbackChunkIds.clear();
|
||||
active.lastPromptResponseWireSeq = null;
|
||||
if (active.replyState === "settled_with_open_tools") active.replyState = "idle";
|
||||
const response = await this.call(
|
||||
this.connection.prompt({ sessionId: this.nativeSessionId, prompt }),
|
||||
);
|
||||
await this.drainNotifications();
|
||||
if (this.closing || this.deferredRetirement || active.deferred !== deferred) return;
|
||||
if (response.usage) {
|
||||
this.lastUsage = {
|
||||
...this.lastUsage,
|
||||
inputTokens: response.usage.inputTokens,
|
||||
outputTokens: response.usage.outputTokens,
|
||||
cachedInputTokens: response.usage.cachedReadTokens ?? undefined,
|
||||
};
|
||||
this.emit({
|
||||
type: "session.usage",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId: active.turnId,
|
||||
usage: this.lastUsage,
|
||||
});
|
||||
}
|
||||
if (response.stopReason === "cancelled") {
|
||||
this.finishDeferredTurn(active, { type: "cancel" });
|
||||
return;
|
||||
}
|
||||
if (response.stopReason !== "end_turn" && active.wirePromptsInFlight === 1) {
|
||||
this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true });
|
||||
}
|
||||
} catch (error) {
|
||||
await this.drainNotifications();
|
||||
if (this.closing || this.deferredRetirement || active.deferred !== deferred) return;
|
||||
if (this.processFailed) {
|
||||
this.finishDeferredTurn(active, {
|
||||
type: "fail",
|
||||
error: { message: describeError(error) },
|
||||
});
|
||||
} else {
|
||||
this.emit({
|
||||
type: "session.notice",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
notice: {
|
||||
id: `acp:steer-error:${input.prompt.clientMessageId}`,
|
||||
severity: "error",
|
||||
title: "Follow-up prompt failed",
|
||||
description: describeError(error),
|
||||
},
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
if (active.lastPromptResponseWireSeq === null) {
|
||||
active.lastPromptResponseWireSeq = this.incomingWireSeq;
|
||||
}
|
||||
active.wirePromptsInFlight -= 1;
|
||||
this.scheduleDeferredSettle();
|
||||
}
|
||||
};
|
||||
active.wirePromptLane = active.wirePromptLane.then(runSteer);
|
||||
}
|
||||
|
||||
private async settleDeferredPrompt(active: ActivePrompt): Promise<void> {
|
||||
this.fallbackChunkIds.clear();
|
||||
const outcome = await new Promise<DeferredTurnOutcome>((resolve) => {
|
||||
active.deferred = { timer: null, resolve };
|
||||
this.scheduleDeferredSettle();
|
||||
});
|
||||
if (this.closing || this.deferredRetirement) return;
|
||||
if (outcome.type === "fail") {
|
||||
this.finishPromptTurn(active.turnId, "failed", outcome.error);
|
||||
return;
|
||||
}
|
||||
this.finishPromptTurn(
|
||||
active.turnId,
|
||||
outcome.type === "cancel" ? "canceled" : "completed",
|
||||
undefined,
|
||||
{
|
||||
preserveQualifyingOpenTools: outcome.type === "complete" && !outcome.terminalizeTools,
|
||||
suppressTrailingToolEcho: outcome.type === "cancel",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private toolKeepsTurnOpen(snapshot: AcpToolCallSnapshot): boolean {
|
||||
const defer = this.options.options.acpOptions?.deferTurnOnRunningTools;
|
||||
if (!defer) return false;
|
||||
return defer.keepsTurnOpen ? defer.keepsTurnOpen(snapshot) : true;
|
||||
}
|
||||
|
||||
private hasQualifyingOpenTools(): boolean {
|
||||
for (const id of this.liveOpenToolIds) {
|
||||
const snapshot = this.toolCalls.get(id);
|
||||
if (snapshot && this.toolKeepsTurnOpen(snapshot)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private hasDeferredBlockers(): boolean {
|
||||
return (
|
||||
(this.activePrompt?.wirePromptsInFlight ?? 0) > 0 ||
|
||||
this.hasQualifyingOpenTools() ||
|
||||
this.permissions.size > 0 ||
|
||||
this.pendingCompactions.size > 0
|
||||
);
|
||||
}
|
||||
|
||||
private shouldDeferTurn(active: ActivePrompt): boolean {
|
||||
if (!this.options.options.acpOptions?.deferTurnOnRunningTools) return false;
|
||||
if (active.cancelling || this.closing || this.processFailed) return false;
|
||||
return this.hasQualifyingOpenTools() || active.crossedEndTurn;
|
||||
}
|
||||
|
||||
private finishDeferredTurn(active: ActivePrompt, outcome: DeferredTurnOutcome): void {
|
||||
const deferred = active.deferred;
|
||||
if (!deferred) return;
|
||||
if (deferred.timer) clearTimeout(deferred.timer);
|
||||
active.deferred = null;
|
||||
deferred.resolve(outcome);
|
||||
}
|
||||
|
||||
private noteDeferredToolTransition(
|
||||
wasOpenQualifying: boolean,
|
||||
isOpenQualifying: boolean,
|
||||
isOpen: boolean,
|
||||
snapshot: AcpToolCallSnapshot,
|
||||
wireSeq: number,
|
||||
): void {
|
||||
const active = this.activePrompt;
|
||||
if (!active || wasOpenQualifying === isOpenQualifying) return;
|
||||
if (!active.deferred && !this.isPostWirePrompt(active, wireSeq)) return;
|
||||
if (!active.deferred && wasOpenQualifying && !isOpen && this.toolKeepsTurnOpen(snapshot)) {
|
||||
active.crossedEndTurn = true;
|
||||
}
|
||||
if (isOpenQualifying) active.replyState = "idle";
|
||||
if (active.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
private noteDeferredChunk(
|
||||
kind: "agent_message_chunk" | "agent_thought_chunk",
|
||||
wireSeq: number,
|
||||
): void {
|
||||
const active = this.activePrompt;
|
||||
if (!active || !this.isPostWirePrompt(active, wireSeq)) return;
|
||||
if (kind === "agent_message_chunk") active.replyState = "open";
|
||||
else if (active.replyState !== "open") active.replyState = "idle";
|
||||
if (active.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
private noteDeferredUsageUpdate(wireSeq: number): void {
|
||||
const active = this.activePrompt;
|
||||
if (!active || !this.isPostWirePrompt(active, wireSeq) || active.replyState !== "open") return;
|
||||
active.replyState = this.hasQualifyingOpenTools() ? "settled_with_open_tools" : "settled";
|
||||
if (active.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
private scheduleDeferredSettle(): void {
|
||||
const active = this.activePrompt;
|
||||
const deferred = active?.deferred;
|
||||
const config = this.options.options.acpOptions?.deferTurnOnRunningTools;
|
||||
if (!active || !deferred || !config || active.cancelling) return;
|
||||
if (deferred.timer) {
|
||||
clearTimeout(deferred.timer);
|
||||
deferred.timer = null;
|
||||
}
|
||||
if (this.hasDeferredBlockers()) return;
|
||||
const settled =
|
||||
active.replyState === "settled" || active.replyState === "settled_with_open_tools";
|
||||
const delayMs = settled
|
||||
? (config.settleDelayMs ?? DEFAULT_DEFERRED_SETTLE_DELAY_MS)
|
||||
: (config.quietLimitMs ?? DEFAULT_DEFERRED_QUIET_LIMIT_MS);
|
||||
deferred.timer = setTimeout(() => {
|
||||
deferred.timer = null;
|
||||
void this.trySettleDeferredTurn(active, deferred);
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
private async trySettleDeferredTurn(
|
||||
active: ActivePrompt,
|
||||
deferred: DeferredTurnState,
|
||||
): Promise<void> {
|
||||
await this.drainNotifications();
|
||||
if (
|
||||
this.closing ||
|
||||
this.processFailed ||
|
||||
active.cancelling ||
|
||||
active.deferred !== deferred ||
|
||||
deferred.timer !== null ||
|
||||
this.hasDeferredBlockers()
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true });
|
||||
}
|
||||
|
||||
private waitForInitialCommands(): Promise<void> {
|
||||
if (this.receivedInitialCommands) return Promise.resolve();
|
||||
const timeoutMs = this.options.options.acpOptions?.initialCommandsTimeoutMs ?? 1_000;
|
||||
@@ -1421,9 +1918,10 @@ class AcpRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
function routeVendorNotifications(
|
||||
function routeIncomingMessages(
|
||||
stream: Stream,
|
||||
receive: (method: string, params: unknown) => void,
|
||||
receiveVendor: (method: string, params: unknown) => void,
|
||||
observeWire: (message: unknown) => void,
|
||||
): Stream {
|
||||
const clientMethods = new Set<string>(Object.values(CLIENT_METHODS));
|
||||
return {
|
||||
@@ -1435,11 +1933,14 @@ function routeVendorNotifications(
|
||||
// The SDK dispatches extensions asynchronously and can resolve a later response first.
|
||||
// Run synchronous vendor transforms in wire order, inside the configuration transaction.
|
||||
try {
|
||||
receive(message.method, message.params);
|
||||
receiveVendor(message.method, message.params);
|
||||
} catch (error) {
|
||||
console.error("Error handling ACP vendor notification", error);
|
||||
}
|
||||
} else controller.enqueue(message);
|
||||
} else {
|
||||
observeWire(message);
|
||||
controller.enqueue(message);
|
||||
}
|
||||
},
|
||||
}),
|
||||
),
|
||||
@@ -1470,11 +1971,12 @@ function permissionOptionBehavior(
|
||||
|
||||
function ownConnectorStream(source: Stream): {
|
||||
stream: Stream;
|
||||
close(): Promise<void>;
|
||||
close(options?: { force?: boolean; timeoutMs?: number }): Promise<void>;
|
||||
whenClosed(): Promise<void> | null;
|
||||
} {
|
||||
const reader = source.readable.getReader();
|
||||
const writer = source.writable.getWriter();
|
||||
let closed = false;
|
||||
let closing: Promise<void> | null = null;
|
||||
const stream: Stream = {
|
||||
readable: new ReadableStream({
|
||||
async pull(controller) {
|
||||
@@ -1496,13 +1998,29 @@ function ownConnectorStream(source: Stream): {
|
||||
};
|
||||
return {
|
||||
stream,
|
||||
async close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
await Promise.allSettled([
|
||||
reader.cancel(new Error("Paseo closed the ACP connector")),
|
||||
writer.close(),
|
||||
]);
|
||||
whenClosed: () => closing,
|
||||
async close(options?: { force?: boolean; timeoutMs?: number }) {
|
||||
if (!closing) {
|
||||
const closeWrite = options?.force
|
||||
? writer.abort(new Error("Paseo aborted the ACP connector"))
|
||||
: writer.close();
|
||||
closing = Promise.allSettled([
|
||||
reader.cancel(new Error("Paseo closed the ACP connector")),
|
||||
closeWrite,
|
||||
]).then((results) => {
|
||||
if (options?.timeoutMs === undefined) return undefined;
|
||||
const rejected = results.find(
|
||||
(result): result is PromiseRejectedResult => result.status === "rejected",
|
||||
);
|
||||
if (rejected) throw rejected.reason;
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
if (options?.timeoutMs !== undefined) {
|
||||
await withTimeout(closing, options.timeoutMs, "ACP connector did not close");
|
||||
} else {
|
||||
await closing.catch(() => undefined);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -53,6 +53,18 @@ export interface AcpOptions {
|
||||
initialCommandsTimeoutMs?: number;
|
||||
/** Allow delayed session/load updates before publishing the session as ready. */
|
||||
loadReplayQuietPeriodMs?: number;
|
||||
/**
|
||||
* Keep a turn open after `end_turn` while qualifying tool calls are still running,
|
||||
* settling once those tools finish and the agent finishes its follow-up reply.
|
||||
*/
|
||||
deferTurnOnRunningTools?: {
|
||||
/** Delay after `usage_update` closes a follow-up reply before settling. Defaults to 500ms. */
|
||||
settleDelayMs?: number;
|
||||
/** Quiet limit after qualifying tools finish if no reply settles via `usage_update`. Defaults to 120_000ms. */
|
||||
quietLimitMs?: number;
|
||||
/** Predicate deciding whether an open tool call keeps the turn open. Defaults to all running tools. */
|
||||
keepsTurnOpen?: (toolCall: AcpToolCallSnapshot) => boolean;
|
||||
};
|
||||
/** An unattended mode that approves ACP allow-once requests in the specified native mode. */
|
||||
autoAcceptMode?: {
|
||||
mode: Omit<ProviderMode, "isUnattended">;
|
||||
|
||||
@@ -881,6 +881,7 @@ export class AgentManager {
|
||||
>();
|
||||
private readonly collectingRuntimes = new Set<string>();
|
||||
private readonly lifecycleMutationTails = new Map<string, Promise<void>>();
|
||||
private readonly pendingCancellations = new Map<string, Promise<unknown>>();
|
||||
private readonly agentStreamCoalescer: AgentStreamCoalescer;
|
||||
private mcpBaseUrl: string | null;
|
||||
private readonly mcpAuthToken: string | null;
|
||||
@@ -2463,80 +2464,83 @@ export class AgentManager {
|
||||
// reload or close; providers do no sequencing of their own.
|
||||
|
||||
async setAgentMode(agentId: string, modeId: string): Promise<AgentProviderNotice | null> {
|
||||
return this.runLifecycleMutation(agentId, async () => {
|
||||
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
|
||||
const notice = (await agent.session.setMode(modeId)) ?? null;
|
||||
await this.drainSessionEvents(agentId);
|
||||
const currentMode = (await agent.session.getCurrentMode()) ?? modeId;
|
||||
agent.config.modeId = currentMode ?? undefined;
|
||||
agent.currentModeId = currentMode;
|
||||
// Update runtimeInfo to reflect the new mode
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = { ...agent.runtimeInfo, modeId: currentMode };
|
||||
}
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
return notice;
|
||||
});
|
||||
return this.runLifecycleMutation(agentId, () =>
|
||||
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
|
||||
const notice = (await agent.session.setMode(modeId)) ?? null;
|
||||
await this.drainSessionEvents(agentId);
|
||||
const currentMode = (await agent.session.getCurrentMode()) ?? modeId;
|
||||
agent.config.modeId = currentMode ?? undefined;
|
||||
agent.currentModeId = currentMode;
|
||||
// Update runtimeInfo to reflect the new mode
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = { ...agent.runtimeInfo, modeId: currentMode };
|
||||
}
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
return notice;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async setAgentModel(agentId: string, modelId: string | null): Promise<void> {
|
||||
return this.runLifecycleMutation(agentId, async () => {
|
||||
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
|
||||
const normalizedModelId =
|
||||
typeof modelId === "string" && modelId.trim().length > 0 ? modelId : null;
|
||||
return this.runLifecycleMutation(agentId, () =>
|
||||
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
|
||||
const normalizedModelId =
|
||||
typeof modelId === "string" && modelId.trim().length > 0 ? modelId : null;
|
||||
|
||||
const selection = await agent.session.setModel?.(normalizedModelId);
|
||||
await this.drainSessionEvents(agentId);
|
||||
const selection = await agent.session.setModel?.(normalizedModelId);
|
||||
await this.drainSessionEvents(agentId);
|
||||
|
||||
// A reset clears the preference even when the provider retains its active model.
|
||||
let effectiveModelId = normalizedModelId;
|
||||
if (normalizedModelId !== null && selection) effectiveModelId = selection.model;
|
||||
// A reset clears the preference even when the provider retains its active model.
|
||||
let effectiveModelId = normalizedModelId;
|
||||
if (normalizedModelId !== null && selection) effectiveModelId = selection.model;
|
||||
|
||||
agent.config.model = effectiveModelId ?? undefined;
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = { ...agent.runtimeInfo, model: effectiveModelId };
|
||||
}
|
||||
this.refreshSessionPersistence(agent);
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
});
|
||||
agent.config.model = effectiveModelId ?? undefined;
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = { ...agent.runtimeInfo, model: effectiveModelId };
|
||||
}
|
||||
this.refreshSessionPersistence(agent);
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async setAgentThinkingOption(
|
||||
agentId: string,
|
||||
thinkingOptionId: string | null,
|
||||
): Promise<AgentProviderNotice | null> {
|
||||
return this.runLifecycleMutation(agentId, async () => {
|
||||
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
|
||||
const normalizedThinkingOptionId =
|
||||
typeof thinkingOptionId === "string" && thinkingOptionId.trim().length > 0
|
||||
? thinkingOptionId
|
||||
: null;
|
||||
return this.runLifecycleMutation(agentId, () =>
|
||||
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
|
||||
const normalizedThinkingOptionId =
|
||||
typeof thinkingOptionId === "string" && thinkingOptionId.trim().length > 0
|
||||
? thinkingOptionId
|
||||
: null;
|
||||
|
||||
let notice: AgentProviderNotice | null = null;
|
||||
if (agent.session.setThinkingOption) {
|
||||
notice = (await agent.session.setThinkingOption(normalizedThinkingOptionId)) ?? null;
|
||||
}
|
||||
await this.drainSessionEvents(agentId);
|
||||
let notice: AgentProviderNotice | null = null;
|
||||
if (agent.session.setThinkingOption) {
|
||||
notice = (await agent.session.setThinkingOption(normalizedThinkingOptionId)) ?? null;
|
||||
}
|
||||
await this.drainSessionEvents(agentId);
|
||||
|
||||
let effectiveThinkingOptionId = normalizedThinkingOptionId;
|
||||
const runtimeInfo = await agent.session.getRuntimeInfo();
|
||||
if (runtimeInfo.thinkingOptionId !== undefined) {
|
||||
effectiveThinkingOptionId = runtimeInfo.thinkingOptionId;
|
||||
}
|
||||
let effectiveThinkingOptionId = normalizedThinkingOptionId;
|
||||
const runtimeInfo = await agent.session.getRuntimeInfo();
|
||||
if (runtimeInfo.thinkingOptionId !== undefined) {
|
||||
effectiveThinkingOptionId = runtimeInfo.thinkingOptionId;
|
||||
}
|
||||
|
||||
agent.config.thinkingOptionId = effectiveThinkingOptionId ?? undefined;
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = {
|
||||
...agent.runtimeInfo,
|
||||
thinkingOptionId: effectiveThinkingOptionId,
|
||||
};
|
||||
}
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
return notice;
|
||||
});
|
||||
agent.config.thinkingOptionId = effectiveThinkingOptionId ?? undefined;
|
||||
if (agent.runtimeInfo) {
|
||||
agent.runtimeInfo = {
|
||||
...agent.runtimeInfo,
|
||||
thinkingOptionId: effectiveThinkingOptionId,
|
||||
};
|
||||
}
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
return notice;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2546,42 +2550,45 @@ export class AgentManager {
|
||||
* one step once the provider accepts. Patches to one agent run one at a time, in arrival order.
|
||||
*/
|
||||
async setAgentOptions(agentId: string, requested: ProviderOptionsPatch): Promise<void> {
|
||||
return this.runLifecycleMutation(agentId, async () => {
|
||||
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
|
||||
const patch = this.convertLegacyOptions(agent.provider, requested);
|
||||
let ended: ProviderOptionsPatch = {};
|
||||
let sent: ProviderOptionsPatch = {};
|
||||
if (Object.keys(patch).length > 0) {
|
||||
// A provider that cannot apply options to a running agent must not store them either.
|
||||
if (!agent.session.applyOptions) {
|
||||
throw new ProviderOptionsValidationError(
|
||||
agent.provider,
|
||||
Object.keys(patch).map((key) => ({
|
||||
path: [key],
|
||||
message: "cannot change on a running session; it applies when the agent is opened",
|
||||
})),
|
||||
return this.runLifecycleMutation(agentId, () =>
|
||||
this.withLiveInteractiveSessionUnlocked(agentId, async (agent) => {
|
||||
const patch = this.convertLegacyOptions(agent.provider, requested);
|
||||
let ended: ProviderOptionsPatch = {};
|
||||
let sent: ProviderOptionsPatch = {};
|
||||
if (Object.keys(patch).length > 0) {
|
||||
// A provider that cannot apply options to a running agent must not store them either.
|
||||
if (!agent.session.applyOptions) {
|
||||
throw new ProviderOptionsValidationError(
|
||||
agent.provider,
|
||||
Object.keys(patch).map((key) => ({
|
||||
path: [key],
|
||||
message: "cannot change on a running session; it applies when the agent is opened",
|
||||
})),
|
||||
);
|
||||
}
|
||||
const set = Object.fromEntries(
|
||||
Object.entries(patch).filter(([, value]) => value != null),
|
||||
);
|
||||
const resolved = this.effectiveOptionsFor(agent.provider, set);
|
||||
sent = Object.fromEntries(Object.keys(patch).map((key) => [key, resolved[key] ?? null]));
|
||||
const modelBefore = agent.runtimeInfo?.model;
|
||||
ended = (await agent.session.applyOptions(sent)) ?? {};
|
||||
// Changes the provider made on its own while applying are older than its final answer.
|
||||
await this.drainSessionEvents(agentId);
|
||||
await this.refreshRuntimeInfo(agent, { emit: false });
|
||||
// An option can choose the model too, as an fx connection does. Reopening the agent on
|
||||
// the earlier preference would send that model to the new connection.
|
||||
const modelAfter = agent.runtimeInfo?.model;
|
||||
if (agent.config.model && modelAfter && modelAfter !== modelBefore) {
|
||||
agent.config.model = modelAfter;
|
||||
}
|
||||
}
|
||||
const set = Object.fromEntries(Object.entries(patch).filter(([, value]) => value != null));
|
||||
const resolved = this.effectiveOptionsFor(agent.provider, set);
|
||||
sent = Object.fromEntries(Object.keys(patch).map((key) => [key, resolved[key] ?? null]));
|
||||
const modelBefore = agent.runtimeInfo?.model;
|
||||
ended = (await agent.session.applyOptions(sent)) ?? {};
|
||||
// Changes the provider made on its own while applying are older than its final answer.
|
||||
await this.drainSessionEvents(agentId);
|
||||
await this.refreshRuntimeInfo(agent, { emit: false });
|
||||
// An option can choose the model too, as an fx connection does. Reopening the agent on
|
||||
// the earlier preference would send that model to the new connection.
|
||||
const modelAfter = agent.runtimeInfo?.model;
|
||||
if (agent.config.model && modelAfter && modelAfter !== modelBefore) {
|
||||
agent.config.model = modelAfter;
|
||||
}
|
||||
}
|
||||
this.storeOptionsPatch({ agent, patch: { ...patch, ...ended } });
|
||||
this.updateEffectiveOptions({ agent, sent, reported: ended });
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
});
|
||||
this.storeOptionsPatch({ agent, patch: { ...patch, ...ended } });
|
||||
this.updateEffectiveOptions({ agent, sent, reported: ended });
|
||||
this.touchUpdatedAt(agent);
|
||||
this.emitState(agent);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** The config as the opened session left it: its own difference from the options it was given. */
|
||||
@@ -3267,6 +3274,33 @@ export class AgentManager {
|
||||
return this.requireSessionAgent(agentId);
|
||||
}
|
||||
|
||||
/** Inside the agent's lane: transparently reopens a retired plugin session before applying config. */
|
||||
private async withLiveInteractiveSessionUnlocked<T>(
|
||||
agentId: string,
|
||||
operation: (agent: ActiveManagedAgent) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const pendingCancellation = this.pendingCancellations.get(agentId);
|
||||
if (pendingCancellation) {
|
||||
await this.waitWithTimeout({
|
||||
operation: pendingCancellation.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
),
|
||||
timeoutMs: this.rescueTimeouts.interruptSessionMs,
|
||||
});
|
||||
}
|
||||
const agent = await this.ensureInteractiveSessionUnlocked(agentId);
|
||||
try {
|
||||
return await operation(agent);
|
||||
} catch (error) {
|
||||
if (!isStaleProviderSessionError(error)) throw error;
|
||||
await this.runs.getPendingRun(agentId)?.settledPromise.catch(() => undefined);
|
||||
if (this.hasInFlightRun(agentId)) throw error;
|
||||
await this.trackAgentRegistrationOperation(this.reloadAgentSessionInternal(agentId));
|
||||
return await operation(this.requireSessionAgent(agentId));
|
||||
}
|
||||
}
|
||||
|
||||
private async *streamAfterHistoryLoad(
|
||||
agentId: string,
|
||||
prompt: AgentPromptInput,
|
||||
@@ -3925,10 +3959,18 @@ export class AgentManager {
|
||||
}
|
||||
|
||||
async cancelAgentRun(agentId: string): Promise<AgentRunCancellationResult> {
|
||||
return this.runForegroundMutation(agentId, () => {
|
||||
const cancellation = this.runForegroundMutation(agentId, () => {
|
||||
this.requireSessionAgent(agentId).pendingReplacement = false;
|
||||
return this.cancelAgentRunNow(agentId);
|
||||
});
|
||||
this.pendingCancellations.set(agentId, cancellation);
|
||||
try {
|
||||
return await cancellation;
|
||||
} finally {
|
||||
if (this.pendingCancellations.get(agentId) === cancellation) {
|
||||
this.pendingCancellations.delete(agentId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async cancelAgentRunNow(agentId: string): Promise<AgentRunCancellationResult> {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { createIdleRuntimeCleanup } from "./idle-runtime-cleanup/index.js";
|
||||
import { relative } from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { runAcpProvider, type AcpStreamMessage } from "@getpaseo/plugin/server/acp";
|
||||
import type {
|
||||
ProviderConnection,
|
||||
ProviderLaunch,
|
||||
@@ -13,6 +14,7 @@ import type {
|
||||
ProviderInput,
|
||||
ProviderRegistration,
|
||||
} from "@getpaseo/plugin/server/provider";
|
||||
import { sendPreparedPromptToAgent } from "./agent-prompt.js";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { createTestLogger } from "../../test-utils/test-logger.js";
|
||||
@@ -2814,3 +2816,592 @@ test("resumes a goose session saved by the generic ACP provider", async () => {
|
||||
await plugins.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test("preserves a deferred ACP background job on steer and cancels it on explicit Stop through AgentManager", async () => {
|
||||
const logger = createTestLogger();
|
||||
const home = await mkdtemp(join(tmpdir(), "paseo-acp-deferred-daemon-"));
|
||||
const storage = new AgentStorage(join(home, "agents"), logger);
|
||||
let cancelCount = 0;
|
||||
let promptCount = 0;
|
||||
let currentMode = "default";
|
||||
let notifyAgent: ((message: AcpStreamMessage) => void) | null = null;
|
||||
let holdNextPrompt: ((release: () => void) => void) | null = null;
|
||||
const modeConfig = () => [
|
||||
{
|
||||
id: "mode",
|
||||
name: "Mode",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: currentMode,
|
||||
options: [
|
||||
{ value: "default", name: "Default" },
|
||||
{ value: "plan", name: "Plan" },
|
||||
],
|
||||
},
|
||||
];
|
||||
const registration = runAcpProvider({
|
||||
id: "deferred-acp-daemon",
|
||||
label: "Deferred ACP Daemon",
|
||||
acpOptions: {
|
||||
deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 1_000 },
|
||||
},
|
||||
connector() {
|
||||
let controller!: ReadableStreamDefaultController<AcpStreamMessage>;
|
||||
const readable = new ReadableStream<AcpStreamMessage>({
|
||||
start(ctrl) {
|
||||
controller = ctrl;
|
||||
},
|
||||
});
|
||||
const send = (message: AcpStreamMessage) => controller.enqueue(message);
|
||||
notifyAgent = send;
|
||||
const writable = new WritableStream<AcpStreamMessage>({
|
||||
write(message) {
|
||||
if (!("method" in message)) return;
|
||||
if (message.method === "session/cancel") {
|
||||
cancelCount += 1;
|
||||
return;
|
||||
}
|
||||
if (!("id" in message)) return;
|
||||
if (message.method === "initialize") {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: message.id,
|
||||
result: { protocolVersion: 1, agentCapabilities: { loadSession: true } },
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/new") {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: message.id,
|
||||
result: { sessionId: "acp-s1", configOptions: modeConfig() },
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/load") {
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { configOptions: modeConfig() } });
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/set_config_option") {
|
||||
const params = message.params as { value?: string } | undefined;
|
||||
if (typeof params?.value === "string") currentMode = params.value;
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { configOptions: modeConfig() } });
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/prompt") {
|
||||
promptCount += 1;
|
||||
if (promptCount === 1) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "bg-job-1",
|
||||
name: "run_command",
|
||||
title: "Background job",
|
||||
status: "in_progress",
|
||||
},
|
||||
},
|
||||
});
|
||||
} else if (promptCount === 2) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "Steered reply" },
|
||||
},
|
||||
},
|
||||
});
|
||||
} else {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "bg-job-2",
|
||||
name: "run_command",
|
||||
title: "Cancelable job",
|
||||
status: "in_progress",
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (holdNextPrompt) {
|
||||
const hook = holdNextPrompt;
|
||||
holdNextPrompt = null;
|
||||
hook(() =>
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { stopReason: "cancelled" } }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
send({ jsonrpc: "2.0", id: message.id, result: { stopReason: "end_turn" } });
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/close") {
|
||||
send({ jsonrpc: "2.0", id: message.id, result: {} });
|
||||
}
|
||||
},
|
||||
});
|
||||
return { readable, writable };
|
||||
},
|
||||
});
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([registration]);
|
||||
const manager = new AgentManager({ clients: plugins.clients(), registry: storage, logger });
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: registration.id, cwd: home }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const first = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "start background job",
|
||||
logger,
|
||||
});
|
||||
expect(first.disposition).toBe("turn_started");
|
||||
if (first.disposition === "turn_started") await first.started;
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
|
||||
// Follow-up steer through AgentManager preserves the background job without session/cancel.
|
||||
const followUp = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "still working?",
|
||||
activeTurnBehavior: "steer",
|
||||
logger,
|
||||
});
|
||||
expect(followUp.disposition).toBe("steered");
|
||||
expect(cancelCount).toBe(0);
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
|
||||
// Completing the job + reply + usage_update settles the turn cleanly.
|
||||
notifyAgent!({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: { sessionUpdate: "tool_call_update", toolCallId: "bg-job-1", status: "completed" },
|
||||
},
|
||||
});
|
||||
notifyAgent!({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "Background job finished." },
|
||||
},
|
||||
},
|
||||
});
|
||||
notifyAgent!({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "acp-s1",
|
||||
update: { sessionUpdate: "usage_update", used: 120, size: 1000 },
|
||||
},
|
||||
});
|
||||
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 3_000 }).toBe("idle");
|
||||
expect(cancelCount).toBe(0);
|
||||
|
||||
// Start a second deferred job, send two steers while steer 1 waits on ACP, and press Stop.
|
||||
let heldSteerResponse: (() => void) | null = null;
|
||||
const second = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "start cancelable job",
|
||||
logger,
|
||||
});
|
||||
if (second.disposition === "turn_started") await second.started;
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
|
||||
// Hold the next steer prompt so Stop races with a queued second steer.
|
||||
holdNextPrompt = (release) => {
|
||||
heldSteerResponse = release;
|
||||
};
|
||||
const steerOne = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "held steer 1",
|
||||
activeTurnBehavior: "steer",
|
||||
logger,
|
||||
});
|
||||
expect(steerOne.disposition).toBe("steered");
|
||||
const steerTwo = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "queued steer 2",
|
||||
activeTurnBehavior: "steer",
|
||||
logger,
|
||||
});
|
||||
expect(steerTwo.disposition).toBe("steered");
|
||||
await expect.poll(() => heldSteerResponse).not.toBeNull();
|
||||
const promptsBeforeStop = promptCount;
|
||||
|
||||
// Stop must send session/cancel immediately, retire the deferred session cleanly,
|
||||
// and never dispatch the queued steer 2 to ACP.
|
||||
await manager.cancelAgentRun(agent.id);
|
||||
expect(cancelCount).toBe(1);
|
||||
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 3_000 }).toBe("idle");
|
||||
expect(promptCount).toBe(promptsBeforeStop);
|
||||
|
||||
// Changing mode immediately after stopping a deferred turn must transparently reopen the session.
|
||||
await manager.setAgentMode(agent.id, "plan");
|
||||
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
|
||||
expect(currentMode).toBe("plan");
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await plugins.shutdown();
|
||||
await storage.flush();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("reopens cleanly for mode changes and follow-up sends initiated while Stop is closing a slow ACP process", async () => {
|
||||
const logger = createTestLogger();
|
||||
const home = await mkdtemp(join(tmpdir(), "paseo-acp-slow-stop-"));
|
||||
const storage = new AgentStorage(join(home, "agents"), logger);
|
||||
const script = join(home, "slow-stop-agent.cjs");
|
||||
const { writeFile } = await import("node:fs/promises");
|
||||
await writeFile(
|
||||
script,
|
||||
`
|
||||
const { createInterface } = require("node:readline");
|
||||
const send = (msg) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\\n");
|
||||
let mode = "default";
|
||||
const configOptions = () => [{
|
||||
id: "mode", name: "Mode", category: "mode", type: "select", currentValue: mode,
|
||||
options: [{ value: "default", name: "Default" }, { value: "plan", name: "Plan" }],
|
||||
}];
|
||||
process.on("SIGTERM", () => {
|
||||
setTimeout(() => process.exit(0), 250);
|
||||
});
|
||||
createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const msg = JSON.parse(line);
|
||||
if (msg.method === "initialize") {
|
||||
send({ id: msg.id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true } } });
|
||||
} else if (msg.method === "session/new") {
|
||||
send({ id: msg.id, result: { sessionId: "slow-s1", configOptions: configOptions() } });
|
||||
} else if (msg.method === "session/load") {
|
||||
send({ id: msg.id, result: { configOptions: configOptions() } });
|
||||
} else if (msg.method === "session/set_config_option") {
|
||||
if (msg.params && typeof msg.params.value === "string") mode = msg.params.value;
|
||||
send({ id: msg.id, result: { configOptions: configOptions() } });
|
||||
} else if (msg.method === "session/prompt") {
|
||||
const text = msg.params?.prompt?.[0]?.text ?? "";
|
||||
if (text.includes("start bg")) {
|
||||
send({ method: "session/update", params: { sessionId: "slow-s1", update: {
|
||||
sessionUpdate: "tool_call", toolCallId: "slow-bg-1", name: "run_command",
|
||||
title: "Slow bg job", status: "in_progress",
|
||||
} } });
|
||||
} else {
|
||||
send({ method: "session/update", params: { sessionId: "slow-s1", update: {
|
||||
sessionUpdate: "agent_message_chunk", content: { type: "text", text: "After stop reply" },
|
||||
} } });
|
||||
}
|
||||
send({ id: msg.id, result: { stopReason: "end_turn" } });
|
||||
} else if (msg.method === "session/close") {
|
||||
send({ id: msg.id, result: {} });
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
const registration = runAcpProvider({
|
||||
id: "slow-stop-acp",
|
||||
label: "Slow Stop ACP",
|
||||
command: [process.execPath, script],
|
||||
acpOptions: {
|
||||
deferTurnOnRunningTools: { settleDelayMs: 25, quietLimitMs: 1_000 },
|
||||
},
|
||||
});
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([registration]);
|
||||
const manager = new AgentManager({ clients: plugins.clients(), registry: storage, logger });
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: registration.id, cwd: home }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const first = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "start bg",
|
||||
logger,
|
||||
});
|
||||
if (first.disposition === "turn_started") await first.started;
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
|
||||
// Start Stop (takes 250ms to terminate the child on SIGTERM) and trigger a mode change mid-shutdown.
|
||||
const stopPromise = manager.cancelAgentRun(agent.id);
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
const modePromise = manager.setAgentMode(agent.id, "plan");
|
||||
await Promise.all([stopPromise, modePromise]);
|
||||
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle");
|
||||
|
||||
// A follow-up prompt immediately after Stop + mode change succeeds cleanly.
|
||||
const next = await sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "fresh prompt",
|
||||
logger,
|
||||
});
|
||||
expect(next.disposition).toBe("turn_started");
|
||||
if (next.disposition === "turn_started") await next.started;
|
||||
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 3_000 }).toBe("idle");
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await plugins.shutdown();
|
||||
await storage.flush();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("does not block mode changes after a plugin refuses Stop by ignoring session.interrupt", async () => {
|
||||
const logger = createTestLogger();
|
||||
let currentMode = "code";
|
||||
const harness = createProviderHarness({
|
||||
async handleInput(input, emit) {
|
||||
if (input.type === "session.open") {
|
||||
emit({
|
||||
type: "session.opened",
|
||||
requestId: input.requestId,
|
||||
sessionId: input.sessionId,
|
||||
capabilities: ["prompt.message", "session.interrupt", "session.configure"],
|
||||
restoration: "core",
|
||||
title: input.config.title,
|
||||
cwd: input.config.cwd,
|
||||
});
|
||||
emit({
|
||||
type: "session.config",
|
||||
sessionId: input.sessionId,
|
||||
config: {
|
||||
mode: currentMode,
|
||||
modes: [
|
||||
{ id: "code", label: "Code" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
models: [],
|
||||
thinkingOptions: [],
|
||||
},
|
||||
});
|
||||
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.prompt") {
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "turn", turnId: "hung-turn" },
|
||||
});
|
||||
emit({
|
||||
type: "session.turn",
|
||||
sessionId: input.sessionId,
|
||||
turnId: "hung-turn",
|
||||
state: "started",
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.interrupt") {
|
||||
// Intentionally never acknowledge session.interrupt.
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.configure") {
|
||||
if (input.changes.mode) currentMode = input.changes.mode;
|
||||
emit({
|
||||
type: "session.config",
|
||||
sessionId: input.sessionId,
|
||||
config: {
|
||||
mode: currentMode,
|
||||
modes: [
|
||||
{ id: "code", label: "Code" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
models: [],
|
||||
thinkingOptions: [],
|
||||
},
|
||||
});
|
||||
emit({ type: "request.completed", requestId: input.requestId });
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([harness.registration]);
|
||||
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
|
||||
const manager = new AgentManager({
|
||||
logger,
|
||||
clients: { "plugin-direct": registry["plugin-direct"].createClient(logger) },
|
||||
providerDefinitions: { "plugin-direct": registry["plugin-direct"] },
|
||||
rescueTimeouts: { interruptSessionMs: 50 },
|
||||
});
|
||||
try {
|
||||
const agent = await manager.createAgent(
|
||||
{ provider: "plugin-direct", cwd: tmpdir() },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const stream = manager.streamAgent(agent.id, "start");
|
||||
void stream.next();
|
||||
await expect
|
||||
.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 2_000 })
|
||||
.toBe("running");
|
||||
|
||||
const cancelResult = await manager.cancelAgentRun(agent.id);
|
||||
expect(cancelResult.status).toBe("refused");
|
||||
|
||||
// Settings change must not hang behind the unacknowledged session.interrupt.
|
||||
await manager.setAgentMode(agent.id, "plan");
|
||||
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await plugins.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test("bounds settings wait when Stop is queued behind an unanswered steer", async () => {
|
||||
const logger = createTestLogger();
|
||||
let currentMode = "code";
|
||||
let releaseSteer: (() => void) | null = null;
|
||||
const harness = createProviderHarness({
|
||||
capabilities: ["prompt.message", "prompt.steer", "session.interrupt", "session.configure"],
|
||||
async handleInput(input, emit) {
|
||||
if (input.type === "session.open") {
|
||||
emit({
|
||||
type: "session.opened",
|
||||
requestId: input.requestId,
|
||||
sessionId: input.sessionId,
|
||||
capabilities: [
|
||||
"prompt.message",
|
||||
"prompt.steer",
|
||||
"session.interrupt",
|
||||
"session.configure",
|
||||
],
|
||||
restoration: "core",
|
||||
title: input.config.title,
|
||||
cwd: input.config.cwd,
|
||||
});
|
||||
emit({
|
||||
type: "session.config",
|
||||
sessionId: input.sessionId,
|
||||
config: {
|
||||
mode: currentMode,
|
||||
modes: [
|
||||
{ id: "code", label: "Code" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
models: [],
|
||||
thinkingOptions: [],
|
||||
},
|
||||
});
|
||||
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.prompt") {
|
||||
if (input.prompt.delivery === "steer") {
|
||||
releaseSteer = () =>
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "steer", turnId: "steer-turn" },
|
||||
});
|
||||
return true;
|
||||
}
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "turn", turnId: "steer-turn" },
|
||||
});
|
||||
emit({
|
||||
type: "session.turn",
|
||||
sessionId: input.sessionId,
|
||||
turnId: "steer-turn",
|
||||
state: "started",
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.interrupt") {
|
||||
return true;
|
||||
}
|
||||
if (input.type === "session.configure") {
|
||||
if (input.changes.mode) currentMode = input.changes.mode;
|
||||
emit({
|
||||
type: "session.config",
|
||||
sessionId: input.sessionId,
|
||||
config: {
|
||||
mode: currentMode,
|
||||
modes: [
|
||||
{ id: "code", label: "Code" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
models: [],
|
||||
thinkingOptions: [],
|
||||
},
|
||||
});
|
||||
emit({ type: "request.completed", requestId: input.requestId });
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
const plugins = new PluginAgentClientRegistry(logger);
|
||||
plugins.replace([harness.registration]);
|
||||
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
|
||||
const manager = new AgentManager({
|
||||
logger,
|
||||
clients: { "plugin-direct": registry["plugin-direct"].createClient(logger) },
|
||||
providerDefinitions: { "plugin-direct": registry["plugin-direct"] },
|
||||
rescueTimeouts: { interruptSessionMs: 50 },
|
||||
});
|
||||
try {
|
||||
const agent = await manager.createAgent(
|
||||
{ provider: "plugin-direct", cwd: tmpdir() },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const stream = manager.streamAgent(agent.id, "start");
|
||||
void stream.next();
|
||||
await expect
|
||||
.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 2_000 })
|
||||
.toBe("running");
|
||||
|
||||
// Start an unanswered steer, queue Stop behind it, then change mode.
|
||||
const steerPromise = manager.steerAgentRun(agent.id, "unanswered steer").catch(() => undefined);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
const stopPromise = manager.cancelAgentRun(agent.id);
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
|
||||
// Mode change must complete within the bounded interrupt timeout even while Stop is queued.
|
||||
await manager.setAgentMode(agent.id, "plan");
|
||||
expect(manager.getAgent(agent.id)?.currentModeId).toBe("plan");
|
||||
|
||||
releaseSteer?.();
|
||||
await Promise.all([steerPromise, stopPromise]);
|
||||
} finally {
|
||||
releaseSteer?.();
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await plugins.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -739,6 +739,7 @@ class ProviderRuntimeSession {
|
||||
}
|
||||
|
||||
async configure(changes: ProviderConfigChanges): Promise<void> {
|
||||
if (this.terminal) throw new StaleProviderSessionError(this.id);
|
||||
const input: Extract<ProviderInput, { type: "session.configure" }> = {
|
||||
type: "session.configure",
|
||||
requestId: randomUUID(),
|
||||
|
||||
@@ -213,3 +213,156 @@ describe("installation", () => {
|
||||
).resolves.toEqual({ status: "not_installed" });
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a turn open for backgrounded run_command calls but not IsDaemon commands", async () => {
|
||||
const { directory, launch } = await launchAgent(`
|
||||
const { createInterface } = require("node:readline");
|
||||
const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
|
||||
let turn = 0;
|
||||
createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const { id, method, params } = JSON.parse(line);
|
||||
switch (method) {
|
||||
case "initialize":
|
||||
send({ id, result: { protocolVersion: 1, agentCapabilities: {} } });
|
||||
break;
|
||||
case "session/new":
|
||||
send({ id, result: { sessionId: "agy-session", configOptions: [
|
||||
{ id: "mode", name: "Mode", category: "mode", type: "select", currentValue: "default",
|
||||
options: [{ value: "default", name: "Default" }] },
|
||||
] } });
|
||||
break;
|
||||
case "session/prompt":
|
||||
turn += 1;
|
||||
if (turn === 1) {
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "tool_call", toolCallId: "daemon-1", name: "run_command",
|
||||
title: "Dev server", status: "in_progress", rawInput: { CommandLine: "npm run dev", IsDaemon: true },
|
||||
} } });
|
||||
send({ id, result: { stopReason: "end_turn" } });
|
||||
} else {
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "tool_call", toolCallId: "bg-1", name: "run_command",
|
||||
title: "Background build", status: "in_progress", rawInput: { CommandLine: "sleep 1" },
|
||||
} } });
|
||||
send({ id, result: { stopReason: "end_turn" } });
|
||||
setTimeout(() => {
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "tool_call_update", toolCallId: "bg-1", status: "completed",
|
||||
} } });
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Build finished." },
|
||||
} } });
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "usage_update", used: 50, size: 1000,
|
||||
} } });
|
||||
}, 80);
|
||||
}
|
||||
break;
|
||||
case "session/close":
|
||||
send({ id, result: {} });
|
||||
break;
|
||||
}
|
||||
});
|
||||
`);
|
||||
const provider = createAntigravityProvider();
|
||||
const connection = await provider.connect({
|
||||
launch,
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send({
|
||||
type: "session.open",
|
||||
requestId: "open-1",
|
||||
sessionId: "agy-test",
|
||||
history: "skip",
|
||||
config: {
|
||||
cwd: directory,
|
||||
env: {},
|
||||
mcpServers: {},
|
||||
settings: {},
|
||||
persist: false,
|
||||
},
|
||||
});
|
||||
await expect
|
||||
.poll(() => events.find((event) => event.type === "session.ready"), { timeout: 3_000 })
|
||||
.toBeDefined();
|
||||
|
||||
// Turn 1: IsDaemon: true completes immediately on end_turn.
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "agy-test",
|
||||
prompt: {
|
||||
clientMessageId: "daemon-turn",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "start dev server" }] },
|
||||
},
|
||||
});
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
events.find(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:daemon-turn" &&
|
||||
event.state === "completed",
|
||||
),
|
||||
{ timeout: 3_000 },
|
||||
)
|
||||
.toBeDefined();
|
||||
|
||||
// Turn 2: non-daemon background command keeps turn open until completion + reply + usage_update.
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "agy-test",
|
||||
prompt: {
|
||||
clientMessageId: "bg-turn",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "run build" }] },
|
||||
},
|
||||
});
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
events.find(
|
||||
(event) =>
|
||||
event.type === "timeline.item" &&
|
||||
event.item.type === "tool_call" &&
|
||||
event.item.id === "bg-1" &&
|
||||
event.item.status === "running",
|
||||
),
|
||||
{ timeout: 3_000 },
|
||||
)
|
||||
.toBeDefined();
|
||||
expect(
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:bg-turn" &&
|
||||
event.state === "completed",
|
||||
),
|
||||
).toBe(false);
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
events.find(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId === "acp:bg-turn" &&
|
||||
event.state === "completed",
|
||||
),
|
||||
{ timeout: 3_000 },
|
||||
)
|
||||
.toBeDefined();
|
||||
expect(events).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: "timeline.item",
|
||||
item: expect.objectContaining({ type: "assistant_message", text: "Build finished." }),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -95,6 +95,16 @@ export function createAntigravityProvider(): ProviderRegistration {
|
||||
acpOptions: {
|
||||
waitForInitialCommands: true,
|
||||
loadReplayQuietPeriodMs: 200,
|
||||
// COMPAT(antigravityAcpV1DeferredTurn): added in v0.18.0, remove once Antigravity CLI supports ACP v2 state_update.
|
||||
deferTurnOnRunningTools: {
|
||||
keepsTurnOpen(toolCall) {
|
||||
const input = toolCall.input;
|
||||
if (typeof input === "object" && input !== null && !Array.isArray(input)) {
|
||||
return input.IsDaemon !== true;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
},
|
||||
autoAcceptMode: {
|
||||
mode: {
|
||||
id: "full-access",
|
||||
|
||||
Reference in New Issue
Block a user