Skip to content

fix(pi-subagents): commit delegate completion notifications at the model's next safe boundary (#2320) - #2389

Merged
ranxianglei merged 1 commit into
masterfrom
2026-10-08_delegate-notify-boundary
Oct 8, 2026
Merged

ranxianglei merged 1 commit into
masterfrom
2026-10-08_delegate-notify-boundary

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

Closes #2320

What & why

In Pi interactive mode, async acp_delegate completion notifications were parked in the host's follow-up queue behind an agent_settled gate, so they stayed invisible until the main task ended — even though delegate results are usually the current task's input. The issue asked for delivery at the next safe boundary while the main task runs.

This implements the full design agreed in the issue thread (both layers), in-repo after the #2384 vendoring:

Mechanism (pi-subagents/src/delegate-tool.ts)

Two-tier commit, tracked per host (WeakMap state; a host without the extension surface degrades gracefully):

  • Busy tier — a revocable pending set of finished-but-unnotified runs is re-checked at Pi's context extension event, which fires before every LLM call (verified against the pinned host 0.83.0: ContextEvent.messages → handler may return ContextEventResult.messages). At each boundary one merged notification is appended directly to the outgoing context mid-task. Because nothing enters an irreversible host queue, late wait/final-file read suppression keeps working right up to the commit — the post-commit staleness window of [Bug][Pi] notifyIfRead="skip" still delivers stale follow-ups after the final result was read #2301 closes at its source on this path (zero async gap between re-check and commit).
  • Idle tier — when no run is active, one merged steering message starts the follow-up turn (single merged wake, re-checked right before sending; all-claimed → cancelled).

Preserved unchanged: coalescing into one message per boundary, send-failure recovery via the undelivered-runs scan, usage dedup, read-suppression for completed runs only (failed runs always notify), waiter/consumed/injected ownership, session-scoped run tracking.

Gate semantics: the busy tier only appends when the context already contains an assistant message (mid-turn rebuild); contexts without one defer to the next commit point with the queue intact.

Intended behavior change (disclosed)

old new
Main task running notification parked in follow-up queue until task end merged into the next model call's context at the safe boundary (work continues afterwards)
Main agent idle steering-less wake after settle single merged steering message, immediate
Host without context event settle-gated followUp send settle-gated steer send (delivery form fixed, timing as before)

No new config surface. No change to other hosts' lanes (omp excluded as before; print/JSON still downgrade async→sync so no notification paths fire there).

Version

pi-subagents 0.1.2 → 0.1.3 (in-repo component; CI-enforced boundary rule). Lockfile carries the one-line echo.

Verification

  • Unit: pi-subagents suite 223/223 on the rebased head. New pi-subagents/tests/delegate-context-notify.test.ts (9 cases) pins both tiers: mid-task commit into the next model call, read-before-boundary drop, failed-always-notifies, two-finishes-one-message merge, non-assistant deferral, waiter exclusion, two-host isolation, idle single/batch steering wakes. delegate-tool.test.ts gains a pin that both legacy send paths use deliverAs: "steer".
  • Real-pi timing e2e (the issue required observing actual model consumption, not just the channel parameter): new tests/e2e/e2e-delegate-notify.test.ts, same hermetic conventions as e2e-native-pi (real pi --mode rpc through the embedded lane against the deterministic fake upstream; gated by ACP_TEST_E2E_NATIVE=1; artifacts under gitignored tmp/). Two scenarios, asserted from the upstream request oracle:
    • mid-task: delegate finishes during an 8-round tool loop; the notification appears as a fresh last-user message at queueIdx < totalDirectives with bash rounds continuing afterwards, and the host queue never parks it (pendingMessageCount stays 0);
    • idle: delegate finishes around/after the parent run ends; the notification auto-starts a follow-up turn with zero further input.
      Both pass locally (real pi 0.83.x) and are now wired into ci-e2e-native.yml alongside the native-pi suite.
  • Typecheck clean (root + component), build green (component dist inlined into dist/agent/pi-native.js).

