Compare commits

...
9 changed files with 393 additions and 28 deletions
@@ -266,7 +266,33 @@ function renderCopyOutput() {
return <button type="button">Copy output</button>;
}
const searchQuery = "IANA example domains";
const queryOnlySearch = { type: "search", query: searchQuery, toolName: "web_search" } as const;
function renderSearchDetails() {
return <ToolCallDetailsContent detail={queryOnlySearch} />;
}
function SearchBadge() {
const [expanded, setExpanded] = React.useState(false);
const toggle = React.useCallback(() => setExpanded((current) => !current), []);
return (
<ExpandableBadge
label="Search"
isExpanded={expanded}
onToggle={toggle}
renderDetails={renderSearchDetails}
/>
);
}
describe("tool detail interaction", () => {
it("shows the query when an expanded search has no results", async () => {
act(() => root.render(<SearchBadge />));
await page.getByRole("button", { name: "Search" }).click();
await expect.element(page.getByText(searchQuery, { exact: true })).toBeVisible();
});
it("keeps detail controls in the tab order", async () => {
function Badge() {
const [expanded, setExpanded] = React.useState(true);
@@ -352,6 +352,9 @@ function buildSearchSections(detail: SearchDetail, ds: DetailStyles): ReactNode[
</View>,
);
}
if (out.length === 0 && detail.query) {
return [<ScrollablePlainTextSection key="search-query" text={detail.query} ds={ds} />];
}
return out;
}
@@ -16,6 +16,7 @@ import {
type SessionNotification,
type SessionUpdate,
type ToolCall,
type ToolCallContent,
type ToolCallUpdate,
type Stream,
} from "@agentclientprotocol/sdk";
@@ -407,6 +408,15 @@ interface ActivePrompt {
const DEFAULT_DEFERRED_SETTLE_DELAY_MS = 500;
const DEFAULT_DEFERRED_QUIET_LIMIT_MS = 120_000;
type AcpToolCallSource = AcpToolCallSnapshot & {
diff?: Extract<ToolCallContent, { type: "diff" }>;
};
interface AcpToolCallState {
source: AcpToolCallSource;
presentation: AcpToolCallSnapshot;
}
class AcpRuntime {
readonly connection: ClientSideConnection;
agentCapabilities: AgentCapabilities = {};
@@ -414,7 +424,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, AcpToolCallState>();
private mcpServerNames: readonly string[] = [];
private readonly liveOpenToolIds = new Set<string>();
private readonly canceledToolCallIds = new Set<string>();
// Running tool rows published by transformers; the turn's terminal closes any left open.
@@ -576,6 +587,7 @@ class AcpRuntime {
connectionCapabilities: readonly ProviderCapability[],
): Promise<readonly ProviderCapability[]> {
const mcpServers = toAcpMcpServers(input.config);
this.mcpServerNames = mcpServers.map((server) => server.name);
let nativeSessionId = readNativeSessionId(input.persistence);
const metadata: Record<string, unknown> = {
_paseo: {
@@ -1460,7 +1472,8 @@ class AcpRuntime {
options?: { preserveQualifyingOpenTools?: boolean; suppressTrailingToolEcho?: boolean },
): void {
const preserve = options?.preserveQualifyingOpenTools === true;
for (const [id, snapshot] of this.toolCalls) {
for (const [id, tool] of this.toolCalls) {
const snapshot = tool.presentation;
if (snapshot.status !== "pending" && snapshot.status !== "in_progress") continue;
if (preserve && this.liveOpenToolIds.has(id) && this.toolKeepsTurnOpen(snapshot)) continue;
this.liveOpenToolIds.delete(id);
@@ -1469,7 +1482,10 @@ class AcpRuntime {
...snapshot,
status: state === "completed" ? "completed" : "failed",
};
this.toolCalls.set(id, completed);
this.toolCalls.set(id, {
source: { ...tool.source, status: completed.status },
presentation: completed,
});
this.emit({
type: "timeline.item",
sessionId: this.options.boundarySessionId,
@@ -1507,16 +1523,32 @@ class AcpRuntime {
if (update.sessionUpdate === "tool_call") {
this.canceledToolCallIds.delete(update.toolCallId);
}
const current = this.toolCalls.get(update.toolCallId);
const tool = this.toolCalls.get(update.toolCallId);
const current = tool?.presentation;
const wasOpenQualifying =
current !== undefined &&
this.liveOpenToolIds.has(current.id) &&
this.toolKeepsTurnOpen(current);
let snapshot = mergeToolCallSnapshot(update, current);
const context = { sessionId: this.options.boundarySessionId };
const source = mergeToolCallSnapshot(update, tool?.source);
let snapshot: AcpToolCallSnapshot = source;
const context = {
sessionId: this.options.boundarySessionId,
mcpServerNames: this.mcpServerNames,
};
for (const transformer of this.transformers)
snapshot = transformer.toolCall?.(snapshot, context) ?? snapshot;
this.toolCalls.set(snapshot.id, snapshot);
if (!snapshot.detail && source.diff && snapshot.kind === "edit") {
snapshot = {
...snapshot,
detail: {
type: "edit",
filePath: source.diff.path,
oldString: source.diff.oldText ?? undefined,
newString: source.diff.newText,
},
};
}
this.toolCalls.set(snapshot.id, { source, presentation: snapshot });
const isOpen = snapshot.status === "pending" || snapshot.status === "in_progress";
if (this.replayWindow === null) {
if (isOpen) this.liveOpenToolIds.add(snapshot.id);
@@ -1789,7 +1821,7 @@ class AcpRuntime {
private hasQualifyingOpenTools(): boolean {
for (const id of this.liveOpenToolIds) {
const snapshot = this.toolCalls.get(id);
const snapshot = this.toolCalls.get(id)?.presentation;
if (snapshot && this.toolKeepsTurnOpen(snapshot)) return true;
}
return false;
@@ -2027,8 +2059,8 @@ function ownConnectorStream(source: Stream): {
function mergeToolCallSnapshot(
update: ToolCall | ToolCallUpdate,
current: AcpToolCallSnapshot | undefined,
): AcpToolCallSnapshot {
current: AcpToolCallSource | undefined,
): AcpToolCallSource {
return {
id: update.toolCallId,
name: firstText(update.name, current?.name),
@@ -2038,6 +2070,10 @@ function mergeToolCallSnapshot(
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 ?? [],
diff:
update.content === undefined
? current?.diff
: update.content?.find((item) => item.type === "diff"),
};
}
+4 -1
View File
@@ -140,7 +140,10 @@ export interface AcpTransformer {
notification: { method: string; params: JsonValue },
context: AcpContext,
): AcpVendorUpdate | readonly AcpVendorUpdate[] | null;
toolCall?(toolCall: AcpToolCallSnapshot, context: AcpContext): AcpToolCallSnapshot;
toolCall?(
toolCall: AcpToolCallSnapshot,
context: AcpContext & { mcpServerNames?: readonly string[] },
): AcpToolCallSnapshot;
}
export function runAcpProvider(options: RunAcpProviderOptions): ProviderRegistration {
@@ -185,6 +185,225 @@ it.each([true, false])(
},
);
const completedToolCalls = [
{
toolCallId: "shell",
name: "run_command",
kind: "execute",
rawInput: {
CommandLine: "printf test; exit 7",
WaitMsBeforeAsync: 5000,
toolSummary: "Run exit code test",
},
rawOutput: { output: "Command exited with code 7.\n\nCommand output:\ntest", exit_code: 7 },
},
{
toolCallId: "read",
name: "read_file",
kind: "read",
locations: [{ path: "/repo/probe.txt" }],
rawInput: { Path: "/repo/probe.txt", StartLine: 2, EndLine: 2 },
},
{
toolCallId: "write",
name: "write_file",
kind: "edit",
locations: [{ path: "/repo/probe.txt" }],
rawInput: { Path: "/repo/probe.txt", Content: "alpha\nbeta\ngamma\n", Overwrite: true },
rawOutput: {},
content: [{ type: "diff", path: "/repo/probe.txt", newText: "alpha\nbeta\ngamma\n" }],
},
{
toolCallId: "edit",
name: "edit_file",
kind: "edit",
locations: [{ path: "/repo/probe.txt" }],
rawInput: { Path: "/repo/probe.txt", Target: "beta", Replacement: "delta" },
rawOutput: {},
content: [
{
type: "diff",
path: "/repo/probe.txt",
oldText: "alpha\nbeta\ngamma\n",
newText: "alpha\ndelta\ngamma\n",
},
],
},
{
toolCallId: "web",
name: "search_web",
kind: "search",
rawInput: { query: "IANA example domains" },
},
{
toolCallId: "paseo",
name: "mcp_paseo_send_agent_prompt",
kind: "other",
rawInput: { agentId: "agent-1", prompt: "Hello", toolSummary: "Send message" },
},
{
toolCallId: "mcp",
name: "mcp_local_tools_echo_message",
kind: "other",
rawInput: { message: "hello", toolSummary: "Echo message hello" },
},
{
toolCallId: "ambiguous",
name: "mcp_paseo_get_agent_status",
kind: "other",
rawInput: { agentId: "agent-1", toolSummary: "Get agent status" },
},
];
it.each(["live", "replay"] as const)(
"maps Antigravity tool calls in %s timelines",
async (source) => {
const { directory, launch } = await launchAgent(`
const { createInterface } = require("node:readline");
const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
const tools = ${JSON.stringify(completedToolCalls)};
const modes = { currentModeId: "default", availableModes: [{ id: "default", name: "Default" }] };
createInterface({ input: process.stdin }).on("line", (line) => {
const { id, method, params } = JSON.parse(line);
const update = (update) => send({ method: "session/update", params: { sessionId: params.sessionId ?? "agy-session", update } });
switch (method) {
case "initialize":
send({ id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true } } });
break;
case "session/new":
send({ id, result: { sessionId: "agy-session", modes } });
update({ sessionUpdate: "available_commands_update", availableCommands: [] });
break;
case "session/load":
case "session/prompt":
for (const { rawOutput, content, ...tool } of tools) {
const completed = { status: "completed", rawOutput, content };
if (method === "session/load") {
update({ sessionUpdate: "tool_call", title: tool.name, ...tool, ...completed });
} else {
update({ sessionUpdate: "tool_call", title: tool.name, ...tool, status: "in_progress" });
update({ sessionUpdate: "tool_call_update", toolCallId: tool.toolCallId, ...completed });
}
}
send({ id, result: method === "session/load" ? { modes } : { stopReason: "end_turn" } });
break;
case "session/close":
send({ id, result: {} });
break;
}
});
`);
const connection = await createAntigravityProvider().connect({
launch,
versions: [1],
capabilities: ["session.persistence", "prompt.message"],
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
await connection.send({
type: "session.open",
requestId: "open",
sessionId: "test",
history: source === "replay" ? "replay" : "skip",
persistence:
source === "replay" ? { version: 1, data: { sessionId: "agy-session" } } : undefined,
config: {
cwd: directory,
env: {},
mcpServers: {
paseo_get: { type: "stdio", command: "other-server" },
local_tools: { type: "stdio", command: "echo-mcp" },
},
settings: {},
persist: true,
},
});
await expect
.poll(
() =>
events.find(
(event) => event.type === "session.ready" || event.type === "request.failed",
),
{ timeout: 4_000 },
)
.toMatchObject({ type: "session.ready" });
if (source === "live") {
await connection.send({
type: "session.prompt",
sessionId: "test",
prompt: {
clientMessageId: "exercise-tools",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "Exercise tools" }] },
},
});
}
const calls = () =>
events.flatMap((event) =>
event.type === "timeline.item" && event.item.type === "tool_call" ? [event.item] : [],
);
await expect
.poll(() => calls().filter((call) => call.status === "completed").length)
.toBe(completedToolCalls.length);
const completed = Object.fromEntries(calls().map((call) => [call.id, call]));
expect(completed.shell.detail).toEqual({
type: "shell",
command: "printf test; exit 7",
output: "Command exited with code 7.\n\nCommand output:\ntest",
exitCode: 7,
});
expect(completed.read.detail).toEqual({
type: "read",
filePath: "/repo/probe.txt",
offset: 2,
limit: 1,
});
expect(completed.write.detail).toEqual({
type: "write",
filePath: "/repo/probe.txt",
content: "alpha\nbeta\ngamma\n",
});
expect(completed.edit.detail).toEqual({
type: "edit",
filePath: "/repo/probe.txt",
oldString: "alpha\nbeta\ngamma\n",
newString: "alpha\ndelta\ngamma\n",
});
expect(completed.web.detail).toEqual({
type: "search",
toolName: "web_search",
query: "IANA example domains",
});
expect(completed.paseo).toMatchObject({
name: "paseo.send_agent_prompt",
detail: { type: "unknown", input: { agentId: "agent-1", prompt: "Hello" }, output: null },
});
expect(completed.paseo.detail).not.toHaveProperty("input.toolSummary");
expect(completed.mcp).toMatchObject({
name: "local_tools.echo_message",
detail: { type: "unknown", input: { message: "hello" }, output: null },
});
expect(completed.mcp.detail).not.toHaveProperty("input.toolSummary");
expect(completed.ambiguous).toMatchObject({
name: "mcp_paseo_get_agent_status",
detail: { type: "unknown", input: { agentId: "agent-1" }, output: null },
});
if (source === "live") {
expect(calls()).toContainEqual(
expect.objectContaining({
id: "shell",
status: "running",
detail: { type: "shell", command: "printf test; exit 7" },
}),
);
}
} finally {
await connection.close();
}
},
);
describe("installation", () => {
const signal = new AbortController().signal;
@@ -6,6 +6,7 @@ import {
type ProviderRegistration,
} from "@getpaseo/plugin/server/provider";
import { z } from "zod";
import { mapToolCall } from "./tool-calls.js";
const legacySession = z.object({
version: z.literal(1),
@@ -15,24 +16,8 @@ const systemPromptCapability = z.object({
antigravity: z.object({ systemPrompt: z.object({ append: z.literal(true) }) }),
});
const fileWrite = z.object({ Path: z.string(), Content: z.string().optional() });
const antigravity: AcpTransformer = {
toolCall(call) {
if (call.name === "write_file") {
const input = fileWrite.safeParse(call.input);
if (input.success) {
return {
...call,
detail: { type: "write", filePath: input.data.Path, content: input.data.Content },
};
}
}
if (call.kind === "read" && call.locations[0]) {
return { ...call, detail: { type: "read", filePath: call.locations[0] } };
}
return call;
},
toolCall: mapToolCall,
sessionOpen({ persistence, systemPrompt, agentMetadata }) {
// COMPAT(antigravityStreamJson): added in v0.16.2, remove after 2027-11-19.
const saved = legacySession.safeParse(persistence);
@@ -0,0 +1,86 @@
import type { AcpToolCallSnapshot, AcpTransformer } from "@getpaseo/plugin/server/acp";
import type { ProviderToolCallDetail } from "@getpaseo/plugin/server/provider";
import { z } from "zod";
const shellInput = z.object({ CommandLine: z.string() });
const shellOutput = z.object({
output: z.string().optional(),
exit_code: z.number().nullable().optional(),
});
const fileRead = z.object({
Path: z.string().optional(),
StartLine: z.int().positive().optional(),
EndLine: z.int().positive().optional(),
});
const fileWrite = z.object({ Path: z.string(), Content: z.string().optional() });
const webSearch = z.object({ query: z.string() });
export const mapToolCall: NonNullable<AcpTransformer["toolCall"]> = (call, context) => {
if (call.name?.startsWith("mcp_")) {
return mapMcpCall(call, call.name, context.mcpServerNames ?? []);
}
const detail = mapNativeDetail(call);
return detail ? { ...call, detail } : call;
};
function mapNativeDetail(call: AcpToolCallSnapshot): ProviderToolCallDetail | undefined {
switch (call.name) {
case "run_command": {
const input = shellInput.safeParse(call.input).data;
if (!input) break;
const output = shellOutput.safeParse(call.output).data;
return {
type: "shell",
command: input.CommandLine,
output: output?.output,
exitCode: output?.exit_code,
};
}
case "write_file": {
const input = fileWrite.safeParse(call.input).data;
if (input) return { type: "write", filePath: input.Path, content: input.Content };
break;
}
case "search_web": {
const input = webSearch.safeParse(call.input).data;
if (input) return { type: "search", toolName: "web_search", query: input.query };
break;
}
}
if (call.kind !== "read") return undefined;
const input = fileRead.safeParse(call.input).data;
const filePath = call.locations[0] ?? input?.Path;
if (!filePath) return undefined;
const { StartLine: offset, EndLine: end } = input ?? {};
return {
type: "read",
filePath,
offset,
limit:
offset !== undefined && end !== undefined && end >= offset ? end - offset + 1 : undefined,
};
}
function mapMcpCall(
call: AcpToolCallSnapshot,
wireName: string,
serverNames: readonly string[],
): AcpToolCallSnapshot {
const qualifiedName = wireName.slice("mcp_".length);
// The wire uses the same separator inside names and between the server and tool.
// Paseo's own server can also appear when replaying with MCP disabled.
const matchingServers = [...new Set([...serverNames, "paseo"])].filter((name) =>
qualifiedName.startsWith(`${name}_`),
);
const server = matchingServers.length === 1 ? matchingServers[0] : undefined;
let input = call.input;
if (typeof input === "object" && input !== null && !Array.isArray(input)) {
const { toolSummary: _summary, ...args } = input;
input = args;
}
return {
...call,
name: server ? `${server}.${qualifiedName.slice(server.length + 1)}` : wireName,
detail: { type: "unknown", input, output: call.output },
};
}
+4
View File
@@ -438,6 +438,10 @@ hooks for vendor behavior. See [Adapt an ACP agent](/docs/plugins/providers#adap
In `discover` and `configure`, call `context.request(method, params)` to send an ACP extension
request. The promise returns a JSON value or rejects with the agent's JSON-RPC error.
In `toolCall`, use `context.mcpServerNames` to recognize servers that Paseo supplied when it opened
the ACP session. Include an empty-list fallback for older SDK versions or servers configured
directly in the agent.
Use `config(state, context)` to return the configuration snapshot that Paseo displays.
Paseo calls this synchronous hook for initial, notification, and committed configuration snapshots.
Use `configure` to send changes to the agent.
+3
View File
@@ -368,6 +368,9 @@ Paseo 刷新 Agent 的方式是关闭它当前的 Provider 会话,再用当前
在 `discover` 和 `configure` 中,调用 `context.request(method, params)` 发送 ACP 扩展请求。
Promise 返回 JSON 值,或以 Agent 的 JSON-RPC 错误拒绝。
在 `toolCall` 中,通过 `context.mcpServerNames` 识别 Paseo 打开 ACP 会话时提供的服务器。
兼容旧版 SDK 或处理直接在 agent 中配置的服务器时,可以回退到空列表。
使用 `config(state, context)` 返回 Paseo 显示的配置快照。
Paseo 在会话就绪、收到配置通知或提交配置更改时调用此同步钩子。
使用 `configure` 向 Agent 发送更改。