Skip to content

design(runtime): model subagents as linked child sessions #1366

Closed

Description

@likun666661

Summary

Maka currently represents a spawned subagent as an isolated child AgentRun inside the parent session:

  • it shares the parent sessionId and 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 RuntimeEvent persistence;
  • 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:

Suggested investigation path

  1. Define child-session identity, lineage, visibility, and lifecycle policy.
  2. Add a read-only parent/child session projection without changing agent_spawn.
  3. Create a child session through the normal SessionStore/Runtime lifecycle and run one existing child profile inside it.
  4. Preserve compatibility for legacy same-session child AgentRuns in list/output/resume paths.
  5. Move agent_spawn and agent_swarm to return both childSessionId and runId.
  6. Reuse normal session stop/recovery, RuntimeEvent persistence, compaction, usage, tool activity, and Host subscriptions.
  7. Add multi-turn follow-up and multi-client observation tests.
  8. 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 childSessionId without adding a second agent lifecycle system.

Related implementation references

中文说明

概述

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 不负责:

建议调研和实施路径

  1. 定义 Child Session identity、lineage、visibility 和 lifecycle policy。
  2. 先添加只读父子 Session 投影,不修改 agent_spawn。
  3. 通过正常 SessionStore/Runtime 生命周期创建 Child Session,并运行一个现有 child profile。
  4. 保证旧的同 Session child AgentRun 在 list/output/resume 路径仍可读取。
  5. 让 agent_spawn 和 agent_swarm 同时返回 childSessionId 与 runId。
  6. 复用普通 Session 的停止/恢复、RuntimeEvent 持久化、压缩、usage、tool activity 与 Host subscription。
  7. 增加多轮追问和多 client 观察测试。
  8. 最后再让 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 生命周期。

相关实现

