Repository navigation
Description
Summary
Maka currently represents a spawned subagent as an isolated child AgentRun inside the parent session:
- it shares the parent
sessionIdand persistence namespace; - it has its own
turnId,runId, backend instance, system prompt, tools, and model context; - it does not append normal messages to the parent transcript;
- a fresh child does not inherit parent or sibling model history;
- resume reconstructs only that child AgentRun lineage.
This is a sound execution-isolation boundary, but it makes durable, interactive, and observable subagent capabilities special cases around AgentRun.
Before implementing the stream-graph scheduler proposed in #1341, investigate promoting each durable subagent identity to a linked child session. An AgentRun would represent one invocation/turn/attempt inside that child session, rather than the entire lifetime of the subagent.
Motivation
A child session could naturally reuse existing session infrastructure for:
- creation, close/archive, stop, recovery, and deletion;
- message and canonical
RuntimeEventpersistence; - multi-turn continuation and follow-up questions;
- context compaction and checkpoint partitioning;
- usage, tool activity, artifacts, and permission interactions;
- Desktop/TUI conversation components;
- Runtime Host subscriptions and multiple clients observing the same subagent;
- reconnecting after the spawning parent turn or client has ended.
This also resolves an existing tension: child AgentRuns share the parent sessionId, so child mid-turn compaction is currently disabled to avoid contaminating the session-global checkpoint stream.
Proposed model
Main Session
├── Main AgentRun
├── Child Session A
│ ├── AgentRun A1
│ ├── AgentRun A2 (follow-up)
│ └── AgentRun A3 (retry/recovery)
├── Child Session B
│ └── AgentRun B1
└── Child Session C
└── AgentRun C1
Suggested semantic boundary:
- Session: a durable, observable, resumable conversational process.
- AgentRun: one invocation, turn, continuation, or attempt within that process.
A child session should retain durable lineage to the spawning parent session and invocation, including parent sessionId, runId, turnId, toolCallId, and optional swarm/item identity. The exact schema remains a design question; existing branch/revision lineage must not be overloaded accidentally.
Important semantics
Fresh context, not a copied branch
A child session should not clone the parent's entire transcript or RuntimeEvent ledger. It should start with the assigned task, an explicit handoff/context package, and references to relevant parent events or artifacts when needed.
Full session internally, nested projection externally
A child session should be a real lifecycle entity in Runtime and Storage, but it need not appear as an ordinary top-level chat. Hosts may project it under the parent while allowing users and supervisors to open, inspect, subscribe, stop, resume, follow up, or promote it to a normal visible session.
Parent relation belongs to the session
Runs inside the child session should behave like normal session-inline runs so later turns reuse the child session history. The cross-session spawn relation belongs on session lineage rather than on AgentRun.parentRunId in a way that suppresses prior-session context.
Lifecycle policy must be explicit
The design must specify:
- parent-stop cascading and independent child resume;
- archive/delete and orphan handling;
- permission ceilings and snapshot versus dynamic inheritance;
- usage aggregation without double-counting;
- workspace/worktree ownership;
- routing permission requests and user questions to the correct host/client;
- visibility and unread behavior in Desktop/TUI.
Why this should precede #1341
With child sessions, a graph operator activation can bind to a durable childSessionId while currentRunId changes across retries, follow-ups, or recovery:
interface OperatorActivation {
graphId: string;
operatorId: string;
activationId: string;
childSessionId: string;
currentRunId?: string;
}Canonical RuntimeEvents remain the stream records. The graph scheduler can subscribe to child-session event streams, while the main Agent acts as a semantic supervisor without becoming the data-path bottleneck.
Non-goals
This issue does not propose:
- implementing the graph scheduler from design(runtime): model subagent orchestration as a supervised stream graph #1341;
- rewriting the Agent runtime or model loop;
- copying the full parent conversation into every child;
- making all child sessions top-level sidebar entries;
- removing AgentRun durability or RuntimeEvent authority;
- immediately rewriting all legacy child AgentRuns.
Suggested investigation path
- Define child-session identity, lineage, visibility, and lifecycle policy.
- Add a read-only parent/child session projection without changing
agent_spawn. - Create a child session through the normal SessionStore/Runtime lifecycle and run one existing child profile inside it.
- Preserve compatibility for legacy same-session child AgentRuns in list/output/resume paths.
- Move
agent_spawnandagent_swarmto return bothchildSessionIdandrunId. - Reuse normal session stop/recovery, RuntimeEvent persistence, compaction, usage, tool activity, and Host subscriptions.
- Add multi-turn follow-up and multi-client observation tests.
- Only then use child sessions as operator identities in design(runtime): model subagent orchestration as a supervised stream graph #1341.
Definition of success
- Every new spawned subagent has a stable child-session identity plus one or more AgentRuns.
- The child has an independent transcript and context lifecycle without cloning parent history.
- It can be inspected, subscribed to, stopped, resumed, and followed up through normal session capabilities.
- Messages, RuntimeEvents, usage, tool activity, artifacts, and compaction are partitioned by child session.
- Parent-child lineage is durable and visible to Runtime Host/Desktop/TUI projections.
- Legacy child AgentRuns remain readable during migration.
- design(runtime): model subagent orchestration as a supervised stream graph #1341 can bind graph operator activations to
childSessionIdwithout adding a second agent lifecycle system.
Related implementation references
packages/runtime/src/agent-swarm-tools.tspackages/runtime/src/session-manager.tspackages/runtime/src/runtime-kernel.tspackages/runtime/src/agent-run.tspackages/runtime/src/child-agent-run-limiter.tspackages/core/src/session.ts- design(runtime): model subagent orchestration as a supervised stream graph #1341
中文说明
概述
Maka 当前把 subagent 表示为父 Session 内的隔离 child AgentRun:共享父 sessionId 和持久化命名空间,但拥有独立的 turnId、runId、backend、system prompt、工具和模型上下文;不会把普通消息写入父 transcript;新 child 不继承父 Agent 或兄弟 Agent 的历史;resume 只重建自己的 AgentRun lineage。
这个执行隔离边界本身合理,但 subagent 的持久化、交互和可观测能力因此都成为围绕 AgentRun 的特殊逻辑。
在实现 #1341 的流处理图调度之前,应该先研究把每个持久 subagent 身份提升为一个有关联的 Child Session。此后 AgentRun 表示 Child Session 内的一次 invocation、turn 或 attempt,而不是 subagent 的整个生命周期。
动机
Child Session 可以自然复用已有 Session 基础设施:
- 创建、关闭/归档、停止、恢复和删除;
- message 与 canonical
RuntimeEvent持久化; - 多轮继续执行和后续追问;
- 上下文压缩和 checkpoint 分区;
- usage、tool activity、artifact 和 permission interaction;
- Desktop/TUI 会话组件;
- Runtime Host 订阅及多个 client 同时观察同一个 subagent;
- 父 turn 或原 client 结束后重新连接 subagent。
这也能解决现有矛盾:child AgentRun 与父 Agent 共享 sessionId,为了避免污染 session-global checkpoint stream,当前 child mid-turn compaction 被明确禁用。
建议模型
主 Session
├── 主 AgentRun
├── Child Session A
│ ├── AgentRun A1
│ ├── AgentRun A2(继续追问)
│ └── AgentRun A3(重试/恢复)
├── Child Session B
│ └── AgentRun B1
└── Child Session C
└── AgentRun C1
建议语义边界:
- Session:一个持久、可观察、可恢复的对话式进程。
- AgentRun:该进程中的一次 invocation、turn、continuation 或 attempt。
Child Session 应持久记录产生它的父 sessionId、runId、turnId、toolCallId,以及可选 swarm/item identity。具体 schema 留待设计,但不能不加区分地复用现有 branch/revision lineage。
重要语义
新鲜上下文,而不是复制 Branch
Child Session 不应复制父会话的完整 transcript 或 RuntimeEvent ledger。它只应从分配的任务、显式 handoff/context package,以及必要的父事件或 artifact 引用开始。
Runtime 内是完整 Session,Host 上是嵌套投影
Child Session 在 Runtime 和 Storage 中应当是完整生命周期实体,但不必作为普通顶层会话显示。Host 可以默认嵌套在父 Session 下,同时允许用户或 supervisor 打开、检查、订阅、停止、恢复、继续追问,或提升为普通可见 Session。
父子关系属于 Session
Child Session 内的 Run 应像普通 session-inline run 一样工作,使后续 turn 能复用 Child Session 自己的历史。跨 Session 的 spawn 关系应保存在 Session lineage 上,而不是继续使用会抑制 prior-session context 的 AgentRun.parentRunId 语义。
必须明确生命周期策略
需要明确:
- 父 Session 停止是否级联、child 是否可独立恢复;
- archive/delete 与孤儿处理;
- permission ceiling 和父配置的快照/动态继承;
- usage 聚合如何避免重复计算;
- workspace/worktree 所有权;
- permission request 和 user question 的 Host/client 路由;
- Desktop/TUI 的可见性与未读语义。
为什么应当先于 #1341
有了 Child Session,operator activation 可以绑定稳定的 childSessionId,而 currentRunId 可以在重试、追问和恢复时变化。Canonical RuntimeEvent 继续作为 stream record;Graph scheduler 订阅 Child Session 的事件流;主 Agent 作为语义 supervisor,而不成为数据路径瓶颈。
非目标
本 Issue 不负责:
- 实现 design(runtime): model subagent orchestration as a supervised stream graph #1341 的 graph scheduler;
- 重写 Agent runtime 或 model loop;
- 把父会话完整历史复制给每个 child;
- 强制所有 Child Session 出现在顶层侧边栏;
- 移除 AgentRun 持久化或 RuntimeEvent 权威性;
- 立即重写全部历史 child AgentRun。
建议调研和实施路径
- 定义 Child Session identity、lineage、visibility 和 lifecycle policy。
- 先添加只读父子 Session 投影,不修改
agent_spawn。 - 通过正常 SessionStore/Runtime 生命周期创建 Child Session,并运行一个现有 child profile。
- 保证旧的同 Session child AgentRun 在 list/output/resume 路径仍可读取。
- 让
agent_spawn和agent_swarm同时返回childSessionId与runId。 - 复用普通 Session 的停止/恢复、RuntimeEvent 持久化、压缩、usage、tool activity 与 Host subscription。
- 增加多轮追问和多 client 观察测试。
- 最后再让 design(runtime): model subagent orchestration as a supervised stream graph #1341 使用 Child Session 作为 operator identity。
成功标准
- 每个新 subagent 都有稳定 Child Session 身份,以及一个或多个 AgentRun。
- Child 拥有独立 transcript 和上下文生命周期,同时不复制父历史。
- Child 可以通过普通 Session 能力被检查、订阅、停止、恢复和继续追问。
- message、RuntimeEvent、usage、tool activity、artifact 和 compaction 按 Child Session 自然分区。
- 父子 lineage 持久化,并能由 Runtime Host/Desktop/TUI 投影。
- 迁移期间旧 child AgentRun 仍然可读。
- design(runtime): model subagent orchestration as a supervised stream graph #1341 可以把 operator activation 绑定到
childSessionId,无需发明第二套 Agent 生命周期。
相关实现
packages/runtime/src/agent-swarm-tools.tspackages/runtime/src/session-manager.tspackages/runtime/src/runtime-kernel.tspackages/runtime/src/agent-run.tspackages/runtime/src/child-agent-run-limiter.tspackages/core/src/session.ts- design(runtime): model subagent orchestration as a supervised stream graph #1341
Activity
likun666661 commentedon Jul 23, 2026
Proposed design direction
The subtle but important conclusion is:
Child sessions solve identity, lifecycle, persistence, interaction, and observation. A future graph scheduler will solve readiness, dependencies, resource admission, and routing. Implementing child sessions first stabilizes the execution identity that a later Agent operator can bind to, without putting graph-specific concepts into the session model.
1. Responsibility boundary
This issue should not introduce
graphId,operatorId,activationId, joins, or scheduler state. Its result should remain useful without #1341.2. Relationship source of truth
Prefer a typed, immutable parent relation stored on the child session. Do not persist a reciprocal
childSessionIds[]array on the parent: two-sided writes create unnecessary atomicity and repair problems.Storage/Host derives or indexes the reverse lookup:
Existing branch/revision fields remain compatible. We can introduce
sessionKind, or first add a narrowsubagentParentblock and normalize lineage later. The critical invariant is that Host code must not infer “branch” fromparentSessionIdalone.3. Child creation semantics
Introduce an internal runtime primitive:
Creation should:
Cross-session provenance belongs to the child Session relation. Runs inside the child should remain ordinary session-inline Runs so follow-up turns automatically replay the child's own history. The first run should therefore not reuse current
AgentRun.parentRunIdsemantics as its model-history boundary.4. Context and event invariants
sessionId.sendMessage(childSessionId, ...)behavior.sessionId.5. Lifecycle policy for v1
Preserve current foreground behavior first:
agent_spawn/agent_swarmwait for child work to settle.A future detached/background lifecycle should be a new ownership policy, not an implicit change to foreground semantics.
6. Permission and configuration policy
At creation, snapshot:
Permission requests and user questions route by
childSessionId, allowing Desktop/TUI/Runtime Host to reuse normal session interaction paths. A safe v1 default is a durable creation-time ceiling plus normal child-session permission evaluation.Usage facts remain owned by the child session. Parent/tree totals should be read-time aggregation over descendants, not duplicated usage records in the parent.
7. Host and observation model
A child is a full Session in Runtime/Storage but a nested projection in the product surface:
Recommended Host capabilities:
A stable
childSessionIdnaturally lets multiple Runtime Host clients observe the same subagent without a separate subagent streaming protocol.8. Compatibility strategy
Do not rewrite historical data. Introduce a compatibility reference:
During migration:
agent_spawncalls create child sessions;agent_listreturns both forms;agent_outputaccepts either form;resume_run_idsremain readable through a legacy path or create a linked child session with explicit provenance;9. Suggested PR sequence
PR 1 — Session relation contract and read model
Typed relation, legacy decoding/defaults, reverse child lookup; no spawn change.
PR 2 — Child-session runtime primitive
Fresh child creation, environment/permission snapshot, first session-inline Run, stop/recovery/no-parent-history invariants; exercise one read-only profile.
PR 3 — Switch
agent_spawnandagent_swarmReturn
childSessionIdplusrunId, add the legacy compatibility union, and preserve foreground cancellation/all-settled behavior.PR 4 — Host lifecycle and multi-turn observation
Nested Desktop/TUI projection, normal subscriptions and interaction routing, follow-up turns, compaction, usage/tool activity, restart, and multi-client tests.
Only after this lifecycle is stable should #1341 bind Agent operator executions to child sessions. That is an implementation-order decision, not architectural coupling: the future scheduler should consume a generic execution handle, with child session as the preferred Agent execution adapter.
10. Core acceptance scenarios
中文方案
设计结论
这里最微妙也最重要的结论是:
Child Session 解决身份、生命周期、持久化、交互和可观察性;未来 Graph Scheduler 解决 readiness、依赖、资源准入和 record routing。先完成 Child Session,是为了稳定未来 Agent operator 绑定的执行身份,而不是把图调度概念放进 Session 模型。
1. 职责边界
本 Issue 不引入
graphId、operatorId、activationId、join 或 scheduler state。即使没有 #1341,Child Session 本身也应成立。2. 父子关系的事实源
建议把类型化、不可变的 parent relation 存在子 Session 上。父 Session 不保存 reciprocal
childSessionIds[],避免双向写入造成原子性、修复和一致性问题。Storage/Host 通过索引或投影提供反向查询
listChildSessions(parentSessionId)。现有 branch/revision 字段继续兼容。可以引入
sessionKind,也可以先添加窄化的subagentParentblock。关键约束是 Host 不能再仅凭parentSessionId推断它一定是 branch。3. Child 创建语义
新增内部 Runtime primitive:
过程包括:校验父 Session/Run;解析 profile 与 permission ceiling;通过正常 SessionStore 创建全新 Child;快照 backend/model/connection/cwd/workspace/profile;持久化 parent relation;写入任务作为正常初始 user turn;通过 RuntimeEvent/artifact refs 关联必要父上下文;启动普通 session-inline AgentRun。
跨 Session provenance 属于 Child Session relation。Child 内部 Run 应保持普通 session-inline 语义,使后续 turn 自动复用 Child 自己的历史;首个 Run 不应继续用当前
AgentRun.parentRunId作为模型历史边界。4. Context/Event 约束
sessionId。sendMessage(childSessionId, ...)。sessionId隔离。5. v1 生命周期
优先保持 foreground 语义:
agent_spawn/agent_swarm等待 child settle。未来 detached/background 应新增 lifecycle ownership policy,而不是隐式改变 foreground。
6. Permission、配置与统计
创建时快照 backend/model/connection、cwd/workspace identity、agent profile/tool allowlist,以及不得超过父 Session 的 permission ceiling。
Permission request/user question 按
childSessionId路由,复用普通 Session interaction path。安全的 v1 默认值是持久 creation-time ceiling,再进行正常 Child Session permission evaluation。Usage facts 只属于 Child Session;父树总量在 read time 聚合 descendants,不能向父 Session 重复写 usage。
7. Host 与观察
Child 在 Runtime/Storage 中是完整 Session,在产品表面上是嵌套投影。Host 支持查询 children、使用现有 Session view 打开、订阅普通事件流、stop/resume/follow-up、展示 usage/tool activity/artifact/permission,并可选 pin/promote 为顶层 Session。
稳定的
childSessionId让多个 Runtime Host client 可以自然观察同一 subagent,无需新增专用流协议。8. 兼容策略
不原地迁移历史数据:
新 spawn 创建 Child Session;
agent_list/agent_output同时支持两种形式;旧resume_run_ids继续可读;不改写历史 AgentRun/RuntimeEvent。9. 建议 PR 顺序
agent_spawn/agent_swarm:返回childSessionId与runId,兼容 legacy,保持 foreground cancellation/all-settled。稳定以后再让 #1341 的 Agent operator 使用 Child Session。这是工程顺序选择,不是架构耦合;未来 Scheduler 面向通用 execution handle,Child Session 只是首选 Agent execution adapter。
10. 核心验收
Astro-Han commentedon Jul 23, 2026
Overall this direction looks right to me. Promoting durable subagent identity to a linked child session removes a growing set of special cases around
AgentRun, and doing it before #1341 is the right sequencing. I suggest clarifying three points.1. Fork-from-parent should remain a first-class option
"Fresh context, not a copied branch" is currently stated as a design principle. I would make
freshthe default rather than the only supported model.The structural choice only needs two modes:
A handoff package is content within
fresh, not a third mode.The fork boundary should be the exact parent-model input that produced the
agent_spawntool call. It should not include the generated tool call itself; the assigned task becomes the child's new input. This gives the child the context on which the parent made the delegation decision without recursively including the delegation action.The snapshot should be self-contained:
"Complete transcript" here does not mean expanding history that the parent model had already lost through compaction. The transcript remains available for inspection, while the child's initial model view should reproduce the parent's effective context at the fork boundary.
This follows the durable-session boundary: deleting, compacting, or continuing the parent must not alter the child. It also avoids adding cross-session transcript and artifact access rules. Artifacts are currently session-scoped, so copying them is consistent with the existing storage authority.
The copying and ledger-cloning machinery behind
branchFromTurn/branchBeforeTurncan be reused, although the spawn boundary is a model-input snapshot rather than necessarily a completed turn boundary. A minimal tool option could be:Fork has two independent benefits:
The sibling case is particularly valuable for a large one-shot
agent_swarmfanout: the shared transcript prefix can be cached once and reused across many child requests, amortizing both cost and latency. Request construction should therefore keep item-specific task text, item IDs, and other varying metadata after the shared cacheable prefix.This remains an opportunity rather than an unconditional guarantee. Cache reuse depends on provider behavior and cache lifetime; if all children start before the shared entry exists, the runtime may eventually need an explicit cache-warming step before concurrent fanout.
Both
agent_spawnandagent_swarmshould accept the same explicit option:The default should remain
fresh. A swarm should selectforkdeliberately rather than allowing a cost optimization to change its context semantics automatically.2. Result delivery should remain synchronous per parent tool call
Today
agent_spawnis synchronous: the parent tool call awaits the child run, and that run's result becomes the tool result. Child sessions should preserve that mapping:agent_spawnbinds its tool result to the child session's first run;This avoids retroactively appending tool results to already closed parent turns.
3. Spawn lineage and fork lineage are separate relations
A forked subagent simultaneously has two kinds of lineage:
runId/turnId/toolCallId;These relations have different responsibilities. Spawn lineage controls nesting, supervision, lifecycle policies, usage aggregation, and swarm/item identity. Fork lineage records the provenance of the copied initial context.
I would therefore keep dedicated spawn lineage, for example:
Fork provenance can be recorded separately when
contextMode: "fork"is used. The implementation may reuse branch-copying machinery, but it should not overloadparentSessionId + branchOfTurnIdto represent both relations.This leaves the core model small:
contextModeonly decides how its initial state is copied.中文对照
整体方向我认为是对的。把持久 subagent 身份提升为有关联的 Child Session,可以消除围绕
AgentRun不断增加的特殊逻辑;先于 #1341 完成这层设计,顺序也合理。建议进一步明确三点。1. 应把从父 Agent fork 保留为一等选项
目前 issue 把 “Fresh context, not a copied branch” 表述为设计原则。建议把
fresh作为默认值,而不是唯一支持的模型。结构上只需要两种模式:
Handoff package 只是
fresh模式中的内容,不是第三种模式。Fork 边界应该是产生这次
agent_spawntool call 的那次父模型输入。它不应包含随后生成的 tool call 自身;分配给 child 的任务作为新的输入追加。这样 child 可以获得父 Agent 作出委派决策时所依据的上下文,又不会递归包含委派行为本身。快照应当自包含:
这里的“完整 transcript”并不意味着把父模型已经通过 compaction 遗忘的历史重新全部展开到模型窗口。完整 transcript 仍可用于检查,但 child 的初始 model view 应复现父 Agent 在 fork 边界实际拥有的 effective context。
这符合持久 Session 的边界:删除、压缩或继续父 Session 都不应改变 child。这样也不需要新增跨 Session transcript 和 artifact 的访问及删除协调规则。Artifact 当前本身就是 session-scoped,因此复制也符合现有存储权限边界。
实现上可以复用
branchFromTurn/branchBeforeTurn背后的消息复制和 ledger 克隆能力,但 spawn 的边界是模型输入快照,不一定是已经完成的 turn boundary。工具层只需要一个最小选项:Fork 有两个相互独立的价值:
第二种情况对一次性 fanout 大量 child 的
agent_swarm尤其有价值:公共 transcript 前缀可以只缓存一次,再由大量 child 请求复用,从而摊薄成本和延迟。构造请求时,应把 item task、item ID 和其他可变元数据放在公共可缓存前缀之后。这是一项优化机会,而不是无条件保证。实际复用取决于 provider 行为和缓存有效期;如果所有 child 在公共缓存建立前同时启动,Runtime 后续可能需要先显式建立缓存,再并发 fanout。
agent_spawn和agent_swarm应接受同一个显式选项:默认值仍应为
fresh。Swarm 应显式选择fork,而不是让成本优化自动改变其上下文语义。2. 每次父工具调用都应保持同步结果交付
当前
agent_spawn是同步的:父 tool call 等待 child run,该 run 的结果成为 tool result。Child Session 应保留这个映射:agent_spawn的 tool result 绑定到 Child Session 的第一个 run;这样不需要向已经关闭的父 turn 追写 tool result。
3. Spawn lineage 和 fork lineage 是两种独立关系
一个 forked subagent 同时拥有两种 lineage:
runId/turnId/toolCallIdspawn;两种关系承担不同职责。Spawn lineage 负责嵌套投影、supervision、生命周期策略、usage 聚合以及 swarm/item identity;fork lineage 负责记录初始上下文快照的来源。
因此建议保留独立的 spawn lineage,例如:
使用
contextMode: "fork"时,再单独记录 fork provenance。实现可以复用现有 branch 的复制机制,但不应让parentSessionId + branchOfTurnId同时承担这两种关系。这样核心模型可以保持很小:
contextMode只决定初始状态如何复制。feat(runtime): migrate agent tools to child sessions (#1385)