mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-20 15:25:13 +00:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
760d70bfb7 | ||
|
|
925a07c7ca | ||
|
|
b10238b16d | ||
|
|
f26d320591 | ||
|
|
3a0fd9a753 | ||
|
|
bcd9c5da8a | ||
|
|
e22c23c15b | ||
|
|
3691dbec3e | ||
|
|
dfabe5dd0a | ||
|
|
8c2a675a7a | ||
|
|
23c0df84ab |
@@ -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>();
|
||||
@@ -366,6 +369,31 @@ interface PendingPermission {
|
||||
resolve(response: RequestPermissionResponse): void;
|
||||
}
|
||||
|
||||
type DeferredTurnOutcome =
|
||||
| { type: "complete"; terminalizeTools: boolean }
|
||||
| { type: "cancel" }
|
||||
| { type: "fail"; error: { message: string } };
|
||||
|
||||
interface DeferredTurnState {
|
||||
replyOpen: boolean;
|
||||
replySettled: boolean;
|
||||
timer: ReturnType<typeof setTimeout> | null;
|
||||
resolve(outcome: DeferredTurnOutcome): void;
|
||||
}
|
||||
|
||||
interface ActivePrompt {
|
||||
turnId: string;
|
||||
settled: Promise<void>;
|
||||
cancelling: boolean;
|
||||
wirePromptsInFlight: number;
|
||||
wirePromptLane: Promise<void>;
|
||||
deferred: DeferredTurnState | null;
|
||||
}
|
||||
|
||||
const DEFAULT_DEFERRED_SETTLE_DELAY_MS = 500;
|
||||
const DEFAULT_DEFERRED_QUIET_LIMIT_MS = 120_000;
|
||||
const DEFAULT_DEFERRED_CANCEL_TIMEOUT_MS = 1_000;
|
||||
|
||||
class AcpRuntime {
|
||||
readonly connection: ClientSideConnection;
|
||||
agentCapabilities: AgentCapabilities = {};
|
||||
@@ -374,6 +402,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>();
|
||||
@@ -407,8 +437,7 @@ class AcpRuntime {
|
||||
private readonly closeConnector: () => Promise<void>;
|
||||
private notificationLane: Promise<void> = Promise.resolve();
|
||||
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> {
|
||||
@@ -484,23 +513,25 @@ class AcpRuntime {
|
||||
);
|
||||
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 +640,26 @@ class AcpRuntime {
|
||||
}
|
||||
|
||||
async prompt(input: Extract<ProviderInput, { type: "session.prompt" }>): Promise<void> {
|
||||
if (this.closing || this.processFailed) {
|
||||
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 {
|
||||
await this.interrupt();
|
||||
}
|
||||
await active.settled;
|
||||
if (this.closing || this.processFailed) {
|
||||
throw new Error("ACP session is closed");
|
||||
}
|
||||
}
|
||||
const prompt = toAcpPrompt(input.prompt);
|
||||
this.replayWindow = null;
|
||||
@@ -643,6 +690,14 @@ class AcpRuntime {
|
||||
turnId,
|
||||
state: "started",
|
||||
});
|
||||
const activePrompt: ActivePrompt = {
|
||||
turnId,
|
||||
settled: Promise.resolve(),
|
||||
cancelling: false,
|
||||
wirePromptsInFlight: 1,
|
||||
wirePromptLane: Promise.resolve(),
|
||||
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 +705,7 @@ class AcpRuntime {
|
||||
).then(
|
||||
async (response): Promise<void> => {
|
||||
await this.drainNotifications();
|
||||
activePrompt.wirePromptsInFlight -= 1;
|
||||
if (response.usage) {
|
||||
this.lastUsage = {
|
||||
...this.lastUsage,
|
||||
@@ -665,33 +721,22 @@ 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;
|
||||
});
|
||||
@@ -699,12 +744,22 @@ class AcpRuntime {
|
||||
|
||||
async interrupt(): Promise<void> {
|
||||
const active = this.activePrompt;
|
||||
if (active) active.cancelling = true;
|
||||
if (active) {
|
||||
active.cancelling = true;
|
||||
if (active.deferred) {
|
||||
// Record open tools owned by Stop before writing session/cancel so any failure
|
||||
// update arriving during or after cancel preserves their canceled state.
|
||||
for (const id of this.liveOpenToolIds) this.canceledToolCallIds.add(id);
|
||||
}
|
||||
}
|
||||
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);
|
||||
if (active.deferred) await this.settleCanceledDeferredTurn(active);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -758,6 +813,7 @@ class AcpRuntime {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
permissionId,
|
||||
});
|
||||
if (this.activePrompt?.deferred) this.scheduleDeferredSettle();
|
||||
}
|
||||
|
||||
async configure(
|
||||
@@ -1066,6 +1122,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,
|
||||
@@ -1144,6 +1201,13 @@ class AcpRuntime {
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
if (this.activePrompt?.deferred) {
|
||||
if (update.sessionUpdate === "agent_message_chunk" && !this.hasDeferredBlockers()) {
|
||||
this.activePrompt.deferred.replyOpen = true;
|
||||
}
|
||||
this.activePrompt.deferred.replySettled = false;
|
||||
this.scheduleDeferredSettle();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
|
||||
@@ -1253,6 +1317,7 @@ class AcpRuntime {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
usage: this.lastUsage,
|
||||
});
|
||||
this.noteDeferredUsageUpdate();
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "compaction_update") {
|
||||
@@ -1267,12 +1332,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 +1375,41 @@ class AcpRuntime {
|
||||
this.pendingCompactions.clear();
|
||||
}
|
||||
|
||||
private reduceToolCall(update: ToolCall | ToolCallUpdate): void {
|
||||
private reduceToolCall(
|
||||
update: Extract<SessionUpdate, { sessionUpdate: "tool_call" | "tool_call_update" }>,
|
||||
): 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);
|
||||
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),
|
||||
});
|
||||
if (this.activePrompt?.deferred) {
|
||||
if (this.toolKeepsTurnOpen(snapshot)) {
|
||||
this.activePrompt.deferred.replyOpen = false;
|
||||
this.activePrompt.deferred.replySettled = false;
|
||||
}
|
||||
this.scheduleDeferredSettle();
|
||||
}
|
||||
}
|
||||
|
||||
private vendorNotification(method: string, params: unknown): void {
|
||||
@@ -1376,25 +1472,299 @@ 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;
|
||||
deferred.replyOpen = false;
|
||||
deferred.replySettled = false;
|
||||
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;
|
||||
}
|
||||
const response = await this.call(
|
||||
this.connection.prompt({ sessionId: this.nativeSessionId, prompt }),
|
||||
);
|
||||
await this.drainNotifications();
|
||||
if (this.closing || 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" || active.cancelling) {
|
||||
this.finishDeferredTurn(active, { type: "cancel" });
|
||||
return;
|
||||
}
|
||||
if (this.hasQualifyingOpenTools()) this.fallbackChunkIds.clear();
|
||||
if (response.stopReason !== "end_turn" && active.wirePromptsInFlight === 1) {
|
||||
this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true });
|
||||
}
|
||||
} catch (error) {
|
||||
await this.drainNotifications();
|
||||
if (this.closing || active.deferred !== deferred) return;
|
||||
if (active.cancelling) {
|
||||
this.finishDeferredTurn(active, { type: "cancel" });
|
||||
} else 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 {
|
||||
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 = { replyOpen: false, replySettled: false, timer: null, resolve };
|
||||
});
|
||||
if (this.closing) 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();
|
||||
}
|
||||
|
||||
private async settleCanceledDeferredTurn(active: ActivePrompt): Promise<void> {
|
||||
if (active.wirePromptsInFlight > 0) {
|
||||
const timeoutMs =
|
||||
this.options.options.acpOptions?.deferTurnOnRunningTools?.cancelTimeoutMs ??
|
||||
DEFAULT_DEFERRED_CANCEL_TIMEOUT_MS;
|
||||
const settled = await settlesWithin(active.wirePromptLane, timeoutMs);
|
||||
if (!settled && active.deferred) {
|
||||
this.finishDeferredTurn(active, { type: "cancel" });
|
||||
await active.settled;
|
||||
if (!this.closing && !this.processFailed) {
|
||||
this.emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
error: { message: "ACP session did not settle canceled prompt" },
|
||||
});
|
||||
await this.close();
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (active.deferred) {
|
||||
this.finishDeferredTurn(active, { type: "cancel" });
|
||||
}
|
||||
}
|
||||
|
||||
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 noteDeferredUsageUpdate(): void {
|
||||
const deferred = this.activePrompt?.deferred;
|
||||
if (!deferred?.replyOpen || this.hasDeferredBlockers()) return;
|
||||
deferred.replySettled = true;
|
||||
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 delayMs = deferred.replySettled
|
||||
? (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;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -53,6 +53,20 @@ 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;
|
||||
/** Bounded wait for an in-flight steered prompt to settle after `session/cancel` before closing the wedged runtime. Defaults to 1_000ms. */
|
||||
cancelTimeoutMs?: 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">;
|
||||
|
||||
@@ -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,232 @@ 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 notifyAgent: ((message: AcpStreamMessage) => void) | null = null;
|
||||
let holdNextPrompt: ((release: () => void) => void) | null = null;
|
||||
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: {} },
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (message.method === "session/new") {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: message.id,
|
||||
result: { sessionId: "acp-s1", configOptions: [] },
|
||||
});
|
||||
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 without waiting behind steer 2,
|
||||
// and releasing steer 1 must not dispatch steer 2 to ACP.
|
||||
const stopPromise = manager.cancelAgentRun(agent.id);
|
||||
await expect.poll(() => cancelCount, { timeout: 2_000 }).toBe(1);
|
||||
heldSteerResponse!();
|
||||
await stopPromise;
|
||||
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle, { timeout: 3_000 }).toBe("idle");
|
||||
expect(promptCount).toBe(promptsBeforeStop);
|
||||
} 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 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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