Activity

  1. added
    enhancement
    on Jul 23, 2026
  2. likun666661 commented on Jul 23, 2026

    @likun666661
    MemberAuthor

    Proposed design direction

    The subtle but important conclusion is:

    Linked child sessions and graph scheduling are architecturally orthogonal, even though child sessions should be delivered first.

    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

    Session control plane
      identity, parent/child relation, visibility, permissions,
      stop/resume/archive, interaction routing, subscriptions
    
    Agent runtime
      one AgentRun at a time inside a session
    
    Event plane
      canonical RuntimeEvents scoped by sessionId + runId
    
    Future graph scheduler
      readiness, fan-out/join, backpressure, resource scheduling
    

    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.

    type SubagentParentRelation = {
      kind: 'subagent';
      parentSessionId: string;
      spawnedBy: {
        parentRunId: string;
        parentTurnId: string;
        toolCallId: string;
      };
      swarm?: { swarmId: string; itemId: string };
      lifecycle: 'foreground';
    };

    Storage/Host derives or indexes the reverse lookup:

    listChildSessions(parentSessionId): Promise<SessionSummary[]>

    Existing branch/revision fields remain compatible. We can introduce sessionKind, or first add a narrow subagentParent block and normalize lineage later. The critical invariant is that Host code must not infer “branch” from parentSessionId alone.

    3. Child creation semantics

    Introduce an internal runtime primitive:

    spawnChildSession({
      parentSessionId,
      spawnedBy,
      agentProfile,
      prompt,
      contextPackage?,
    }): Promise<{
      childSessionId: string;
      turnId: string;
      runId: string;
    }>

    Creation should:

    1. Validate the parent session and active parent run.
    2. Resolve the child profile and permission ceiling.
    3. Create a fresh Session through the normal SessionStore lifecycle.
    4. Snapshot backend, connection, model, cwd/workspace identity, and child profile.
    5. Persist the typed parent relation on the child header.
    6. Append a normal initial user turn containing the assigned task.
    7. Reference relevant parent RuntimeEvents/artifacts instead of cloning the parent ledger.
    8. Start a normal session-inline AgentRun in the child session.

    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.parentRunId semantics as its model-history boundary.

    4. Context and event invariants

    • Never clone the full parent transcript or RuntimeEvent ledger.
    • The initial prompt is the explicit task/handoff package.
    • Extra context is copied deliberately or referenced through canonical event/artifact refs.
    • Child messages and RuntimeEvents use the child sessionId.
    • Follow-ups use normal sendMessage(childSessionId, ...) behavior.
    • Compaction/checkpointing is partitioned by child sessionId.
    • The parent receives a bounded result/reference, not the full child transcript.

    5. Lifecycle policy for v1

    Preserve current foreground behavior first:

    • agent_spawn/agent_swarm wait for child work to settle.
    • Parent tool cancellation propagates to the active child session.
    • Stopping the parent stops active foreground-owned children.
    • Stopping one child affects only that child.
    • Completed child sessions remain durable and can be reopened or followed up.
    • Archiving a parent may collapse its nested children in Host projection without mutating every child.
    • Deleting a parent must not silently cascade-delete child transcripts; retain inspectable orphans unless deletion is explicitly recursive.

    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:

    • backend/model/connection;
    • cwd/workspace identity;
    • agent profile and tool allowlist;
    • a permission ceiling that cannot exceed the parent.

    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:

    Main session
    ├── Local Read · completed
    ├── Web Research · running
    └── Verification · waiting
    

    Recommended Host capabilities:

    • list children of a parent;
    • open a child using the existing session view;
    • subscribe to its normal message/RuntimeEvent stream;
    • stop/resume/follow up;
    • show usage, tool activity, artifacts, and permission state;
    • optionally pin/promote it to a top-level session.

    A stable childSessionId naturally 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:

    type SubagentExecutionRef =
      | { kind: 'child_session'; sessionId: string; currentRunId?: string }
      | { kind: 'legacy_child_run'; sessionId: string; runId: string };

    During migration:

    • new agent_spawn calls create child sessions;
    • agent_list returns both forms;
    • agent_output accepts either form;
    • existing resume_run_ids remain readable through a legacy path or create a linked child session with explicit provenance;
    • no historical AgentRun/RuntimeEvent rewrite is required.

    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_spawn and agent_swarm

    Return childSessionId plus runId, 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

    1. Spawn a child, restart, reopen it, and inspect the same transcript.
    2. Follow up and prove the child sees its own history but not the full parent history.
    3. Stop the parent during foreground child work and prove cancellation reaches the child.
    4. Stop one child and prove siblings and parent continue.
    5. Trigger compaction and prove checkpoints are isolated by child session.
    6. Observe one running child from two clients with consistent event ordering.
    7. Aggregate parent-tree usage without duplicating stored usage facts.
    8. Read legacy child AgentRuns alongside new child sessions.
    中文方案

    设计结论

    这里最微妙也最重要的结论是:

    Child Session 与 Graph Schedule 在架构职责上正交,但工程交付顺序上应先完成 Child Session。

    Child Session 解决身份、生命周期、持久化、交互和可观察性;未来 Graph Scheduler 解决 readiness、依赖、资源准入和 record routing。先完成 Child Session,是为了稳定未来 Agent operator 绑定的执行身份,而不是把图调度概念放进 Session 模型。

    1. 职责边界

    Session 控制面
      identity、父子关系、visibility、permission、
      stop/resume/archive、交互路由、subscription
    
    Agent Runtime
      在一个 Session 内执行一次 AgentRun
    
    Event Plane
      按 sessionId + runId 持久化 canonical RuntimeEvent
    
    未来 Graph Scheduler
      readiness、fan-out/join、backpressure、资源调度
    

    本 Issue 不引入 graphId、operatorId、activationId、join 或 scheduler state。即使没有 #1341,Child Session 本身也应成立。

    2. 父子关系的事实源

    建议把类型化、不可变的 parent relation 存在子 Session 上。父 Session 不保存 reciprocal childSessionIds[],避免双向写入造成原子性、修复和一致性问题。

    type SubagentParentRelation = {
      kind: 'subagent';
      parentSessionId: string;
      spawnedBy: {
        parentRunId: string;
        parentTurnId: string;
        toolCallId: string;
      };
      swarm?: { swarmId: string; itemId: string };
      lifecycle: 'foreground';
    };

    Storage/Host 通过索引或投影提供反向查询 listChildSessions(parentSessionId)。

    现有 branch/revision 字段继续兼容。可以引入 sessionKind,也可以先添加窄化的 subagentParent block。关键约束是 Host 不能再仅凭 parentSessionId 推断它一定是 branch。

    3. Child 创建语义

    新增内部 Runtime primitive:

    spawnChildSession({
      parentSessionId,
      spawnedBy,
      agentProfile,
      prompt,
      contextPackage?,
    }) -> { childSessionId, turnId, runId }

    过程包括:校验父 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 约束

    • 不复制父 Session 的完整 transcript 或 RuntimeEvent ledger。
    • 初始输入是显式 task/handoff package。
    • 额外上下文必须显式复制或用 canonical event/artifact ref 引用。
    • Child message/RuntimeEvent 使用 child sessionId。
    • 后续追问复用普通 sendMessage(childSessionId, ...)。
    • compaction/checkpoint 按 child sessionId 隔离。
    • 父 Agent 只获得有界结果/引用,不自动吸收完整 child transcript。

    5. v1 生命周期

    优先保持 foreground 语义:

    • agent_spawn/agent_swarm 等待 child settle。
    • parent tool cancellation 传播到活跃 Child Session。
    • 停止父 Session 时停止活跃的 foreground-owned children。
    • 停止一个 child 不影响父和兄弟 child。
    • 已完成 child 持久存在,可重新打开和继续追问。
    • archive 父 Session 可在 Host 投影上折叠 child,不必修改全部 child header。
    • 删除父 Session 不应悄悄级联删除 child transcript;除非显式递归删除,否则保留可检查 orphan。

    未来 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. 兼容策略

    不原地迁移历史数据:

    type SubagentExecutionRef =
      | { kind: 'child_session'; sessionId: string; currentRunId?: string }
      | { kind: 'legacy_child_run'; sessionId: string; runId: string };

    新 spawn 创建 Child Session;agent_list/agent_output 同时支持两种形式;旧 resume_run_ids 继续可读;不改写历史 AgentRun/RuntimeEvent。

    9. 建议 PR 顺序

    1. Session relation contract/read model:类型化 relation、旧数据 decoding、反向 child lookup,不改变 spawn。
    2. Child-session runtime primitive:全新 Child 创建、环境/权限快照、首个 session-inline Run、停止/恢复/no-parent-history;先跑只读 profile。
    3. 切换 agent_spawn/agent_swarm:返回 childSessionId 与 runId,兼容 legacy,保持 foreground cancellation/all-settled。
    4. Host lifecycle/multi-turn observation:嵌套 Desktop/TUI、subscription、interaction routing、follow-up、compaction、usage/tool activity、restart、多 client 测试。

    稳定以后再让 #1341 的 Agent operator 使用 Child Session。这是工程顺序选择,不是架构耦合;未来 Scheduler 面向通用 execution handle,Child Session 只是首选 Agent execution adapter。

    10. 核心验收

    1. Spawn child,重启后重新打开同一 transcript。
    2. 继续追问时只看到 child 自己的历史,不看到完整父历史。
    3. foreground child 运行时停止父 Session,取消传播到 child。
    4. 停止一个 child,不影响父和兄弟 child。
    5. compaction checkpoint 按 Child Session 隔离。
    6. 两个 client 同时观察一个 child,事件顺序一致。
    7. 父树 usage 聚合不重复写 usage facts。
    8. legacy child AgentRun 与新 Child Session 可同时读取。
  3. Astro-Han commented on Jul 23, 2026

    @Astro-Han
    Contributor

    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 fresh the default rather than the only supported model.

    The structural choice only needs two modes:

    • fresh — copy an explicit task and context package into the child session;
    • fork — copy a complete snapshot of the parent's conversation state into the child session.

    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_spawn tool 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:

    • copy the complete transcript prefix into the child session;
    • copy the runtime ledger/checkpoint state needed to reconstruct the parent's effective model context at that boundary;
    • copy any required artifacts into the child session's own namespace;
    • let the child compact and evolve independently afterward.

    "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 / branchBeforeTurn can be reused, although the spawn boundary is a model-input snapshot rather than necessarily a completed turn boundary. A minimal tool option could be:

    contextMode: "fresh" | "fork";

    Fork has two independent benefits:

    1. Context reuse. Parallel-worker-style subagents sometimes perform better when they inherit the state from which the parent delegated the work.
    2. Cache reuse and fanout amortization. There are two possible reuse paths:
      • parent to child — when the parent and child use the same system prompt, tool definitions, model, and effective context prefix;
      • sibling to sibling — even if the child profile differs from the parent, a homogeneous swarm can share one long prefix across all children when they use the same profile, tools, model, and fork snapshot. Each item then diverges only at its task suffix.

    The sibling case is particularly valuable for a large one-shot agent_swarm fanout: 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_spawn and agent_swarm should accept the same explicit option:

    contextMode: "fresh" | "fork";

    The default should remain fresh. A swarm should select fork deliberately rather than allowing a cost optimization to change its context semantics automatically.

    2. Result delivery should remain synchronous per parent tool call

    Today agent_spawn is 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_spawn binds its tool result to the child session's first run;
    • when the parent agent follows up, it makes another synchronous tool call that resumes the same child transcript, starts a new run, and returns that run's result;
    • when a user follows up directly in the child session, the result remains in the child session and owes the parent transcript no tool result;
    • if the parent turn is aborted while a child is running, the completed result remains durable in the child session and can be inspected or pulled by a later parent 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:

    • it was spawned by a specific parent runId / turnId / toolCallId;
    • its initial context was forked from a specific parent-model input snapshot.

    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:

    spawnedBy?: {
      sessionId: string;
      runId: string;
      turnId: string;
      toolCallId: string;
      swarmId?: string;
      itemId?: string;
    };

    Fork provenance can be recorded separately when contextMode: "fork" is used. The implementation may reuse branch-copying machinery, but it should not overload parentSessionId + branchOfTurnId to represent both relations.

    This leaves the core model small:

    • Child Session owns a durable, self-contained conversational state.
    • AgentRun is one invocation within it.
    • Spawn lineage explains who created and supervises it.
    • contextMode only decides how its initial state is copied.
    中文对照

    整体方向我认为是对的。把持久 subagent 身份提升为有关联的 Child Session,可以消除围绕 AgentRun 不断增加的特殊逻辑;先于 #1341 完成这层设计,顺序也合理。建议进一步明确三点。

    1. 应把从父 Agent fork 保留为一等选项

    目前 issue 把 “Fresh context, not a copied branch” 表述为设计原则。建议把 fresh 作为默认值,而不是唯一支持的模型。

    结构上只需要两种模式:

    • fresh:把显式任务和 context package 复制进 Child Session;
    • fork:把父 Agent 对话状态的完整快照复制进 Child Session。

    Handoff package 只是 fresh 模式中的内容,不是第三种模式。

    Fork 边界应该是产生这次 agent_spawn tool call 的那次父模型输入。它不应包含随后生成的 tool call 自身;分配给 child 的任务作为新的输入追加。这样 child 可以获得父 Agent 作出委派决策时所依据的上下文,又不会递归包含委派行为本身。

    快照应当自包含:

    • 把完整 transcript 前缀复制进 Child Session;
    • 复制在该边界重建父 Agent effective model context 所需的 runtime ledger/checkpoint 状态;
    • 把所需 artifact 复制进 Child Session 自己的 namespace;
    • 此后由 child 独立执行 compaction 和继续演化。

    这里的“完整 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。工具层只需要一个最小选项:

    contextMode: "fresh" | "fork";

    Fork 有两个相互独立的价值:

    1. 复用上下文。 对于并行 worker 类型的 subagent,继承父 Agent 作出委派时的状态,有时本身就能带来更好的效果。
    2. 复用缓存并摊薄 fanout 成本。 这里存在两条缓存复用路径:
      • 父 Agent 到 child:parent 和 child 使用相同的 system prompt、工具定义、模型和有效上下文前缀;
      • Sibling 之间:即使 child profile 与 parent 不同,只要同构 swarm 中的 children 使用相同的 profile、工具、模型和 fork 快照,它们仍可共享一个较长的公共前缀。各 item 只在最后的任务后缀处分叉。

    第二种情况对一次性 fanout 大量 child 的 agent_swarm 尤其有价值:公共 transcript 前缀可以只缓存一次,再由大量 child 请求复用,从而摊薄成本和延迟。构造请求时,应把 item task、item ID 和其他可变元数据放在公共可缓存前缀之后。

    这是一项优化机会,而不是无条件保证。实际复用取决于 provider 行为和缓存有效期;如果所有 child 在公共缓存建立前同时启动,Runtime 后续可能需要先显式建立缓存,再并发 fanout。

    agent_spawn 和 agent_swarm 应接受同一个显式选项:

    contextMode: "fresh" | "fork";

    默认值仍应为 fresh。Swarm 应显式选择 fork,而不是让成本优化自动改变其上下文语义。

    2. 每次父工具调用都应保持同步结果交付

    当前 agent_spawn 是同步的:父 tool call 等待 child run,该 run 的结果成为 tool result。Child Session 应保留这个映射:

    • agent_spawn 的 tool result 绑定到 Child Session 的第一个 run;
    • 父 Agent 发起 follow-up 时,再执行一次同步工具调用:恢复同一个 child transcript、启动新 run,并返回该 run 的结果;
    • 用户直接在 Child Session 中发起 follow-up 时,结果保留在 Child Session 内,不需要向父 transcript 交付 tool result;
    • 如果 child 仍在运行时父 turn 被中止,child 的完成结果继续持久化在 Child Session 中,父 Agent 后续的新 run 可以检查或拉取它。

    这样不需要向已经关闭的父 turn 追写 tool result。

    3. Spawn lineage 和 fork lineage 是两种独立关系

    一个 forked subagent 同时拥有两种 lineage:

    • 它由父 Session 中某个具体的 runId / turnId / toolCallId spawn;
    • 它的初始上下文 fork 自父 Agent 的某个具体模型输入快照。

    两种关系承担不同职责。Spawn lineage 负责嵌套投影、supervision、生命周期策略、usage 聚合以及 swarm/item identity;fork lineage 负责记录初始上下文快照的来源。

    因此建议保留独立的 spawn lineage,例如:

    spawnedBy?: {
      sessionId: string;
      runId: string;
      turnId: string;
      toolCallId: string;
      swarmId?: string;
      itemId?: string;
    };

    使用 contextMode: "fork" 时,再单独记录 fork provenance。实现可以复用现有 branch 的复制机制,但不应让 parentSessionId + branchOfTurnId 同时承担这两种关系。

    这样核心模型可以保持很小:

    • Child Session 拥有持久、自包含的对话状态;
    • AgentRun 是其中的一次 invocation;
    • Spawn lineage 说明谁创建和监督它;
    • contextMode 只决定初始状态如何复制。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions