diff --git a/docs/architecture/rust-agent/plugins/Wait.md b/docs/architecture/rust-agent/plugins/Wait.md index b3f5424f81..93c0e5ed12 100644 --- a/docs/architecture/rust-agent/plugins/Wait.md +++ b/docs/architecture/rust-agent/plugins/Wait.md @@ -1,6 +1,6 @@ # Wait -The Wait plugin registers Wait in every Session and WaitBranch in every branch. +The Wait plugin registers Wait in every Session and WaitBranch in every branch. The branch part's target contract is [WaitBranch](../../../design/plugins/WaitBranch.md). ## Wait @@ -82,18 +82,9 @@ Provides branch-local wait state recording eligible arrivals during an open turn | `B:Dispatcher` | Consume arrivals and turn boundaries in order. | | `B:Timeline` | Read the last `turn/start` or `turn/end` and the unpublished tail, so the rebuild knows whether a turn is open. | -### Data face +### Data face (current and target) -`wait` is this part's service by name -([service faces §3.4](../../../design/service-faces.md#34-对象句柄拆成操作加-id)): - -```text -wait.wait(taskId: string | null, timeoutMs: number, cancelled: () => void | Promise) - -> {reason: "notification", taskIds, waitedMs} - | {reason: "user_steer", waitedMs} | {reason: "already_notified", taskIds, waitedMs} - | {reason: "timeout", waitedMs} | {reason: "interrupted", waitedMs} - -> error {code: "AlreadyWaiting" | "Reloading", message} -``` +Current implementation: `wait(taskId, timeoutMs, cancelled)` in [wait.rs](../../../../crates/dim-agent-capabilities/src/wait.rs), answering `WaitResult` or `WaitCallError`. The target is [WaitBranch](../../../design/plugins/WaitBranch.md) § Operations, which takes `wait(request, cancelled)` and a `state()` read, and answers `WaitResult`, `WaitState` or `WaitCallError`. It is the same wait the tool call makes. `cancelled` is the call's own cancellation and ends it as `interrupted`, releasing the single-wait slot. diff --git a/docs/design/capability-document-review.md b/docs/design/capability-document-review.md index 660bb82141..3031bca77a 100644 --- a/docs/design/capability-document-review.md +++ b/docs/design/capability-document-review.md @@ -16,7 +16,7 @@ and completion belong in the issue. The proposed authoring method is in the | What do order, state responsibility and work settlement mean? | [Time bus §1–5](../architecture/rust-agent/time-bus.md) | State the feature's transitions and consequences, not another global rule | | What can a plugin read/write and how does it join live consumption? | [Plugin contract §5–7](plugin-contract.md) | State dependencies and use the contract; bindings describe spelling only | | What does a query return, and how do cutoff, relations and continuation work? | [Property query §2–3](timeline-property-query.md) | Define business selection and arguments; do not reproduce query semantics | -| What survives a reload for one feature? | The [lifecycle contract](plugin-contract.md#72-generations-reload-and-rebuild) and its owner design, for example [Goal state](plugins/Goal-state-read.md), [Queue recovery](input-queue-recovery.md), [Prompt state](prompt-state-read.md), [Wait](../architecture/rust-agent/plugins/Wait.md) | Apply the existing lifecycle obligations and the owner's business recovery outcome; restoring state does not justify leaving old execution running | +| What survives a reload for one feature? | The [lifecycle contract](plugin-contract.md#72-generations-reload-and-rebuild) and its owner design, for example [Goal state](plugins/Goal-state-read.md), [Queue recovery](input-queue-recovery.md), [Prompt state](prompt-state-read.md), [WaitBranch](plugins/WaitBranch.md) | Apply the existing lifecycle obligations and the owner's business recovery outcome; restoring state does not justify leaving old execution running | | How do owner reads and saved results fit together? | [Saving boundaries](owner-state-indexed-reads.md), [Resume design](resume-read-design.md) | Keep cross-module dependencies here and detailed fields/algorithms in owner documents | | How does a part mount, name dependencies and cross languages? | [rutis usage](rutis-usage.md), [service faces](service-faces.md) | Link the current binding; do not copy old API spellings into architecture rules | | What exists in the actual assembly? | [Generated catalog](../architecture/rust-agent/generated/catalog.md) | Use as implementation evidence for that profile, not a closed universe of plugins | diff --git a/docs/design/cli-current-activity.md b/docs/design/cli-current-activity.md index 57336eb7c5..15c0d1fb34 100644 --- a/docs/design/cli-current-activity.md +++ b/docs/design/cli-current-activity.md @@ -136,22 +136,23 @@ Source reviewed against `077892025020a2875a559b432dfa3256878422ff`. ## Owner requirement for named waits -To show “Waiting for task: CI checks” in #1659, ToolExecution needs an agreed -public per-call activity contract with [Wait](../architecture/rust-agent/plugins/Wait.md). -ToolExecution owns tool lifecycle and call identity. WaitBranch owns admission -and settlement through the existing branch-local `wait` face. Tool handler start -alone cannot establish that WaitBranch accepted a wait or supply its clock. - -The owner decision must cover: - -- A scoped identity for the admitted wait: Session, branch, turn, request, - dispatch event ID and call ID, with an optional task ID. Publish a positive - admission signal and the authoritative admission time if elapsed time is - supported. Correlate the target by exact task identity in the same Session - and branch. Use the task projection’s existing title fallback. -- Matching settlement for notices, steer, timeout, interruption and reload, - ordered against batch and turn completion. Handle rejected calls and - immediate outcomes without leaving a live wait claim. A timeout ends the +To show “Waiting for task: CI checks” in #1659, the CLI reads a positive +admission signal and its start from [WaitBranch](plugins/WaitBranch.md)'s +`state` read. ToolExecution owns the tool's lifecycle and call identity; +WaitBranch owns the line's admitted wait, its admission and its settlement. A +tool handler's start alone cannot establish that WaitBranch accepted a wait or +supply its clock. + +The decision covers: + +- One admitted wait per line: `state()` answers `{waiting, startedAt?, taskId?}`, + with the optional task ID and the admission time. The reply carries no call + ID and no turn or request identity; the client correlates it with its own + turn and batch. Reading the task’s title uses the task projection’s existing + title fallback. +- Settlement by the `wait` call’s result: notices, steer, timeout, + interruption and reload end it, ordered against batch and turn completion. + A refused call ends at once and leaves no live wait claim. A timeout ends the wait independently of the target’s outcome. - Evidence for any claim that the foreground is waiting on one object. A concurrent wait can share a step with calls such as `read`. Use the @@ -159,16 +160,20 @@ The owner decision must cover: A confirmed untargeted wait can say “Waiting for a background task or new input”. A confirmed targeted wait with an unavailable task can say “Waiting for task: details unavailable”. -- If exact reconnect restoration is required, a bounded owner read at a - fixed cutoff and an ordered handoff to live updates. A gap leaves the - relationship unknown. WaitBranch reload settles accepted calls and - rebuilds open-turn status, so a reload does not reconstruct an old wait. +- Reconnect: a client reads `state` again and claims a wait only while it + answers one. WaitBranch reload settles accepted calls and rebuilds open-turn + status, so a reload does not reconstruct an old wait. -The owners decide whether existing progress facts can contribute and what -additional admission or settlement evidence is needed. The design with -shipped facts adds no service face, Timeline event, stored format or flag -change. The conditional status below depends on that owner decision and -an admitted wait with an authoritative start. +The design with shipped facts adds no Timeline event, stored format or flag +change; the owner adds the `state` read. The App Server reads it by +`(sessionId, branchId)` and answers a protocol v4 client through a method or +notice that needs a maintainer decision, so the client-protocol addition is a +separate decision. Until that lands, the status below has no client path. + +The former per-call requirement — a call ID, dispatch event ID, request +identity and a per-call admission record — is dropped: the slot makes the +line’s admitted wait unique, and the `wait` result settles it. Recorded in +[WaitBranch](plugins/WaitBranch.md) § Use and scope. Conditional scrollback and fullscreen examples: @@ -230,8 +235,10 @@ adopted inputs. Repainting adds zero RPCs, history scans or remote CI polls. Cover untargeted and unknown-target waits, colliding task IDs across scopes, immediate outcomes, active or unknown concurrent siblings and missing clock origins. - If exact reconnect becomes part of that contract, test owner cutoff, - live handoff, stale settlement and wait generation reload. + Reconnect is settled by [WaitBranch](plugins/WaitBranch.md)'s `state` read: + a client reads it again and claims a wait only while it answers one, and a + reload does not restore an old wait. Test that re-read, not owner cutoff, + live handoff or stale settlement. ## Ablation review @@ -239,5 +246,5 @@ The existing composer, task strip and bounded projection suffice for batch-level display. Keep batch and task identities separate because their lifetimes diverge at handoff. A per-call tracker, an additional store or a timer read cannot establish admission from the default facts. -Named waits depend on the owner contract. Exact restoration is a -separate requirement for that contract to settle. +Named waits read the owner contract's `state`. Reconnect restoration is +settled there: the client re-reads `state` and an old wait is not restored. diff --git a/docs/design/examples/capability-models/coverage-audit.md b/docs/design/examples/capability-models/coverage-audit.md index 7bba118c18..0174430f61 100644 --- a/docs/design/examples/capability-models/coverage-audit.md +++ b/docs/design/examples/capability-models/coverage-audit.md @@ -32,7 +32,7 @@ | [ToolExecutor](../../../architecture/rust-agent/plugins/ToolExecution.md#toolexecutor) | 执行段、排他、取消、单父调用的子效果 | claim 在提交前登记、未派发批次释放;resolve_write 后批准和执行同一个调用;两个父调用各收自己的子 effects;已有父返回效果不重复补入;progress/completed/batch-result 身份和顺序 | 不证明宿主副作用能回滚;也不新增排队后的二次授权。NestedSettlement 只有一个 parent,不能检查跨 parent 混入 | | [InputQueue](../../../architecture/rust-agent/plugins/InputQueue.md#inputqueue) | held/released、替代与删除同批、单输入首个控制 | 多条 Queue 的实际到达顺序;不同 turn 的 handover;普通 pending 排除 handover;notHeld 不产生替代;已接纳但发布未知的服务结果;多个 owed withdrawal 按命令序结算;observable snapshot 等结果提交后更新 | SubmitChecks 是 Session 入口的依赖,不重做检查;“检查通过不预留条目”仍须与条件接纳一起核对 | | [Loop](../../../architecture/rust-agent/plugins/Loop.md) | 单 turn/request、工具后下一步、reload 失败、局部 continuation | 已采用输入如何组成每轮请求;停止后旧未应用队列不被误启动;未执行工具身份逐项结算;预算恢复、输出上限、工具步骤、用户输入共同决定结束还是续行;failure chain 数值跨请求不重置 | 不检查模型回答质量;输入和失败链影响下一步选择,不能仅作为无结构布尔值丢掉 | -| [WaitBranch](../../../architecture/rust-agent/plugins/Wait.md) | 槽/tracker、关闭 drain、task 匹配、最后回合边界恢复 | 通知资格、顺序、Steer 优先;不匹配通知保留;AlreadyWaiting/Reloading/Interrupted/Timeout 的可观察区别;已有通知立即取走与注册唤醒的交接;工具与服务的 timeout 边界不同。详见下一节 | 不负责后台任务执行完成;超时也不停止任务。无需模拟真实毫秒,但要有“到期”输入 | +| [WaitBranch](../../../architecture/rust-agent/plugins/Wait.md)、[契约](../../plugins/WaitBranch.md) | 槽/tracker、关闭 drain、task 匹配、最后回合边界恢复 | 通知资格、顺序、Steer 优先;不匹配通知保留;AlreadyWaiting/Reloading/Interrupted/Timeout 的可观察区别;已有通知立即取走与注册唤醒的交接;工具与服务的 timeout 边界不同。详见下一节 | 不负责后台任务执行完成;超时也不停止任务。无需模拟真实毫秒,但要有“到期”输入 | | [ContextPreparation](../../../architecture/rust-agent/plugins/ContextPreparation.md) | prepare 结果互斥、内容 cut、compaction 返回后交接 | 预算超限先压缩、仍不适配则终止且不无限再恢复;最终请求被 host 改变后重新验证,不能沿用旧估计;Steer 在自动压缩中到达时延后替换;配置/guide 更新对同一 source 的采用 | 压缩文本质量及 codec 算法可外置;是否允许 model/call、是否重用估计是本次请求的状态责任 | | [ModelProvider](../../../architecture/rust-agent/plugins/ModelProvider.md#failure-chain) | 单请求输出终态、重试上限/等待预算 | continuation 继承 attempts/waited,预算耗尽时根本不调用;request-local backoff/malformed 额度重置与 chain 总额不重置;ToolStart 与完整 ToolUse 的不同错误结算;按 request 关联 usage/terminal | 流解析算法可外置,但“工具参数未完成”与“已完整但未执行”必须保留为不同交接状态 | | [Prompt](../../../architecture/rust-agent/plugins/Prompt.md) | source 单调采用、配置同批、退役记录同批 | configure 成功/失败/被 supersede 的结果;撤销缺失 source;首次 opening receipt 与后续动态变更的顺序;按完整 source/scope 身份恢复有效 entry。现有 Retirement 模型每 scope 一个集合成员,未覆盖多 source 的替换关系 | 未定位生产者的 context/scope 不当作已完成端到端路径;无需重写 PromptHost 内部加载 | @@ -56,7 +56,7 @@ 先找队列中第一个 Steer,再找第一个匹配 task。无 taskId 时两个不同 task 都匹配。 两段历史 `task A → task B` 与 `task B → task A` 在原模型中得到相同集合 `{A,B}`; -但调用 `wait(null, ...)` 在代码中应分别取 A 和 B。因此原抽象不足以检查这个选择承诺。 +但调用 `wait(WaitRequest { task_id: None, timeout_ms }, cancelled)` 在代码中应分别取 A 和 B。因此原抽象不足以检查这个选择承诺。 这不影响原模型对 tracker/drain 的检查,却限制了它能代表的 Wait 行为范围。 这里依据的是方法注释和实现的现行选择行为,不另立新的公开 FIFO 规范;集合抽象对原先的生命周期命题仍可适用。 diff --git a/docs/design/examples/owner-handoff-verification.md b/docs/design/examples/owner-handoff-verification.md index 845eef8a24..b1f002cd2d 100644 --- a/docs/design/examples/owner-handoff-verification.md +++ b/docs/design/examples/owner-handoff-verification.md @@ -11,7 +11,7 @@ | [时间总线 §2、§4](../../architecture/rust-agent/time-bus.md):生产方只按自身已消费状态复核;消费者拒绝中断后的迟到请求 | `AgentLoop::on_event` 在模型终态上写 tool-call;ToolExecutor 的 handler 记录 interrupt、拒绝批次;`InterruptHandoff.Deliver` | Dispatcher 单事实串行交付;允许在较早事实尚在派发时追加 interrupt。两个消费者进度分开,不引入全局取消位 | | ToolExecutor 在途工作先释放资源再写结果;Loop 等结果再结束 turn | [ToolExecution](../../architecture/rust-agent/plugins/ToolExecution.md) 的任务 join 与 result;`Invoke/Finish`、`TurnEndWaitsForResult` | 本模型将 host 结束作为动作机会;不证明 host 尊重取消或最终返回 | | [重载协议](../../architecture/rust-agent/single-tree.md#能力重载协议):旧工作不重执行,各 owner 写自己的终态 | `WaitBranch` cleanup、ToolExecutor cleanup/rebuild、Loop rebuild/on_event;`GenerationHandoff` | 一个已持久化的 turn 和顶层 batch;一个调用、各 owner 最多一次正常换代,另允许一次进程崩溃 | -| [Wait](../../architecture/rust-agent/plugins/Wait.md) 重载拒绝旧调用,并把 reload 交给工具结算 | `ReplyReload/Settle/ConsumeLoop`,`ReloadDoesNotContinue` | `Reloading` → HostError → result settlement 标记的转换来自代码;普通完成另有 `NormalReply`,不会预先假定所有结果都是重载失败 | +| [WaitBranch](../plugins/WaitBranch.md) 重载拒绝旧调用,并把 reload 交给工具结算(当前实现见 [Wait](../../architecture/rust-agent/plugins/Wait.md)) | `ReplyReload/Settle/ConsumeLoop`,`ReloadDoesNotContinue` | `Reloading` → HostError → result settlement 标记的转换来自代码;普通完成另有 `NormalReply`,不会预先假定所有结果都是重载失败 | | 新代读完整固定 cut 后再消费后缀 | ToolExecutor `rebuild`、Loop `rebuild`;`CaptureTool/CaptureLoop` 与后续处理 | C 的暂存/串行算法作为既有接口前提;本模型不复制队列,而让 Loop 在重建前后读到终态 | | 失败不能伪装成功接管 | `RebuildTool(FALSE)/RebuildLoop(FALSE)` 保留 failed;`Settle(FALSE)`、`StorageFailure` 保留写入故障 | 查询失败与存储故障分开;required apply 失败的装配回滚不在模型中,见第 4 节。不能据此宣称分支继续健康运行 | diff --git a/docs/design/examples/timeline-capability-analysis.md b/docs/design/examples/timeline-capability-analysis.md index 061ca3288e..6315a766f3 100644 --- a/docs/design/examples/timeline-capability-analysis.md +++ b/docs/design/examples/timeline-capability-analysis.md @@ -81,7 +81,7 @@ - **转换**:open 回合内的合格通知或 Steer 可结束等待;匹配 task ID 取对应通知;turn/end 清通知;reload 终止旧调用并拒绝保留原生句柄的新调用。 - **恢复**:`open=(last({turn/start,turn/end},c)=start)`;pending 通知和旧调用不恢复。工具结果归 ToolExecutor 写,不由 Wait 另写终态。 - **性质/论证**:open 的最后边界等价于对边界规则的归纳;接纳和关闭共用锁,tracker 登记发生在解锁前,关闭后 drain 不会漏过新接纳;释放槽早于释放 tracker。进度仍依赖调用 future 被 poll 或 drop。 -- **对应**:[wait.rs](../../../crates/dim-agent-capabilities/src/wait.rs)、[Wait](../../architecture/rust-agent/plugins/Wait.md)、[#1619](https://github.com/arcships/dim/pull/1619);复用 #1616 的有界恢复模型,当前 local_execution 的原生、face、完整工具 reload 流程验证新实现。 +- **对应**:[wait.rs](../../../crates/dim-agent-capabilities/src/wait.rs)、[WaitBranch](../plugins/WaitBranch.md)(当前实现见 [Wait](../../architecture/rust-agent/plugins/Wait.md))、[#1619](https://github.com/arcships/dim/pull/1619);复用 #1616 的有界恢复模型,当前 local_execution 的原生、face、完整工具 reload 流程验证新实现。 ## 7. ContextPreparation diff --git a/docs/design/examples/timeline-contract-coverage.md b/docs/design/examples/timeline-contract-coverage.md index b4114e5f53..6377d1f908 100644 --- a/docs/design/examples/timeline-contract-coverage.md +++ b/docs/design/examples/timeline-contract-coverage.md @@ -62,7 +62,7 @@ B 的后续查询范围证据见 [#1737](https://github.com/arcships/dim/pull/17 | 所有者 | 设计/实现入口 | 已有模型与尚待闭合的前提 | | --- | --- | --- | -| Wait | `plugins/Wait.md`;`wait.rs::rebuild` | `RecoveryBoundary/WaitRuntime`:只恢复 open-turn,丢弃通知/旧等待;固定 cut 与动态 consume 由 B/C 提供 | +| WaitBranch | `plugins/WaitBranch.md`;`wait.rs::rebuild` | `RecoveryBoundary/WaitRuntime`:只恢复 open-turn,丢弃通知/旧等待;固定 cut 与动态 consume 由 B/C 提供 | | InputQueue | `plugins/InputQueue.md`;`input_queue/recovery.rs::rebuild` | `InputRecovery/InputOrdering`:成员、首个控制决定、handover/turn;先等 committed cut 发布再查询,不能只做 start-minus-end | | Approval、ToolExecutor、ModelProvider、ContextPreparation、Loop | [逐项分析 §2–8](timeline-capability-analysis.md#2-approval) 中链接的 owner 页与 rebuild/恢复查询 | `RecoverySelection` 仅适用于对应未结算身份子问题;effects、控制事件、旧 request/turn 及结算次序仍依赖各业务模型,D 不可只复用集合公式 | | Prompt、ToolBinding、ContextUsage | [逐项分析 §9–11](timeline-capability-analysis.md#9-prompt) 中链接的采用、projection/checkpoint、usage 入口 | `PromptRetirement/ToolRetirement/ContextUsage/UsageIdentity`:持久业务身份与当前资源身份不同;B 的选择与 D 的采用交接待闭合 | diff --git a/docs/design/examples/wait-argument.md b/docs/design/examples/wait-argument.md index 26d7e4015b..ee0c3a8481 100644 --- a/docs/design/examples/wait-argument.md +++ b/docs/design/examples/wait-argument.md @@ -5,7 +5,7 @@ Issue: [#1615](https://github.com/arcships/dim/issues/1615). This is an optional worked argument, not a required design format for other Capabilities. See the [design guide](../capability-design-arguments.md) for the default approach. -The [Wait contract](../../architecture/rust-agent/plugins/Wait.md#waitbranch) remains authoritative. +The [WaitBranch contract](../plugins/WaitBranch.md) remains authoritative. No event, runtime state, persistence format or recovery behavior is proposed here. The executable model is [WaitRecovery.tla](wait-model/WaitRecovery.tla), with [finite configuration](wait-model/WaitRecovery.cfg). @@ -19,7 +19,7 @@ consume later events without losing or repeating their positions? | Facts have an immutable total sequence within one branch | [Time bus §1](../../architecture/rust-agent/time-bus.md#1-只认序号) | | A fixed-cutoff query observes that prefix, including the permitted publishing tail; errors fail recovery rather than mean empty history | [Property query §2–3](../timeline-property-query.md) | | Subscribe holds live delivery while rebuilding; live delivery then resumes strictly above the returned cutoff in order | [Plugin contract §5.2](../plugin-contract.md#52-consuming-facts) | -| `turn/start` sets open; `turn/end` clears it; other facts do not change it | [WaitBranch](../../architecture/rust-agent/plugins/Wait.md#waitbranch) | +| `turn/start` sets open; `turn/end` clears it; other facts do not change it | [wait.rs](../../../crates/dim-agent-capabilities/src/wait.rs) `consume`; target [WaitBranch](../plugins/WaitBranch.md) | | Reload restores open-turn status, not old arrival notifications | Same owner contract; no claim that pre-reload wait outcomes are reproduced | The model treats append as an eligible immutable fact, abstracting storage admission/publication diff --git a/docs/design/examples/wait-contract-experiment.md b/docs/design/examples/wait-contract-experiment.md index 8746c727e5..1dd175603d 100644 --- a/docs/design/examples/wait-contract-experiment.md +++ b/docs/design/examples/wait-contract-experiment.md @@ -3,7 +3,7 @@ Scope: connect Wait's Timeline obligations to observable implementation behavior. Issue: [#1615](https://github.com/arcships/dim/issues/1615). -The [Wait owner document](../../architecture/rust-agent/plugins/Wait.md) remains the contract. +The [WaitBranch contract](../plugins/WaitBranch.md) remains the contract; the [Wait plugin page](../../architecture/rust-agent/plugins/Wait.md) describes the current implementation. The [usage-context review](wait-usage-context.md) grounds the environment in actual callers, producers and complete flows, and distinguishes broader test traces from reachable product traces. This extends the [recovery argument](wait-argument.md) with a coverage inventory and a concrete @@ -18,7 +18,7 @@ implementation experiment. It does not make the Boolean projection a complete Wa | A task-specific call returns a matching task; a consumed arrival cannot be returned again | Wait tool and service contract | Notification argument; matching calls followed by draining calls | | Recovery uses the last boundary and connects to later consumption | WaitBranch plus Dispatcher/query contracts | Existing P1–P4 and TLC model; real queries held across later boundary/arrival writes | | Steer takes priority among currently pending arrivals, then the first matching task | Current `Wait::take` behavior, also referencing TS `takeMatchingInput` in its source | Explicit experimental selection policy below; not a new cross-plugin rule or a priority over future arrivals | -| One wait per branch; caller cancellation/drop releases the slot | Wait service contract | Existing concurrency/stop flow; the [usage-context experiment](wait-usage-context.md#4-corrections-to-model-scope) identifies missing generation cancellation as a violation of the existing reload protocol | +| One wait per line; caller cancellation releases the slot, a dropped native future releases it, and a bridge caller must cancel before abandoning its reply | [WaitBranch contract](../plugins/WaitBranch.md) | Existing concurrency/stop flow; the [usage-context experiment](wait-usage-context.md#4-corrections-to-model-scope) identifies missing generation cancellation as a violation of the existing reload protocol | | Timeout bounds, error text and tool result format | Wait tool contract | Existing timeout-boundary flow; no mathematical timing guarantee here | | Exact winner of simultaneous timeout, cancellation and arrival | No total priority specified by the owner contract | Do not infer one from a sequential experiment; an asynchronous model must permit the contracted outcomes | | External task execution and cancellation | BackgroundExec or the corresponding task owner | Dependency on its notification contract; outside Wait's proof | diff --git a/docs/design/examples/wait-usage-context.md b/docs/design/examples/wait-usage-context.md index 616f00b11a..f3abf30448 100644 --- a/docs/design/examples/wait-usage-context.md +++ b/docs/design/examples/wait-usage-context.md @@ -37,10 +37,10 @@ Wait is neither a durable inbox nor a join operation for the external process. | --- | --- | --- | | Which profile actually installs Wait? | [defaults.rs](../../../crates/dim-agent-capabilities/src/defaults.rs), `install_local_execution`; [workspace_tools/mod.rs](../../../crates/dim-agent-capabilities/src/workspace_tools/mod.rs), `install` | Local execution installs Wait and BackgroundExec. Do not infer a global assembly from a shared event type | | Who calls the tool? | [wait.rs](../../../crates/dim-agent-capabilities/src/wait.rs), `WaitPlugin`, `WaitTool::run`; [tool_executor.rs](../../../crates/dim-agent-capabilities/src/tool_executor.rs), `execute` | The selected tool handler receives a branch/turn context and caller cancellation; the task id comes from the model's call, not a Wait-owned task table | -| Is the tool the only entry? | Wait's public service and the [owner's data face](../../architecture/rust-agent/plugins/Wait.md#data-face) | Other plugins can call the service. Tool timeout limits cannot be assumed for every service caller; bridge callers must signal cancellation before abandoning the reply | +| Is the tool the only entry? | Wait's public service and the [owner's contract](../plugins/WaitBranch.md) | Other plugins can call the service. Tool timeout limits cannot be assumed for every service caller; bridge callers must signal cancellation before abandoning the reply | | What produces wake facts? | [background.rs](../../../crates/dim-agent-capabilities/src/workspace_tools/background.rs), `ended`, `wake`, `wake_input`, `wakes` | A successful notification append follows the terminal fact. Completed/failed tasks can wake; cancelled tasks do not. Branch closing suppresses new wakes. Posting can fail, so a terminal is not by itself a delivered notification | | Are these producers exclusive? | [shell_session.rs](../../../crates/dim-agent-capabilities/src/shell_session.rs), `settle`, also uses `wake_input`; `install_minimal_execution` in defaults | There is another producer of the same format in a different profile. That installer does not itself install Wait. Shared format is evidence of compatibility, not proof that the two profiles co-install all consumers | -| What happens when there is no open turn? | [input_queue.rs](../../../crates/dim-agent-capabilities/src/input_queue.rs), `input`, `release`; [agent_loop.rs](../../../crates/dim-agent-capabilities/src/agent_loop.rs), `driven`, `try_start` | A steer can become applied input and start a new turn. Its absence from Wait's pending state is intentional | +| What happens when there is no open turn? | [input_queue.rs](../../../crates/dim-agent-capabilities/src/input_queue.rs), `input`, `release`; [agent_loop.rs](../../../crates/dim-agent-capabilities/src/agent_loop.rs), `driven`, `try_start` | A steer can become applied input and start a new turn. The current service parks without accepting an arrival; the target answers `NoTurn` instead ([WaitBranch contract](../plugins/WaitBranch.md)) | | Can turns occur in arbitrary order? | AgentLoop's `try_start` and `consume` handling of `TurnStart`/`TurnEnd` | The real Loop checks turn identity and phase. Arbitrary repeated starts/ends in the isolated experiment are a broader input space, not reachable product traces | | Who cancels an active wait? | ToolExecutor's `StopInterrupt` handling and generation token; Wait's `arrival`; [host.rs](../../../crates/dim-agent-capabilities/src/host.rs), `call_until_cancelled` | Wait does not subscribe to stop events; the caller propagates cancellation. Cancelling this wait does not imply cancelling the background command | | Does reload reconnect an existing call? | WaitTool resolves an `Arc` per call; WaitBranch installs a fresh service and subscription; owner contract says futures are caller-owned | The current recovery model omits active old calls. The lifecycle contract requires settlement; caller ownership of the future does not exempt the service generation from ending its work | diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 206ed6d609..b9f350ca07 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -8,6 +8,7 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Plugin | Process part | Session part | Branch part | Phase / issue | | --- | --- | --- | --- | --- | +| [WaitBranch](WaitBranch.md) | — | — | arrivals, the one wait slot and the admitted-wait read | #2027 | | [Migration](Migration.md) | on-demand import tasks, source mappings, progress and retry records; unloaded after settlement | — | — | [Delivery plan](../../plan/analysis/legacy-migration.md) | | [Provider management](../appserver/provider-management.md) | existing Provider: configuration, catalogs, client preferences and management methods | — | — | #329 | | [Questions](Questions.md) | — | `ask_user` tool, `session.question.respond`, waiters of running `ask_user` calls; no events | — | M2; #262 | diff --git a/docs/design/plugins/WaitBranch.md b/docs/design/plugins/WaitBranch.md new file mode 100644 index 0000000000..1c95d49fd5 --- /dev/null +++ b/docs/design/plugins/WaitBranch.md @@ -0,0 +1,254 @@ +# WaitBranch + +Scope: branch. Issue: #2027. + +WaitBranch owns one line's wake-ups: the steers and background-task notices released on the line during an open turn that the model has not read yet, and the one wait a caller may park on them. The `wait` tool is the Wait owner's Session part (#2026) and registers with `toolRegistry`; this document is the branch part's target contract, and the current implementation is described in the [Wait plugin page](../../architecture/rust-agent/plugins/Wait.md). The division is: the Wait document (the tool's owner, #2026) owns the tool declaration, its model-facing texts and the tool-result settlement, and registers no arrival table and no `wait` or `state` operation; the arrival table, the single slot and the two operations are this contract's. + +## Use and scope: responsibility split + +WaitBranch owns: + +- **Arrivals.** The inputs released on the line during an open turn: a Steer, and a background task's tagged notice. An input the model has already read, or one deleted before it read, no longer counts. The arrivals and the notices the model read are per turn and `turn/end` clears both. The read-notice record is separate from the arrival table: a tagged notice released as the turn's opening input never enters the arrivals, and reading it still records its task. +- **The open-turn admission.** A wait is admitted only while the line's turn is open, because the input that opens a turn is released before `turn/start`; a call while it is closed answers `NoTurn`. +- **The wait slot.** One wait per line; a second concurrent wait is refused. +- **The admitted wait's state.** One read of the line's admitted wait: whether one runs, when it was admitted, and the task it names. +- **The wait call's lifetime.** A caller-owned call bound to the owner's generation: the caller ends it with its cancellation, and the owner ends it at its close, a turn end or a reload; the next generation admits a wait without answering `AlreadyWaiting` for one that ended. The `wait` tool's call is ended by ToolExecutor's cancellation before Loop writes `turn/end`; a caller that outlives the turn, a Session part or a bridge caller, is ended by the owner at `turn/end`. +- **The timeout.** The caller's bound on this wait, not on the task it waits for. + +Callers keep as business: + +- Which task a caller waits for, and what to do after a wake-up: the tool and its model-facing texts. +- Which inputs are sent to the line and which mode and tag they carry: the operator entry and a client's Steer, the `branch` tool's messages between lines ([timeline_tree.rs](../../../crates/dim-agent-capabilities/src/timeline_tree.rs)), EventHub's deliveries ([publish.rs](../../../crates/dim-event-hub/src/publish.rs)), and a background task's notice ([background.rs](../../../crates/dim-agent-capabilities/src/workspace_tools/background.rs)). +- The turn's run: Loop. +- What a client shows for a wait it reads: its own text and layout, from `state` and the tool result ([#1659](https://github.com/arcships/dim/issues/1659)); the App Server reads `state` and answers the client through that client-protocol addition. + +| Requirement (caller) | Can callers compose it from the operations below without breaking WaitBranch's invariants? | Handling | +| --- | --- | --- | +| The `wait` tool parks until a matching arrival, a Steer, the timeout or its own cancellation, and answers `AlreadyNotified` for a task whose notice the model already read | No: the arrival set, the read-notice record, the single slot and the generation's settlement are the owner's, and a caller polling the Timeline would read state it does not own | `wait` | +| A caller wants the task that finished | Yes: the reply names the task id and the time waited | Business | +| A client reads whether the model already read a notice | Yes: the history read answers the consumed input | Business | +| The CLI shows a named wait while the call runs ([#1659](https://github.com/arcships/dim/issues/1659)) | No: the admission time and the admitted task are the owner's, and a client watching a tool call would claim a wait the owner never admitted | `state` | + +An operation exists only where the row says No. `state` is the positive admission signal: the App Server reads the line's admitted wait by `(sessionId, branchId)` ([ADR 027](../../adr/027-cross-scope-access-by-id.md) D1) and answers the CLI through the method or notice the Rpc owner defines ([#1659](https://github.com/arcships/dim/issues/1659)), a client change that needs a maintainer decision. A batch such as `[exec, wait]` claims no wait before that read answers one. At most one wait is admitted per line, so the reply needs no call id. + +## Caller example + +The `wait` tool, on the calling line, reaches this owner by line id and passes the optional task and its own cancellation. + +```rust +let cancelled: CancelledFn = Arc::new(move || { + let cancel = cancel.clone(); + Box::pin(async move { + cancel.cancelled().await; + Ok(()) + }) +}); +let result = line_owner::(line)? + .wait(WaitRequest { task_id, timeout_ms }, cancelled) + .await; +let content = match result { + Ok(WaitResult::Notification { task_ids, .. }) => { + format!("wait ended: notification ({})", task_ids.join(", ")) + } + Ok(WaitResult::UserSteer { .. }) => "wait ended: steer".into(), + Ok(WaitResult::AlreadyNotified { task_ids, .. }) => already(&task_ids), + Ok(WaitResult::Timeout { .. }) => "wait ended: timeout".into(), + Ok(WaitResult::Interrupted { .. }) => "wait ended: interrupted".into(), + Err(error) => return settle(error), +}; +``` + +`settle` is the tool's own wording: a refusal text for `AlreadyWaiting` and `NoTurn`, and the reload settlement for `Reloading`. + +The App Server reads the same operation for a client: it resolves the line by `(sessionId, branchId)` ([ADR 027](../../adr/027-cross-scope-access-by-id.md) D1) and calls `state()`, whose reply is `WaitState {waiting, startedAt?, taskId?}`. + +## Own contract + +### Dependencies + +| Owner | Operation | Use | +| --- | --- | --- | +| BranchScope | `dispatcher`, `timeline` | The line's facts in order and its committed head. | + +The `wait` tool is a caller reached by line id ([ADR 027](../../adr/027-cross-scope-access-by-id.md) D1), not a dependency: WaitBranch injects nothing of the Session's. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `wait` | Wait for the next matching arrival, a Steer, the timeout or the caller's cancellation; a wait naming a task also answers `AlreadyNotified` when the model already read that notice | `{taskId?, timeoutMs}` | `WaitResult`: `Notification {taskIds, waitedMs}`, `UserSteer {waitedMs}`, `AlreadyNotified {taskIds, waitedMs}`, `Timeout {waitedMs}` or `Interrupted {waitedMs}` | The caller's cancel ends the wait as `Interrupted` and releases the slot; a dropped native future releases it too | `AlreadyWaiting` (another wait holds the line's slot), `NoTurn` (no turn is open), `Unavailable` (the committed head cannot be read), `Reloading` (an accepted wait on a closing line or a reloading part; a new call on a closing line is answered by the route as line-gone) | +| `state` | Read the line's admitted wait: whether one runs, its admission time and the task it names | `{}` | `WaitState {waiting, startedAt?, taskId?}`; `startedAt` is the admission time in milliseconds since the Unix epoch, and both fields are present only when `waiting` is true | None: the read does not wait | `Unavailable` (the committed head cannot be read), `Reloading` (a call that lands on an ended generation; a closing line is answered by the by-id route as line-gone before the read reaches the owner) | + +`timeoutMs` is this wait's bound, and the tool holds its model-facing range of 1 through 300,000 milliseconds; the owner uses the timeout the call carries and has no policy on how long a caller may park, so it bounds no task execution. A wait is admitted only while the turn is open, so a call while it is closed answers `NoTurn`; the open-turn state is the one the owner folded from dispatched facts, rebuilt from the committed head and its permitted publishing tail when a generation starts, and confirmed there before a call is decided, so a committed boundary that has not been dispatched yet is not missed. The confirmation is a Timeline read: a failed read answers `Unavailable` and changes nothing. The read only refreshes the folded value; the generation, the refreshed open-turn state and the slot are then checked under one lock, so a `turn/end` that dispatches after the read still ends an admitted call. `state` answers from the same confirmed value, so a committed `turn/end` that has not been dispatched yet makes it answer `waiting: false`. Only an input released during an open turn is an arrival, and the input that opened the turn is never one, because it is released before `turn/start`. A wait naming a task answers `AlreadyNotified` when the model read that task's notice in this turn and no eligible arrival is pending: a pending Steer, or a pending notice the caller accepts, is taken first, and the notice it read is not waited for again. The read-notice record covers every tagged notice the model read in this turn, including one released as the turn's opening input. `UserSteer` names any Steer input, from the operator, another line or EventHub, not only one the user typed. A turn end ends a wait that outlives the turn with `Interrupted` and releases its slot, and the arrivals and read notices from that turn are cleared; the `wait` tool's call is ended by ToolExecutor's cancellation before Loop writes `turn/end`, so the tool writes no result for a turn that already ended. A reload ends an accepted wait with `Reloading` instead of replaying an arrival: a cancelled background task emits no wake, and an arrival from the previous generation is not a wake the model can still act on. The tool settles that call as a reload, and the turn fails without a continuation. `state` reads the same slot and arrival set without taking the slot: it answers the admitted wait or that none runs, so a client never infers a wait from a tool call that the owner has not admitted. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `AlreadyWaiting` | `wait` | One wait runs on the line; report that a wait is already running | +| `NoTurn` | `wait` | No turn is open on the line; the tool reports the refusal and a call made in a turn is admitted | +| `Unavailable` | `wait`, `state` | The committed head cannot be read, so nothing was decided; the tool reports a tool error and the turn continues, and a `state` caller reports that it cannot confirm and reads again | +| `Reloading` | `wait`, `state` | The tool settles its call as a reload and the turn fails; a `state` caller reports that no wait runs and reads again after the reload; a `wait` or `state` call on a closing line gets the route's line-gone and stops | + +The `AlreadyWaiting` message keeps the tool's existing text, which names the Session; the slot is one per line. The next steps above are the `wait` caller's, which is the tool; a Session part that calls `wait` reports the same refusal to its own caller and retries when the condition changes. The App Server's `state` read has only `Unavailable` and `Reloading` to report. + +### Flows + +| Operation | Normal path | No turn is open | Caller cancels or unloads | Turn ends | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | --- | +| `wait` | Confirm the open turn at the committed head, answering `Unavailable` if the read fails; admit under the slot, register the call in the generation's tracker, wait for an arrival, the timeout or cancellation, release the slot, answer | Answer `NoTurn` and hold no slot | The cancellation ends the wait as `Interrupted`; the slot is released before the tracking token; a bridge caller must cancel, and dropping its reply alone does not release the slot | The owner ends a wait that outlives the turn with `Interrupted` and releases its slot; the arrivals and the notices read in that turn are cleared. The `wait` tool's call is ended by ToolExecutor's cancellation before Loop writes `turn/end`, so its result belongs to that turn | Admission stops; an accepted wait on a closing line ends `Reloading`, and a reload ends the generation the same way and waits for active slots; a new call on a closing line is answered by the route as line-gone; a new generation starts with no old arrivals | WaitBranch: the slot, the arrivals, the `Interrupted` turn end and the `Reloading` generation end; the Wait tool (#2026): the result text; ToolExecutor: the tool-result fact | +| `state` | Confirm the open turn at the committed head, answering `Unavailable` if the read fails, then answer `waiting: false` for a confirmed closed turn, or the line's admitted wait with its start and task, or that none runs | Answer `waiting: false`, because no wait is admitted while the turn is closed | Nothing to cancel: the read does not wait and holds no slot | The admitted wait ends at the turn end, so a read afterwards answers none | A reload ends the generation, so a call that lands on it answers `Reloading` and the next generation answers none; a closing line ends the part and the route reports the line gone | WaitBranch | + +Admission checks the generation, then the confirmed turn, then the slot: `Reloading` when the generation has ended, `Unavailable` when the committed head cannot be read, `NoTurn` when the turn is closed, `AlreadyWaiting` when another call holds the slot. + +## Client-visible changes + +The `wait` data face takes one request object and omits `taskId` instead of passing `null`; no existing client-protocol message changes, the thrown error's `data` stays undefined, and the tool answers the new `NoTurn` and `Unavailable` codes with texts of its own. The `state` read and its `WaitState` reply are additive, and the client path for it is the addition recorded below. + +The named-wait display's client path is the App Server's: it reads `state` by `(sessionId, branchId)` and answers a protocol v4 client through a method or notice the Rpc owner defines for [#1659](https://github.com/arcships/dim/issues/1659). That client-protocol addition is a maintainer decision recorded in [cli-current-activity.md](../cli-current-activity.md), not a change of this face. + +| Change | Reason | Affected | Migration | +| --- | --- | --- | --- | +| `wait(taskId, timeoutMs, cancelled)` becomes `wait(request, cancelled)`, where the request is `WaitRequest {taskId?, timeoutMs}` | the face carries its parameters as one request value, so the optional task and the timeout serialize together | a TypeScript caller of `wait` | pass the two fields as one object, omit `taskId` instead of passing `null`, and keep the cancellation callback | +| `state` is a new read | a client showing a named wait needs a positive admission signal and the authoritative start | a caller that shows a running wait | new call: `state()` answers `{waiting, startedAt?, taskId?}`; additive, so no existing caller changes | +| the error kinds add `NoTurn` and `Unavailable`; `AlreadyWaiting` and `Reloading` keep their codes and meanings | the opening input of a turn is released before `turn/start`, and confirming the committed head can fail | a caller matching a thrown code | report `NoTurn` instead of parking and call again during a turn; report `Unavailable` and retry, because nothing was decided | + +## Exceptions with reasons + +None: the owner hands out no object, and every call that is polled ends in a value or one of its errors. + +## Supersedes + +- `docs/design/service-faces.md` section 3.4: the `wait` row's operations, now `state()` and `wait(request, cancelled)`, and its link to the Wait plugin page's data face; the row names the operations and links this contract. +- `docs/design/cli-current-activity.md` section "Owner requirement for named waits": the open questions about a positive admission signal and an authoritative start are answered by `state` read by the App Server; the client path is the separate maintainer decision recorded there. +- `docs/design/examples/wait-contract-experiment.md`, `docs/design/examples/wait-argument.md`, `docs/design/examples/wait-usage-context.md` and `docs/design/research/remote-plugins.md`: the sentences and table cells that name the Wait plugin page as the contract, the owner's data face or the `wait` service's target now name this contract, and the cells that stated a dropped reply releases the slot or that a wait can be called while no turn is open now state this contract's rule. +- `docs/design/timeline-branches.md` and `docs/zh/design/timeline-branches.md`: the input-mode cells and the opener's waiting sentence that name `wait` now link this contract; `docs/design/examples/capability-models/coverage-audit.md` states this contract's `wait` call shape. +- `docs/design/capability-document-review.md`, `docs/design/examples/owner-handoff-verification.md`, `docs/design/examples/timeline-capability-analysis.md` and `docs/design/examples/timeline-contract-coverage.md`: the rows and lists that name the Wait plugin page as the owner design or recovery contract now name this contract; the page stays as the current implementation. +- `docs/architecture/rust-agent/plugins/Wait.md` § Data face: the face it prints is the current implementation, and the target it names is this contract. + +No other design document defines this owner's surface. The Wait document (its owner is #2026) keeps the tool declaration, its texts and the tool-result settlement, and the [Wait plugin page](../../architecture/rust-agent/plugins/Wait.md) describes the current implementation. + +## Verification + +- A Steer or a tagged notice released during an open turn ends a wait; an input the model read first does not end a later wait; the input that opened the turn never ends one. +- `wait` with a task id wakes on that task's notice or on any Steer, so a Steer ends it while the named task is unfinished. +- Without a task id, `wait` wakes on any arrival: a Steer or any task's notice. +- A wait while no turn is open answers `NoTurn` and holds no slot; the line admits a wait once its turn opens. +- A second concurrent wait answers `AlreadyWaiting`; the first releases its slot on cancellation, on timeout and on drop. +- `turn/end` ends a caller that outlives the turn with `Interrupted` and releases its slot; the arrivals and the notices read in that turn are not carried into the next turn. The `wait` tool's call is ended by its cancellation before the turn ends and writes no result after it. +- A wait naming a task answers `AlreadyNotified` when the model read that task's notice in this turn and no eligible arrival is pending: a pending Steer answers `UserSteer` even then, and a notice the model read as the turn's opening input answers `AlreadyNotified`. +- A `wait` after a committed `turn/start` that is not yet dispatched is admitted, and one after a committed `turn/end` answers `NoTurn`; `state` answers `waiting: false` in that window. +- A failed committed-head read answers `Unavailable` and decides nothing: the tool reports a tool error and the turn continues, and a `state` caller retries on its next read. +- A `turn/end` that dispatches between the confirmation and the lock makes that call answer `NoTurn` because it is not admitted; a call admitted before the dispatch ends with `Interrupted`. +- A wait answers `Timeout` when its bound elapses, and `Interrupted` when the caller's cancellation ends it. +- `state` answers `waiting: true` with the admission time and, when the wait names one, the task id while a wait is admitted, and `waiting: false` otherwise; the read takes no slot and ends no wait. +- `state` answers `Reloading` for an ended generation; the next generation answers that no wait runs. A batch such as `[exec, wait]` claims no wait before `state` answers one. +- A reload ends an accepted wait with `Reloading`; the tool ends the call through the existing reload settlement, and the turn fails without continuing. +- A closing line ends an accepted wait with `Reloading`; a `wait` or `state` call on a closing line is answered by the by-id route as line-gone. +- An arrival from before a reload is not replayed; the new generation rebuilds only whether a turn is open. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One branch part and a Capability: it folds the line's input and turn facts; it writes no fact of its own. | +| §2 scopes | Branch: arrivals, the slot and the admitted wait belong to one line. A Session part calls `wait` by line id, and the App Server reads `state` by `(sessionId, branchId)`. | +| §3 orthogonality | No other owner's state is read; the arrivals are the line's facts. | +| §4 rule 1 | No command event: the wait answers its caller and writes nothing. | +| §4 rule 2 | No handover. | +| §4 rule 3 | No `before` callback: the handler folds the line's input and turn facts and returns, and the wait is the caller's call rather than a write hook. | +| §4 rule 4 | The Timeline, Dispatcher, `before` and batches gain nothing: the arrival kinds and the wait's meaning stay in this part, and no core module special-cases it. | +| §4 rule 5 | No batch. | +| §4 rule 6 | The wait adds no context; its reply is a tool result. | +| §4 rule 7 | Callers use `wait` and `state`; the owner folds public facts. | +| §4 rule 8 | No infrastructure change of its own; the `wait` tool's access by line id and the App Server's by `(sessionId, branchId)` are [ADR 027](../../adr/027-cross-scope-access-by-id.md) D1 and [#2127](https://github.com/arcships/dim/issues/2127). | +| §4 rule 9 | No Timeline fact. | +| §7.1 design questions | Resources: the arrivals are values folded from the line's facts, the slot and the admitted wait are the live call state, and no resource outlives a call. Lifecycle: a call ends with an arrival, `AlreadyNotified`, the timeout, the caller's cancellation or, for a caller that outlives the turn, the turn's end; the owner ends its generation's calls with `Reloading`, the Wait tool writes the result text and ToolExecutor the tool-result fact. Callers: two operations, `state` and `wait`, with four errors on `wait` and two on `state`; the CLI's running-wait display reads `state`. | +| §7.2 every call lands on one operation | The `wait` tool calls `wait`, the App Server reads `state` by `(sessionId, branchId)`, and a cross-language caller calls the same operations; no other entry exists. | +| §7.2 only values, views and callbacks cross | `state` is a read-only view, the request and the reply are data, and `cancelled` is the call's own callback. | +| §7.2 no relay, no peek | The owner returns no other owner's data and reads no other owner's state: the arrivals and the live open-turn state come from the dispatcher, and open-turn status is restored from the committed head and its permitted publishing tail, confirmed there before each admission. | +| §7.2 one face, no forwarding | Two operations on the `Wait` type, `state` and `wait`; the private `arrival` path the tool used is removed. | +| §7.2 data only on the public face | The request and the reply are data, the error is a code and a message, and no handle or channel crosses. | +| §7.2 no caller business concepts | The request carries a task id and a timeout; the model-facing texts, the task policy and the turn stay with the callers. | +| §7.2 no owner-internal mechanism pushed out | The arrival set, the slot, the generation tracker and the `Reloading` decision stay inside; the admission time leaves only as the value `state` publishes. The caller passes its cancellation or reads a value, and the tool owns the model-facing text while ToolExecutor writes the tool-result fact. | +| §7.2 cross-scope lifecycle | A Session part calls `wait` by line id and the App Server reads `state` by `(sessionId, branchId)` (ADR 027 D1). A call belongs to the generation that admitted it: the owner ends it `Reloading` when that generation ends and `Interrupted` at a turn end for a caller that outlives the turn, the tool and ToolExecutor settle the ended call, and a caller that abandons a native call releases the slot on drop. | +| §7.2 one change | The request object, the `state` read, every caller's migration and the removal of `arrival` land in one change. | +| ADR 002 D1 | Branch: the arrivals belong to one line's turn. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | +| ADR 002 D3 | Dependencies point outward: the owner injects the branch's dispatcher and timeline, and no core part depends on it; the Session tool part consumes it. | +| ADR 002 D4 | No configuration of its own: the timeout is the call's parameter, not a setting. | +| ADR 002 D5 | The contract is language-neutral — a task id, a timeout, a result kind, the task ids and an admission time; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. The access by id is [ADR 027](../../adr/027-cross-scope-access-by-id.md) D1, tracked by [#2127](https://github.com/arcships/dim/issues/2127); the client path is the Rpc owner's addition, tracked by [#1659](https://github.com/arcships/dim/issues/1659). + +## Binding appendix + +The service is marked on the `Wait` type; the wire name stays `wait`. + +```rust +use crate::host::CancelledFn; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WaitRequest { + #[serde(skip_serializing_if = "Option::is_none")] + pub task_id: Option, + pub timeout_ms: u64, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WaitState { + pub waiting: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub started_at: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub task_id: Option, +} + +#[derive(Debug, Clone, serde::Serialize)] +#[serde( + tag = "reason", + rename_all = "snake_case", + rename_all_fields = "camelCase" +)] +pub enum WaitResult { + Notification { + task_ids: Vec, + waited_ms: u64, + }, + UserSteer { + waited_ms: u64, + }, + AlreadyNotified { + task_ids: Vec, + waited_ms: u64, + }, + Timeout { + waited_ms: u64, + }, + Interrupted { + waited_ms: u64, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum WaitCallError { + #[error("wait is already running in this session.")] + AlreadyWaiting, + #[error("no turn is open")] + NoTurn, + #[error("the committed head cannot be read")] + Unavailable, + #[error("capability reloading")] + Reloading, +} + +#[rutis::service] +impl Wait { + pub async fn state(&self) -> Result { /* .. */ } + pub async fn wait(&self, request: WaitRequest, cancelled: CancelledFn) -> Result { /* .. */ } +} +``` diff --git a/docs/design/research/remote-plugins.md b/docs/design/research/remote-plugins.md index 4551cb3328..26b93d966c 100644 --- a/docs/design/research/remote-plugins.md +++ b/docs/design/research/remote-plugins.md @@ -360,7 +360,7 @@ leaf 是 rutis 里对端的一种角色,不是实例: | 已经是 leaf | WorkflowSession | 本来就是 TypeScript,`workflowRuns` 是 `call: async` 数据面;把 runtime 连接换成远程即可 | | 纯逻辑 leaf(今天) | Questions | inject 可借,只用 dispatched 方法,且不提供宿主按类型查的服务;移植到 TS/Python 或 Rust leaf host | | 用了 skipped/私有 API,需数据面 | Goal(`Changes` 捕获、`TreeCommands::get`)、Recall(`get`、`branch.sequence/query`)、BranchTool(`get`、`branch.service::()`)、TreeTimeline(私有 tree)、SessionBroadcast(内部状态)、SessionBroadcastEnd(`SessionIdentity.unloading` 是 `#[serde(skip)]`) | 先给 `tree.info`/`tree.query`、`branchLine`、Goal 的 change 写入、SessionBroadcastEnd 的 idle release 补数据面,或把这些部件留在宿主;GoalBranch 的 `settingsService` 换现有的 `settings` | -| 提供类型服务,需操作面 | Wait(`wait` 返回 `WaitResult`、收 `CancellationToken`)、BranchLine(`branchLine`)、InputQueue(`inputQueue`)、InputMethods(`submitChecks`)、PrepareModelHost(`prepareModelHost`) | 宿主用 `branch.service::()` 或 `Key` 查;先加操作面/数据面,或改由宿主自己跑 | +| 提供类型服务,需操作面 | Wait(`wait` 收按引用传递的取消回调、返回 serde 的 `WaitResult`;目标面见 [WaitBranch](../plugins/WaitBranch.md))、BranchLine(`branchLine`)、InputQueue(`inputQueue`)、InputMethods(`submitChecks`)、PrepareModelHost(`prepareModelHost`) | 宿主用 `branch.service::()` 或 `Key` 查;先加操作面/数据面,或改由宿主自己跑 | | 换现有数据面后可 leaf | SessionTitle(`settingsService` → `settings`,`sessionStore` → `sessionMetadata`,`auxiliaryModelHost` → `auxiliaryModel`)、SchedulerSession(`scheduleJobs`、`wakeups`)、Attachments(`sessionFilesHost`,目标名 `sessionFiles`)、PromptSuggestion(`modelHost`、`providerConnectionResolver`、`promptSuggestionSettingsHost`) | 把 Rust 类型键的注入换成已有数据面的名字;没有对应数据面的先加 | | 资源 leaf | HostPlatform、FileStorage、SqliteStorage、WorkspaceTools、ShellSession、SkillsCatalog、Mcp、Modality、ExternalAgent、PluginManager、RuntimeManager | 在资源所在机器上跑,本地 I/O,对外提供数据服务;现有 Rust 实现放进 Rust leaf host 复用 | | 不是 leaf | SessionScope、BranchScope、mounter、SessionLoader、Rpc、Transport、ServerControl、Connection | 它们定义实例和入口,是 leaf 被挂载、被服务的一方 | @@ -524,7 +524,7 @@ flowchart TB | Goal | `GoalSession` 捕获 `Changes`、调 `TreeCommands::get`(skip);`GoalBranch` 要 `settingsService` | `GoalBranch` 换现有的 `settings`;给 change 写入、`tree.info`/`tree.query` 补数据面,或留宿主 | | Recall、BranchTool | `TreeCommands::get`、`branch.sequence/query`、`branch.service::()` | 补 `tree.info`/`tree.query` 和 `branchLine` 数据面,或留宿主 | | TreeTimeline、SessionBroadcast | 私有 tree / 内部状态 | 留宿主,或先设计数据面 | -| Wait、BranchLine、InputQueue、InputMethods、PrepareModelHost | 提供 `wait`/`branchLine`/`inputQueue`/`submitChecks`/`prepareModelHost`;Wait 收 `CancellationToken`、返回 `WaitResult` | 先加操作面/数据面,或留宿主 | +| Wait、BranchLine、InputQueue、InputMethods、PrepareModelHost | 提供 `wait`/`branchLine`/`inputQueue`/`submitChecks`/`prepareModelHost`;Wait 收取消回调、返回 serde 的 `WaitResult`(目标面见 [WaitBranch](../plugins/WaitBranch.md)) | 先加操作面/数据面,或留宿主 | | SchedulerSession | `scheduleJobs`、`wakeups` | 加两个数据面 | | PromptSuggestion | `modelHost`、`providerConnectionResolver`、`promptSuggestionSettingsHost` | 换 `auxiliaryModel`,其余加数据面或留宿主 | | Attachments | `sessionFilesHost`(当前名) | 加数据面;目标名 `sessionFiles` | @@ -595,7 +595,7 @@ flowchart TB | 类型 | 名字 | 改法 | | --- | --- | --- | | 数据内容、未标记 | `executionSettingsHost`、`toolchainSourceHost`、`sessionFilesHost`、`historyRenderer`、`selectableModelsHost`、`auxiliaryModelHost`、`promptSuggestionSettingsHost`、`worktreeAssociations`、`listenAddresses`、`sessionClientsHost`、`hooksService`、`mcpService`、`skillsCatalog`、`uiExtensions`、`loader`、`agentIndex`、`collaborationDirectory`、`credentialVariablesHost`、`reservedMethods`、`agentConfig`、`collaborationConfig`、`skillsConfig`、`initialPromptConfiguration`、`promptRegistry`、`toolSourcesView`、`faultReporter`、`branchOpening`、`configurationPublisher`、`configureControl`、`fileReads` | 定义 serde 类型加 `#[rutis::service]`,catalog 标 `data`。带回调的(`submitChecks`、`uiExtensions` 的部分方法)回调按引用跨,但不能在锁里同步调用 | -| 操作服务 / 类型面 | `wait`、`branchLine`、`submitChecks`、`prepareModelHost` | 先设计操作面(`start`/`wait`/`result`)或留宿主;`wait` 收 `CancellationToken`、返回 `WaitResult`,不是 serde 数据 | +| 操作服务 / 类型面 | `wait`、`branchLine`、`submitChecks`、`prepareModelHost` | 先设计操作面(`start`/`wait`/`result`)或留宿主;`wait` 收取消回调、返回 serde 的 `WaitResult`(目标面见 [WaitBranch](../plugins/WaitBranch.md)) | | 对象→操作 | `hostPlatform`、`fileStorage`、`sqliteStorage`、`sessionStore`、`timelineStore`、`toolHost`、`sessionLoader`、`timelineFactory`、`mcpSession`、`collaborationSession`、`backgroundExec`、`approval`、`permission` | 发 id,拆成 `start`/`wait`/`kill`、`open`/`read`/`write`/`close`、`append`/`query`/`ack`、`decide`/`cancel`;实现留在所有者 | | 新接口直接按数据设计 | `execHost`、`fsHost`、`dbHost` | 资源 leaf 和远程 DB 不包旧对象,直接定义操作 | diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 0cf6cd6437..8052413897 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -139,12 +139,12 @@ Proposed target operations: [Resource and repository operations](contracts/resou | `approval` | `pending()`、`decide(requestId, decision)` | 待处理请求、批次准入 | | `permission` | `check(call, risk, cancelled)` | 预设、权限状态、advisor | | `inputQueue` | `submit(input)`、`withdraw(command)` | 排序、恢复、InputSnapshot | -| `wait` | `wait(taskId, timeoutMs, cancelled)` | 到达记录、单次等待槽 | +| `wait` | `state()`、`wait(request, cancelled)` | 到达记录、单次等待槽、已准入等待 | 形状与错误见所有者:[Permission](../architecture/rust-agent/plugins/Permission.md#permission-data-face)、 [Approval](../architecture/rust-agent/plugins/Permission.md#approval-data-face)、 [InputQueue](../architecture/rust-agent/plugins/InputQueue.md#data-face)、 -[Wait](../architecture/rust-agent/plugins/Wait.md#data-face) 与 +[WaitBranch](plugins/WaitBranch.md) 与 [toolHost](../architecture/rust-agent/tool-contributions.md#21-宿主工具的-toolhost-数据面)。 `inputQueue.withdraw` 只做普通撤回;Steer 必须走 `session.input.withdraw` 的校验与提交检查入口。 diff --git a/docs/design/timeline-branches.md b/docs/design/timeline-branches.md index f94037a38d..41ec901e75 100644 --- a/docs/design/timeline-branches.md +++ b/docs/design/timeline-branches.md @@ -135,8 +135,8 @@ A message is an `input/message` on the receiver's Timeline, written through `Tre | Mode | Effect on the receiver | When to use it | | --- | --- | --- | -| `append` (default) | Rides with the receiver's next model request. It never starts a turn and does not wake `wait` | Progress or context the receiver should have at its next step | -| `steer` | Enters the receiver's current turn at its next step, or starts a turn if the receiver is idle. It wakes `wait` | The receiver must act on it now, or the receiver is idle | +| `append` (default) | Rides with the receiver's next model request. It never starts a turn and does not wake `wait` ([WaitBranch](plugins/WaitBranch.md)) | Progress or context the receiver should have at its next step | +| `steer` | Enters the receiver's current turn at its next step, or starts a turn if the receiver is idle. It wakes `wait` ([WaitBranch](plugins/WaitBranch.md)) | The receiver must act on it now, or the receiver is idle | Queue is not exposed. The only Queue input one line gives another is the opening input. @@ -169,7 +169,7 @@ These are Collaboration's message modes and words (`append`, `steer`), with the - the line has a driving input pending. The second bullet keeps a line that has become the default branch from waking its opener every time the user talks to it there: it is answering the user, not reporting to its opener. A second move restores the notice without any write, because the rule is read from the current fact and not from a note. This way a line that stops without telling its opener never leaves the opener waiting on silence, and a line that already steered it does not notify it twice. The notice carries the turn's status (`completed`, `failed` or `cancelled`). -- **Waiting.** An opener waits for its lines with the existing `wait` tool. A steer message, an idle notice or an ended notice wakes it ([wait.rs](../../crates/dim-agent-capabilities/src/wait.rs)). +- **Waiting.** An opener waits for its lines with the existing `wait` tool. A steer message, an idle notice or an ended notice wakes it ([WaitBranch](plugins/WaitBranch.md)). ### 6.1 Resources and limits diff --git a/docs/zh/design/plugins/README.md b/docs/zh/design/plugins/README.md index 266a344e16..f75c5f738d 100644 --- a/docs/zh/design/plugins/README.md +++ b/docs/zh/design/plugins/README.md @@ -8,6 +8,7 @@ | 插件 | 进程部件 | Session 部件 | 分支部件 | 阶段 / issue | | --- | --- | --- | --- | --- | +| [WaitBranch](../../../design/plugins/WaitBranch.md) | — | — | 到达记录、单次等待槽与已准入等待的读 | #2027 | | [Migration](../../../design/plugins/Migration.md) | 按需加载的导入任务、来源映射、进度与重试记录;结算后卸载 | — | — | [实施计划](../../../plan/analysis/legacy-migration.md) | | [Provider 管理](../appserver/provider-management.md) | 现有 Provider:配置、目录、客户端偏好与管理方法 | — | — | #329 | | [Questions](Questions.md) | — | `ask_user` 工具、`session.question.respond`、运行中 `ask_user` 调用的等待者;没有事件 | — | M2;#262 | diff --git a/docs/zh/design/timeline-branches.md b/docs/zh/design/timeline-branches.md index 2bb166a04f..cb1f0c3445 100644 --- a/docs/zh/design/timeline-branches.md +++ b/docs/zh/design/timeline-branches.md @@ -119,8 +119,8 @@ BranchLine 注入 `B:Dispatcher`、`B:TimelineIdentity`、`B:BranchLifecycle` | 模式 | 对接收方的作用 | 何时用 | | --- | --- | --- | -| `append`(默认) | 随接收方下一次模型请求一起送达。它从不开启新的一轮,也不唤醒 `wait` | 接收方在下一步应该知道的进展或背景 | -| `steer` | 在接收方当前这一轮的下一步进入;接收方空闲时开启新的一轮。它会唤醒 `wait` | 接收方必须马上处理,或接收方处于空闲 | +| `append`(默认) | 随接收方下一次模型请求一起送达。它从不开启新的一轮,也不唤醒 `wait`([WaitBranch](../../design/plugins/WaitBranch.md)) | 接收方在下一步应该知道的进展或背景 | +| `steer` | 在接收方当前这一轮的下一步进入;接收方空闲时开启新的一轮。它会唤醒 `wait`([WaitBranch](../../design/plugins/WaitBranch.md)) | 接收方必须马上处理,或接收方处于空闲 | 不开放 Queue。一条线给另一条线的唯一 Queue 输入是开启输入。 @@ -153,7 +153,7 @@ BranchLine 注入 `B:Dispatcher`、`B:TimelineIdentity`、`B:BranchLifecycle` - 这条线还有待处理的驱动输入。 第二条让一条已经是默认分支的线不再每轮都去唤醒开它的那条线:用户在它上面说话时,它在回答用户,不是在向开它的那条线汇报。再切走一次就自动恢复通知,因为这个条件读的是当前事实,不是某条说明。这样,一条线一声不响地停下时,开它的那条线不会一直等下去;已经 steer 过开线方的线,也不会重复通知它。通知带这一轮的状态(`completed`、`failed` 或 `cancelled`)。 -- **等待。** 开线方用现有的 `wait` 工具等它开的线。steer 消息、空闲通知或结束通知都会唤醒它([wait.rs](../../../crates/dim-agent-capabilities/src/wait.rs))。 +- **等待。** 开线方用现有的 `wait` 工具等它开的线。steer 消息、空闲通知或结束通知都会唤醒它([WaitBranch](../../design/plugins/WaitBranch.md))。 ### 6.1 资源与限制