Skip to content

Commit 98a35c7

Browse files
Merge remote-tracking branch 'origin/main' into feat/lead-conversation-kind
2 parents 477d2ba + c3dd2cf commit 98a35c7

38 files changed

Lines changed: 910 additions & 993 deletions

‎design/child-agents.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,9 @@ child chooses to report reaches the parent.
4646
and only the text of a `reply` leaves it.
4747
- One stop stops the whole tree below it. When a parent stops a child, it
4848
gets no result. When a person stops a child, its parent gets `stopped`.
49-
New work from the parent, or a person's input, ends the stop.
49+
New work from the parent, or a person's input, ends the stop. While
50+
stopped, a Conversation keeps its Watches and saves automated input as
51+
skipped Messages that start no Turn. Only a stop holds input.
5052
- A parent never waits forever, and never sees a running child as done.
5153
Each result names the siblings that did not report yet. A Task that fails,
5254
or still has no answer after one reminder, tells its parent `failed`. A

‎packages/junior/src/chat/agent-invocations/child-input.ts‎

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
import { isPersonInput } from "@/chat/conversations/kind-behavior";
2-
import {
3-
getConversationStoppedAtMs,
4-
isSkippedAfterConversationStop,
5-
} from "@/chat/conversations/session-stop";
2+
import { getConversationStoppedAtMs } from "@/chat/conversations/session-stop";
63
import { isEventMailboxMetadata } from "@/chat/events/notification";
74
import { eq } from "drizzle-orm";
85
import { alias } from "drizzle-orm/pg-core";
@@ -83,16 +80,15 @@ export function childAgentInput(
8380
* Event, and input from a child agent go to an agent invocation, and so do a
8481
* result, and input to a child that waits for its own child agents
8582
* (`replaced`). A stopped child drops input from its own child agents, also
86-
* input sent before the stop. A session stop at `stoppedAtMs` skips Events
87-
* as `skipInputAfterConversationStop` does.
83+
* input sent before the stop. A stopped Conversation never routes automated
84+
* input: `enqueueAutomatedInput` and the stop hold it first.
8885
*
8986
* TODO(dcramer): Drop the agent invocation route with the legacy child worker
9087
* (#3060 step 7).
9188
*/
9289
export async function routeChildInput(
9390
message: InboundMessage,
9491
latest: AgentInvocation | undefined,
95-
stoppedAtMs: number | undefined,
9692
): Promise<ChildInputRoute> {
9793
if (isPersonInput(message.source)) {
9894
return "Conversation loop";
@@ -109,20 +105,12 @@ export async function routeChildInput(
109105
if (!(await isFromStoredParent(message, parentMessage))) {
110106
return "dropped";
111107
}
112-
if (open) {
113-
return "agent invocation";
114-
}
115-
return isSkippedAfterConversationStop(message, stoppedAtMs)
116-
? "dropped"
117-
: "Conversation loop";
108+
return open ? "agent invocation" : "Conversation loop";
118109
}
119110
const input = childAgentInput(message);
120111
if (!input) {
121-
if (open && isEventMailboxMetadata(message.input.metadata)) {
122-
return "agent invocation";
123-
}
124-
return isSkippedAfterConversationStop(message, stoppedAtMs)
125-
? "dropped"
112+
return open && isEventMailboxMetadata(message.input.metadata)
113+
? "agent invocation"
126114
: "Conversation loop";
127115
}
128116
if (latest && isStoppedAgentInvocation(latest)) {
@@ -144,9 +132,7 @@ export async function routeChildInput(
144132
) {
145133
return "agent invocation";
146134
}
147-
return isSkippedAfterConversationStop(message, stoppedAtMs)
148-
? "dropped"
149-
: "Conversation loop";
135+
return "Conversation loop";
150136
}
151137

152138
/**

‎packages/junior/src/chat/agent-invocations/errors.ts‎

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -47,13 +47,3 @@ export class AgentMessageTargetError extends Error {
4747
this.name = "AgentMessageTargetError";
4848
}
4949
}
50-
51-
/** A top-level agent paused automated Turns, so it takes no agent message. */
52-
export class AgentMessagePausedError extends Error {
53-
constructor(conversationId: string) {
54-
super(
55-
`${conversationId} paused automated work until a person replies there`,
56-
);
57-
this.name = "AgentMessagePausedError";
58-
}
59-
}

‎packages/junior/src/chat/agent-invocations/list.ts‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,6 @@ async function listChildAgentsFromInvocations(
234234
(await runsOnConversationLoop(
235235
conversationKindFromRow(row),
236236
byChild.get(row.conversationId)![0],
237-
row.stoppedAt?.getTime(),
238237
workStates.get(row.conversationId)?.execution.pendingMessages ?? [],
239238
mailboxTurnSources.get(row.conversationId) ?? [],
240239
))
@@ -354,7 +353,6 @@ async function listChildAgentsWithoutAgentInvocations(
354353
runsOnConversationLoop(
355354
kind,
356355
undefined,
357-
undefined,
358356
workStates.get(row.conversationId)?.execution.pendingMessages ?? [],
359357
mailboxTurnSources.get(row.conversationId) ?? [],
360358
),
@@ -399,16 +397,14 @@ function answersParent(kind: ConversationKind, source: string | undefined) {
399397
async function runsOnConversationLoop(
400398
kind: ConversationKind,
401399
latest: AgentInvocation | undefined,
402-
stoppedAtMs: number | undefined,
403400
pending: readonly InboundMessage[],
404401
mailboxTurnSources: ReadonlyArray<Source | undefined>,
405402
) {
406403
for (const message of pending) {
407404
if (
408405
answersParent(kind, message.source) &&
409406
// oxlint-disable-next-line no-await-in-loop -- Callers already run each child under the fan-out cap, and the first loop route ends the check.
410-
(await routeChildInput(message, latest, stoppedAtMs)) ===
411-
"Conversation loop"
407+
(await routeChildInput(message, latest)) === "Conversation loop"
412408
) {
413409
return true;
414410
}

‎packages/junior/src/chat/agent-invocations/result-actors.ts‎

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import type { Actor } from "@/chat/actor";
33
import { EVENT_SYSTEM_ACTOR } from "@/chat/events/actor";
44
import { actorSchema } from "@sentry/junior-plugin-api";
55
import * as z from "zod";
6-
import { getConversationStoppedAtMs } from "@/chat/conversations/session-stop";
76
import type { MailboxTurnWork } from "@/chat/task-execution/mailbox-turn";
87
import {
98
childAgentInput,
@@ -62,21 +61,15 @@ export async function withAgentInvocationResultActors(
6261
return work;
6362
}
6463
const conversationId = work.batch[0]?.message.conversationId;
65-
const [latest, stoppedAtMs] = conversationId
66-
? await Promise.all([
67-
getLatestAgentInvocationForConversation(conversationId),
68-
getConversationStoppedAtMs(conversationId),
69-
])
70-
: [undefined, undefined];
64+
const latest = conversationId
65+
? await getLatestAgentInvocationForConversation(conversationId)
66+
: undefined;
7167
const batch = await mapBounded(work.batch, async (entry) => {
7268
// A parent message from the stored parent runs as the Actor of the
7369
// parent's Turn, with its grants and text, as on an Agent invocation.
7470
const parentMessage = readParentMessage(entry.message);
7571
if (parentMessage) {
76-
if (
77-
(await routeChildInput(entry.message, latest, stoppedAtMs)) ===
78-
"dropped"
79-
) {
72+
if ((await routeChildInput(entry.message, latest)) === "dropped") {
8073
logDroppedParentMessage(entry.message, parentMessage);
8174
return undefined;
8275
}
@@ -98,9 +91,7 @@ export async function withAgentInvocationResultActors(
9891
if (!input) {
9992
return entry;
10093
}
101-
if (
102-
(await routeChildInput(entry.message, latest, stoppedAtMs)) === "dropped"
103-
) {
94+
if ((await routeChildInput(entry.message, latest)) === "dropped") {
10495
return undefined;
10596
}
10697
const { invocation } = await getChildAgentInputSender(entry.message, input);

‎packages/junior/src/chat/agent-invocations/result.ts‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,10 @@ import {
1313
import { EVENT_SYSTEM_ACTOR } from "@/chat/events/actor";
1414
import { credentialContextForActor } from "@/chat/credentials/context";
1515
import { eventInboxItemInputs } from "@/chat/inbox-items/prompt-input";
16-
import { getConversationStoppedAtMs } from "@/chat/conversations/session-stop";
16+
import {
17+
enqueueAutomatedInput,
18+
getConversationStoppedAtMs,
19+
} from "@/chat/conversations/session-stop";
1720
import { turnBehavior } from "@/chat/conversations/kind-behavior";
1821
import { getConversationStore, getSqlExecutor } from "@/chat/db";
1922
import { closeOpenTodosOfChild } from "@/chat/todos/store";
@@ -31,7 +34,6 @@ import type {
3134
} from "@/chat/task-execution/conversation-turn";
3235
import type { ConversationWorkQueue } from "@/chat/task-execution/queue";
3336
import {
34-
appendAndEnqueueInboundMessage,
3537
getConversationWorkState,
3638
type InboundMessage,
3739
type RenderInboundText,
@@ -243,8 +245,8 @@ function buildResultInboundMessage(
243245
* Append one terminal agent invocation result to the parent mailbox and wake
244246
* the parent. Repeat calls are safe.
245247
*
246-
* Results do not go through `admitAutomatedTurn`, so the automated-turn limit
247-
* never drops them. Result Turns still count toward that limit.
248+
* A stopped parent holds the result. Result Turns count toward the
249+
* automated-turn limit.
248250
* TODO(dcramer): Add a per-parent total invocation limit as the loop guard
249251
* for spawn -> result -> spawn chains (#881).
250252
*/
@@ -298,7 +300,7 @@ export async function enqueueAgentInvocationResult(
298300
) {
299301
await closeTodosForResult(invocation, invocation.status, nowMs);
300302
}
301-
await appendAndEnqueueInboundMessage({
303+
await enqueueAutomatedInput({
302304
message: buildResultInboundMessage(invocation, nowMs),
303305
renderText: renderResultUnderLock(invocation, terminalResult(invocation)),
304306
queue: options.queue,
@@ -410,7 +412,7 @@ export async function enqueueAgentMessageToParent(args: {
410412
namespace: AGENT_INVOCATION_EVENT_NAMESPACE,
411413
trustedSummary: summary,
412414
});
413-
await appendAndEnqueueInboundMessage({
415+
await enqueueAutomatedInput({
414416
message: {
415417
conversationId: args.sender.parentConversationId,
416418
createdAtMs: nowMs,
@@ -521,7 +523,7 @@ export async function enqueueChildResultToParent(args: {
521523
) {
522524
await closeTodosForResult(args.sender, "completed", nowMs);
523525
}
524-
await appendAndEnqueueInboundMessage({
526+
await enqueueAutomatedInput({
525527
message: {
526528
conversationId: args.sender.parentConversationId,
527529
createdAtMs: nowMs,
@@ -686,9 +688,8 @@ async function startAgentInvocationsForChildInput(
686688
if (messages.length === 0 || !latest) {
687689
return undefined;
688690
}
689-
const stoppedAtMs = await getConversationStoppedAtMs(context.conversationId);
690691
const routes = await mapBounded(messages, (message) =>
691-
routeChildInput(message, latest, stoppedAtMs),
692+
routeChildInput(message, latest),
692693
);
693694
if (!routes.includes("agent invocation")) {
694695
return undefined;

‎packages/junior/src/chat/agent-invocations/stop.ts‎

Lines changed: 12 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,12 @@ import { and, eq, gt, inArray, isNotNull, ne, or } from "drizzle-orm";
22
import type { StateAdapter } from "chat";
33
import {
44
getConversationStoppedAtMs,
5-
markConversationsStopped,
5+
stopConversationTree,
66
} from "@/chat/conversations/session-stop";
77
import { getSqlExecutor } from "@/chat/db";
8-
import { cancelSignInWait } from "@/chat/task-execution/turn-cancel";
98
import {
109
dropPendingMessages,
1110
getConversationWorkState,
12-
stopConversationWork,
1311
} from "@/chat/task-execution/store";
1412
import { juniorAgentInvocations, juniorConversations } from "@/db/schema";
1513
import { mapBounded } from "@/chat/fan-out";
@@ -28,9 +26,8 @@ import type { TerminalAgentInvocation } from "./types";
2826
/**
2927
* Stop one child agent of a parent Conversation and every child agent below
3028
* it. The parent gets no result. SQL stops the work first. Then each
31-
* Conversation in the tree ends its session. An agent stop is not a person
32-
* stop, so their Watches end. A Conversation stop request aborts each run
33-
* that is still working.
29+
* Conversation in the tree stops through `stopConversationTree`, which keeps
30+
* their Watches and holds their automated input.
3431
*
3532
* Returns undefined when the child does not belong to the parent.
3633
*/
@@ -54,7 +51,7 @@ export async function stopChildAgent(args: {
5451
return undefined;
5552
}
5653
await finishStoppedTree(tree, tree.conversationIds, {
57-
cancelWatches: true,
54+
stoppedAtMs: Date.now(),
5855
state: args.state,
5956
});
6057
await dropUnreadLoopReplies(
@@ -80,8 +77,7 @@ export async function stopChildAgent(args: {
8077
*
8178
* Only a person's stop of this Conversation itself leaves child agents to
8279
* stop here: an agent stop, or a stop of a Conversation above it, stops this
83-
* Conversation's own agent invocations first, so it cannot spawn more. So
84-
* this keeps their Watches, as a person's stop does.
80+
* Conversation's own agent invocations first, so it cannot spawn more.
8581
*/
8682
export async function stopChildAgentsOf(
8783
conversationId: string,
@@ -98,13 +94,12 @@ export async function stopChildAgentsOf(
9894
includeRoot: false,
9995
taskedAfterMs: stoppedAtMs,
10096
});
101-
await skipUnreadResults(conversationId, nowMs, state);
10297
// They take the stop of this Conversation, so input that ends it ends
10398
// theirs too.
10499
const stoppedIds = tree.conversationIds.filter((id) => id !== conversationId);
105100
await finishStoppedTree(tree, stoppedIds, {
106-
cancelWatches: false,
107-
nowMs: stoppedAtMs,
101+
nowMs,
102+
stoppedAtMs,
108103
state,
109104
});
110105
await dropUnreadLoopReplies(tree.conversationIds, stoppedIds, state);
@@ -134,59 +129,15 @@ export async function stopChildAgentsBelow(
134129
const tree = await stopAgentInvocationTree(conversationId, nowMs, {
135130
includeRoot: false,
136131
});
137-
await skipUnreadResults(conversationId, nowMs, state);
138132
const stoppedIds = tree.conversationIds.filter((id) => id !== conversationId);
139133
await finishStoppedTree(tree, stoppedIds, {
140-
cancelWatches: false,
141-
nowMs: stoppedAtMs,
134+
nowMs,
135+
stoppedAtMs,
142136
state,
143137
});
144138
await dropUnreadLoopReplies(tree.conversationIds, stoppedIds, state);
145139
}
146140

147-
/**
148-
* Skip the `appended` results and replies that still wait in a Conversation's
149-
* mailbox, so they start no Turn. A result that the Conversation already read keeps its
150-
* status. Call this after the tree stop: it skipped each `pending` result and
151-
* stopped each child agent, so no result becomes `appended` after this read.
152-
*
153-
* The mailbox read is not atomic with the parent worker. A worker that takes
154-
* a result before this update holds the work lease, so the stop request of
155-
* the Conversation stops its Turn. A result that such a Turn took but did not
156-
* ack yet is marked `skipped`.
157-
*/
158-
async function skipUnreadResults(
159-
conversationId: string,
160-
nowMs: number,
161-
state: StateAdapter | undefined,
162-
): Promise<void> {
163-
const messages =
164-
(await getConversationWorkState({ conversationId, state }))?.messages ?? [];
165-
// A child's `reply` is its result, so a stop skips it too. A reply from a
166-
// Turn on the Conversation loop names no work of its own:
167-
// `dropUnreadLoopReplies` drops it instead.
168-
const invocationIds = (await readChildMessageSenders(messages)).flatMap(
169-
(sender) => {
170-
const invocation = sender && ownAgentInvocation(sender);
171-
return invocation ? [invocation] : [];
172-
},
173-
);
174-
if (invocationIds.length === 0) {
175-
return;
176-
}
177-
await getSqlExecutor()
178-
.db()
179-
.update(juniorAgentInvocations)
180-
.set({ parentMailboxStatus: "skipped", updatedAt: new Date(nowMs) })
181-
.where(
182-
and(
183-
eq(juniorAgentInvocations.parentConversationId, conversationId),
184-
inArray(juniorAgentInvocations.invocationId, invocationIds),
185-
eq(juniorAgentInvocations.parentMailboxStatus, "appended"),
186-
),
187-
);
188-
}
189-
190141
/**
191142
* Drop the unread replies that Turns on the Conversation loop of the stopped
192143
* Conversations left in each mailbox of `mailboxIds`. Such a reply names
@@ -256,17 +207,13 @@ export async function dropOwnUnreadLoopReplies(
256207
async function finishStoppedTree(
257208
tree: StoppedAgentTree,
258209
conversationIdsToStop: string[],
259-
options: Parameters<typeof markConversationsStopped>[1],
210+
options: Omit<Parameters<typeof stopConversationTree>[1], "onStopSaved">,
260211
): Promise<void> {
261212
for (const invocation of tree.stopped) {
262213
// oxlint-disable-next-line no-await-in-loop -- Append the end markers in stop order.
263214
await recordSubagentEnded(invocation);
264215
}
265-
await markConversationsStopped(conversationIdsToStop, options);
266-
await mapBounded(conversationIdsToStop, async (conversationId) => {
267-
await cancelSignInWait(conversationId);
268-
await stopConversationWork({ conversationId, state: options.state });
269-
});
216+
await stopConversationTree(conversationIdsToStop, options);
270217
}
271218

272219
/**
@@ -513,7 +460,7 @@ async function stopLockedAgentInvocationTree(
513460
),
514461
// With `includeRoot: false`, an `appended` result sent to the
515462
// Conversation can be one that it already read, so only `pending`
516-
// results are skipped here. See `skipUnreadResults`.
463+
// results are skipped here.
517464
and(
518465
eq(juniorAgentInvocations.parentConversationId, conversationId),
519466
eq(juniorAgentInvocations.parentMailboxStatus, "pending"),

0 commit comments

Comments
 (0)