mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-20 15:25:13 +00:00
Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a608dcd997 | ||
|
|
a8f1cc2e53 | ||
|
|
6a94956be8 | ||
|
|
a929921df3 | ||
|
|
285f03520e | ||
|
|
451a5e907c | ||
|
|
230dc8d00d | ||
|
|
0b30bf032b | ||
|
|
aed906aaba | ||
|
|
d30e159c0c | ||
|
|
23a1e0c237 | ||
|
|
0d1d2c4f80 | ||
|
|
1e1c1f1892 | ||
|
|
589a2f6c89 | ||
|
|
6137ef4ebc | ||
|
|
76ff0f45da | ||
|
|
4f4a20017f | ||
|
|
35ae17d72f | ||
|
|
d0acdad709 | ||
|
|
344cb3a389 | ||
|
|
28c0904c28 | ||
|
|
06a6863046 | ||
|
|
c7fbd08215 | ||
|
|
66185df4f5 |
@@ -10,6 +10,7 @@ test("retries a failed observation and receives subsequent updates", async () =>
|
||||
}
|
||||
const observers: Observer[] = [];
|
||||
let releases = 0;
|
||||
const interrupted: string[] = [];
|
||||
const item = {
|
||||
id: "shell",
|
||||
kind: "shell",
|
||||
@@ -19,6 +20,10 @@ test("retries a failed observation and receives subsequent updates", async () =>
|
||||
const client = {
|
||||
getLastServerInfoMessage: () => ({ features: { agentBackgroundWork: true } }),
|
||||
stopAgentBackgroundWork: async () => {},
|
||||
cancelAgent: async (agentId: string) => {
|
||||
interrupted.push(agentId);
|
||||
if (interrupted.length === 1) throw new Error("Stop failed");
|
||||
},
|
||||
listAgentBackgroundWork: async () => [item],
|
||||
observeAgentBackgroundWork: () => ({
|
||||
subscribe: (observer: Observer) => {
|
||||
@@ -54,6 +59,13 @@ test("retries a failed observation and receives subsequent updates", async () =>
|
||||
payload: { agentId: "agent", items: [] },
|
||||
});
|
||||
expect(model.getSnapshot()).toEqual({ status: "ready", items: [] });
|
||||
const firstStop = model.interruptSession();
|
||||
expect(model.getSnapshot().sessionStop).toBe("pending");
|
||||
await firstStop;
|
||||
expect(model.getSnapshot().sessionStop).toBe("error");
|
||||
await model.interruptSession();
|
||||
expect(model.getSnapshot().sessionStop).toBeUndefined();
|
||||
expect(interrupted).toEqual(["agent", "agent"]);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
@@ -71,6 +83,7 @@ test("starts observing after the same client reconnects", async () => {
|
||||
getLastServerInfoMessage: () =>
|
||||
connected ? { features: { agentBackgroundWork: true } } : null,
|
||||
stopAgentBackgroundWork: async () => {},
|
||||
cancelAgent: async () => {},
|
||||
listAgentBackgroundWork: async () => [item],
|
||||
observeAgentBackgroundWork: () => ({
|
||||
subscribe: (observer: { snapshot(): void }) => {
|
||||
|
||||
@@ -8,6 +8,7 @@ interface BackgroundWorkClient {
|
||||
features?: { agentBackgroundWork?: boolean; agentBackgroundWorkStop?: boolean } | null;
|
||||
} | null;
|
||||
stopAgentBackgroundWork(agentId: string, item: PaseoAgentBackgroundWorkItem): Promise<void>;
|
||||
cancelAgent(agentId: string): Promise<void>;
|
||||
listAgentBackgroundWork(agentId: string): Promise<PaseoAgentBackgroundWorkItem[]>;
|
||||
observeAgentBackgroundWork(): {
|
||||
subscribe(observer: {
|
||||
@@ -45,6 +46,10 @@ export function createHostBackgroundWorkModel(
|
||||
return items.map(({ canStop: _canStop, stopToken: _stopToken, ...item }) => item);
|
||||
};
|
||||
return createBackgroundWorkModel({
|
||||
interruptSession: () => {
|
||||
if (!client) return Promise.reject(new Error("Host disconnected"));
|
||||
return client.cancelAgent(agentId);
|
||||
},
|
||||
stop: (item) => {
|
||||
if (!client) return Promise.reject(new Error("Host disconnected"));
|
||||
return client.stopAgentBackgroundWork(agentId, item);
|
||||
|
||||
@@ -18,12 +18,14 @@ function kindKey(kind: string): "shell" | "monitor" | "heartbeat" | "other" {
|
||||
export function BackgroundWorkTrack({
|
||||
model,
|
||||
count,
|
||||
canInterruptSession,
|
||||
}: {
|
||||
model: ReturnType<typeof createHostBackgroundWorkModel>;
|
||||
count: number;
|
||||
canInterruptSession: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { items, status, stops } = useSyncExternalStore(
|
||||
const { items, status, stops, sessionStop } = useSyncExternalStore(
|
||||
model.subscribe,
|
||||
model.getSnapshot,
|
||||
model.getSnapshot,
|
||||
@@ -77,6 +79,25 @@ export function BackgroundWorkTrack({
|
||||
stopStatus={stops?.[item.stopToken ?? ""]?.status}
|
||||
/>
|
||||
))}
|
||||
{canInterruptSession && status === "ready" ? (
|
||||
<ComposerTrackRow>
|
||||
<View style={styles.row}>
|
||||
{sessionStop === "error" ? (
|
||||
<Text style={styles.facts}>{t("message.backgroundWork.stopError")}</Text>
|
||||
) : null}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={sessionStop === "pending"}
|
||||
onPress={model.interruptSession}
|
||||
>
|
||||
{sessionStop === "pending"
|
||||
? t("message.backgroundWork.stopping")
|
||||
: t("message.backgroundWork.stopSession")}
|
||||
</Button>
|
||||
</View>
|
||||
</ComposerTrackRow>
|
||||
) : null}
|
||||
</ComposerTrackPill>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { PaseoAgentBackgroundWorkItem as AgentBackgroundWorkItem } from "@g
|
||||
interface Port {
|
||||
list(): Promise<AgentBackgroundWorkItem[]>;
|
||||
stop?(item: AgentBackgroundWorkItem): Promise<void>;
|
||||
interruptSession?(): Promise<void>;
|
||||
observe(callbacks: {
|
||||
snapshot(): void;
|
||||
disconnected(): void;
|
||||
@@ -15,6 +16,7 @@ interface BackgroundWorkState {
|
||||
status: "loading" | "stale" | "ready" | "error";
|
||||
items: AgentBackgroundWorkItem[] | null;
|
||||
stops?: Record<string, { status: "pending" | "error"; item: AgentBackgroundWorkItem }>;
|
||||
sessionStop?: "pending" | "error";
|
||||
}
|
||||
|
||||
export function createBackgroundWorkModel(port: Port) {
|
||||
@@ -25,10 +27,7 @@ export function createBackgroundWorkModel(port: Port) {
|
||||
let observationFailed = false;
|
||||
const listeners = new Set<() => void>();
|
||||
const publish = (next: BackgroundWorkState) => {
|
||||
state =
|
||||
next.stops === undefined && state.stops === undefined
|
||||
? next
|
||||
: { ...next, stops: next.stops ?? state.stops };
|
||||
state = { ...state, ...next };
|
||||
for (const listener of listeners) listener();
|
||||
};
|
||||
const refresh = async () => {
|
||||
@@ -58,7 +57,12 @@ export function createBackgroundWorkModel(port: Port) {
|
||||
{ ...entry, status: "error" as const },
|
||||
]),
|
||||
);
|
||||
publish({ status: state.items === null ? "loading" : "stale", items: state.items, stops });
|
||||
publish({
|
||||
status: state.items === null ? "loading" : "stale",
|
||||
items: state.items,
|
||||
...(stops ? { stops } : {}),
|
||||
...(state.sessionStop === "pending" ? { sessionStop: "error" } : {}),
|
||||
});
|
||||
},
|
||||
failed: () => {
|
||||
observationFailed = true;
|
||||
@@ -95,6 +99,18 @@ export function createBackgroundWorkModel(port: Port) {
|
||||
publish({ ...state, stops: { ...state.stops, [token]: { status: "error", item } } });
|
||||
}
|
||||
},
|
||||
interruptSession: async () => {
|
||||
if (!port.interruptSession || state.status !== "ready" || state.sessionStop === "pending")
|
||||
return;
|
||||
const generation = stopGeneration;
|
||||
publish({ ...state, sessionStop: "pending" });
|
||||
try {
|
||||
await port.interruptSession();
|
||||
if (generation === stopGeneration) publish({ ...state, sessionStop: undefined });
|
||||
} catch {
|
||||
if (generation === stopGeneration) publish({ ...state, sessionStop: "error" });
|
||||
}
|
||||
},
|
||||
retry: () => {
|
||||
if (observationFailed) {
|
||||
stop?.();
|
||||
|
||||
@@ -406,6 +406,7 @@ export const ar: TranslationResources = {
|
||||
notRunning: "لم يعد قيد التشغيل",
|
||||
dismiss: "إغلاق",
|
||||
stop: "إيقاف",
|
||||
stopSession: "إيقاف الوكيل وعمله في الخلفية",
|
||||
stopping: "جارٍ الإيقاف…",
|
||||
stopError: "تعذر تأكيد الإيقاف.",
|
||||
label: "في الخلفية",
|
||||
|
||||
@@ -405,6 +405,7 @@ export const en = {
|
||||
notRunning: "No longer running",
|
||||
dismiss: "Dismiss",
|
||||
stop: "Stop",
|
||||
stopSession: "Stop agent and its background work",
|
||||
stopping: "Stopping…",
|
||||
stopError: "Could not confirm stop.",
|
||||
label: "Background",
|
||||
|
||||
@@ -411,6 +411,7 @@ export const es: TranslationResources = {
|
||||
notRunning: "Ya no está en ejecución",
|
||||
dismiss: "Cerrar",
|
||||
stop: "Detener",
|
||||
stopSession: "Detener el agente y su trabajo en segundo plano",
|
||||
stopping: "Deteniendo…",
|
||||
stopError: "No se pudo confirmar la detención.",
|
||||
label: "Segundo plano",
|
||||
|
||||
@@ -411,6 +411,7 @@ export const fr: TranslationResources = {
|
||||
notRunning: "N’est plus en cours",
|
||||
dismiss: "Fermer",
|
||||
stop: "Arrêter",
|
||||
stopSession: "Arrêter l’agent et son travail en arrière-plan",
|
||||
stopping: "Arrêt…",
|
||||
stopError: "Impossible de confirmer l’arrêt.",
|
||||
label: "Arrière-plan",
|
||||
|
||||
@@ -411,6 +411,7 @@ export const ja: TranslationResources = {
|
||||
notRunning: "実行は終了しました",
|
||||
dismiss: "閉じる",
|
||||
stop: "停止",
|
||||
stopSession: "エージェントとそのバックグラウンド処理を停止",
|
||||
stopping: "停止中…",
|
||||
stopError: "停止を確認できませんでした。",
|
||||
label: "バックグラウンド",
|
||||
|
||||
@@ -407,6 +407,7 @@ export const ko: TranslationResources = {
|
||||
notRunning: "더 이상 실행 중이 아님",
|
||||
dismiss: "닫기",
|
||||
stop: "중지",
|
||||
stopSession: "에이전트와 백그라운드 작업 중지",
|
||||
stopping: "중지 중…",
|
||||
stopError: "중지를 확인하지 못했습니다.",
|
||||
label: "백그라운드",
|
||||
|
||||
@@ -410,6 +410,7 @@ export const ptBR: TranslationResources = {
|
||||
notRunning: "Não está mais em execução",
|
||||
dismiss: "Dispensar",
|
||||
stop: "Parar",
|
||||
stopSession: "Parar o agente e seu trabalho em segundo plano",
|
||||
stopping: "Parando…",
|
||||
stopError: "Não foi possível confirmar a parada.",
|
||||
label: "Segundo plano",
|
||||
|
||||
@@ -410,6 +410,7 @@ export const ru: TranslationResources = {
|
||||
notRunning: "Больше не выполняется",
|
||||
dismiss: "Закрыть",
|
||||
stop: "Остановить",
|
||||
stopSession: "Остановить агента и его фоновые задачи",
|
||||
stopping: "Остановка…",
|
||||
stopError: "Не удалось подтвердить остановку.",
|
||||
label: "В фоне",
|
||||
|
||||
@@ -406,6 +406,7 @@ export const zhCN: TranslationResources = {
|
||||
notRunning: "已不再运行",
|
||||
dismiss: "关闭",
|
||||
stop: "停止",
|
||||
stopSession: "停止智能体及其后台任务",
|
||||
stopping: "正在停止…",
|
||||
stopError: "无法确认已停止。",
|
||||
label: "后台",
|
||||
|
||||
@@ -52,10 +52,10 @@ export const AgentTracks = memo(function AgentTracks({
|
||||
rows: subagentRows,
|
||||
});
|
||||
const { tabId } = usePaneContext();
|
||||
const backgroundWorkCount = useSessionStore((state) => {
|
||||
const backgroundWork = useSessionStore((state) => {
|
||||
const session = state.sessions[serverId];
|
||||
const agent = session?.agents.get(agentId) ?? session?.agentDetails.get(agentId);
|
||||
return agent?.backgroundWork?.count ?? 0;
|
||||
return agent?.backgroundWork;
|
||||
});
|
||||
const backgroundModel = useMemo(
|
||||
() => createHostBackgroundWorkModel(serverId, agentId),
|
||||
@@ -121,7 +121,11 @@ export const AgentTracks = memo(function AgentTracks({
|
||||
|
||||
return (
|
||||
<ComposerTrackBar>
|
||||
<BackgroundWorkTrack model={backgroundModel} count={backgroundWorkCount} />
|
||||
<BackgroundWorkTrack
|
||||
model={backgroundModel}
|
||||
count={backgroundWork?.count ?? 0}
|
||||
canInterruptSession={backgroundWork?.canInterruptSession === true}
|
||||
/>
|
||||
{parentAgentId ? <ParentAgentPill serverId={serverId} parentAgentId={parentAgentId} /> : null}
|
||||
<AgentTaskList tasks={tasks} />
|
||||
<SubagentsTrack
|
||||
|
||||
@@ -23,7 +23,7 @@ export const stopSchema: OutputSchema<StopResult> = {
|
||||
|
||||
export function addStopOptions(cmd: Command): Command {
|
||||
return cmd
|
||||
.description("Interrupt an agent if it is running (no-op for idle agents)")
|
||||
.description("Interrupt an active agent or its cancellable session background work")
|
||||
.argument("[id]", "Agent ID (or prefix) - optional if --all or --cwd specified")
|
||||
.option("--all", "Stop all agents")
|
||||
.option("--cwd <path>", "Stop all agents in directory");
|
||||
@@ -81,10 +81,11 @@ export async function runStopCommand(
|
||||
agents = [fetchResult.agent];
|
||||
}
|
||||
|
||||
// Interrupt each running agent. Idle agents are a no-op.
|
||||
const stopResults = await Promise.all(
|
||||
agents.map(async (agent) => {
|
||||
if (agent.status !== "running") return { ok: true as const, id: agent.id, stopped: false };
|
||||
if (agent.status !== "running" && !agent.backgroundWork?.canInterruptSession) {
|
||||
return { ok: true as const, id: agent.id, stopped: false };
|
||||
}
|
||||
try {
|
||||
await client.cancelAgent(agent.id);
|
||||
return { ok: true as const, id: agent.id, stopped: true };
|
||||
|
||||
@@ -115,24 +115,22 @@ async function fixture() {
|
||||
test("managed two-home restart retains its supervisor and never routes ordinary commands or stop to the other home", async () => {
|
||||
const f = await fixture();
|
||||
const [a, b] = f.homes as [string, string];
|
||||
const portA = await port(),
|
||||
portB = await port(),
|
||||
movedPort = await port();
|
||||
try {
|
||||
await f.configure(a, `127.0.0.1:${portA}`);
|
||||
await f.configure(b, `127.0.0.1:${portB}`);
|
||||
await f.configure(a, "127.0.0.1:0");
|
||||
await f.configure(b, "127.0.0.1:0");
|
||||
const launchA = await f.ok(["start", "--home", a, "--timeout", "30"]);
|
||||
expect(launchA.listen).toMatch(/^127\.0\.0\.1:[1-9]\d*$/);
|
||||
const poisoned = {
|
||||
PASEO_HOME: a,
|
||||
PASEO_HOST: `127.0.0.1:${portA}`,
|
||||
PASEO_LISTEN: `127.0.0.1:${portA}`,
|
||||
PORT: String(portA),
|
||||
PASEO_HOST: launchA.listen,
|
||||
PASEO_LISTEN: launchA.listen,
|
||||
PORT: launchA.listen.split(":")[1],
|
||||
PASEO_WEB_UI_ENABLED: "true",
|
||||
PASEO_RELAY_ENABLED: "true",
|
||||
};
|
||||
const launchB = await f.ok(["daemon", "start", "--home", b, "--timeout", "30"], poisoned);
|
||||
expect(launchA.listen).toBe(`127.0.0.1:${portA}`);
|
||||
expect(launchB.listen).toBe(`127.0.0.1:${portB}`);
|
||||
expect(launchB.listen).toMatch(/^127\.0\.0\.1:[1-9]\d*$/);
|
||||
expect(launchB.listen).not.toBe(launchA.listen);
|
||||
const beforeA = await f.liveStatus(a);
|
||||
const beforeB = await f.liveStatus(b, poisoned);
|
||||
if (process.platform !== "win32") {
|
||||
@@ -151,13 +149,13 @@ test("managed two-home restart retains its supervisor and never routes ordinary
|
||||
expect(restart.supervisorPid).toBe(launchB.pid);
|
||||
expect(restart.workerPid).not.toBe(beforeB.workerPid);
|
||||
const saved = await f.ok(
|
||||
["daemon", "config", "set", "daemon.listen", `127.0.0.1:${movedPort}`, "--home", b],
|
||||
["daemon", "config", "set", "daemon.listen", "localhost:0", "--home", b],
|
||||
poisoned,
|
||||
);
|
||||
expect(saved.restartRequiredPaths).toContain("daemon.listen");
|
||||
await f.ok(["daemon", "restart", "--home", b, "--timeout", "30"], poisoned);
|
||||
const moved = await f.liveStatus(b);
|
||||
expect(moved.listen).toBe(`127.0.0.1:${movedPort}`);
|
||||
expect(moved.listen).toMatch(/^localhost:[1-9]\d*$/);
|
||||
expect(moved.pid).toBe(launchB.pid);
|
||||
await f.ok(["daemon", "stop", "--home", b], poisoned);
|
||||
const stoppedQuery = await f.run(["--json", "project", "ls", "--home", b], poisoned);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { spawnProcess, terminateProcess } from "../process.js";
|
||||
import { Readable, Writable } from "node:stream";
|
||||
import {
|
||||
AGENT_METHODS,
|
||||
ClientSideConnection,
|
||||
CLIENT_METHODS,
|
||||
PROTOCOL_VERSION,
|
||||
@@ -25,6 +27,7 @@ import type {
|
||||
AcpConfigChange,
|
||||
AcpConfigureContext,
|
||||
AcpRequest,
|
||||
AcpStreamMessage,
|
||||
AcpToolCallSnapshot,
|
||||
AcpTransformer,
|
||||
AcpVendorUpdate,
|
||||
@@ -36,6 +39,7 @@ import {
|
||||
ProviderInputSchema,
|
||||
negotiateProviderCapabilities,
|
||||
requireProviderCapabilities,
|
||||
type ProviderBackgroundWorkItem,
|
||||
type ProviderCatalog,
|
||||
type ProviderCapability,
|
||||
type ProviderConfigState,
|
||||
@@ -55,16 +59,28 @@ import {
|
||||
const ADAPTER_CAPABILITIES = [
|
||||
"prompt.message",
|
||||
"prompt.command",
|
||||
"session.can_stop_runtime",
|
||||
"session.configure",
|
||||
"permission",
|
||||
] as const;
|
||||
|
||||
const DEFAULT_OUT_OF_TURN_SETTLE_DELAY_MS = 500;
|
||||
const DEFAULT_OUT_OF_TURN_QUIET_LIMIT_MS = 120_000;
|
||||
|
||||
interface AcpBoundarySession {
|
||||
runtime: AcpRuntime;
|
||||
capabilities: readonly ProviderCapability[];
|
||||
mutationLane: Promise<void>;
|
||||
}
|
||||
|
||||
type AcpToolSettlement = "completed" | "failed" | "canceled";
|
||||
|
||||
interface AcpToolCallRecord {
|
||||
snapshot: AcpToolCallSnapshot;
|
||||
turnId?: string;
|
||||
settlement?: AcpToolSettlement;
|
||||
}
|
||||
|
||||
export async function createAcpProviderConnection(
|
||||
options: RunAcpProviderOptions,
|
||||
request: ProviderConnectRequest,
|
||||
@@ -224,6 +240,16 @@ async function dispatch(input: ProviderInput, state: AcpConnectionState): Promis
|
||||
input.response,
|
||||
);
|
||||
return;
|
||||
case "session.can_stop_runtime": {
|
||||
const session = requireSession(state, input.sessionId);
|
||||
state.emit({
|
||||
type: "session.can_stop_runtime",
|
||||
requestId: input.requestId,
|
||||
sessionId: input.sessionId,
|
||||
canStop: session.runtime.canStopRuntime(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "session.configure": {
|
||||
const session = requireSession(state, input.sessionId);
|
||||
await mutateSession(session, () => session.runtime.configure(input.changes));
|
||||
@@ -329,6 +355,7 @@ async function openSession(
|
||||
capabilities,
|
||||
mutationLane: Promise.resolve(),
|
||||
});
|
||||
runtime.startLiveUpdates();
|
||||
state.emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
|
||||
} catch (error) {
|
||||
await runtime.close();
|
||||
@@ -373,7 +400,8 @@ class AcpRuntime {
|
||||
private readonly child: ChildProcessWithoutNullStreams | null;
|
||||
private emit: (event: ProviderEvent) => void;
|
||||
private readonly messages = new Map<string, string>();
|
||||
private readonly toolCalls = new Map<string, AcpToolCallSnapshot>();
|
||||
private readonly toolCalls = new Map<string, AcpToolCallRecord>();
|
||||
private readonly stoppedToolCalls = 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>();
|
||||
@@ -396,7 +424,7 @@ class AcpRuntime {
|
||||
>();
|
||||
/**
|
||||
* Replay updates count as history until the session reports ready.
|
||||
* Once ready, suppress late replay rows until the first prompt.
|
||||
* Adapters without autonomous activity can suppress late replay until their first prompt.
|
||||
*/
|
||||
private replayWindow: "replay" | "skip" | null = null;
|
||||
private lastLoadUpdateAt = 0;
|
||||
@@ -406,7 +434,18 @@ class AcpRuntime {
|
||||
private stagedTransformerConfig: ProviderConfigState | null = null;
|
||||
private readonly closeConnector: () => Promise<void>;
|
||||
private notificationLane: Promise<void> = Promise.resolve();
|
||||
private interruption: { sent: boolean } | null = null;
|
||||
private autoAccept = false;
|
||||
private readonly outOfTurnActivity: { settleDelayMs: number; quietLimitMs: number } | null;
|
||||
private readonly backgroundToolCalls = new Set<string>();
|
||||
private publishedBackgroundWork = false;
|
||||
private autonomousTurn: {
|
||||
turnId: string;
|
||||
cancelling: boolean;
|
||||
replyOpen: boolean;
|
||||
sawAssistantMessage: boolean;
|
||||
settleTimer: ReturnType<typeof setTimeout> | null;
|
||||
} | null = null;
|
||||
private activePrompt: { turnId: string; settled: Promise<void>; cancelling: boolean } | null =
|
||||
null;
|
||||
private lastUsage: ProviderUsage = {};
|
||||
@@ -473,36 +512,42 @@ class AcpRuntime {
|
||||
this.closeConnector = closeConnector;
|
||||
this.emit = options.emit;
|
||||
this.transformers = options.options.transformers ?? [];
|
||||
const outOfTurn = options.options.acpOptions?.outOfTurnActivity;
|
||||
this.outOfTurnActivity = outOfTurn
|
||||
? {
|
||||
settleDelayMs:
|
||||
typeof outOfTurn === "object" && outOfTurn.settleDelayMs !== undefined
|
||||
? outOfTurn.settleDelayMs
|
||||
: DEFAULT_OUT_OF_TURN_SETTLE_DELAY_MS,
|
||||
quietLimitMs:
|
||||
typeof outOfTurn === "object" && outOfTurn.quietLimitMs !== undefined
|
||||
? outOfTurn.quietLimitMs
|
||||
: DEFAULT_OUT_OF_TURN_QUIET_LIMIT_MS,
|
||||
}
|
||||
: null;
|
||||
const client: Client = {
|
||||
requestPermission: (request) => this.requestPermission(request),
|
||||
sessionUpdate: (notification) =>
|
||||
this.enqueueNotification(() => this.sessionUpdate(notification)),
|
||||
sessionUpdate: (notification) => {
|
||||
const interrupt = this.interruption;
|
||||
return this.enqueueNotification(() =>
|
||||
this.sessionUpdate(notification, interrupt?.sent === true),
|
||||
);
|
||||
},
|
||||
};
|
||||
this.connection = new ClientSideConnection(
|
||||
() => client,
|
||||
routeVendorNotifications(stream, (method, params) => this.vendorNotification(method, params)),
|
||||
routeAcpMessages(
|
||||
stream,
|
||||
(method, params) => this.vendorNotification(method, params),
|
||||
this.outOfTurnActivity ? () => this.activePrompt?.settled : undefined,
|
||||
),
|
||||
);
|
||||
if (!child)
|
||||
void this.connection.closed.then(() => this.failRuntime("ACP transport closed unexpectedly"));
|
||||
child?.on("error", (error) => this.failRuntime(describeError(error)));
|
||||
child?.once("close", (code, signal) =>
|
||||
this.failRuntime(`ACP process exited (${signal ?? code ?? "unknown"})`),
|
||||
);
|
||||
if (!child) void this.connection.closed.then(() => this.handleUnexpectedTransportClose());
|
||||
child?.on("error", (error) => {
|
||||
this.processFailed = true;
|
||||
this.settlePendingWork();
|
||||
if (this.closing || !this.nativeSessionId) return;
|
||||
this.emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
error: { message: describeError(error) },
|
||||
});
|
||||
});
|
||||
child?.once("close", (code, signal) => {
|
||||
if (this.closing || this.processFailed || !this.nativeSessionId) return;
|
||||
this.processFailed = true;
|
||||
this.settlePendingWork();
|
||||
this.emit({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
error: { message: `ACP process exited (${signal ?? code ?? "unknown"})` },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async open(
|
||||
@@ -588,6 +633,10 @@ class AcpRuntime {
|
||||
return sessionCapabilities;
|
||||
}
|
||||
|
||||
startLiveUpdates(): void {
|
||||
if (this.outOfTurnActivity) this.replayWindow = null;
|
||||
}
|
||||
|
||||
async discover(cwd?: string): Promise<ProviderCatalog> {
|
||||
if (cwd === undefined && this.options.options.acpOptions?.workspaceOnlyCatalog) {
|
||||
return { models: [], modes: [] };
|
||||
@@ -608,13 +657,37 @@ class AcpRuntime {
|
||||
};
|
||||
}
|
||||
|
||||
canStopRuntime(): boolean {
|
||||
return (
|
||||
this.activePrompt === null &&
|
||||
this.autonomousTurn === null &&
|
||||
this.backgroundToolCalls.size === 0 &&
|
||||
this.permissions.size === 0
|
||||
);
|
||||
}
|
||||
|
||||
async prompt(input: Extract<ProviderInput, { type: "session.prompt" }>): Promise<void> {
|
||||
const active = this.activePrompt;
|
||||
if (active) {
|
||||
await this.interrupt();
|
||||
await active.settled;
|
||||
}
|
||||
if (this.outOfTurnActivity) {
|
||||
// Keep admission behind any Stop already writing its cancellation.
|
||||
await this.enqueueNotification(() => this.beginPrompt(input));
|
||||
} else {
|
||||
this.beginPrompt(input);
|
||||
}
|
||||
}
|
||||
|
||||
private beginPrompt(input: Extract<ProviderInput, { type: "session.prompt" }>): void {
|
||||
if (this.autonomousTurn) {
|
||||
// session/cancel can kill running background commands and subagents; complete the
|
||||
// out-of-turn wakeup without cancelling so a follow-up prompt leaves them alive.
|
||||
this.finishAutonomousTurn("completed");
|
||||
}
|
||||
const prompt = toAcpPrompt(input.prompt);
|
||||
this.interruption = null;
|
||||
this.replayWindow = null;
|
||||
const turnId = `acp:${input.prompt.clientMessageId}`;
|
||||
this.fallbackChunkIds.clear();
|
||||
@@ -643,13 +716,14 @@ class AcpRuntime {
|
||||
turnId,
|
||||
state: "started",
|
||||
});
|
||||
// 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.
|
||||
// The SDK dispatches notifications without awaiting them. Apply updates already in
|
||||
// the lane before settling. The stream holds post-response frames for live wakeups.
|
||||
const settled = this.call(
|
||||
this.connection.prompt({ sessionId: this.nativeSessionId, prompt }),
|
||||
).then(
|
||||
async (response): Promise<void> => {
|
||||
await this.drainNotifications();
|
||||
if (this.outOfTurnActivity) await this.notificationLane;
|
||||
else await this.drainNotifications();
|
||||
if (response.usage) {
|
||||
this.lastUsage = {
|
||||
...this.lastUsage,
|
||||
@@ -665,9 +739,13 @@ class AcpRuntime {
|
||||
});
|
||||
}
|
||||
const state = response.stopReason === "cancelled" ? "canceled" : "completed";
|
||||
const preserveBackground = state === "completed" && this.outOfTurnActivity !== null;
|
||||
this.fallbackChunkIds.clear();
|
||||
this.terminalizeTransientItems(state);
|
||||
this.terminalizeTransientItems(state, { preserveInProgressTools: preserveBackground });
|
||||
if (preserveBackground) this.syncBackgroundWorkFromInProgressTools();
|
||||
else this.clearBackgroundWork();
|
||||
this.finishTurnPermissions(turnId);
|
||||
if (this.activePrompt?.turnId === turnId) this.activePrompt = null;
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
@@ -677,10 +755,18 @@ class AcpRuntime {
|
||||
return undefined;
|
||||
},
|
||||
async (error): Promise<void> => {
|
||||
await this.drainNotifications();
|
||||
if (this.outOfTurnActivity) await this.notificationLane;
|
||||
else await this.drainNotifications();
|
||||
this.fallbackChunkIds.clear();
|
||||
this.terminalizeTransientItems("failed");
|
||||
const canceled = this.activePrompt?.cancelling === true;
|
||||
const preserveBackground = !canceled && this.outOfTurnActivity !== null;
|
||||
this.terminalizeTransientItems(canceled ? "canceled" : "failed", {
|
||||
turnId: preserveBackground ? turnId : undefined,
|
||||
});
|
||||
if (preserveBackground) this.syncBackgroundWorkFromInProgressTools();
|
||||
else if (canceled) this.clearBackgroundWork();
|
||||
this.finishTurnPermissions(turnId);
|
||||
if (this.activePrompt?.turnId === turnId) this.activePrompt = null;
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
@@ -697,15 +783,48 @@ class AcpRuntime {
|
||||
});
|
||||
}
|
||||
|
||||
async interrupt(): Promise<void> {
|
||||
const active = this.activePrompt;
|
||||
if (active) active.cancelling = true;
|
||||
try {
|
||||
await this.call(this.connection.cancel({ sessionId: this.nativeSessionId }));
|
||||
} finally {
|
||||
interrupt(): Promise<void> {
|
||||
// A peer can publish cancellation updates before the outbound write finishes.
|
||||
// Settle the owned tools before reducing those updates.
|
||||
return this.enqueueNotification(async () => {
|
||||
const active = this.activePrompt;
|
||||
const autonomous = this.autonomousTurn;
|
||||
if (active) active.cancelling = true;
|
||||
if (autonomous) {
|
||||
autonomous.cancelling = true;
|
||||
this.cancelAutonomousSettle();
|
||||
}
|
||||
const previousInterruption = this.interruption;
|
||||
const interruption = { sent: false };
|
||||
if (this.outOfTurnActivity) this.interruption = interruption;
|
||||
try {
|
||||
await this.call(this.connection.cancel({ sessionId: this.nativeSessionId }));
|
||||
// ACP v1 cannot associate late replies with the stopped turn. A new prompt
|
||||
// reopens live delivery while updates received before it stay suppressed.
|
||||
interruption.sent = true;
|
||||
} catch (error) {
|
||||
this.interruption = previousInterruption;
|
||||
if (active) active.cancelling = false;
|
||||
if (autonomous && this.autonomousTurn === autonomous) {
|
||||
autonomous.cancelling = false;
|
||||
this.syncAutonomousTimer();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (this.outOfTurnActivity) {
|
||||
for (const { request } of this.permissions.values()) {
|
||||
this.stoppedToolCalls.add(request.toolCall.toolCallId);
|
||||
}
|
||||
}
|
||||
// An agent may wait for its outstanding permission replies before ending the prompt.
|
||||
if (active) this.finishTurnPermissions(active.turnId);
|
||||
}
|
||||
if (autonomous && this.autonomousTurn?.turnId === autonomous.turnId) {
|
||||
this.finishAutonomousTurn("canceled");
|
||||
} else if (this.outOfTurnActivity) {
|
||||
this.terminalizeTransientItems("canceled");
|
||||
this.clearBackgroundWork();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
listSessions(cwd?: string) {
|
||||
@@ -725,6 +844,7 @@ class AcpRuntime {
|
||||
if (!pending) return;
|
||||
const active = this.activePrompt;
|
||||
if (active?.cancelling && pending.turnId === active.turnId) return;
|
||||
if (this.autonomousTurn?.cancelling && pending.turnId === this.autonomousTurn.turnId) return;
|
||||
const selected = selectPermissionOption(pending.request.options, response);
|
||||
if (response.selectedActionId !== undefined && !selected) {
|
||||
throw new Error(
|
||||
@@ -758,6 +878,7 @@ class AcpRuntime {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
permissionId,
|
||||
});
|
||||
this.syncAutonomousTimer();
|
||||
}
|
||||
|
||||
async configure(
|
||||
@@ -768,7 +889,7 @@ class AcpRuntime {
|
||||
autoAcceptMode &&
|
||||
changes.mode !== undefined &&
|
||||
(changes.mode === autoAcceptMode.mode.id) !== this.autoAccept &&
|
||||
(this.activePrompt || this.permissions.size > 0)
|
||||
(this.activePrompt || this.autonomousTurn || this.permissions.size > 0)
|
||||
) {
|
||||
throw new Error(
|
||||
`Finish or stop the current turn before switching to or from ${autoAcceptMode.mode.label}.`,
|
||||
@@ -1045,27 +1166,38 @@ class AcpRuntime {
|
||||
private async requestPermission(
|
||||
request: RequestPermissionRequest,
|
||||
): Promise<RequestPermissionResponse> {
|
||||
const interrupt = this.interruption;
|
||||
await this.notificationLane;
|
||||
if (this.closing || this.processFailed || this.activePrompt?.cancelling) {
|
||||
return { outcome: { outcome: "cancelled" } };
|
||||
const { toolCallId } = request.toolCall;
|
||||
if (interrupt?.sent && request.sessionId === this.nativeSessionId) {
|
||||
this.stoppedToolCalls.add(toolCallId);
|
||||
}
|
||||
if (
|
||||
this.autoAccept &&
|
||||
request.sessionId === this.nativeSessionId &&
|
||||
this.nativeModeId() === this.options.options.acpOptions?.autoAcceptMode?.nativeMode
|
||||
this.closing ||
|
||||
this.processFailed ||
|
||||
interrupt?.sent ||
|
||||
this.stoppedToolCalls.has(toolCallId) ||
|
||||
this.activePrompt?.cancelling ||
|
||||
this.autonomousTurn?.cancelling
|
||||
) {
|
||||
const allowOptions = request.options.filter((option) => option.kind.startsWith("allow"));
|
||||
const allowOnce = allowOptions.find((option) => option.kind === "allow_once");
|
||||
if (
|
||||
allowOnce &&
|
||||
new Set(allowOptions.map((option) => option.kind)).size === allowOptions.length
|
||||
) {
|
||||
return { outcome: { outcome: "selected", optionId: allowOnce.optionId } };
|
||||
}
|
||||
return { outcome: { outcome: "cancelled" } };
|
||||
}
|
||||
const permissionId = `permission:${request.toolCall.toolCallId}`;
|
||||
if (this.isOutOfTurnLive()) {
|
||||
this.ensureAutonomousTurn();
|
||||
this.onAutonomousNonReplyActivity();
|
||||
}
|
||||
const optionId = this.autoAcceptOptionId(request);
|
||||
if (optionId !== undefined) {
|
||||
return { outcome: { outcome: "selected", optionId } };
|
||||
}
|
||||
const permissionId = `permission:${toolCallId}`;
|
||||
return new Promise((resolve) => {
|
||||
this.permissions.set(permissionId, { request, resolve, turnId: this.activePrompt?.turnId });
|
||||
this.permissions.set(permissionId, {
|
||||
request,
|
||||
resolve,
|
||||
turnId: this.activePrompt?.turnId ?? this.autonomousTurn?.turnId,
|
||||
});
|
||||
this.syncAutonomousTimer();
|
||||
this.emit({
|
||||
type: "session.permission",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
@@ -1085,11 +1217,32 @@ class AcpRuntime {
|
||||
});
|
||||
}
|
||||
|
||||
private sessionUpdate(notification: SessionNotification): void {
|
||||
if (notification.sessionId !== this.nativeSessionId) return;
|
||||
private autoAcceptOptionId(request: RequestPermissionRequest): string | undefined {
|
||||
if (
|
||||
!this.autoAccept ||
|
||||
request.sessionId !== this.nativeSessionId ||
|
||||
this.nativeModeId() !== this.options.options.acpOptions?.autoAcceptMode?.nativeMode
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
const allowOptions = request.options.filter((option) => option.kind.startsWith("allow"));
|
||||
if (new Set(allowOptions.map((option) => option.kind)).size !== allowOptions.length) {
|
||||
return undefined;
|
||||
}
|
||||
return allowOptions.find((option) => option.kind === "allow_once")?.optionId;
|
||||
}
|
||||
|
||||
private sessionUpdate(notification: SessionNotification, interrupted: boolean): void {
|
||||
if (notification.sessionId !== this.nativeSessionId || this.processFailed) return;
|
||||
if (this.replayWindow) this.lastLoadUpdateAt = performance.now();
|
||||
if (this.replayWindow === "skip") {
|
||||
const update = notification.update;
|
||||
const { update } = notification;
|
||||
if (this.replayWindow === "skip" || interrupted) {
|
||||
if (
|
||||
interrupted &&
|
||||
(update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update")
|
||||
) {
|
||||
this.stoppedToolCalls.add(update.toolCallId);
|
||||
}
|
||||
if (
|
||||
update.sessionUpdate === "available_commands_update" ||
|
||||
update.sessionUpdate === "config_option_update" ||
|
||||
@@ -1100,14 +1253,11 @@ class AcpRuntime {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (
|
||||
this.replayWindow === "replay" &&
|
||||
notification.update.sessionUpdate === "user_message_chunk"
|
||||
) {
|
||||
this.reduceUserMessageChunk(notification.update);
|
||||
if (this.replayWindow === "replay" && update.sessionUpdate === "user_message_chunk") {
|
||||
this.reduceUserMessageChunk(update);
|
||||
return;
|
||||
}
|
||||
this.reduceUpdate(notification.update);
|
||||
this.reduceUpdate(update);
|
||||
}
|
||||
|
||||
private reduceUpdate(update: SessionUpdate): void {
|
||||
@@ -1129,6 +1279,10 @@ class AcpRuntime {
|
||||
);
|
||||
this.fallbackChunkIds.delete("user_message_chunk");
|
||||
if (update.content.type !== "text") return;
|
||||
if (this.isOutOfTurnLive()) {
|
||||
this.ensureAutonomousTurn();
|
||||
this.onAutonomousChunk(update.sessionUpdate === "agent_message_chunk");
|
||||
}
|
||||
const id = this.resolveChunkId(update.sessionUpdate, update.messageId);
|
||||
const text = `${this.messages.get(id) ?? ""}${update.content.text}`;
|
||||
this.messages.set(id, text);
|
||||
@@ -1147,14 +1301,36 @@ class AcpRuntime {
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
|
||||
if (update.sessionUpdate === "tool_call") this.fallbackChunkIds.clear();
|
||||
this.reduceToolCall(update);
|
||||
this.reduceLiveToolUpdate(update);
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "plan") this.fallbackChunkIds.clear();
|
||||
this.reduceStateUpdate(update);
|
||||
}
|
||||
|
||||
private reduceLiveToolUpdate(
|
||||
update: Extract<SessionUpdate, { sessionUpdate: "tool_call" | "tool_call_update" }>,
|
||||
): void {
|
||||
// A stopped tool can still report output and terminal echoes after the next prompt.
|
||||
if (this.stoppedToolCalls.has(update.toolCallId)) return;
|
||||
const previous = this.toolCalls.get(update.toolCallId);
|
||||
if (update.sessionUpdate === "tool_call") this.fallbackChunkIds.clear();
|
||||
const previousStatus = previous?.snapshot.status;
|
||||
const backgroundProgress =
|
||||
this.backgroundToolCalls.has(update.toolCallId) &&
|
||||
(update.status == null || update.status === previousStatus);
|
||||
// An already finished tool can receive output without waking the agent.
|
||||
const outOfTurn =
|
||||
this.isOutOfTurnLive() &&
|
||||
!backgroundProgress &&
|
||||
previousStatus !== "completed" &&
|
||||
previousStatus !== "failed" &&
|
||||
(previous?.settlement === undefined || update.status != null);
|
||||
if (outOfTurn) this.ensureAutonomousTurn();
|
||||
this.reduceToolCall(update);
|
||||
if (outOfTurn) this.onAutonomousNonReplyActivity();
|
||||
}
|
||||
|
||||
// Historical user messages arrive only as replayed chunks; a live prompt
|
||||
// already echoes its own user message when it is admitted.
|
||||
private reduceUserMessageChunk(
|
||||
@@ -1253,6 +1429,10 @@ class AcpRuntime {
|
||||
sessionId: this.options.boundarySessionId,
|
||||
usage: this.lastUsage,
|
||||
});
|
||||
if (this.outOfTurnActivity && this.autonomousTurn) {
|
||||
this.autonomousTurn.replyOpen = false;
|
||||
this.syncAutonomousTimer();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (update.sessionUpdate === "compaction_update") {
|
||||
@@ -1270,19 +1450,22 @@ class AcpRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
private terminalizeTransientItems(state: "completed" | "failed" | "canceled"): void {
|
||||
for (const [id, snapshot] of this.toolCalls) {
|
||||
private terminalizeTransientItems(
|
||||
state: AcpToolSettlement,
|
||||
options?: { preserveInProgressTools?: boolean; turnId?: string },
|
||||
): void {
|
||||
for (const [id, record] of this.toolCalls) {
|
||||
const { snapshot, turnId, settlement } = record;
|
||||
if (snapshot.status !== "pending" && snapshot.status !== "in_progress") continue;
|
||||
const completed: AcpToolCallSnapshot = {
|
||||
...snapshot,
|
||||
status: state === "completed" ? "completed" : "failed",
|
||||
};
|
||||
this.toolCalls.set(id, completed);
|
||||
this.emit({
|
||||
type: "timeline.item",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
item: terminalToolItem(toolTimelineItem(snapshot), state),
|
||||
});
|
||||
if (options?.turnId && options.turnId !== turnId) continue;
|
||||
if (options?.preserveInProgressTools && snapshot.status === "in_progress") continue;
|
||||
// Antigravity can send more tool input after Stop even if its row already settled.
|
||||
if (state === "canceled" && (!settlement || this.outOfTurnActivity)) {
|
||||
this.stoppedToolCalls.add(id);
|
||||
}
|
||||
if (settlement) continue;
|
||||
this.toolCalls.set(id, { ...record, settlement: state });
|
||||
this.emitToolCall(terminalToolItem(toolTimelineItem(snapshot), state), turnId);
|
||||
}
|
||||
for (const item of this.vendorToolCalls.values()) {
|
||||
this.emit({
|
||||
@@ -1304,15 +1487,177 @@ class AcpRuntime {
|
||||
|
||||
private reduceToolCall(update: ToolCall | ToolCallUpdate): void {
|
||||
const current = this.toolCalls.get(update.toolCallId);
|
||||
let snapshot = mergeToolCallSnapshot(update, current);
|
||||
let snapshot = mergeToolCallSnapshot(update, current?.snapshot);
|
||||
const context = { sessionId: this.options.boundarySessionId };
|
||||
for (const transformer of this.transformers)
|
||||
snapshot = transformer.toolCall?.(snapshot, context) ?? snapshot;
|
||||
this.toolCalls.set(snapshot.id, snapshot);
|
||||
// Tool snapshots can keep changing after the turn that first published the row.
|
||||
const activeTurnId = this.activePrompt?.turnId ?? this.autonomousTurn?.turnId;
|
||||
const turnId = this.outOfTurnActivity ? (current?.turnId ?? activeTurnId) : undefined;
|
||||
const settlement = update.status == null ? current?.settlement : undefined;
|
||||
this.toolCalls.set(snapshot.id, { snapshot, turnId, settlement });
|
||||
if (this.backgroundToolCalls.has(snapshot.id) && snapshot.status !== "in_progress") {
|
||||
this.backgroundToolCalls.delete(snapshot.id);
|
||||
this.publishBackgroundWork();
|
||||
}
|
||||
const item = toolTimelineItem(snapshot);
|
||||
this.emitToolCall(settlement ? terminalToolItem(item, settlement) : item, turnId);
|
||||
}
|
||||
|
||||
private emitToolCall(item: ToolCallTimelineItem, turnId: string | undefined): void {
|
||||
this.emit({
|
||||
type: "timeline.item",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
item: toolTimelineItem(snapshot),
|
||||
item,
|
||||
...(turnId ? { turnId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
private isOutOfTurnLive(): boolean {
|
||||
return (
|
||||
this.outOfTurnActivity !== null &&
|
||||
this.activePrompt === null &&
|
||||
this.replayWindow === null &&
|
||||
!this.closing &&
|
||||
!this.processFailed
|
||||
);
|
||||
}
|
||||
|
||||
private ensureAutonomousTurn(): void {
|
||||
if (this.autonomousTurn) return;
|
||||
const turnId = `acp:autonomous:${randomUUID()}`;
|
||||
this.fallbackChunkIds.clear();
|
||||
this.autonomousTurn = {
|
||||
turnId,
|
||||
cancelling: false,
|
||||
replyOpen: false,
|
||||
sawAssistantMessage: false,
|
||||
settleTimer: null,
|
||||
};
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId,
|
||||
state: "started",
|
||||
acceptsFollowUp: true,
|
||||
});
|
||||
}
|
||||
|
||||
private onAutonomousChunk(isAssistantMessage: boolean): void {
|
||||
if (!this.autonomousTurn) return;
|
||||
this.autonomousTurn.replyOpen = true;
|
||||
this.autonomousTurn.sawAssistantMessage = isAssistantMessage;
|
||||
this.syncAutonomousTimer();
|
||||
}
|
||||
|
||||
private onAutonomousNonReplyActivity(): void {
|
||||
if (!this.autonomousTurn) return;
|
||||
this.autonomousTurn.replyOpen = false;
|
||||
this.autonomousTurn.sawAssistantMessage = false;
|
||||
this.syncAutonomousTimer();
|
||||
}
|
||||
|
||||
private syncAutonomousTimer(): void {
|
||||
const turn = this.autonomousTurn;
|
||||
if (!turn || !this.outOfTurnActivity) return;
|
||||
if (this.hasPendingPermissionsForTurn(turn.turnId)) {
|
||||
this.cancelAutonomousSettle();
|
||||
return;
|
||||
}
|
||||
if (!turn.replyOpen && turn.sawAssistantMessage) {
|
||||
this.scheduleAutonomousSettle(this.outOfTurnActivity.settleDelayMs);
|
||||
return;
|
||||
}
|
||||
this.scheduleAutonomousSettle(this.outOfTurnActivity.quietLimitMs);
|
||||
}
|
||||
|
||||
private cancelAutonomousSettle(): void {
|
||||
if (!this.autonomousTurn?.settleTimer) return;
|
||||
clearTimeout(this.autonomousTurn.settleTimer);
|
||||
this.autonomousTurn.settleTimer = null;
|
||||
}
|
||||
|
||||
private scheduleAutonomousSettle(delayMs: number): void {
|
||||
if (!this.autonomousTurn) return;
|
||||
this.cancelAutonomousSettle();
|
||||
const turnId = this.autonomousTurn.turnId;
|
||||
this.autonomousTurn.settleTimer = setTimeout(() => {
|
||||
if (this.autonomousTurn?.turnId !== turnId) return;
|
||||
this.finishAutonomousTurn("completed");
|
||||
}, delayMs);
|
||||
this.autonomousTurn.settleTimer.unref?.();
|
||||
}
|
||||
|
||||
private finishAutonomousTurn(state: "completed" | "canceled" | "failed"): void {
|
||||
const turn = this.autonomousTurn;
|
||||
if (!turn) return;
|
||||
this.cancelAutonomousSettle();
|
||||
this.autonomousTurn = null;
|
||||
const preserveBackground = state === "completed" && this.outOfTurnActivity !== null;
|
||||
this.fallbackChunkIds.clear();
|
||||
this.terminalizeTransientItems(state, { preserveInProgressTools: preserveBackground });
|
||||
if (preserveBackground) this.syncBackgroundWorkFromInProgressTools();
|
||||
else this.clearBackgroundWork();
|
||||
this.finishTurnPermissions(turn.turnId);
|
||||
this.emit({
|
||||
type: "session.turn",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
turnId: turn.turnId,
|
||||
state,
|
||||
});
|
||||
}
|
||||
|
||||
private hasPendingPermissionsForTurn(turnId: string): boolean {
|
||||
for (const pending of this.permissions.values()) {
|
||||
if (pending.turnId === turnId) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private syncBackgroundWorkFromInProgressTools(): void {
|
||||
const next = new Set<string>();
|
||||
for (const [id, { snapshot, settlement }] of this.toolCalls) {
|
||||
if (!settlement && snapshot.status === "in_progress") next.add(id);
|
||||
}
|
||||
if (
|
||||
next.size === this.backgroundToolCalls.size &&
|
||||
[...next].every((id) => this.backgroundToolCalls.has(id))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.backgroundToolCalls.clear();
|
||||
for (const id of next) this.backgroundToolCalls.add(id);
|
||||
this.publishBackgroundWork();
|
||||
}
|
||||
|
||||
private clearBackgroundWork(emitClear = true): void {
|
||||
const hadAny = this.backgroundToolCalls.size > 0 || this.publishedBackgroundWork;
|
||||
this.backgroundToolCalls.clear();
|
||||
if (!hadAny) return;
|
||||
this.publishedBackgroundWork = false;
|
||||
if (!emitClear || this.closing) return;
|
||||
this.emit({
|
||||
type: "session.background_work",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
items: [],
|
||||
});
|
||||
}
|
||||
|
||||
private publishBackgroundWork(): void {
|
||||
const items: ProviderBackgroundWorkItem[] = [];
|
||||
for (const id of this.backgroundToolCalls) {
|
||||
const snapshot = this.toolCalls.get(id)?.snapshot;
|
||||
if (snapshot && snapshot.status === "in_progress") {
|
||||
items.push(toBackgroundWorkItem(snapshot));
|
||||
}
|
||||
}
|
||||
if (items.length === 0 && !this.publishedBackgroundWork) return;
|
||||
this.publishedBackgroundWork = items.length > 0;
|
||||
this.emit({
|
||||
type: "session.background_work",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
items,
|
||||
...(items.length > 0 ? { canInterruptSession: true } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1368,25 +1713,39 @@ class AcpRuntime {
|
||||
]);
|
||||
}
|
||||
|
||||
private enqueueNotification(operation: () => void): Promise<void> {
|
||||
private enqueueNotification(operation: () => void | Promise<void>): Promise<void> {
|
||||
const result = this.notificationLane.then(operation);
|
||||
this.notificationLane = result.catch(() => undefined);
|
||||
return result;
|
||||
}
|
||||
|
||||
private handleUnexpectedTransportClose(): void {
|
||||
private failRuntime(message: string): void {
|
||||
if (this.closing || this.processFailed) return;
|
||||
this.processFailed = true;
|
||||
if (this.outOfTurnActivity) this.terminalizeTransientItems("failed");
|
||||
this.settlePendingWork();
|
||||
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 {
|
||||
this.cancelAutonomousSettle();
|
||||
this.autonomousTurn = null;
|
||||
if (this.backgroundToolCalls.size > 0 || this.publishedBackgroundWork) {
|
||||
this.backgroundToolCalls.clear();
|
||||
this.publishedBackgroundWork = false;
|
||||
if (!this.closing) {
|
||||
this.emit({
|
||||
type: "session.background_work",
|
||||
sessionId: this.options.boundarySessionId,
|
||||
items: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const permission of this.permissions.values()) {
|
||||
permission.resolve({ outcome: { outcome: "cancelled" } });
|
||||
}
|
||||
@@ -1421,13 +1780,36 @@ class AcpRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
function routeVendorNotifications(
|
||||
function routeAcpMessages(
|
||||
stream: Stream,
|
||||
receive: (method: string, params: unknown) => void,
|
||||
receiveVendor: (method: string, params: unknown) => void,
|
||||
promptSettlement?: () => Promise<void> | undefined,
|
||||
): Stream {
|
||||
const clientMethods = new Set<string>(Object.values(CLIENT_METHODS));
|
||||
let promptResponse: { id: string | number | null; settled: Promise<void> } | undefined;
|
||||
return {
|
||||
writable: stream.writable,
|
||||
writable: promptSettlement
|
||||
? new WritableStream<AcpStreamMessage>({
|
||||
async write(message) {
|
||||
if (
|
||||
"id" in message &&
|
||||
"method" in message &&
|
||||
message.method === AGENT_METHODS.session_prompt
|
||||
) {
|
||||
const settled = promptSettlement();
|
||||
if (settled) promptResponse = { id: message.id, settled };
|
||||
}
|
||||
const writer = stream.writable.getWriter();
|
||||
try {
|
||||
await writer.write(message);
|
||||
} finally {
|
||||
writer.releaseLock();
|
||||
}
|
||||
},
|
||||
close: () => stream.writable.close(),
|
||||
abort: (reason) => stream.writable.abort(reason),
|
||||
})
|
||||
: stream.writable,
|
||||
readable: stream.readable.pipeThrough(
|
||||
new TransformStream({
|
||||
transform(message, controller) {
|
||||
@@ -1435,11 +1817,24 @@ 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);
|
||||
return;
|
||||
}
|
||||
controller.enqueue(message);
|
||||
if (
|
||||
promptResponse &&
|
||||
"id" in message &&
|
||||
!("method" in message) &&
|
||||
message.id === promptResponse.id
|
||||
) {
|
||||
// The SDK can read the response now. Hold later frames until its turn settles.
|
||||
const { settled } = promptResponse;
|
||||
promptResponse = undefined;
|
||||
return settled;
|
||||
}
|
||||
},
|
||||
}),
|
||||
),
|
||||
@@ -1516,7 +1911,7 @@ function mergeToolCallSnapshot(
|
||||
name: firstText(update.name, current?.name),
|
||||
title: firstText(update.title, current?.title, update.name) ?? "Tool call",
|
||||
kind: firstText(update.kind, current?.kind),
|
||||
status: firstDefined(update.status, current?.status, "pending") ?? "pending",
|
||||
status: update.status ?? current?.status ?? "pending",
|
||||
input: jsonValue(firstDefined(update.rawInput, current?.input, null)),
|
||||
output: jsonValue(firstDefined(update.rawOutput, current?.output, null)),
|
||||
locations: update.locations?.map((location) => location.path) ?? current?.locations ?? [],
|
||||
@@ -1693,6 +2088,34 @@ function configValues(
|
||||
|
||||
type ToolCallTimelineItem = Extract<ProviderTimelineItem, { type: "tool_call" }>;
|
||||
|
||||
function toBackgroundWorkItem(snapshot: AcpToolCallSnapshot): ProviderBackgroundWorkItem {
|
||||
const input = jsonRecord(snapshot.input);
|
||||
let command: string | undefined;
|
||||
if (snapshot.detail?.type === "shell") {
|
||||
command = snapshot.detail.command;
|
||||
} else if (typeof input.CommandLine === "string") {
|
||||
command = input.CommandLine;
|
||||
} else if (typeof input.command === "string") {
|
||||
command = input.command;
|
||||
}
|
||||
const kind =
|
||||
snapshot.detail?.type === "shell" ||
|
||||
snapshot.kind === "execute" ||
|
||||
snapshot.name === "run_command"
|
||||
? "shell"
|
||||
: "other";
|
||||
const summary =
|
||||
typeof input.toolSummary === "string" && input.toolSummary.trim().length > 0
|
||||
? input.toolSummary.trim()
|
||||
: null;
|
||||
return {
|
||||
id: snapshot.id,
|
||||
kind,
|
||||
description: summary ?? snapshot.title ?? snapshot.name ?? null,
|
||||
...(command ? { command } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function toolTimelineItem(snapshot: AcpToolCallSnapshot): ToolCallTimelineItem {
|
||||
const input = jsonRecord(snapshot.input);
|
||||
const isEdit = snapshot.kind === "edit" || snapshot.name?.toLowerCase().includes("edit") === true;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -53,6 +53,11 @@ export interface AcpOptions {
|
||||
initialCommandsTimeoutMs?: number;
|
||||
/** Allow delayed session/load updates before publishing the session as ready. */
|
||||
loadReplayQuietPeriodMs?: number;
|
||||
/**
|
||||
* Support ACP v1 agents whose background tools stay `in_progress` across `end_turn` and
|
||||
* later stream follow-up `session/update` notifications outside `session/prompt`.
|
||||
*/
|
||||
outOfTurnActivity?: boolean | { settleDelayMs?: number; quietLimitMs?: number };
|
||||
/** An unattended mode that approves ACP allow-once requests in the specified native mode. */
|
||||
autoAcceptMode?: {
|
||||
mode: Omit<ProviderMode, "isUnattended">;
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ProviderInputSchema, type ProviderInput } from "./provider.js";
|
||||
import { ProviderEventSchema, ProviderInputSchema, type ProviderInput } from "./provider.js";
|
||||
|
||||
it("advertises session interruption for background work without granting an item Stop", () => {
|
||||
const item = { id: "tool", kind: "shell", description: "Build" };
|
||||
const inventory = {
|
||||
type: "session.background_work",
|
||||
sessionId: "session-1",
|
||||
canInterruptSession: true,
|
||||
};
|
||||
expect(ProviderEventSchema.parse({ ...inventory, items: [{ ...item, canStop: true }] })).toEqual({
|
||||
...inventory,
|
||||
items: [item],
|
||||
});
|
||||
});
|
||||
|
||||
type ReviewMode = "uncommitted" | "base" | "all";
|
||||
type Delivery = "auto" | "steer";
|
||||
|
||||
@@ -504,6 +504,14 @@ export interface ProviderNotice {
|
||||
dismissed?: boolean;
|
||||
}
|
||||
|
||||
export interface ProviderBackgroundWorkItem {
|
||||
id: string;
|
||||
/** Provider-neutral kind (for example "shell", "monitor", "heartbeat", or "other"). */
|
||||
kind: string;
|
||||
description: string | null;
|
||||
command?: string;
|
||||
}
|
||||
|
||||
export interface ProviderPermissionAction {
|
||||
id: string;
|
||||
label: string;
|
||||
@@ -722,6 +730,8 @@ export type ProviderEvent =
|
||||
sessionId: string;
|
||||
turnId: string;
|
||||
state: "started" | "completed" | "failed" | "canceled";
|
||||
/** On an autonomous start, signals that a new prompt can take over without interrupting. */
|
||||
acceptsFollowUp?: boolean;
|
||||
error?: ProviderError;
|
||||
}
|
||||
| { type: "session.usage"; sessionId: string; turnId?: string; usage: ProviderUsage }
|
||||
@@ -730,7 +740,22 @@ export type ProviderEvent =
|
||||
| { type: "session.permission"; sessionId: string; request: ProviderPermissionRequest }
|
||||
| { type: "session.permission_resolved"; sessionId: string; permissionId: string }
|
||||
| { type: "session.notice"; sessionId: string; notice: ProviderNotice }
|
||||
| { type: "timeline.item"; sessionId: string; item: ProviderTimelineItem; timestamp?: string };
|
||||
| {
|
||||
type: "session.background_work";
|
||||
sessionId: string;
|
||||
/** Full replacement of the session's live background work, or null to clear. */
|
||||
items: ProviderBackgroundWorkItem[] | null;
|
||||
/** The session's interrupt operation also stops its background work. */
|
||||
canInterruptSession?: boolean;
|
||||
}
|
||||
| {
|
||||
type: "timeline.item";
|
||||
sessionId: string;
|
||||
item: ProviderTimelineItem;
|
||||
timestamp?: string;
|
||||
/** Original turn of the item when an update arrives in a later turn. */
|
||||
turnId?: string;
|
||||
};
|
||||
|
||||
export function negotiateProviderCapabilities(
|
||||
offered: readonly string[],
|
||||
@@ -1545,6 +1570,7 @@ export const ProviderEventSchema: z.ZodType<ProviderEvent> = z.discriminatedUnio
|
||||
sessionId: idSchema,
|
||||
turnId: idSchema,
|
||||
state: z.enum(["started", "completed", "failed", "canceled"]),
|
||||
acceptsFollowUp: z.boolean().optional(),
|
||||
error: providerErrorSchema.optional(),
|
||||
})
|
||||
.strip(),
|
||||
@@ -1583,12 +1609,32 @@ export const ProviderEventSchema: z.ZodType<ProviderEvent> = z.discriminatedUnio
|
||||
z
|
||||
.object({ type: z.literal("session.notice"), sessionId: idSchema, notice: noticeSchema })
|
||||
.strip(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("session.background_work"),
|
||||
sessionId: idSchema,
|
||||
items: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
id: idSchema,
|
||||
kind: z.string().min(1),
|
||||
description: z.string().nullable(),
|
||||
command: z.string().optional(),
|
||||
})
|
||||
.strip(),
|
||||
)
|
||||
.nullable(),
|
||||
canInterruptSession: z.boolean().optional(),
|
||||
})
|
||||
.strip(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("timeline.item"),
|
||||
sessionId: idSchema,
|
||||
item: timelineItemSchema,
|
||||
timestamp: z.string().optional(),
|
||||
turnId: idSchema.optional(),
|
||||
})
|
||||
.strip(),
|
||||
]);
|
||||
|
||||
@@ -907,6 +907,8 @@ export const AgentBackgroundWorkSummarySchema = z.object({
|
||||
count: z.number().int().nonnegative(),
|
||||
/** Defaults to the total count when omitted. */
|
||||
runningCount: z.number().int().nonnegative().optional(),
|
||||
/** The session interrupt command also stops its current background work. */
|
||||
canInterruptSession: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type AgentBackgroundWorkSummary = z.infer<typeof AgentBackgroundWorkSummarySchema>;
|
||||
|
||||
@@ -3180,7 +3180,9 @@ export class AgentManager {
|
||||
}): Promise<string | null> {
|
||||
const { agent, agentId, pendingRun, prompt, options, promptStart } = params;
|
||||
if (promptStart?.admit?.() === false) {
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
if (!(await this.releaseUnstartedRunWithProviderEvents(agentId, pendingRun))) {
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
@@ -3217,8 +3219,10 @@ export class AgentManager {
|
||||
stale: true,
|
||||
});
|
||||
agent.pendingReplacement = false;
|
||||
if (!agent.activeForegroundTurnId) agent.lifecycle = "idle";
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
if (!(await this.releaseUnstartedRunWithProviderEvents(agentId, pendingRun))) {
|
||||
if (!agent.activeForegroundTurnId) agent.lifecycle = "idle";
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
agent.pendingReplacement = false;
|
||||
@@ -3231,12 +3235,17 @@ export class AgentManager {
|
||||
messageId: options.clientMessageId,
|
||||
});
|
||||
}
|
||||
await this.handleStreamEvent(agent, {
|
||||
type: "turn_failed",
|
||||
provider: agent.provider,
|
||||
error: errorMsg,
|
||||
});
|
||||
this.finalizeForegroundTurn(agent);
|
||||
if (await this.releaseUnstartedRunWithProviderEvents(agentId, pendingRun)) {
|
||||
await this.appendSystemErrorTimelineMessage(agent, agent.provider, errorMsg);
|
||||
this.emitState(agent);
|
||||
} else {
|
||||
await this.handleStreamEvent(agent, {
|
||||
type: "turn_failed",
|
||||
provider: agent.provider,
|
||||
error: errorMsg,
|
||||
});
|
||||
this.finalizeForegroundTurn(agent);
|
||||
}
|
||||
} finally {
|
||||
// A steer waiting on this start is released only once the run is cleared.
|
||||
this.runs.settleForegroundRun(agentId, pendingRun.token);
|
||||
@@ -3245,6 +3254,19 @@ export class AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
private async releaseUnstartedRunWithProviderEvents(
|
||||
agentId: string,
|
||||
pending: PendingForegroundRun,
|
||||
): Promise<boolean> {
|
||||
const restored = this.runs.restoreAutonomousRun(agentId, pending);
|
||||
if (!restored && pending.stagedEvents.length === 0) return false;
|
||||
// The provider refused this start. Its staged events belong to the existing session.
|
||||
if (!restored) this.runs.settleForegroundRun(agentId, pending.token);
|
||||
for (const event of pending.stagedEvents.splice(0)) this.enqueueSessionEvent(agentId, event);
|
||||
await this.drainSessionEvents(agentId);
|
||||
return restored || this.runs.hasRun(agentId);
|
||||
}
|
||||
|
||||
private async ensureInteractiveSession(agentId: string): Promise<ActiveManagedAgent> {
|
||||
const agent = this.requireSessionAgent(agentId);
|
||||
if (this.historySessions.has(agent.session)) {
|
||||
@@ -3317,7 +3339,8 @@ export class AgentManager {
|
||||
},
|
||||
"agent.manager.stream.request",
|
||||
);
|
||||
if (existingAgent.activeForegroundTurnId || this.runs.hasRun(agentId)) {
|
||||
const acceptsFollowUp = this.runs.acceptsFollowUp(agentId);
|
||||
if (existingAgent.activeForegroundTurnId || (this.runs.hasRun(agentId) && !acceptsFollowUp)) {
|
||||
this.logger.trace(
|
||||
{
|
||||
agentId,
|
||||
@@ -3514,9 +3537,10 @@ export class AgentManager {
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
admission?: { allowAutonomousHandoff?: boolean },
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
this.requireSessionAgent(agentId);
|
||||
return this.replaceRunInForegroundLane(agentId, prompt, options, promptStart);
|
||||
return this.replaceRunInForegroundLane(agentId, prompt, options, promptStart, admission);
|
||||
}
|
||||
|
||||
async steerAgentRun(
|
||||
@@ -3674,9 +3698,9 @@ export class AgentManager {
|
||||
promptStart?: ForegroundPromptStart,
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId);
|
||||
return this.replaceRunInForegroundLane(agent.id, prompt, options, promptStart, (live) =>
|
||||
this.assertSteerAdmissionOwnsTurn(live, expectedTurnId),
|
||||
);
|
||||
return this.replaceRunInForegroundLane(agent.id, prompt, options, promptStart, {
|
||||
assert: (live) => this.assertSteerAdmissionOwnsTurn(live, expectedTurnId),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -3688,12 +3712,12 @@ export class AgentManager {
|
||||
prompt: AgentPromptInput,
|
||||
options: AgentRunOptions | undefined,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
assertAdmission?: (agent: ActiveManagedAgent) => void,
|
||||
admission?: { assert?: (agent: ActiveManagedAgent) => void; allowAutonomousHandoff?: boolean },
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
// Replacements queue in arrival order; each one holds the foreground lane only while
|
||||
// it cancels and reserves, so Stop is never stuck behind a replacement that is waiting.
|
||||
return this.runQueuedMutation(this.replacementMutationTails, agentId, () =>
|
||||
this.replaceRunWhenAdmitted(agentId, prompt, options, promptStart, assertAdmission),
|
||||
this.replaceRunWhenAdmitted(agentId, prompt, options, promptStart, admission),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3702,7 +3726,7 @@ export class AgentManager {
|
||||
prompt: AgentPromptInput,
|
||||
options: AgentRunOptions | undefined,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
assertAdmission?: (agent: ActiveManagedAgent) => void,
|
||||
delivery?: { assert?: (agent: ActiveManagedAgent) => void; allowAutonomousHandoff?: boolean },
|
||||
): Promise<AsyncGenerator<AgentStreamEvent>> {
|
||||
let stalledStart: PendingForegroundRun | null = null;
|
||||
for (;;) {
|
||||
@@ -3716,8 +3740,9 @@ export class AgentManager {
|
||||
if (starting && starting.start.status !== "started" && starting !== stalledStart) {
|
||||
return { status: "starting" as const, run: starting };
|
||||
}
|
||||
assertAdmission?.(agent);
|
||||
if (!this.hasInFlightRun(agent.id)) {
|
||||
delivery?.assert?.(agent);
|
||||
const canHandOff = delivery?.allowAutonomousHandoff && this.runs.acceptsFollowUp(agent.id);
|
||||
if (!this.hasInFlightRun(agent.id) || canHandOff) {
|
||||
return {
|
||||
status: "reserved" as const,
|
||||
iterator: this.streamAgent(agent.id, prompt, options, promptStart),
|
||||
@@ -3924,8 +3949,21 @@ export class AgentManager {
|
||||
}
|
||||
}
|
||||
|
||||
async cancelAgentRun(agentId: string): Promise<AgentRunCancellationResult> {
|
||||
return this.runForegroundMutation(agentId, () => {
|
||||
async cancelAgentRun(
|
||||
agentId: string,
|
||||
options?: { includeBackgroundWork?: boolean },
|
||||
): Promise<AgentRunCancellationResult> {
|
||||
return this.runForegroundMutation(agentId, async () => {
|
||||
if (options?.includeBackgroundWork) {
|
||||
await this.drainSessionEvents(agentId);
|
||||
if (!this.hasInFlightRun(agentId)) {
|
||||
if (!this.backgroundWork.canInterruptSession(agentId)) return { status: "not_running" };
|
||||
const { session } = this.requireSessionAgent(agentId);
|
||||
const acknowledged = await this.interruptSession(session, agentId);
|
||||
await this.drainSessionEvents(agentId);
|
||||
return { status: acknowledged ? "settled" : "refused" };
|
||||
}
|
||||
}
|
||||
this.requireSessionAgent(agentId).pendingReplacement = false;
|
||||
return this.cancelAgentRunNow(agentId);
|
||||
});
|
||||
@@ -4825,7 +4863,7 @@ export class AgentManager {
|
||||
const items =
|
||||
event.items === null
|
||||
? this.backgroundWork.clear(agent.id)
|
||||
: this.backgroundWork.apply(agent.id, event.items);
|
||||
: this.backgroundWork.apply(agent.id, event.items, undefined, event.canInterruptSession);
|
||||
this.publishBackgroundWork(agent.id, items);
|
||||
return;
|
||||
}
|
||||
@@ -5391,7 +5429,13 @@ export class AgentManager {
|
||||
});
|
||||
return undefined;
|
||||
case "turn_started":
|
||||
this.onStreamTurnStarted({ agent, eventTurnId, isForegroundEvent, flags });
|
||||
this.onStreamTurnStarted({
|
||||
agent,
|
||||
eventTurnId,
|
||||
isForegroundEvent,
|
||||
flags,
|
||||
acceptsFollowUp: event.acceptsFollowUp,
|
||||
});
|
||||
return undefined;
|
||||
case "permission_requested":
|
||||
this.onStreamPermissionRequested(agent, event);
|
||||
@@ -5570,6 +5614,7 @@ export class AgentManager {
|
||||
eventTurnId: string | undefined;
|
||||
isForegroundEvent: boolean;
|
||||
flags: StreamEventFlags;
|
||||
acceptsFollowUp?: boolean;
|
||||
}): void {
|
||||
const { agent, eventTurnId, isForegroundEvent, flags } = params;
|
||||
this.logger.trace(
|
||||
@@ -5593,7 +5638,7 @@ export class AgentManager {
|
||||
flags.shouldNotifyWaiters = false;
|
||||
return;
|
||||
}
|
||||
this.runs.trackAutonomousRun(agent.id, eventTurnId ?? null);
|
||||
this.runs.trackAutonomousRun(agent.id, eventTurnId ?? null, params.acceptsFollowUp);
|
||||
if (eventTurnId) {
|
||||
this.openActiveTurn(agent, eventTurnId, new Date());
|
||||
}
|
||||
|
||||
@@ -92,7 +92,9 @@ async function startOrReplaceRun(
|
||||
}> {
|
||||
const replaced = Boolean(options?.replaceRunning && agentManager.hasInFlightRun(agentId));
|
||||
const iterator = replaced
|
||||
? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions, promptStart)
|
||||
? await agentManager.replaceAgentRun(agentId, prompt, options?.runOptions, promptStart, {
|
||||
allowAutonomousHandoff: options?.activeTurnBehavior !== "interrupt",
|
||||
})
|
||||
: agentManager.streamAgent(agentId, prompt, options?.runOptions, promptStart);
|
||||
return { iterator, replaced };
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ export interface PendingForegroundRun {
|
||||
token: string;
|
||||
kind: "foreground";
|
||||
stagedEvents: AgentStreamEvent[];
|
||||
handoffFrom?: AutonomousAgentRun;
|
||||
start: ForegroundRunStart;
|
||||
turnStartedPromise: Promise<void>;
|
||||
resolveTurnStarted: () => void;
|
||||
@@ -31,6 +32,7 @@ export interface AutonomousAgentRun {
|
||||
token: string;
|
||||
kind: "autonomous";
|
||||
turnId: string | null;
|
||||
acceptsFollowUp: boolean;
|
||||
started: true;
|
||||
settled: boolean;
|
||||
settledPromise: Promise<void>;
|
||||
@@ -49,6 +51,10 @@ export class AgentRunState {
|
||||
|
||||
createPendingRun(agentId: string): PendingForegroundRun {
|
||||
const pendingRun = createPendingForegroundRun();
|
||||
const current = this.runs.get(agentId);
|
||||
if (current?.kind === "autonomous" && current.acceptsFollowUp) {
|
||||
pendingRun.handoffFrom = current;
|
||||
}
|
||||
this.runs.set(agentId, pendingRun);
|
||||
return pendingRun;
|
||||
}
|
||||
@@ -64,6 +70,7 @@ export class AgentRunState {
|
||||
): void {
|
||||
run.start = start;
|
||||
if (start.status === "started") {
|
||||
this.settleHandoff(run);
|
||||
run.resolveTurnStarted();
|
||||
}
|
||||
}
|
||||
@@ -99,7 +106,16 @@ export class AgentRunState {
|
||||
return run.start.status === "started" ? run.start.turnId : null;
|
||||
}
|
||||
|
||||
trackAutonomousRun(agentId: string, turnId: string | null): TrackedAgentRun {
|
||||
acceptsFollowUp(agentId: string): boolean {
|
||||
const run = this.runs.get(agentId);
|
||||
return run?.kind === "autonomous" && run.acceptsFollowUp;
|
||||
}
|
||||
|
||||
trackAutonomousRun(
|
||||
agentId: string,
|
||||
turnId: string | null,
|
||||
acceptsFollowUp = false,
|
||||
): TrackedAgentRun {
|
||||
const current = this.runs.get(agentId);
|
||||
if (current) {
|
||||
return current;
|
||||
@@ -109,6 +125,7 @@ export class AgentRunState {
|
||||
...createTrackedRunState(),
|
||||
kind: "autonomous",
|
||||
turnId,
|
||||
acceptsFollowUp,
|
||||
started: true,
|
||||
};
|
||||
this.runs.set(agentId, run);
|
||||
@@ -120,6 +137,14 @@ export class AgentRunState {
|
||||
if (!run) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
run.kind === "foreground" &&
|
||||
run.handoffFrom &&
|
||||
(turnId === undefined || turnId === run.handoffFrom.turnId)
|
||||
) {
|
||||
this.settleHandoff(run);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
run.kind === "foreground" &&
|
||||
(run.start.status !== "started" || run.start.turnId !== turnId)
|
||||
@@ -154,6 +179,14 @@ export class AgentRunState {
|
||||
}
|
||||
}
|
||||
|
||||
restoreAutonomousRun(agentId: string, pending: PendingForegroundRun): boolean {
|
||||
if (this.runs.get(agentId) !== pending || !pending.handoffFrom) return false;
|
||||
this.runs.set(agentId, pending.handoffFrom);
|
||||
pending.handoffFrom = undefined;
|
||||
settleTrackedRun(pending);
|
||||
return true;
|
||||
}
|
||||
|
||||
createTurnStream(turnId: string): ForegroundTurnStream {
|
||||
return new ForegroundTurnStream(turnId);
|
||||
}
|
||||
@@ -239,8 +272,15 @@ export class AgentRunState {
|
||||
|
||||
private clearRun(agentId: string, run: TrackedAgentRun): void {
|
||||
this.runs.delete(agentId);
|
||||
if (run.kind === "foreground") this.settleHandoff(run);
|
||||
settleTrackedRun(run);
|
||||
}
|
||||
|
||||
private settleHandoff(run: PendingForegroundRun): void {
|
||||
if (!run.handoffFrom) return;
|
||||
settleTrackedRun(run.handoffFrom);
|
||||
run.handoffFrom = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export class ForegroundTurnStream {
|
||||
|
||||
@@ -420,7 +420,7 @@ export type AgentTimelineItem =
|
||||
|
||||
export type AgentStreamEvent =
|
||||
| { type: "thread_started"; sessionId: string; provider: AgentProvider }
|
||||
| { type: "turn_started"; provider: AgentProvider; turnId?: string }
|
||||
| { type: "turn_started"; provider: AgentProvider; turnId?: string; acceptsFollowUp?: boolean }
|
||||
| { type: "turn_completed"; provider: AgentProvider; usage?: AgentUsage; turnId?: string }
|
||||
| { type: "usage_updated"; provider: AgentProvider; usage: AgentUsage; turnId?: string }
|
||||
| {
|
||||
@@ -488,6 +488,7 @@ export type AgentStreamEvent =
|
||||
type: "background_work";
|
||||
provider: AgentProvider;
|
||||
items: import("./background-work/index.js").AgentBackgroundWorkInput[] | null;
|
||||
canInterruptSession?: boolean;
|
||||
};
|
||||
|
||||
export function getAgentStreamEventTurnId(event: AgentStreamEvent): string | undefined {
|
||||
|
||||
@@ -61,16 +61,20 @@ function encodeProviderItemId(id: string): string {
|
||||
* Daemon services publish individual items that outlive provider sessions.
|
||||
*/
|
||||
export class AgentBackgroundWorkStore {
|
||||
private readonly providerItems = new Map<string, AgentBackgroundWorkItem[]>();
|
||||
private readonly providerWork = new Map<
|
||||
string,
|
||||
{ items: AgentBackgroundWorkItem[]; canInterruptSession: boolean }
|
||||
>();
|
||||
private readonly daemonItems = new Map<string, Map<string, DaemonBackgroundWork>>();
|
||||
|
||||
apply(
|
||||
agentId: string,
|
||||
inputs: readonly AgentBackgroundWorkInput[],
|
||||
timestamp: string = new Date().toISOString(),
|
||||
canInterruptSession = false,
|
||||
): AgentBackgroundWorkItem[] | null {
|
||||
const previous = this.providerItems.get(agentId);
|
||||
const previousById = new Map(previous?.map((item) => [item.id, item]));
|
||||
const previous = this.providerWork.get(agentId);
|
||||
const previousById = new Map(previous?.items.map((item) => [item.id, item]));
|
||||
const seen = new Set<string>();
|
||||
const next: AgentBackgroundWorkItem[] = [];
|
||||
for (const input of inputs) {
|
||||
@@ -88,8 +92,9 @@ export class AgentBackgroundWorkStore {
|
||||
startedAt: previousById.get(id)?.startedAt ?? timestamp,
|
||||
});
|
||||
}
|
||||
if (previous && sameItems(previous, next)) return null;
|
||||
this.providerItems.set(agentId, next);
|
||||
if (previous?.canInterruptSession === canInterruptSession && sameItems(previous.items, next))
|
||||
return null;
|
||||
this.providerWork.set(agentId, { items: next, canInterruptSession });
|
||||
return this.list(agentId);
|
||||
}
|
||||
|
||||
@@ -130,7 +135,7 @@ export class AgentBackgroundWorkStore {
|
||||
}
|
||||
|
||||
authorizeProviderStop(agentId: string, itemId: string, stopToken: string): string {
|
||||
const item = this.providerItems.get(agentId)?.find(({ id }) => id === itemId);
|
||||
const item = this.providerWork.get(agentId)?.items.find(({ id }) => id === itemId);
|
||||
if (!item?.canStop || item.stopToken !== stopToken) {
|
||||
throw new Error("Background work is no longer available to stop");
|
||||
}
|
||||
@@ -138,15 +143,20 @@ export class AgentBackgroundWorkStore {
|
||||
}
|
||||
|
||||
list(agentId: string): AgentBackgroundWorkItem[] {
|
||||
const items = [...(this.providerItems.get(agentId) ?? [])];
|
||||
const items = [...(this.providerWork.get(agentId)?.items ?? [])];
|
||||
for (const { item } of this.daemonItems.get(agentId)?.values() ?? []) {
|
||||
items.push(item);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
canInterruptSession(agentId: string): boolean {
|
||||
const work = this.providerWork.get(agentId);
|
||||
return work?.canInterruptSession === true && work.items.length > 0;
|
||||
}
|
||||
|
||||
summary(agentId: string): AgentBackgroundWorkSummary | undefined {
|
||||
const items = this.providerItems.get(agentId);
|
||||
const items = this.providerWork.get(agentId)?.items;
|
||||
const daemonItems = this.daemonItems.get(agentId);
|
||||
if (!items && !daemonItems) return undefined;
|
||||
|
||||
@@ -155,11 +165,15 @@ export class AgentBackgroundWorkStore {
|
||||
for (const work of daemonItems?.values() ?? []) {
|
||||
if (work.countsAsRunning) runningCount++;
|
||||
}
|
||||
return runningCount === count ? { count } : { count, runningCount };
|
||||
return {
|
||||
count,
|
||||
...(runningCount === count ? {} : { runningCount }),
|
||||
...(this.canInterruptSession(agentId) ? { canInterruptSession: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
clear(agentId: string): AgentBackgroundWorkItem[] | null {
|
||||
if (!this.providerItems.delete(agentId)) return null;
|
||||
if (!this.providerWork.delete(agentId)) return null;
|
||||
return this.list(agentId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,10 @@ export type LifecycleAgentSnapshot = Pick<ManagedAgent, "id" | "cwd" | "lifecycl
|
||||
export interface LifecycleAgentManager {
|
||||
getAgent(agentId: string): LifecycleAgentSnapshot | null;
|
||||
hasInFlightRun(agentId: string): boolean;
|
||||
cancelAgentRun(agentId: string): Promise<AgentRunCancellationResult>;
|
||||
cancelAgentRun(
|
||||
agentId: string,
|
||||
options?: { includeBackgroundWork?: boolean },
|
||||
): Promise<AgentRunCancellationResult>;
|
||||
clearAgentAttention(agentId: string): Promise<void>;
|
||||
archiveAgent(agentId: string): Promise<{ archivedAt: string }>;
|
||||
archiveSnapshot(agentId: string, archivedAt: string): Promise<StoredAgentRecord>;
|
||||
@@ -58,6 +61,7 @@ interface RequestedAgentRunCancellation extends CancelAgentRunResult {
|
||||
async function requestAgentRunCancellation(
|
||||
dependencies: Pick<AgentLifecycleCommandDependencies, "agentManager" | "logger">,
|
||||
agentId: string,
|
||||
includeBackgroundWork = false,
|
||||
): Promise<RequestedAgentRunCancellation> {
|
||||
const { agentManager, logger } = dependencies;
|
||||
const agent = agentManager.getAgent(agentId);
|
||||
@@ -67,7 +71,7 @@ async function requestAgentRunCancellation(
|
||||
}
|
||||
|
||||
const hasInFlightRun = agentManager.hasInFlightRun(agentId);
|
||||
if (!hasInFlightRun) {
|
||||
if (!hasInFlightRun && !includeBackgroundWork) {
|
||||
logger.trace(
|
||||
{ agentId, lifecycle: agent.lifecycle, hasInFlightRun },
|
||||
"cancelAgentRunCommand: skipping because agent is not running",
|
||||
@@ -80,7 +84,9 @@ async function requestAgentRunCancellation(
|
||||
"cancelAgentRunCommand: interrupting",
|
||||
);
|
||||
const startedAt = Date.now();
|
||||
const cancellation = await agentManager.cancelAgentRun(agentId);
|
||||
const cancellation = includeBackgroundWork
|
||||
? await agentManager.cancelAgentRun(agentId, { includeBackgroundWork: true })
|
||||
: await agentManager.cancelAgentRun(agentId);
|
||||
logger.debug(
|
||||
{ agentId, cancellation: cancellation.status, durationMs: Date.now() - startedAt },
|
||||
"cancelAgentRunCommand: cancelAgentRun completed",
|
||||
@@ -96,8 +102,13 @@ async function requestAgentRunCancellation(
|
||||
export async function cancelAgentRunCommand(
|
||||
dependencies: Pick<AgentLifecycleCommandDependencies, "agentManager" | "logger">,
|
||||
agentId: string,
|
||||
options?: { includeBackgroundWork?: boolean },
|
||||
): Promise<CancelAgentRunResult> {
|
||||
const result = await requestAgentRunCancellation(dependencies, agentId);
|
||||
const result = await requestAgentRunCancellation(
|
||||
dependencies,
|
||||
agentId,
|
||||
options?.includeBackgroundWork,
|
||||
);
|
||||
if (result.cancellation.status === "refused") {
|
||||
dependencies.logger.warn(
|
||||
{ agentId },
|
||||
|
||||
@@ -13,10 +13,14 @@ import type {
|
||||
ProviderInput,
|
||||
ProviderRegistration,
|
||||
} from "@getpaseo/plugin/server/provider";
|
||||
import { runAcpProvider } from "@getpaseo/plugin/server/acp";
|
||||
import { AgentSideConnection, PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
|
||||
import { sendPromptToAgent } from "./agent-prompt.js";
|
||||
import { cancelAgentRunCommand } from "./lifecycle-command.js";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { createTestLogger } from "../../test-utils/test-logger.js";
|
||||
import type { AgentClient, AgentStreamEvent } from "./agent-sdk-types.js";
|
||||
import type { AgentClient, AgentPromptInput, AgentStreamEvent } from "./agent-sdk-types.js";
|
||||
import { toStoredAgentRecord } from "./agent-projections.js";
|
||||
import { AgentManager } from "./agent-manager.js";
|
||||
import { buildProviderRegistry } from "./provider-registry.js";
|
||||
@@ -2814,3 +2818,435 @@ test("resumes a goose session saved by the generic ACP provider", async () => {
|
||||
await plugins.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps Antigravity wakeup replies separate after reloading the agent", async () => {
|
||||
const home = await mkdtemp(join(tmpdir(), "plugin-wakeup-reload-"));
|
||||
const logger = createTestLogger();
|
||||
const storage = new AgentStorage(join(home, "agents"), logger);
|
||||
const sessionId = "native-session";
|
||||
let wake!: (text: string) => Promise<void>;
|
||||
const registration = runAcpProvider({
|
||||
id: "test-antigravity",
|
||||
label: "Test Antigravity",
|
||||
acpOptions: { outOfTurnActivity: { settleDelayMs: 10 } },
|
||||
connector: () => {
|
||||
const clientToAgent = new TransformStream();
|
||||
const agentToClient = new TransformStream();
|
||||
const bindWakeup = () => {
|
||||
wake = async (text) => {
|
||||
await acp.sessionUpdate({
|
||||
sessionId,
|
||||
update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },
|
||||
});
|
||||
await acp.sessionUpdate({
|
||||
sessionId,
|
||||
update: { sessionUpdate: "usage_update", used: 10, size: 100 },
|
||||
});
|
||||
};
|
||||
};
|
||||
const acp = new AgentSideConnection(
|
||||
() => ({
|
||||
initialize: async () => ({
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
agentCapabilities: { loadSession: true },
|
||||
}),
|
||||
newSession: async () => {
|
||||
bindWakeup();
|
||||
return { sessionId };
|
||||
},
|
||||
loadSession: async () => {
|
||||
bindWakeup();
|
||||
return {};
|
||||
},
|
||||
unstable_closeSession: async () => ({}),
|
||||
prompt: async () => ({ stopReason: "end_turn" }),
|
||||
cancel: async () => {},
|
||||
}),
|
||||
{ writable: agentToClient.writable, readable: clientToAgent.readable },
|
||||
);
|
||||
return { writable: clientToAgent.writable, readable: agentToClient.readable };
|
||||
},
|
||||
});
|
||||
const registry = new PluginAgentClientRegistry(logger);
|
||||
registry.replace([registration]);
|
||||
const manager = new AgentManager({ clients: registry.clients(), registry: storage, logger });
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: registration.id, cwd: home }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const replies = () =>
|
||||
manager
|
||||
.getTimeline(agent.id)
|
||||
.flatMap((item) => (item.type === "assistant_message" ? [item.text] : []));
|
||||
|
||||
await wake("First wakeup.");
|
||||
await expect.poll(replies).toEqual(["First wakeup."]);
|
||||
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle).toBe("idle");
|
||||
await manager.reloadAgentSession(agent.id);
|
||||
await wake("Second wakeup.");
|
||||
await expect.poll(replies).toEqual(["First wakeup.", "Second wakeup."]);
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await registry.shutdown();
|
||||
await storage.flush();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["steer", "stop", "interrupt", "refused follow-up"] as const)(
|
||||
"Antigravity ACP background work through the daemon's %s command",
|
||||
async (action) => {
|
||||
const home = await mkdtemp(join(tmpdir(), "plugin-bg-work-"));
|
||||
const logger = createTestLogger();
|
||||
const storage = new AgentStorage(join(home, "agents"), logger);
|
||||
const calls: string[] = [];
|
||||
let wake!: () => Promise<void>;
|
||||
const registration = runAcpProvider({
|
||||
id: "test-antigravity",
|
||||
label: "Test Antigravity",
|
||||
acpOptions: { outOfTurnActivity: true },
|
||||
connector: () => {
|
||||
const clientToAgent = new TransformStream();
|
||||
const agentToClient = new TransformStream();
|
||||
const acp = new AgentSideConnection(
|
||||
() => ({
|
||||
initialize: async () => ({ protocolVersion: PROTOCOL_VERSION, agentCapabilities: {} }),
|
||||
newSession: async () => ({ sessionId: "native-session" }),
|
||||
prompt: async ({ sessionId, prompt }) => {
|
||||
const text = prompt[0]?.type === "text" ? prompt[0].text : "";
|
||||
calls.push(text);
|
||||
if (text === "Start two commands") {
|
||||
for (const toolCallId of ["cmd-1", "cmd-2"]) {
|
||||
await acp.sessionUpdate({
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: toolCallId,
|
||||
kind: "execute",
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
}
|
||||
wake = async () => {
|
||||
const finished = action === "refused follow-up" ? ["cmd-1", "cmd-2"] : ["cmd-1"];
|
||||
for (const toolCallId of finished) {
|
||||
await acp.sessionUpdate({
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
return { stopReason: "end_turn" };
|
||||
},
|
||||
cancel: async () => {
|
||||
calls.push("session/cancel");
|
||||
},
|
||||
}),
|
||||
{ writable: agentToClient.writable, readable: clientToAgent.readable },
|
||||
);
|
||||
return { writable: clientToAgent.writable, readable: agentToClient.readable };
|
||||
},
|
||||
});
|
||||
const registry = new PluginAgentClientRegistry(logger);
|
||||
registry.replace([registration]);
|
||||
const manager = new AgentManager({ clients: registry.clients(), registry: storage, logger });
|
||||
try {
|
||||
const agent = await manager.createAgent({ provider: registration.id, cwd: home }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const dispatch = (prompt: AgentPromptInput, activeTurnBehavior?: "steer" | "interrupt") =>
|
||||
sendPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
logger,
|
||||
prompt,
|
||||
activeTurnBehavior,
|
||||
});
|
||||
const send = async (prompt: string, activeTurnBehavior?: "steer" | "interrupt") => {
|
||||
const result = await dispatch(prompt, activeTurnBehavior);
|
||||
if (result.disposition !== "turn_started")
|
||||
throw new Error(`Unexpected dispatch: ${result.disposition}`);
|
||||
await result.started;
|
||||
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle).toBe("idle");
|
||||
};
|
||||
await send("Start two commands");
|
||||
const toolStatuses = (callId: string) =>
|
||||
manager
|
||||
.getTimeline(agent.id)
|
||||
.flatMap((item) =>
|
||||
item.type === "tool_call" && item.callId === callId ? [item.status] : [],
|
||||
);
|
||||
expect(manager.listAgentBackgroundWork(agent.id)).toMatchObject([
|
||||
{ id: "cmd-1", kind: "shell" },
|
||||
{ id: "cmd-2", kind: "shell" },
|
||||
]);
|
||||
|
||||
if (action !== "stop") {
|
||||
await wake();
|
||||
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
}
|
||||
if (action === "steer") {
|
||||
await send("Follow up", "steer");
|
||||
expect(calls).toEqual(["Start two commands", "Follow up"]);
|
||||
expect(manager.listAgentBackgroundWork(agent.id)).toEqual([
|
||||
{ id: "cmd-2", kind: "shell", description: "cmd-2", startedAt: expect.any(String) },
|
||||
]);
|
||||
expect(toolStatuses("cmd-1")).toEqual(["completed"]);
|
||||
} else if (action === "interrupt") {
|
||||
await send("Follow up", "interrupt");
|
||||
expect(calls).toEqual(["Start two commands", "session/cancel", "Follow up"]);
|
||||
expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]);
|
||||
} else if (action === "refused follow-up") {
|
||||
await expect.poll(() => manager.listAgentBackgroundWork(agent.id)).toEqual([]);
|
||||
const result = await dispatch(
|
||||
[{ type: "image", data: "AA==", mimeType: "image/png" }],
|
||||
"steer",
|
||||
);
|
||||
if (result.disposition !== "turn_started")
|
||||
throw new Error(`Unexpected dispatch: ${result.disposition}`);
|
||||
await expect(result.started).rejects.toThrow(/image/i);
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
const { cancelled } = await cancelAgentRunCommand(
|
||||
{ agentManager: manager, logger },
|
||||
agent.id,
|
||||
);
|
||||
expect(cancelled).toBe(true);
|
||||
await expect.poll(() => calls).toEqual(["Start two commands", "session/cancel"]);
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle");
|
||||
} else {
|
||||
const foregroundOnly = await cancelAgentRunCommand(
|
||||
{ agentManager: manager, logger },
|
||||
agent.id,
|
||||
);
|
||||
expect(foregroundOnly.cancelled).toBe(false);
|
||||
expect(calls).toEqual(["Start two commands"]);
|
||||
|
||||
const { cancelled } = await cancelAgentRunCommand(
|
||||
{ agentManager: manager, logger },
|
||||
agent.id,
|
||||
{ includeBackgroundWork: true },
|
||||
);
|
||||
expect(cancelled).toBe(true);
|
||||
await expect.poll(() => calls).toEqual(["Start two commands", "session/cancel"]);
|
||||
expect(manager.listAgentBackgroundWork(agent.id)).toEqual([]);
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle");
|
||||
expect(toolStatuses("cmd-2")).toEqual(["canceled"]);
|
||||
}
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await registry.shutdown();
|
||||
await storage.flush();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("preserves a wakeup arriving while an idle prompt is refused", async () => {
|
||||
const home = await mkdtemp(join(tmpdir(), "plugin-wakeup-admission-"));
|
||||
const logger = createTestLogger();
|
||||
const storage = new AgentStorage(join(home, "agents"), logger);
|
||||
const harness = createProviderHarness({
|
||||
handleInput: async (input, emit) => {
|
||||
if (input.type !== "session.prompt") return false;
|
||||
const { sessionId, prompt } = input;
|
||||
if (prompt.clientMessageId === "initial") {
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId,
|
||||
clientMessageId: "initial",
|
||||
result: { type: "turn", turnId: "initial-turn" },
|
||||
});
|
||||
emit({ type: "session.turn", sessionId, turnId: "initial-turn", state: "started" });
|
||||
emit({
|
||||
type: "session.background_work",
|
||||
sessionId,
|
||||
items: [{ id: "command", kind: "shell", description: "Background command" }],
|
||||
canInterruptSession: true,
|
||||
});
|
||||
emit({ type: "session.turn", sessionId, turnId: "initial-turn", state: "completed" });
|
||||
} else {
|
||||
emit({
|
||||
type: "session.turn",
|
||||
sessionId,
|
||||
turnId: "wakeup",
|
||||
state: "started",
|
||||
acceptsFollowUp: true,
|
||||
});
|
||||
emit({ type: "session.background_work", sessionId, items: [] });
|
||||
emit({
|
||||
type: "timeline.item",
|
||||
sessionId,
|
||||
item: {
|
||||
type: "assistant_message",
|
||||
id: "wakeup-reply",
|
||||
text: "The background command finished.",
|
||||
},
|
||||
});
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId,
|
||||
clientMessageId: prompt.clientMessageId,
|
||||
result: { type: "failed", error: { message: "Follow-up refused" } },
|
||||
});
|
||||
}
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const registry = new PluginAgentClientRegistry(logger);
|
||||
registry.replace([harness.registration]);
|
||||
const manager = new AgentManager({ clients: registry.clients(), registry: storage, logger });
|
||||
try {
|
||||
const agent = await manager.createAgent(
|
||||
{ provider: harness.registration.id, cwd: home },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
await manager.runAgent(agent.id, "Start command", { clientMessageId: "initial" });
|
||||
expect(manager.getAgent(agent.id)?.lifecycle).toBe("idle");
|
||||
expect(manager.listAgentBackgroundWork(agent.id).map((item) => item.id)).toEqual(["command"]);
|
||||
|
||||
const result = await sendPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
logger,
|
||||
prompt: "Follow up",
|
||||
messageId: "follow-up",
|
||||
});
|
||||
if (result.disposition !== "turn_started")
|
||||
throw new Error(`Unexpected dispatch: ${result.disposition}`);
|
||||
await expect(result.started).rejects.toThrow("Follow-up refused");
|
||||
await expect
|
||||
.poll(() => ({
|
||||
lifecycle: manager.getAgent(agent.id)?.lifecycle,
|
||||
backgroundWork: manager.listAgentBackgroundWork(agent.id),
|
||||
replies: manager
|
||||
.getTimeline(agent.id)
|
||||
.flatMap((item) => (item.type === "assistant_message" ? [item.text] : [])),
|
||||
}))
|
||||
.toMatchObject({
|
||||
lifecycle: "running",
|
||||
backgroundWork: [],
|
||||
replies: expect.arrayContaining(["The background command finished."]),
|
||||
});
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await registry.shutdown();
|
||||
await storage.flush();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ type: "session.runtime_failed", phase: "wakeup" },
|
||||
{ type: "session.closed", phase: "wakeup" },
|
||||
{ type: "session.closed", phase: "foreground" },
|
||||
{ type: "session.closed", phase: "handoff" },
|
||||
{ type: "session.runtime_failed", phase: "handoff" },
|
||||
{ type: "connection.closed", phase: "idle" },
|
||||
] as const)("retires plugin work on $type during $phase", async ({ type, phase }) => {
|
||||
const logger = createTestLogger();
|
||||
const harness = createProviderHarness({
|
||||
async handleInput(input, emit) {
|
||||
if (phase === "wakeup" || input.type !== "session.prompt") return false;
|
||||
emit({
|
||||
type: "session.prompt_result",
|
||||
sessionId: input.sessionId,
|
||||
clientMessageId: input.prompt.clientMessageId,
|
||||
result: { type: "turn", turnId: "foreground" },
|
||||
});
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const registry = new PluginAgentClientRegistry(logger);
|
||||
registry.replace([harness.registration]);
|
||||
const manager = new AgentManager({ clients: registry.clients(), logger });
|
||||
try {
|
||||
const agent = await manager.createAgent(
|
||||
{ provider: harness.registration.id, cwd: tmpdir() },
|
||||
undefined,
|
||||
{ workspaceId: undefined },
|
||||
);
|
||||
const opened = harness.inputs.find((input) => input.type === "session.open");
|
||||
if (!opened) throw new Error("Expected the plugin session to open");
|
||||
manager.setDaemonBackgroundWork({
|
||||
agentId: agent.id,
|
||||
namespace: "heartbeat",
|
||||
id: "watch",
|
||||
kind: "heartbeat",
|
||||
description: "Daemon heartbeat",
|
||||
startedAt: "2026-11-20T00:00:00.000Z",
|
||||
stop: async () => {},
|
||||
});
|
||||
harness.emit({
|
||||
type: "session.background_work",
|
||||
sessionId: opened.sessionId,
|
||||
items: [{ id: "command", kind: "shell", description: "Background command" }],
|
||||
canInterruptSession: true,
|
||||
});
|
||||
await expect
|
||||
.poll(() => manager.getAgentBackgroundWorkSummary(agent.id))
|
||||
.toEqual({
|
||||
count: 2,
|
||||
canInterruptSession: true,
|
||||
});
|
||||
|
||||
if (phase === "wakeup" || phase === "handoff") {
|
||||
harness.emit({
|
||||
type: "session.turn",
|
||||
sessionId: opened.sessionId,
|
||||
turnId: "wakeup",
|
||||
state: "started",
|
||||
acceptsFollowUp: true,
|
||||
});
|
||||
await expect.poll(() => manager.getAgent(agent.id)?.lifecycle).toBe("running");
|
||||
}
|
||||
let run: ReturnType<AgentManager["runAgent"]> | undefined;
|
||||
if (phase === "foreground" || phase === "handoff") {
|
||||
run = manager.runAgent(agent.id, "Start foreground");
|
||||
void run.catch(() => undefined);
|
||||
await expect
|
||||
.poll(() => manager.getAgent(agent.id)?.activeForegroundTurnId)
|
||||
.toBe("foreground");
|
||||
}
|
||||
if (type === "connection.closed") {
|
||||
registry.replace([]);
|
||||
await harness.waitForClose();
|
||||
} else {
|
||||
harness.emit(
|
||||
type === "session.runtime_failed"
|
||||
? { type, sessionId: opened.sessionId, error: { message: "Provider process exited" } }
|
||||
: { type, sessionId: opened.sessionId },
|
||||
);
|
||||
}
|
||||
await expect
|
||||
.poll(() => ({
|
||||
lifecycle: manager.getAgent(agent.id)?.lifecycle,
|
||||
summary: manager.getAgentBackgroundWorkSummary(agent.id),
|
||||
inventory: manager.listAgentBackgroundWork(agent.id).map((item) => item.id),
|
||||
}))
|
||||
.toEqual({
|
||||
lifecycle: type === "session.runtime_failed" ? "error" : "idle",
|
||||
summary: { count: 1 },
|
||||
inventory: ["heartbeat:watch"],
|
||||
});
|
||||
const stopped = await cancelAgentRunCommand({ agentManager: manager, logger }, agent.id);
|
||||
expect(stopped.cancelled).toBe(false);
|
||||
expect(harness.inputs.some((input) => input.type === "session.interrupt")).toBe(false);
|
||||
if (run && type === "session.runtime_failed") {
|
||||
await expect(run).rejects.toThrow("Provider process exited");
|
||||
} else if (run) {
|
||||
await expect(run).resolves.toMatchObject({ canceled: true });
|
||||
}
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await registry.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -682,6 +682,10 @@ class ProviderRuntimeSession {
|
||||
return this.capabilities;
|
||||
}
|
||||
|
||||
get activeTurnId(): string | undefined {
|
||||
return [...this.activeTurnIds].at(-1);
|
||||
}
|
||||
|
||||
onEvent(listener: (event: ProviderEvent) => void): () => void {
|
||||
// This buffer bridges session.open and adapter attachment. Once replayed,
|
||||
// the adapter owns history; retaining live cumulative snapshots is quadratic.
|
||||
@@ -861,12 +865,16 @@ class ProviderRuntimeSession {
|
||||
connectionClosed(error = new Error("Provider connection closed")): void {
|
||||
// Closing fails only an interrupted turn. An idle session goes stale, and its next prompt
|
||||
// reopens it from persistence.
|
||||
if (!this.terminal && this.activeTurnIds.size > 0) {
|
||||
this.publish({
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.id,
|
||||
error: { message: error.message },
|
||||
});
|
||||
if (!this.terminal) {
|
||||
this.publish(
|
||||
this.activeTurnIds.size > 0
|
||||
? {
|
||||
type: "session.runtime_failed",
|
||||
sessionId: this.id,
|
||||
error: { message: error.message },
|
||||
}
|
||||
: { type: "session.closed", sessionId: this.id },
|
||||
);
|
||||
}
|
||||
this.terminal = true;
|
||||
this.rejectPending(error);
|
||||
@@ -1645,10 +1653,35 @@ class PluginAgentSession implements AgentSession {
|
||||
return this.translateConfig(event);
|
||||
case "session.notice":
|
||||
return this.translateNotice(event);
|
||||
case "session.background_work":
|
||||
return [
|
||||
{
|
||||
type: "background_work",
|
||||
provider: this.provider,
|
||||
items: event.items,
|
||||
canInterruptSession: event.canInterruptSession,
|
||||
},
|
||||
];
|
||||
case "session.runtime_failed":
|
||||
return [this.translateFailure(event.error)];
|
||||
case "session.closed":
|
||||
return event.error ? [this.translateFailure(event.error)] : [];
|
||||
case "session.closed": {
|
||||
const retired: AgentStreamEvent[] = [
|
||||
{ type: "background_work", provider: this.provider, items: null },
|
||||
];
|
||||
// Prompt acceptance can precede the provider's turn-start notification.
|
||||
const turnId = this.bridge.activeTurnId ?? this.currentTurnId ?? undefined;
|
||||
if (event.error) {
|
||||
retired.push(this.translateFailure(event.error, turnId));
|
||||
} else if (turnId) {
|
||||
retired.push({
|
||||
type: "turn_canceled",
|
||||
provider: this.provider,
|
||||
turnId,
|
||||
reason: "Provider closed the session",
|
||||
});
|
||||
}
|
||||
this.currentTurnId = null;
|
||||
return retired;
|
||||
}
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
@@ -1657,7 +1690,12 @@ class PluginAgentSession implements AgentSession {
|
||||
private translateTurn(event: Extract<ProviderEvent, { type: "session.turn" }>): AgentStreamEvent {
|
||||
if (event.state === "started") {
|
||||
this.currentTurnId = event.turnId;
|
||||
return { type: "turn_started", provider: this.provider, turnId: event.turnId };
|
||||
return {
|
||||
type: "turn_started",
|
||||
provider: this.provider,
|
||||
turnId: event.turnId,
|
||||
...(event.acceptsFollowUp ? { acceptsFollowUp: true } : {}),
|
||||
};
|
||||
}
|
||||
if (this.currentTurnId === event.turnId) this.currentTurnId = null;
|
||||
if (event.state === "completed") {
|
||||
@@ -1691,7 +1729,7 @@ class PluginAgentSession implements AgentSession {
|
||||
type: "timeline",
|
||||
provider: this.provider,
|
||||
item,
|
||||
turnId: this.currentTurnId ?? undefined,
|
||||
turnId: event.turnId ?? this.currentTurnId ?? undefined,
|
||||
timestamp: event.timestamp,
|
||||
},
|
||||
]
|
||||
@@ -1833,11 +1871,11 @@ class PluginAgentSession implements AgentSession {
|
||||
];
|
||||
}
|
||||
|
||||
private translateFailure(error: ProviderError): AgentStreamEvent {
|
||||
private translateFailure(error: ProviderError, turnId: string | undefined): AgentStreamEvent {
|
||||
return {
|
||||
type: "turn_failed",
|
||||
provider: this.provider,
|
||||
turnId: this.currentTurnId ?? undefined,
|
||||
turnId,
|
||||
error: error.message,
|
||||
code: error.code,
|
||||
diagnostic: error.diagnostic,
|
||||
|
||||
@@ -53,12 +53,15 @@ test.each(["existing", "new"])(
|
||||
);
|
||||
try {
|
||||
await backend.start();
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });
|
||||
if (population === "new") {
|
||||
await Promise.all(removed.map((path) => writeFile(path, "before")));
|
||||
for (const path of removed) notifications.emit("change", "change", path);
|
||||
await expect
|
||||
.poll(() => backend.getDiagnostics().nativeTrackedFileCount)
|
||||
.toBe(removed.length);
|
||||
}
|
||||
await Promise.all(removed.map((path) => rm(path)));
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });
|
||||
for (const path of removed) notifications.emit("change", "change", path);
|
||||
// The file-only event uses the eight-second optional audit debounce.
|
||||
await vi.advanceTimersByTimeAsync(8_000);
|
||||
|
||||
@@ -5334,6 +5334,7 @@ export class Session {
|
||||
await cancelAgentRunCommand(
|
||||
{ agentManager: this.agentManager, logger: this.sessionLogger },
|
||||
agentId,
|
||||
{ includeBackgroundWork: true },
|
||||
);
|
||||
if (requestId) {
|
||||
const agent = this.agentManager.getAgent(agentId);
|
||||
|
||||
@@ -213,3 +213,111 @@ describe("installation", () => {
|
||||
).resolves.toEqual({ status: "not_installed" });
|
||||
});
|
||||
});
|
||||
|
||||
it("tracks backgrounded run_command work and out-of-turn wakeups", async () => {
|
||||
const { directory, launch } = await launchAgent(`
|
||||
const { createInterface } = require("node:readline");
|
||||
const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
|
||||
createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const { id, method, params } = JSON.parse(line);
|
||||
switch (method) {
|
||||
case "initialize":
|
||||
send({ id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true } } });
|
||||
break;
|
||||
case "session/new":
|
||||
send({ id, result: { sessionId: "agy-bg-session", modes: { currentModeId: "default", availableModes: [{ id: "default", name: "Default" }] } } });
|
||||
send({ method: "session/update", params: { sessionId: "agy-bg-session", update: { sessionUpdate: "available_commands_update", availableCommands: [] } } });
|
||||
break;
|
||||
case "session/prompt":
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "tool_call", toolCallId: "bg-1", name: "run_command", kind: "execute",
|
||||
title: "npm run typecheck", status: "in_progress",
|
||||
rawInput: { CommandLine: "npm run typecheck", toolSummary: "Typecheck" },
|
||||
} } });
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Waiting for typecheck." },
|
||||
} } });
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "usage_update", used: 1000, size: 1048576,
|
||||
} } });
|
||||
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: "Typecheck passed." },
|
||||
} } });
|
||||
send({ method: "session/update", params: { sessionId: params.sessionId, update: {
|
||||
sessionUpdate: "usage_update", used: 1100, size: 1048576,
|
||||
} } });
|
||||
}, 80);
|
||||
break;
|
||||
case "session/close":
|
||||
send({ id, result: {} });
|
||||
break;
|
||||
}
|
||||
});
|
||||
`);
|
||||
const provider = createAntigravityProvider();
|
||||
const connection = await provider.connect({
|
||||
launch,
|
||||
versions: [1],
|
||||
capabilities: ["prompt.message", "session.can_stop_runtime"],
|
||||
});
|
||||
const events: ProviderEvent[] = [];
|
||||
connection.onEvent((event) => events.push(event));
|
||||
try {
|
||||
await connection.send({
|
||||
type: "session.open",
|
||||
requestId: "open-1",
|
||||
sessionId: "test",
|
||||
history: "skip",
|
||||
config: { cwd: directory, env: {}, mcpServers: {}, settings: {}, persist: true },
|
||||
});
|
||||
await expect
|
||||
.poll(() => events.find((event) => event.type === "session.ready"), { timeout: 3_000 })
|
||||
.toBeDefined();
|
||||
await connection.send({
|
||||
type: "session.prompt",
|
||||
sessionId: "test",
|
||||
prompt: {
|
||||
clientMessageId: "prompt-1",
|
||||
delivery: "auto",
|
||||
input: { type: "message", content: [{ type: "text", text: "Check types" }] },
|
||||
},
|
||||
});
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
events.find(
|
||||
(event) =>
|
||||
event.type === "session.turn" &&
|
||||
event.turnId.startsWith("acp:autonomous:") &&
|
||||
event.state === "completed",
|
||||
),
|
||||
{ timeout: 3_000 },
|
||||
)
|
||||
.toBeDefined();
|
||||
expect(events).toContainEqual({
|
||||
type: "session.background_work",
|
||||
sessionId: "test",
|
||||
canInterruptSession: true,
|
||||
items: [
|
||||
{
|
||||
id: "bg-1",
|
||||
kind: "shell",
|
||||
description: "Typecheck",
|
||||
command: "npm run typecheck",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(events.findLast((event) => event.type === "session.background_work")).toEqual({
|
||||
type: "session.background_work",
|
||||
sessionId: "test",
|
||||
items: [],
|
||||
});
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -95,6 +95,8 @@ export function createAntigravityProvider(): ProviderRegistration {
|
||||
acpOptions: {
|
||||
waitForInitialCommands: true,
|
||||
loadReplayQuietPeriodMs: 200,
|
||||
// COMPAT(antigravityAcpV1OutOfTurn): added in v0.17.0, remove after agy acp negotiates ACP v2 state_update.
|
||||
outOfTurnActivity: true,
|
||||
autoAcceptMode: {
|
||||
mode: {
|
||||
id: "full-access",
|
||||
|
||||
@@ -331,6 +331,9 @@ turn or finish as a side effect with a `completed` prompt result.
|
||||
Advertise only capabilities you implement. If steering is unsupported, omit `prompt.steer`; Paseo
|
||||
can replace the active turn instead.
|
||||
|
||||
For a turn the session starts on its own, set `acceptsFollowUp: true` on the started
|
||||
`session.turn` event if the next ordinary prompt can take over without an interrupt.
|
||||
|
||||
## Permit idle runtime cleanup
|
||||
|
||||
Paseo can release an idle resumable session after one hour when its daemon baseline allows cleanup.
|
||||
@@ -369,6 +372,10 @@ queued completion reports, or pending autonomous replies. This query must not st
|
||||
session. Return `false` while work remains. A rejected query, invalid response, or timeout also
|
||||
keeps the runtime alive. Never respond with `request.completed` for this query.
|
||||
|
||||
Publish `session.background_work` to replace the live background-work list. Set
|
||||
`canInterruptSession: true` when `session.interrupt` also stops that work. Paseo offers a
|
||||
session-wide Stop action while the list contains work. Publish an empty list when the work stops.
|
||||
|
||||
Paseo always checks foreground work, permissions, queued deliveries, lifecycle operations,
|
||||
working managed/native descendants, and outstanding local or remote finish subscriptions for the
|
||||
caller. Subscription protection lasts through registration, recovery and notification dispatch
|
||||
|
||||
Reference in New Issue
Block a user