diff --git a/CHANGELOG.md b/CHANGELOG.md index 829b4cd43..8db989067 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,9 @@ starts with **Upgrade notes**: read them before you upgrade. The upgrade procedu - The GitHub powers `vulnerability_alerts:read` (list Dependabot alerts) and `vulnerability_alerts:write` (dismiss one). ([#1822]) +- A session that spawns a child session gets a new prompt when the child finishes a turn. + The prompt carries the child's outcome and its last message, so the parent does not have + to poll for it. ([#1825]) ### Fixed @@ -436,3 +439,4 @@ The first tagged release. See the [#1788]: https://github.com/cortexapps/engrams/pull/1788 [#1789]: https://github.com/cortexapps/engrams/pull/1789 [#1822]: https://github.com/cortexapps/engrams/pull/1822 +[#1825]: https://github.com/cortexapps/engrams/pull/1825 diff --git a/orchestrator/src/listeners/__tests__/child-report-consumer.test.ts b/orchestrator/src/listeners/__tests__/child-report-consumer.test.ts new file mode 100644 index 000000000..cedf4aca0 --- /dev/null +++ b/orchestrator/src/listeners/__tests__/child-report-consumer.test.ts @@ -0,0 +1,181 @@ +import { describe, expect, test } from "bun:test"; +import { Code, ConnectError } from "@connectrpc/connect"; + +import type { CuratedEvent } from "../../control-plane/session-events.ts"; +import { + childReportPromptId, + makeChildReportConsumer, + REPORT_MESSAGE_CHARS, + renderChildReport, + type SpawnedChild, +} from "../child-report-consumer.ts"; + +const CHILD = "11111111-1111-4111-8111-111111111111"; +const PARENT = "22222222-2222-4222-8222-222222222222"; +const ctx = { sessionId: CHILD }; + +const openChild: SpawnedChild = { + canonicalTaskName: "build/tests", + taskStatus: "working", + parentSessionId: PARENT, +}; + +function assistant(idx: bigint, runId: string, text: string): CuratedEvent { + return { + idx, + kind: "agent_message", + payloadJson: JSON.stringify({ run_id: runId, role: "assistant", text }), + }; +} + +function userEcho(idx: bigint, text: string): CuratedEvent { + return { + idx, + kind: "agent_message", + payloadJson: JSON.stringify({ run_id: "", role: "user", text }), + }; +} + +function runCompleted(idx: bigint, runId: string, ok = true): CuratedEvent { + return { idx, kind: "run_completed", payloadJson: JSON.stringify({ run_id: runId, ok }) }; +} + +function harness( + child: SpawnedChild | null, + send: (input: { sessionId: string; promptId: string; text: string }) => Promise = async () => {}, +) { + const sent: Array<{ sessionId: string; promptId: string; text: string }> = []; + const consumer = makeChildReportConsumer({ + findSpawnedChild: async () => child, + sendPrompt: async (input) => { + await send(input); + sent.push(input); + }, + }); + return { consumer, sent }; +} + +describe("child report consumer", () => { + test("a child run end sends one prompt to the parent with the last assistant message", async () => { + const { consumer, sent } = harness(openChild); + expect(await consumer.appliesTo(CHILD)).toBe(true); + + await consumer.handle(userEcho(1n, "run the tests"), ctx); + await consumer.handle(assistant(2n, "r1", "Starting."), ctx); + await consumer.handle({ idx: 3n, kind: "tool_call_completed", payloadJson: "{}" }, ctx); + await consumer.handle(assistant(4n, "r1", "All 12 tests pass."), ctx); + await consumer.handle(runCompleted(5n, "r1"), ctx); + + expect(sent).toEqual([ + { + sessionId: PARENT, + promptId: childReportPromptId(CHILD, "r1"), + text: + `Child session "build/tests" (${CHILD}) finished a turn (completed).\n\n` + + "All 12 tests pass.\n\nUse read_session for its full output.", + }, + ]); + }); + + test("a failed run and an interrupted run name their outcome", async () => { + const { consumer, sent } = harness(openChild); + await consumer.handle(runCompleted(1n, "r1", false), ctx); + await consumer.handle({ idx: 2n, kind: "run_interrupted", payloadJson: '{"run_id":"r2"}' }, ctx); + expect(sent.map((s) => s.text.split("\n")[0])).toEqual([ + `Child session "build/tests" (${CHILD}) finished a turn (failed).`, + `Child session "build/tests" (${CHILD}) finished a turn (interrupted).`, + ]); + expect(sent[0]!.text).toContain("The child sent no assistant message in this turn."); + }); + + test("the cursor holds before an unreported message, so a restart replays it", async () => { + const { consumer } = harness(openChild); + expect(await consumer.handle(userEcho(1n, "go"), ctx)).toBeUndefined(); + expect(await consumer.handle(assistant(2n, "r1", "Working."), ctx)).toBe(1n); + expect(await consumer.handle({ idx: 3n, kind: "file_changed", payloadJson: "{}" }, ctx)).toBe(1n); + expect(await consumer.handle(assistant(4n, "r1", "Done."), ctx)).toBe(3n); + expect(await consumer.handle(runCompleted(5n, "r1"), ctx)).toBeUndefined(); + }); + + test("a redelivered run end after a restart sends the same prompt id and text", async () => { + const first = harness(openChild); + await first.consumer.handle(assistant(4n, "r1", "Done."), ctx); + await first.consumer.handle(runCompleted(5n, "r1"), ctx); + + // A fresh consumer resumes from the held floor (idx 3). + const replay = harness(openChild); + await replay.consumer.handle(assistant(4n, "r1", "Done."), ctx); + await replay.consumer.handle(runCompleted(5n, "r1"), ctx); + + expect(replay.sent).toEqual(first.sent); + }); + + test("a message from an earlier run is not reported for a later run", async () => { + const { consumer, sent } = harness(openChild); + await consumer.handle(assistant(1n, "r1", "old"), ctx); + await consumer.handle(runCompleted(2n, "r2"), ctx); + expect(sent[0]!.text).not.toContain("old"); + }); + + test("a cancelled child sends nothing", async () => { + const { consumer, sent } = harness({ ...openChild, taskStatus: "cancelled" }); + await consumer.handle(assistant(1n, "r1", "Done."), ctx); + await consumer.handle(runCompleted(2n, "r1"), ctx); + expect(sent).toEqual([]); + }); + + test("a session that is not a spawned child does not apply and sends nothing", async () => { + const { consumer, sent } = harness(null); + expect(await consumer.appliesTo(CHILD)).toBe(false); + await consumer.handle(runCompleted(1n, "r1"), ctx); + expect(sent).toEqual([]); + }); + + test("a parent that has ended is skipped without a retry", async () => { + let calls = 0; + const { consumer } = harness(openChild, async () => { + calls += 1; + throw new ConnectError("session is completed", Code.FailedPrecondition); + }); + await consumer.handle(runCompleted(1n, "r1"), ctx); + expect(calls).toBe(1); + }); + + test("a transient send error retries, then gives up without failing the child", async () => { + let calls = 0; + const { consumer } = harness(openChild, async () => { + calls += 1; + throw new ConnectError("unavailable", Code.Unavailable); + }); + for (let attempt = 1; attempt < 5; attempt++) { + await expect(consumer.handle(runCompleted(1n, "r1"), ctx)).rejects.toThrow("unavailable"); + } + await consumer.handle(runCompleted(1n, "r1"), ctx); + expect(calls).toBe(5); + }); +}); + +describe("renderChildReport", () => { + test("keeps the end of a long message, where the child states its result, and says so", () => { + const text = renderChildReport({ + canonicalTaskName: "a", + childSessionId: CHILD, + outcome: "completed", + lastMessage: "q".repeat(500) + "x".repeat(REPORT_MESSAGE_CHARS - 6) + "STATUS", + }); + const note = `[Truncated: the last ${REPORT_MESSAGE_CHARS} of ${REPORT_MESSAGE_CHARS + 500} characters.]`; + expect(text).toContain(`${note}\n\n${"x".repeat(REPORT_MESSAGE_CHARS - 6)}STATUS`); + expect(text).not.toContain("q"); + expect(text.endsWith("Use read_session for its full output.")).toBe(true); + }); + + test("keeps a message at the limit whole", () => { + const text = renderChildReport({ + canonicalTaskName: "a", + childSessionId: CHILD, + outcome: "completed", + lastMessage: "y".repeat(REPORT_MESSAGE_CHARS), + }); + expect(text).not.toContain("[Truncated"); + }); +}); diff --git a/orchestrator/src/listeners/child-report-consumer.ts b/orchestrator/src/listeners/child-report-consumer.ts new file mode 100644 index 000000000..250164e92 --- /dev/null +++ b/orchestrator/src/listeners/child-report-consumer.ts @@ -0,0 +1,219 @@ +/** + * Reports a spawned child's turn to the session that spawned it. + * + * When a child session (a `subsession` task) ends a run, this consumer sends + * the spawning session a prompt with the child's last assistant message of + * that run. The parent does not have to poll `wait_sessions` to learn that a + * child finished. + * + * Replay safety: the prompt id is a function of the child session id and the + * run id, and the coordinator accepts a repeated prompt id as a no-op. While + * an assistant message waits for its run to end, `handle` returns the held + * floor (the idx just before that message), so a listener restart replays + * the message before the run end. + */ + +import { Code, ConnectError } from "@connectrpc/connect"; +import { and, eq } from "drizzle-orm"; + +import { sessions } from "../control-plane/client.ts"; +import type { CuratedEvent } from "../control-plane/session-events.ts"; +import { getDb } from "../db/client.ts"; +import { task as taskTable, taskSession as taskSessionTable } from "../db/schema.ts"; +import { log as rootLog } from "../log.ts"; +import type { SessionConsumer } from "./consumer.ts"; + +const log = rootLog.child({ component: "child-report-consumer" }); + +/** Bound on the child message text that goes into the parent's prompt. A + * longer message keeps its end, where a child states its result. */ +export const REPORT_MESSAGE_CHARS = 4000; + +/** Sends per run end before the consumer stops retrying a transient error. */ +const MAX_SEND_ATTEMPTS = 5; + +export interface SpawnedChild { + canonicalTaskName: string; + taskStatus: string; + parentSessionId: string; +} + +export interface ChildReportConsumerDeps { + /** The spawned-child task behind `sessionId`, or null for a session that + * is not a spawned child. */ + findSpawnedChild(sessionId: string): Promise; + sendPrompt(input: { sessionId: string; promptId: string; text: string }): Promise; +} + +export type TurnOutcome = "completed" | "failed" | "interrupted"; + +interface RunEnd { + runId: string; + outcome: TurnOutcome; +} + +function parseRunEnd(event: CuratedEvent): RunEnd | undefined { + if (event.kind !== "run_completed" && event.kind !== "run_interrupted") return undefined; + let payload: { run_id?: unknown; ok?: unknown } = {}; + try { + payload = JSON.parse(event.payloadJson) as typeof payload; + } catch { + // A malformed payload still ends the run; the event idx names it. + } + const runId = + typeof payload.run_id === "string" && payload.run_id !== "" + ? payload.run_id + : `idx-${event.idx}`; + if (event.kind === "run_interrupted") return { runId, outcome: "interrupted" }; + return { runId, outcome: payload.ok === false ? "failed" : "completed" }; +} + +function parseAssistantMessage(event: CuratedEvent): { runId: string; text: string } | undefined { + if (event.kind !== "agent_message") return undefined; + try { + const p = JSON.parse(event.payloadJson) as { role?: unknown; run_id?: unknown; text?: unknown }; + return p.role === "assistant" && typeof p.text === "string" + ? { runId: typeof p.run_id === "string" ? p.run_id : "", text: p.text } + : undefined; + } catch { + return undefined; + } +} + +/** The prompt id of the report for one child run. The coordinator keys + * prompts by id, so the same id is never accepted twice. */ +export function childReportPromptId(childSessionId: string, runId: string): string { + return `child_report:${childSessionId}:${runId}`; +} + +export function renderChildReport(input: { + canonicalTaskName: string; + childSessionId: string; + outcome: TurnOutcome; + lastMessage: string | undefined; +}): string { + const head = `Child session "${input.canonicalTaskName}" (${input.childSessionId}) finished a turn (${input.outcome}).`; + const message = input.lastMessage?.trim() ?? ""; + let body: string; + if (message === "") { + body = "The child sent no assistant message in this turn."; + } else if (message.length > REPORT_MESSAGE_CHARS) { + body = `[Truncated: the last ${REPORT_MESSAGE_CHARS} of ${message.length} characters.]\n\n${message.slice(-REPORT_MESSAGE_CHARS)}`; + } else { + body = message; + } + return `${head}\n\n${body}\n\nUse read_session for its full output.`; +} + +/** A rejection that a retry cannot fix: the parent session is gone or ended + * (NotFound, or FailedPrecondition for a terminal session), or the prompt id + * already belongs to a different prompt. */ +function isPermanentSendError(err: unknown): boolean { + return ( + err instanceof ConnectError && + (err.code === Code.NotFound || + err.code === Code.FailedPrecondition || + err.code === Code.InvalidArgument) + ); +} + +export function makeChildReportConsumer(deps: ChildReportConsumerDeps): SessionConsumer { + // The last assistant message since the previous run end. Every event + // returns its idx - 1 as the commit while it is held (see the header). + let held: { runId: string; text: string; idx: bigint } | null = null; + let applies: boolean | undefined; + let attemptRunId = ""; + let attempts = 0; + + async function report(run: RunEnd, ctx: { sessionId: string }): Promise { + // Re-read per run end: the parent can cancel the child at any time. + const child = await deps.findSpawnedChild(ctx.sessionId); + if (child === null || child.taskStatus === "cancelled") return; + const text = renderChildReport({ + canonicalTaskName: child.canonicalTaskName, + childSessionId: ctx.sessionId, + outcome: run.outcome, + lastMessage: held !== null && held.runId === run.runId ? held.text : undefined, + }); + const promptId = childReportPromptId(ctx.sessionId, run.runId); + try { + await deps.sendPrompt({ sessionId: child.parentSessionId, promptId, text }); + } catch (err) { + if (run.runId !== attemptRunId) { + attemptRunId = run.runId; + attempts = 0; + } + attempts += 1; + if (!isPermanentSendError(err) && attempts < MAX_SEND_ATTEMPTS) { + throw err; // the listener redelivers this event with backoff + } + log.warn( + { sessionId: ctx.sessionId, parentSessionId: child.parentSessionId, promptId, attempts, err }, + "child turn report not sent to the parent session", + ); + return; + } + log.info( + { sessionId: ctx.sessionId, parentSessionId: child.parentSessionId, promptId }, + "child turn reported to the parent session", + ); + } + + return { + name: "child-report", + // Every kind: an event this consumer is not interested in commits its own + // idx, and that would move the cursor past a held message. + interestedIn: () => true, + async appliesTo(sessionId) { + applies ??= (await deps.findSpawnedChild(sessionId)) !== null; + return applies; + }, + async handle(event, ctx) { + const message = parseAssistantMessage(event); + if (message !== undefined) { + held = { ...message, idx: event.idx }; + return event.idx - 1n; + } + const run = parseRunEnd(event); + if (run === undefined) return held === null ? undefined : held.idx - 1n; + await report(run, ctx); + held = null; + }, + }; +} + +export function makeProductionChildReportConsumer(): SessionConsumer { + const db = getDb(); + return makeChildReportConsumer({ + async findSpawnedChild(sessionId) { + const rows = await db + .select({ + canonicalTaskName: taskTable.canonicalTaskName, + taskStatus: taskTable.status, + parentTaskId: taskTable.parentTaskId, + spawningSessionId: taskTable.spawningSessionId, + }) + .from(taskSessionTable) + .innerJoin(taskTable, eq(taskSessionTable.taskId, taskTable.id)) + .where(and(eq(taskSessionTable.sessionId, sessionId), eq(taskTable.type, "subsession"))) + .limit(1); + const row = rows[0]; + if ( + row === undefined || + row.parentTaskId == null || + row.spawningSessionId == null || + row.canonicalTaskName == null + ) { + return null; + } + return { + canonicalTaskName: row.canonicalTaskName, + taskStatus: row.taskStatus, + parentSessionId: row.spawningSessionId, + }; + }, + async sendPrompt(input) { + await sessions.sendPrompt(input); + }, + }); +} diff --git a/orchestrator/src/listeners/manager.ts b/orchestrator/src/listeners/manager.ts index e005e7baa..b6b0f7d64 100644 --- a/orchestrator/src/listeners/manager.ts +++ b/orchestrator/src/listeners/manager.ts @@ -11,6 +11,7 @@ import { SessionListener } from "./session-listener.ts"; import { makeProductionOtelExporterConsumers } from "./otel-exporter-consumer.ts"; import { makeProductionPrLinkConsumer } from "./pr-link-consumer.ts"; import { makeProductionAutomationConsumer } from "./automation-consumer.ts"; +import { makeProductionChildReportConsumer } from "./child-report-consumer.ts"; import { makeProductionTitleConsumer } from "./title-consumer.ts"; import { makeProductionToolConsumer } from "./tool-consumer.ts"; import { config } from "../config.ts"; @@ -227,6 +228,7 @@ export function makeProductionListenerManager(): ListenerManager { makeProductionPrLinkConsumer(), makeProductionAutomationConsumer(), makeProductionTitleConsumer(), + makeProductionChildReportConsumer(), makeSpecProjectionConsumer(productionSpecProjection), // [] when config.telemetry is unset — telemetry off costs nothing. ...makeProductionOtelExporterConsumers(config.telemetry), diff --git a/orchestrator/src/tools/coordination.ts b/orchestrator/src/tools/coordination.ts index a0ef330b9..10f97fbab 100644 --- a/orchestrator/src/tools/coordination.ts +++ b/orchestrator/src/tools/coordination.ts @@ -506,7 +506,7 @@ export function registerCoordinationTools(registry: ToolRegistry): void { registry.register({ name: "spawn_session", description: - "Spawn a named child session. Optional file_paths may name files anywhere in this session and are copied to the same absolute paths before the message is sent.", + "Spawn a named child session. Optional file_paths may name files anywhere in this session and are copied to the same absolute paths before the message is sent. When the child finishes a turn, its final message arrives in this session as a new prompt, so you do not have to poll with wait_sessions.", input: SpawnInput, output: z.object({ session_id: z.string(), canonical_task_name: z.string() }), handling: "handled",