Compare commits

...
Author SHA1 Message Date
Mohamed Boudra dd3ce76b84 fix(server): report every turn end and keep following until the child settles
A child that ends its turn while it still has pending work (a background task such as
`npm run dev`, queued messages, or its own delegated agents) now reports `finished` to its
caller at once. The notice names the pending work and says the caller will hear again. The
subscription keeps following the child: each later turn end reports again, and the child
settling with nothing pending, with or without another turn, sends the final `finished`.
The 24-hour follow limit sends a final `finished` with the child's last reply.

Every notice is a plain `agent_finished` tool call. There is no still-working event.

The observation's initial wait no longer repeats a turn end the stream already reported,
which would have sent the first turn end twice.
2026-11-28 11:54:57 +01:00
Mohamed Boudra f73c3a594f fix(server): stop waking the parent when a delegated child ends its turn but is still working
#10864 told the caller "ended its turn but is still working" whenever a child's turn ended
with work pending, and "is still working" after 24 hours of following. The caller could not
act on either notice; it only woke up to wait again. The watch now follows such a child
silently and reports once: finished when it settles, or errored, permission, and closed as
they happen. After 24 hours it reports finished with the child's last reply, so a task that
never ends cannot hold the caller forever.

The still-working event and its agent_still_working tool are gone. Transcripts with #10864's
event="message" notices replay as messages from the child, as clients showed them then.
2026-11-28 11:54:57 +01:00
Mohamed Boudra a579cbe795 fix(server): keep a delivered message's sender when a provider trims the replayed prompt
Claude history replay trims each user prompt, so a body that started with whitespace came
back shorter than the marker's length and replayed as raw text. Drop the body's leading
whitespace before writing the marker.
2026-11-28 11:54:56 +01:00
Mohamed Boudra bfa46ab6c8 refactor(server): let the daemon decide whether an agent message is a tool call or a message
Lifecycle notices (finished, errored, needs permission, closed, still working) now reach
clients as ordinary plain-text tool calls such as "Agent finished · Child". Only peer
send_agent_prompt messages keep the agentMessage sender so they still render as a
"Sent by" bubble. No protocol fields were added.

