mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 02:05:31 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d9022b1f56 | ||
|
|
e9e37754d1 | ||
|
|
170101f146 |
+13
-1
@@ -183,7 +183,7 @@ caller, child, and host into one watch.
|
||||
|
||||
Bootstrap restores these watches after repairing stale running records to `closed` and before opening
|
||||
ingress. Reading a closed child's result does not load its provider. A finish notification reports that
|
||||
the child's run has settled; the parent decides whether its task is complete. A child chosen for restart
|
||||
the child has settled (see below); the parent decides whether its task is complete. A child chosen for restart
|
||||
recovery is observed only after its resume was sent, so the parent never hears that it was closed
|
||||
in between. Archived or deleted parents suppress delivery;
|
||||
parent-owned creation watches also stop
|
||||
@@ -196,6 +196,18 @@ 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`.
|
||||
|
||||
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.
|
||||
A watched child that closes before its finish event also notifies the caller so delegated work cannot disappear silently during archive or workspace teardown.
|
||||
|
||||
@@ -1618,6 +1618,11 @@ export class AgentManager {
|
||||
return this.backgroundWork.summary(agentId);
|
||||
}
|
||||
|
||||
/** The live session started work that will start another turn by itself. */
|
||||
hasPendingWakeup(agentId: string): boolean {
|
||||
return this.agents.get(agentId)?.session.hasPendingWakeup?.() ?? false;
|
||||
}
|
||||
|
||||
private publishBackgroundWork(agentId: string, items: AgentBackgroundWorkItem[] | null): void {
|
||||
if (items) this.dispatch({ type: "background_work", agentId, items });
|
||||
}
|
||||
|
||||
@@ -24,7 +24,8 @@ const sourceSchema = z.discriminatedUnion("kind", [
|
||||
agentId: agentIdSchema,
|
||||
serverId: z.string().min(1).optional(),
|
||||
title: z.string().min(1).optional(),
|
||||
event: z.enum(["finished", "errored", "permission-required", "closed"]),
|
||||
// "message" reports a child that ended its turn but has not finished its work.
|
||||
event: z.enum(["message", "finished", "errored", "permission-required", "closed"]),
|
||||
}),
|
||||
]);
|
||||
export type AgentPromptSource = z.infer<typeof sourceSchema>;
|
||||
|
||||
@@ -774,6 +774,11 @@ export interface AgentSession {
|
||||
* An optional additional veto: missing methods use daemon baseline eligibility;
|
||||
* implemented checks that reject or return false keep the runtime resident. */
|
||||
canStopRuntime?(): Promise<boolean>;
|
||||
/**
|
||||
* True while work this session started will start another turn by itself, such as a
|
||||
* background task that reports back when it ends. Recurring triggers do not count.
|
||||
*/
|
||||
hasPendingWakeup?(): boolean;
|
||||
/** Release live runtime resources without archiving or deleting the durable native session. */
|
||||
close(): Promise<void>;
|
||||
listCommands?(): Promise<AgentSlashCommand[]>;
|
||||
|
||||
+269
-12
@@ -3,7 +3,8 @@ import { HostObservationError } from "../host-operations/index.js";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { afterEach, describe, expect, test } from "vitest";
|
||||
import { formatAgentMessage, parseAgentMessage } from "../agent-messages/envelope.js";
|
||||
import type { WaitForFinishResult } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { AgentMessageDelivery } from "../agent-messages/index.js";
|
||||
import { buildStoredAgentPayload } from "../agent-projections.js";
|
||||
@@ -12,8 +13,11 @@ import {
|
||||
createFinishSubscriptions,
|
||||
createJsonFinishSubscriptionStore,
|
||||
type FinishObservation,
|
||||
type FinishSubscription,
|
||||
type FinishSubscriptions,
|
||||
type PendingWork,
|
||||
} from "./index.js";
|
||||
import type { FinishObservationResult } from "./internal/observation-buffer.js";
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
@@ -25,21 +29,32 @@ function deferred<T>() {
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
class Observation implements FinishObservation {
|
||||
waits: Array<{ signal: AbortSignal; result: ReturnType<typeof deferred<WaitForFinishResult>> }> =
|
||||
[];
|
||||
waits: Array<{
|
||||
signal: AbortSignal;
|
||||
childAgentId: string;
|
||||
result: ReturnType<typeof deferred<FinishObservationResult>>;
|
||||
}> = [];
|
||||
permission = deferred<void>();
|
||||
opening: Promise<void> = Promise.resolve();
|
||||
openedSignals: AbortSignal[] = [];
|
||||
async open(_record: unknown, signal: AbortSignal) {
|
||||
/** Work that will start each child's next turn by itself, as the local host reports it. */
|
||||
work = new Map<string, PendingWork[]>();
|
||||
async open(record: FinishSubscription, signal: AbortSignal) {
|
||||
this.openedSignals.push(signal);
|
||||
await this.opening;
|
||||
return { next: () => this.wait(signal), close: async () => {} };
|
||||
return { next: () => this.wait(record.childAgentId, signal), close: async () => {} };
|
||||
}
|
||||
async wait(signal: AbortSignal) {
|
||||
pendingWork(record: FinishSubscription): PendingWork[] {
|
||||
return this.work.get(record.childAgentId) ?? [];
|
||||
}
|
||||
waitsFor(childAgentId: string) {
|
||||
return this.waits.filter((entry) => entry.childAgentId === childAgentId);
|
||||
}
|
||||
async wait(childAgentId: string, signal: AbortSignal) {
|
||||
signal.throwIfAborted();
|
||||
const result = deferred<WaitForFinishResult>();
|
||||
const result = deferred<FinishObservationResult>();
|
||||
signal.addEventListener("abort", () => result.reject(new Error("Stopped")), { once: true });
|
||||
this.waits.push({ signal, result });
|
||||
this.waits.push({ signal, childAgentId, result });
|
||||
return result.promise;
|
||||
}
|
||||
afterPermission() {
|
||||
@@ -48,9 +63,18 @@ class Observation implements FinishObservation {
|
||||
}
|
||||
class Delivery implements AgentMessageDelivery {
|
||||
prompts: string[] = [];
|
||||
/** Prompts as the recipient's provider receives them, inside their envelope. */
|
||||
enqueued: string[] = [];
|
||||
acknowledgments: Array<ReturnType<typeof deferred<"steered">>> = [];
|
||||
enqueue(message: Parameters<AgentMessageDelivery["enqueue"]>[0]) {
|
||||
this.prompts.push(String(message.prompt));
|
||||
this.enqueued.push(
|
||||
formatAgentMessage({
|
||||
id: "notification",
|
||||
source: message.source ?? null,
|
||||
text: String(message.prompt),
|
||||
}),
|
||||
);
|
||||
const acknowledgment = deferred<"steered">();
|
||||
this.acknowledgments.push(acknowledgment);
|
||||
return {
|
||||
@@ -68,7 +92,12 @@ afterEach(async () => {
|
||||
for (const service of services.splice(0)) await service.close();
|
||||
await Promise.all(homes.splice(0).map((home) => rm(home, { recursive: true, force: true })));
|
||||
});
|
||||
async function scenario(directory?: string, removalFailures = 0, retryDelayMs = 1) {
|
||||
async function scenario(
|
||||
directory?: string,
|
||||
removalFailures = 0,
|
||||
retryDelayMs = 1,
|
||||
followLimitMs?: number,
|
||||
) {
|
||||
const home = directory ?? (await mkdtemp(join(tmpdir(), "finish-recovery-")));
|
||||
if (!directory) homes.push(home);
|
||||
const durableStore = createJsonFinishSubscriptionStore(home);
|
||||
@@ -89,10 +118,12 @@ async function scenario(directory?: string, removalFailures = 0, retryDelayMs =
|
||||
store,
|
||||
messages: () => delivery,
|
||||
open: observation.open.bind(observation),
|
||||
pendingWork: observation.pendingWork.bind(observation),
|
||||
callerIsActive: async () => active,
|
||||
serverId: "origin",
|
||||
logger: createTestLogger(),
|
||||
retryDelayMs,
|
||||
...(followLimitMs === undefined ? {} : { followLimitMs }),
|
||||
});
|
||||
services.push(service);
|
||||
await service.start();
|
||||
@@ -108,12 +139,16 @@ async function scenario(directory?: string, removalFailures = 0, retryDelayMs =
|
||||
};
|
||||
}
|
||||
const intent = { callerAgentId: "parent", childAgentId: "child" };
|
||||
function outcome(status: "idle" | "running" | "closed" | "error" = "closed"): WaitForFinishResult {
|
||||
function outcome(
|
||||
status: "idle" | "running" | "closed" | "error" = "closed",
|
||||
childAgentId = "child",
|
||||
lastMessage = "Partial work saved",
|
||||
): WaitForFinishResult {
|
||||
return {
|
||||
status: status === "error" ? "error" : "idle",
|
||||
final: buildStoredAgentPayload(
|
||||
{
|
||||
id: "child",
|
||||
id: childAgentId,
|
||||
provider: "codex",
|
||||
cwd: "/tmp",
|
||||
title: "Child",
|
||||
@@ -125,7 +160,7 @@ function outcome(status: "idle" | "running" | "closed" | "error" = "closed"): Wa
|
||||
["codex"],
|
||||
(_provider, own) => own ?? {},
|
||||
),
|
||||
lastMessage: "Partial work saved",
|
||||
lastMessage,
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
@@ -485,6 +520,7 @@ test("finish recovery protects callers before durable intent has loaded", async
|
||||
},
|
||||
messages: () => s.delivery,
|
||||
open: s.observation.open.bind(s.observation),
|
||||
pendingWork: s.observation.pendingWork.bind(s.observation),
|
||||
callerIsActive: async () => true,
|
||||
serverId: "origin",
|
||||
logger: createTestLogger(),
|
||||
@@ -521,3 +557,224 @@ test("an undispatched follow-up does not block the running child's permission no
|
||||
expect(state.delivery.prompts[0]).toContain("approval");
|
||||
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>>) {
|
||||
await state.service.register(intent);
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
state.observation.work.set("child", ["background 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);
|
||||
}
|
||||
|
||||
test("reports one interim notice, then finished with the reply of the turn that settles it", 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.");
|
||||
expect(parseAgentMessage(state.delivery.enqueued[0]!)).toMatchObject({
|
||||
source: { kind: "agent-notification", event: "message" },
|
||||
});
|
||||
expect(await state.store.list()).toEqual([
|
||||
expect.objectContaining({ followingSince: expect.any(String) }),
|
||||
]);
|
||||
|
||||
state.observation.work.set("child", []);
|
||||
state.observation.waits[1]!.result.resolve(outcome("idle", "child", "FINAL: done"));
|
||||
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(parseAgentMessage(state.delivery.enqueued[1]!)).toMatchObject({
|
||||
source: { event: "finished" },
|
||||
});
|
||||
state.delivery.acknowledgments[1]!.resolve("steered");
|
||||
await expect.poll(async () => (await state.store.list()).length).toBe(0);
|
||||
// A turn a person starts after the child settled has no observer left to report it.
|
||||
expect(state.observation.waits).toHaveLength(2);
|
||||
expect(state.service.hasPendingForCaller("parent")).toBe(false);
|
||||
});
|
||||
|
||||
test("stays silent for turns that end while work is still pending", async () => {
|
||||
const state = await scenario();
|
||||
await following(state);
|
||||
state.observation.waits[1]!.result.resolve(outcome("idle", "child", "Still waiting"));
|
||||
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.");
|
||||
});
|
||||
|
||||
test("sends finished when its work drains while it is idle, without another turn", async () => {
|
||||
const state = await scenario();
|
||||
await following(state);
|
||||
state.observation.work.set("child", []);
|
||||
state.observation.waits[1]!.result.resolve({
|
||||
...outcome("idle", "child", "Waiting for the build"),
|
||||
workChanged: true,
|
||||
});
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("Agent child (Child) finished.");
|
||||
});
|
||||
|
||||
test("ignores a work change before the child's first turn ends", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register(intent);
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
state.observation.waits[0]!.result.resolve({ ...outcome("idle"), workChanged: true });
|
||||
await until(() => state.observation.waits.length === 2);
|
||||
expect(state.delivery.prompts).toEqual([]);
|
||||
state.observation.waits[1]!.result.resolve(outcome("idle"));
|
||||
await until(() => state.delivery.prompts.length === 1);
|
||||
expect(state.delivery.prompts[0]).toContain("finished.");
|
||||
});
|
||||
|
||||
test("restart while following neither repeats the notice nor loses 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"));
|
||||
await until(() => restarted.delivery.prompts.length === 1);
|
||||
expect(restarted.delivery.prompts[0]).toContain("finished.");
|
||||
expect(restarted.delivery.prompts[0]).toContain("FINAL");
|
||||
});
|
||||
|
||||
test("a permission request raised after waking up reaches the parent", async () => {
|
||||
const state = await scenario();
|
||||
await following(state);
|
||||
const result = outcome("running");
|
||||
result.status = "permission";
|
||||
result.final!.pendingPermissions = [
|
||||
{ id: "plan", name: "ExitPlanMode", input: {}, kind: "plan" } as NonNullable<
|
||||
typeof result.final
|
||||
>["pendingPermissions"][number],
|
||||
];
|
||||
state.observation.waits[1]!.result.resolve(result);
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("needs permission");
|
||||
expect(state.delivery.prompts[1]).toContain("respond_to_permission");
|
||||
state.delivery.acknowledgments[1]!.resolve("steered");
|
||||
await until(() => state.observation.waits.length === 3);
|
||||
state.observation.work.set("child", []);
|
||||
state.observation.waits[2]!.result.resolve(outcome("idle", "child", "Plan approved and done"));
|
||||
await until(() => state.delivery.prompts.length === 3);
|
||||
expect(state.delivery.prompts[2]).toContain("finished.");
|
||||
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 () => {
|
||||
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"));
|
||||
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");
|
||||
state.delivery.acknowledgments[0]!.resolve("steered");
|
||||
|
||||
wait("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"));
|
||||
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");
|
||||
});
|
||||
|
||||
test("a followed helper settles when its last delegation ends without reporting to it", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register({ callerAgentId: "parent", childAgentId: "helper" });
|
||||
await state.service.register({
|
||||
callerAgentId: "helper",
|
||||
childAgentId: "sub",
|
||||
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"));
|
||||
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");
|
||||
|
||||
// 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"));
|
||||
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");
|
||||
});
|
||||
|
||||
test("agents that only wait on each other settle and both callers hear finished", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register({ callerAgentId: "parent", childAgentId: "helper" });
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
// 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"));
|
||||
await until(() => state.delivery.prompts.length === 1);
|
||||
expect(state.delivery.prompts[0]).toContain("Agent helper (Child) ended its turn");
|
||||
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"));
|
||||
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");
|
||||
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"));
|
||||
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");
|
||||
});
|
||||
|
||||
test("stops following at the follow limit and says the child is still working", 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.");
|
||||
state.delivery.acknowledgments[1]!.resolve("steered");
|
||||
await expect.poll(async () => (await state.store.list()).length).toBe(0);
|
||||
});
|
||||
|
||||
test("errors while following end the subscription as they do today", async () => {
|
||||
const state = await scenario();
|
||||
await following(state);
|
||||
state.observation.waits[1]!.result.resolve(outcome("error"));
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("errored");
|
||||
state.delivery.acknowledgments[1]!.resolve("steered");
|
||||
await expect.poll(async () => (await state.store.list()).length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,10 +7,17 @@ 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,
|
||||
} from "./internal/notification.js";
|
||||
import {
|
||||
createFollowing,
|
||||
FOLLOW_LIMIT,
|
||||
type FollowOutcome,
|
||||
type Notice,
|
||||
} from "./internal/following.js";
|
||||
export { createJsonFinishSubscriptionStore } from "./internal/json-store.js";
|
||||
|
||||
export interface FinishSubscription {
|
||||
@@ -20,7 +27,17 @@ export interface FinishSubscription {
|
||||
serverId?: string;
|
||||
/** 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.
|
||||
*/
|
||||
followingSince?: string;
|
||||
}
|
||||
/**
|
||||
* Work that will start the child's next turn without a new prompt from the caller.
|
||||
* Recurring triggers such as heartbeats are not pending work: they never settle.
|
||||
*/
|
||||
export type PendingWork = "turn" | "background work" | "queued messages" | "delegated agents";
|
||||
export interface FinishSubscriptionStore {
|
||||
list(): Promise<FinishSubscription[]>;
|
||||
put(subscription: FinishSubscription): Promise<void>;
|
||||
@@ -32,6 +49,8 @@ export interface FinishObservationSession {
|
||||
}
|
||||
export interface FinishObservation {
|
||||
open(subscription: FinishSubscription, signal: AbortSignal): Promise<FinishObservationSession>;
|
||||
/** The child's own pending work. Empty when its host cannot tell, as for remote children. */
|
||||
pendingWork(subscription: FinishSubscription): readonly PendingWork[];
|
||||
}
|
||||
interface Dependencies extends FinishObservation {
|
||||
store: FinishSubscriptionStore;
|
||||
@@ -40,6 +59,8 @@ 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. */
|
||||
followLimitMs?: number;
|
||||
}
|
||||
export interface FinishRegistration {
|
||||
/** The prompt was accepted. Replaces preceding registrations for this pair. */
|
||||
@@ -64,10 +85,13 @@ interface Watch {
|
||||
decide(accepted: boolean): void;
|
||||
pending: boolean;
|
||||
task?: Promise<void>;
|
||||
/** Decides a followed child's state again; see `createFollowing`. */
|
||||
recheck?(): void;
|
||||
}
|
||||
function key(record: FinishSubscription): string {
|
||||
return JSON.stringify([record.callerAgentId, record.childAgentId, record.serverId]);
|
||||
}
|
||||
const DEFAULT_FOLLOW_LIMIT_MS = 24 * 60 * 60_000;
|
||||
|
||||
/** Owns durable intent, live observation, supersession, and dispatch acknowledgment. */
|
||||
export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptions {
|
||||
@@ -109,6 +133,18 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
if (!group.size && watches.get(key(watch.records[0]!)) === group)
|
||||
watches.delete(key(watch.records[0]!));
|
||||
}
|
||||
/**
|
||||
* A watch that ends without telling its caller leaves that caller's own watchers with no event:
|
||||
* the caller may have no work left now.
|
||||
*/
|
||||
function recheckCallerOf(watch: Watch): void {
|
||||
const { callerAgentId } = watch.records[0]!;
|
||||
for (const group of watches.values())
|
||||
for (const watcher of group) {
|
||||
const record = watcher.records[0]!;
|
||||
if (record.childAgentId === callerAgentId && !record.serverId) watcher.recheck?.();
|
||||
}
|
||||
}
|
||||
async function remove(watch: Watch): Promise<void> {
|
||||
// Only IDs captured by this observer are eligible; newer registrations survive.
|
||||
for (const record of watch.records) await deps.store.remove(record.id);
|
||||
@@ -169,19 +205,19 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
}
|
||||
async function deliver(
|
||||
record: FinishSubscription,
|
||||
result: FinishObservationResult,
|
||||
notice: Notice,
|
||||
permissions: Set<string>,
|
||||
signal: AbortSignal,
|
||||
): Promise<boolean> {
|
||||
const requests = result.final?.pendingPermissions ?? [];
|
||||
const reason = reasonFor(result);
|
||||
): Promise<void> {
|
||||
const { reason, result } = notice;
|
||||
const requests = result?.final?.pendingPermissions ?? [];
|
||||
for (const id of permissions)
|
||||
if (!requests.some((request) => request.id === id)) permissions.delete(id);
|
||||
const acknowledgments: Promise<unknown>[] = [];
|
||||
for (const request of reason === "needs permission" ? requests : [undefined]) {
|
||||
if (signal.aborted) return false;
|
||||
if (signal.aborted) return;
|
||||
if (request && permissions.has(request.id)) continue;
|
||||
const title = result.final?.title ?? record.childAgentId;
|
||||
const title = result?.final?.title ?? record.childAgentId;
|
||||
const receipt = deps.messages().enqueue({
|
||||
recipientId: record.callerAgentId,
|
||||
prompt: formatFinishNotificationBody({
|
||||
@@ -189,8 +225,9 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
serverId: record.serverId ?? deps.serverId,
|
||||
title,
|
||||
reason,
|
||||
lastAssistantMessage: result.lastMessage,
|
||||
lastAssistantMessage: result?.lastMessage ?? null,
|
||||
permissionRequest: request,
|
||||
pendingWork: notice.work,
|
||||
}),
|
||||
source: {
|
||||
kind: "agent-notification",
|
||||
@@ -211,9 +248,42 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
);
|
||||
}
|
||||
await abortable(Promise.all(acknowledgments), signal);
|
||||
if (signal.aborted) return false;
|
||||
if (reason !== "needs permission") return true;
|
||||
return false;
|
||||
}
|
||||
function delegations(agentId: string): FinishSubscription[] {
|
||||
const records: FinishSubscription[] = [];
|
||||
for (const group of watches.values())
|
||||
for (const watch of group)
|
||||
if (watch.records[0]!.callerAgentId === agentId) records.push(watch.records[0]!);
|
||||
return records;
|
||||
}
|
||||
function delegates(agentId: string): boolean {
|
||||
return registering.has(agentId) || delegations(agentId).length > 0;
|
||||
}
|
||||
/**
|
||||
* Whether one of the agent's delegations can still bring it a notice. A delegate that has settled
|
||||
* is about to report; a delegate that only waits on agents in `chain` never will, so agents that
|
||||
* wait on each other settle together.
|
||||
*/
|
||||
function awaitsDelegates(agentId: string, chain: Set<string>): boolean {
|
||||
if (registering.has(agentId)) return true;
|
||||
chain.add(agentId);
|
||||
return delegations(agentId).some((delegation) => {
|
||||
// A remote delegate's work is known only to its host.
|
||||
if (delegation.serverId) return true;
|
||||
const delegate = delegation.childAgentId;
|
||||
if (chain.has(delegate)) return false;
|
||||
if (deps.pendingWork(delegation).length > 0 || delegations(delegate).length === 0)
|
||||
return true;
|
||||
return awaitsDelegates(delegate, chain);
|
||||
});
|
||||
}
|
||||
/** Everything that will start the child's next turn by itself. */
|
||||
function pendingWork(record: FinishSubscription): PendingWork[] {
|
||||
const work = [...deps.pendingWork(record)];
|
||||
// A remote child's own subscriptions live on its host.
|
||||
if (!record.serverId && awaitsDelegates(record.childAgentId, new Set()))
|
||||
work.push("delegated agents");
|
||||
return work;
|
||||
}
|
||||
async function run(watch: Watch, group: Set<Watch>): Promise<void> {
|
||||
const signal = watch.controller.signal;
|
||||
@@ -224,17 +294,27 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
(intent) => intent.requireParentOwnership === true,
|
||||
),
|
||||
};
|
||||
const following = createFollowing({
|
||||
records: watch.records,
|
||||
store: deps.store,
|
||||
limitMs: deps.followLimitMs ?? DEFAULT_FOLLOW_LIMIT_MS,
|
||||
pendingWork: () => pendingWork(record),
|
||||
reasonFor,
|
||||
});
|
||||
watch.recheck = following.recheck;
|
||||
const permissions = new Set<string>();
|
||||
let observation: FinishObservationSession | undefined;
|
||||
let pending: FinishObservationResult | undefined;
|
||||
let acknowledged = false;
|
||||
/** 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 remoteFailures = 0;
|
||||
let retries = 0;
|
||||
let warned = false;
|
||||
async function observeNext(): Promise<FinishObservationResult | undefined> {
|
||||
async function observeNext(): Promise<FollowOutcome | undefined> {
|
||||
try {
|
||||
observation ??= await deps.open(record, signal);
|
||||
const result = await abortable(observation.next(), signal);
|
||||
const result = await following.next(abortable(observation.next(), signal), signal);
|
||||
remoteFailures = 0;
|
||||
return result;
|
||||
} catch (error) {
|
||||
@@ -254,39 +334,56 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
};
|
||||
}
|
||||
}
|
||||
async function end(notified: boolean): Promise<true> {
|
||||
await remove(watch);
|
||||
stop(watch, group);
|
||||
if (!notified) recheckCallerOf(watch);
|
||||
return true;
|
||||
}
|
||||
async function decide(outcome: FollowOutcome): Promise<Notice | undefined | "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)
|
||||
await decisions(group);
|
||||
signal.throwIfAborted();
|
||||
if (await suppressed(record, outcome === FOLLOW_LIMIT ? undefined : outcome))
|
||||
return "suppressed";
|
||||
return following.decide(outcome);
|
||||
}
|
||||
/** Handles one outcome. Returns true once the subscription has ended. */
|
||||
async function step(): Promise<boolean> {
|
||||
if (await suppressed(record)) return end(false);
|
||||
if (!current) {
|
||||
const outcome = await observeNext();
|
||||
if (!outcome) {
|
||||
await delay(signal, retries++);
|
||||
return false;
|
||||
}
|
||||
current = { outcome, decided: false, sent: false };
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
if (!current.decided) {
|
||||
const notice = await decide(current.outcome);
|
||||
if (notice === "suppressed") return end(false);
|
||||
current = { ...current, decided: true, notice };
|
||||
}
|
||||
const { notice } = current;
|
||||
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);
|
||||
current = undefined;
|
||||
retries = 0;
|
||||
warned = false;
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
while (!signal.aborted) {
|
||||
try {
|
||||
if (await suppressed(record)) {
|
||||
await remove(watch);
|
||||
stop(watch, group);
|
||||
return;
|
||||
}
|
||||
if (!pending) pending = await observeNext();
|
||||
if (!pending) {
|
||||
await delay(signal, retries++);
|
||||
continue;
|
||||
}
|
||||
if (signal.aborted) return;
|
||||
// A queued follow-up cannot start until the current permission is answered.
|
||||
// Its pending registration must not hold the running turn's checkpoint.
|
||||
if (pending.status !== "permission" || watch.pending) await decisions(group);
|
||||
if (signal.aborted) return;
|
||||
if (await suppressed(record, pending)) {
|
||||
await remove(watch);
|
||||
stop(watch, group);
|
||||
return;
|
||||
}
|
||||
if (!acknowledged) acknowledged = await deliver(record, pending, permissions, signal);
|
||||
if (acknowledged) {
|
||||
// A removal failure retries only the commit, never the already accepted callback.
|
||||
await remove(watch);
|
||||
stop(watch, group);
|
||||
return;
|
||||
}
|
||||
pending = undefined;
|
||||
retries = 0;
|
||||
warned = false;
|
||||
if (await step()) return;
|
||||
} catch (error) {
|
||||
if (signal.aborted) return;
|
||||
// Delivery and storage failures retain the captured outcome and durable intent.
|
||||
@@ -308,11 +405,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
|
||||
return {
|
||||
hasPendingForCaller(agentId) {
|
||||
if (recovering || registering.has(agentId)) return true;
|
||||
for (const group of watches.values()) {
|
||||
for (const watch of group) if (watch.records[0]!.callerAgentId === agentId) return true;
|
||||
}
|
||||
return false;
|
||||
return recovering || delegates(agentId);
|
||||
},
|
||||
start: () =>
|
||||
serialize(async () => {
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { setTimeout as pause } from "node:timers/promises";
|
||||
import type { FinishSubscription, FinishSubscriptionStore, PendingWork } from "../index.js";
|
||||
import type { FinishObservationResult } from "./observation-buffer.js";
|
||||
import type { FinishNotificationReason } from "./notification.js";
|
||||
|
||||
/** The followed child is still working when the follow limit passes. */
|
||||
export const FOLLOW_LIMIT = Symbol("follow limit");
|
||||
export type FollowOutcome = FinishObservationResult | typeof FOLLOW_LIMIT;
|
||||
|
||||
/** What the caller is told about one outcome. */
|
||||
export interface Notice {
|
||||
reason: FinishNotificationReason;
|
||||
result: FinishObservationResult | null;
|
||||
work: readonly PendingWork[];
|
||||
}
|
||||
|
||||
interface Options {
|
||||
/** The watch's coalesced records; any one already following makes the watch follow. */
|
||||
records: readonly FinishSubscription[];
|
||||
store: Pick<FinishSubscriptionStore, "put">;
|
||||
limitMs: number;
|
||||
/** Work that will start the child's next turn by itself, read when a turn ends. */
|
||||
pendingWork(): readonly PendingWork[];
|
||||
reasonFor(result: FinishObservationResult): FinishNotificationReason;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function createFollowing(options: Options) {
|
||||
let since = options.records
|
||||
.map((record) => record.followingSince)
|
||||
.filter((value) => value !== undefined)
|
||||
.sort()[0];
|
||||
let latest: FinishObservationResult | null = null;
|
||||
/** Set when something outside the child's own events may have settled it. */
|
||||
let stale = false;
|
||||
let wake: (() => void) | undefined;
|
||||
|
||||
/** The child's last idle outcome, decided again. Nothing while it waits on a permission. */
|
||||
function recheckOutcome(): FinishObservationResult | undefined {
|
||||
stale = false;
|
||||
if (latest?.status !== "idle") return undefined;
|
||||
return { ...latest, workChanged: true };
|
||||
}
|
||||
|
||||
async function follow(): Promise<void> {
|
||||
const followingSince = new Date().toISOString();
|
||||
// Written before the notice is sent, so a restart never repeats it.
|
||||
for (const record of options.records) await options.store.put({ ...record, followingSince });
|
||||
since = followingSince;
|
||||
}
|
||||
|
||||
return {
|
||||
/** The observed outcome, or the follow limit once a followed child runs out of time. */
|
||||
async next(observed: Promise<FinishObservationResult>, signal: AbortSignal) {
|
||||
if (!since) return observed;
|
||||
// The losing side settles when the observation closes.
|
||||
observed.catch(() => undefined);
|
||||
const rechecked = stale && recheckOutcome();
|
||||
if (rechecked) return rechecked;
|
||||
const timer = new AbortController();
|
||||
const limit = pause(
|
||||
Math.max(0, Date.parse(since) + options.limitMs - Date.now()),
|
||||
FOLLOW_LIMIT,
|
||||
{ signal: AbortSignal.any([signal, timer.signal]) },
|
||||
);
|
||||
limit.catch(() => undefined);
|
||||
const recheck = new Promise<FinishObservationResult>((resolve) => {
|
||||
wake = () => {
|
||||
const outcome = recheckOutcome();
|
||||
if (outcome) resolve(outcome);
|
||||
};
|
||||
});
|
||||
try {
|
||||
return await Promise.race<FollowOutcome>([observed, limit, recheck]);
|
||||
} finally {
|
||||
wake = undefined;
|
||||
timer.abort();
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Decides the child's state again without an event from it, as when a delegation of its
|
||||
* own ended without reporting back. Only a followed child is decided again.
|
||||
*/
|
||||
recheck() {
|
||||
if (!since) return;
|
||||
stale = true;
|
||||
wake?.();
|
||||
},
|
||||
/** Returns nothing when the outcome is not worth telling the caller. */
|
||||
async decide(outcome: FollowOutcome): Promise<Notice | undefined> {
|
||||
if (outcome === FOLLOW_LIMIT)
|
||||
return { reason: "is still working", result: latest, work: options.pendingWork() };
|
||||
latest = outcome;
|
||||
const reason = options.reasonFor(outcome);
|
||||
if (reason !== "finished") return { reason, result: outcome, work: [] };
|
||||
// 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 };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -11,6 +11,7 @@ const recordsSchema = z.array(
|
||||
childAgentId: z.string().min(1),
|
||||
serverId: z.string().min(1).optional(),
|
||||
requireParentOwnership: z.boolean().optional(),
|
||||
followingSince: z.iso.datetime().optional(),
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
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"
|
||||
@@ -19,8 +24,23 @@ export const finishNotificationEvents = {
|
||||
"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",
|
||||
"queued messages": "queued messages",
|
||||
"delegated agents": "agents it is waiting on",
|
||||
};
|
||||
|
||||
const FINISH_NOTIFICATION_MESSAGE_LIMIT = 4000;
|
||||
|
||||
interface FinishNotificationBodyInput {
|
||||
@@ -30,6 +50,7 @@ interface FinishNotificationBodyInput {
|
||||
reason: FinishNotificationReason;
|
||||
lastAssistantMessage: string | null;
|
||||
permissionRequest?: AgentPermissionRequest;
|
||||
pendingWork?: readonly PendingWork[];
|
||||
}
|
||||
|
||||
export function formatFinishNotificationBody(params: FinishNotificationBodyInput): string {
|
||||
@@ -40,9 +61,20 @@ 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 statusLine = `Agent ${params.childAgentId} (${params.title}) ${params.reason}.`;
|
||||
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 sections = [statusLine];
|
||||
if (params.serverId) sections.push(`Server: ${params.serverId}`);
|
||||
if (params.reason === "ended its turn but is still working")
|
||||
sections.push(
|
||||
"This is not its final reply. You will be notified when it finishes, errors, or needs permission.",
|
||||
);
|
||||
if (params.reason === "is still working")
|
||||
sections.push(
|
||||
"This finish subscription has ended without a final reply. Check the agent with `get_agent_status`.",
|
||||
);
|
||||
if (params.reason === "needs permission" && params.permissionRequest) {
|
||||
sections.push(
|
||||
"Respond with `respond_to_permission` using the `agentId` and `requestId` below.",
|
||||
|
||||
+3
-1
@@ -2,6 +2,8 @@ import type { WaitForFinishResult } from "@getpaseo/client/internal/daemon-clien
|
||||
|
||||
export type FinishObservationResult = WaitForFinishResult & {
|
||||
reason?: "was canceled" | "host unreachable" | "host removed";
|
||||
/** The idle child's background work changed without a turn ending. */
|
||||
workChanged?: true;
|
||||
};
|
||||
|
||||
/** Coalesces duplicate checkpoints and retains one terminal result while delivery is pending. */
|
||||
@@ -23,7 +25,7 @@ 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 terminal = result;
|
||||
} else if (!result.workChanged || !terminal || terminal.workChanged) terminal = result;
|
||||
wake?.();
|
||||
}
|
||||
return {
|
||||
|
||||
@@ -33,6 +33,12 @@ function observeState(
|
||||
return;
|
||||
}
|
||||
if (event?.type === "turn_started") return;
|
||||
if (event?.type === "background_work") {
|
||||
// An idle child's work can settle without another turn.
|
||||
if (snapshot.status === "idle")
|
||||
buffer.push({ status: "idle", final: snapshot, lastMessage, error: null, workChanged: true });
|
||||
return;
|
||||
}
|
||||
if (event?.type === "permission_requested") {
|
||||
buffer.push({
|
||||
status: "permission",
|
||||
|
||||
@@ -8,7 +8,7 @@ import { createHostObservationResolver, type ToolHosts } from "../../host-operat
|
||||
import { openFinishObservation } from "./observation-stream.js";
|
||||
import type { AgentStreamEvent } from "../../agent-sdk-types.js";
|
||||
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
|
||||
import type { FinishObservation } from "../index.js";
|
||||
import type { FinishObservation, PendingWork } from "../index.js";
|
||||
|
||||
export function createFinishObservation(input: {
|
||||
agentManager: AgentManager;
|
||||
@@ -74,7 +74,15 @@ export function createFinishObservation(input: {
|
||||
(event) => {
|
||||
if (event.type === "agent_state" && event.agent.lifecycle !== "idle")
|
||||
publish(toAgentPayload(event.agent, { title: stored?.title }));
|
||||
else if (
|
||||
else if (event.type === "background_work") {
|
||||
const current = agentManager.getAgent(agentId);
|
||||
if (current)
|
||||
publish(toAgentPayload(current, { title: stored?.title }), {
|
||||
type: "background_work",
|
||||
provider: current.provider,
|
||||
items: event.items,
|
||||
});
|
||||
} else if (
|
||||
event.type === "agent_stream" &&
|
||||
[
|
||||
"permission_requested",
|
||||
@@ -114,5 +122,16 @@ export function createFinishObservation(input: {
|
||||
},
|
||||
},
|
||||
});
|
||||
return { open: (record, signal) => openFinishObservation(resolver, record, signal) };
|
||||
return {
|
||||
open: (record, signal) => openFinishObservation(resolver, record, signal),
|
||||
pendingWork(record) {
|
||||
// Only this daemon can tell what will wake its own agents.
|
||||
if (record.serverId && record.serverId !== input.serverId) return [];
|
||||
const work: PendingWork[] = [];
|
||||
if (agentManager.getAgent(record.childAgentId)?.lifecycle === "running") work.push("turn");
|
||||
if (agentManager.hasPendingWakeup(record.childAgentId)) work.push("background work");
|
||||
if (input.messages().hasPending(record.childAgentId)) work.push("queued messages");
|
||||
return work;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -903,35 +903,42 @@ async function createAgentMcpServer(
|
||||
options: Parameters<typeof createAgentMcpServerWithDependencies>[0],
|
||||
subscriptionStore?: FinishSubscriptionStore,
|
||||
schedule?: (delayMs: number, callback: () => void) => () => void,
|
||||
/** Another caller's server on the same daemon: shares its message delivery and subscriptions. */
|
||||
daemonOf?: object,
|
||||
) {
|
||||
const messages = createTestAgentMessages({ ...options, schedule });
|
||||
const messages =
|
||||
(daemonOf && serverDeliveries.get(daemonOf)) ||
|
||||
createTestAgentMessages({ ...options, schedule });
|
||||
const records = new Map<string, FinishSubscription>();
|
||||
const subscriptions = createFinishSubscriptions({
|
||||
store: subscriptionStore ?? {
|
||||
list: async () => [...records.values()],
|
||||
put: async (record) => {
|
||||
records.set(record.id, record);
|
||||
const existingSubscriptions = daemonOf && serverSubscriptions.get(daemonOf);
|
||||
const subscriptions =
|
||||
existingSubscriptions ||
|
||||
createFinishSubscriptions({
|
||||
store: subscriptionStore ?? {
|
||||
list: async () => [...records.values()],
|
||||
put: async (record) => {
|
||||
records.set(record.id, record);
|
||||
},
|
||||
remove: async (id) => {
|
||||
records.delete(id);
|
||||
},
|
||||
},
|
||||
remove: async (id) => {
|
||||
records.delete(id);
|
||||
},
|
||||
},
|
||||
messages: () => messages,
|
||||
callerIsActive: async (id) => !(await options.agentStorage.get(id))?.archivedAt,
|
||||
serverId: options.serverId ?? "self",
|
||||
logger: options.logger,
|
||||
...createFinishObservation({
|
||||
...options,
|
||||
waitForResume: async () => {},
|
||||
messages: () => messages,
|
||||
callerIsActive: async (id) => !(await options.agentStorage.get(id))?.archivedAt,
|
||||
serverId: options.serverId ?? "self",
|
||||
hosts: () => {
|
||||
if (!options.hosts) throw new Error("No hosts");
|
||||
return options.hosts();
|
||||
},
|
||||
}),
|
||||
});
|
||||
subscriptionServices.push(subscriptions);
|
||||
logger: options.logger,
|
||||
...createFinishObservation({
|
||||
...options,
|
||||
waitForResume: async () => {},
|
||||
messages: () => messages,
|
||||
serverId: options.serverId ?? "self",
|
||||
hosts: () => {
|
||||
if (!options.hosts) throw new Error("No hosts");
|
||||
return options.hosts();
|
||||
},
|
||||
}),
|
||||
});
|
||||
if (!existingSubscriptions) subscriptionServices.push(subscriptions);
|
||||
const server = await createAgentMcpServerWithDependencies({
|
||||
agentMessages: () => messages,
|
||||
finishSubscriptions: () => subscriptions,
|
||||
@@ -3628,6 +3635,8 @@ class HeldTurnAgentSession implements AgentSession {
|
||||
private interruptGate: Promise<void> | null = null;
|
||||
private closeGate?: { signalStart: () => void; waitForRelease: Promise<void> };
|
||||
private nextStartError: Error | null = null;
|
||||
/** Work this session started will start a turn by itself, as a Claude background task does. */
|
||||
pendingWakeup = false;
|
||||
|
||||
constructor(
|
||||
readonly provider: AgentProvider,
|
||||
@@ -3663,6 +3672,26 @@ class HeldTurnAgentSession implements AgentSession {
|
||||
this.nextStartError = error;
|
||||
}
|
||||
|
||||
hasPendingWakeup(): boolean {
|
||||
return this.pendingWakeup;
|
||||
}
|
||||
|
||||
publishBackgroundWork(items: Array<{ id: string; description: string }>): void {
|
||||
this.pushEvent({
|
||||
type: "background_work",
|
||||
provider: this.provider,
|
||||
items: items.map((item) => ({ ...item, kind: "shell" })),
|
||||
});
|
||||
}
|
||||
|
||||
/** The provider wakes the session without a prompt, the way a background task completion does. */
|
||||
startAutonomousTurn(): void {
|
||||
if (this.activeTurnId) throw new Error("A turn is already running");
|
||||
const turnId = `autonomous-${randomUUID()}`;
|
||||
this.activeTurnId = turnId;
|
||||
this.pushEvent({ type: "turn_started", provider: this.provider, turnId });
|
||||
}
|
||||
|
||||
tryHandleOutOfBand(prompt: AgentPromptInput) {
|
||||
return prompt === "/side-command" ? { run: async () => {} } : null;
|
||||
}
|
||||
@@ -5226,6 +5255,202 @@ describe("message order for one recipient", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("finish notifications for a child that ends its turn while still working", () => {
|
||||
const logger = createTestLogger();
|
||||
const existingCwd = process.cwd();
|
||||
|
||||
async function setup() {
|
||||
const workdir = await mkdtemp(join(tmpdir(), "mcp-still-working-"));
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const parentClient = new HeldTurnAgentClient("claude", false);
|
||||
const childClient = new HeldTurnAgentClient("codex", true);
|
||||
const agentManager = new AgentManager({
|
||||
clients: { claude: parentClient, codex: childClient },
|
||||
registry: storage,
|
||||
logger,
|
||||
});
|
||||
const parent = await agentManager.createAgent(
|
||||
{ provider: "claude", cwd: existingCwd },
|
||||
undefined,
|
||||
{ workspaceId: "wks_parent" },
|
||||
);
|
||||
const server = await createAgentMcpServer({
|
||||
agentManager,
|
||||
agentStorage: storage,
|
||||
callerAgentId: parent.id,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
});
|
||||
async function createChild(from: typeof server, title: string) {
|
||||
const created = await invokeToolWithParsedInput(registeredTool(from, "create_agent"), {
|
||||
relationship: { kind: "subagent" },
|
||||
workspace: { kind: "current" },
|
||||
title,
|
||||
provider: "codex/gpt-5.4",
|
||||
initialPrompt: "Build it",
|
||||
});
|
||||
const id = z.object({ agentId: z.string() }).parse(created.structuredContent).agentId;
|
||||
await vi.waitFor(() => expect(agentManager.getAgent(id)?.lifecycle).toBe("running"));
|
||||
const session = childClient.sessions.at(-1)!;
|
||||
return { id, session };
|
||||
}
|
||||
const parentPrompts = () => parentClient.sessions[0]?.prompts ?? [];
|
||||
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();
|
||||
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");
|
||||
|
||||
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("WAITING for the build");
|
||||
expect(parseAgentMessage(parentPrompts()[0]!)).toMatchObject({
|
||||
source: { kind: "agent-notification", agentId: child.id, event: "message" },
|
||||
});
|
||||
|
||||
// Claude publishes the empty roster before the turn its task notification starts.
|
||||
child.session.publishBackgroundWork([]);
|
||||
child.session.startAutonomousTurn();
|
||||
await vi.waitFor(() => expect(agentManager.getAgent(child.id)?.lifecycle).toBe("running"));
|
||||
child.session.pendingWakeup = false;
|
||||
child.session.finishTurn("FINAL: done");
|
||||
|
||||
await vi.waitFor(() => expect(parentPrompts()).toHaveLength(2));
|
||||
expect(parentPrompts()[1]).toContain(`Agent ${child.id} (Builder) finished.`);
|
||||
expect(parentPrompts()[1]).toContain("FINAL: done");
|
||||
expect(parseAgentMessage(parentPrompts()[1]!)).toMatchObject({
|
||||
source: { kind: "agent-notification", agentId: child.id, event: "finished" },
|
||||
});
|
||||
|
||||
// A turn after the child settled, as a person starts in the app, 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);
|
||||
}
|
||||
});
|
||||
|
||||
it("reports finished when the child's background work drains without another turn", async () => {
|
||||
const { workdir, storage, agentManager, server, createChild, parentPrompts } = await setup();
|
||||
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");
|
||||
|
||||
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");
|
||||
} finally {
|
||||
await removeAgentStateDir(agentManager, storage, workdir);
|
||||
}
|
||||
});
|
||||
|
||||
it("a heartbeat does not hold the child's finish notification", async () => {
|
||||
const { workdir, storage, agentManager, server, createChild, parentPrompts } = await setup();
|
||||
try {
|
||||
const child = await createChild(server, "Watcher");
|
||||
agentManager.setDaemonBackgroundWork({
|
||||
agentId: child.id,
|
||||
namespace: "heartbeat",
|
||||
id: "check-ci",
|
||||
kind: "heartbeat",
|
||||
countsAsRunning: false,
|
||||
description: "Check CI",
|
||||
startedAt: new Date().toISOString(),
|
||||
stop: async () => {},
|
||||
});
|
||||
child.session.finishTurn("Done; a heartbeat checks CI");
|
||||
await vi.waitFor(() => expect(parentPrompts()).toHaveLength(1));
|
||||
expect(parentPrompts()[0]).toContain(`Agent ${child.id} (Watcher) finished.`);
|
||||
} finally {
|
||||
await removeAgentStateDir(agentManager, storage, workdir);
|
||||
}
|
||||
});
|
||||
|
||||
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();
|
||||
try {
|
||||
const helper = await createChild(server, "Helper");
|
||||
const helperServer = await createAgentMcpServer(
|
||||
{
|
||||
agentManager,
|
||||
agentStorage: storage,
|
||||
callerAgentId: helper.id,
|
||||
providerSnapshotManager: createOpenCodeManager().manager,
|
||||
logger,
|
||||
},
|
||||
undefined,
|
||||
undefined,
|
||||
server,
|
||||
);
|
||||
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.`,
|
||||
);
|
||||
|
||||
sub.session.finishTurn("SUB RESULT");
|
||||
// The sub helper's finish starts the helper's next turn.
|
||||
await vi.waitFor(() => expect(helper.session.prompts).toHaveLength(2));
|
||||
expect(helper.session.prompts[1]).toContain(`Agent ${sub.id} (Sub helper) finished.`);
|
||||
await vi.waitFor(() => expect(agentManager.getAgent(helper.id)?.lifecycle).toBe("running"));
|
||||
helper.session.finishTurn("HELPER FINAL");
|
||||
|
||||
await vi.waitFor(() => expect(parentPrompts()).toHaveLength(2));
|
||||
expect(parentPrompts()[1]).toContain(`Agent ${helper.id} (Helper) finished.`);
|
||||
expect(parentPrompts()[1]).toContain("HELPER FINAL");
|
||||
} 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();
|
||||
try {
|
||||
const child = await createChild(server, "Planner");
|
||||
child.session.pendingWakeup = true;
|
||||
child.session.finishTurn("Waiting for research");
|
||||
await vi.waitFor(() => expect(parentPrompts()).toHaveLength(1));
|
||||
|
||||
child.session.startAutonomousTurn();
|
||||
child.session.pendingWakeup = false;
|
||||
child.session.requestPermission("plan-approval");
|
||||
await vi.waitFor(() => expect(parentPrompts()).toHaveLength(2));
|
||||
expect(parentPrompts()[1]).toContain("needs permission");
|
||||
expect(parentPrompts()[1]).toContain("plan-approval");
|
||||
|
||||
await invokeToolWithParsedInput(registeredTool(server, "respond_to_permission"), {
|
||||
agentId: child.id,
|
||||
requestId: "plan-approval",
|
||||
response: { behavior: "allow" },
|
||||
});
|
||||
child.session.finishTurn("Plan executed");
|
||||
await vi.waitFor(() => expect(parentPrompts()).toHaveLength(3));
|
||||
expect(parentPrompts()[2]).toContain(`Agent ${child.id} (Planner) finished.`);
|
||||
expect(parentPrompts()[2]).toContain("Plan executed");
|
||||
} finally {
|
||||
await removeAgentStateDir(agentManager, storage, workdir);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("send_agent_prompt MCP tool to an OMP child", () => {
|
||||
const logger = createTestLogger();
|
||||
const existingCwd = process.cwd();
|
||||
|
||||
@@ -495,6 +495,7 @@ export function wrapSessionProvider(provider: AgentProvider, inner: AgentSession
|
||||
stopBackgroundWork: inner.stopBackgroundWork?.bind(inner),
|
||||
close: () => inner.close(),
|
||||
canStopRuntime: inner.canStopRuntime?.bind(inner),
|
||||
hasPendingWakeup: inner.hasPendingWakeup?.bind(inner),
|
||||
listCommands: inner.listCommands?.bind(inner),
|
||||
setModel: inner.setModel?.bind(inner),
|
||||
setThinkingOption: inner.setThinkingOption?.bind(inner),
|
||||
|
||||
+64
-15
@@ -864,7 +864,8 @@ test("Claude session started by a control request without a turn can stop its ru
|
||||
}
|
||||
});
|
||||
|
||||
test("Claude session runtime safety observes pumped background work and autonomous replies", async () => {
|
||||
/** A Claude session whose SDK stream the test feeds one message at a time. */
|
||||
async function createPumpedClaudeSession() {
|
||||
let wake: (() => void) | undefined;
|
||||
const channel = { closed: false };
|
||||
const queue: Array<{ message: SDKMessage; consumed(): void }> = [];
|
||||
@@ -937,12 +938,33 @@ test("Claude session runtime safety observes pumped background work and autonomo
|
||||
usage: { input_tokens: 1, output_tokens: 1 },
|
||||
total_cost_usd: 0,
|
||||
};
|
||||
try {
|
||||
await session.startTurn("start background work");
|
||||
// A session-only cron lives in this process, and Claude reports it only to the Stop hook.
|
||||
const stop = (session_crons: SessionCronSummary[]) => {
|
||||
const stopInput: StopHookInput = {
|
||||
hook_event_name: "Stop",
|
||||
session_id: "runtime-safety",
|
||||
transcript_path: "",
|
||||
cwd: process.cwd(),
|
||||
stop_hook_active: false,
|
||||
session_crons,
|
||||
};
|
||||
return stopHook!(stopInput, undefined, { signal: new AbortController().signal });
|
||||
};
|
||||
/** Starts a foreground turn and returns once Claude has opened it. */
|
||||
async function startTurn(prompt: string) {
|
||||
await session.startTurn(prompt);
|
||||
await connection;
|
||||
const input = await nativeInput.next();
|
||||
await push({ type: "command_lifecycle", command_uuid: input.value.uuid, state: "started" });
|
||||
await push(init);
|
||||
}
|
||||
return { session, push, stop, startTurn, init, result };
|
||||
}
|
||||
|
||||
test("Claude session runtime safety observes pumped background work and autonomous replies", async () => {
|
||||
const { session, push, stop, startTurn, init, result } = await createPumpedClaudeSession();
|
||||
try {
|
||||
await startTurn("start background work");
|
||||
await push(result);
|
||||
expect(await session.canStopRuntime!()).toBe(true);
|
||||
await push({
|
||||
@@ -966,18 +988,6 @@ test("Claude session runtime safety observes pumped background work and autonomo
|
||||
expect(await session.canStopRuntime!()).toBe(false);
|
||||
await push(result);
|
||||
expect(await session.canStopRuntime!()).toBe(true);
|
||||
// A session-only cron lives in this process, and Claude reports it only to the Stop hook.
|
||||
const stop = (session_crons: SessionCronSummary[]) => {
|
||||
const stopInput: StopHookInput = {
|
||||
hook_event_name: "Stop",
|
||||
session_id: "runtime-safety",
|
||||
transcript_path: "",
|
||||
cwd: process.cwd(),
|
||||
stop_hook_active: false,
|
||||
session_crons,
|
||||
};
|
||||
return stopHook!(stopInput, undefined, { signal: new AbortController().signal });
|
||||
};
|
||||
await stop([{ id: "99eb0b69", schedule: "0 */6 * * *", recurring: true, prompt: "say hi" }]);
|
||||
expect(await session.canStopRuntime!()).toBe(false);
|
||||
await stop([]);
|
||||
@@ -986,3 +996,42 @@ test("Claude session runtime safety observes pumped background work and autonomo
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("Claude session reports a pending wakeup until the turn its background work starts", async () => {
|
||||
const { session, push, stop, startTurn, init, result } = await createPumpedClaudeSession();
|
||||
try {
|
||||
await startTurn("run the build in the background");
|
||||
await push({
|
||||
type: "system",
|
||||
subtype: "background_tasks_changed",
|
||||
tasks: [{ task_id: "build", task_type: "local_bash", description: "npm run build" }],
|
||||
});
|
||||
await push(result);
|
||||
expect(session.hasPendingWakeup!()).toBe(true);
|
||||
// Claude's order at wake-up: the notification, the empty roster, then the new turn.
|
||||
await push({
|
||||
type: "system",
|
||||
subtype: "task_notification",
|
||||
task_id: "build",
|
||||
status: "completed",
|
||||
output: "built",
|
||||
summary: "built",
|
||||
});
|
||||
await push({ type: "system", subtype: "background_tasks_changed", tasks: [] });
|
||||
expect(session.hasPendingWakeup!()).toBe(true);
|
||||
await push(init);
|
||||
expect(session.hasPendingWakeup!()).toBe(false);
|
||||
await push(result);
|
||||
expect(session.hasPendingWakeup!()).toBe(false);
|
||||
|
||||
// A one-shot wakeup starts a turn by itself; a recurring cron never settles.
|
||||
const wakeup = { id: "wake", schedule: "30 14 26 11 *", recurring: false, prompt: "check" };
|
||||
const cron = { id: "cron", schedule: "0 */6 * * *", recurring: true, prompt: "say hi" };
|
||||
await stop([wakeup, cron]);
|
||||
expect(session.hasPendingWakeup!()).toBe(true);
|
||||
await stop([cron]);
|
||||
expect(session.hasPendingWakeup!()).toBe(false);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -348,6 +348,41 @@ describe("Claude runtime exit", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("reports the failure before it empties background work when the idle process dies", async () => {
|
||||
let capturedOptions: Options | undefined;
|
||||
const queryFactory = vi.fn(({ options }: ClaudeQueryInput) => {
|
||||
capturedOptions = options;
|
||||
return createQueryMock(BACKGROUND_SHELL_TURN_EVENTS);
|
||||
});
|
||||
const child = createChildProcessStub();
|
||||
vi.spyOn(spawnUtils, "spawnProcess").mockReturnValue(child);
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
queryFactory,
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
});
|
||||
const session = await client.createSession({ provider: "claude", cwd: process.cwd() });
|
||||
|
||||
try {
|
||||
await session.run("start a background shell");
|
||||
capturedOptions?.spawnClaudeCodeProcess?.(SPAWN_OPTIONS);
|
||||
const events: AgentStreamEvent[] = [];
|
||||
session.subscribe((event) => events.push(event));
|
||||
|
||||
child.emit("exit", 1, null);
|
||||
|
||||
// A watcher that sees the work end first takes the idle child for settled.
|
||||
expect(
|
||||
events
|
||||
.filter((event) => event.type === "turn_failed" || event.type === "background_work")
|
||||
.map((event) => event.type),
|
||||
).toEqual(["turn_failed", "background_work"]);
|
||||
expect(session.hasPendingWakeup?.()).toBe(false);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("empties background work when a query restart retires the process", async () => {
|
||||
let capturedOptions: Options | undefined;
|
||||
const child = createChildProcessStub();
|
||||
|
||||
@@ -3329,6 +3329,11 @@ class ClaudeAgentSession implements AgentSession {
|
||||
return this.persistence;
|
||||
}
|
||||
|
||||
hasPendingWakeup(): boolean {
|
||||
// A delivered task notification opens its turn only with the next init.
|
||||
return this.notificationTurnId !== null || this.runtimeSafety.hasPendingWakeup();
|
||||
}
|
||||
|
||||
async canStopRuntime(): Promise<boolean> {
|
||||
return (
|
||||
!this.activeForegroundTurnId &&
|
||||
@@ -4491,8 +4496,8 @@ class ClaudeAgentSession implements AgentSession {
|
||||
{ agentId: this.agentId, pid: child.pid, code, signal },
|
||||
"Claude runtime exited unexpectedly",
|
||||
);
|
||||
this.failRunningRuntimeTasks();
|
||||
if (this.activeForegroundTurnId || this.autonomousTurn) {
|
||||
this.failRunningRuntimeTasks();
|
||||
// The pump is about to throw. It waits for stderr to flush and reports the
|
||||
// real cause; reporting here first would replace that with a bare exit code
|
||||
// and detach this.query, which is how the pump recognizes its own stream.
|
||||
@@ -4502,11 +4507,14 @@ class ClaudeAgentSession implements AgentSession {
|
||||
// failing against a dead transport forever.
|
||||
this.query = null;
|
||||
this.input = null;
|
||||
// The failure goes first: an idle agent whose background work just ended
|
||||
// otherwise reads as settled to anyone waiting for it to finish.
|
||||
this.dispatchEvents([
|
||||
this.buildTurnFailedEvent(
|
||||
`Claude stopped unexpectedly (${signal ? `signal ${signal}` : `exit code ${code ?? "unknown"}`}). Any background shells, monitors or other work it had running were terminated with it.`,
|
||||
),
|
||||
]);
|
||||
this.failRunningRuntimeTasks();
|
||||
}
|
||||
|
||||
private failRunningRuntimeTasks(): void {
|
||||
|
||||
@@ -23,9 +23,12 @@ export class ClaudeRuntimeSafety {
|
||||
// count unknown until the next Stop, so an interrupted or failed turn keeps the runtime.
|
||||
private sessionCrons = 0;
|
||||
private sessionCronsUnknown = false;
|
||||
// One-shot wakeups (ScheduleWakeup) start a turn by themselves; recurring crons never settle.
|
||||
private oneShotWakeups = 0;
|
||||
|
||||
reset(): void {
|
||||
this.sessionCrons = 0;
|
||||
this.oneShotWakeups = 0;
|
||||
this.sessionCronsUnknown = false;
|
||||
this.inventoryState = "unknown";
|
||||
this.turnSeen = false;
|
||||
@@ -51,7 +54,20 @@ export class ClaudeRuntimeSafety {
|
||||
observeStop(sessionCrons: readonly SessionCronSummary[] | undefined): void {
|
||||
if (this.inventoryState === "retired") return;
|
||||
this.sessionCronsUnknown = false;
|
||||
if (sessionCrons) this.sessionCrons = sessionCrons.length;
|
||||
if (sessionCrons) {
|
||||
this.sessionCrons = sessionCrons.length;
|
||||
this.oneShotWakeups = sessionCrons.filter((cron) => !cron.recurring).length;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True while a live background task or an undelivered task notification will start a turn,
|
||||
* or a one-shot wakeup is scheduled. Recurring crons are excluded: they never settle.
|
||||
*/
|
||||
hasPendingWakeup(): boolean {
|
||||
return (
|
||||
this.liveTasks.length > 0 || this.awaitingNotifications.size > 0 || this.oneShotWakeups > 0
|
||||
);
|
||||
}
|
||||
|
||||
/** Returns a full replacement only when the visible inventory changes. */
|
||||
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { experimental_createMCPClient } from "ai";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import pino from "pino";
|
||||
import { beforeAll, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { parseAgentMessage } from "../agent/agent-messages/index.js";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { canRunRealProvider, createRealProviderClients } from "./real-provider-test-config.js";
|
||||
|
||||
const CallToolResultSchema = z.object({
|
||||
structuredContent: z.object({ agentId: z.string() }),
|
||||
});
|
||||
|
||||
async function createAgentAs(port: number, callerAgentId: string, args: Record<string, unknown>) {
|
||||
const url = new URL(`http://127.0.0.1:${port}/mcp/agents`);
|
||||
url.searchParams.set("callerAgentId", callerAgentId);
|
||||
const mcp = await experimental_createMCPClient({
|
||||
transport: new StreamableHTTPClientTransport(url),
|
||||
});
|
||||
try {
|
||||
const callTool = Reflect.get(mcp, "callTool").bind(mcp);
|
||||
const result = await callTool({ name: "create_agent", args });
|
||||
return CallToolResultSchema.parse(result).structuredContent.agentId;
|
||||
} finally {
|
||||
await mcp.close();
|
||||
}
|
||||
}
|
||||
|
||||
describe("daemon E2E (real claude) - finish notification across a background wake-up", () => {
|
||||
let canRun = false;
|
||||
|
||||
beforeAll(async () => {
|
||||
canRun = await canRunRealProvider("claude");
|
||||
});
|
||||
|
||||
beforeEach((context) => {
|
||||
if (!canRun) context.skip();
|
||||
});
|
||||
|
||||
test("the caller hears the child is still working, then gets its autonomous final reply", async () => {
|
||||
const logger = pino({ level: "silent" });
|
||||
const cwd = mkdtempSync(path.join(tmpdir(), "daemon-real-claude-finish-wake-"));
|
||||
const callerPrompts: string[] = [];
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
agentClients: {
|
||||
...createTestAgentClients({
|
||||
onStartTurn(prompt, config) {
|
||||
if (config.title === "Finish caller" && typeof prompt === "string")
|
||||
callerPrompts.push(prompt);
|
||||
},
|
||||
}),
|
||||
...createRealProviderClients(["claude"], logger),
|
||||
},
|
||||
logger,
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
const token = `FINAL_${Date.now().toString(36)}`;
|
||||
|
||||
try {
|
||||
await client.connect();
|
||||
const caller = await client.createAgent({
|
||||
provider: "codex",
|
||||
cwd,
|
||||
title: "Finish caller",
|
||||
modeId: "full-access",
|
||||
});
|
||||
const childId = await createAgentAs(daemon.port, caller.id, {
|
||||
relationship: { kind: "subagent" },
|
||||
workspace: { kind: "current" },
|
||||
provider: "claude/haiku",
|
||||
title: "Background child",
|
||||
notifyOnFinish: true,
|
||||
settings: { modeId: "bypassPermissions" },
|
||||
initialPrompt: [
|
||||
"Use the Bash tool with run_in_background: true to run exactly: sleep 20",
|
||||
"Do not wait or poll for it.",
|
||||
"Reply immediately with exactly: SPAWNED",
|
||||
`When the background task completes later, reply with exactly: ${token}`,
|
||||
].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,
|
||||
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);
|
||||
expect(daemon.daemon.agentManager.getAgent(childId)?.lifecycle).toBe("idle");
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}
|
||||
}, 420_000);
|
||||
});
|
||||
Reference in New Issue
Block a user