Relationship to #2301

Complementary, not redundant: #7 (already on master) gates when the plugin commits; this changes where the committed bytes land. On the busy tier the notification never reaches an irreversible queue, which removes the "committed but then claimed" race window that #2301 documents; the idle tier keeps a single re-check immediately before the steering send.

Notes

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 收到,开始对 PR #2389 做 review(按规范:原 issue #2320 方向关 → 回归审查 → 代码审查 → 测试有效性 → diff 整洁度 + CI)。先给初步结论,完整八问结论随后补上。

@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-10-08_delegate-notify-boundary (b3c4039)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.2613-pr.2389.87c763a

This exact version is immutable and reproducible. The rolling pr tag tracks the newest test build across all PRs.

Option B — Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr2389.tgz
npm install -g package

Install instructions are refreshed on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 PR #2389 review 结论(结构化八问)

① 是什么问题:Pi 交互模式下 acp_delegate 异步完成通知以 followUp 入宿主队列,主任务运行期间一直滞留不可见;而子任务结果通常是当前任务的输入。本质缺陷是「提交点」放错了层——通知被提交进一个不可撤销的宿主队列,既等不到边界也撤不回来(#2301 的排队后抑制竞态同根)。

② 什么原因导致:旧实现把「投递时机」和「投递载体」耦合在 settle 事件 + sendUserMessage(followUp) 一条路径上:busy 时只能等整个任务结束,idle 时 followUp 语义也不精确;且检查与提交之间有 async 间隙,read/wait 抑制追不上提交。

③ 影响范围与严重程度:所有 Pi 交互/RPC 会话里用 async delegate 的用户;特定条件下有问题——子任务完成而主任务仍在长跑时,结果无法及时参与当前工作(重复劳动、失败处理延迟、用户误判)。非死锁,时序级影响。standalone 与内嵌两条 lane 都受影响。

④ 怎么修复的:两层提交,均把「所有权复查(waiter/consumed/read-suppression)挪到提交发生的同一同步段内」:

  • busy 层:注册 Pi context 扩展事件(每次 LLM 调用前触发),在出站消息列表原地复查并追加一条合并通知,返回 {messages} 替换——检查到落定零 await,[Bug][Pi] notifyIfRead="skip" still delivers stale follow-ups after the final result was read #2301 竞态从源头关闭;门控要求上下文已含 assistant 消息,首回合/辅助上下文拒收,队列原样留给下一边界。
  • idle 层:settle 后一条合并消息走 sendUserMessage({deliverAs:"steer"}) 立即起轮(单条唤醒,发送前再复查)。
  • 状态改为 per-host(WeakMap + 强引用枚举表),顺带修掉旧全局 notifyPi last-write-wins 的跨会话串扰。
  • injectResult 拆出纯文本构建 buildInjectText,发送语义不变仍导出;版本 0.1.2→0.1.3 + lockfile 回声,符合 component boundary 规则。

⑤ 是否有回归问题:对触碰路径的既有行为逐项清点——

  • 合并机制(feat(compress): configurable compression prompts (three-level, risk-gated) #157):两层都保持「相近完成 → 一条消息」,busy/idle 各有单测钉住 ✅
  • read/wait 抑制([Bug][Pi] notifyIfRead="skip" still delivers stale follow-ups after the final result was read #2301):提交时刻复查保留,busy 层新增「边界前已读即丢弃且永不补投」,failed 永不被抑制 ✅(单测覆盖)
  • waiter/consumed 所有权:排除逻辑不变,wait 路径独占投递;被移出队列的 waiter run 仍被 findUndeliveredRuns 的 !r.waiter 挡住,wait 异常清除后可经 recovery notice 兜底,无丢失无双投 ✅
  • 发送失败恢复:idle 层语义不变(sent 才标 injected,covered 仅在发送成功后标记);busy 层是同步追加无失败路径 ✅
  • usage 去重:separate 模式累加时序保持(先累加后构建 trailer);busy 层无条件标 usageReported(提交不可能失败,合理);merged 模式行为一致 ✅
  • print/JSON 同步降级、omp 排除:diff 未触碰 ✅
  • CI 高危门禁(pi-subagents-guard/version-guard/lane-guard/kernel-guard/docs-sync)+ real-pi/opencode/codex/dsh native lanes 全绿。
    结论:无回归。

⑥ 是否破坏缓存:不涉及(bili proxy 前缀缓存路径未触碰;本改动在 Pi 扩展 lane 内)。

⑦ 是否改了设计方向:有,属 issue 内已议定的设计落地:通知提交模型从「settle 门控 + 宿主队列」转向「边界提交(busy=上下文内联 / idle=steering 起轮)」。数据流未变(结果文件仍是持久事实源)。

⑧ 是否引入新配置:无。

行为变更披露(旧→新):

  1. busy 期投递时机:滞留至任务结束 → 下一个 model call 边界即达(本 PR 目的);
  2. idle 期载体:followUp → steer(idle 下两者几乎等价,steer 语义更准);
  3. 需补一句描述:busy 层注入是一次性上下文注入——只存在于那一次 LLM 调用的出站列表,不写入会话持久历史(已核实 pi-agent-core streamAssistantResponse:transform 结果仅用于当次请求,不回写 context.messages)。若模型看到通知但当下没消费,不会重发(已标 injected);持久通道 = 结果文件 + fleet widget + status 工具。这与旧 followUp「消费后成为永久历史条目」不同,是所选机制的固有取舍,我认为可接受(文件是 source of truth),但建议 PR 描述的行为表补上这一行,免得后人误以为通知会留在历史里。

验证证据(本地定向,非全量预跑):pi-subagents 套件 223/223 过;typecheck+build 干净;ACP_TEST_E2E_NATIVE=1 真实 pi --mode rpc(本机 0.83.6)×确定性 fake upstream 两场景本地实跑通过——midtask 场景证明通知以 fresh last-user-message 身份在 queueIdx<N 时被消费且 pendingMessageCount 全程为 0(buggy 形态必挂),idle 场景证明无进一步输入也能送达。这正是 #2320 要求的「宿主队列→模型消费」级验证,不是只断言 deliverAs。CI head d07c13a:24/26 绿,余 2 个 windows test job 在跑。

代码审查要点:宿主侧契约已对 pinned 0.83.0 源码核实——ContextEvent/ContextEventResult{messages?} 类型匹配;emitContext 全宿主唯一发射点(agent loop transformContext,compaction 不走它),handler 抛错被宿主捕获不毁请求,多 handler 链式替换语义正确。残留风险(记录,不阻塞):未来宿主若把辅助模型调用(如内置 compaction)也路由进同一 transformContext 且其上下文含 assistant 消息,批次可能被辅助调用吃掉并标 injected 而主模型看不到;当前 0.83.x 不存在此路径,assistant 门控只能缓解不能根除,建议随宿主升级时复查。

小发现处置:per-host 状态表的强引用枚举集 knownHosts 只增不减(ExtensionAPI 按会话创建,长寿命进程随会话数单调增长;prune 需先改闭包捕获否则队列脑裂,非顺手可修)→ 已立项 #2390(带来源标记,低优先级)。

判定:可合(待 windows 两个 test job 转绿即可;唯一建议项是 PR 描述补 busy 层一次性注入的披露句)。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

补充:分析本 PR 时发现的一个低优先级问题(per-host 通知注册表 knownHosts 只增不减)已单独处理——见 issue #2390 与 stacked PR #2392(base 即本分支)。它不阻塞本 PR 合并;本 PR 合入 master 后,我会把 #2392 rebase 到 master。若你更希望把它折进本 PR(合并前),告诉我即可。

@ranxianglei

Copy link
Copy Markdown
Owner Author

pull下master subagent已经复制进来了

…del's next safe boundary (#2320)

Completion notifications were parked in Pi's host queue via
sendUserMessage(deliverAs: "followUp") behind an agent_settled gate, so
they stayed invisible until the main task ended even though delegate
results are usually the current task's input.

Two-tier commit, tracked per host:
- busy: a revocable pending set is re-checked at the `context` extension
  event (fires before every LLM call) and one merged notification is
  appended to the outgoing context mid-task; nothing enters an
  irreversible host queue, so late wait/read suppression keeps working
  right up to the commit
- idle: one merged steering message starts the follow-up turn

Intended behavior change: old = notification delivered only after the
main task ends (follow-up queue); new = delivered at the next safe
boundary while the task runs, or immediately when idle. Per-host state
is isolated (WeakMap); hosts without a `context` event degrade to the
former settle-gated path with steering delivery instead of followUp.
pi-subagents 0.1.2 -> 0.1.3.

Adds tests/e2e/e2e-delegate-notify.test.ts (real pi RPC through the
embedded lane, gated by ACP_TEST_E2E_NATIVE; ci-e2e-native.yml now runs
it) asserting actual model-consumption timing from the upstream oracle:
mid-task consumption with work remaining afterwards, and idle auto-start
without further input.

Unit layer: pi-subagents suite 223/223 (new delegate-context-notify.test.ts
pins both tiers, merge/suppression/gate/isolation/wake semantics).

Supersedes ranxianglei/billion-context-pi-subagents#9 (opened before the
#2384 in-repo vendoring).
@ranxianglei
ranxianglei force-pushed the 2026-10-08_delegate-notify-boundary branch from d07c13a to b3c4039 Compare October 8, 2026 13:45
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 已 rebase 到最新 master 并推送(八问摘要)

收到同步提示后执行:git fetch → 确认 PR 父提交即 #2386(pi-subagents vendor)合并点,其后 master 新增提交(#2331、#2369 等,共 61 files/±2757)零触碰本 PR 的 8 个文件 → git rebase origin/master 无冲突,单提交重放干净。

  1. 是什么问题:PR 分支落后于 master(behind),需对齐当前 master 才能合并——纯维护操作,非代码问题。
  2. 什么原因导致:PR 基于 feat: vendor billion-context-pi-subagents in-repo under pi-subagents/ (#2384) #2386 vendor 合并点创建,期间 master 前进了若干无关提交。
  3. 影响范围与严重程度:仅 PR 分支基线;无功能影响。
  4. 怎么修复的:rebase(非 merge)保持单提交线性历史,diff 逐字节不变(8 files, +898/-126);force-push 到 PR 分支 2026-10-08_delegate-notify-boundary(d07c13a → b3c4039)。
  5. 是否有回归问题:不涉及新代码变更;rebase 后在 rebased head 上定向复验——pi-subagents 套件 223/223 过、npm run typecheck 干净、npm run build 绿(build-info b3c4039)。全量回归交给 CI。
  6. 是否破坏缓存:不涉及。
  7. 是否改了设计方向:不涉及。
  8. 是否引入新配置:不涉及。

PR 状态已转干净:mergeable=True,head=b3c40395a,与 master 无冲突(当前 blocked 仅为新 head 的 CI 还在跑)。上一轮 review 结论维持:可合,待 CI 全绿 + 描述补 busy 层一次性注入披露句即可。

@ranxianglei
ranxianglei merged commit 74a55c6 into master Oct 8, 2026
26 checks passed
@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

📦 Merged Build Published

This merge to master was published as 0.0.150-master.74a55c6 (rolling master tag).

npm install -g billion-context@0.0.150-master.74a55c6  # this exact build
npm install -g billion-context@master  # always the newest merged build

npm view billion-context@master prints the current version at any time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug][Pi] acp_delegate 完成通知使用 followUp,主任务运行期间长期滞留队列;建议改用 steer

1 participant