Delivered prompts carry a trailing <paseo-message .../> marker instead of a leading
<paseo-system> envelope, so the body (including a slash command) stays at character 0
and is no longer XML-escaped. Plain human messages get no marker unless they share a
turn with agent messages or contain marker syntax. Legacy envelopes and legacy
agentMessage notification rows keep rendering (COMPAT tagged).
2026-11-28 11:54:56 +01:00
42 changed files with 1270 additions and 667 deletions
+18 -11
View File
@@ -198,17 +198,24 @@ outstanding intent. A crash after successful dispatch but before removal commits
notification. Clean shutdown can also flush an already queued callback while retaining its intent,
so that callback can repeat after restart. This is an at-least-once wakeup, without turn attribution or exactly-once delivery.
A turn end is not always a settled child. When the child ends its turn with work that will start its
next turn by itself, the caller gets one `message` notice ("ended its turn but is still working") and
the subscription keeps following the child. That work is a running turn, queued messages, a pending
provider wake-up (`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and
one-shot wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats,
recurring crons, change-request watches, and other daemon background items never count: they are
external triggers, not work the caller is waiting for. While following, turn ends and work changes stay
silent until nothing is pending, which sends `finished` and removes the subscription. `followingSince`
is stored before the notice is sent, so restarts resume following without repeating it, and following
ends after 24 hours with an "is still working" notice. Remote children and providers without the probe
report their first turn end as `finished`.
A turn end is not always a settled child. A child can end its turn with work that will start its next
turn by itself: a running turn, queued messages, a pending provider wake-up
(`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and one-shot
wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats, recurring
crons, change-request watches, and other daemon background items never count: they are external
triggers, not work the caller is waiting for.
Every turn end reports `finished` at once. When work is still pending, the notice names it and the
subscription follows the child: each later turn end reports `finished` again, and the child settling
with nothing pending sends a final `finished` and removes the subscription, even when the work
drains without another turn. Reporting at once keeps a long-lived task, such as a dev server, from
leaving the caller without the child's reply. Following is what lets the caller hear the reply a
background task wakes up later ([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change
that leaves work pending sends nothing. Errors, permission requests, and closes report as they
happen. `followingSince` is stored when following starts, so a restart keeps following instead of
waiting for another turn end. After 24 hours of following, the caller gets a final `finished` with
the child's last reply and the subscription ends. Remote children and providers without the probe
report their first turn end as a settled `finished`.
Permission requests are notification checkpoints, not the end of that subscription. The caller is notified again after a permission response when the child finishes, errors, or requests another permission.
The permission notification includes the normalized request plus the child and request IDs, so the caller can inspect it and respond without fetching agent status.
+24 -8
View File
@@ -330,19 +330,35 @@ that starts or accepts them. Received messages retain sender attribution, while
notifications remain visible events. Collapse, timing and locally mounted history share
these boundaries.
Agent-message XML belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes
Agent-message markup belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes
provenance; acceptance, provider echoes, import, and replay share its projection. The delivery ID is
also the projected call ID, so a provider echo cannot create a second row. Sender IDs are opaque and
do not imply local ownership or authorization. Capture the sender title at delivery: archived or
removed senders must remain understandable without a live directory lookup.
The optional `agentMessage` payload carries event, sender, and delivered text. Shared client
presentation (`protocol/paseo-tool-presentation`) owns its heading and expanded details, next to the
labels for every Paseo MCP tool. The daemon
must not construct UI labels or prepend sender labels to the semantic message body. The existing
`tool_call` / `plain_text` envelope is a compatibility adapter: older clients still parse the row and
expand its body. New clients use the typed payload, never infer the event from a tool name or parse
XML. Stream reduction and disk-cache serialization preserve the payload without rendering it.
Each delivered message keeps its text first and ends with a `<paseo-message … length="N"/>` marker.
Text at character 0 stays the sender's, so a provider still reads a slash command there, and bodies
are never escaped. `length` bounds the text before the marker, so marker syntax inside a body cannot
split it, and a batch splits back into rows by reading markers from the end. A person's prompt gets a
marker only when it shares a provider turn with other deliveries or contains `<paseo-message` or
`<paseo-system`. Transcripts written before markers open with a `<paseo-system>` envelope; the
projection still reads those (`COMPAT(leadingPaseoSystemEnvelope)`).
The daemon decides whether a delivery is a message or a tool call, and clients render what it sends:
- A person's text is a `user_message`.
- A peer message is an `agent_message` tool call whose `agentMessage` carries sender and text. The
wire has no sender on `user_message`, so clients present it as a "Sent by" bubble.
- Lifecycle notifications (`agent_finished`, `agent_errored`, `agent_needs_permission`,
`agent_closed`), schedule fires (`heartbeat`), and change-request updates
are plain tool calls. `plain_text` detail carries the sender in `label`, the body in `text`, and
the icon. Clients render the heading from the tool name, so no notification event reaches them.
`isTimelineTurnTrigger` (`packages/protocol/src/timeline-turn.ts`) lists the delivered tool names that
start a turn. Add a name there when the daemon projects a new delivery. Rows that older daemons stored
with notification `agentMessage` metadata are rewritten to the plain call at presentation
(`COMPAT(agentNotificationMetadata)`). Stream reduction and disk-cache serialization preserve the
payload without rendering it.
The compatibility boundary for older daemons is snapshot normalization: running/idle status becomes an
anonymous active turn or idle state once, and downstream code consumes the same activity shape. The app
@@ -13,8 +13,12 @@ import { test, expect } from "../support/fixtures";
import { expectComposerVisible } from "../support/helpers/composer";
import { withDirectoryPlugin } from "../support/helpers/plugin-timeline";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
test.use({
e2eInjectPaseoTools: true,
e2eDaemonConfig: {
version: 1,
agents: {
@@ -290,6 +294,89 @@ test("received messages show their sender and open that agent", async ({ page })
}
});
/** Calls a Paseo MCP tool as `callerAgentId`, the way that agent's provider would. */
async function callPaseoToolAs(
callerAgentId: string,
name: string,
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const mcp = new Client({ name: "turn-collapse-e2e", version: "1" });
await mcp.connect(
new StreamableHTTPClientTransport(
new URL(`http://127.0.0.1:${getE2EDaemonPort()}/mcp/agents?callerAgentId=${callerAgentId}`),
),
);
try {
const response = await mcp.callTool({ name, arguments: args });
expect(response, name).not.toMatchObject({ isError: true });
return response.structuredContent as Record<string, unknown>;
} finally {
await mcp.close();
}
}
test("a delegated child reports each turn end as a compact tool call until its own delegate is done", async ({
page,
}, testInfo) => {
const frames: string[] = [];
page.on("websocket", (socket) => {
socket.on("framereceived", ({ payload }) => {
if (typeof payload === "string") frames.push(payload);
});
});
const childNoticeFrames = () => frames.filter((frame) => frame.includes('"label":"Child"'));
const parent = await seedMockAgentWorkspace({ repoPrefix: "child-notices-", title: "Lead" });
try {
await openAgentRoute(page, parent);
await expectComposerVisible(page);
const child = await callPaseoToolAs(parent.agentId, "create_agent", {
workspaceId: parent.workspaceId,
title: "Child",
provider: "mock/e2e-fast-stream",
settings: { modeId: "load-test" },
initialPrompt: "Delegate the slow part",
});
const childId = String(child.agentId);
// The child's own delegate outlives the child's first turn.
const grandchild = await callPaseoToolAs(childId, "create_agent", {
workspaceId: parent.workspaceId,
title: "Grandchild",
provider: "mock/ten-second-stream",
settings: { modeId: "load-test" },
initialPrompt: "Take your time",
});
const notices = page.getByRole("button", { name: /^Agent .*Child/ });
const finished = page.getByRole("button", { name: /^Agent finished.*Child/ });
// The child ended its turn while waiting on its delegate: the parent hears it now.
await expect(finished).toHaveCount(1, { timeout: 30_000 });
const delegate = await parent.client.waitForAgentUpsert(String(grandchild.agentId), () => true);
expect(delegate.status, "the delegate must still be running").toBe("running");
expect(
childNoticeFrames().some((frame) => frame.includes("It still has agents it is waiting on.")),
).toBe(true);
// The delegate reports to the child, and the child's settled turn reaches the parent.
await expect(finished).toHaveCount(2, { timeout: 60_000 });
await expect(notices).toHaveCount(2);
await expect(page.getByText(/still working/i)).toHaveCount(0);
await expect(page.getByText(/Sent by/)).toHaveCount(0);
await expect(page.getByText(/<agent-response>/)).toHaveCount(0);
await finished.last().scrollIntoViewIfNeeded();
await page.screenshot({ path: testInfo.outputPath("child-notices.png") });
// Notification events stay on the daemon: clients get only plain tool calls.
expect(frames.filter((frame) => frame.includes('"agentMessage"'))).toEqual([]);
expect(childNoticeFrames().some((frame) => frame.includes('"name":"agent_finished"'))).toBe(
true,
);
expect(childNoticeFrames().filter((frame) => /"name":"agent_(?!finished)/.test(frame))).toEqual(
[],
);
} finally {
await parent.cleanup();
}
});
test("long sender attribution stays on one line in compact chat", async ({ page }, testInfo) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.addInitScript(() =>
+9 -10
View File
@@ -463,16 +463,15 @@ export async function delegateFleetThroughMcp() {
direction: "tail",
limit: 100,
});
return timeline.entries
.flatMap(({ item }) =>
item.type === "tool_call" && item.agentMessage ? [item.agentMessage] : [],
)
.filter(
(message) =>
message.event === "finished" &&
message.sender.id === child.agentId &&
message.text.includes(`Server: ${child.serverId}`),
).length;
return timeline.entries.filter(
({ item }) =>
item.type === "tool_call" &&
item.name === "agent_finished" &&
item.detail.type === "plain_text" &&
item.detail.label === child.title &&
item.detail.text?.includes(child.agentId) &&
item.detail.text.includes(`Server: ${child.serverId}`),
).length;
})
.toBe(1);
},
@@ -783,6 +783,56 @@ it("presents received agent messages as attributed bubbles with the original tur
});
});
it("presents a finished notification as a compact tool call, not a received message", () => {
const call = toolCall("notice", "agent_finished");
if (call.payload.source !== "agent") throw new Error("Expected agent tool");
call.payload.data.detail = {
type: "plain_text",
label: "Child",
text: "Agent child (Child) finished.",
icon: "bot",
};
const result = createStreamPresentation()({
...presentationOptions,
transform: undefined,
tail: [call],
head: [],
});
expect(result.tail).toEqual([call]);
});
// COMPAT(agentNotificationMetadata): rows from daemons that sent notification metadata.
it("presents a legacy notification as the plain tool call current daemons send", () => {
const call = toolCall("legacy", "agent_message");
if (call.payload.source !== "agent") throw new Error("Expected agent tool");
call.turnId = "turn";
call.payload.data.detail = { type: "plain_text", text: "Done", icon: "bot" };
call.payload.data.agentMessage = {
event: "finished",
sender: { id: "child", title: "Child" },
text: "Done",
};
const result = createStreamPresentation()({
...presentationOptions,
transform: undefined,
tail: [call],
head: [],
});
expect(result.tail).toHaveLength(1);
const [presented] = result.tail;
if (presented?.kind !== "tool_call" || presented.payload.source !== "agent")
throw new Error("Expected agent tool");
expect(presented).toMatchObject({ id: call.id, turnId: "turn" });
expect(presented.payload.data).toEqual({
provider: "codex",
callId: "legacy",
name: "agent_finished",
status: "completed",
error: null,
detail: { type: "plain_text", label: "Child", text: "Done", icon: "bot" },
});
});
it("does not reopen the previous turn while a new run waits for its first row", () => {
const timestamp = new Date();
const tail: StreamItem[] = [
+24 -2
View File
@@ -9,7 +9,14 @@ import {
type ToolCallDetailLevel,
type ToolCallDetailProjection,
} from "@/tool-calls/detail-level/projection";
import type { StreamItem, UserMessageItem } from "@/types/stream";
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import { legacyAgentNotificationToolCall } from "@getpaseo/protocol/paseo-tool-presentation/index";
import {
isAgentToolCallItem,
type AgentToolCallItem,
type StreamItem,
type UserMessageItem,
} from "@/types/stream";
import { collapseTurns, type TurnCollapse } from "./turn-collapse/model";
import type { ReadingRowReplacements } from "./reading-anchor";
@@ -56,6 +63,7 @@ const NO_COLLAPSED_TURNS: StreamPresentation["turns"] = collapseTurns({
/** Source messages reach plugins before display projection. */
export function createStreamPresentation() {
const userMessageCache = new WeakMap<UserMessageItem, UserMessageItem>();
const legacyNotificationCache = new WeakMap<AgentToolCallItem, AgentToolCallItem>();
function presentUserMessage(item: UserMessageItem): UserMessageItem {
const cached = userMessageCache.get(item);
@@ -72,6 +80,19 @@ export function createStreamPresentation() {
return projected;
}
// COMPAT(agentNotificationMetadata): added in v0.18.1, remove after 2027-06-01.
function presentLegacyNotification(item: AgentToolCallItem, message: AgentMessage): StreamItem {
const cached = legacyNotificationCache.get(item);
if (cached) return cached;
const { agentMessage: _legacy, ...data } = item.payload.data;
const presented: AgentToolCallItem = {
...item,
payload: { source: "agent", data: { ...data, ...legacyAgentNotificationToolCall(message) } },
};
legacyNotificationCache.set(item, presented);
return presented;
}
let historySource: StreamItem[] | undefined;
let historyTransform: TimelineItemTransform | undefined;
let historyRows: StreamItem[] = [];
@@ -86,7 +107,7 @@ export function createStreamPresentation() {
let collapsed: TurnCollapse | undefined;
function presentRows(item: StreamItem): StreamItem[] {
if (item.kind === "tool_call" && item.payload.source === "agent") {
if (isAgentToolCallItem(item)) {
const message = item.payload.data.agentMessage;
if (message?.event === "message") {
return [
@@ -101,6 +122,7 @@ export function createStreamPresentation() {
},
];
}
if (message) return [presentLegacyNotification(item, message)];
}
return [item.kind === "user_message" ? presentUserMessage(item) : item];
}
@@ -162,11 +162,12 @@ describe("collapseTurns", () => {
create.payload.data.detail = { type: "unknown", input: { title: "Side fix" }, output: null };
const finished = shell("finished");
if (finished.payload.source !== "agent") throw new Error("Expected agent tool");
finished.payload.data.name = "agent_notification";
finished.payload.data.agentMessage = {
event: "finished",
sender: { id: "worker", title: "PR helper" },
finished.payload.data.name = "agent_finished";
finished.payload.data.detail = {
type: "plain_text",
label: "PR helper",
text: "Finished",
icon: "bot",
};
const items: StreamItem[] = [
user("u1"),
@@ -77,11 +77,8 @@ describe("canonical turn membership", () => {
delete trigger.turnId;
expect(continuesTurn(previous, trigger)).toBe(false);
trigger.payload.data.name = "agent_message";
trigger.payload.data.agentMessage = {
event: "finished",
sender: { id: "worker" },
text: "Done",
};
expect(continuesTurn(previous, trigger)).toBe(false);
trigger.payload.data.name = "agent_finished";
expect(continuesTurn(previous, trigger)).toBe(false);
});
-1
View File
@@ -827,7 +827,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
cwd={context.cwd}
serverId={resolvedServerId}
metadata={data.metadata}
agentMessage={data.agentMessage}
isLastInSequence={isLastInSequence}
onOpenFilePath={handleToolCallOpenFile}
standalone={options.standalone}
+1 -5
View File
@@ -2331,7 +2331,6 @@ function areExpandableBadgePropsEqual(previous: ExpandableBadgeProps, next: Expa
}
interface ToolCallProps {
agentMessage?: AgentMessage;
serverId?: string;
toolName: string;
args?: unknown;
@@ -2354,7 +2353,6 @@ interface ToolCallProps {
}
export const ToolCall = memo(function ToolCall({
agentMessage,
serverId,
toolName,
args,
@@ -2403,7 +2401,6 @@ export const ToolCall = memo(function ToolCall({
const presentation = useMemo(
() =>
buildToolCallPresentation({
agentMessage,
toolName,
status,
error: error ?? null,
@@ -2413,7 +2410,7 @@ export const ToolCall = memo(function ToolCall({
targetAgentTitle,
resolveIcon: resolveToolCallIcon,
}),
[toolName, status, error, effectiveDetail, metadata, cwd, agentMessage, targetAgentTitle],
[toolName, status, error, effectiveDetail, metadata, cwd, targetAgentTitle],
);
const handleOpenFile = useMemo(() => {
const openFilePath = presentation.openFilePath;
@@ -2524,7 +2521,6 @@ export const ToolCall = memo(function ToolCall({
function areToolCallPropsEqual(previous: ToolCallProps, next: ToolCallProps) {
if (previous.toolName !== next.toolName) return false;
if (previous.serverId !== next.serverId) return false;
if (previous.agentMessage !== next.agentMessage) return false;
if (previous.args !== next.args) return false;
if (previous.result !== next.result) return false;
if (previous.error !== next.error) return false;
@@ -1,11 +1,10 @@
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import type { ToolCallDetail } from "@getpaseo/protocol/agent-types";
import { describe, expect, it } from "vitest";
import { buildToolCallPresentation, type ToolCallPresentationIcon } from "./presentation";
const fakeIcons = {
paseo: (() => null) as ToolCallPresentationIcon,
bot: (() => null) as ToolCallPresentationIcon,
brain: (() => null) as ToolCallPresentationIcon,
eye: (() => null) as ToolCallPresentationIcon,
wrench: (() => null) as ToolCallPresentationIcon,
@@ -14,10 +13,9 @@ const fakeIcons = {
function fakeResolveIcon(
toolName: string,
detail: ToolCallDetail | undefined,
agentMessage: AgentMessage | undefined,
): ToolCallPresentationIcon {
if (agentMessage) {
return fakeIcons.paseo;
if (detail?.type === "plain_text" && detail.icon === "bot") {
return fakeIcons.bot;
}
if (detail?.type === "plan") {
return fakeIcons.brain;
@@ -118,46 +116,29 @@ describe("tool-call presentation", () => {
});
it.each([
["message", "Message received"],
["finished", "Agent finished"],
["errored", "Agent errored"],
["permission-required", "Agent needs permission"],
["closed", "Agent closed"],
] as const)(
"presents %s with a fixed label, the sender as context, and the Paseo icon",
(event, heading) => {
const presentation = buildToolCallPresentation({
toolName: "internal_name_should_not_be_visible",
status: "completed",
error: null,
detail: { type: "plain_text", label: "legacy summary", text: "legacy body", icon: "bot" },
agentMessage: {
event,
sender: { id: "server::sender", title: "QA messenger" },
text: "The delivered message.",
},
resolveIcon: fakeResolveIcon,
});
expect(presentation.displayName).toBe(heading);
expect(presentation.summary).toBe("QA messenger");
expect(presentation.icon).toBe(fakeIcons.paseo);
expect(presentation.detail).toEqual({
type: "plain_text",
text: "From agent: server::sender\n\nThe delivered message.",
});
},
);
it("uses an opaque sender ID when no title is available", () => {
["agent_finished", "Agent finished"],
["agent_errored", "Agent errored"],
["agent_needs_permission", "Agent needs permission"],
["agent_closed", "Agent closed"],
] as const)("presents the %s notification from its plain-text detail", (toolName, heading) => {
const detail = {
type: "plain_text" as const,
label: "QA messenger",
text: "The delivered notification.",
icon: "bot" as const,
};
const presentation = buildToolCallPresentation({
toolName: "agent_message",
toolName,
status: "completed",
error: null,
agentMessage: { event: "message", sender: { id: "remote::worker" }, text: "Hello" },
detail,
resolveIcon: fakeResolveIcon,
});
expect(presentation.displayName).toBe("Message received");
expect(presentation.summary).toBe("remote::worker");
expect(presentation.displayName).toBe(heading);
expect(presentation.summary).toBe("QA messenger");
expect(presentation.icon).toBe(fakeIcons.bot);
expect(presentation.detail).toEqual(detail);
expect(presentation.canOpenDetails).toBe(true);
});
it("shows the target agent title as context for Paseo agent tools", () => {
+2 -9
View File
@@ -1,5 +1,3 @@
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import { buildAgentMessageDisplay } from "@getpaseo/protocol/paseo-tool-presentation/index";
import type { PlanOutcome } from "@/components/plan-card";
import type { ComponentType } from "react";
import type { ToolCallDetail } from "@getpaseo/protocol/agent-types";
@@ -15,7 +13,6 @@ type ToolCallStatus = "executing" | "running" | "completed" | "failed" | "cancel
export type ToolCallPresentationIcon = ComponentType<{ size?: number; color?: string }>;
interface BuildToolCallPresentationInput {
agentMessage?: AgentMessage;
toolName: string;
status: ToolCallStatus;
error: unknown;
@@ -43,7 +40,6 @@ export interface ToolCallPresentation {
export type ToolCallIconResolver = (
toolName: string,
detail: ToolCallDetail | undefined,
agentMessage: AgentMessage | undefined,
) => ToolCallPresentationIcon;
function displayStatus(status: ToolCallStatus): ToolCallDisplayInput["status"] {
@@ -57,13 +53,10 @@ function displayDetail(detail: ToolCallDetail | undefined): ToolCallDetail {
export function buildToolCallPresentation(
input: BuildToolCallPresentationInput,
): ToolCallPresentation {
const detail = input.agentMessage
? buildAgentMessageDisplay(input.agentMessage).detail
: input.detail;
const detail = input.detail;
const detailForDisplay = displayDetail(detail);
const displayModel = buildToolCallDisplayModel({
name: input.toolName,
agentMessage: input.agentMessage,
status: displayStatus(input.status),
error: input.error ?? null,
detail: detailForDisplay,
@@ -83,7 +76,7 @@ export function buildToolCallPresentation(
displayName: displayModel.displayName,
summary: displayModel.summary,
errorText: displayModel.errorText,
icon: input.resolveIcon(input.toolName, detail, input.agentMessage),
icon: input.resolveIcon(input.toolName, detail),
isLoadingDetails,
hasDetails,
canOpenDetails: hasDetails || isLoadingDetails,
@@ -54,13 +54,9 @@ describe("resolveToolCallIconName", () => {
expect(icon).toBe("wrench");
});
it("uses the Paseo icon for agent messages despite the legacy bot detail icon", () => {
const icon = resolveToolCallIconName(
"agent_message",
{ type: "plain_text", text: "Done.", icon: "bot" },
{ event: "finished", sender: { id: "agt_1" }, text: "Done." },
);
expect(icon).toBe("paseo");
it("uses the plain-text icon a daemon notification names", () => {
expect(
resolveToolCallIconName("agent_finished", { type: "plain_text", text: "Done.", icon: "bot" }),
).toBe("bot");
});
});
+1 -10
View File
@@ -1,4 +1,3 @@
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import type { ToolCallDetail, ToolCallIconName } from "@getpaseo/protocol/agent-types";
import { isPaseoToolName } from "@getpaseo/protocol/tool-name-normalization";
@@ -18,15 +17,7 @@ const TOOL_DETAIL_ICON_NAMES: Record<ToolCallDetail["type"], ToolCallIcon> = {
unknown: "wrench",
};
export function resolveToolCallIconName(
toolName: string,
detail?: ToolCallDetail,
agentMessage?: AgentMessage,
): ToolCallIcon {
// Agent messages are Paseo deliveries; the wire detail's legacy "bot" icon is for old clients.
if (agentMessage) {
return "paseo";
}
export function resolveToolCallIconName(toolName: string, detail?: ToolCallDetail): ToolCallIcon {
const lowerName = toolName.trim().toLowerCase();
if (detail?.type === "plain_text" && detail.icon) {
+1 -3
View File
@@ -10,7 +10,6 @@ import {
SquareTerminal,
Wrench,
} from "lucide-react-native";
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import type { ToolCallDetail } from "@getpaseo/protocol/agent-types";
import { PaseoLogo } from "@/components/icons/paseo-logo";
import { resolveToolCallIconName, type ToolCallIcon } from "./tool-call-icon-name";
@@ -37,7 +36,6 @@ export function componentForToolCallIcon(name: ToolCallIcon): ToolCallIconCompon
export function resolveToolCallIcon(
toolName: string,
detail?: ToolCallDetail,
agentMessage?: AgentMessage,
): ToolCallIconComponent {
return componentForToolCallIcon(resolveToolCallIconName(toolName, detail, agentMessage));
return componentForToolCallIcon(resolveToolCallIconName(toolName, detail));
}
@@ -1,31 +1,30 @@
import type { AgentMessage } from "../agent-message.js";
import type { ToolCallDetail } from "../agent-types.js";
import { toSummaryText } from "./summary-text.js";
export interface AgentMessageDisplay {
displayName: string;
summary?: string;
detail: ToolCallDetail;
}
/** Events read noun-first ("Agent finished"); the sender goes in the summary. */
const EVENT_LABELS: Record<AgentMessage["event"], string> = {
message: "Message received",
finished: "Agent finished",
errored: "Agent errored",
"permission-required": "Agent needs permission",
closed: "Agent closed",
const LEGACY_NOTIFICATION_TOOL_NAMES: Record<Exclude<AgentMessage["event"], "message">, string> = {
finished: "agent_finished",
errored: "agent_errored",
"permission-required": "agent_needs_permission",
closed: "agent_closed",
};
/** Presentation shared by clients; never used to encode provider prompts. */
export function buildAgentMessageDisplay(message: AgentMessage): AgentMessageDisplay {
const summary = toSummaryText(message.sender.title ?? message.sender.id);
/**
* COMPAT(agentNotificationMetadata): added in v0.18.1, remove after 2027-06-01. Older daemons,
* and rows they persisted, send lifecycle notifications as `agent_message` calls with
* `agentMessage` metadata. Current daemons send the plain tool call this returns.
* Returns null for a peer message, which keeps its metadata.
*/
export function legacyAgentNotificationToolCall(
message: AgentMessage,
): { name: string; detail: ToolCallDetail } | null {
if (message.event === "message") return null;
return {
displayName: EVENT_LABELS[message.event],
...(summary ? { summary } : {}),
name: LEGACY_NOTIFICATION_TOOL_NAMES[message.event],
detail: {
type: "plain_text",
text: `From agent: ${message.sender.id}\n\n${message.text}`,
label: message.sender.title ?? message.sender.id,
text: message.text,
icon: "bot",
},
};
}
@@ -1,12 +1,13 @@
import { describe, expect, it } from "vitest";
import {
buildAgentMessageDisplay,
legacyAgentNotificationToolCall,
buildPaseoToolDisplay,
getPaseoToolTargetAgentId,
MAX_SUMMARY_CHARS,
PASEO_TOOL_NAMES,
} from "./index.js";
import { buildToolCallDisplayModel } from "../tool-call-display.js";
function display(toolName: string, input: unknown, targetAgentTitle?: string) {
return buildPaseoToolDisplay({
@@ -115,34 +116,38 @@ describe("Paseo tool display", () => {
});
});
describe("agent message display", () => {
describe("legacy agent notifications", () => {
it.each([
["message", "Message received"],
["finished", "Agent finished"],
["errored", "Agent errored"],
["permission-required", "Agent needs permission"],
["closed", "Agent closed"],
] as const)("labels %s noun-first with the sender as context", (event, label) => {
const result = buildAgentMessageDisplay({
event,
sender: { id: "srv::agt_1", title: "QA messenger" },
text: "Done.",
});
expect(result.displayName).toBe(label);
expect(result.summary).toBe("QA messenger");
expect(result.detail).toEqual({ type: "plain_text", text: "From agent: srv::agt_1\n\nDone." });
});
["finished", "agent_finished", "Agent finished"],
["errored", "agent_errored", "Agent errored"],
["permission-required", "agent_needs_permission", "Agent needs permission"],
["closed", "agent_closed", "Agent closed"],
] as const)(
"reads a %s notification as the plain tool call daemons now send",
(event, name, label) => {
const call = legacyAgentNotificationToolCall({
event,
sender: { id: "srv::agt_1", title: "QA messenger" },
text: "Done.",
});
expect(call).toEqual({
name,
detail: { type: "plain_text", label: "QA messenger", text: "Done.", icon: "bot" },
});
expect(buildToolCallDisplayModel({ ...call!, status: "completed", error: null })).toEqual({
displayName: label,
summary: "QA messenger",
});
},
);
it("falls back to the sender ID and truncates a long title", () => {
it("names the sender ID without a title and leaves peer messages alone", () => {
expect(
buildAgentMessageDisplay({ event: "finished", sender: { id: "srv::agt_1" }, text: "" })
.summary,
).toBe("srv::agt_1");
const summary = buildAgentMessageDisplay({
event: "finished",
sender: { id: "a", title: "t".repeat(500) },
text: "",
}).summary;
expect(summary).toHaveLength(MAX_SUMMARY_CHARS);
legacyAgentNotificationToolCall({ event: "closed", sender: { id: "srv::agt_1" }, text: "" })
?.detail,
).toMatchObject({ label: "srv::agt_1" });
expect(
legacyAgentNotificationToolCall({ event: "message", sender: { id: "a" }, text: "Hi" }),
).toBeNull();
});
});
@@ -3,7 +3,7 @@ import { getPaseoToolLeafName, isPaseoToolName } from "../tool-name-normalizatio
import { getPaseoToolEntry, PASEO_TOOL_CATALOG, type PaseoToolName } from "./catalog.js";
import { toSummaryText } from "./summary-text.js";
export { buildAgentMessageDisplay, type AgentMessageDisplay } from "./agent-message.js";
export { legacyAgentNotificationToolCall } from "./agent-message.js";
export {
buildPaseoToolDetailSections,
type PaseoToolDetailField,
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { isTimelineTurnTrigger } from "./timeline-turn.js";
describe("timeline turn triggers", () => {
it.each([
"heartbeat",
"agent_message",
"agent_finished",
"agent_errored",
"agent_needs_permission",
"agent_closed",
])("a delivered %s prompt starts a turn", (name) => {
expect(isTimelineTurnTrigger({ type: "tool_call", name })).toBe(true);
});
it("an ordinary tool call stays inside its turn", () => {
expect(isTimelineTurnTrigger({ type: "tool_call", name: "Bash" })).toBe(false);
expect(isTimelineTurnTrigger({ type: "user_message" })).toBe(true);
});
});
+14 -6
View File
@@ -12,13 +12,21 @@ export function continuesTimelineTurn(
return !nextIsTrigger;
}
export function isTimelineTurnTrigger(item: {
type: string;
name?: string;
agentMessage?: unknown;
}): boolean {
/** Tool calls the daemon projects from prompts it delivered: schedules, messages, notifications. */
const DELIVERED_PROMPT_TOOL_NAMES: ReadonlySet<string> = new Set([
"heartbeat",
"agent_message",
"agent_finished",
"agent_errored",
"agent_needs_permission",
"agent_closed",
]);
export function isTimelineTurnTrigger(item: { type: string; name?: string }): boolean {
return (
item.type === "user_message" ||
(item.type === "tool_call" && (item.agentMessage !== undefined || item.name === "heartbeat"))
(item.type === "tool_call" &&
item.name !== undefined &&
DELIVERED_PROMPT_TOOL_NAMES.has(item.name))
);
}
+7 -12
View File
@@ -1,13 +1,10 @@
import type { ToolCallTimelineItem } from "./agent-types.js";
import {
buildAgentMessageDisplay,
buildPaseoToolDisplay,
} from "./paseo-tool-presentation/index.js";
import { buildPaseoToolDisplay } from "./paseo-tool-presentation/index.js";
import { stripCwdPrefix } from "./path-utils.js";
export type ToolCallDisplayInput = Pick<
ToolCallTimelineItem,
"name" | "status" | "error" | "metadata" | "detail" | "agentMessage"
"name" | "status" | "error" | "metadata" | "detail"
> & {
cwd?: string;
/** Title of the agent a Paseo call targets, when the caller knows it. */
@@ -151,13 +148,11 @@ function buildUnknownDetailOverride(input: ToolCallDisplayInput): DetailDisplay
export function buildToolCallDisplayModel(input: ToolCallDisplayInput): ToolCallDisplayModel {
const errorText = input.status === "failed" ? formatErrorText(input.error) : undefined;
const paseoDisplay = input.agentMessage
? buildAgentMessageDisplay(input.agentMessage)
: buildPaseoToolDisplay({
toolName: input.name,
detail: input.detail,
targetAgentTitle: input.targetAgentTitle,
});
const paseoDisplay = buildPaseoToolDisplay({
toolName: input.name,
detail: input.detail,
targetAgentTitle: input.targetAgentTitle,
});
if (paseoDisplay) {
return {
displayName: paseoDisplay.displayName,
@@ -118,10 +118,38 @@ describe("curateAgentActivity", () => {
{ kind: "agent-notification", agentId: "agt_child", event: "finished" },
"Child is done.",
),
delivered(
{
kind: "agent-notification",
agentId: "agt_child",
title: "Child",
event: "permission-required",
},
"Child needs approval.",
),
// A row an older daemon persisted with notification metadata.
{
type: "tool_call",
callId: "legacy",
name: "agent_message",
status: "completed",
error: null,
agentMessage: { event: "errored", sender: { id: "agt_old" }, text: "Old failure." },
detail: { type: "plain_text", text: "Old failure.", icon: "bot" },
},
];
expect(curateAgentActivity(timeline)).toBe(
"[Message received] CI lead\nTake ownership.\nRead the handoff.\n[Agent finished] agt_child\nChild is done.",
[
"[Message received] CI lead",
"Take ownership.\nRead the handoff.",
"[Agent finished] agt_child",
"Child is done.",
"[Agent needs permission] Child",
"Child needs approval.",
"[Agent errored] agt_old",
"Old failure.",
].join("\n"),
);
});
@@ -1,9 +1,9 @@
import type { AgentTimelineItem, ToolCallTimelineItem } from "./agent-sdk-types.js";
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import type { AgentAttachment } from "@getpaseo/protocol/messages";
import type { AgentTimelineRow } from "./agent-timeline-store-types.js";
import { isLikelyExternalToolName } from "@getpaseo/protocol/tool-name-normalization";
import { buildAgentMessageDisplay } from "@getpaseo/protocol/paseo-tool-presentation/index";
import { legacyAgentNotificationToolCall } from "@getpaseo/protocol/paseo-tool-presentation/index";
import { isTimelineTurnTrigger } from "@getpaseo/protocol/timeline-turn";
import { buildToolCallDisplayModel } from "@getpaseo/protocol/tool-call-display";
import { projectTimelineRows, selectItemsByProjectedLimit } from "./timeline-projection.js";
@@ -127,17 +127,30 @@ function formatToolCallEntry(
return activityEntry(summary ? `[${displayName}] ${summary}` : `[${displayName}]`);
}
function appendAgentMessageEntries(entries: ActivityEntry[], message: AgentMessage) {
const display = buildAgentMessageDisplay(message);
entries.push(
activityEntry(
display.summary ? `[${display.displayName}] ${display.summary}` : `[${display.displayName}]`,
),
);
const body = message.text.trim();
function appendBody(entries: ActivityEntry[], text: string | undefined) {
const body = text?.trim();
if (body) entries.push(activityEntry(body));
}
function appendToolCallEntries(
entries: ActivityEntry[],
item: ToolCallTimelineItem,
options?: ActivityCuratorOptions,
) {
if (item.agentMessage?.event === "message") {
const sender = item.agentMessage.sender;
entries.push(activityEntry(`[Message received] ${sender.title ?? sender.id}`));
appendBody(entries, item.agentMessage.text);
return;
}
const legacy = item.agentMessage ? legacyAgentNotificationToolCall(item.agentMessage) : null;
const call = legacy ? { ...item, ...legacy } : item;
entries.push(formatToolCallEntry(call, options));
// A prompt the daemon delivered is read in full, like a person's prompt.
if (isTimelineTurnTrigger(call) && call.detail.type === "plain_text")
appendBody(entries, call.detail.text);
}
function curateProjectedActivityEntries(
items: readonly AgentTimelineItem[],
options?: ActivityCuratorOptions,
@@ -164,14 +177,9 @@ function curateProjectedActivityEntries(
case "reasoning":
appendTextEntry(entries, item, options);
break;
case "tool_call": {
if (item.agentMessage) {
appendAgentMessageEntries(entries, item.agentMessage);
break;
}
entries.push(formatToolCallEntry(item, options));
case "tool_call":
appendToolCallEntries(entries, item, options);
break;
}
case "todo":
entries.push(activityEntry("[Tasks]"));
for (const entry of item.items) {
@@ -14878,24 +14878,18 @@ test.each(["live", "history", "accepted"] as const)(
manager
.getTimeline(agent.id)
.filter((row) => row.type === "tool_call")
.map((row) => ({ callId: row.callId, agentMessage: row.agentMessage })),
.map((row) => ({ callId: row.callId, name: row.name, agentMessage: row.agentMessage })),
).toEqual([
{
callId: "paseo-agent-message:report",
name: "agent_message",
agentMessage: {
event: "message",
sender: { id: "worker", serverId: "remote-host" },
text: "Result <ready>",
},
},
{
callId: "paseo-agent-message:finish",
agentMessage: {
event: "finished",
sender: { id: "worker", serverId: "remote-host" },
text: "Worker finished",
},
},
{ callId: "paseo-agent-message:finish", name: "agent_finished", agentMessage: undefined },
]);
expect(manager.getTimeline(agent.id).filter((row) => row.type === "user_message")).toEqual(
[],
@@ -266,12 +266,12 @@ test("batches retain each sender's attachment context and image order", async ()
expect(prompt).toEqual([
{
type: "text",
text: '<paseo-system version="1" kind="agent-message" source-agent-id="one" message-id="first">\nFirst\n</paseo-system>',
text: 'First\n\n<paseo-message kind="agent-message" message-id="first" source-agent-id="one" length="5"/>',
},
firstImage,
{
type: "text",
text: '<paseo-system version="1" kind="agent-message" source-agent-id="two" message-id="second">\nSecond\n\nGitHub Issue #42: Context\nhttps://example.com/42\n\nAttached\n</paseo-system>',
text: 'Second\n\nGitHub Issue #42: Context\nhttps://example.com/42\n\nAttached\n\n<paseo-message kind="agent-message" message-id="second" source-agent-id="two" length="66"/>',
},
secondImage,
]);
@@ -519,7 +519,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
unarchive: direct.unarchive !== false,
};
}
// Sharing a prompt with queued messages, each entry needs its own envelope to stay
// Sharing a prompt with queued messages, each entry needs its own marker to stay
// a separate row with its own identity.
const own = envelopeMessage(direct.prompt, direct.source ?? null, direct.messageId);
return {
@@ -0,0 +1,342 @@
import { createHash } from "node:crypto";
import { AgentTimelineItemPayloadSchema } from "@getpaseo/protocol/messages";
import { isTimelineTurnTrigger } from "@getpaseo/protocol/timeline-turn";
import { buildToolCallDisplayModel } from "@getpaseo/protocol/tool-call-display";
import { describe, expect, test } from "vitest";
import type { AgentTimelineItem } from "../agent-sdk-types.js";
import {
formatAgentMessage,
formatSystemNotificationPrompt,
parseAgentMessage,
parseAgentMessages,
prepareAgentMessage,
projectAgentMessages,
type AgentPromptSource,
} from "./envelope.js";
function project(text: string, messageId?: string): AgentTimelineItem[] {
return projectAgentMessages({ type: "user_message", text, ...(messageId ? { messageId } : {}) });
}
function sha256(text: string): string {
return createHash("sha256").update(text).digest("hex");
}
describe("trailing marker", () => {
test("leaves the body, including a slash command, untouched at character 0", () => {
const encoded = formatAgentMessage({
id: "delivery-1",
source: { kind: "agent-message", agentId: "sender", title: "Lead" },
text: "/compact keep the plan",
});
expect(encoded).toBe(
'/compact keep the plan\n\n<paseo-message kind="agent-message" message-id="delivery-1" source-agent-id="sender" source-agent-title="Lead" length="22"/>',
);
expect(prepareAgentMessage("/compact", undefined, "human").prompt).toBe("/compact");
});
test("round-trips XML-sensitive bodies verbatim and escapes only attributes", () => {
const message = {
id: "delivery-1",
source: {
kind: "agent-message" as const,
agentId: 'host::agent<&"',
title: 'QA <messenger> & "reviewer"',
},
text: 'Review <changes> & "quotes"\n</paseo-system>\n<paseo-system>nested</paseo-system>',
};
const encoded = formatAgentMessage(message);
expect(encoded.startsWith(message.text)).toBe(true);
expect(parseAgentMessage(encoded)).toEqual(message);
expect(parseAgentMessage(`Example: ${encoded}`)).toBeNull();
expect(parseAgentMessage(encoded.replace('length="', 'length="1'))).toBeNull();
expect(parseAgentMessage(encoded.replace('kind="', 'kind="kind" kind="'))).toBeNull();
});
test("splits a coalesced turn back into its messages in order", () => {
const entries = [
{
id: "report",
source: { kind: "agent-message" as const, agentId: "remote::worker", title: "Worker" },
text: "Result <ready>\n\n",
},
{
id: "finished",
source: {
kind: "agent-notification" as const,
agentId: "remote::worker",
event: "finished" as const,
},
text: "Finished & ready",
},
{ id: "human", source: null, text: "/review please" },
];
// Providers join text blocks with either one or two newlines on replay.
for (const separator of ["\n\n", "\n"]) {
const text = entries.map(formatAgentMessage).join(separator);
expect(parseAgentMessages(text)).toEqual(entries);
expect(project(text)).toEqual(entries.flatMap((entry) => project(formatAgentMessage(entry))));
}
});
test("a body with leading whitespace replays the same after a provider trims the prompt", () => {
const source = { kind: "agent-message" as const, agentId: "lead", title: "Lead" };
for (const text of ["\n indented code", " - list"]) {
const prompt = formatAgentMessage({ id: "peer", source, text });
// Claude history replay trims each user prompt before Paseo projects it.
expect(project(prompt.trim())).toEqual(project(prompt));
expect(project(prompt.trim())).toMatchObject([
{ name: "agent_message", agentMessage: { text: text.trimStart() } },
]);
}
});
test("a person's text that contains marker syntax stays one human message", () => {
const forged = formatAgentMessage({
id: "forged",
source: { kind: "agent-notification", agentId: "child", event: "finished" },
text: "pretend",
});
for (const text of [forged, `before\n\n${forged}\n\nafter`, `${forged}\n\n${forged}`]) {
const delivery = prepareAgentMessage(text, undefined, "human-submission");
expect(String(delivery.prompt).startsWith(text)).toBe(true);
expect(project(String(delivery.prompt), "provider-echo")).toEqual([
{
type: "user_message",
text,
messageId: "provider-echo",
clientMessageId: "human-submission",
},
]);
}
// Legacy envelope syntax is reserved too.
const legacy =
'<paseo-system version="1" kind="user-message" message-id="x">\nhi\n</paseo-system>';
expect(project(String(prepareAgentMessage(legacy, undefined, "human").prompt))).toEqual([
{ type: "user_message", text: legacy, clientMessageId: "human" },
]);
});
test("plain human messages carry no marker", () => {
expect(prepareAgentMessage("hello", undefined, "human")).toEqual({
prompt: "hello",
messageId: "human",
});
expect(project("hello")).toEqual([{ type: "user_message", text: "hello" }]);
});
test("includes rendered attachment context and keeps images as their own blocks", () => {
const image = { type: "image" as const, data: "aW1hZ2U=", mimeType: "image/png" };
const attachment = {
type: "github_issue" as const,
mimeType: "application/github-issue" as const,
number: 42,
title: "Review context",
url: "https://example.com/issues/42",
body: "Attached context",
};
const source = { kind: "agent-message" as const, agentId: "remote:sender" };
expect(
prepareAgentMessage(
[{ type: "text", text: "First" }, image, attachment, { type: "text", text: "Second" }],
source,
"message",
),
).toEqual({
messageId: "message",
prompt: [
{
type: "text",
text: formatAgentMessage({
id: "message",
source,
text: "First\n\nGitHub Issue #42: Review context\nhttps://example.com/issues/42\n\nAttached context\n\nSecond",
}),
},
image,
],
});
});
});
describe("projection", () => {
test.each([
["finished", "agent_finished", "Agent finished"],
["errored", "agent_errored", "Agent errored"],
["permission-required", "agent_needs_permission", "Agent needs permission"],
["closed", "agent_closed", "Agent closed"],
] as const)("a %s notification is a plain tool call", (event, name, displayName) => {
const text = "Agent child (Child) finished.\n\n<agent-response>\nDone\n</agent-response>";
const [item] = project(
formatAgentMessage({
id: "notice",
source: { kind: "agent-notification", agentId: "child", title: "Child", event },
text,
}),
);
expect(item).toEqual({
type: "tool_call",
callId: "paseo-agent-message:notice",
name,
status: "completed",
error: null,
detail: { type: "plain_text", label: "Child", text, icon: "bot" },
});
// The existing wire shape carries it whole, and every client renders it from these fields.
expect(AgentTimelineItemPayloadSchema.parse(item)).toEqual(item);
expect(isTimelineTurnTrigger(item!)).toBe(true);
if (item?.type !== "tool_call") throw new Error("Expected a tool call");
expect(buildToolCallDisplayModel(item)).toEqual({ displayName, summary: "Child" });
});
test("a notification without a title names the sender ID", () => {
const [item] = project(
formatAgentMessage({
id: "notice",
source: { kind: "agent-notification", agentId: "srv::child", event: "closed" },
text: "Closed",
}),
);
expect(item).toMatchObject({ detail: { label: "srv::child" } });
});
test("a peer message keeps its sender for the Sent by bubble", () => {
const [item] = project(
formatAgentMessage({
id: "peer",
source: { kind: "agent-message", agentId: "lead", serverId: "srv", title: "Lead" },
text: "Take over",
}),
);
expect(item).toEqual({
type: "tool_call",
callId: "paseo-agent-message:peer",
name: "agent_message",
status: "completed",
error: null,
agentMessage: {
event: "message",
sender: { id: "lead", serverId: "srv", title: "Lead" },
text: "Take over",
},
detail: { type: "plain_text", text: "Take over", icon: "bot" },
});
expect(isTimelineTurnTrigger(item!)).toBe(true);
});
test("schedule prompts are heartbeat tool calls with a stable identity", () => {
const text = formatSystemNotificationPrompt("Schedule fired (id=heartbeat, run=run-1).");
expect(text.startsWith("Schedule fired")).toBe(true);
const items = project(text, "fire-1");
expect(items).toEqual([
{
type: "tool_call",
callId: expect.stringMatching(/^paseo-system:/),
name: "heartbeat",
status: "completed",
error: null,
detail: {
type: "plain_text",
text: "Schedule fired (id=heartbeat, run=run-1).",
icon: "sparkles",
},
},
]);
expect(project(text, "provider-message")).toEqual(items);
});
test("change request updates name their URL", () => {
const source: AgentPromptSource = {
kind: "change-request-update",
url: "https://github.com/o/r/pull/1",
};
expect(project(formatAgentMessage({ id: "cr", source, text: "CI green" }))).toEqual([
{
type: "tool_call",
callId: "paseo-change-request:cr",
name: "change_request_update",
status: "completed",
error: null,
detail: { type: "plain_text", label: "https://github.com/o/r/pull/1", text: "CI green" },
},
]);
});
});
// COMPAT(leadingPaseoSystemEnvelope): transcripts written before trailing markers.
describe("legacy envelopes in provider transcripts", () => {
const legacy = (attributes: string, body: string) =>
`<paseo-system version="1" ${attributes}>\n${body}\n</paseo-system>`;
test("a legacy batch projects like the trailing markers that replaced it", () => {
const text = [
legacy(
'kind="agent-message" source-agent-id="lead" message-id="m1" source-agent-title="Lead &amp; co"',
"Review &lt;this&gt;",
),
legacy(
'kind="agent-notification" source-agent-id="child" message-id="m2" source-agent-title="Child" event="finished"',
"Done",
),
// #10864 sent a child's interim turn-end notice with the neutral "message" event.
legacy(
'kind="agent-notification" source-agent-id="child" message-id="m3" source-agent-title="Child" event="message"',
"Still going",
),
legacy('kind="change-request-update" source-url="https://x.test/pr/1" message-id="m4"', "CI"),
legacy('kind="user-message" message-id="m5"', "/goal pause"),
].join("\n\n");
const current = [
{
id: "m1",
source: { kind: "agent-message" as const, agentId: "lead", title: "Lead & co" },
text: "Review <this>",
},
{
id: "m2",
source: {
kind: "agent-notification" as const,
agentId: "child",
title: "Child",
event: "finished" as const,
},
text: "Done",
},
{
id: "m3",
source: { kind: "agent-message" as const, agentId: "child", title: "Child" },
text: "Still going",
},
{
id: "m4",
source: { kind: "change-request-update" as const, url: "https://x.test/pr/1" },
text: "CI",
},
{ id: "m5", source: null, text: "/goal pause" },
];
expect(parseAgentMessages(text)).toEqual(current);
expect(project(text)).toEqual(current.flatMap((entry) => project(formatAgentMessage(entry))));
});
test("a legacy schedule envelope keeps its heartbeat identity", () => {
const text = "<paseo-system>\nSchedule fired (id=s, run=r).\n</paseo-system>";
expect(project(text)).toEqual([
{
type: "tool_call",
callId: `paseo-system:${sha256(text)}`,
name: "heartbeat",
status: "completed",
error: null,
detail: { type: "plain_text", text: "Schedule fired (id=s, run=r).", icon: "sparkles" },
},
]);
});
test("malformed legacy envelopes stay human text", () => {
const text = legacy('kind="agent-message" source-agent-id="a" message-id="m"', "a < b");
expect(project(text)).toEqual([{ type: "user_message", text }]);
expect(project(`Example: ${text}`)).toEqual([
{ type: "user_message", text: `Example: ${text}` },
]);
});
});
@@ -8,34 +8,64 @@ import type {
} from "../agent-sdk-types.js";
const agentIdSchema = z.string().min(1);
const sourceSchema = z.discriminatedUnion("kind", [
z.object({
kind: z.literal("change-request-update"),
url: z.url({ protocol: /^https?$/ }),
}),
z.object({
kind: z.literal("agent-message"),
agentId: agentIdSchema,
serverId: z.string().min(1).optional(),
title: z.string().min(1).optional(),
}),
z.object({
kind: z.literal("agent-notification"),
agentId: agentIdSchema,
serverId: z.string().min(1).optional(),
title: z.string().min(1).optional(),
// "message" reports a child that ended its turn but has not finished its work.
event: z.enum(["message", "finished", "errored", "permission-required", "closed"]),
}),
const changeRequestSourceSchema = z.object({
kind: z.literal("change-request-update"),
url: z.url({ protocol: /^https?$/ }),
});
const agentMessageSourceSchema = z.object({
kind: z.literal("agent-message"),
agentId: agentIdSchema,
serverId: z.string().min(1).optional(),
title: z.string().min(1).optional(),
});
const agentNotificationSourceSchema = z.object({
kind: z.literal("agent-notification"),
agentId: agentIdSchema,
serverId: z.string().min(1).optional(),
title: z.string().min(1).optional(),
event: z.enum(["finished", "errored", "permission-required", "closed"]),
});
/** Senders a delivery names. A schedule fire is marked by the schedule module alone. */
const promptSourceSchema = z.discriminatedUnion("kind", [
changeRequestSourceSchema,
agentMessageSourceSchema,
agentNotificationSourceSchema,
]);
export type AgentPromptSource = z.infer<typeof sourceSchema>;
const markedSourceSchema = z.discriminatedUnion("kind", [
changeRequestSourceSchema,
agentMessageSourceSchema,
agentNotificationSourceSchema,
z.object({ kind: z.literal("schedule") }),
]);
export type AgentPromptSource = z.infer<typeof promptSourceSchema>;
type MarkedSource = z.infer<typeof markedSourceSchema>;
type AgentNotificationEvent = z.infer<typeof agentNotificationSourceSchema>["event"];
interface AgentMessage {
id: string;
source: AgentPromptSource | null;
/** Null for a person's prompt that needs a marker to keep its own row. */
source: MarkedSource | null;
text: string;
}
/** Each notification is its own tool; clients render it from the name and plain-text detail. */
const NOTIFICATION_TOOL_NAMES: Record<AgentNotificationEvent, string> = {
finished: "agent_finished",
errored: "agent_errored",
"permission-required": "agent_needs_permission",
closed: "agent_closed",
};
/**
* A marker follows the text it describes, so the prompt's first character stays the sender's
* (a provider reads slash commands there) and the text needs no escaping. `length` bounds the
* text, so marker syntax inside a body can never split it.
*/
const MARKER_START = "\n\n<paseo-message ";
const MARKER_PATTERN = /^<paseo-message((?:\s+[a-z-]+="[^"<>]*")+)\/>$/;
/** A person's prompt containing this syntax gets its own marker so it replays as their text. */
const RESERVED_SYNTAX = /<paseo-(?:message|system)\b/;
function escapeXml(value: string): string {
return value.replace(/[&<>"']/g, (character) => {
switch (character) {
@@ -71,40 +101,51 @@ function unescapeXml(value: string): string | null {
});
}
export function formatAgentMessage(message: AgentMessage): string {
function markerAttributes(message: AgentMessage): Array<[string, string]> {
const { source } = message;
if (source?.kind === "change-request-update") {
return `<paseo-system version="1" kind="change-request-update" source-url="${escapeXml(source.url)}" message-id="${escapeXml(message.id)}">\n${escapeXml(message.text)}\n</paseo-system>`;
const attributes: Array<[string, string]> = [
["kind", source?.kind ?? "user-message"],
["message-id", message.id],
];
if (source?.kind === "agent-message" || source?.kind === "agent-notification") {
attributes.push(["source-agent-id", source.agentId]);
if (source.serverId) attributes.push(["source-server-id", source.serverId]);
if (source.title) attributes.push(["source-agent-title", source.title]);
}
const attributes = source
? `kind="${source.kind}" source-agent-id="${escapeXml(source.agentId)}"`
: 'kind="user-message"';
const server = source?.serverId ? ` source-server-id="${escapeXml(source.serverId)}"` : "";
const title = source?.title ? ` source-agent-title="${escapeXml(source.title)}"` : "";
const event = source?.kind === "agent-notification" ? ` event="${source.event}"` : "";
return `<paseo-system version="1" ${attributes} message-id="${escapeXml(message.id)}"${server}${title}${event}>\n${escapeXml(message.text)}\n</paseo-system>`;
if (source?.kind === "agent-notification") attributes.push(["event", source.event]);
if (source?.kind === "change-request-update") attributes.push(["source-url", source.url]);
attributes.push(["length", String(message.text.length)]);
return attributes;
}
export function parseAgentMessage(text: string): AgentMessage | null {
const envelope = /^<paseo-system((?:\s+[a-z-]+="[^"<>]*")+)>\n([\s\S]*)\n<\/paseo-system>$/.exec(
text,
);
if (!envelope) return null;
export function formatAgentMessage(message: AgentMessage): string {
// Providers trim a user prompt when they replay history, so the body never starts with
// whitespace; otherwise the replayed body would fall short of `length`.
const text = message.text.trimStart();
const attributes = markerAttributes({ ...message, text })
.map(([name, value]) => ` ${name}="${escapeXml(value)}"`)
.join("");
return `${text}\n\n<paseo-message${attributes}/>`;
}
function parseAttributes(raw: string): Map<string, string> | null {
const attributes = new Map<string, string>();
for (const match of envelope[1].matchAll(/\s+([a-z-]+)="([^"<>]*)"/g)) {
for (const match of raw.matchAll(/\s+([a-z-]+)="([^"<>]*)"/g)) {
const value = unescapeXml(match[2]);
if (value === null || attributes.has(match[1])) return null;
attributes.set(match[1], value);
}
if (attributes.get("version") !== "1") return null;
return attributes;
}
function toMessage(attributes: Map<string, string>, text: string): AgentMessage | null {
const id = attributes.get("message-id");
const body = unescapeXml(envelope[2]);
if (!id || body === null) return null;
if (!id) return null;
if (attributes.get("kind") === "user-message") {
if (attributes.has("source-agent-id") || attributes.has("event")) return null;
return { id, source: null, text: body };
return { id, source: null, text };
}
const source = sourceSchema.safeParse({
const source = markedSourceSchema.safeParse({
kind: attributes.get("kind"),
agentId: attributes.get("source-agent-id"),
serverId: attributes.get("source-server-id"),
@@ -112,18 +153,76 @@ export function parseAgentMessage(text: string): AgentMessage | null {
title: attributes.get("source-agent-title"),
url: attributes.get("source-url"),
});
if (!source.success) return null;
return { id, source: source.data, text: body };
return source.success ? { id, source: source.data, text } : null;
}
/** Accept only a complete sequence of envelopes; prose around them stays user text. */
export function parseAgentMessages(text: string): AgentMessage[] | null {
/** Reads markers from the end; each one claims the `length` characters before it. */
function parseMarkedMessages(text: string): AgentMessage[] | null {
const messages: AgentMessage[] = [];
let rest = text.replace(/\n+$/, "");
while (rest) {
const markerStart = rest.lastIndexOf(MARKER_START);
if (markerStart < 0) return null;
const marker = MARKER_PATTERN.exec(rest.slice(markerStart + 2));
const attributes = marker ? parseAttributes(marker[1]) : null;
const length = attributes?.get("length");
if (!attributes || !length || !/^\d+$/.test(length)) return null;
const bodyStart = markerStart - Number(length);
if (bodyStart < 0) return null;
const message = toMessage(attributes, rest.slice(bodyStart, markerStart));
if (!message) return null;
messages.unshift(message);
rest = rest.slice(0, bodyStart);
// Providers replay the joined text blocks of a batch with one or two newlines between them.
const previous = rest.replace(/\n+$/, "");
if (previous === rest && rest) return null;
rest = previous;
}
return messages.length ? messages : null;
}
// COMPAT(leadingPaseoSystemEnvelope): added in v0.18.1, remove after 2027-11-28. Provider
// transcripts written before trailing markers open with a <paseo-system> envelope.
const LEGACY_ENVELOPE = /^<paseo-system((?:\s+[a-z-]+="[^"<>]*")+)>\n([\s\S]*)\n<\/paseo-system>$/;
const LEGACY_SCHEDULE_ENVELOPE = /^<paseo-system>\n([\s\S]*)\n<\/paseo-system>$/;
function parseLegacyEnvelope(text: string): AgentMessage | null {
const envelope = LEGACY_ENVELOPE.exec(text);
const attributes = envelope ? parseAttributes(envelope[1]) : null;
if (!envelope || !attributes || attributes.get("version") !== "1") return null;
const body = unescapeXml(envelope[2]);
if (body === null) return null;
// #10864 sent a child's interim "ended its turn" notice with the neutral "message" event,
// which clients showed as a message from the child.
if (attributes.get("kind") === "agent-notification" && attributes.get("event") === "message")
attributes.set("kind", "agent-message");
return toMessage(attributes, body);
}
function parseLegacyEnvelopes(text: string): AgentMessage[] | null {
const schedule = LEGACY_SCHEDULE_ENVELOPE.exec(text);
if (schedule) {
// Schedule bodies include the run ID, keeping identity stable across replay.
const id = createHash("sha256").update(text).digest("hex");
return [{ id, source: { kind: "schedule" }, text: schedule[1] }];
}
// Bodies are XML escaped, so a literal closing tag unambiguously ends an entry.
const parts = text.split(/(?<=<\/paseo-system>)\n+(?=<paseo-system )/);
const messages = parts.map(parseAgentMessage);
const messages = text
.split(/(?<=<\/paseo-system>)\n+(?=<paseo-system )/)
.map(parseLegacyEnvelope);
return messages.every((message) => message !== null) ? messages : null;
}
/** Accept only text made entirely of marked messages; prose around them stays user text. */
export function parseAgentMessages(text: string): AgentMessage[] | null {
return parseMarkedMessages(text) ?? parseLegacyEnvelopes(text);
}
export function parseAgentMessage(text: string): AgentMessage | null {
const messages = parseAgentMessages(text);
return messages?.length === 1 ? messages[0]! : null;
}
function renderMessageText(block: AgentPromptContentBlock): string[] {
if (block.type === "image") return [];
if (block.type === "text") return [block.text];
@@ -143,20 +242,17 @@ export function prepareAgentMessage(
.flatMap((block) =>
block.type === "text" && !("mimeType" in block) ? [block.text] : [],
)
.join("\n")
.trim();
// Quote reserved envelopes only when they arrived through the human send path.
// This provenance must survive provider history, not only the accepted local row.
if (!parseAgentMessages(submittedText) && !isSystemInjectedEnvelope(submittedText)) {
return { prompt, messageId: id };
}
.join("\n");
// Mark reserved syntax only when it arrived through the human send path. This provenance
// must survive provider history, not only the accepted local row.
if (!RESERVED_SYNTAX.test(submittedText)) return { prompt, messageId: id };
}
return envelopeMessage(prompt, source ?? null, id);
}
/**
* Wrap a prompt in its envelope unconditionally. A person's prompt (`source` null) needs one
* only when it is quoted or shares a provider prompt with agent messages.
* Mark a prompt unconditionally. A person's prompt (`source` null) needs a marker only when it
* contains marker syntax or shares a provider prompt with agent messages.
*/
export function envelopeMessage(
prompt: AgentPromptInput,
@@ -165,96 +261,92 @@ export function envelopeMessage(
): { prompt: AgentPromptInput; messageId: string } {
const messageId = id ?? randomUUID();
const text = typeof prompt === "string" ? prompt : prompt.flatMap(renderMessageText).join("\n\n");
// Render textual attachments before wrapping, so provider replay still contains one
// complete envelope instead of an envelope followed by provider-rendered context.
const envelope = formatAgentMessage({ id: messageId, source, text });
// Render textual attachments before marking, so provider replay still contains one
// complete marked message instead of one followed by provider-rendered context.
const marked = formatAgentMessage({ id: messageId, source, text });
return {
messageId,
prompt:
typeof prompt === "string"
? envelope
: [{ type: "text", text: envelope }, ...prompt.filter((block) => block.type === "image")],
? marked
: [{ type: "text", text: marked }, ...prompt.filter((block) => block.type === "image")],
};
}
/** The same projection owns provider echoes, acceptance, import, and replay. */
export function projectAgentMessages(item: AgentTimelineItem): AgentTimelineItem[] {
if (item.type === "user_message") {
const messages = parseAgentMessages(item.text);
if (messages) {
return messages.flatMap((message) => {
const projected = projectAgentMessage({ ...item, text: formatAgentMessage(message) });
return projected ? [projected] : [];
});
}
}
const projected = projectAgentMessage(item);
return projected ? [projected] : [];
}
function projectAgentMessage(item: AgentTimelineItem): AgentTimelineItem | null {
if (item.type !== "user_message") return item;
const message = parseAgentMessage(item.text);
if (!message) {
if (!isSystemInjectedEnvelope(item.text)) return item;
// Schedule bodies include the run ID, keeping identity stable across replay.
const text = item.text.slice("<paseo-system>\n".length, -"\n</paseo-system>".length);
return {
type: "tool_call",
callId: `paseo-system:${createHash("sha256").update(item.text).digest("hex")}`,
name: "heartbeat",
status: "completed",
error: null,
detail: { type: "plain_text", text, icon: "sparkles" },
};
}
const { source } = message;
if (!source) {
return { ...item, text: message.text, clientMessageId: message.id };
}
if (source.kind === "change-request-update") {
return {
type: "tool_call",
callId: `paseo-change-request:${message.id}`,
name: "change_request_update",
status: "completed",
error: null,
detail: { type: "plain_text", text: message.text },
};
}
return {
type: "tool_call",
callId: `paseo-agent-message:${message.id}`,
agentMessage: {
event: source.kind === "agent-message" ? "message" : source.event,
sender: {
id: source.agentId,
...(source.serverId ? { serverId: source.serverId } : {}),
...(source.title ? { title: source.title } : {}),
},
text: message.text,
},
// COMPAT(agentMessageToolEnvelope): added in v0.11.1; remove after 2027-04-08
// once clients can accept a dedicated timeline variant. Older clients still
// parse this existing shape and can expand the delivered body.
name: "agent_message",
status: "completed",
error: null,
detail: { type: "plain_text", text: message.text, icon: "bot" },
};
if (item.type !== "user_message") return [item];
const messages = parseAgentMessages(item.text);
return messages ? messages.map((message) => projectAgentMessage(item, message)) : [item];
}
/**
* Wrap a body in <paseo-system>…</paseo-system> so the receiving agent
* recognizes the prompt as system-injected context — not a user turn.
* Used by schedule fires; agent messages use the versioned envelope.
* The daemon decides how each delivered message reads: a person's text and peer messages are
* messages, and everything the daemon reports is a completed plain-text tool call.
*/
export function formatSystemNotificationPrompt(reason: string): string {
return `<paseo-system>\n${reason}\n</paseo-system>`;
function projectAgentMessage(
item: Extract<AgentTimelineItem, { type: "user_message" }>,
message: AgentMessage,
): AgentTimelineItem {
const { source } = message;
if (!source) return { ...item, text: message.text, clientMessageId: message.id };
switch (source.kind) {
case "schedule":
return {
type: "tool_call",
callId: `paseo-system:${message.id}`,
name: "heartbeat",
status: "completed",
error: null,
detail: { type: "plain_text", text: message.text, icon: "sparkles" },
};
case "change-request-update":
return {
type: "tool_call",
callId: `paseo-change-request:${message.id}`,
name: "change_request_update",
status: "completed",
error: null,
detail: { type: "plain_text", label: source.url, text: message.text },
};
case "agent-notification":
return {
type: "tool_call",
callId: `paseo-agent-message:${message.id}`,
name: NOTIFICATION_TOOL_NAMES[source.event],
status: "completed",
error: null,
detail: {
type: "plain_text",
label: source.title ?? source.agentId,
text: message.text,
icon: "bot",
},
};
case "agent-message":
return {
type: "tool_call",
callId: `paseo-agent-message:${message.id}`,
// The wire has no sender on a user message, so clients render this as a "Sent by"
// bubble. Older clients that predate the bubble expand the plain-text body.
agentMessage: {
event: "message",
sender: {
id: source.agentId,
...(source.serverId ? { serverId: source.serverId } : {}),
...(source.title ? { title: source.title } : {}),
},
text: message.text,
},
name: "agent_message",
status: "completed",
error: null,
detail: { type: "plain_text", text: message.text, icon: "bot" },
};
}
}
const SYSTEM_ENVELOPE_PATTERN = /^<paseo-system>\n[\s\S]*\n<\/paseo-system>$/;
export function isSystemInjectedEnvelope(text: string): boolean {
return SYSTEM_ENVELOPE_PATTERN.test(text);
/** Mark a schedule fire so the receiving agent reads it as daemon context, not a user turn. */
export function formatSystemNotificationPrompt(body: string): string {
return formatAgentMessage({ id: randomUUID(), source: { kind: "schedule" }, text: body });
}
@@ -5,7 +5,6 @@ export {
prepareAgentMessage,
projectAgentMessages,
formatSystemNotificationPrompt,
isSystemInjectedEnvelope,
type AgentPromptSource,
} from "./envelope.js";
export { createAgentMessageDelivery, type AgentMessageDelivery } from "./delivery.js";
@@ -1,11 +1,3 @@
import {
formatSystemNotificationPrompt,
isSystemInjectedEnvelope,
parseAgentMessage,
formatAgentMessage,
prepareAgentMessage,
projectAgentMessages,
} from "./agent-messages/index.js";
import { expect, test, vi } from "vitest";
import { randomUUID } from "node:crypto";
import { mkdtempSync, rmSync } from "node:fs";
@@ -23,11 +15,6 @@ import type {
AgentStreamEvent,
} from "./agent-sdk-types.js";
test("isSystemInjectedEnvelope matches the envelope formatSystemNotificationPrompt produces", () => {
expect(isSystemInjectedEnvelope(formatSystemNotificationPrompt("child finished"))).toBe(true);
expect(isSystemInjectedEnvelope("hello world")).toBe(false);
});
// Independent of the production constant so shortening the budget breaks this test.
const EXPECTED_RUN_START_BUDGET_MS = 60_000;
// The slowest provider startup budget the run-start wait has to sit outside of today
@@ -258,123 +245,3 @@ test("waiting for a run start still gives up at the run start budget", async ()
await scenario.cleanup();
}
});
test("agent envelopes round-trip opaque sender IDs and XML-sensitive messages", () => {
const message = {
id: "delivery-1",
source: {
kind: "agent-message" as const,
agentId: 'host::agent<&"',
title: 'QA <messenger> & "reviewer"',
},
text: 'Review <changes> & "quotes"\n</paseo-system>\n<paseo-system>nested</paseo-system>',
};
const encoded = formatAgentMessage(message);
expect(parseAgentMessage(encoded)).toEqual(message);
expect(parseAgentMessage(`Example: ${encoded}`)).toBeNull();
expect(parseAgentMessage(encoded.replace('version="1"', 'version="2"'))).toBeNull();
expect(parseAgentMessage(encoded.replace("&lt;", "<"))).toBeNull();
expect(parseAgentMessage(encoded.replace('version="1"', 'version="1" version="1"'))).toBeNull();
});
test("a delivered batch projects each message and completion separately in order", () => {
const entries = [
{
id: "report",
source: { kind: "agent-message" as const, agentId: "remote::worker", title: "Worker" },
text: "Result <ready>",
},
{
id: "finished",
source: {
kind: "agent-notification" as const,
agentId: "remote::worker",
event: "finished" as const,
},
text: "Finished & ready",
},
];
const text = entries.map(formatAgentMessage).join("\n\n");
expect(projectAgentMessages({ type: "user_message", text })).toEqual(
entries.flatMap((entry) =>
projectAgentMessages({ type: "user_message", text: formatAgentMessage(entry) }),
),
);
// Human submissions containing the same envelopes must survive replay as human text.
const pasted = prepareAgentMessage(text, undefined, "human-batch");
expect(projectAgentMessages({ type: "user_message", text: String(pasted.prompt) })).toEqual([
{ type: "user_message", text, clientMessageId: "human-batch" },
]);
});
test("agent envelope includes rendered attachment context and preserves images", () => {
const image = { type: "image" as const, data: "aW1hZ2U=", mimeType: "image/png" };
const attachment = {
type: "github_issue" as const,
mimeType: "application/github-issue" as const,
number: 42,
title: "Review context",
url: "https://example.com/issues/42",
body: "Attached context",
};
const source = { kind: "agent-message" as const, agentId: "remote:sender" };
expect(
prepareAgentMessage(
[{ type: "text", text: "First" }, image, attachment, { type: "text", text: "Second" }],
source,
"message",
),
).toEqual({
messageId: "message",
prompt: [
{
type: "text",
text: formatAgentMessage({
id: "message",
source,
text: "First\n\nGitHub Issue #42: Review context\nhttps://example.com/issues/42\n\nAttached context\n\nSecond",
}),
},
image,
],
});
});
test("a human pasting an agent envelope stays a human message through provider replay", () => {
const pasted = formatAgentMessage({
id: "example",
source: { kind: "agent-message", agentId: "sender" },
text: "hello",
});
const delivery = prepareAgentMessage(pasted, undefined, "human-submission");
expect(
projectAgentMessages({
type: "user_message",
text: String(delivery.prompt),
messageId: "provider-echo",
})[0],
).toEqual({
type: "user_message",
text: pasted,
messageId: "provider-echo",
clientMessageId: "human-submission",
});
});
test("schedule prompts remain visible as completed tool calls on replay", () => {
const text = formatSystemNotificationPrompt("Heartbeat: check progress");
expect(projectAgentMessages({ type: "user_message", messageId: "fire-1", text })).toEqual([
expect.objectContaining({
type: "tool_call",
status: "completed",
detail: { type: "plain_text", text: "Heartbeat: check progress", icon: "sparkles" },
}),
]);
});
test("schedule trigger identity survives the provider assigning a message ID", () => {
const text = formatSystemNotificationPrompt("Schedule fired (id=heartbeat, run=run-1).");
expect(projectAgentMessages({ type: "user_message", text })).toEqual(
projectAgentMessages({ type: "user_message", text, messageId: "provider-message" }),
);
});
@@ -558,28 +558,35 @@ test("an undispatched follow-up does not block the running child's permission no
expect(await state.store.list()).toHaveLength(2);
});
describe("a child that ends its turn while it is still working", () => {
async function following(state: Awaited<ReturnType<typeof scenario>>) {
const STILL_WORKING = "You will be notified again when it settles";
describe("a child that ends its turn with work pending", () => {
/** Ends the child's first turn with `work` pending; the caller accepts the turn-end notice. */
async function following(
state: Awaited<ReturnType<typeof scenario>>,
work: PendingWork[] = ["background work"],
) {
await state.service.register(intent);
await until(() => state.observation.waits.length === 1);
state.observation.work.set("child", ["background work"]);
state.observation.work.set("child", work);
state.observation.waits[0]!.result.resolve(outcome("idle", "child", "Waiting for the build"));
await until(() => state.delivery.prompts.length === 1);
state.delivery.acknowledgments[0]!.resolve("steered");
await until(() => state.observation.waits.length === 2);
}
const wait = (state: Awaited<ReturnType<typeof scenario>>, child: string, index = 0) =>
state.observation.waitsFor(child)[index]!;
test("reports one interim notice, then finished with the reply of the turn that settles it", async () => {
test("reports the turn end at once with its pending work, then the final finish", async () => {
const state = await scenario();
await following(state);
const interim = state.delivery.prompts[0]!;
expect(interim).toContain("Agent child (Child) ended its turn but is still working");
expect(interim).toContain("background work");
expect(interim).toContain("This is not its final reply");
expect(interim).toContain("Waiting for the build");
expect(interim).not.toContain("Child) finished.");
// A task such as a dev server can run for as long as the child lives.
expect(state.delivery.prompts[0]).toContain("Agent child (Child) finished.");
expect(state.delivery.prompts[0]).toContain("Waiting for the build");
expect(state.delivery.prompts[0]).toContain("It still has background work that will wake it.");
expect(state.delivery.prompts[0]).toContain(STILL_WORKING);
expect(parseAgentMessage(state.delivery.enqueued[0]!)).toMatchObject({
source: { kind: "agent-notification", event: "message" },
source: { kind: "agent-notification", event: "finished" },
});
expect(await state.store.list()).toEqual([
expect.objectContaining({ followingSince: expect.any(String) }),
@@ -590,8 +597,9 @@ describe("a child that ends its turn while it is still working", () => {
await until(() => state.delivery.prompts.length === 2);
expect(state.delivery.prompts[1]).toContain("Agent child (Child) finished.");
expect(state.delivery.prompts[1]).toContain("FINAL: done");
expect(state.delivery.prompts[1]).not.toContain(STILL_WORKING);
expect(parseAgentMessage(state.delivery.enqueued[1]!)).toMatchObject({
source: { event: "finished" },
source: { kind: "agent-notification", event: "finished" },
});
state.delivery.acknowledgments[1]!.resolve("steered");
await expect.poll(async () => (await state.store.list()).length).toBe(0);
@@ -600,19 +608,24 @@ describe("a child that ends its turn while it is still working", () => {
expect(state.service.hasPendingForCaller("parent")).toBe(false);
});
test("stays silent for turns that end while work is still pending", async () => {
test("reports each later turn that ends while work is still pending", async () => {
const state = await scenario();
await following(state);
await following(state, ["queued messages"]);
expect(state.delivery.prompts[0]).toContain("It still has queued messages.");
state.observation.waits[1]!.result.resolve(outcome("idle", "child", "Still waiting"));
await until(() => state.delivery.prompts.length === 2);
expect(state.delivery.prompts[1]).toContain("Still waiting");
expect(state.delivery.prompts[1]).toContain(STILL_WORKING);
state.delivery.acknowledgments[1]!.resolve("steered");
await until(() => state.observation.waits.length === 3);
expect(state.delivery.prompts).toHaveLength(1);
state.observation.work.set("child", []);
state.observation.waits[2]!.result.resolve(outcome("idle", "child", "FINAL"));
await until(() => state.delivery.prompts.length === 2);
expect(state.delivery.prompts[1]).toContain("finished.");
await until(() => state.delivery.prompts.length === 3);
expect(state.delivery.prompts[2]).toContain("FINAL");
expect(state.delivery.prompts[2]).not.toContain(STILL_WORKING);
});
test("sends finished when its work drains while it is idle, without another turn", async () => {
test("sends the final finish when its work drains while it is idle, without another turn", async () => {
const state = await scenario();
await following(state);
state.observation.work.set("child", []);
@@ -622,6 +635,20 @@ describe("a child that ends its turn while it is still working", () => {
});
await until(() => state.delivery.prompts.length === 2);
expect(state.delivery.prompts[1]).toContain("Agent child (Child) finished.");
expect(state.delivery.prompts[1]).not.toContain(STILL_WORKING);
state.delivery.acknowledgments[1]!.resolve("steered");
await expect.poll(async () => (await state.store.list()).length).toBe(0);
});
test("a work change that leaves work pending sends nothing", async () => {
const state = await scenario();
await following(state);
state.observation.waits[1]!.result.resolve({
...outcome("idle", "child", "Waiting for the build"),
workChanged: true,
});
await until(() => state.observation.waits.length === 3);
expect(state.delivery.prompts).toHaveLength(1);
});
test("ignores a work change before the child's first turn ends", async () => {
@@ -636,21 +663,21 @@ describe("a child that ends its turn while it is still working", () => {
expect(state.delivery.prompts[0]).toContain("finished.");
});
test("restart while following neither repeats the notice nor loses the final finish", async () => {
test("restart while following keeps following and still reports the final finish", async () => {
const first = await scenario();
await following(first);
await first.service.close();
const restarted = await scenario(first.home);
await until(() => restarted.observation.waits.length === 1);
restarted.observation.work.set("child", ["queued messages"]);
restarted.observation.waits[0]!.result.resolve(outcome("idle", "child", "Still waiting"));
await until(() => restarted.observation.waits.length === 2);
expect(restarted.delivery.prompts).toEqual([]);
restarted.observation.work.set("child", []);
restarted.observation.waits[1]!.result.resolve(outcome("idle", "child", "FINAL"));
// A work change only counts once following, so this settles the child after a restart.
restarted.observation.waits[0]!.result.resolve({
...outcome("idle", "child", "FINAL"),
workChanged: true,
});
await until(() => restarted.delivery.prompts.length === 1);
expect(restarted.delivery.prompts[0]).toContain("finished.");
expect(restarted.delivery.prompts[0]).toContain("FINAL");
expect(restarted.delivery.prompts[0]).not.toContain(STILL_WORKING);
});
test("a permission request raised after waking up reaches the parent", async () => {
@@ -676,30 +703,30 @@ describe("a child that ends its turn while it is still working", () => {
expect(state.delivery.prompts[2]).toContain("Plan approved and done");
});
test("a helper waiting on its own delegated agent is followed until that delegation settles", async () => {
test("a helper waiting on its own delegated agent reports now and again once it settles", async () => {
const state = await scenario();
await state.service.register({ callerAgentId: "parent", childAgentId: "helper" });
await state.service.register({ callerAgentId: "helper", childAgentId: "sub" });
await until(() => state.observation.waits.length === 2);
const wait = (child: string, index = 0) => state.observation.waitsFor(child)[index]!;
wait("helper").result.resolve(outcome("idle", "helper", "Waiting for my helper"));
wait(state, "helper").result.resolve(outcome("idle", "helper", "Waiting for my helper"));
await until(() => state.delivery.prompts.length === 1);
expect(state.delivery.prompts[0]).toContain("ended its turn but is still working");
expect(state.delivery.prompts[0]).toContain("agents it is waiting on");
expect(state.delivery.prompts[0]).toContain("Agent helper (Child) finished.");
expect(state.delivery.prompts[0]).toContain("It still has agents it is waiting on.");
state.delivery.acknowledgments[0]!.resolve("steered");
wait("sub").result.resolve(outcome("idle", "sub", "Sub result"));
wait(state, "sub").result.resolve(outcome("idle", "sub", "Sub result"));
await until(() => state.delivery.prompts.length === 2);
expect(state.delivery.prompts[1]).toContain("Agent sub (Child) finished.");
state.delivery.acknowledgments[1]!.resolve("steered");
await until(() => !state.service.hasPendingForCaller("helper"));
await until(() => state.observation.waitsFor("helper").length === 2);
wait("helper", 1).result.resolve(outcome("idle", "helper", "Helper final"));
wait(state, "helper", 1).result.resolve(outcome("idle", "helper", "Helper final"));
await until(() => state.delivery.prompts.length === 3);
expect(state.delivery.prompts[2]).toContain("Agent helper (Child) finished.");
expect(state.delivery.prompts[2]).toContain("Helper final");
expect(state.delivery.prompts[2]).not.toContain(STILL_WORKING);
});
test("a followed helper settles when its last delegation ends without reporting to it", async () => {
@@ -711,19 +738,19 @@ describe("a child that ends its turn while it is still working", () => {
requireParentOwnership: true,
});
await until(() => state.observation.waits.length === 2);
const wait = (child: string, index = 0) => state.observation.waitsFor(child)[index]!;
wait("helper").result.resolve(outcome("idle", "helper", "Waiting for my helper"));
wait(state, "helper").result.resolve(outcome("idle", "helper", "Waiting for my helper"));
await until(() => state.delivery.prompts.length === 1);
expect(state.delivery.prompts[0]).toContain("ended its turn but is still working");
state.delivery.acknowledgments[0]!.resolve("steered");
await until(() => state.observation.waitsFor("helper").length === 2);
// The sub was detached from the helper, so its result is not reported to the helper.
wait("sub").result.resolve(outcome("idle", "sub", "Sub result"));
wait(state, "sub").result.resolve(outcome("idle", "sub", "Sub result"));
await until(() => state.delivery.prompts.length === 2);
expect(state.delivery.prompts[1]).toContain("Agent helper (Child) finished.");
expect(state.delivery.prompts[1]).toContain("Waiting for my helper");
expect(state.delivery.prompts[1]).not.toContain("Sub result");
expect(state.delivery.prompts[1]).not.toContain(STILL_WORKING);
expect(state.delivery.prompts.join("\n")).not.toContain("Sub result");
});
test("agents that only wait on each other settle and both callers hear finished", async () => {
@@ -733,37 +760,40 @@ describe("a child that ends its turn while it is still working", () => {
// The helper asks its parent a question and waits for the answer.
await state.service.register({ callerAgentId: "helper", childAgentId: "parent" });
await until(() => state.observation.waits.length === 2);
const wait = (child: string, index = 0) => state.observation.waitsFor(child)[index]!;
state.observation.work.set("parent", ["turn"]);
wait("helper").result.resolve(outcome("idle", "helper", "Asked my parent"));
wait(state, "helper").result.resolve(outcome("idle", "helper", "Asked my parent"));
await until(() => state.delivery.prompts.length === 1);
expect(state.delivery.prompts[0]).toContain("Agent helper (Child) ended its turn");
expect(state.delivery.prompts[0]).toContain("Agent helper (Child) finished.");
expect(state.delivery.prompts[0]).toContain(STILL_WORKING);
state.delivery.acknowledgments[0]!.resolve("steered");
// The parent answers. It waits on the helper, and the helper waits only on it.
state.observation.work.set("parent", []);
wait("parent").result.resolve(outcome("idle", "parent", "The answer"));
wait(state, "parent").result.resolve(outcome("idle", "parent", "The answer"));
await until(() => state.delivery.prompts.length === 2);
expect(state.delivery.prompts[1]).toContain("Agent parent (Child) finished.");
expect(state.delivery.prompts[1]).toContain("The answer");
expect(state.delivery.prompts[1]).not.toContain(STILL_WORKING);
state.delivery.acknowledgments[1]!.resolve("steered");
await until(() => !state.service.hasPendingForCaller("helper"));
await until(() => state.observation.waitsFor("helper").length === 2);
wait("helper", 1).result.resolve(outcome("idle", "helper", "Helper final"));
wait(state, "helper", 1).result.resolve(outcome("idle", "helper", "Helper final"));
await until(() => state.delivery.prompts.length === 3);
expect(state.delivery.prompts[2]).toContain("Agent helper (Child) finished.");
expect(state.delivery.prompts[2]).toContain("Helper final");
expect(state.delivery.prompts[2]).not.toContain(STILL_WORKING);
});
test("stops following at the follow limit and says the child is still working", async () => {
test("at the follow limit the caller gets a final finished with the child's last reply", async () => {
const state = await scenario(undefined, 0, 1, 50);
await following(state);
await until(() => state.delivery.prompts.length === 2);
expect(state.delivery.prompts[1]).toContain("Agent child (Child) is still working");
expect(state.delivery.prompts[1]).toContain("This finish subscription has ended");
expect(state.delivery.prompts[1]).not.toContain("finished.");
expect(state.delivery.prompts[1]).toContain("Agent child (Child) finished.");
expect(state.delivery.prompts[1]).toContain("Waiting for the build");
expect(state.delivery.prompts[1]).toContain("Paseo stopped following it");
expect(state.delivery.prompts[1]).not.toContain(STILL_WORKING);
state.delivery.acknowledgments[1]!.resolve("steered");
await expect.poll(async () => (await state.store.list()).length).toBe(0);
});
@@ -7,7 +7,6 @@ import type { FinishObservationResult } from "./internal/observation-buffer.js";
import type { AgentMessageDelivery } from "../agent-messages/index.js";
import { getParentAddressFromLabels } from "@getpaseo/protocol/agent-labels";
import {
endsSubscription,
formatFinishNotificationBody,
finishNotificationEvents,
type FinishNotificationReason,
@@ -15,6 +14,7 @@ import {
import {
createFollowing,
FOLLOW_LIMIT,
type Decision,
type FollowOutcome,
type Notice,
} from "./internal/following.js";
@@ -28,8 +28,8 @@ export interface FinishSubscription {
/** Creation subscriptions stop reporting after the child is detached. */
requireParentOwnership?: boolean;
/**
* Set once the child ended a turn while it was still working and the caller was told so.
* The subscription then follows the child until it settles or the follow limit passes.
* Set once the child ended a turn with work pending that will start its next turn. The
* subscription then follows the child silently until it settles or the follow limit passes.
*/
followingSince?: string;
}
@@ -59,7 +59,7 @@ interface Dependencies extends FinishObservation {
serverId: string;
logger: Logger;
retryDelayMs?: number;
/** How long a child that is still working is followed before the subscription gives up. */
/** How long a child with pending work is followed before its last reply is reported. */
followLimitMs?: number;
}
export interface FinishRegistration {
@@ -227,7 +227,8 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
reason,
lastAssistantMessage: result?.lastMessage ?? null,
permissionRequest: request,
pendingWork: notice.work,
pendingWork: notice.pendingWork,
followLimit: notice.followLimit,
}),
source: {
kind: "agent-notification",
@@ -305,9 +306,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
const permissions = new Set<string>();
let observation: FinishObservationSession | undefined;
/** One outcome and how far it got. Retries resume it: nothing is lost or sent twice. */
let current:
| { outcome: FollowOutcome; decided: boolean; notice?: Notice; sent: boolean }
| undefined;
let current: { outcome: FollowOutcome; decision?: Decision; sent: boolean } | undefined;
let remoteFailures = 0;
let retries = 0;
let warned = false;
@@ -340,7 +339,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
if (!notified) recheckCallerOf(watch);
return true;
}
async function decide(outcome: FollowOutcome): Promise<Notice | undefined | "suppressed"> {
async function decide(outcome: FollowOutcome): Promise<Decision | "suppressed"> {
// A queued follow-up cannot start until the current permission is answered.
// Its pending registration must not hold the running turn's checkpoint.
if (outcome === FOLLOW_LIMIT || outcome.status !== "permission" || watch.pending)
@@ -359,22 +358,24 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
await delay(signal, retries++);
return false;
}
current = { outcome, decided: false, sent: false };
current = { outcome, sent: false };
}
signal.throwIfAborted();
if (!current.decided) {
const notice = await decide(current.outcome);
if (notice === "suppressed") return end(false);
current = { ...current, decided: true, notice };
let { decision } = current;
if (!decision) {
const decided = await decide(current.outcome);
if (decided === "suppressed") return end(false);
decision = decided;
current = { ...current, decision };
}
const { notice } = current;
const { notice, done } = decision;
if (notice && !current.sent) {
await deliver(record, notice, permissions, signal);
signal.throwIfAborted();
current.sent = true;
}
// A removal failure retries only the commit, never the already accepted callback.
if (notice && endsSubscription(notice.reason)) return end(true);
if (done) return end(notice !== undefined);
current = undefined;
retries = 0;
warned = false;
@@ -3,7 +3,7 @@ import type { FinishSubscription, FinishSubscriptionStore, PendingWork } from ".
import type { FinishObservationResult } from "./observation-buffer.js";
import type { FinishNotificationReason } from "./notification.js";
/** The followed child is still working when the follow limit passes. */
/** The followed child still has pending work when the follow limit passes. */
export const FOLLOW_LIMIT = Symbol("follow limit");
export type FollowOutcome = FinishObservationResult | typeof FOLLOW_LIMIT;
@@ -11,9 +11,20 @@ export type FollowOutcome = FinishObservationResult | typeof FOLLOW_LIMIT;
export interface Notice {
reason: FinishNotificationReason;
result: FinishObservationResult | null;
work: readonly PendingWork[];
/** The turn ended with this work pending; the watch keeps following the child. */
pendingWork?: readonly PendingWork[];
/** The follow limit passed while the child still had pending work; the watch ends. */
followLimit?: true;
}
/** What one outcome means for the watch: what to tell the caller, and whether to stop watching. */
export interface Decision {
notice?: Notice;
done: boolean;
}
const KEEP_WATCHING: Decision = { done: false };
interface Options {
/** The watch's coalesced records; any one already following makes the watch follow. */
records: readonly FinishSubscription[];
@@ -26,9 +37,11 @@ interface Options {
/**
* Separates "the turn ended" from "the child has stopped". A watch waits for its prompt's turn.
* If that turn ends while the child still has pending work, the caller is told once and the
* watch follows the child: later turn ends and work changes stay silent until the child
* settles, which reports `finished`, or until the follow limit passes.
* Each turn end reports `finished` at once. When work that will start the child's next turn is
* still pending, the notice names that work and the watch follows the child: later turn ends
* report again, and the child settling with nothing pending, even without another turn, sends the
* final `finished` and ends the watch. When the follow limit passes first, the caller gets a final
* `finished` with the child's last reply.
*/
export function createFollowing(options: Options) {
let since = options.records
@@ -49,7 +62,7 @@ export function createFollowing(options: Options) {
async function follow(): Promise<void> {
const followingSince = new Date().toISOString();
// Written before the notice is sent, so a restart never repeats it.
// A restart keeps following instead of waiting for another turn end.
for (const record of options.records) await options.store.put({ ...record, followingSince });
since = followingSince;
}
@@ -91,20 +104,22 @@ export function createFollowing(options: Options) {
stale = true;
wake?.();
},
/** Returns nothing when the outcome is not worth telling the caller. */
async decide(outcome: FollowOutcome): Promise<Notice | undefined> {
async decide(outcome: FollowOutcome): Promise<Decision> {
if (outcome === FOLLOW_LIMIT)
return { reason: "is still working", result: latest, work: options.pendingWork() };
return { notice: { reason: "finished", result: latest, followLimit: true }, done: true };
latest = outcome;
const reason = options.reasonFor(outcome);
if (reason !== "finished") return { reason, result: outcome, work: [] };
// A permission request is a checkpoint; the caller still hears how the child ends.
if (reason !== "finished")
return { notice: { reason, result: outcome }, done: reason !== "needs permission" };
// Before the prompt's turn ends, a work change says nothing about its outcome.
if (outcome.workChanged && !since) return undefined;
const work = options.pendingWork();
if (!work.length) return { reason, result: outcome, work };
if (since) return undefined;
await follow();
return { reason: "ended its turn but is still working", result: outcome, work };
if (outcome.workChanged && !since) return KEEP_WATCHING;
const pendingWork = options.pendingWork();
if (!pendingWork.length) return { notice: { reason, result: outcome }, done: true };
if (!since) await follow();
// Work that changed but is still pending brings no new reply.
if (outcome.workChanged) return KEEP_WATCHING;
return { notice: { reason, result: outcome, pendingWork }, done: false };
},
};
}
@@ -1,10 +1,6 @@
import type { AgentPermissionRequest } from "../../agent-sdk-types.js";
import type { PendingWork } from "../index.js";
export type FinishNotificationReason =
/** The turn ended while work that will wake the child is pending. The subscription stays. */
| "ended its turn but is still working"
/** The follow limit passed while the child was still working. The subscription ends. */
| "is still working"
| "host unreachable"
| "host removed"
| "finished"
@@ -22,18 +18,9 @@ export const finishNotificationEvents = {
"needs permission": "permission-required",
"was closed": "closed",
"is unavailable": "closed",
// Use the existing failure event so older clients still parse agent-message metadata.
"was canceled": "errored",
// Not a finish: the existing neutral event keeps older clients parsing the metadata.
"ended its turn but is still working": "message",
"is still working": "message",
} as const;
/** Permission requests and the still-working notice leave the subscription in place. */
export function endsSubscription(reason: FinishNotificationReason): boolean {
return reason !== "needs permission" && reason !== "ended its turn but is still working";
}
const PENDING_WORK_DESCRIPTIONS: Record<PendingWork, string> = {
turn: "a turn in progress",
"background work": "background work that will wake it",
@@ -50,7 +37,10 @@ interface FinishNotificationBodyInput {
reason: FinishNotificationReason;
lastAssistantMessage: string | null;
permissionRequest?: AgentPermissionRequest;
/** The turn ended with this work pending; the subscription stays. */
pendingWork?: readonly PendingWork[];
/** The follow limit ended the subscription while the child still had pending work. */
followLimit?: true;
}
export function formatFinishNotificationBody(params: FinishNotificationBodyInput): string {
@@ -61,19 +51,16 @@ export function formatFinishNotificationBody(params: FinishNotificationBodyInput
: `Could not observe child agent ${params.childAgentId} on host ${params.serverId} after three failed attempts.`;
return `${host}\n\nStatus of child agent ${params.childAgentId} (${params.title}) is unknown.\n\nServer: ${params.serverId}\n\nThis finish subscription has ended. Reassess the delegated work; reconnecting will not resume notifications.`;
}
const work = params.pendingWork?.length
? `: ${params.pendingWork.map((item) => PENDING_WORK_DESCRIPTIONS[item]).join(", ")}`
: "";
const statusLine = `Agent ${params.childAgentId} (${params.title}) ${params.reason}${work}.`;
const statusLine = `Agent ${params.childAgentId} (${params.title}) ${params.reason}.`;
const sections = [statusLine];
if (params.serverId) sections.push(`Server: ${params.serverId}`);
if (params.reason === "ended its turn but is still working")
if (params.pendingWork?.length)
sections.push(
"This is not its final reply. You will be notified when it finishes, errors, or needs permission.",
`It still has ${params.pendingWork.map((work) => PENDING_WORK_DESCRIPTIONS[work]).join(", ")}. You will be notified again when it settles, errors, or needs permission.`,
);
if (params.reason === "is still working")
if (params.followLimit)
sections.push(
"This finish subscription has ended without a final reply. Check the agent with `get_agent_status`.",
"Paseo stopped following it while it still had pending work. Check the agent with `get_agent_status`.",
);
if (params.reason === "needs permission" && params.permissionRequest) {
sections.push(
@@ -13,6 +13,8 @@ export function createObservationBuffer(signal: AbortSignal) {
const resolvedBeforeInitial = new Set<string>();
let initialPending = true;
let terminal: FinishObservationResult | undefined;
/** A turn end arrived from the stream; the initial wait can only repeat it. */
let ended = false;
let failure: unknown;
let wake: (() => void) | undefined;
const abort = () => {
@@ -25,7 +27,10 @@ export function createObservationBuffer(signal: AbortSignal) {
if (result.status === "permission") {
for (const request of result.final?.pendingPermissions ?? [])
if (!delivered.has(request.id)) permissions.set(request.id, result);
} else if (!result.workChanged || !terminal || terminal.workChanged) terminal = result;
} else if (!result.workChanged || !terminal || terminal.workChanged) {
terminal = result;
if (!result.workChanged) ended = true;
}
wake?.();
}
return {
@@ -38,7 +43,7 @@ export function createObservationBuffer(signal: AbortSignal) {
if (pendingPermissions.length)
push({ ...result, final: { ...result.final, pendingPermissions } });
} else if (
!terminal &&
!ended &&
result.final?.status !== "running" &&
result.final?.status !== "initializing"
)
@@ -148,6 +148,35 @@ test("late initial permission snapshot cannot resurrect an already resolved requ
}
});
test("the initial wait that resolves after a turn end does not report that turn again", async () => {
const { host, observation } = await scenario();
try {
host.emit("idle", { type: "turn_completed", provider: "codex" });
const ended = await observation.next();
expect(ended.status).toBe("idle");
// The ordinary wait was waiting on the same turn and resolves after it.
host.baseline.resolve({
status: "idle",
final: ended.final,
lastMessage: "Last response",
error: null,
});
await host.baseline.promise;
await Promise.resolve();
let settled = false;
const next = observation.next().then((result) => {
settled = true;
return result;
});
await new Promise((resolve) => setTimeout(resolve, 10));
expect(settled).toBe(false);
host.emit("idle", { type: "turn_completed", provider: "codex" });
expect((await next).status).toBe("idle");
} finally {
await observation.close();
}
});
test("lookup failure uses its error channel and never fabricates a missing-child result", async () => {
const { host, observation } = await scenario();
try {
@@ -568,27 +568,31 @@ describe("Suite A: Core Fixes", () => {
timeoutMs: 10000,
label: `${outcome} notification`,
check: () => {
const items = daemonHandle.daemon.agentManager
.getTimeline(parentAgentId)
.filter(
(item) => item.type === "tool_call" && item.agentMessage?.sender.id === childId,
);
const items = daemonHandle.daemon.agentManager.getTimeline(parentAgentId).filter(
(item) =>
item.type === "tool_call" &&
item.detail.type === "plain_text" &&
item.detail.label === "Follow-up child" &&
// Each case creates its own child under the same title and parent.
item.detail.text.includes(childId),
);
return items.length > 0 ? items : null;
},
});
expect(notifications).toEqual([
expect.objectContaining({
{
type: "tool_call",
agentMessage: {
event: outcome,
sender: {
id: childId,
serverId: daemonHandle.daemon.getServerId(),
title: "Follow-up child",
},
text: expect.stringContaining(`(Follow-up child) ${outcome}.`),
callId: expect.stringMatching(/^paseo-agent-message:/),
name: `agent_${outcome}`,
status: "completed",
error: null,
detail: {
type: "plain_text",
label: "Follow-up child",
text: expect.stringContaining(`${childId} (Follow-up child) ${outcome}.`),
icon: "bot",
},
}),
},
]);
expect(daemonHandle.daemon.agentManager.getAgent(childId)?.lifecycle).toBe(status);
} finally {
@@ -4930,13 +4930,15 @@ describe("send_agent_prompt MCP tool", () => {
const pending = invokeToolWithParsedInput(tool, {
agentId: child.id,
prompt: "Follow up",
prompt: "/review the diff",
});
await vi.waitFor(() => expect(childSession.prompts).toHaveLength(1));
// The provider reads the sender's command at character 0; the marker trails it.
expect(String(childSession.prompts[0])).toMatch(/^\/review the diff\n\n<paseo-message /);
expect(parseAgentMessage(childSession.prompts[0])).toEqual({
id: expect.any(String),
source: { kind: "agent-message", agentId: parent.id },
text: "Follow up",
text: "/review the diff",
});
acknowledgeTurnStart();
const response = await pending;
@@ -5410,12 +5412,12 @@ describe("message order for one recipient", () => {
});
});
describe("finish notifications for a child that ends its turn while still working", () => {
describe("finish notifications for a child that ends its turn with work pending", () => {
const logger = createTestLogger();
const existingCwd = process.cwd();
async function setup() {
const workdir = await mkdtemp(join(tmpdir(), "mcp-still-working-"));
const workdir = await mkdtemp(join(tmpdir(), "mcp-pending-work-"));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const parentClient = new HeldTurnAgentClient("claude", false);
const childClient = new HeldTurnAgentClient("codex", true);
@@ -5450,25 +5452,30 @@ describe("finish notifications for a child that ends its turn while still workin
return { id, session };
}
const parentPrompts = () => parentClient.sessions[0]?.prompts ?? [];
return { workdir, storage, agentManager, parent, server, createChild, parentPrompts };
return {
workdir,
storage,
agentManager,
parent,
server,
createChild,
parentPrompts,
};
}
it("tells the parent the child is still working, then reports its autonomous final reply", async () => {
const { workdir, storage, agentManager, server, createChild, parentPrompts } = await setup();
it("reports the turn end now with its background task, and again when the task wakes the child", async () => {
const context = await setup();
const { workdir, storage, agentManager, server, createChild, parentPrompts } = context;
try {
const child = await createChild(server, "Builder");
child.session.pendingWakeup = true;
child.session.publishBackgroundWork([{ id: "build", description: "npm run build" }]);
child.session.finishTurn("WAITING for the build");
// The task can run for as long as the child lives, so the parent hears this turn now.
await vi.waitFor(() => expect(parentPrompts()).toHaveLength(1));
expect(parentPrompts()[0]).toContain(
`Agent ${child.id} (Builder) ended its turn but is still working: background work that will wake it.`,
);
expect(parentPrompts()[0]).toContain(`Agent ${child.id} (Builder) finished.`);
expect(parentPrompts()[0]).toContain("WAITING for the build");
expect(parseAgentMessage(parentPrompts()[0]!)).toMatchObject({
source: { kind: "agent-notification", agentId: child.id, event: "message" },
});
expect(parentPrompts()[0]).toContain("It still has background work that will wake it.");
// Claude publishes the empty roster before the turn its task notification starts.
child.session.publishBackgroundWork([]);
@@ -5480,6 +5487,7 @@ describe("finish notifications for a child that ends its turn while still workin
await vi.waitFor(() => expect(parentPrompts()).toHaveLength(2));
expect(parentPrompts()[1]).toContain(`Agent ${child.id} (Builder) finished.`);
expect(parentPrompts()[1]).toContain("FINAL: done");
expect(parentPrompts()[1]).not.toContain("It still has");
expect(parseAgentMessage(parentPrompts()[1]!)).toMatchObject({
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
});
@@ -5495,21 +5503,31 @@ describe("finish notifications for a child that ends its turn while still workin
}
});
it("reports finished when the child's background work drains without another turn", async () => {
const { workdir, storage, agentManager, server, createChild, parentPrompts } = await setup();
it("sends the final finish when the background task stops without another turn", async () => {
const context = await setup();
const { workdir, storage, agentManager, server, createChild, parentPrompts } = context;
try {
const child = await createChild(server, "Builder");
child.session.pendingWakeup = true;
child.session.publishBackgroundWork([{ id: "server", description: "dev server" }]);
child.session.finishTurn("Started the dev server");
await vi.waitFor(() => expect(parentPrompts()).toHaveLength(1));
expect(parentPrompts()[0]).toContain("ended its turn but is still working");
expect(parentPrompts()[0]).toContain(`Agent ${child.id} (Builder) finished.`);
expect(parentPrompts()[0]).toContain("Started the dev server");
child.session.pendingWakeup = false;
child.session.publishBackgroundWork([]);
await vi.waitFor(() => expect(parentPrompts()).toHaveLength(2));
expect(parentPrompts()[1]).toContain(`Agent ${child.id} (Builder) finished.`);
expect(parentPrompts()[1]).toContain("Started the dev server");
expect(parentPrompts()[1]).not.toContain("It still has");
// The subscription ended there: a later turn reports nothing.
child.session.startAutonomousTurn();
child.session.finishTurn("Unrelated later work");
await vi.waitFor(() => expect(agentManager.getAgent(child.id)?.lifecycle).toBe("idle"));
await new Promise((resolve) => setTimeout(resolve, 100));
expect(parentPrompts()).toHaveLength(2);
} finally {
await removeAgentStateDir(agentManager, storage, workdir);
}
@@ -5537,8 +5555,9 @@ describe("finish notifications for a child that ends its turn while still workin
}
});
it("follows a helper that waits on its own child until the helper's final reply", async () => {
const { workdir, storage, agentManager, server, createChild, parentPrompts } = await setup();
it("reports a helper's turn end while it waits on its own child, then its final reply", async () => {
const context = await setup();
const { workdir, storage, agentManager, server, createChild, parentPrompts } = context;
try {
const helper = await createChild(server, "Helper");
const helperServer = await createAgentMcpServer(
@@ -5555,11 +5574,9 @@ describe("finish notifications for a child that ends its turn while still workin
);
const sub = await createChild(helperServer, "Sub helper");
helper.session.finishTurn("Waiting for my helper");
await vi.waitFor(() => expect(parentPrompts()).toHaveLength(1));
expect(parentPrompts()[0]).toContain(
`Agent ${helper.id} (Helper) ended its turn but is still working: agents it is waiting on.`,
);
expect(parentPrompts()[0]).toContain(`Agent ${helper.id} (Helper) finished.`);
expect(parentPrompts()[0]).toContain("It still has agents it is waiting on.");
sub.session.finishTurn("SUB RESULT");
// The sub helper's finish starts the helper's next turn.
@@ -5571,18 +5588,21 @@ describe("finish notifications for a child that ends its turn while still workin
await vi.waitFor(() => expect(parentPrompts()).toHaveLength(2));
expect(parentPrompts()[1]).toContain(`Agent ${helper.id} (Helper) finished.`);
expect(parentPrompts()[1]).toContain("HELPER FINAL");
expect(parentPrompts()[1]).not.toContain("It still has");
} finally {
await removeAgentStateDir(agentManager, storage, workdir);
}
});
it("a permission request after waking up reaches the parent, and the settled turn still reports", async () => {
const { workdir, storage, agentManager, server, createChild, parentPrompts } = await setup();
const context = await setup();
const { workdir, storage, agentManager, server, createChild, parentPrompts } = context;
try {
const child = await createChild(server, "Planner");
child.session.pendingWakeup = true;
child.session.finishTurn("Waiting for research");
await vi.waitFor(() => expect(parentPrompts()).toHaveLength(1));
expect(parentPrompts()[0]).toContain("Waiting for research");
child.session.startAutonomousTurn();
child.session.pendingWakeup = false;
@@ -1903,7 +1903,7 @@ test(
// A CLI process can take longer than the two-second quiet window to start.
// Exercise each delivery across windows; delivery.test.ts owns batching with a clock.
await expect.poll(() => parentPrompts, { timeout: 10000 }).toHaveLength(1);
expect(parentPrompts[0]).toContain("REMOTE_REPORT &lt;ready&gt;");
expect(parentPrompts[0]).toMatch(/^REMOTE_REPORT <ready>\n\n<paseo-message /);
const cli = await promisify(execFile)(
process.execPath,
@@ -1953,17 +1953,24 @@ test(
})
.toEqual(["completed", "completed"]);
const timeline = await origin.client.fetchAgentTimeline(parent.id);
const messages = timeline.entries.flatMap((row) =>
row.item.type === "tool_call" && row.item.agentMessage ? [row.item.agentMessage] : [],
const delivered = timeline.entries.flatMap((row) =>
row.item.type === "tool_call" && row.item.callId.startsWith("paseo-agent-message:")
? [row.item]
: [],
);
expect(
messages.map((message) => [message.event, message.sender.id, message.sender.serverId]),
delivered.map(({ name, agentMessage, detail }) => [
name,
agentMessage?.sender.id,
agentMessage?.sender.serverId,
detail.type === "plain_text" ? detail.label : undefined,
]),
).toEqual([
["message", child.id, bId],
["message", parent.id, undefined],
["finished", child.id, bId],
["agent_message", child.id, bId, undefined],
["agent_message", parent.id, undefined, undefined],
["agent_finished", undefined, undefined, "Batch child"],
]);
expect(messages[0]!.text).toBe("REMOTE_REPORT <ready>");
expect(delivered[0]!.agentMessage!.text).toBe("REMOTE_REPORT <ready>");
expect(timeline.entries.filter((row) => row.item.type === "user_message")).toEqual([]);
const human = await aWorkspace.agents.create({
@@ -5,6 +5,7 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/
import { expect, test } from "vitest";
import type { AgentPromptInput } from "../agent/agent-sdk-types.js";
import type { PaseoToolCatalog } from "../agent/tools/types.js";
import { parseAgentMessages } from "../agent/agent-messages/index.js";
import { createTestAgentClient } from "../test-utils/fake-agent-client.js";
import { createDaemonTestContext } from "../test-utils/index.js";
import { githubWatchFixture } from "./test-utils/github-watch-fixture.js";
@@ -364,15 +365,12 @@ test("GitHub PR watches batch with child messages and survive restart", async ({
expect(nextTurn).toContain(review.inline);
expect(nextTurn).toContain(page101);
expect(nextTurn).toContain(`Check failed on ${failed.head.sha}`);
const envelopes = nextTurn?.match(/<paseo-system [^>]+>\n[\s\S]*?\n<\/paseo-system>/g);
const childEnvelope = envelopes?.find((envelope) => envelope.includes(childReport));
expect(childEnvelope).toContain(`kind="agent-message" source-agent-id="${childId}"`);
expect(childEnvelope).toContain('source-agent-title="QA child"');
expect(childEnvelope).not.toContain(url);
const prEnvelope = envelopes?.find((envelope) => envelope.includes(failedCheck.details_url));
expect(prEnvelope).toContain('kind="change-request-update"');
expect(prEnvelope).toContain(`source-url="${url}"`);
expect(prEnvelope).not.toContain(childReport);
expectChildReportBesideUpdate(nextTurn!, {
childId,
childReport,
url,
detailsUrl: failedCheck.details_url,
});
expect((await client.waitForFinish(busy.id)).status).toBe("idle");
await client.sendMessage(busy.id, "Hold while I unsubscribe");
await client.waitForAgentUpsert(busy.id, (agent) => agent.status === "running");
@@ -446,11 +444,7 @@ test("GitHub PR watches batch with child messages and survive restart", async ({
expect(turns.filter(({ text }) => baselineComments.some((link) => text.includes(link)))).toEqual(
[],
);
expect(
updates(idleDir).every(({ text }) =>
text.startsWith(`<paseo-system version="1" kind="change-request-update" source-url="${url}"`),
),
).toBe(true);
expect(updates(idleDir).every(({ text }) => isChangeRequestUpdateFor(text, url))).toBe(true);
expect(busyTurns()).toHaveLength(4);
expect(updates(busyDir).some(({ text }) => text.includes(discarded))).toBe(false);
expect(turns.filter(({ text }) => text.includes(page101))).toHaveLength(3);
@@ -464,3 +458,28 @@ test("GitHub PR watches batch with child messages and survive restart", async ({
JSON.stringify(turns.map(({ cwd, text, at }) => ({ recipient: path.basename(cwd), text, at }))),
);
}, 1_200_000);
function isChangeRequestUpdateFor(prompt: string, url: string): boolean {
const messages = parseAgentMessages(prompt) ?? [];
return messages.every(
({ source }) => source?.kind === "change-request-update" && source.url === url,
);
}
/** A child's report and the pull request update share one turn as separate messages. */
function expectChildReportBesideUpdate(
prompt: string,
expected: { childId: string; childReport: string; url: string; detailsUrl: string },
) {
const messages = parseAgentMessages(prompt) ?? [];
const child = messages.find((message) => message.text.includes(expected.childReport));
expect(child?.source).toMatchObject({
kind: "agent-message",
agentId: expected.childId,
title: "QA child",
});
expect(child?.text).not.toContain(expected.url);
const update = messages.find((message) => message.text.includes(expected.detailsUrl));
expect(update?.source).toEqual({ kind: "change-request-update", url: expected.url });
expect(update?.text).not.toContain(expected.childReport);
}
@@ -43,7 +43,7 @@ describe("daemon E2E (real claude) - finish notification across a background wak
if (!canRun) context.skip();
});
test("the caller hears the child is still working, then gets its autonomous final reply", async () => {
test("the caller hears the turn that started the task, then the autonomous final reply", async () => {
const logger = pino({ level: "silent" });
const cwd = mkdtempSync(path.join(tmpdir(), "daemon-real-claude-finish-wake-"));
const callerPrompts: string[] = [];
@@ -85,32 +85,26 @@ describe("daemon E2E (real claude) - finish notification across a background wak
].join(" "),
});
await vi.waitFor(() => expect(callerPrompts).toHaveLength(1), {
timeout: 180_000,
interval: 250,
});
const interim = parseAgentMessage(callerPrompts[0]!);
expect(interim.source).toMatchObject({
kind: "agent-notification",
agentId: childId,
event: "message",
});
expect(interim.text).toContain("ended its turn but is still working");
expect(interim.text).toContain("background work that will wake it");
await vi.waitFor(() => expect(callerPrompts).toHaveLength(2), {
timeout: 180_000,
timeout: 360_000,
interval: 250,
});
const final = parseAgentMessage(callerPrompts[1]!);
expect(final.source).toMatchObject({
kind: "agent-notification",
agentId: childId,
event: "finished",
});
expect(final.text).toContain("Background child) finished.");
expect(final.text).toContain(token);
const [spawned, final] = callerPrompts.map((prompt) => parseAgentMessage(prompt)!);
// The turn that replied SPAWNED ends with the background task still running: it reports now
// and names the pending work, and the subscription stays until the task wakes the child.
for (const notice of [spawned, final])
expect(notice.source).toMatchObject({
kind: "agent-notification",
agentId: childId,
event: "finished",
});
expect(spawned!.text).toContain("Background child) finished.");
expect(spawned!.text).toContain("SPAWNED");
expect(spawned!.text).toContain("It still has background work that will wake it.");
expect(final!.text).not.toContain("It still has");
expect(final!.text).toContain(token);
expect(daemon.daemon.agentManager.getAgent(childId)?.lifecycle).toBe("idle");
expect(callerPrompts).toHaveLength(2);
} finally {
await client.close();
await daemon.close();
@@ -436,8 +436,10 @@ describe("daemon E2E (real OMP)", () => {
for (const item of items) {
if (
item.type === "tool_call" &&
item.agentMessage?.sender.id === child.id &&
item.agentMessage.event === "finished"
item.name === "agent_finished" &&
item.callId.startsWith("paseo-agent-message:") &&
item.detail.type === "plain_text" &&
item.detail.text?.includes(child.id)
)
notifications++;
}