Repository navigation
Description
Objective
Add durable subagents by running them as normal Junior conversations through the same end-to-end durable turn workflow as root conversations and scheduled/plugin agents.
The goal is not to invent a generic “subagent runtime” or to extract abstractions from the issue text. The shared boundary should be discovered by moving real workloads onto one workflow and deleting the duplicate paths they replace.
The simple story and contract
Every agent is a conversation. A root agent, a named agent, and an ephemeral
subagent all use the same conversation, mailbox, lease, turn, continuation,
and recovery machinery. “Subagent” only describes the relationship between
the agent doing the delegation and the agent receiving the work.
Suppose agent A asks an agent named researcher to investigate something:
- A looks up
researcherin its durable agent bindings. - If the binding exists, A continues that agent by using its existing child
conversationId. If it does not exist, A creates a new child conversation
and saves the name-to-conversation binding. An unnamed/ephemeral agent
always gets a new conversation. - A creates a distinct invocation for this task, appends the task to the
child's mailbox, and sends a queue wake containing only the child's
conversationId. - A does not execute the child inline or recursively call
AgentRunner.
A separate serverless conversation-worker invocation acquires the child's
lease and starts or resumes the child turn. Later execution slices may run
in different serverless function instances. - The child keeps its own history and can run concurrently with A or outlive
A's current turn. New work for the same named child is appended to that same
conversation and is steered or ordered according to the input contract. - When the invocation finishes, its terminal result is delivered durably to
A's mailbox and wakes A. The child's conversation remains available for the
next invocation. - Any agent may in turn create or continue its own child agents using the same
rules once delegation depth and resource limits permit it.
The durable identities are intentionally separate:
conversationIdis the persistent identity and history of one agent.- An agent name is a scoped, convenient binding to a
conversationId; it is
not the durable identity itself. invocationIdidentifies one delegated task and its terminal result, even
when many invocations reuse the same named agent conversation.
Therefore delegation means scheduling work for another conversation. It must
never mean running a nested agent loop inside the parent's serverless process.
What the code does today
The implementation already shares important inner layers:
processConversationWorkowns the provider-backed mailbox, conversation lease, check-in, cooperative yield, queue redelivery, and missing-wake recovery.AgentRunner/executeAgentRunowns Pi execution, tool use, safe-boundary checkpoints, session-record restoration, timeout/yield/auth suspension, model profile, reasoning, actor, authority, artifacts, and sandbox continuity.- SQL visible messages and append-only agent steps own durable conversation history; session records are resumability projections and thread state is runtime scratch.
The remaining duplication is the orchestration between those layers:
- New Slack turns run through
SlackTurnRuntimeandreply-executor.ts. - Resumed Slack turns re-enter the conversation queue, but then use a separate
agent-continue-runner.ts/slack-resume.tslifecycle for restoration, outcomes, delivery, and terminalization. - OAuth callbacks can also call the Slack resume lifecycle directly, bypassing conversation-lease ownership for that execution slice.
- Scheduled/plugin
agent-dispatchowns its own record version, attempt counter, lease, callback, incomplete-work index, heartbeat recovery, continuation loop, Slack delivery guard, and terminal result path. - Local CLI execution is synchronous and should remain an adapter rather than being forced through the serverless queue.
Target workflow
Every asynchronous conversation should advance through one durable workflow:
- Input is appended to the conversation mailbox under a stable idempotency key.
- The conversation work callback acquires the conversation lease.
- Under that lease, the worker either resumes the active turn or starts the next mailbox turn.
- The turn restores durable history, execution configuration, authority, artifacts, sandbox state, and current input.
- Before consuming the mailbox item, the workflow durably checkpoints the prompt plus the active task/authority reference needed by later slices.
AgentRunneradvances one execution slice.- The worker handles completion, auth pause, suspension, cooperative yield, retryable failure, or terminal failure.
- A completion target accepts either a provider-visible reply or an internal result.
- Only after completion acceptance does the workflow persist delivered terminal state; already-checkpointed mailbox input is not replayed.
- Incomplete work is re-woken through conversation execution; there is no workload-specific lease or recovery loop.
Provider adapters may own ingress parsing, status/reaction UX, formatting, and provider delivery. They must not own a second turn lifecycle. Internal child results use the same workflow with a different completion target.
State ownership and API shape
The queue callback and worker entry point should be keyed by conversationId, not by a caller-reconstructed execution request:
await appendConversationInput({
conversationId,
idempotencyKey,
input,
});
await wakeConversation(conversationId);
await processConversation(conversationId);First contact is the exception to the id-only API: provider ingress or child creation must establish and validate the conversation's durable route/defaults atomically with the first append. Later wake-ups and resumes use only conversationId; they must not infer missing authority or routing from the callback.
State should be owned at the narrowest durable level that can restore it:
- Queue wake:
conversationIdonly. It is a signed wake-up hint, not routing authority. - Conversation: mailbox/execution state, optional provider destination, transcript/history identity, parent lineage, and conversation-level defaults.
- Mailbox input / invocation: idempotency key, task text/attachments, actor, credential subject or delegated authority, input disposition, execution destination/authority when task-specific, and the durable task reference needed to restore completion behavior.
- Active turn / session record:
turnId, execution slices, safe checkpoint, resolved model/reasoning configuration, runtime state, exact authority, and a small durable reference to the task/origin when conversation history alone cannot restore it. - Provider adapter: raw provider payload parsing, provider context hydration, status UX, and provider delivery.
Named-agent bindings primarily resolve to a child conversationId plus policy. Each invocation remains a separate task/result identity even when it reuses that conversation.
The current code does not yet meet this shape:
- Conversation queue messages redundantly contain
destination, and queue verification treats it as routing authority. - Every mailbox message currently repeats the provider destination. That can remain as a migration/bootstrap field initially, but it must not become queue routing authority or the only way to restore a non-Slack task.
- Production conversation work is wired directly to the Slack worker. A future second consumer must resolve start/resume behavior from the active session or parsed mailbox input, not from
conversation.sourcealone (resource_eventalready executes through Slack behavior). - Slack mailbox metadata contains serialized provider
ThreadandMessageobjects because turn preparation still consumes provider objects directly. - SQL has origin, creator, and credential-subject columns, but current conversation writes leave them null and the runtime
ConversationStoreread model does not expose them. They are not runtime authority yet.
The first slices should move toward this API incrementally; they should not introduce a large new request/config object that callers must reconstruct beside conversationId.
Some behavior is task-specific and must remain explicit rather than inferred from provider/source conditionals inside the worker:
- Whether newly arrived input starts a later turn, may steer the active turn, or must wait. Slack messages may steer; a later named-agent invocation should normally remain ordered mailbox work.
- Whether missing authorization pauses for interactive UX or terminally blocks/fails non-interactive work.
- Whether successful completion permits no visible reply, requires provider-visible output, or produces an internal invocation result.
- Which durable record fences delivery. Once the completion target accepts output, recovery may repair state but must not deliver the same result again.
These are properties/references of the input, invocation, or completion target—not reasons to create separate execution loops.
Implementation strategy
Do not build a provider-neutral framework ahead of a second consumer. Consolidate the current root path, then immediately prove the seam by migrating agent-dispatch and deleting its duplicate lifecycle.
The first code change should be the conversation-id queue reader/writer rollout in #876, not a new turn-runtime module.
1. #876 — unify new and resumed turns in the conversation worker
- Reduce queue wake payloads to
conversationId; load destination/source from durable conversation work. - Make one leased worker decision loop choose between resuming an active turn and starting mailbox input.
- Change authorization callbacks to persist authorization completion and wake the conversation; they must not execute the agent directly.
- Move shared restoration, outcome handling, terminalization, and completion ordering out of the separate Slack initial/resume paths as required by the migration.
- Keep Slack parsing, status, authorization UX, and reply formatting in Slack-owned code.
- Preserve current Slack behavior and recovery semantics.
#877 is folded into #876; continuation is part of the full turn workflow rather than a separate architectural layer.
2. #882 — migrate agent-dispatch as the second consumer
- Append dispatch input as stable conversation mailbox work.
- Persist a small dispatch/task reference and exact authority before mailbox acknowledgement so later slices can restore the dispatch from
conversationIdwithout reconstructing context from a callback payload. - Execute and resume dispatches through the same conversation lease and worker loop.
- Preserve plugin idempotency, actor, credential subject, destination authority, status projection, and Slack completion behavior.
- Delete the dispatch-owned lease, callback loop, incomplete index, and heartbeat recovery after parity.
This slice proves the shared workflow is real rather than a Slack refactor with generic names.
3. #879 — add bindings, invocations, and live child execution
- Add stable named-agent bindings and per-task invocation records.
- Create or reuse child conversations with immutable parent lineage.
- Enqueue invocation input through the same mailbox and execute it through the proven worker loop.
- Persist one terminal invocation result without exposing model-facing tools yet.
4. #878 — deliver child results to parents durably
- Write terminal invocation results and parent-notification outbox entries atomically/recoverably.
- Append one idempotent inbound result message to the parent mailbox.
- Use queue delivery only as a wake-up hint; repair failed parent notification from durable invocation state.
5. #880 — expose minimal model-facing delegation
- Add replay-safe spawn/result tools.
- Support named continuity and ephemeral agents over the proven binding/invocation model.
- Prefer automatic parent result delivery; status lookup is deterministic recovery, not model polling.
6. #881 — add bounded context and operational controls
- Add explicit context seeding, inspection, cancellation/archival only where justified.
- Enforce depth, concurrency, invocation, rollout, and token limits before recursive delegation.
- Never broaden parent authority, credentials, tools, visibility, or workspace scope.
Completion gates
- Root Slack conversations, scheduled/plugin dispatch, and child conversations use the same mailbox, lease, turn selection, session-record, continuation, terminalization, and recovery workflow.
- Queue wakes identify only the conversation; durable conversation/input/invocation state owns execution context.
- There is no independent dispatch or subagent execution loop.
- Initial and resumed work follow the same conversation-owned turn lifecycle.
- Child work survives execution-slice timeout, worker loss, queue redelivery, missing wake-ups, and parent completion.
- One invocation produces at most one durable terminal result and one parent inbound-message effect.
- Failed parent notification remains discoverable and repairable.
- Slack and local user-visible behavior remains compatible.
- Integration tests cover input idempotency, continuation, worker recovery, delivery fencing, parent notification repair, failure, and authority inheritance.
- Evals cover delegation choice, named reuse, bounded context sharing, and result consumption.
Open follow-ups from the #879/#1065 cut
- Child invocations currently set
disabledFeatures: ["handoff", "interactive-auth", "subagents"], so missing credentials hard-fail instead of pausing for an OAuth link. - Follow-up: decide whether delegated child work should be able to force interactive auth when a tool requires credentials the parent already has authority to request (see also Add subagent context, lifecycle controls, and execution limits #881).
- Code markers:
packages/junior/src/chat/agent-invocations/work.ts,packages/junior/src/chat/agent/request.ts.
Non-goals
- A separate subagent runtime, queue, lease, session format, or recovery loop.
- Treating the current issue decomposition or proposed type names as architecture requirements.
- Reusing provider resource-event subscriptions as the invocation-result protocol.
- Exactly-once queue delivery.
- Default full-transcript forks.
- Unbounded or recursive delegation in the initial rollout.
- Routing local CLI turns through the serverless queue solely for symmetry.
Activity
[-]Subagents: shared durable agent runtime and named delegation[/-][+]Build durable subagents on shared conversation execution[/+]dcramer commentedon Jul 23, 2026
Follow-up from the implementation trace: the desired worker API is conversation-id driven. Queue wakes should carry only
conversationId; conversation/input/invocation/session state should own the context needed to start or resume work. The current destination-bearing queue/mailbox contract blocks destinationless child conversations, so #876 now includes removing that requirement before consolidating the start/resume loop.ref(dispatch): route dispatches through conversation work (#1059)
sentry-junior commentedon Aug 6, 2026
Recorded from the #1065 cut: child invocations currently disable
interactive-authand hard-fail on missing credentials. Follow-up is whether delegated children should be able to force the interactive auth flow when the parent already has authority to request it. Code TODOs:agent-invocations/work.ts,agent/request.ts. Also tracked on #881.docs(agent): track child interactive-auth follow-up
sentry-junior commentedon Oct 13, 2026
Tracked under #2105, the master tracker for letting a conversation coordinate child conversations. It covers this work plus the coordinator/child steering, child status, and the coding-mode consumer (#1998).
sentry-junior commentedon Nov 2, 2026
Superseded by #2567.
Most of this plan shipped: conversation-id-only queue wakes (#876), OAuth callbacks that wake the Conversation (#1913), dispatch on the Conversation worker (#882, #1059), and bindings, Agent invocations and parent results (#879, #1065, #2106). The build left the target in one place: Agent invocation rows (and dispatch records) got their own run statuses, so child and dispatch work keep a second Turn lifecycle beside Conversation execution.
#2567 audits the current design at
05108d93c, keeps the principles, completion gates and non-goals from this issue that still apply (its section 0), and lists the items from here that are still open.