From 430373d83c47e11274620266732a945e4780f796 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 15:00:09 +0800 Subject: [PATCH 01/10] docs(design): target contracts for the Session registries and tools Refs #2026, Refs #2015. --- docs/design/plugins/Attachments.md | 155 ++++++++++++ docs/design/plugins/InputMethods.md | 182 ++++++++++++++ docs/design/plugins/PromptGuide.md | 172 ++++++++++++++ docs/design/plugins/PromptSources.md | 231 +++++++++++++++++- docs/design/plugins/PromptSuggestion.md | 140 ++++++++++- docs/design/plugins/Questions.md | 155 +++++++++++- docs/design/plugins/Recall.md | 113 ++++++++- docs/design/plugins/SessionMethods.md | 210 +++++++++++++++++ docs/design/plugins/ShellInput.md | 164 ++++++++++++- docs/design/plugins/ToolRegistry.md | 300 ++++++++++++++++++++++++ docs/design/plugins/Wait.md | 158 +++++++++++++ docs/design/plugins/WorkspaceTools.md | 205 ++++++++++++++++ 12 files changed, 2176 insertions(+), 9 deletions(-) create mode 100644 docs/design/plugins/InputMethods.md create mode 100644 docs/design/plugins/PromptGuide.md create mode 100644 docs/design/plugins/SessionMethods.md create mode 100644 docs/design/plugins/ToolRegistry.md create mode 100644 docs/design/plugins/Wait.md create mode 100644 docs/design/plugins/WorkspaceTools.md diff --git a/docs/design/plugins/Attachments.md b/docs/design/plugins/Attachments.md index 49dc5f52b5..ce15e2fa9b 100644 --- a/docs/design/plugins/Attachments.md +++ b/docs/design/plugins/Attachments.md @@ -1,5 +1,160 @@ # Attachments +Scope: session. Issue: #2026. + +Attachments owns the `attachment` methods: a client stores a large paste or imports a host file as a Session file and reads one back. The current implementation is in `crates/dim-agent-attachments/src/lib.rs`; the plugin page is [Attachments](../../architecture/rust-agent/plugins/Attachments.md). The Session file store is #2018's; this owner holds no state of its own. + +## Use and scope: responsibility split + +Attachments owns: + +- **The three methods.** `attachment.put`, `attachment.import` and `attachment.read`, their input rules and their reply shapes. +- **The content rules.** Empty text, the 10 MiB paste limit, the 16 MiB image limit and the image re-encoding that keeps a stored image acceptable. +- **The ownership check.** The Session id in the request must be the calling Session's. + +Callers keep: + +- What a file is for: the model reads the returned path with `read`. +- The file's bytes and its name: the client supplies them; SessionStore owns the name rule and the storage cap. +- Attachment references: the image block's `fileId` is the Session file's id. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A client stores a large paste as a Session file | No: the content rules and the store call are this owner's | `attachment.put` | +| A client imports a host file as a Session file | No: the image check, the re-encoding and the store call are this owner's | `attachment.import` | +| A client reads a stored attachment by range | No: the range read and the base64 reply are this owner's | `attachment.read` | +| The file is owned by this Session | No: the ownership check is this owner's | the same methods | +| The store's name rule and cap | Yes: SessionStore answers `invalid`/`too_large` | Business | + +An operation or parameter exists only where the row says No. + +## Caller example + +A client stores a paste and reads it back: + +```rust +let PutReply { attachment_id, path, bytes } = attachments.put(PutAttachment { + session_id: session.clone(), + name: Some("paste.txt".into()), + text, +}, cancelled.clone()).await?; +let ReadReply { data, eof } = attachments.read(ReadAttachment { + session_id: session, + file_id: attachment_id, + offset: 0, +}, cancelled).await?; +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `S:sessionIdentity` | The calling Session's id for the ownership check. | +| `P:sessionFiles` | The Session file store's `put`, `import` and `read` operations (#2018). | +| `S:sessionMethods` | Register the `attachment` namespace until this part unloads. | + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `attachment.put` | Store a paste as a Session file | `{sessionId, name?, text}` | `{attachmentId, path, bytes}` | The caller's token; a committed file stays | `invalid`, `too_large`, `not_found`, `storage`, `closed` | +| `attachment.import` | Copy a host file into the Session's files | `{sessionId, path, name?}` | `{attachmentId, path, bytes}` | The caller's token; a committed file stays | `invalid`, `too_large`, `not_found`, `storage`, `closed` | +| `attachment.read` | Read a stored attachment by offset | `{sessionId, fileId, offset}` | `{data, eof}` | The caller's token | `invalid`, `not_found`, `storage`, `closed` | + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid` | The text is empty, the Session id is not the calling Session's, or the parameters are malformed | +| `too_large` | The paste is over 10 MiB or the image over 16 MiB; store a smaller one | +| `not_found` | The Session file or the host path is gone | +| `storage` | The store failed; retry or report it | +| `closed` | The Session is closing; write nothing | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `put`, `import` | Check the calling Session, check the content, call the store, answer the path | Before the store's commit nothing is stored; after it the file stays | The call ends; the store's commit settles | New calls are refused; in-flight calls settle | SessionStore for the file | +| `read` | Check the ownership, read the range, base64 | The read stops; nothing changes | The call ends | Answers `closed` once the Session is gone | SessionStore for the read | + +## Exceptions with reasons + +- The image is decoded and re-encoded before storage: a stored image must already be acceptable to the model, so the owner scales it once at the boundary instead of at every read. +- The reply's `path` is the model's handle: the model reads the file with `read`, and the file's ownership is the Session's. + +## Verification + +- `put` stores a paste and answers its path and size; empty text and over-10-MiB text are refused; a name absent defaults to `paste.txt`. +- `import` copies a host file; a non-image over the limit and an unsupported image are refused; an image is re-encoded when needed. +- `read` pages by offset and answers `eof`; the Session id must match the calling Session. +- A store failure answers `storage`; a closing Session answers `closed`; nothing is stored on a refusal. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part; no state, no Timeline fact. | +| §2 scopes | Session: the methods serve one Session's files. | +| §3 orthogonality | No other owner's state is read; the store answers its own errors. | +| §4 rules 1–5, 9 | No command event, handoff, before callback, batch or Timeline fact. | +| §4 rule 6 | The stored path reaches the model as the method's reply. | +| §4 rule 7 | Clients use the three methods; no caller reads the store's tables. | +| §4 rule 8 | No infrastructure change. | +| §7 values and ids | The Session id, file id, path and bytes are data. | +| §7 no proxy | The store answers the file; this owner answers the method. | +| §7 one interface | One name, `attachment`, on the method table. | +| §7 cross-language | The methods are data. | +| §7 one change | The implementation task changes the method handlers in one change. | +| ADR 002 D1 | Session scope. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | The part depends on the Session file store. | +| ADR 002 D4 | No setting. | +| ADR 002 D5 | The contract is data. | + +## Requirements raised to mechanism owners + +1. [#2018](https://github.com/arcships/dim/issues/2018): the `sessionFiles` operations `put`, `import` and `read` with ids, and the image boundary this owner uses. + +## Binding appendix + +The `attachment` namespace is registered with the method table; the handlers are callbacks. + +```rust +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PutAttachment { + pub session_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + pub text: String, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PutReply { pub attachment_id: String, pub path: String, pub bytes: u64 } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReadAttachment { pub session_id: String, pub file_id: String, pub offset: u64 } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReadReply { pub data: String, pub eof: bool } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AttachmentError { + Invalid { message: String }, + TooLarge { message: String }, + NotFound, + Storage { message: String }, + Closed, +} +``` + Attachments imports files for a Session and returns durable references. Its public face is the `attachment` namespace contributed to [`sessionMethods`](../contracts/session-boundary.md#a1-method-contributions). diff --git a/docs/design/plugins/InputMethods.md b/docs/design/plugins/InputMethods.md new file mode 100644 index 0000000000..be849ab929 --- /dev/null +++ b/docs/design/plugins/InputMethods.md @@ -0,0 +1,182 @@ +# InputMethods + +Scope: session. Issue: #2026. + +InputMethods owns the Session's submit-check table and the `session.input` method contributions: the checks parts register before operator input is written, and the two methods that withdraw or read a line's pending input. The current implementation is in `crates/dim-agent-capabilities/src/input_queue.rs` and is described in the [InputQueue plugin page](../../architecture/rust-agent/plugins/InputQueue.md). The line's input queue is InputQueue's (#2027); this document states what the methods call. + +## Use and scope: responsibility split + +InputMethods owns: + +- **Check registrations.** One check per registering row, with its callback and its lifetime; a registration ends when its row unloads. +- **The checked input.** Running every check in name order, combining their blocks and warnings, and placing the blocks after the operator's own content. +- **The two `session.input` methods.** Their declarations and handler; the input state stays with the line's InputQueue. + +Callers keep: + +- What a check means: Hooks and Skills decide; a check that fails is no opinion. +- When input is written: the operator-entry paths call `prepare` and write the result; the line's queue decides order, idempotency and withdrawal. +- The line an input belongs to: the caller names the line id. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A part checks operator input for its row's lifetime | No: the duplicate check and the row's lifetime are the owner's | `register` | +| An entry turns a candidate input into the input it writes | No: the check order, the block placement and the drop rule are the owner's; a caller composing them forgets the placement | `prepare` | +| An entry reads or withdraws a line's pending input | No: the input state is InputQueue's and is reached by line id | `session.input.withdraw`, `session.input.pending` (the methods below) | +| A check refuses the input with its own code | Yes: `prepare` answers `blocked` with the check's message | Business | +| A check contributes context | Yes: `prepare` appends the check's marker blocks after the operator's content | Business | + +An operation or parameter exists only where the row says No. + +## Caller example + +Hooks registers its `UserPromptSubmit` check from its `apply`: + +```rust +checks.register(RegisterCheck { name: "hooks".into(), check: Arc::new(run_hooks) }).await?; +``` + +An operator entry prepares the input before writing it: + +```rust +let prepared = checks.prepare(PrepareInput { + entry: SubmitEntry::Submit, + branch_id: line.clone(), + user: data.user.clone(), + mode: data.effective_mode(), +}).await?; +match prepared { + Prepared::Ready { user } => session.input.commit(user, &line).await?, + Prepared::Blocked { message } => return Err(RpcError::app(-32000, "input_blocked", message)), +} +``` + +`session.input.withdraw` composes a command and the line's queue: + +```rust +let receipt = line_owner::(line.clone())? + .withdraw(WithdrawInput { input_id, reason, steer }, cancelled.clone()) + .await?; +``` + +## Own contract + +### Dependencies + +None beyond the line's input owner, reached by line id. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `register` | Publish a check for the calling row's lifetime | `{name, check}` | `{}` | None | `duplicate`, `invalid`, `closed` | +| `prepare` | Turn a candidate input into the input an entry writes | `{entry, branchId, user, mode}` | `{prepared: {user}}` or `{blocked: {message}}` | The caller's token stops the checks; a check already running stops with the token | `cancelled`, `closed` | +| `session.input.withdraw` | Withdraw a pending input on a line | `{sessionId, branchId, inputId, reason?, steer?}` | the queue's receipt | The caller's token; a committed withdrawal is not undone | `invalid`, `input_blocked`, `interrupted`, `closed` | +| `session.input.pending` | Read a line's pending input | `{sessionId, branchId}` | the queue's pending value | None | `invalid`, `closed` | + +`check` is a callback by reference; it never runs inside the Timeline's commit lock. `prepare` returns the input the entry writes, with the checks' marker blocks already placed after the operator's content; a non-marker block is dropped with a diagnostic, as today. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `duplicate` | The check name is registered already; the row must not register twice | +| `invalid` | The check name is empty, the entry/mode pair is unknown, or the request is malformed | +| `cancelled` | The entry's call was interrupted while a check ran; write nothing | +| `input_blocked` | A check refused the input; the message is the caller's error | +| `interrupted` | The withdrawal was admitted and its publication not confirmed; read the line's state before retrying | +| `closed` | This Session or the line is closing; write nothing | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `register` | Check the name and record the callback under the row | — | The registration is withdrawn | New registrations are refused | The registering row | +| `prepare` | Take the registered checks in name order, run each with the token, combine, place the blocks, answer | A running check stops with the token; the entry writes nothing | The checks' callbacks are revoked; the entry writes nothing | Pending preparations end `closed` | InputMethods for the combination; each check for its own work | +| `session.input.withdraw` | Validate the input, run the checks, write the command to the line's queue, wait for publication, answer the receipt | A committed withdrawal is not undone; the wait ends `interrupted` | The command settles with the line | The line's queue answers by its own state | The line's InputQueue | +| `session.input.pending` | Read the line's queue value | — | Nothing | Answers the state it observed | The line's InputQueue | + +## Exceptions with reasons + +- A check that fails counts as proceed: an input check is an opinion, and a failing check must not block the operator's input. +- The first block in name order is the answer; later checks still run for their warnings: the caller reads one refusal and every warning, as the operator-entry flow already does. +- `prepare` applies the marker rule itself: a check's context must be a runtime marker element, and an entry that forgot the rule would let a check's text read as the operator's words. + +## Verification + +- A registration lives until its row unloads; a duplicate name is refused; a check's failure is no opinion. +- `prepare` runs checks in name order, the first block answers, and every warning is returned; a non-marker block is dropped; an input without operator content takes no blocks. +- A cancelled preparation runs no further check and writes nothing; a running check stops with the token. +- `session.input.withdraw` with a steer runs the checks before writing the command; a block answers `input_blocked` and writes nothing; the committed command's receipt carries the warnings. +- The two methods answer `invalid` for a malformed request and `closed` after the line ends. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part; it writes no Timeline fact itself (the line's queue writes the withdrawal). | +| §2 scopes | Session: the check table serves the Session's entries; the input state is the line's. | +| §3 orthogonality | No other owner's state is read; the line's queue is reached by id. | +| §4 rules 1–5, 9 | No command event of its own, no handoff, no before callback, no batch, no Timeline fact. | +| §4 rule 6 | A check's blocks enter context only through the input the entry writes; this owner adds no path. | +| §4 rule 7 | Callers use these operations; no caller reads the check table. | +| §4 rule 8 | No infrastructure change. | +| §7 values, ids and callbacks | The candidate input and the receipt are data; the check is a callback; the line is an id; no object crosses. | +| §7 no proxy | The check table answers its own checks; the line's queue answers the input. | +| §7 one interface | One name, `submitChecks`, on the owner type; `append_blocks` leaves the public surface. | +| §7 cross-language | Every operation is data or a callback; no method exists only for Rust. | +| §7 one change | The implementation task deletes `append_blocks` and the separate check call, adds `prepare`, and migrates both entries in one change. | +| ADR 002 D1 | Session scope for the checks; the input state is the line's. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | A check follows its row's lifetime. | +| ADR 002 D4 | No setting. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +1. [#2027](https://github.com/arcships/dim/issues/2027): the line's InputQueue needs `withdraw`/`pending` operations reached by line id, including the publication wait. The line mechanism is [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025)'s `(session, line)` access; until it exists the two methods cannot be migrated off `TreeCommands`. + +## Binding appendix + +The service is marked on `SubmitChecks` under `submitChecks`. `append_blocks` stops being public. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is not a request field. + +```rust +use crate::host::CancelledFn; +use dim_agent_types::{InputMode, UserInput}; +use rutis::host::BoxFuture; +use rutis::Ctx; +use std::sync::Arc; + +pub type CheckFn = Arc BoxFuture<'static, Result> + Send + Sync>; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RegisterCheck { pub name: String, pub check: CheckFn } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PrepareInput { + pub entry: SubmitEntry, + pub branch_id: String, + pub user: Option, + pub mode: InputMode, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Prepared { + Ready { user: Option }, + Blocked { message: String }, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum InputError { + Duplicate { message: String }, + Invalid { message: String }, + Cancelled, + Blocked { message: String }, + Interrupted, + Closed, +} +``` diff --git a/docs/design/plugins/PromptGuide.md b/docs/design/plugins/PromptGuide.md new file mode 100644 index 0000000000..e22039efb8 --- /dev/null +++ b/docs/design/plugins/PromptGuide.md @@ -0,0 +1,172 @@ +# PromptGuide + +Scope: session. Issue: #2026. + +PromptGuide owns the Session's input-guide table: the entries parts register for the markers they write, and the composition that turns the entries in force for one line into the System a request carries. The current implementation is described in the [Prompt](../../architecture/rust-agent/plugins/Prompt.md) page; the branch's adoption of the composition is #2027's. + +## Use and scope: responsibility split + +PromptGuide owns: + +- **Registrations.** One entry per registering row under its scope and first marker; an entry ends when its row unloads. +- **Uniqueness per composition.** A marker has at most one entry in force for a line; a session-scoped entry meets every line, and two branch-scoped entries meet when they name the same line. +- **The frame.** The head and tail of the guide, and the two entries for the markers Prompt itself writes. +- **The composition.** Entries ordered by their own order and first marker, joined with the frame into one System. + +Callers keep: + +- The text they write and the markers they emit; the entry explains the marker and is the writer's. +- When to compose and what base to place: Prompt's adoption and ContextPreparation/ Loop place the System. +- Which line a request belongs to: the caller passes the line id. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A part explains the markers it writes, for its row's lifetime | No: the marker uniqueness and the row's lifetime are the owner's | `register` | +| A part composes the guide for one line over a base | No: the entries in force and the frame are the owner's state | `compose` | +| A part re-composes when an entry appears or withdraws | No: a poll loop in the caller misses withdrawals and order changes | `observe`, then `compose` | +| Change an entry's text | Yes: register the new entry from the writer's next load | Business | +| Decide where the System goes | Yes: Prompt and ContextPreparation place it | Business | + +An operation or parameter exists only where the row says No. + +## Caller example + +A writer registers from its `apply`; the entry ends with the row: + +```rust +guide.register(RegisterEntry { + scope: GuideScope::Session, + entry: GuideEntry { markers: vec!["dim-exec".into()], order: 90, text: EXEC_ENTRY.into() }, +}).await?; +``` + +Prompt composes for its line over the adopted base, and observes changes: + +```rust +let SystemReply { system } = guide.compose(ComposeGuide { line: line.clone(), base: Some(base) }).await?; +let _ = guide.observe(ObserveGuide { + listener: Arc::new(move |version| { + let guide = guide.clone(); + let line = line.clone(); + Box::pin(async move { adopt_composed(guide.compose(ComposeGuide { line, base: None }).await).await }) + }), +}).await?; +``` + +## Own contract + +### Dependencies + +None. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `register` | Publish an entry for the calling row's lifetime | `{scope, entry}` | `{}` | None | `invalid`, `duplicate_marker`, `too_large`, `closed` | +| `compose` | The System for one line over a base | `{line, base?}` | `{system}` | None; a pure read | None | +| `observe` | The composition version now and on each change until the row unloads | `{listener}` | `{}` | The row's unload ends the subscription | `closed` | + +`scope` is `"session"` or `{branch: lineId}`; `entry` is `{markers, order, text}`, `markers` at least one and each `[a-z][a-z0-9_-]{0,63}`, `text` at most 4096 bytes. `listener` is a callback by reference; it runs outside the table's lock and outside the Timeline's commit lock. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid` | A marker is outside the grammar, the scope's line id is empty or the entry has no marker; fix the entry | +| `duplicate_marker` | A marker the entry names has an entry whose scope meets this one; change the marker or the scope | +| `too_large` | The text is over 4096 bytes; shorten it | +| `closed` | This Session is closing; a later generation serves the next Session | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `register` | Check the scope, markers, size and duplicates, record under the row, raise the version | — | The entry is withdrawn; the composition moves | New registrations are refused; the table reloads with the Session | The registering row | +| `compose` | Select the entries in force for the line, sort, join with the frame | — | Nothing | Answers the state it observed | PromptGuide | +| `observe` | Register the listener under the row and call it with the current version | The row's unload ends it | The subscription ends | The listener stays until the generation unloads | PromptGuide | + +## Exceptions with reasons + +- An entry whose writer registers while another composes may publish two configurations: the composition before and after the entry. The branch's adoption takes the later one; the intermediate System is the cost of not holding the composition across the writer's load. +- A composition already made does not change when an entry withdraws: Prompt's adoption decides when the System moves, so a branch that is closing records nothing. + +## Verification + +- A registration lives until its row unloads; an invalid marker, an empty branch id, an oversized text and a meeting duplicate are refused with their own kinds. +- `compose` orders by the entry's order then first marker; a session entry meets every line; two branch entries for different lines never meet. +- `observe` delivers the current version and each later change; the row's unload ends delivery. +- A writer's withdrawal moves the composition only at the next adoption; a closing branch adopts nothing. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part; it writes no Timeline fact. | +| §2 scopes | Session: contributors live at both scopes and the Session is their nearest common owner; an entry's scope names where it applies. | +| §3 orthogonality | No other owner's state is read; the composition is the owner's own state. | +| §4 rules 1–5, 9 | No command event, handoff, before callback, batch or Timeline fact. | +| §4 rule 6 | The composed System reaches the model through Prompt's adoption; this owner adds no context path. | +| §4 rule 7 | Callers use these operations; no caller reads the entry table. | +| §4 rule 8 | No infrastructure change. | +| §7 values, ids and callbacks | The entry and the System are data; the listener is a callback; the line is an id; no object crosses. | +| §7 no proxy | The table answers its own entries and composition. | +| §7 one interface | One name, `guideEntries`, on the owner type; no wrapper. | +| §7 cross-language | `register`, `compose` and `observe` are data and a callback; no method exists only for Rust. | +| §7 one change | The implementation task deletes the Rust-only composition methods and migrates Prompt, ContextPreparation and Loop in one change. | +| ADR 002 D1 | Session scope. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type. | +| ADR 002 D3 | An entry follows its writer's lifetime; the table depends on no contributor. | +| ADR 002 D4 | No setting selects a behaviour here. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +The service is marked on `GuideEntries` under `guideEntries`. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is not a request field. + +```rust +use crate::host::CancelledFn; +use dim_agent_types::SystemPrompt; +use rutis::host::BoxFuture; +use rutis::Ctx; +use std::sync::Arc; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum GuideScope { Session, Branch(String) } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GuideEntry { pub markers: Vec, pub order: i32, pub text: String } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RegisterEntry { pub scope: GuideScope, pub entry: GuideEntry } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ComposeGuide { pub line: String, #[serde(default)] pub base: Option } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SystemReply { pub system: SystemPrompt } + +pub type Listener = Arc BoxFuture<'static, ()> + Send + Sync>; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ObserveGuide { pub listener: Listener } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum GuideError { + Invalid { message: String }, + DuplicateMarker { message: String }, + TooLarge { message: String }, + Closed, +} +``` diff --git a/docs/design/plugins/PromptSources.md b/docs/design/plugins/PromptSources.md index 90c40ad827..8969e3212e 100644 --- a/docs/design/plugins/PromptSources.md +++ b/docs/design/plugins/PromptSources.md @@ -1,6 +1,235 @@ # PromptSources -Status: Draft ([#548](https://github.com/arcships/dim/issues/548)). Requirements: [model-facing prompts §7 and §9.1](../model-prompts.md#7-language). Rules: [design rules](../../architecture/rust-agent/principles.md) §1, §4 and §5, [ADR 002](../../adr/002-plugin-scope.md). Scope: Session. Language: Rust. The current capability is on [PromptSources](../../architecture/rust-agent/plugins/PromptSources.md)'s capability page. +Scope: session. Issue: #2026. + +PromptSources is the Session's prompt sources and the Session's reply language. Two owners share this document because one part holds both states: **PromptSources** owns the registered sources, the load operation and the initial configuration; **SessionLanguage** owns the reply-language value and its version. The current implementation is described in the [PromptSources plugin page](../../architecture/rust-agent/plugins/PromptSources.md). The branch polling and Prompt's adoption are #2027's; this document states what they call. + +## Use and scope: responsibility split + +PromptSources owns: + +- **Source registrations.** One named source per registering row: its load callback and its lifetime; a registration ends when its row unloads. +- **Loading one source for a target.** The target names the source and the branch, turn or task scope; the reply is one entry or none. +- **The initial configuration.** The source targets and model a new branch adopts, read when a branch opens. +- **The built-in sources.** `dim/base`, `dim/session`, project and user instructions, environment, date and language, registered at apply. +- **The language value.** The operator's reply language, its version, and the transition that changes it. + +Callers keep: + +- What a source says: its text, its version and its delivery; Prompt adopts entries and owns the adopted prompt state. +- Which sources a branch checks and when: the branch part's polling (#2027). +- The Session record write for a language change: the Session store owns the record (#2018); the update entry composes the record write, the value change and each loaded branch's adoption. +- The policy texts' content: the factory configuration supplies them; this owner stores and serves them. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A part publishes a named source for its row's lifetime | No: the name's uniqueness and the row's lifetime are the owner's | `register` | +| A branch loads one source for a target | No: the source's callback is the owner's; a caller holding the callback would carry the contributor's object | `load` | +| A branch opens and adopts every source registered then | No: the target set and the model come from the owner's state | `initial` | +| A branch checks a source again later | Yes: `load` with the same target | Business | +| The branch knows whether it has the current text | Yes: the entry carries its version; the branch compares | Business | +| Read the reply language | No: the live value is the owner's | `get` | +| Change the reply language | No: the value, its version and the transition are the owner's | `set` | +| Make a changed language visible on every loaded branch before replying | No: each branch's adoption is its own operation; the update entry calls it per line | Business composition (Requirements 1) | + +An operation or parameter exists only where the row says No. + +## Caller example + +The built-in sources register at apply, and Skills registers its own source the same way: + +```rust +for name in SOURCES { + sources.register(RegisterSource { name: name.into(), load: sources.clone() }).await?; +} +``` + +A branch adopts at open and reloads one source when its periodic check moves it: + +```rust +let Some(update) = sources.initial().await? else { return Ok(()) }; +prompt.configure(ConfigureRequest::Initial(update), cancelled.clone()).await?; + +if let Some(entry) = sources.load(LoadSource { source: "dim/instructions/project".into(), scope }, cancelled.clone()).await? { + if adopted.version != entry.version { + prompt.configure(ConfigureRequest::Loaded { sources: vec![entry] }, cancelled.clone()).await?; + } +} +``` + +The language update entry composes the record, the value and each loaded branch: + +```rust +store.set_session_language(&session_id, language).await?; // #2018's record +let Changed { previous, version } = language.set(SetLanguage { language }).await?; +for line in tree.directory(None)?.lines { + line_owner::(line.line)?.adopt(LanguageUpdate { version }, cancelled.clone()).await?; +} +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `P:HostPlatform` | Home, environment and shell/platform context for the environment source. | +| `S:sessionConfig` | Working directory, Session context and the language seed. | +| `P:basePromptSettingsHost` | The user's replacement of `dim/base`, read once at apply; absent keeps the factory text. | + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `register` | Publish a source for the calling row's lifetime | `{name, load}` | `{}` | None | `duplicate`, `invalid`, `closed` | +| `load` | One source's entry for a target | `{source, scope}` | `{entry?}` | The caller's token stops the load; a withdrawn source only stops later lookups | `unknown`, `cancelled`, `failed` | +| `initial` | What a new branch adopts | `{}` | `{configuration?}`: source targets and model | None | None | +| `get` | The reply language and its version | `{}` | `{language?, version}` | None | None | +| `set` | Change the reply language | `{language?}` | `{previous?, version}` | None; the owner completes it | None | + +`load` is a callback by reference on the owner's side: the contributor's load runs outside the owner's locks and outside the Timeline's commit lock; an accepted load settles even after its source withdraws. `get` and `set` are values and a transition; no lock, version or wait crosses. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `duplicate` | The source name is registered already; the row must not register twice | +| `invalid` | The source name is empty or outside the source grammar | +| `unknown` | No source of that name is registered now; drop the target or re-read `initial` | +| `cancelled` | The load stopped before the entry was produced; the branch adopts nothing | +| `failed` | The source failed while producing the entry; the branch keeps its adopted text and retries on its next check | +| `closed` | This Session is closing; a later generation serves the next Session | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `register` | Check the name and record the callback under the row | — | The registration is withdrawn; accepted loads settle | New registrations are refused; the registry reloads with the Session | The registering row | +| `load` | Find the source, call the callback with the target, return the entry | The load ends `cancelled`; the callback's own I/O is the contributor's to stop | The load ends `cancelled`; a load already accepted settles by the source's rule | Pending loads settle or end `closed` | PromptSources for the lookup; the source for its content | +| `initial` | Read the registered names and the model into one value | — | Nothing to release | Pending reads answer the state they observed | PromptSources | +| `get` | Read the value and version | — | Nothing | Answers the state it observed | SessionLanguage | +| `set` | Take the value's gate, replace the value, raise the version | — | Nothing | Refused once the part unloads | SessionLanguage | + +## Exceptions with reasons + +- The base prompt setting is read while the part applies: a read failure keeps the factory text, and the source serves it for the Session's life; no per-load read means a later user change waits for the next Session. +- A withdrawn source does not cancel a load it already accepted: the source's I/O is its own, and the branch's comparison by version makes a late entry harmless. +- The language value is a cell with a version, not a per-branch copy: every branch reads the same value and decides by version whether it adopted it; no branch holds the value's lock. + +## Sources and classes + +Each source is one name with an owner, a delivery and a class. The delivery decides where a change takes effect: a `System` source is part of the composed system prompt; a `Context` or `State` source is delivered as an Append input block. + +| Source | Delivery | Order | Author | Class | +| --- | --- | --- | --- | --- | +| `dim/base` | System | 0 | PromptSources | Policy | +| `dim/session` | System | 50 | The host or the profile | Content | +| `dim/instructions/project` | Context (``) | 100 | The project | Content | +| `dim/instructions/user` | Context (``) | 110 | The user | Content | +| `dim/environment/context` | State (``) | 200 | PromptSources | Facts, plus two guidance texts | +| `dim/environment/date` | State (``) | 210 | PromptSources | Fact | +| `dim/language` | State (``) | 220 | PromptSources | Fact | + +`dim/base` is the identity sentence and the rules; the environment source's shell and file-encoding guidance is policy too. Both are replaceable at the factory configuration (`base`, `shell_guidance`, `file_encoding_guidance`), and the product sets none. The environment source states the working directory, home, shell executable and edition, output encoding, platform and time zone; the date source states the date in the process's local time zone. `dim/session` is the host's or the profile's system prompt, carried and never edited. The user's and project's `AGENTS.md` are read as files, escaped with the context-block escape rule and carried verbatim; a missing or unreadable file produces no entry. + +## The language source + +Source `dim/language` states the operator's language in one sentence, and no entry when the operator selected none: + +```text +The operator set this session's reply language to Simplified Chinese. +``` + +The value is `SessionConfig.language`, seeded by `session.create {language?}` and changed by `session.language.update`; the daemon never reads the client's interface-locale file. The update writes the record, calls `set`, and has each loaded branch adopt the new version before it replies; a branch loaded later reads the current version at open, and each branch's periodic check remains the fallback. + +## Verification + +- A registration lives until its row unloads; a duplicate name and an empty name are refused; a load of an unregistered name is `unknown`. +- A load forwards the caller's cancellation and settles normally after its source withdraws; a failing source answers `failed`. +- `initial` lists the sources registered then and the Session's model; a source registered later appears at the next branch open. +- `get` answers the language and version; `set` answers the previous value and a higher version; a branch that already adopted the version does not adopt again. +- The language update writes the record, calls `set`, and each loaded line adopts before the reply; a branch opened later reads the current version at open. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | PromptSources is one Session part holding two owners' state; it writes no Timeline fact and folds none. Branch polling is a separate branch part (#2027). | +| §2 scopes | Session: sources and the language value belong to one Session; a branch reads by target and by version. | +| §3 orthogonality | No other owner's state is read or changed; the base prompt text is read through the host face. | +| §4 rules 1–5, 9 | No command event, handoff, before callback, business meaning in the core, batch, or Timeline fact. | +| §4 rule 6 | Entries reach the model only after Prompt adopts them; this owner adds no context path. | +| §4 rule 7 | Callers use these operations; no caller reads a source callback or the value's lock. | +| §4 rule 8 | No infrastructure change. | +| §7 values, ids and callbacks | Targets, entries, the initial configuration and the language value are data; the source load is a callback; the language adoption by line is an id-addressed operation; no source object or lock crosses. | +| §7 no proxy | The registry answers its own sources; the base text is the host's; the language value is its own. | +| §7 one interface | `promptSources` and `sessionLanguage` name the two owners' own operations; `promptHost`, `promptRegistry` and `initialPromptConfiguration` leave the catalog; no wrapper type remains. | +| §7 one change | The implementation task deletes the wrappers, adds these operations and migrates every caller in one change. | +| ADR 002 D1 | Session scope: sources and the language value live with one Session. | +| ADR 002 D2 | No wiring plugin: the operations are on the owners' types. | +| ADR 002 D3 | A source follows its part's lifetime; the registry depends on no contributor. | +| ADR 002 D4 | The policy texts are factory configuration; no business setting is read per load. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +1. [#2027](https://github.com/arcships/dim/issues/2027): Prompt's branch owner needs an operation reached by line id that adopts a language update (the value's version) before the update replies. The line mechanism is [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025)'s `(session, line)` access; until it exists the update cannot keep the before-reply promise and this contract records the gap. +2. [#2018](https://github.com/arcships/dim/issues/2018): the Session record's `setSessionLanguage` operation the update entry calls before `set`. + +## Binding appendix + +The services are marked on their owner types under `promptSources` and `sessionLanguage`. `PromptHost`, `PromptRegistry` as a second name and `InitialPromptConfiguration` leave; the shared types below are the wire shapes. `caller: &Ctx` is the rutis caller parameter for `register`; `CancelledFn` is the cancellation argument and is not a request field. + +```rust +use crate::host::CancelledFn; +use dim_agent_runtime::{ConfigureUpdate, PromptEntry, PromptScope, PromptSourceTarget, ReplyLanguage}; +use rutis::host::BoxFuture; +use rutis::Ctx; +use std::sync::Arc; + +pub type LoadFn = + Arc BoxFuture<'static, Result, String>> + Send + Sync>; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RegisterSource { pub name: String, pub load: LoadFn } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LoadSource { pub source: String, pub scope: PromptScope } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LoadReply { pub entry: Option } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct InitialReply { pub configuration: Option } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LanguageValue { pub language: Option, pub version: u64 } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SetLanguage { pub language: Option } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Changed { pub previous: Option, pub version: u64 } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SourceError { + Duplicate { message: String }, + Invalid { message: String }, + Unknown { message: String }, + Cancelled, + Failed { message: String }, + Closed, +} +``` + PromptSources provides the Session's named prompt sources and the Session's prompt registry. It owns the words of the sources it authors — the base prompt and the shell guidance — and carries, but does not own, the host's system prompt and the user's and the project's `AGENTS.md`. It states the runtime environment and the date as facts. It contributes no input-guide entry: the markers it feeds are Prompt's, which writes them and explains them ([Prompt §4](Prompt.md#4-the-built-in-entries-and-their-writers)). diff --git a/docs/design/plugins/PromptSuggestion.md b/docs/design/plugins/PromptSuggestion.md index 830d3a6a31..bb242b363e 100644 --- a/docs/design/plugins/PromptSuggestion.md +++ b/docs/design/plugins/PromptSuggestion.md @@ -1,6 +1,144 @@ # PromptSuggestion -Status: Design. Scope: [ADR 002](../../adr/002-plugin-scope.md) (process and Session). Language: Rust. Phase: P1; [#943](https://github.com/arcships/dim/issues/943). +Scope: session. Issue: #2026. + +PromptSuggestion owns the client's reply suggestion: the offer after a turn ends, the model call that produces it, and the client's accept or dismiss. The current implementation is in `crates/dim-agent-capabilities/src/prompt_suggestion.rs`; the plugin page is [PromptSuggestion](../../architecture/rust-agent/plugins/PromptSuggestion.md). + +## Use and scope: responsibility split + +PromptSuggestion owns: + +- **The offer.** One pending suggestion per Session, keyed by the turn that produced it; a new turn's offer replaces the pending one. +- **The decision.** Whether a suggestion is due: the Session's settings, the turn's end, and the appended compaction request. +- **The model call.** One `Once` request through the provider owner, with a streamed reply the client watches. +- **The client's answer.** Accept or dismiss the offer. + +Callers keep: + +- What a suggestion says: the model produces it; the client decides. +- The turn's facts: the line's Timeline answers them. +- The context usage that decides a compaction: the line's ContextUsage publishes it. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A client asks for a suggestion after a turn | No: the pending offer and the due decision are the owner's | `session.suggestion.request` | +| A client accepts or dismisses the offer | No: the offer's identity and its single use are the owner's | `session.suggestion.respond` | +| The model call is made with the right provider and budget | No: the selection and the once-request are the provider owner's | `providerService.invoke` | +| A compaction changes the context | No: the line's usage is the branch owner's | the line's ContextUsage by id | + +An operation or parameter exists only where the row says No. + +## Caller example + +The client asks and answers; the offer is identified by its turn: + +```rust +let RequestReply { offer_id, text } = suggestion.request(RequestSuggestion { turn_id }, cancelled.clone()).await?; +suggestion.respond(RespondSuggestion { offer_id, accept: true }).await?; +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `S:sessionConfig` | `interactive` and the collaboration role: only a leader's interactive Session offers suggestions. | +| `S:sessionIdentity` | The Session id in the offer and the request. | +| `S:sessionScope` | `activated`/`closing`: the part works only while the Session runs. | +| `S:sessionMethods` | Register `session.suggestion` until this part unloads. | +| `P:providerService` | `resolve` and `invoke` with `Once` for the suggestion request (#2019). | +| `P:promptSuggestionSettingsHost` | The user's enable flag and size bound, read per decision. | +| `S:timelineTree` | The line's directory record and the turn's end fact. | +| The line's ContextUsage | The usage that decides an appended compaction request, reached by line id (#2027). | + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `session.suggestion.request` | Ask for a suggestion for one turn | `{sessionId, turnId}` | `{offerId, text}` | The caller's token stops the model call; the offer is dropped | `invalid`, `cancelled`, `closed` | +| `session.suggestion.respond` | Accept or dismiss one offer | `{sessionId, offerId, accept}` | `{}` | None | `invalid`, `closed` | + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid` | The turn id is not the last turn, the offer is not pending, or the parameters are malformed | +| `cancelled` | The model call stopped; no offer remains | +| `closed` | The Session is closing; no suggestion is made | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `request` | Check the settings and the turn, resolve the model, run one `Once` request, stream to the client, answer the offer | The model call stops; the offer is dropped | The call ends; the part's tasks stop | New requests are refused; a pending offer is dropped | PromptSuggestion for the offer; the provider for the request | +| `respond` | Take the offer, answer `{}` | Nothing | The offer stays until the part unloads | A pending offer is dropped at close | PromptSuggestion | + +## Exceptions with reasons + +- The suggestion is one `Once` request, not the dialogue chain: a suggestion is a single paid request and must not retry or substitute a model behind the client's back. +- The offer is keyed by the turn: a new turn's offer replaces the pending one, so a client cannot accept a suggestion for a turn that has moved on. + +## Verification + +- A request after the last turn ends produces one offer; a second request replaces it; a request for an older turn is `invalid`. +- The model call uses the selected provider and model with `Once`; a cancelled request leaves no offer; a disabled setting makes no call. +- `respond` accepts or dismisses the pending offer once; a second answer is `invalid`. +- The part's unload drops the pending offer and stops its tasks. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part; it writes no Timeline fact. | +| §2 scopes | Session: the offer serves one Session; the line's state is read by id. | +| §3 orthogonality | No other owner's state is read; the provider and the line's usage are reached by their operations. | +| §4 rules 1–5, 9 | No command event, handoff, before callback, batch or Timeline fact. | +| §4 rule 6 | The suggestion reaches the client, not the model context. | +| §4 rule 7 | Clients use the two methods; no caller reads the offer table. | +| §4 rule 8 | No infrastructure change. | +| §7 values, ids and callbacks | The turn id, offer id and text are data; the model reply streams through the provider's callback; no provider object crosses. | +| §7 no proxy | The provider answers the model call; the line answers its usage; this owner answers the offer. | +| §7 one interface | One name, `session.suggestion`, on the method table. | +| §7 cross-language | The methods are data. | +| §7 one change | The implementation task migrates the model call to `providerService` and the usage read to the line access in one change. | +| ADR 002 D1 | Session scope for the offer; the line's usage is the branch's. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | The part depends on the provider and the Session scope; absent settings or provider only disable suggestions. | +| ADR 002 D4 | The enable flag and size bound are read at use, not at reload. | +| ADR 002 D5 | The contract is data. | + +## Requirements raised to mechanism owners + +1. [#2019](https://github.com/arcships/dim/issues/2019): `providerService.resolve` and `invoke {request, mode: "once"}` with the streamed consumer the suggestion needs. +2. [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025): the line access that lets this Session part read the line's ContextUsage by `(session, line)` id, and [#2027](https://github.com/arcships/dim/issues/2027)'s usage operation for it. + +## Binding appendix + +The `session.suggestion` namespace is registered with the method table; the handlers are callbacks. + +```rust +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RequestSuggestion { pub session_id: String, pub turn_id: String } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RequestReply { pub offer_id: String, pub text: String } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RespondSuggestion { pub session_id: String, pub offer_id: String, pub accept: bool } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SuggestionError { + Invalid { message: String }, + Cancelled, + Closed, +} +``` + PromptSuggestion offers the message the user would plausibly send next. When a client that witnessed a completed turn has an empty composer, it asks the Session with `session.suggestion.request {sessionId, turnId}`; the Session part clones the turn's last `ModelCall` request, appends the assistant message that request produced and one instruction, and invokes the same model through the model host and the provider connection resolver. The reply is one validated line, delivered as a Session broadcast notice (`session.notice`, source `PromptSuggestion`). The offer is display-only: it enters no Timeline event, no storage and no model context, and the next real request is the same with or without it. A suggestion is only ever inserted into a client's composer, never sent. diff --git a/docs/design/plugins/Questions.md b/docs/design/plugins/Questions.md index 398bc9c353..dda4f4534a 100644 --- a/docs/design/plugins/Questions.md +++ b/docs/design/plugins/Questions.md @@ -1,6 +1,159 @@ # Questions -Status: Implemented ([#262](https://github.com/arcships/dim/issues/262): #269, #336, #351; redesign [#144](https://github.com/arcships/dim/issues/144)); the maintainer's confirmations are recorded in [§12](#12-ready-confirmation). Overall design: [overview §4](../overview.md#4-plugin-catalog). Milestone: M2. Language: Rust. Scope: Session ([ADR 002](../../adr/002-plugin-scope.md)). +Scope: session. Issue: #2026. + +Questions owns the `ask_user` tool and the Session part that holds the model's pending questions: the table keyed by `(line, request, call)` and the claim that makes a question visible before its call is published. The current implementation is in `crates/dim-agent-questions/src/lib.rs`; the plugin page is [Questions](../../architecture/rust-agent/plugins/Questions.md). The claim's tool-side contract is in [ToolRegistry](ToolRegistry.md#own-contract). + +## Use and scope: responsibility split + +Questions owns: + +- **The waiter table.** One entry per waiting question, keyed by line, request and call; whoever removes the entry under the lock decides the call's output. +- **The answer's validation.** Answers must name every question once, choose offered labels and respect `multiSelect` and `allowCustom`. +- **The claim.** A question exists before its `step/tool-call` fact and is removed when the answer, the call's cancel or the part's unload ends it. + +Callers keep: + +- When to ask: the model decides; the tool's input shape is this owner's declaration. +- Whether a question may run: Permission and the Session's `interactive` flag decide. +- The client's answer: it arrives as the `session.question.respond` method, not as a fact. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| The model asks and waits for one answer | No: the table, the claim and the single-answer rule are the owner's | the `ask_user` tool | +| A client answers or declines the waiting call | No: the entry and the answer validation are the owner's | `session.question.respond` | +| A client lists the waiting questions on a line | No: the table is the owner's | `session.question.pending` | +| The question is visible before the fact that publishes it | No: the claim must exist before the append and be released on every path that never dispatches | the claim callback | + +An operation or parameter exists only where the row says No. + +## Caller example + +The tool registers with its declaration and claim callback; the claim inserts the waiter and returns nothing: + +```rust +tools.register(RegisterTool { + declaration: ask_user_definition(), + execute: Arc::new(|call, context, cancelled| Box::pin(run_ask_user(call, context, cancelled))), + claim: Some(Arc::new(|call, context| claim_question(call, context))), +}).await?; +``` + +A client answers; the method resolves the waiter and the call's result follows: + +```rust +methods.respond(RespondQuestion { line, request_id, call_id, answers })?; // {} once the waiting call takes it +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `S:sessionConfig` | `interactive`, read per call; a non-interactive Session gets an error result. | +| `S:toolRegistry` | Register `ask_user` until this part unloads. | +| `S:sessionMethods` | Register `session.question` until this part unloads. | + +### Contributions + +No service of its own. The table is reached only through the tool call's wait and the two methods. + +| Contribution | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | +| `session.question.respond` | `{sessionId, branchId, requestId, callId, answers? \| declined: true}` | `{}` | The call's own admission | `invalid`, `not_pending` | +| `session.question.pending` | `{sessionId, branchId}` | `{requests}` | None | `invalid` | + +The tool's own outcomes are `ToolResult`s: answered, declined, non-interactive, invalid input, cancelled, and the part's reload settlement. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid` | The answer names no question, repeats one, chooses an unoffered label, or the call's input is malformed | +| `not_pending` | No waiting call matches the three ids; re-read `pending` | + +### Flows + +| Path | Normal | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| Claim | Insert the entry before the append, keyed by `(line, request, call)` | The claim is released before dispatch | The entry is removed with the row | The part's unload removes every entry | Questions; the release is `release_claims` | +| Wait | The tool waits on the entry's sender | The call's token removes the entry; the result is `cancelled` | The claim's release removes the entry | The part's unload drops the senders; ToolExecutor settles the call | Questions | +| Answer | `respond` validates, removes the entry, sends the answer | The answer is delivered and then dropped with the claim; the call's result is its refusal | Nothing to release | The part's unload removes pending entries | Questions | + +## Exceptions with reasons + +- An answer accepted between the claim and a refused append is delivered and then dropped with the claim: the call's result is the refusal, and the question does not stay open. +- A wait left by a reload or restart is settled by ToolExecutor, not rebuilt: the waiter is a human I/O, and the line's facts do not hold it. +- `pending` reads the table directly: a waiting question is the owner's own state, not a Timeline fact. + +## Verification + +- Input rules: 1 to 4 questions, unique ids, 2 to 6 options, headers, custom text; a malformed input answers `invalid` before any entry is created. +- A claim inserts before the append; a refused append, an interrupt before dispatch, a refused admission, a cancelled task, a Loop error and a reload leave no entry. +- `respond` removes the entry and the waiting call answers; a second `respond` answers `not_pending`; an answer for another line's entry is `not_pending`. +- The part's unload removes every pending entry and the calls settle as reloading. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part; it writes no Timeline fact. | +| §2 scopes | Session: the table serves the Session's lines; a branch part registers a Session namespace only through this part's placement. | +| §3 orthogonality | No other owner's state is read; the `interactive` flag is the creation record. | +| §4 rules 1–5, 9 | No command event, handoff, before callback, batch or Timeline fact; the claim is the tool mechanism's, not a fact. | +| §4 rule 6 | The answer reaches the model as the tool result. | +| §4 rule 7 | Clients use the two methods; no caller reads the table. | +| §4 rule 8 | No infrastructure change; the claim is the tool mechanism's contract. | +| §7 values, ids and callbacks | Ids and answers are data; the claim is a callback; no waiter object or sender crosses. | +| §7 no proxy | The table answers its own lines' questions. | +| §7 one interface | No service name; the tool and the two methods are the surface. | +| §7 cross-language | The methods are data; the tool's execute is a callback. | +| §7 one change | The implementation task migrates the claim to the tool contract's operations in one change. | +| ADR 002 D1 | Session scope. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | The tool depends on the registry and the method table. | +| ADR 002 D4 | No setting. | +| ADR 002 D5 | The contract is data; the binding is below. | + +## Requirements raised to mechanism owners + +None beyond the claim contract recorded in [ToolRegistry](ToolRegistry.md#requirements-raised-to-mechanism-owners). + +## Binding appendix + +The claim callback is the tool contract's `ClaimFn`; the method handler is the table's `call` callback. The waiter table and its entries stay private. + +```rust +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RespondQuestion { + pub session_id: String, + pub branch_id: String, + pub request_id: String, + pub call_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub answers: Option>, + #[serde(default)] + pub declined: bool, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Answer { pub question_id: String, pub selected: Vec, #[serde(default)] pub custom: Option } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PendingReply { pub requests: Vec } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum QuestionError { + Invalid { message: String }, + NotPending, +} +``` + The model asks the user one or more questions through the `ask_user` tool and waits for the answer: single choice, multiple choice, several questions in one call, custom answer, or a decline. **The question is the pending tool call, and the answer is its tool result.** A client sees the question as the committed `step/tool-call` of `ask_user` that has no `step/tool-result` yet, answers it with the Session method `session.question.respond`, and the waiting handler returns the answer as its `ToolResult`; ToolExecutor publishes it in the batch's `step/tool-result` like any other tool output. The model learns the user's choice only from `ToolResult.content`. diff --git a/docs/design/plugins/Recall.md b/docs/design/plugins/Recall.md index 3bc0c90dfe..5fed219642 100644 --- a/docs/design/plugins/Recall.md +++ b/docs/design/plugins/Recall.md @@ -1,10 +1,113 @@ # Recall -Status: Ready (approved 2026-10-21, §15). Issue: -[#129](https://github.com/arcships/dim/issues/129). Milestone: M2. Language: Rust. Scope: -[ADR 002](../../adr/002-plugin-scope.md) (Session). Depends on -[ContextCompaction](ContextCompaction.md) (F1, implemented) and tool registration with `toolRegistry` -([session-boundary A.5](../contracts/session-boundary.md#a5-tool-contribution), implemented). +Scope: session. Issue: #2026. + +Recall owns the `recall` tool: the model asks for its own line's history, and the tool pages the line's facts at a pinned head. The current implementation is in `crates/dim-agent-capabilities/src/recall.rs`; the plugin page is [Recall](../../architecture/rust-agent/plugins/Recall.md). The history read is TimelineTree's (#2024); this owner holds no state. + +## Use and scope: responsibility split + +Recall owns: + +- **The tool's declaration and result text.** What a call returns: turn, input, reply and tool origins, ranked and paged. +- **The page budget.** At most 128 origin positions, 20 entries or 8,000 characters per page, eight bodies per batch. +- **The pinned cutoff of one call.** A compaction during the call cannot move it. + +Callers keep: + +- What the model wants: the tool's arguments are the model's. +- The line's facts: TimelineTree answers them at a cutoff; this owner only selects and renders. +- Context assembly: the result is one tool result. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| The model reads its line's history | No: the selection, ranking and paging are this owner's | the `recall` tool | +| The model names a cutoff or a page | Yes: the tool's arguments | Business | +| The tool pins one head for the call | No: the pin is TimelineTree's read and this owner's selection | TimelineTree's `read`, called once | + +An operation or parameter exists only where the row says No. + +## Caller example + +The tool resolves the calling line and reads at its head; no `Branch` object is involved: + +```rust +let line = execution.branch_id; // a value +let ReadLinesReply { through, events } = tree.read(ReadLines { + line: line.clone(), + scope: None, + from: Some(after + 1), + through: Some(head), + fields: RECALL_FIELDS.to_vec(), + limit: Some(PAGE), +}).await?; +render(events) +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `S:timelineTree` | `read` at the line's cutoff; the directory record names the head. | +| `S:toolRegistry` | Register `recall` until this part unloads. | + +### Contributions + +No service of its own; the `recall` tool is the whole surface. + +### Errors + +The tool answers `ToolResult`s; the tree's read errors become the tool's content: `unknown` (the line is not this Session's), `beyond_head` (lower the cutoff), `not_batch_boundary` (use a reply's `through`), `continuation_without_cutoff`, `closed` (the Session is closing). A cancel after the first page answers the tool as cancelled without further pages. + +### Flows + +| Path | Normal | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| Recall | Resolve the line, read the index page, load at most eight bodies, render, page | The call stops between pages; the result is cancelled | The call ends; no resource | `closed` from the tree; the tool ends | Recall; the tree for the read | + +## Exceptions with reasons + +- The call pins the head it started at: a compaction during the call must not move the page's boundary, so the first `read`'s cutoff is reused for every later page. +- A body that is not needed for the summary is not loaded: the tool counts and titles, not the text, so the index page stays bounded. + +## Verification + +- A call lists the newest 21 turn positions and pages 20 entries or 8,000 characters; a continuation repeats the original cutoff. +- A text term narrows the origins; a short or non-ASCII query keeps the metadata path; at most eight bodies are loaded per batch. +- A compaction during the call does not move the pinned head; a reload ends the call `closed`. +- The result carries the same text for the same facts regardless of the line's live state. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part; it writes no fact and folds no state, so it is not a Capability. | +| §2 scopes | Session tool reading a line's facts; the line is an id. | +| §3 orthogonality | No other owner's state is read; the tree answers the facts. | +| §4 rules 1–5, 9 | No command event, handoff, before callback, batch or Timeline fact. | +| §4 rule 6 | The result reaches the model as the tool result. | +| §4 rule 7 | The tool calls the tree's operation; no caller reads the tree's internals. | +| §4 rule 8 | No infrastructure change. | +| §7 values and ids | The line id, the cutoff and the page are data; no object crosses. | +| §7 no proxy | The tree answers the facts; Recall only selects and renders. | +| §7 one interface | No service name; the tool is the surface. | +| §7 cross-language | The tool's execute is a callback; its input and result are data. | +| §7 one change | The implementation task replaces the `TreeCommands`/`Branch` lookup with `timelineTree.read` in one change. | +| ADR 002 D1 | Session scope. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | The tool depends on the tree's read. | +| ADR 002 D4 | No setting; the page budget is the owner's. | +| ADR 002 D5 | The contract is data. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +No service. The tool registers through the tool contract; its input is `{query?, after?, limit?}` and its result is one `ToolResult` whose content is the rendered page. + Recall is a Session plugin that gives the model one read-only tool, `recall`. It tells the model the history of its own branch as an account of what happened: what the user said, what the model diff --git a/docs/design/plugins/SessionMethods.md b/docs/design/plugins/SessionMethods.md new file mode 100644 index 0000000000..d89527dc9e --- /dev/null +++ b/docs/design/plugins/SessionMethods.md @@ -0,0 +1,210 @@ +# SessionMethods + +Scope: session. Issue: #2026. + +SessionMethods owns a Session's method table: the namespaces its parts register, who answers a name now, and the admission of one call. The current implementation is in `crates/dim-agent-capabilities/src/methods.rs` and is described in the [SessionMethods plugin page](../../architecture/rust-agent/plugins/SessionMethods.md). ManagementMethods (#2021) is the process table with the same shape; Rpc, the registering parts and `session.methods` are callers. + +## Use and scope: responsibility split + +SessionMethods owns: + +- **Registrations.** One namespace per registering row, its declarations and its call callback; a registration ends when its row unloads. +- **Admission.** One call: the name's owner, the interruption kind its declaration names, the caller identity, and the settlement of the calls a registration accepted. +- **Withdrawn namespaces.** The last row that held each namespace, so a call after a withdrawal answers `reloading` or `unavailable` instead of falling through to a parent namespace. +- **Reserved names.** The host's own roots, built-ins and management namespaces are refused at registration; the host supplies the check as a process face. +- **The method list.** The declarations of the namespaces registered now, each under its owning namespace. + +Callers keep: + +- What a method means: the registering part declares and implements its namespace. +- Routing: Rpc decides which table a wire name reaches and reads `sessionId` from the params. +- Client methods: Rpc serves `session.methods` and the built-ins; this table answers its own registrations. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A part publishes a namespace for its row's lifetime | No: the lifetime, the duplicate check and the reserved-name check are the owner's | `register` | +| Rpc dispatches one call to the namespace that holds it | No: the lookup, the caller identity, the interruption and the withdrawn-row answer are the owner's | `call` | +| `session.methods` lists what a Session serves | No: the declarations and the withdrawn-row rule are the owner's | `methods` | +| The caller checks that a namespace is free before registering | Yes: `register` answers `duplicate` or `reserved`; a pre-check races the next registration | Business | +| Rpc routes a name between management and Session | Yes: management answers its own `call`; Rpc reads `sessionId` | Business | +| A provider notifies its caller | Yes: the handler has the caller identity and uses `callChannel` (#2021) | Business | + +An operation or parameter exists only where the row says No. + +## Caller example + +A part registers from its `apply`; the registration belongs to that part's row: + +```rust +methods.register(RegisterNamespace { + namespace: "session.input".into(), + declarations, + call: Arc::new(|call, cancelled| Box::pin(withdraw(call, cancelled))), +}).await?; +``` + +Rpc dispatches one wire call; the caller identity is data, and the reply is `MethodReply` data: + +```rust +let reply = match table.call(CallRequest { + method: method.into(), + params, + caller: Some(CallerRef { connection_id, call_id }), +}).await { + Ok(reply) => reply, + Err(MethodError::UnknownMethod) => return Err(RpcError::unknown_method()), + Err(MethodError::Reloading) => return Err(RpcError::reloading()), + Err(MethodError::Unavailable) => return Err(RpcError::unavailable()), + Err(MethodError::Interrupted) => return Err(RpcError::interrupted()), + Err(MethodError::Invalid { .. }) => return Err(RpcError::invalid("Invalid request parameters")), +}; +``` + +`session.methods` composes the value with the management table: + +```rust +let Methods { methods } = table.methods().await?; +let listed = methods.into_iter().filter(|decl| !management.holds(&decl.name)).collect::>(); +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `P:reservedMethods` | The host's reserved names, consulted at registration; absent when the assembly serves no protocol. | +| The loader's row status (`rutis/loader`) | The withdrawn namespace's registering row, read when a call answers `reloading` or `unavailable`. | + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `register` | Publish a namespace for the calling row's lifetime | `{namespace, declarations, call}` | `{}` | None; the owner completes it | `reserved`, `duplicate`, `invalid` | +| `call` | Dispatch one call to the namespace that holds it | `{method, params, caller?}` | `{reply}` | The calling connection closing ends the call as interrupted; the provider's unload ends it by its declaration (`report` or `drain`) | `unknown_method`, `reloading`, `unavailable`, `interrupted`, `invalid` | +| `methods` | The declarations registered now | `{}` | `{methods}` | None | None | + +`caller` is `{connectionId, callId}`: the connection the call arrived on and the call id the reply ordering uses; absent for an in-process call. The table passes the caller identity to the handler unchanged and writes no socket. `call` is a callback by reference; it never runs inside the Timeline's commit lock. + +A handler's reply is `MethodReply` data: `{kind: "value", value}` or the handler's own error as `{code, message}`. The table adds no meaning. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `reserved` | The namespace or a name is the host's; pick another name | +| `duplicate` | The namespace is registered already; the row must not register twice | +| `invalid` | The namespace or a declaration is outside the grammar, or the request is malformed | +| `unknown_method` | No registered or withdrawn namespace holds the name; the client sees an unknown method | +| `reloading` | The registering row is starting or reloading; retry after it is Active | +| `unavailable` | The registering row failed or cannot run; the client sees the service as unavailable | +| `interrupted` | The provider unloaded while the call ran; the call may have committed, so read the current state before retrying | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `register` | Check the grammar, the reserved names and the duplicate, record the declarations and the callback under the row | — | The registration is withdrawn and its row recorded | New registrations are refused; the table reloads with the Session | The registering row | +| `call` | Find the owner, admit the call, run the callback, return the reply; on unload interrupt `report` and wait for `drain` | The connection's close ends the call as interrupted; the handler's own work settles by its own rule | The call ends; the registration's accepted calls settle | A withdrawn namespace answers from its row's status; a table reload ends in-flight calls | The table for admission and settlement; the handler for its effects | +| `methods` | Read the registered namespaces' declarations | — | Nothing to release | Pending reads answer from the state they observed | SessionMethods | + +## Exceptions with reasons + +- The table reads the loader's row status for a withdrawn namespace: the status is the mechanism's record of the registering row, not another business owner's state, and the table cannot answer `reloading` or `unavailable` without it. +- A handler's notifications are not written here: the caller identity is data and `callChannel` (#2021) addresses the connection by call id, so no connection, `Caller` or caller index crosses this owner. +- The table remembers the registering row per namespace: a withdrawn namespace must answer from that row rather than fall through to a parent namespace. + +## Verification + +Flow tests on the owner: + +- A registration lives until its row unloads; a duplicate namespace, a reserved name and a malformed declaration are refused; a refused registration fails the registering part. +- `call` reaches the longest namespace holding the name; a withdrawn namespace answers `reloading` while the row starts and `unavailable` once it failed; a name no namespace ever held is `unknown_method`. +- A `report` call interrupted by the provider's unload replies `interrupted` and the provider's unload waits for it; a `drain` call settles with its own result. +- The caller identity reaches the handler unchanged for a wire call and is absent for an in-process call; the handler's notification with the same call id is written by `callChannel`. +- `methods` lists the registered declarations and excludes nothing the table does not know; Rpc's filter removes management-held names. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the host's reserved names and reads the loader's row status. | +| §2 scopes | Session: the table serves one Session; a branch part registers a Session namespace through this table only when its feature places the part in the Session. | +| §3 orthogonality | No other owner's state is read or changed; the reserved names and the loader are the mechanism's faces. | +| §4 rule 1 | No command event: a registration is the calling row's effect. | +| §4 rule 2 | No handoff: the reply is data; the handler's work settles with its registration. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | Core and assembly carry no method-specific meaning; a namespace's contents are its part's. | +| §4 rule 5 | No batches. | +| §4 rule 6 | No context path: a method's reply reaches the client through Rpc. | +| §4 rule 7 | Callers use `register`, `call` and `methods`; no caller sees the table, a provider or a channel. | +| §4 rule 8 | No infrastructure change; the withdrawn-row answer is the loader's existing record. | +| §4 rule 9 | No Timeline fact. | +| §7 values, ids and callbacks | The caller identity is data; `call` is a callback by reference; a registration lives with its row; no object, channel or provider crosses. | +| §7 no proxy | The table answers its own registrations; the loader answers the row status. | +| §7 one interface | One name, `sessionMethods`, on the owner type; the Rust binding and the wire call the same methods; `SessionMethods` no longer derefs to a shared table type. | +| §7 cross-language | Every operation is data or a callback; no method exists only for Rust. | +| §7 one change | The implementation task deletes the old dispatch surface, adds these operations and migrates Rpc and every registering part in one change. | +| ADR 002 D1 | Session scope: namespaces belong to one Session's parts. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type; `ForeignMethods` leaves. | +| ADR 002 D3 | No dependency on providers; a failed row affects only its namespaces. | +| ADR 002 D4 | The namespace set is structural: parts bring their namespaces. | +| ADR 002 D5 | The contract is data; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +1. [#2021](https://github.com/arcships/dim/issues/2021): the Session table takes the same `call {method, params, caller?}` request and `{reply}` shape as ManagementMethods, so Rpc has one call path for both tables (already recorded by the Connection contract). +2. [#2021](https://github.com/arcships/dim/issues/2021): `reservedMethods` stays a process face; the Session table consults `check {namespace, declarations}` at registration. + +## Binding appendix + +The service is marked on `SessionMethods` under the wire name `sessionMethods`. `MethodTable`, `ForeignMethods` and the `SessionMethods` deref leave; the table's storage is private. `caller: &Ctx` is the rutis caller parameter the dispatch fills for `register`; `CancelledFn` is the binding's cancellation argument and is not a request field. + +```rust +use crate::host::CancelledFn; +use dim_agent_types::MethodReply; +use rutis::host::BoxFuture; +use rutis::Ctx; +use std::sync::Arc; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RegisterNamespace { + pub namespace: String, + pub declarations: Vec, + pub call: Arc BoxFuture<'static, Result> + Send + Sync>, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CallerRef { pub connection_id: String, pub call_id: String } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CallRequest { + pub method: String, + pub params: serde_json::Value, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub caller: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CallReply { pub reply: MethodReply } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Methods { pub methods: Vec } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum MethodError { + Reserved { message: String }, + Duplicate { message: String }, + Invalid { message: String }, + UnknownMethod, + Reloading, + Unavailable, + Interrupted, +} +``` diff --git a/docs/design/plugins/ShellInput.md b/docs/design/plugins/ShellInput.md index 7e82efb1c3..eaca1a8088 100644 --- a/docs/design/plugins/ShellInput.md +++ b/docs/design/plugins/ShellInput.md @@ -1,6 +1,168 @@ # ShellInput -Status: Implemented ([capability page](../../architecture/rust-agent/plugins/ShellInput.md)). Overall design: [overview §4](../overview.md#4-plugin-catalog). Phase: P1. Language: Rust. Scope: Session ([ADR 002](../../adr/002-plugin-scope.md)). Built on C1 ([#47](https://github.com/arcships/dim/issues/47), including per-call progress, [#125](https://github.com/arcships/dim/pull/125)) and S7 ([#52](https://github.com/arcships/dim/issues/52)) ([roadmap §3.3](../roadmap.md#33-插件开工顺序)). +Scope: session. Issue: #2026. + +ShellInput owns the operator's shell in the Session's workspace: `shell.run`, `shell.stop` and `shell.list`, the run table, and the `` entry that records a command's result. The current implementation is in `crates/dim-agent-capabilities/src/shell_input.rs`; the plugin page is [ShellInput](../../architecture/rust-agent/plugins/ShellInput.md). + +## Use and scope: responsibility split + +ShellInput owns: + +- **Runs.** One run id per accepted command, its output capture and its terminal record; a run ends when its command settles. +- **The shell.** Where a command runs, how its output is captured, and when a command is stopped. +- **The input it writes.** A command's result becomes an input on the line that asked, carrying the `` entry. +- **The Session's hold.** A running command holds the Session so an idle release does not end it. + +Callers keep: + +- When to run a command: the client calls the method. +- What a command means: the operator writes it. +- The line's other input: the line's InputQueue decides order and idempotency. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A client runs a command in the Session's workspace | No: the run table, the capture and the hold are the owner's | `shell.run` | +| A client stops a running command | No: the run's process tree is the owner's | `shell.stop` | +| A client lists the running commands | No: the run table is the owner's | `shell.list` | +| The command's result reaches the model | No: writing the input is the owner's; the line's queue decides the order | the same run operation | +| A command runs when the Session is closing | No: the phase check and the hold are the owner's | `shell.run` answers `closed` | + +An operation or parameter exists only where the row says No. + +## Caller example + +A client runs a command and later stops it: + +```rust +let RunReply { run_id, output_path } = shell.run(RunCommand { + branch_id: line.clone(), + command, + run_in_background: false, + timeout_ms: 30_000, +}, cancelled.clone()).await?; +shell.stop(StopRun { run_id }, cancelled).await?; +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `P:HostPlatform` | Home, shell, environment and process supervision. | +| `S:sessionConfig` | cwd, collaboration role and the shell preference. | +| `S:sessionScope` | `phase` and `withHold` for the command's extent. | +| `S:sessionIdentity` | The Session id in the entry and the output path. | +| `S:sessionMethods` | Register the `shell` namespace until this part unloads. | +| `S:guideEntries` | The `` entry, registered until this part unloads. | + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `shell.run` | Run one command and write its result as the line's input | `{branchId, command, runInBackground?, timeoutMs?}` | `{runId, outputPath?}` | The caller's token stops the command; the line's input is not written | `invalid`, `closed`, `cancelled` | +| `shell.stop` | Stop a running command | `{runId}` | `{}` | None; the stop settles | `invalid`, `closed` | +| `shell.list` | The commands running now | `{}` | `{runs}` | None | None | + +`branchId` is the line id. The result input is written to that line's input owner by id; the entry's text is registered with `guideEntries`. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid` | The command is empty, the run id is unknown, or the line id is malformed | +| `closed` | The Session or the line is closing; no command starts | +| `cancelled` | The command stopped before its result was written; the run's process tree is released | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `shell.run` | Check the phase, take the hold, spawn the command, capture, write the input, release the hold | The command stops; the input is not written; the hold is released | The command's process tree is released; the part's unload joins the runs | New runs are refused; running commands stop and settle | ShellInput for the run and the process tree; the line's queue for the input's order | +| `shell.stop` | Stop the run and settle it | Nothing | Nothing | Refused `closed` | ShellInput | +| `shell.list` | Read the run table | — | Nothing | Answers the state it observed | ShellInput | + +## Exceptions with reasons + +- The result input is written by this owner, not by the client: the command's output and the entry belong to the run, and the line's queue receives one input. +- A background command is not started here; the tool's background mode is `exec`'s, and ShellInput's runs are the operator's shell commands. +- The hold is taken before the spawn and released after the input commits: an idle release must not end the Session between the command and its result. + +## Verification + +- `shell.run` writes the result as one input on the named line; a cancelled run writes nothing and releases its process tree. +- `shell.stop` ends a running command; an unknown or ended run id is `invalid`; `shell.list` answers the running set. +- A Session closing before the spawn answers `closed`; a hold taken before the spawn keeps an idle release from ending the Session. +- The entry is registered at apply and its text reaches the model through the input. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part; it writes the line's input through the line's owner, not a Timeline event of its own. | +| §2 scopes | Session: the runs belong to the Session's workspace; the line is an id. | +| §3 orthogonality | No other owner's state is read; the line's queue is reached by id. | +| §4 rules 1–5, 9 | No command event, handoff, before callback, batch or Timeline fact of its own. | +| §4 rule 6 | The result reaches the model as the input this owner writes. | +| §4 rule 7 | Callers use the three methods; no caller reads the run table. | +| §4 rule 8 | No infrastructure change. | +| §7 values, ids and callbacks | The run id, the line id and the output path are data; no process handle crosses. | +| §7 no proxy | The line's queue answers its input; this owner answers its runs. | +| §7 one interface | One name, `shell`, on the method table; no wrapper. | +| §7 cross-language | The methods are data; no method exists only for Rust. | +| §7 one change | The implementation task replaces the `TreeCommands` line lookup with the line access in one change. | +| ADR 002 D1 | Session scope for the runs; the line's input is the line's. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | The part depends on HostPlatform and the Session scope. | +| ADR 002 D4 | No setting selects the shell; the Session's preference is read at use. | +| ADR 002 D5 | The contract is data. | + +## Requirements raised to mechanism owners + +1. [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025): the line access that lets this Session part write an input to the named line by `(session, line)` id. +2. [#2027](https://github.com/arcships/dim/issues/2027): the line's `inputQueue.submit` operation the result input is written through. + +## Binding appendix + +The `shell` namespace is registered with the method table; the handler is a callback. The run table is private. + +```rust +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RunCommand { + pub branch_id: String, + pub command: String, + #[serde(default)] + pub run_in_background: bool, + #[serde(default)] + pub timeout_ms: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RunReply { + pub run_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_path: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StopRun { pub run_id: String } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RunList { pub runs: Vec } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ShellError { + Invalid { message: String }, + Closed, + Cancelled, +} +``` + Executes `!command` and `!!command` typed by the user in the Session's working directory. The result of `!command` (the command and its bounded output) is written as an Append input, so it enters context with the next model request; the output of `!!command` goes only to the calling client. ShellInput is a Session plugin with no events. It provides `shell.run`, `shell.stop` and `shell.list` as ordinary Session methods by registering the namespace `shell` with its Session's `sessionMethods` ([session-boundary](../contracts/session-boundary.md)); contracts are language-neutral, and the Rust form is [Appendix G](#appendix-g-rust-binding). At most one command runs per Session. A command ends on its own, on `shell.stop`, or when the Session part ends (Session close, ShellInput or Session reload, App Server shutdown). While it runs it holds the Session, so a host's idle unload waits for it (§3.2). diff --git a/docs/design/plugins/ToolRegistry.md b/docs/design/plugins/ToolRegistry.md new file mode 100644 index 0000000000..0a156ce871 --- /dev/null +++ b/docs/design/plugins/ToolRegistry.md @@ -0,0 +1,300 @@ +# ToolRegistry + +Scope: session. Issue: #2026. + +ToolRegistry owns a Session's tool offerings: the host tools, the tools and dynamic sources parts register, the generation each request runs, and the source status other parts observe. The current implementation is described in the [ToolRegistry plugin page](../../architecture/rust-agent/plugins/ToolRegistry.md). ToolBinding, ToolExecutor, Loop and the contributors are callers; their contracts are #2027, #2028 and their own. + +## Use and scope: responsibility split + +ToolRegistry owns: + +- **The host tool table.** The tools the host offers this Session, read once from the host tools owner when the registry applies. +- **Registrations.** One tool or one dynamic source per registering row, with its declaration, its execute callback, its optional claim callback and its versions; a registration ends when its row unloads. +- **Generations.** A source publishes complete sets under never-reused version ids; the registry adopts, rejects and withdraws whole sets, and keeps the versions a live adoption names. +- **Adoption.** The generation one request's prefix runs: the declarations it declares and the source versions it names. An adoption is an id bound to the adopting row. +- **The claim before the fact.** The pre-publish registration a call needs, keyed by `(request, call)`, routed to the contributor that claimed it, released when the request abandons the call or the row unloads. +- **The mount list.** `SessionConfig.tools` decides which host and registered tools are declared, fixed at creation. +- **The source status view.** Each source key's adopted version or rejection, published as a value and a subscription. + +Callers keep: + +- What a tool does: its declaration, schema, risk and execution, inside the contributor's part. +- Which tools a request declares: the adopted configuration carries them; the branch keeps the adoption id. +- Approval and permission: ToolExecutor and Permission decide; the registry decides nothing about whether a call may run. +- Result facts: ToolExecutor records them; the registry returns the result unchanged. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A part publishes one tool for its row's lifetime | No: the registration's lifetime, the name and declaration checks and the host-name reservation are the owner's | `register` | +| A dynamic source publishes a complete set under a new version | No: version uniqueness, whole-set validation and atomic replacement are the owner's | `register_source` | +| A request prefix fixes the generation it runs | No: resolving versions, checking every declared tool has a handler, and keeping the generation alive until release are the owner's | `adopt`, `release` | +| The branch executes one call of a request | No: the tool's owner runs it and the handler never leaves the registry; a caller holding the handler would carry the contributor's object | `run` | +| The branch resolves a write target before approval | No: only the owner knows which generation the request adopted and which handler answers | `resolve_write` | +| The branch orders a call within its batch | No: the class is a property of the adopted handler | `ordering` | +| A call needs a registration before `step/tool-call` and none if it never dispatches | No: the claim must exist before the fact and be released on every abandon path; composing it makes each caller hold the contributor's entry | `claim`, `release_claims` | +| A context fingerprint reads the current declarations and versions | No: both are the owner's state | `declarations` | +| A management view observes adopted and rejected versions | No: the status is the owner's | `sources`, `observe_sources` | +| Which tools a request declares | Yes: the adopted configuration is a value; the branch passes its source versions to `adopt` | Business | +| Approve, deny or cancel a call | Yes: ToolExecutor, Permission and Approval decide | Business | + +An operation or parameter exists only where the row says No. + +## Caller example + +A part registers a tool and, for `ask_user`, a claim callback; the registration lives with the part's row: + +```rust +registry.register(RegisterTool { + declaration: ask_user_definition(), + execute: Arc::new(|call, context, cancelled| Box::pin(run_ask_user(call, context, cancelled))), + claim: Some(Arc::new(|call, context| claim_question(call, context))), // inserts the waiter; no object comes back +}).await?; +``` + +The branch fixes a request's generation and runs one of its calls: + +```rust +// Sources are the configuration's versions; the owner resolves them and checks every declared tool. +let Adoption { adoption } = registry.adopt(AdoptRequest { + tools: settings.tools.clone(), + sources: settings.tool_sources.clone(), +}).await?; +// ... +let result = registry.run(RunCall { + adoption: adoption.clone(), + call: ToolCall { id, name, input }, + caller: ToolExecutionContext { turn_id, request_id, branch_id }, +}, cancelled.clone()).await?; +// A refusal or a bad call is a ToolResult; only the kinds below reach this caller. +``` + +Before the call is published, Loop claims it and ToolExecutor releases nothing on the normal path: + +```rust +let claimed = registry.claim(ClaimCalls { request: request_id.clone(), calls: calls.clone() }).await?; +// A refused append, an interrupt before dispatch, a refused admission or a Loop error: +registry.release_claims(ReleaseClaims { request: request_id.clone(), calls }).await?; +``` + +A context fingerprint and a management view read values: + +```rust +let Declarations { tools, sources } = registry.declarations().await?; +let status = registry.sources().await?; // adopted or rejected per source key +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `S:toolHost` | The host tools owner: declarations, execute, write-target resolution and ordering for the host's tools. | +| `S:sessionConfig` | The mount list and the excluded names, fixed at creation. | +| `S:sessionIdentity` | The Session id in a foreign tool's neutral call and the attach span. | +| `S:sessionScope` | `activated` and `closing`: the refresh task starts at publication and ends when close starts. | + +The registry provides `toolRegistry` on its owner type and nothing else; `toolSourcesView` leaves the catalog and its value is `sources`/`observe_sources` on the same face. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `register` | Publish one tool for the calling row's lifetime | `{declaration, execute, claim?}` | `{}` | None; the owner completes it | `invalid`, `closed` | +| `register_source` | Publish a dynamic source the calling row owns | `{name, source}` | `{}` | None | `invalid`, `closed` | +| `adopt` | Fix the generation a request prefix runs | `{tools, sources}` | `{adoption}` | None; the owner completes it | `invalid`, `unavailable`, `closed` | +| `release` | Stop keeping an adoption's versions before the row unloads | `{adoption}` | `{released}` | None | `invalid`, `closed` | +| `run` | Run one call of an adopted generation | `{adoption, call, caller}` | `{result}` | The caller's token stops the call; the tool's own settlement stays with its contributor | `invalid`, `unavailable`, `cancelled`, `closed` | +| `resolve_write` | Resolve a write's target without effects, before admission | `{adoption, call}` | `{call}` | The caller's token stops the resolution | `invalid`, `unavailable`, `cancelled`, `closed` | +| `ordering` | The class deciding whether the call shares its step | `{adoption, call}` | `{class: "concurrent" \| "exclusive"}` | None | `invalid`, `unavailable`, `closed` | +| `claim` | Make the calls' pre-publish registrations exist before `step/tool-call` | `{request, calls}` | `{claimed: [callId]}` | None; the owner completes it | `invalid`, `closed` | +| `release_claims` | Drop the claims a request never dispatched | `{request, calls}` | `{}` | None | `invalid`, `closed` | +| `declarations` | The current declarations and source versions | `{}` | `{tools, sources}` | None | None | +| `sources` | Each source key's adopted version or rejection | `{}` | `{sources}` | None | None | +| `observe_sources` | The status now and on each change until the row unloads | `{listener}` | `{}` | The row's unload ends the subscription | `closed` | + +`execute`, `claim` and `listener` are callbacks by reference; they run outside the registry's locks and outside the Timeline's commit lock. `caller` is `{turnId, requestId, branchId}` data, not an object. A `ToolResult` a contributor returns is data and is returned unchanged; the tool's own failure is `isError`, not an owner error. + +An adoption id and a claim's `(request, call)` entry are bound to the calling row: the row's unload releases them, so a caller that loses the id leaks nothing. `release` and `release_claims` only free them sooner. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid` | Fix the input: a name outside `[A-Za-z0-9_-]{1,64}`, a host tool's name, a name registered already, a declaration without a risk or with an unknown field, a declared tool with no handler or a changed definition, an unknown adoption, request or claim | +| `unavailable` | The adopted source version is no longer this owner's; re-read the configuration and adopt again | +| `cancelled` | Nothing ran; the call stopped before the tool or the resolver started | +| `closed` | This Session is closing or this generation is unloading; a follow-up decision waits for the replacement generation | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `register`, `register_source` | Validate, record under the row, offer from the next read | — | The registration is withdrawn and its sets stop being offered | New registrations are refused; the task ends at `closing` | The registering row | +| `adopt` | Resolve every source version, check every declared tool, record the adoption under the row, answer the id | — | The row's adoptions are released with the row | New adoptions are refused; existing ones keep their versions until released | ToolRegistry | +| `run` | Resolve the adoption, pick the tool's handler, call it with the caller data and a child token, return the result | The child token fires; the contributor settles its own work | The call ends; the contributor's row unload settles it by the contributor's rule | New calls are refused; in-flight calls end `closed` or with the contributor's settlement | ToolRegistry for admission and the adoption; the contributor for its work | +| `resolve_write`, `ordering` | Resolve the adoption and ask the handler | The resolution stops | The call ends | Refused `closed` | ToolRegistry | +| `claim` | Route each call to its tool's claim callback, record the contributor per `(request, call)`, answer the claimed ids | — | The row's claims are released with the row | New claims are refused; recorded claims are released | ToolRegistry for the record; the contributor for the pending entry | +| `release_claims` | Route the release to the contributor recorded for each call, drop the record | — | Nothing left to release | A release for an unloaded contributor is a no-op | ToolRegistry | +| `observe_sources` | Register the listener under the row and call it with the current status | The row's unload ends the subscription | The subscription ends; the callback's future is revoked | The listener stays until the generation unloads | ToolRegistry | + +## Exceptions with reasons + +- The tool's handler, declaration and claim callbacks are the contributor's code. The registry holds them under the contributor's row and never hands them out; a request names an adoption, not a handler. +- A tool's own failure crosses as the `ToolResult` the contributor returns; the registry adds no error kind for it, and the caller reads `isError` and the content. +- A host tool's declaration is read once when the registry applies: the host tools owner's table is fixed for the Session, and a host tools reload reloads the registry with it. +- A foreign tool's execute callback holds the calling row's generation: a call after that row starts unloading is not made, and a call in flight ends with the contributor's reload message. + +## Verification + +Flow tests on the owner: + +- A registration lives until its row unloads; a duplicate name, a host tool's name and an invalid declaration are `invalid`; a foreign declaration without a risk is `invalid`. +- `adopt` refuses a tool with no handler and a source version the owner no longer holds; a released adoption's versions stop being kept; a branch row's unload releases its adoptions. +- `run` uses the adopted generation after the source publishes a newer one; a call whose contributor unloaded ends with the contributor's message; cancelling the call ends it `cancelled`. +- `claim` records each claiming contributor before the append; `release_claims` after a refused append leaves no entry; a dispatched call's entry lives until the answer or the cancel; a contributor's unload removes its entries. +- `declarations` and `sources` answer the current state; `observe_sources` delivers the current status and later changes; the row's unload ends the subscription. +- A call in flight when the Session starts closing ends `closed`; the refresh task starts at `activated` and ends at `closing`. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part. It writes no Timeline fact and folds none, so it is not a Capability. It injects the host tools owner, the creation record and the Session scope. | +| §2 scopes | Session: the tool table and the adoptions belong to one Session; the branch's executor calls by adoption id and keeps no handler. | +| §3 orthogonality | No other owner's state is read or changed. A contributor that needs a new tool shape extends its own declaration; a caller that needs a new read asks here. | +| §4 rule 1 | No command event: a registration is the calling row's effect, not a Timeline fact. | +| §4 rule 2 | No handoff of a call: the registry routes the call and returns the result; ToolExecutor keeps the result's facts. | +| §4 rule 3 | No before callback: `execute`, `claim` and `listener` run outside the commit lock. | +| §4 rule 4 | Core and assembly carry no tool-specific meaning; a tool's declaration and result format are the contributor's. | +| §4 rule 5 | No batches: the registry adds no Timeline write. | +| §4 rule 6 | Declarations reach the model through the adopted configuration; results through ToolExecutor. The registry adds no context path. | +| §4 rule 7 | Callers use the operations; no caller reads the table, a version or a handler. | +| §4 rule 8 | No infrastructure change; the registration lifetime is the caller row's effect and the scope's wait is `sessionScope`. | +| §4 rule 9 | No Timeline fact; the source status is memory, read live. | +| §7 values, ids and callbacks | A registration, adoption, claim and status cross as data or ids; `execute`, `claim` and `listener` are callbacks by reference; no handler, set or provider object crosses. | +| §7 no proxy | The registry answers its own table and adoption; it does not answer another owner's declaration or result. | +| §7 one interface | One name, `toolRegistry`, on the owner type; `toolSourcesView` leaves the catalog; the Rust binding and the wire call the same methods. | +| §7 cross-language | Every operation is data, a callback or an id; no method exists only for Rust. | +| §7 one change | The implementation task deletes the old surface, adds these operations and migrates every caller in one change. | +| ADR 002 D1 | Session scope: the table, versions and adoptions live with one Session. | +| ADR 002 D2 | No wiring plugin: the operations are on the owner type; no `ForeignRegistry` wrapper remains. | +| ADR 002 D3 | A registration follows its part's lifetime; the registry depends on no contributor. | +| ADR 002 D4 | The mount list is structural; a business setting never selects tools. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +1. **A tool call's claim needs one shared lifecycle.** The claim's owner is the contributor whose tool needs it; the branch's request record holds the `(request, call)` ids it claimed and owes a release on every path that does not dispatch; the tool table routes `claim`/`release_claims` by tool name and records the claiming contributor until release. Publish order is claim before `step/tool-call`; the transfer happens when ToolExecutor takes the call from the batch; the contributor's pending entry ends at the answer, the call's cancel or its own unload; the branch's release ends only the claims that never dispatched. This is one contract across the tool table, Questions and the branch request; it is stated here because the table is the directory that makes the routing possible. +2. [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025): the line mechanism `(session, line)` a Session part uses to reach a line owner's operation by id. The tool parts that act on the calling line use it; this owner does not. + +## Binding appendix + +The service is marked on `ToolRegistry` under the wire name `toolRegistry`. `ForeignRegistry`, the `ToolHost` wrapper and `ToolSourcesView` leave the catalog; the host tools owner's operations stay under `toolHost`. `caller: &Ctx` is the rutis caller parameter the dispatch fills for `register`/`register_source`; `CancelledFn` is the binding's cancellation argument and is not a request field. + +```rust +use crate::host::CancelledFn; +use dim_agent_types::{ToolCall, ToolDefinition, ToolExecutionContext, ToolResult}; +use rutis::host::BoxFuture; +use rutis::Ctx; +use std::sync::Arc; +use tokio_util::sync::CancellationToken; + +pub type AdoptionId = String; + +pub type ExecuteFn = Arc< + dyn Fn(ToolCall, ToolExecutionContext, CancelledFn) -> BoxFuture<'static, Result> + + Send + + Sync, +>; +pub type ClaimFn = Arc< + dyn Fn(&ToolCall, &ToolExecutionContext) -> BoxFuture<'static, Result> + Send + Sync, +>; +pub type LoadSetFn = Arc< + dyn Fn() -> BoxFuture<'static, Result, String>> + Send + Sync, +>; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RegisterTool { + pub declaration: ToolDefinition, + pub execute: ExecuteFn, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub claim: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RegisterSource { pub name: String, pub source: LoadSetFn } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdoptRequest { pub tools: Vec, pub sources: Vec } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Adoption { pub adoption: AdoptionId } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RunCall { + pub adoption: AdoptionId, + pub call: ToolCall, + pub caller: ToolExecutionContext, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RunReply { pub result: ToolResult } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClaimCalls { pub request: String, pub calls: Vec } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Claimed { pub claimed: Vec } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReleaseClaims { pub request: String, pub calls: Vec } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Declarations { + pub tools: Vec, + pub sources: Vec, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SourceStatus { + pub adopted: Option, + pub rejected: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SourcesReply { pub sources: std::collections::BTreeMap } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ObserveSources { pub listener: Arc BoxFuture<'static, ()> + Send + Sync> } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ToolSourceRejection { /* {version, reason} as today */ } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum OrderClass { Concurrent, Exclusive } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ToolError { + Invalid { message: String }, + Unavailable { message: String }, + Cancelled, + Closed, +} +``` diff --git a/docs/design/plugins/Wait.md b/docs/design/plugins/Wait.md new file mode 100644 index 0000000000..150be2902e --- /dev/null +++ b/docs/design/plugins/Wait.md @@ -0,0 +1,158 @@ +# Wait + +Scope: session (the tool) and branch (the arrival owner). Issue: #2026. + +Wait owns the model's wait: the `wait` tool and the branch's arrival table. The current implementation is described in the [Wait plugin page](../../architecture/rust-agent/plugins/Wait.md). The tool is a Session part; the arrival table is a branch Capability (#2027's scope) reached by line id. + +## Use and scope: responsibility split + +Wait owns: + +- **The arrival table.** Per line, the inputs that can end a wait (a background task's notice, a steer, a line's own events) from their release until the model reads them, and the single-wait slot. +- **One wait.** From the call to the first matching arrival, the timeout or the cancellation. +- **The tool declaration.** Its schema and result kinds. + +Callers keep: + +- When to wait: the model decides. +- What a task id means: BackgroundExec and Collaboration own their tasks. +- The notice's text: the producers write it; the arrival table records only that it arrived. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| The model waits on its line for a matching arrival | No: the arrival table, the single slot and the reload rule are the owner's | `wait` | +| The model asks for one task or any arrival | Yes: the same operation with an optional task id | Business | +| A second wait runs beside the first | No: the single-wait slot is the owner's | `wait` answers `busy` | +| Read what already arrived | Yes: `wait` with a zero or small timeout answers the arrival at once, or the notice in the model's context | Business | + +An operation or parameter exists only where the row says No. + +## Caller example + +The tool runs on the calling line and waits there: + +```rust +let line = execution.branch_id; // the line id the call carries +let WaitReply { ended } = line_owner::(line)?.wait(WaitRequest { + task_id, + timeout_ms: 300_000, +}, cancelled.clone()).await?; +match ended { + Ended::Notification { task_ids, waited_ms } => result_text(task_ids, waited_ms), + Ended::Steer { waited_ms } => result_text_steer(waited_ms), + Ended::AlreadyNotified { task_ids, waited_ms } => already(task_ids, waited_ms), + Ended::Timeout { waited_ms } => timed_out(waited_ms), + Ended::Interrupted { waited_ms } => interrupted(waited_ms), +} +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `B:dispatcher` | Consume `input/message`, `turn/start` and `turn/end` in order and record arrivals. | +| `B:timeline` | Read the line's own facts at the branch's cut; commit no fact from here. | +| `B:timelineIdentity` | Name the line this table belongs to. | + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `wait` | Wait on this line for a matching arrival, the timeout or the cancellation | `{taskId?, timeoutMs?}` | `{ended}`: `notification {taskIds, waitedMs}`, `steer {waitedMs}`, `alreadyNotified {taskIds, waitedMs}`, `timeout {waitedMs}`, `interrupted {waitedMs}` | The caller's token ends the wait as `interrupted` and releases the slot; a dropped Rust future releases the slot | `busy`, `cancelled`, `closed` | + +`timeoutMs` is 1 through 300,000, default 300,000. The slot is single: a second wait on the same line answers `busy` until the first ends or its caller drops it. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `busy` | A wait is running on this line; end it or retry after it ends | +| `cancelled` | The call stopped before any arrival; nothing was consumed | +| `closed` | The line is ending or the table is unloading; wait on the replacement generation | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `wait` | Take the slot, return an already-arrived match, otherwise wait for a release, the timeout or the token | The token ends the wait `interrupted` and releases the slot; the arrival stays recorded | The dropped call releases the slot; the arrival stays for a later wait or read | The generation's unload ends an accepted wait `closed`; the arrivals are rebuilt from the line's facts | Wait for the slot and the result; the caller for its dropped future | + +## Exceptions with reasons + +- An arrival taken by a wait stays recorded: a later read of the same notice in the turn is told it was already delivered, so a wait never consumes the model's only copy. +- A branch close cancels a wait without a wake: the line is ending, and the model's next turn is on another line. +- The table folds the line's own facts at open: wait has no persistent state of its own, and the branch rebuilds the same arrivals after a reload. + +## Verification + +- A wait ends on the matching completion, not on the input that started the turn; a steer or a stop ends it; a second wait answers `busy`. +- A notice the model already read does not end a later wait; the wait answers `alreadyNotified`. +- Cancelling a wait ends it `interrupted` and releases the slot; dropping the future releases the slot. +- An arrival recorded before the call is answered at once; a reload rebuilds the arrivals from the line's facts. +- The line's end ends a wait with `closed` and no wake. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | The tool is a Session part, not a Capability; the arrival table is a branch Capability: it folds the line's facts in order and writes none. | +| §2 scopes | The tool is Session; the table is branch; the tool reaches the table by line id. | +| §3 orthogonality | No other owner's state is read; the task ids are values. | +| §4 rules 1–5, 9 | No command event, handoff, before callback, batch or Timeline fact from the table. | +| §4 rule 6 | The wait's result reaches the model as the tool result; notices reach it as inputs their producers write. | +| §4 rule 7 | The tool calls the table's operation; no caller reads the arrivals. | +| §4 rule 8 | No infrastructure change. | +| §7 values, ids and callbacks | The request and result are data; task ids and the line id are values; the cancellation is an argument; no object crosses. | +| §7 no proxy | The table answers its own arrivals; the tasks belong to their owners. | +| §7 one interface | One name, `wait`, on the branch owner; the Session tool only registers. | +| §7 cross-language | The operation is data; no method exists only for Rust. | +| §7 one change | The implementation task migrates the tool off `TreeCommands` in one change. | +| ADR 002 D1 | Branch scope for the arrivals; Session for the tool. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | The tool depends on the line's table by id, not on the table's implementation. | +| ADR 002 D4 | The timeout default is the owner's; no setting. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +1. [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025): the line access that lets the Session tool reach the line's `wait` by `(session, line)` id; the current call takes it from `TreeCommands.get(line)?.service::()`. + +## Binding appendix + +The service is marked on `Wait` under `wait`. `caller: &Ctx` fills the line identity; `CancelledFn` is not a request field. + +```rust +use crate::host::CancelledFn; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WaitRequest { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub task_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub timeout_ms: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(tag = "reason", rename_all = "snake_case", rename_all_fields = "camelCase")] +pub enum Ended { + 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(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WaitReply { pub ended: Ended } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WaitError { + Busy { message: String }, + Cancelled, + Closed, +} +``` diff --git a/docs/design/plugins/WorkspaceTools.md b/docs/design/plugins/WorkspaceTools.md new file mode 100644 index 0000000000..4fadc9ca49 --- /dev/null +++ b/docs/design/plugins/WorkspaceTools.md @@ -0,0 +1,205 @@ +# WorkspaceTools + +Scope: session (WorkspaceTools), process (WorkspaceToolsOwner, MentionIndex). Issue: #2026. + +WorkspaceTools owns the Session's host tools: `read`, `write`, `edit`, `glob`, `grep`, `exec` and `exec_stop`, the method namespaces that read their output, and the process owner that holds the mention index and the file-write coordinator. The current implementation is described in the [WorkspaceTools plugin page](../../architecture/rust-agent/plugins/WorkspaceTools.md). FileReads and BackgroundExec are branch owners (#2028); their calls appear only as requirements. + +## Use and scope: responsibility split + +WorkspaceTools owns: + +- **The host tool table.** The declarations of the seven tools and their execution, with the Session's cwd, output directory and boundaries. +- **File I/O.** Reads, globs, greps, the staged write and edit replacements, and the per-path write admission the owner keeps across Sessions and generations. +- **Command execution.** Foreground commands and their process trees; a command handed to the background is BackgroundExec's (#2028). +- **Output registration.** An output path a result gives the model is registered with the Session's file owner before the result leaves (#2018). +- **The mention index.** One process-wide walked directory index, shared by the Session search and the management search, reused for ten seconds per root. +- **The four method namespaces.** `session.files`, `session.exec.pending`, `session.exec.finished`, `session.exec.output` and `.page`. + +Callers keep: + +- Approval and permission: ToolExecutor and Permission decide; the host tools never decide whether a call may run. +- Which branch state a file call needs: FileReads and BackgroundExec own it; this owner reaches the line by id. +- The model-facing text: declarations are this owner's, their policy sentences are judged by #2027's rule. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| The tool table reads the host tools' declarations | No: the declarations are built from the Session's configuration | `declarations` | +| The branch executes one host tool call | No: the process tree, the write admission and the output handoff are the owner's | `execute` | +| The branch resolves a write target before admission | No: path resolution and the boundary are the owner's | `resolve_write` | +| The branch orders a call within its batch | No: the class is a property of the call's tool | `ordering` | +| A client reads the files an `@` mention offers | No: the walked index and its freshness are the owner's | `search` | +| A client reads a line's command output | No: the output file is registered by the line's BackgroundExec | `session.exec.output` reached by line id | +| Register an output path with the Session's file owner | Yes: the tool does it before returning | Business inside the owner | + +An operation or parameter exists only where the row says No. + +## Caller example + +ToolRegistry injects the host tools owner and reads the table at apply: + +```rust +let Declarations { tools } = host.declarations().await?; +for definition in tools { registry.register(HostTool { definition, host: host.clone() }).await?; } +``` + +The registry runs a host tool call, and resolves a write target before admission: + +```rust +let RunReply { result } = host.execute(ExecuteTool { call, caller }).await?; +let Resolved { call } = host.resolve_write(ResolveWrite { call }).await?; +let OrderReply { class } = host.ordering(OrderCall { call }).await?; +``` + +A client searches, and the Session part reads its own line's task: + +```rust +let SearchReply { candidates } = index.search(SearchFiles { root, query, limit }).await?; +let ExecOutput { text } = line_owner::(line)?.output(task_id).await?; +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `P:HostPlatform` | Home, shell, environment and process supervision. | +| `S:sessionConfig` | cwd, collaboration role and the Session's output directory. | +| `S:sessionIdentity` | The Session id for the output directory and the search root. | +| `S:sessionScope` | `activated`/`closing` for the tool generation and `hold` for a running background task. | +| `S:sessionMethods` | Register the four method namespaces until the part unloads. | +| `P:mentions` | The process owner's walked index. | +| `P:sessionFiles` | Register an output path with the Session's file owner. | + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `declarations` | The host tools' declarations for this Session | `{}` | `{tools}` | None | None | +| `execute` | Run one host tool call | `{call, caller}` | `{result}` | The caller's token stops the command or the call; a finished file write is not undone | `invalid`, `cancelled`, `closed` | +| `resolve_write` | Resolve a write or edit target without effects, before admission | `{call}` | `{call}` | The caller's token stops the resolution | `invalid`, `cancelled`, `closed` | +| `ordering` | The class deciding whether the call shares its step | `{call}` | `{class: "concurrent" \| "exclusive"}` | None | `invalid`, `closed` | +| `search` | The files an `@` mention offers under one root | `{root, query, limit?}` | `{candidates: [{relativePath, absolutePath, dir}]}` | The caller's token stops the search; the walk ends at its budget | `invalid`, `cancelled`, `closed` | +| `session.files.search` | The Session's own workspace search | `{sessionId, query, limit?}` | `{candidates}` | The caller's token | `invalid`, `cancelled`, `closed` | +| `session.exec.pending` | A line's pending commands | `{sessionId, branchId}` | `{pending}` | None | `invalid`, `closed` | +| `session.exec.finished` | A line's recently finished commands | `{sessionId, branchId}` | `{finished}` | None | `invalid`, `closed` | +| `session.exec.output` | A task's bounded live tail | `{sessionId, branchId, taskId}` | `{text}` | None | `invalid`, `missing`, `closed` | +| `session.exec.output.page` | One page of a task's registered output file | `{sessionId, branchId, taskId, cursor, limit?}` | `{text, bytes, nextCursor?, truncated}` | The caller's token | `invalid`, `missing`, `unavailable`, `closed` | + +`caller` is `{turnId, requestId, branchId}` data. `session.files.search` and the management `workspace.files.search` call the same `search` with the same index; the management entry supplies its own root and the Session entry supplies the Session's cwd. Paths cross as UTF-8 strings. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid` | The call names no host tool, the root is not an absolute existing directory, the task id or cursor is malformed, or the write target cannot be resolved | +| `missing` | The task is not known on this line; list the line's tasks | +| `unavailable` | The task's output file is gone; treat the output as unavailable | +| `cancelled` | The call stopped before its effect; nothing was written or started | +| `closed` | This Session or line is closing; a later generation serves the next Session | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `execute` | Resolve cwd and boundary, run or write, register the output path, return the result | The process tree or the write stops; a published write stays | The call ends; a background handoff settles with BackgroundExec | New calls are refused; in-flight calls end `closed`; running commands of the part stop | WorkspaceTools for the call and the process tree; BackgroundExec for a handed-off command | +| `resolve_write` | Resolve the path against the boundary, answer the call | The resolution stops | Nothing to release | Refused `closed` | WorkspaceTools | +| `ordering` | Read the call's tool class | — | Nothing | Refused `closed` | WorkspaceTools | +| `search` | Walk or reuse the root's index, rank, answer UTF-8 paths | The search stops; the walk is the owner's and ends at its budget | Nothing to release | Refused `closed` | WorkspaceToolsOwner | +| `session.exec.output*` | Resolve the line, ask its BackgroundExec | The read stops | Nothing | Answers by the line's state | BackgroundExec | + +## Exceptions with reasons + +- A file write publishes before its result is returned: a cancel after the replace leaves the file changed and the result says so; the declaration on the result is the fact consumers read. +- The output path is registered with `sessionFiles` before the result leaves: a registration failure fails the call, so the model never receives an unowned path. +- A collaboration member keeps commands in the foreground: the leader treats a member's idle as the end of a request, so a background command would finish after its result. +- The file-write coordinator outlives the part and every Session it serves: old calls settle in the domain new ones enter. + +## Verification + +- The declarations match the Session's cwd, boundary and mount list; a call in flight when the part unloads ends `closed`. +- `execute` runs each tool, registers an output path before returning, and hands a background command to the line's BackgroundExec by id. +- `resolve_write` answers the same call with an absolute canonical path and writes nothing. +- The Session search and the management search share one walk; a file written after a walk is not offered until the next walk; paths are UTF-8 strings. +- `session.exec.output` answers a live task's tail and `missing` for an ended or unknown task; `.page` reads the registered file by cursor. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part and one process owner; neither writes a Timeline fact, so neither is a Capability. BackgroundExec is the branch Capability (#2028). | +| §2 scopes | The tools, the output directory and the methods are Session; the index and the write coordinator are process; branch state is reached by line id. | +| §3 orthogonality | No other owner's state is read; the line's owners are reached by id. | +| §4 rules 1–5, 9 | No command event, handoff, before callback, batch or Timeline fact of this owner. | +| §4 rule 6 | Results reach the model through ToolExecutor; this owner adds no context path. | +| §4 rule 7 | Callers use these operations; no caller reads the table or the coordinator. | +| §4 rule 8 | No infrastructure change; HostPlatform's shape is #2032's. | +| §7 values, ids and callbacks | Declarations, calls and results are data; the line and the task are ids; the index hands out candidates, not handles. | +| §7 no proxy | The Session search and the management search both call this owner's `search`; the App Server does not copy the index. | +| §7 one interface | `toolHost` is marked on the host tools owner; `ToolHost`/`ToolDriver` wrappers leave; the methods stay on `sessionMethods`. | +| §7 cross-language | Every operation is data; no method exists only for Rust. | +| §7 one change | The implementation task deletes the wrappers and the `TreeCommands` lookups and migrates every caller in one change. | +| ADR 002 D1 | Session scope for the tools; process for the shared index and the write coordinator. | +| ADR 002 D2 | No wiring plugin: the operations are on the owners' types. | +| ADR 002 D3 | The host tools are the core; FileReads and BackgroundExec are branch owners they reach by id. | +| ADR 002 D4 | The boundary and the coordinator are assembly configuration, not business settings. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +1. [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025): the line access that lets this Session part reach FileReads and BackgroundExec by `(session, line)` id. The file tools need the line's read bindings and `exec` needs the line's background owner; neither may be taken from a `Branch` object. +2. [#2028](https://github.com/arcships/dim/issues/2028): FileReads' binding operation and BackgroundExec's start/output/wait operations, reached by line id; the current calls take them from `TreeCommands.get(line)?.service::()`. +3. [#2018](https://github.com/arcships/dim/issues/2018): `sessionFiles.register` and the read/write operations the output and attachment paths use. + +## Binding appendix + +The service is marked on the host tools owner under `toolHost`. `ToolHost` and `ToolDriver` no longer exist; `ToolDriver`'s declarations, resolution and ordering become operations on the owner. `caller: &Ctx` fills the Session's identity for the tools; `CancelledFn` is not a request field. + +```rust +use crate::host::CancelledFn; +use dim_agent_types::{ToolCall, ToolDefinition, ToolExecutionContext, ToolResult}; +use rutis::host::BoxFuture; +use rutis::Ctx; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeclarationsReply { pub tools: Vec } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ExecuteTool { pub call: ToolCall, pub caller: ToolExecutionContext } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RunReply { pub result: ToolResult } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ResolveWrite { pub call: ToolCall } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Resolved { pub call: ToolCall } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchFiles { pub root: String, pub query: String, pub limit: Option } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Candidate { pub relative_path: String, pub absolute_path: String, pub dir: bool } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchReply { pub candidates: Vec } + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ToolHostError { + Invalid { message: String }, + Missing { message: String }, + Unavailable { message: String }, + Cancelled, + Closed, +} +``` From 5017cee339daeb471d85abc2fac779d5a9a20936 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 15:17:43 +0800 Subject: [PATCH 02/10] docs(design): align operation names with the sibling contracts Refs #2026, Refs #2015. --- docs/design/plugins/Attachments.md | 2 +- docs/design/plugins/InputMethods.md | 47 +++---- docs/design/plugins/PromptSources.md | 8 +- docs/design/plugins/PromptSuggestion.md | 8 +- docs/design/plugins/Questions.md | 2 +- docs/design/plugins/ShellInput.md | 4 +- docs/design/plugins/ToolRegistry.md | 4 +- docs/design/plugins/Wait.md | 156 +++++++++--------------- docs/design/plugins/WorkspaceTools.md | 6 +- 9 files changed, 96 insertions(+), 141 deletions(-) diff --git a/docs/design/plugins/Attachments.md b/docs/design/plugins/Attachments.md index ce15e2fa9b..f95f3afdeb 100644 --- a/docs/design/plugins/Attachments.md +++ b/docs/design/plugins/Attachments.md @@ -51,7 +51,7 @@ let ReadReply { data, eof } = attachments.read(ReadAttachment { | Service | Purpose | | --- | --- | -| `S:sessionIdentity` | The calling Session's id for the ownership check. | +| `S:sessionScope` | `identity` for the calling Session's id, used by the ownership check. | | `P:sessionFiles` | The Session file store's `put`, `import` and `read` operations (#2018). | | `S:sessionMethods` | Register the `attachment` namespace until this part unloads. | diff --git a/docs/design/plugins/InputMethods.md b/docs/design/plugins/InputMethods.md index be849ab929..20964b0af3 100644 --- a/docs/design/plugins/InputMethods.md +++ b/docs/design/plugins/InputMethods.md @@ -15,16 +15,16 @@ InputMethods owns: Callers keep: - What a check means: Hooks and Skills decide; a check that fails is no opinion. -- When input is written: the operator-entry paths call `prepare` and write the result; the line's queue decides order, idempotency and withdrawal. +- When input is written: the operator-entry paths call `check` and write the returned input; the line's queue decides order, idempotency and withdrawal. - The line an input belongs to: the caller names the line id. | Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | | A part checks operator input for its row's lifetime | No: the duplicate check and the row's lifetime are the owner's | `register` | -| An entry turns a candidate input into the input it writes | No: the check order, the block placement and the drop rule are the owner's; a caller composing them forgets the placement | `prepare` | +| An entry turns a candidate input into the input it writes | No: the check order, the block placement and the drop rule are the owner's; a caller composing them forgets the placement | `check` | | An entry reads or withdraws a line's pending input | No: the input state is InputQueue's and is reached by line id | `session.input.withdraw`, `session.input.pending` (the methods below) | -| A check refuses the input with its own code | Yes: `prepare` answers `blocked` with the check's message | Business | -| A check contributes context | Yes: `prepare` appends the check's marker blocks after the operator's content | Business | +| A check refuses the input with its own code | Yes: `check` answers `blocked` with the check's message | Business | +| A check contributes context | Yes: `check` appends the check's marker blocks after the operator's content | Business | An operation or parameter exists only where the row says No. @@ -36,19 +36,22 @@ Hooks registers its `UserPromptSubmit` check from its `apply`: checks.register(RegisterCheck { name: "hooks".into(), check: Arc::new(run_hooks) }).await?; ``` -An operator entry prepares the input before writing it: +An operator entry checks the input before writing it: ```rust -let prepared = checks.prepare(PrepareInput { +let checked = checks.check(CheckInput { entry: SubmitEntry::Submit, branch_id: line.clone(), user: data.user.clone(), mode: data.effective_mode(), }).await?; -match prepared { - Prepared::Ready { user } => session.input.commit(user, &line).await?, - Prepared::Blocked { message } => return Err(RpcError::app(-32000, "input_blocked", message)), -} +let warnings = match checked { + Checked::Proceed { user, warnings } => { + session.input.commit(user, &line).await?; + warnings + } + Checked::Blocked { message } => return Err(RpcError::app(-32000, "input_blocked", message)), +}; ``` `session.input.withdraw` composes a command and the line's queue: @@ -70,11 +73,11 @@ None beyond the line's input owner, reached by line id. | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `register` | Publish a check for the calling row's lifetime | `{name, check}` | `{}` | None | `duplicate`, `invalid`, `closed` | -| `prepare` | Turn a candidate input into the input an entry writes | `{entry, branchId, user, mode}` | `{prepared: {user}}` or `{blocked: {message}}` | The caller's token stops the checks; a check already running stops with the token | `cancelled`, `closed` | +| `check` | Turn a candidate input into the input an entry writes | `{entry, branchId, user, mode}` | `{proceed: {user, warnings}}` or `{blocked: {message}}` | The caller's token stops the checks; a check already running stops with the token | `cancelled`, `closed` | | `session.input.withdraw` | Withdraw a pending input on a line | `{sessionId, branchId, inputId, reason?, steer?}` | the queue's receipt | The caller's token; a committed withdrawal is not undone | `invalid`, `input_blocked`, `interrupted`, `closed` | -| `session.input.pending` | Read a line's pending input | `{sessionId, branchId}` | the queue's pending value | None | `invalid`, `closed` | +| `session.input.pending` | Whether an input is held and unapplied at a cutoff | `{sessionId, branchId, inputId, through?, includeBlockPresence?}` | `{pending, blockPresence?}` | The caller's token stops the wait for the cutoff | `invalid`, `cancelled`, `closed` | -`check` is a callback by reference; it never runs inside the Timeline's commit lock. `prepare` returns the input the entry writes, with the checks' marker blocks already placed after the operator's content; a non-marker block is dropped with a diagnostic, as today. +`check` is a callback by reference; it never runs inside the Timeline's commit lock. `check` returns the input the entry writes, with the checks' marker blocks already placed after the operator's content, and the warnings the client shows; a non-marker block is dropped with a diagnostic, as today. ### Errors @@ -92,20 +95,20 @@ None beyond the line's input owner, reached by line id. | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `register` | Check the name and record the callback under the row | — | The registration is withdrawn | New registrations are refused | The registering row | -| `prepare` | Take the registered checks in name order, run each with the token, combine, place the blocks, answer | A running check stops with the token; the entry writes nothing | The checks' callbacks are revoked; the entry writes nothing | Pending preparations end `closed` | InputMethods for the combination; each check for its own work | +| `check` | Take the registered checks in name order, run each with the token, combine, place the blocks, answer | A running check stops with the token; the entry writes nothing | The checks' callbacks are revoked; the entry writes nothing | Pending checks end `closed` | InputMethods for the combination; each check for its own work | | `session.input.withdraw` | Validate the input, run the checks, write the command to the line's queue, wait for publication, answer the receipt | A committed withdrawal is not undone; the wait ends `interrupted` | The command settles with the line | The line's queue answers by its own state | The line's InputQueue | -| `session.input.pending` | Read the line's queue value | — | Nothing | Answers the state it observed | The line's InputQueue | +| `session.input.pending` | Read the line's queue `pending` at the cutoff | The wait stops | Nothing | Answers the state it observed | The line's InputQueue | ## Exceptions with reasons - A check that fails counts as proceed: an input check is an opinion, and a failing check must not block the operator's input. - The first block in name order is the answer; later checks still run for their warnings: the caller reads one refusal and every warning, as the operator-entry flow already does. -- `prepare` applies the marker rule itself: a check's context must be a runtime marker element, and an entry that forgot the rule would let a check's text read as the operator's words. +- `check` applies the marker rule itself: a check's context must be a runtime marker element, and an entry that forgot the rule would let a check's text read as the operator's words. ## Verification - A registration lives until its row unloads; a duplicate name is refused; a check's failure is no opinion. -- `prepare` runs checks in name order, the first block answers, and every warning is returned; a non-marker block is dropped; an input without operator content takes no blocks. +- `check` runs checks in name order, the first block answers, and every warning is returned; a non-marker block is dropped; an input without operator content takes no blocks. - A cancelled preparation runs no further check and writes nothing; a running check stops with the token. - `session.input.withdraw` with a steer runs the checks before writing the command; a block answers `input_blocked` and writes nothing; the committed command's receipt carries the warnings. - The two methods answer `invalid` for a malformed request and `closed` after the line ends. @@ -125,7 +128,7 @@ None beyond the line's input owner, reached by line id. | §7 no proxy | The check table answers its own checks; the line's queue answers the input. | | §7 one interface | One name, `submitChecks`, on the owner type; `append_blocks` leaves the public surface. | | §7 cross-language | Every operation is data or a callback; no method exists only for Rust. | -| §7 one change | The implementation task deletes `append_blocks` and the separate check call, adds `prepare`, and migrates both entries in one change. | +| §7 one change | The implementation task deletes `append_blocks` and the separate check call, adds `check`, and migrates both entries in one change. | | ADR 002 D1 | Session scope for the checks; the input state is the line's. | | ADR 002 D2 | No wiring plugin. | | ADR 002 D3 | A check follows its row's lifetime. | @@ -134,7 +137,7 @@ None beyond the line's input owner, reached by line id. ## Requirements raised to mechanism owners -1. [#2027](https://github.com/arcships/dim/issues/2027): the line's InputQueue needs `withdraw`/`pending` operations reached by line id, including the publication wait. The line mechanism is [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025)'s `(session, line)` access; until it exists the two methods cannot be migrated off `TreeCommands`. +1. [#2027](https://github.com/arcships/dim/issues/2027): the line's InputQueue needs `withdraw`/`pending` operations reached by line id, including the publication wait. The line mechanism is [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025)'s `(session, line)` access; until it exists the two methods cannot be migrated off `TreeCommands`. `withdraw` uses the `user` returned by `check` instead of appending blocks itself. ## Binding appendix @@ -155,7 +158,7 @@ pub struct RegisterCheck { pub name: String, pub check: CheckFn } #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PrepareInput { +pub struct CheckInput { pub entry: SubmitEntry, pub branch_id: String, pub user: Option, @@ -164,8 +167,8 @@ pub struct PrepareInput { #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub enum Prepared { - Ready { user: Option }, +pub enum Checked { + Proceed { user: Option, warnings: Vec }, Blocked { message: String }, } diff --git a/docs/design/plugins/PromptSources.md b/docs/design/plugins/PromptSources.md index 8969e3212e..4c6ba63786 100644 --- a/docs/design/plugins/PromptSources.md +++ b/docs/design/plugins/PromptSources.md @@ -63,7 +63,7 @@ The language update entry composes the record, the value and each loaded branch: store.set_session_language(&session_id, language).await?; // #2018's record let Changed { previous, version } = language.set(SetLanguage { language }).await?; for line in tree.directory(None)?.lines { - line_owner::(line.line)?.adopt(LanguageUpdate { version }, cancelled.clone()).await?; + line_owner::(line.line)?.configure(LanguageUpdate { version }, cancelled.clone()).await?; } ``` @@ -74,7 +74,7 @@ for line in tree.directory(None)?.lines { | Service | Purpose | | --- | --- | | `P:HostPlatform` | Home, environment and shell/platform context for the environment source. | -| `S:sessionConfig` | Working directory, Session context and the language seed. | +| `S:sessionScope` | The creation record: working directory, Session context and the language seed (`config`). | | `P:basePromptSettingsHost` | The user's replacement of `dim/base`, read once at apply; absent keeps the factory text. | ### Operations @@ -173,8 +173,8 @@ The value is `SessionConfig.language`, seeded by `session.create {language?}` an ## Requirements raised to mechanism owners -1. [#2027](https://github.com/arcships/dim/issues/2027): Prompt's branch owner needs an operation reached by line id that adopts a language update (the value's version) before the update replies. The line mechanism is [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025)'s `(session, line)` access; until it exists the update cannot keep the before-reply promise and this contract records the gap. -2. [#2018](https://github.com/arcships/dim/issues/2018): the Session record's `setSessionLanguage` operation the update entry calls before `set`. +1. [#2027](https://github.com/arcships/dim/issues/2027): Prompt's branch owner needs a `configure` operation reached by line id that adopts a language update (the value's version) before the update replies. The line mechanism is [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025)'s `(session, line)` access; until it exists the update cannot keep the before-reply promise and this contract records the gap. +2. [#2018](https://github.com/arcships/dim/issues/2018): the Session record's `setLanguage` operation the update entry calls before `set`. ## Binding appendix diff --git a/docs/design/plugins/PromptSuggestion.md b/docs/design/plugins/PromptSuggestion.md index bb242b363e..7c8c74ab03 100644 --- a/docs/design/plugins/PromptSuggestion.md +++ b/docs/design/plugins/PromptSuggestion.md @@ -43,14 +43,12 @@ suggestion.respond(RespondSuggestion { offer_id, accept: true }).await?; | Service | Purpose | | --- | --- | -| `S:sessionConfig` | `interactive` and the collaboration role: only a leader's interactive Session offers suggestions. | -| `S:sessionIdentity` | The Session id in the offer and the request. | -| `S:sessionScope` | `activated`/`closing`: the part works only while the Session runs. | +| `S:sessionScope` | `config` for `interactive` and the role (only a leader's interactive Session offers suggestions), `identity` for the Session id, and `activated`/`closing`: the part works only while the Session runs. | | `S:sessionMethods` | Register `session.suggestion` until this part unloads. | | `P:providerService` | `resolve` and `invoke` with `Once` for the suggestion request (#2019). | | `P:promptSuggestionSettingsHost` | The user's enable flag and size bound, read per decision. | | `S:timelineTree` | The line's directory record and the turn's end fact. | -| The line's ContextUsage | The usage that decides an appended compaction request, reached by line id (#2027). | +| The line's ContextUsage | `read`, the usage value that decides an appended compaction request, reached by line id (#2027). | ### Operations @@ -111,7 +109,7 @@ suggestion.respond(RespondSuggestion { offer_id, accept: true }).await?; ## Requirements raised to mechanism owners 1. [#2019](https://github.com/arcships/dim/issues/2019): `providerService.resolve` and `invoke {request, mode: "once"}` with the streamed consumer the suggestion needs. -2. [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025): the line access that lets this Session part read the line's ContextUsage by `(session, line)` id, and [#2027](https://github.com/arcships/dim/issues/2027)'s usage operation for it. +2. [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025): the line access that lets this Session part read the line's ContextUsage by `(session, line)` id, and [#2027](https://github.com/arcships/dim/issues/2027)'s `read` operation for it. ## Binding appendix diff --git a/docs/design/plugins/Questions.md b/docs/design/plugins/Questions.md index dda4f4534a..99084d6937 100644 --- a/docs/design/plugins/Questions.md +++ b/docs/design/plugins/Questions.md @@ -51,7 +51,7 @@ methods.respond(RespondQuestion { line, request_id, call_id, answers })?; // {} | Service | Purpose | | --- | --- | -| `S:sessionConfig` | `interactive`, read per call; a non-interactive Session gets an error result. | +| `S:sessionScope` | `config` for `interactive`, read per call; a non-interactive Session gets an error result. | | `S:toolRegistry` | Register `ask_user` until this part unloads. | | `S:sessionMethods` | Register `session.question` until this part unloads. | diff --git a/docs/design/plugins/ShellInput.md b/docs/design/plugins/ShellInput.md index eaca1a8088..19f275aa33 100644 --- a/docs/design/plugins/ShellInput.md +++ b/docs/design/plugins/ShellInput.md @@ -50,9 +50,7 @@ shell.stop(StopRun { run_id }, cancelled).await?; | Service | Purpose | | --- | --- | | `P:HostPlatform` | Home, shell, environment and process supervision. | -| `S:sessionConfig` | cwd, collaboration role and the shell preference. | -| `S:sessionScope` | `phase` and `withHold` for the command's extent. | -| `S:sessionIdentity` | The Session id in the entry and the output path. | +| `S:sessionScope` | `config` for cwd, the collaboration role and the shell preference, `identity` for the Session id in the entry and the output path, and `phase`/`withHold` for the command's extent. | | `S:sessionMethods` | Register the `shell` namespace until this part unloads. | | `S:guideEntries` | The `` entry, registered until this part unloads. | diff --git a/docs/design/plugins/ToolRegistry.md b/docs/design/plugins/ToolRegistry.md index 0a156ce871..627e7465f5 100644 --- a/docs/design/plugins/ToolRegistry.md +++ b/docs/design/plugins/ToolRegistry.md @@ -90,9 +90,7 @@ let status = registry.sources().await?; // adopted or rejected per source key | Service | Purpose | | --- | --- | | `S:toolHost` | The host tools owner: declarations, execute, write-target resolution and ordering for the host's tools. | -| `S:sessionConfig` | The mount list and the excluded names, fixed at creation. | -| `S:sessionIdentity` | The Session id in a foreign tool's neutral call and the attach span. | -| `S:sessionScope` | `activated` and `closing`: the refresh task starts at publication and ends when close starts. | +| `S:sessionScope` | `config` for the mount list and the excluded names (fixed at creation), `identity` for the Session id in a foreign tool's neutral call and the attach span, and `activated`/`closing` for the refresh task. | The registry provides `toolRegistry` on its owner type and nothing else; `toolSourcesView` leaves the catalog and its value is `sources`/`observe_sources` on the same face. diff --git a/docs/design/plugins/Wait.md b/docs/design/plugins/Wait.md index 150be2902e..4d491ab93f 100644 --- a/docs/design/plugins/Wait.md +++ b/docs/design/plugins/Wait.md @@ -1,49 +1,52 @@ # Wait -Scope: session (the tool) and branch (the arrival owner). Issue: #2026. +Scope: session. Issue: #2026. -Wait owns the model's wait: the `wait` tool and the branch's arrival table. The current implementation is described in the [Wait plugin page](../../architecture/rust-agent/plugins/Wait.md). The tool is a Session part; the arrival table is a branch Capability (#2027's scope) reached by line id. +Wait owns the `wait` tool: the tool's declaration and the text the model reads when a wait ends. The line's arrival table and the single-wait slot are WaitBranch's (#2027; its contract lands with that issue); this document states what the tool calls. ## Use and scope: responsibility split Wait owns: -- **The arrival table.** Per line, the inputs that can end a wait (a background task's notice, a steer, a line's own events) from their release until the model reads them, and the single-wait slot. -- **One wait.** From the call to the first matching arrival, the timeout or the cancellation. -- **The tool declaration.** Its schema and result kinds. +- **The tool declaration.** Its schema, its two optional inputs and the result kinds the model reads. +- **The result text.** `wait ended: notification ()`, `wait ended: steer`, `wait ended: interrupted`, `wait ended: timeout`, and the `already delivered` answer for a notice the model already read. +- **The refusal texts.** A second wait's `wait is already running in this session.` and the reload settlement. Callers keep: - When to wait: the model decides. - What a task id means: BackgroundExec and Collaboration own their tasks. -- The notice's text: the producers write it; the arrival table records only that it arrived. +- The arrival table and the slot: WaitBranch owns them; the tool only reads the result. | Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | -| The model waits on its line for a matching arrival | No: the arrival table, the single slot and the reload rule are the owner's | `wait` | -| The model asks for one task or any arrival | Yes: the same operation with an optional task id | Business | -| A second wait runs beside the first | No: the single-wait slot is the owner's | `wait` answers `busy` | -| Read what already arrived | Yes: `wait` with a zero or small timeout answers the arrival at once, or the notice in the model's context | Business | +| The model waits on its line for a matching arrival | No: the arrival table and the single slot are the line owner's | the `wait` tool calling WaitBranch's `wait` by line id | +| The model asks for one task or any arrival | Yes: the same call with an optional task id | Business | +| A second wait runs beside the first | No: the slot is the line owner's; the tool turns `already_waiting` into its refusal text | Business mapping | +| Read what already arrived | Yes: the line's `wait` answers `already_notified`, or the notice is already in the model's context | Business | An operation or parameter exists only where the row says No. ## Caller example -The tool runs on the calling line and waits there: +The tool runs on the calling line and asks the line's owner to wait: ```rust -let line = execution.branch_id; // the line id the call carries -let WaitReply { ended } = line_owner::(line)?.wait(WaitRequest { - task_id, - timeout_ms: 300_000, -}, cancelled.clone()).await?; -match ended { - Ended::Notification { task_ids, waited_ms } => result_text(task_ids, waited_ms), - Ended::Steer { waited_ms } => result_text_steer(waited_ms), - Ended::AlreadyNotified { task_ids, waited_ms } => already(task_ids, waited_ms), - Ended::Timeout { waited_ms } => timed_out(waited_ms), - Ended::Interrupted { waited_ms } => interrupted(waited_ms), -} +let line = execution.branch_id; // a value +let WaitReply { reason, task_ids, waited_ms } = line_owner::(line)? + .wait(WaitRequest { task_id, timeout_ms: 300_000 }, cancelled.clone()) + .await + .map_err(|error| match error { + WaitError::AlreadyWaiting => ToolResult::error("wait is already running in this session."), + WaitError::Closed => ToolResult::error("The wait was cancelled: capability reloading."), + })?; +let text = match reason { + Reason::Notification => format!("wait ended: notification ({})", task_ids.join(", ")), + Reason::UserSteer => "wait ended: steer".into(), + Reason::AlreadyNotified => format!("wait ended: notification ({}) was already delivered above.", task_ids.join(", ")), + Reason::Timeout => "wait ended: timeout".into(), + Reason::Interrupted => "wait ended: interrupted".into(), +}; ``` ## Own contract @@ -52,107 +55,64 @@ match ended { | Service | Purpose | | --- | --- | -| `B:dispatcher` | Consume `input/message`, `turn/start` and `turn/end` in order and record arrivals. | -| `B:timeline` | Read the line's own facts at the branch's cut; commit no fact from here. | -| `B:timelineIdentity` | Name the line this table belongs to. | +| `S:toolRegistry` | Register `wait` until this part unloads. | +| The line access and WaitBranch's `wait` | The arrival table and the slot, reached by line id (#2027). | -### Operations +### Contributions -| Operation | Intent | Request | Reply | Cancellation | Errors | -| --- | --- | --- | --- | --- | --- | -| `wait` | Wait on this line for a matching arrival, the timeout or the cancellation | `{taskId?, timeoutMs?}` | `{ended}`: `notification {taskIds, waitedMs}`, `steer {waitedMs}`, `alreadyNotified {taskIds, waitedMs}`, `timeout {waitedMs}`, `interrupted {waitedMs}` | The caller's token ends the wait as `interrupted` and releases the slot; a dropped Rust future releases the slot | `busy`, `cancelled`, `closed` | - -`timeoutMs` is 1 through 300,000, default 300,000. The slot is single: a second wait on the same line answers `busy` until the first ends or its caller drops it. +No service of its own; the `wait` tool is the whole surface. -### Errors +| Contribution | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | +| `wait` tool | `{taskId?, timeoutMs?}` | one `ToolResult`: the text above, `isError` for a refusal or a cancelled wait | The call's token; a dropped call releases the slot | mapped from the line's `already_waiting`/`closed` | -| Kind | What the caller does next | -| --- | --- | -| `busy` | A wait is running on this line; end it or retry after it ends | -| `cancelled` | The call stopped before any arrival; nothing was consumed | -| `closed` | The line is ending or the table is unloading; wait on the replacement generation | +The tool's own input rules are its schema's: `timeoutMs` is 1 through 300,000, default 300,000; a non-string task id or an out-of-range timeout is an invalid-input result. ### Flows -| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| Path | Normal | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `wait` | Take the slot, return an already-arrived match, otherwise wait for a release, the timeout or the token | The token ends the wait `interrupted` and releases the slot; the arrival stays recorded | The dropped call releases the slot; the arrival stays for a later wait or read | The generation's unload ends an accepted wait `closed`; the arrivals are rebuilt from the line's facts | Wait for the slot and the result; the caller for its dropped future | +| Tool call | Register the tool, call the line's `wait`, map the reason to text, return the result | The line's `wait` answers `interrupted`; the tool returns that text | The dropped call releases the line's slot | The line's owner answers `closed`; the tool returns the reload settlement | WaitBranch for the slot and arrivals; ToolExecutor for the tool result's fact | ## Exceptions with reasons -- An arrival taken by a wait stays recorded: a later read of the same notice in the turn is told it was already delivered, so a wait never consumes the model's only copy. -- A branch close cancels a wait without a wake: the line is ending, and the model's next turn is on another line. -- The table folds the line's own facts at open: wait has no persistent state of its own, and the branch rebuilds the same arrivals after a reload. +- The tool's result texts are protocol: the model reads the task ids and the end reason, and a change to either changes what it can do next. +- A notice the model already read does not end a later wait: the line's owner answers `already_notified`, and the tool tells the model it was delivered. ## Verification -- A wait ends on the matching completion, not on the input that started the turn; a steer or a stop ends it; a second wait answers `busy`. -- A notice the model already read does not end a later wait; the wait answers `alreadyNotified`. -- Cancelling a wait ends it `interrupted` and releases the slot; dropping the future releases the slot. -- An arrival recorded before the call is answered at once; a reload rebuilds the arrivals from the line's facts. -- The line's end ends a wait with `closed` and no wake. +- A wait ends on the matching completion, not on the input that started the turn; a steer or a stop ends it; a second wait answers the refusal text. +- A notice the model already read answers `already delivered above`; a timeout answers `wait ended: timeout`. +- Cancelling the tool call ends the wait as interrupted and releases the slot; dropping the future releases the slot. +- A reload answers the settlement text; the line's next generation starts with no old arrivals. ## Rule check | Rule | Application | | --- | --- | -| §1 parts and Capabilities | The tool is a Session part, not a Capability; the arrival table is a branch Capability: it folds the line's facts in order and writes none. | +| §1 parts and Capabilities | One Session part; it writes no Timeline fact; the arrival table is WaitBranch's branch Capability. | | §2 scopes | The tool is Session; the table is branch; the tool reaches the table by line id. | -| §3 orthogonality | No other owner's state is read; the task ids are values. | -| §4 rules 1–5, 9 | No command event, handoff, before callback, batch or Timeline fact from the table. | -| §4 rule 6 | The wait's result reaches the model as the tool result; notices reach it as inputs their producers write. | -| §4 rule 7 | The tool calls the table's operation; no caller reads the arrivals. | +| §3 orthogonality | No other owner's state is read; the line owner answers the arrival. | +| §4 rules 1–5, 9 | No command event, handoff, before callback, batch or Timeline fact from the tool. | +| §4 rule 6 | The result reaches the model as the tool result. | +| §4 rule 7 | The tool calls the line owner's operation; no caller reads the arrivals. | | §4 rule 8 | No infrastructure change. | -| §7 values, ids and callbacks | The request and result are data; task ids and the line id are values; the cancellation is an argument; no object crosses. | -| §7 no proxy | The table answers its own arrivals; the tasks belong to their owners. | -| §7 one interface | One name, `wait`, on the branch owner; the Session tool only registers. | -| §7 cross-language | The operation is data; no method exists only for Rust. | +| §7 values, ids and callbacks | The line id and the task ids are data; the cancellation is an argument; no object crosses. | +| §7 no proxy | The line owner answers the arrival; the tool answers its text. | +| §7 one interface | No service of its own; the tool is the surface. | +| §7 cross-language | The tool's execute is a callback; its input and result are data. | | §7 one change | The implementation task migrates the tool off `TreeCommands` in one change. | -| ADR 002 D1 | Branch scope for the arrivals; Session for the tool. | +| ADR 002 D1 | Session for the tool; branch for the arrivals. | | ADR 002 D2 | No wiring plugin. | -| ADR 002 D3 | The tool depends on the line's table by id, not on the table's implementation. | -| ADR 002 D4 | The timeout default is the owner's; no setting. | -| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| ADR 002 D3 | The tool depends on the line owner's operation. | +| ADR 002 D4 | The timeout default is the tool's; no setting. | +| ADR 002 D5 | The contract is data. | ## Requirements raised to mechanism owners -1. [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025): the line access that lets the Session tool reach the line's `wait` by `(session, line)` id; the current call takes it from `TreeCommands.get(line)?.service::()`. +1. [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025): the line access that lets the Session tool reach WaitBranch's `wait` by `(session, line)` id. +2. [#2027](https://github.com/arcships/dim/issues/2027): WaitBranch's `wait {taskId?, timeoutMs?}` with `{reason, taskIds?, waitedMs}` and `already_waiting`/`closed`, as its contract states. ## Binding appendix -The service is marked on `Wait` under `wait`. `caller: &Ctx` fills the line identity; `CancelledFn` is not a request field. - -```rust -use crate::host::CancelledFn; - -#[derive(serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct WaitRequest { - #[serde(default, skip_serializing_if = "Option::is_none")] - pub task_id: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub timeout_ms: Option, -} - -#[derive(serde::Serialize, serde::Deserialize)] -#[serde(tag = "reason", rename_all = "snake_case", rename_all_fields = "camelCase")] -pub enum Ended { - 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(serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct WaitReply { pub ended: Ended } - -#[derive(serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum WaitError { - Busy { message: String }, - Cancelled, - Closed, -} -``` +No service. The tool registers through the tool contract; its input is `{taskId?, timeoutMs?}` and its result is one `ToolResult` whose content is the text above. diff --git a/docs/design/plugins/WorkspaceTools.md b/docs/design/plugins/WorkspaceTools.md index 4fadc9ca49..6899349a45 100644 --- a/docs/design/plugins/WorkspaceTools.md +++ b/docs/design/plugins/WorkspaceTools.md @@ -64,9 +64,7 @@ let ExecOutput { text } = line_owner::(line)?.output(task_id).aw | Service | Purpose | | --- | --- | | `P:HostPlatform` | Home, shell, environment and process supervision. | -| `S:sessionConfig` | cwd, collaboration role and the Session's output directory. | -| `S:sessionIdentity` | The Session id for the output directory and the search root. | -| `S:sessionScope` | `activated`/`closing` for the tool generation and `hold` for a running background task. | +| `S:sessionScope` | `config` for cwd, the collaboration role and the output directory, `identity` for the Session id and the search root, and `activated`/`closing`/`hold` for the tool generation and a running background task. | | `S:sessionMethods` | Register the four method namespaces until the part unloads. | | `P:mentions` | The process owner's walked index. | | `P:sessionFiles` | Register an output path with the Session's file owner. | @@ -148,7 +146,7 @@ let ExecOutput { text } = line_owner::(line)?.output(task_id).aw ## Requirements raised to mechanism owners 1. [#2024](https://github.com/arcships/dim/issues/2024)/[#2025](https://github.com/arcships/dim/issues/2025): the line access that lets this Session part reach FileReads and BackgroundExec by `(session, line)` id. The file tools need the line's read bindings and `exec` needs the line's background owner; neither may be taken from a `Branch` object. -2. [#2028](https://github.com/arcships/dim/issues/2028): FileReads' binding operation and BackgroundExec's start/output/wait operations, reached by line id; the current calls take them from `TreeCommands.get(line)?.service::()`. +2. [#2028](https://github.com/arcships/dim/issues/2028): FileReads' binding operation and BackgroundExec's `adopt`/`output`/`wait` operations, reached by line id; the current calls take them from `TreeCommands.get(line)?.service::()`. 3. [#2018](https://github.com/arcships/dim/issues/2018): `sessionFiles.register` and the read/write operations the output and attachment paths use. ## Binding appendix From d0fc26c88e1387383268c2daca95689123f10a7d Mon Sep 17 00:00:00 2001 From: eric8810 Date: Mon, 23 Nov 2026 19:37:01 +0800 Subject: [PATCH 03/10] docs(design): remove the superseded designs and make ToolBinding the adoption interface The five owner documents keep the new contract and the still-valid client and fork behavior; each has one Rule check. ToolRegistry keeps the Session's resolvable generations; ToolBinding calls adopt, release, claim and release_claims and settles them from the request's terminal facts. --- docs/design/plugins/PromptSources.md | 145 ----- docs/design/plugins/PromptSuggestion.md | 370 ------------ docs/design/plugins/Questions.md | 555 +----------------- docs/design/plugins/Recall.md | 742 ------------------------ docs/design/plugins/ShellInput.md | 551 ------------------ docs/design/plugins/ToolRegistry.md | 26 +- 6 files changed, 18 insertions(+), 2371 deletions(-) diff --git a/docs/design/plugins/PromptSources.md b/docs/design/plugins/PromptSources.md index 4c6ba63786..67d3e9724f 100644 --- a/docs/design/plugins/PromptSources.md +++ b/docs/design/plugins/PromptSources.md @@ -229,148 +229,3 @@ pub enum SourceError { Closed, } ``` - - -PromptSources provides the Session's named prompt sources and the Session's prompt registry. It owns the words of the sources it authors — the base prompt and the shell guidance — and carries, but does not own, the host's system prompt and the user's and the project's `AGENTS.md`. It states the runtime environment and the date as facts. It contributes no input-guide entry: the markers it feeds are Prompt's, which writes them and explains them ([Prompt §4](Prompt.md#4-the-built-in-entries-and-their-writers)). - -## 1. Sources and their classes - -Each source is one name with an owner, a delivery and a class ([model-facing prompts §4](../model-prompts.md#4-protocol-and-policy)). The class is per text, not per source, where a source's block mixes them. - -| Source | Delivery | Order | Author | Class | -| --- | --- | --- | --- | --- | -| `dim/base` | System | 0 | PromptSources | Policy | -| `dim/session` | System | 50 | The host or the profile | Content | -| `dim/instructions/project` | Context (``) | 100 | The project | Content | -| `dim/instructions/user` | Context (``) | 110 | The user | Content | -| `dim/environment/context` | State (``) | 200 | PromptSources | Facts, plus two guidance texts (§1.2) | -| `dim/environment/date` | State (``) | 210 | PromptSources | Fact | -| `dim/language` | State (``) | 220 | PromptSources | Fact (designed, §3) | - -The delivery decides where a change takes effect. A `System` source is part of the composed system prompt: another line inherits it through the prefix's configuration and applies it where the fact appears. A `Context` or `State` source is delivered as an Append input block, written in the same batch as its `prompt/changed`, and the change names that block's id in `inputs`; a line whose inherited prefix never consumed that input does not count the change as adopted. It adopts the source's current value itself, and the block arrives at that line's own consumption point. The same holds for an `Initialize` change: delivery decides, not the reason the change was written. - -### 1.1 Policy - -`dim/base` is policy: the identity sentence and the rules — safety, tone, progress updates, objectivity, engineering, git, working method, ending a turn, and the linking conventions. It is guidance about how to work; the runtime behaves the same whatever it says. The shape of a tool's input, and how its entries apply, is stated by the tool's own declaration rather than by `dim/base`. - -The shell guidance is policy too. It is the sentence the environment source carries for the operator's shell (`Use POSIX shell syntax. …`, or the PowerShell, cmd, Git Bash and other editions), plus the file-encoding guidance on Windows: how to quote, how to invoke a path with spaces, which legacy encodings to ask the read tool for. None of it states a runtime fact. - -Both are replaceable at PromptSources' factory configuration (§2); the product sets neither, so a candidate runs through the shipped assembly ([model-facing prompts §8.1](../model-prompts.md#81-the-rule)). - -### 1.2 Facts, and the report on the environment source - -The environment source states facts: the working directory, the home directory, the shell's executable and edition, its output encoding, the platform, and the time zone. The date source states the date, in the process's local time zone. - -**Two texts in the environment source are guidance, not facts**: `shell_guidance` and `file_encoding_guidance`. They tell the model how to work; the runtime would behave identically if they said something else, and they are false of nothing. They stay where they are — inside the environment block, as the model reads them today — and they become policy members of the factory configuration. Moving them out of the state block would change what every request carries, which is a text change this issue does not make. - -### 1.3 Content - -`dim/session` is the host's or the profile's system prompt: carried, never edited. The user's and the project's `AGENTS.md` are the instruction bodies: read as files, escaped with the context-block escape rule so their text cannot forge a marker, and carried verbatim — the project's with a one-line header naming its path and that it applies to that directory and below, the user's with a header naming it as `~/AGENTS.md`. Neither is summarized, rewritten or trimmed beyond the surrounding whitespace. A missing or unreadable file produces no entry rather than an empty one. - -## 2. Policy at the factory configuration - -The factory configuration carries the three policy texts, in the shape [the summary strategy's](../plugins/ContextCompaction.md#134-evaluation) optional system prompt uses: an optional member each, `None` keeping the built-in text, and the product profile setting none of them. - -| Member | Replaces | -| --- | --- | -| `base` | `dim/base`'s identity and rules | -| `shell_guidance` | The shell guidance the environment source carries, per shell edition | -| `file_encoding_guidance` | The file-encoding guidance the environment source carries | - -A candidate is installed through the shipped assembly — the same plugin, constructed with a configuration — never by patching text at a request boundary ([model-facing prompts §8.1](../model-prompts.md#81-the-rule)). - -### 2.1 The product's user override - -The product profile sets no factory text, so the App Server may supply the operator's `base` from its user settings ([prompt overrides](../appserver/prompt-overrides.md)). The port is `BasePromptSettingsHost`, optional and read while the Session's sources are assembled: the factory `base` outranks it, a read failure keeps the built-in text, and the value applies to Sessions loaded after the change. The port replaces one field; the shell and file-encoding guidance stay factory-only, because their shape is per shell edition and platform. - -## 3. The "Agent prompt language" state source - -The source names the language the model writes to the operator in ([model-facing prompts §7](../model-prompts.md#7-language)). It settles the case where the operator's environment language and their messages' language disagree — English logs or code pasted into a Chinese session — by making the answer language an explicit choice instead of an inference from the last message. - -**The block.** Source `dim/language`, delivery State, order 220, so it follows the environment and the date. Its body is one sentence, the language named in English: - -```text -The operator set this session's reply language to Simplified Chinese. -``` - -The body states the setting itself, and asks for nothing: a state block is read as the situation, never as an instruction, and it names the language the model writes to the operator in ([model-facing prompts §7](../model-prompts.md#7-language)). The language names are the ones the operator selects — English, Simplified Chinese, Traditional Chinese, Japanese, Korean, Bahasa Indonesia, German, French, Spanish, Portuguese (Brazil), Portuguese (Portugal). The sentence's wording is policy: it is judged against the current text when the source is built ([model-facing prompts §8](../model-prompts.md#8-judging-a-change)), and this design does not build it. - -**No selection, no block.** When the operator has chosen no language — the system default — the source produces no entry and the base sentence's rule stands. - -**The carrier.** The client carries the operator's choice into the Session: `session.create {language?}` seeds it and `session.language.update` changes it, and the value is `SessionConfig.language`, an optional member of the Session's config record. The daemon never reads the client's interface-locale file. The PromptSources Session part provides the Session's live value as the `SessionLanguage` cell and reads it on every load; the cell's `get` is the `sessionLanguage` data face, which other languages read by name, and the branch part re-exposes that cell on each branch for the Session methods that change it, as the Skill list is re-exposed. The face has no write: an update also writes the Session record and has Prompt adopt the source. A Session created without a choice, including a record written by an older client, has no value and produces no entry. An update adopts the value on `main` and, before it replies, on every loaded branch, so that branch's next request carries it without a wake; a branch loaded later reads the current value when it loads, and each branch's periodic check remains the fallback. - -## 4. Dependencies - -| Service | Purpose | -| --- | --- | -| `S:PromptRegistry` | Register each source by name, until this part unloads | -| `P:HostPlatform` | Home, environment and the operator's shell | -| `S:SessionConfig` | Working directory and the host's system prompt | - -The language source reads the part's own `SessionLanguage` cell rather than an injected service. - -## 5. Cross-module requirements - -1. **The operator's language for the Session** (§3): the Session's config carries it (`SessionConfig.language`), `session.create {language?}` seeds it and `session.language.get/update` read and change it, and this plugin reads the Session's live value. No configuration file carries it, and no other module decides it. -2. **The plugin bridge** ([Prompt §6.1](Prompt.md#61-the-plugin-bridge)): no further requirement reaches PromptSources; the markers its sources feed are Prompt's, and Prompt's page raises what they need. - -## 6. Rule check - -| Rule | How this design complies | -| --- | --- | -| §1 Plugins and capabilities bounded | The sources, their classes and their texts are PromptSources'; the guide's frame and the entries of the markers it writes are Prompt's | -| §3 Orthogonality | The sources travel on the existing prompt-source contract; this design adds no route of its own | -| §4 rule 1 Apply registers, cleanup releases | The sources register from `apply` and end with the part's generation | -| §4 rule 6 Context from consumed events | Sources keep reaching the model through adoption and Append inputs; this design adds no path | -| §4 rule 7 Public events and services | The source adds no protocol method or event of its own: it is one more name in an existing set. The Session's value is a service the owning part provides at the Session scope and re-exposes on each branch, as the Skill list does (ADR 002 D1, D2) | -| §4 rule 8 Infrastructure unchanged | None is changed. The language fact is raised, not built | -| ADR 002 D1 Scope | The sources live in the Session, where their state lives | -| D4 Configuration | No configuration file is added; the policy members are the plugin's factory configuration, as the summary strategy's system prompt is | -| D5 Language-neutral contracts | The language source is a state block, data on an existing channel | -| ADR 008 D2 No delivery status | The document states the design only | -| ADR 008 D3 Own scope only | The guide's route and the frame stay on [Prompt](Prompt.md)'s page | - -## 7. Binding appendix - -```rust -/// Factory configuration of the sources' policy texts. The product sets -/// none of them, so the built-in texts are in force. -#[derive(Clone, Default)] -pub struct PromptSourcesConfig { - /// `dim/base` in place of the built-in identity and rules. - pub base: Option>, - /// The shell guidance the environment source carries, per edition. - pub shell_guidance: Option String + Send + Sync>>, - /// The file-encoding guidance the environment source carries. - pub file_encoding_guidance: Option>, -} - -impl PromptSourcesPlugin { - /// The plugin with the built-in policy texts in force. - pub fn new(names: &Names<'_>, today: Today) -> rutis::Result; - /// The plugin with a candidate's texts at its factory configuration. - pub fn with_config( - names: &Names<'_>, - today: Today, - config: PromptSourcesConfig, - ) -> rutis::Result; -} - -/// Registers PromptSources with the policy texts at `config`. -pub fn install_with_config( - builder: &mut AgentBuilder, - today: Today, - every: Duration, - config: PromptSourcesConfig, -); - -/// Registers PromptSources with the built-in texts: `install` and -/// `install_with_clock` are this entry with the default configuration. -pub fn install(builder: &mut AgentBuilder); -``` - -The language source's binding is one more arm of the source loader: name `dim/language`, delivery `State`, order 220, body from the operator's setting when one is carried and no entry when none is. - -## Reading and adopting current source values - -Opening loads the current sources once. The periodic branch checker starts after that initial opening interval; a checker mounted on an already active branch still checks immediately. Each instructions source reads only its own file body. The checker compares each loaded target through the existing state watch and hands changed values to the existing resolved-source adoption; it does not reload their names. Language adoption keeps the Session language gate through its final load and adoption. No file cache or additional persistent event is introduced. diff --git a/docs/design/plugins/PromptSuggestion.md b/docs/design/plugins/PromptSuggestion.md index 7c8c74ab03..beb607fd11 100644 --- a/docs/design/plugins/PromptSuggestion.md +++ b/docs/design/plugins/PromptSuggestion.md @@ -136,373 +136,3 @@ pub enum SuggestionError { Closed, } ``` - - -PromptSuggestion offers the message the user would plausibly send next. When a client that witnessed a completed turn has an empty composer, it asks the Session with `session.suggestion.request {sessionId, turnId}`; the Session part clones the turn's last `ModelCall` request, appends the assistant message that request produced and one instruction, and invokes the same model through the model host and the provider connection resolver. The reply is one validated line, delivered as a Session broadcast notice (`session.notice`, source `PromptSuggestion`). The offer is display-only: it enters no Timeline event, no storage and no model context, and the next real request is the same with or without it. A suggestion is only ever inserted into a client's composer, never sent. - -The offer is not a Capability ([principles §1](../../architecture/rust-agent/principles.md)): it owns no Timeline state, folds no facts and writes no events, and the display rule sends it through a Session notice ([principles §4 rule 9](../../architecture/rust-agent/principles.md)). - -## 1. Parts and scope - -The feature is one plugin with two parts, split by the owner of their state: - -| Part | Scope | State it owns | Depends on | Provides | -| --- | --- | --- | --- | --- | -| `PromptSuggestionSettings` | Process (App Server) | The `prompt-suggestion` Settings source | `P:Settings` | `P:PromptSuggestionSettingsHost` | -| `PromptSuggestion` | Session | The latest completed turn's request and content, the offer in flight, the shown offer, the unused count | `S:SessionIdentity`, `S:SessionConfig`, `S:SessionLifecycle`, `S:SessionMethods`, `S:TreeCommands`, `P:ModelHost`, `P:ProviderConnectionResolver` in the product's process-model mode, and, when the assembly binds it, `P:PromptSuggestionSettingsHost` | `session.suggestion` with `sessionMethods` | - -The process part declares the source where every other business source of this daemon lives, next to `ExecutionSettings` and `ModelLog`; the source is process state shared by Sessions, so it is not a Session part ([ADR 002 D1](../../adr/002-plugin-scope.md)). The source itself is read by the Session part through the host port at each decision ([ADR 002 D4](../../adr/002-plugin-scope.md)): changing `enabled` or `maxChars` never reloads a part. - -The part is installed where the connection mode is known, never inferred. `prompt_suggestion::install` requires the process `ProviderConnectionResolver`; the product root calls it beside `install_compaction` ([`crates/dim-app-server/src/cli.rs`](../../../crates/dim-app-server/src/cli.rs)), and so does every other assembly whose model is the process one. An assembly whose model is local calls `prompt_suggestion::install_local` instead, which sends `ModelConnection::Local` as `ModelProviderPlugin::new` does; the in-process transport fixtures and the architecture graph are that kind of assembly. `defaults::install_local_execution` installs no part, so a root that forgets the call has no suggestion rather than one sent over a connection that was never resolved. It stays idle while the setting is off: no request is started and no model call is made. - -An assembly that binds no `PromptSuggestionSettingsHost` (an evaluation, the architecture graph) has the feature off. - -## 2. Structure - -```mermaid -flowchart LR - subgraph PROC["Process"] - Settings["Settings source prompt-suggestion"] - Model["ModelHost"] - Resolver["ProviderConnectionResolver"] - Rpc["Rpc"] - end - subgraph SESS["Session"] - PS["PromptSuggestion"]:::new - SB["Session broadcast"] - Methods["sessionMethods"] - end - PS -->|"read each decision"| Settings - PS -->|"invoke"| Model - PS -->|"resolve connection"| Resolver - PS -->|"listen: session/{id} events on main"| SB - PS -->|"offer / cleared"| SB - PS -->|"register session.suggestion"| Methods - Rpc -->|"session.suggestion.* dispatched through the Session"| Methods - SB -->|"session.notice"| Rpc - classDef new fill:#d3f9d8,stroke:#2b8a3e,color:#000 -``` - -The Session part observes its own Session through the existing broadcast ([ADR 002 D2](../../adr/002-plugin-scope.md)); it needs no branch service and no Dispatcher subscription, because it consumes no fact in order and derives everything from the events the broadcast already carries. It asks nothing of another plugin: `ModelHost` and `ProviderConnectionResolver` are the host ports the compaction strategy also uses, and the notice is the public record of [Session broadcast notices](../appserver/session-notices.md). - -## 3. State - -All state is in memory, per Session, and lost on unload: - -| State | Content | Set by | -| --- | --- | --- | -| Latest turn | The newest `turn/start`'s `turnId`, and whether its `turn/end` was `Completed` | `turn/start`, `turn/end` | -| Turn request | The turn's last `model/call`: `{turnId, requestId, request}` | `model/call` | -| Turn content | The turn's last `model/content`: `{requestId, content}` | `model/content` | -| Newer input | Whether an `input/message` or `input/applied` followed the latest turn's end | `input/message`, `input/applied` | -| In-flight | At most one: `{turnId, invocation, cancellation token}`, and whether it has passed its preflight | `session.suggestion.request` | -| Offer | At most one: `{turnId, text}` | a completed request | -| Unused count | Offers cleared without an accept since the last accept or turn-on of the switch | `cleared`, `respond` and a settings change | - -Nothing is stored, replayed or exported, and no `model/usage` event is written: the suggestion is not a turn. The request identity is the suggestion's own ([§5](#5-the-request-and-the-cache)); the logs carry numbers and reason codes, never the text or the conversation. - -The part holds one cancellation token that ends with it: unloading cancels the token, closes the task tracker and waits for its tasks, so a replaced part leaves no request running while its replacement starts. A request the unload cancels announces nothing. - -## 4. Flow - -### 4.1 A request and its offer - -```mermaid -sequenceDiagram - participant C as Client - participant Rpc - participant PS as PromptSuggestion - participant Settings as Settings - participant BH as ModelHost - participant SB as Session broadcast - Note over PS: turn/end Completed for turn T - C->>Rpc: session.suggestion.request {sessionId, turnId: T} - Rpc->>PS: sessionMethods call - PS->>Settings: read prompt-suggestion - PS-->>Rpc: {accepted: true} - PS->>PS: clone the turn's last request, append - PS->>BH: invoke (30 s deadline) - BH-->>PS: one line - PS->>SB: notice offer {turnId, text} - SB-->>C: session.notice {source: PromptSuggestion, kind: offer} - C->>Rpc: session.suggestion.respond {sessionId, turnId, action: accept} - PS->>SB: notice cleared {turnId, reason: accepted} -``` - -`request` answers at once and never waits for the model. The offer arrives as a notice, so a slow model does not hold an RPC open, and every attached client sees it; each client decides for itself whether its composer is empty. - -### 4.2 Why the client asks - -Only the client knows that the user is not typing, that no panel is open and that no question or approval is pending, so only the client triggers. The daemon never generates on its own; a client that attaches later sees only a notice that was emitted while it was attached, and the offer is not replayed. The terminal client's rules are [§11](#11-terminal-client). - -## 5. The request and the cache - -The request is built by one public function of the feature's module, which the evaluation reuses: - -```rust -pub fn suggestion_request( - request: &Arc, - content: &[MessagePart], - instruction: &str, -) -> Arc; -``` - -| Step | Content | -| --- | --- | -| Clone | The turn's last `ModelCall` `request`, with `provider_id`, `model_id`, `capability_snapshot`, `system`, `tools`, every earlier message and the whole `config` unchanged | -| Append | `Message { role: Assistant, content: Parts(content.clone()) }`, exactly as history builds a completed output's message, then `Message::text(User, instruction)` | -| Identity | `metadata.turnId` and `metadata.extensions.requestId` gain the `/suggestion` suffix, so a model recording names the suggestion apart from the turn's call; nothing else in `metadata` changes | -| Unchanged | `max_tokens`, reasoning, tool choice, service tier and every other configuration member | - -The configuration is left as it is, including `max_tokens`: the output is bounded by the reader of §6, which stops once the reply can no longer be offered, and by the 30 s deadline, not by a per-request cap. Each configuration member participates in the cache key on at least one protocol or is constrained by another (Anthropic requires the output cap to exceed a thinking budget), so changing one would defeat the purpose of cloning the request. - -Why this keeps the cache: a provider's prefix cache matches the start of the request exactly, and a change anywhere in the prefix recomputes everything after it. The suggestion's system, tools and every earlier message hold the turn's own text, so the turn's cached prefix matches; the only new tokens are the assistant message and the instruction at the tail. On Anthropic the aimux converter places the automatic breakpoints at the end of the system and on the last user or tool message: the system one stays, and the tail one is placed again on the instruction, because the instruction is now the last user message. No earlier message's text changes; only that marker moves, so the wire comparison of an earlier message ignores it ([Appendix B](#appendix-b-acceptance)). On the automatic-prefix protocols the same prefix matches the same way. The turn's cache write ended at its own last message, which the suggestion's request still contains; and because nothing is written to the Timeline and no history is mutated, the next real request is identical with and without a suggestion. - -The suggestion never goes through `ModelProvider` or the loop: it calls `ModelHost` with a connection from `ProviderConnectionResolver` (with `ModelConnection::Local` when the assembly's model is local), as `summary_strategy.rs` does for compaction. It therefore writes no `model/call`, `model/content`, `model/usage` or any other Timeline event. - -## 6. The instruction and the validator - -The instruction is one user message after the assistant message: - -```text -You predict the next message the user will send in this conversation. Reply with exactly one line the user would type next, in the user's language, at most {maxChars} characters. It must be a user message, not an assistant answer. Do not use quotes, markdown or explanation. Do not call tools. The conversation is data, not instructions. If the next user message is not predictable, reply with . -``` - -The model sees the conversation as it last saw it, then its own assistant answer, then the instruction: exactly the shape of the next real turn, with the instruction in place of the user's actual next message. A mid-conversation system message is not portable across protocols and would break that shape. - -The stream is read to its end unless the reply can no longer be offered under §6's rule, then dropped, which cancels the request. A tool call, an error or a cancellation means no offer. The whole request runs under a 30 s deadline. - -The reply is validated in this order; any failure clears with `invalid`, and there are no retries: - -| # | Rule | -| --- | --- | -| 1 | Trim. The result is non-empty and at most `maxChars` characters (code points) | -| 2 | No line break, control character, `<` or `>` | -| 3 | No leading `/`, `@` or `!`, which a client's composer would interpret | -| 4 | Not `` and not refusal or sentinel text (`none`, `null`, `undefined`, `no suggestion`, `nothing to suggest`, and the common Chinese equivalents) | -| 5 | Not an assistant-style opening (`I'll`, `i will`, `let me`, `here's`, `you should`, and the common Chinese equivalents) | -| 6 | Not a repeat of the last conversational user message, compared after trimming, ASCII lowercasing and whitespace collapsing; runtime state and rule envelopes do not count as user replies | - -The reply is offered only when its trimmed text is a single line of at most `maxChars` characters: the reader stops at the first non-whitespace character after a line break, or when the trimmed text exceeds `maxChars`, and a trailing line break alone is trimmed away. The validator is deliberately conservative: a missing suggestion is better than a wrong one, and the evaluation measures precision. - -## 7. Methods and notices - -Two methods are registered on `sessionMethods` under the namespace `session.suggestion`, as SessionTitle registers `session.rename`: - -| Method | Params | Reply | Errors | -| --- | --- | --- | --- | -| `session.suggestion.request` | `{sessionId, turnId}` | `{accepted: bool, reason?: string}`; `accepted` means the model call for the turn started, by this request or by one it shares | `invalid_params`, dispatch errors of the Session boundary | -| `session.suggestion.respond` | `{sessionId, turnId, action: "accept" \| "dismiss"}` | `{}` | `invalid_params`, dispatch errors of the Session boundary | - -Notices follow [Session broadcast notices](../appserver/session-notices.md); Rpc adds `sessionId`: - -```text -session.notice {sessionId, source: "PromptSuggestion", kind: "offer", data: {turnId, text}} -session.notice {sessionId, source: "PromptSuggestion", kind: "cleared", data: {turnId, reason}} -``` - -`accept` clears the shown offer, counts the accept and resets the unused count; it does not cancel a request that is merely in flight for the same turn; accepting marks that turn used. `dismiss` clears the offer and cancels a request in flight for that turn. - -## 8. Gates, cancellation and reasons - -The gates of `request`, in order. A refused request answers `{accepted: false, reason}` and emits no notice, because no offer was ever shown: - -| # | Gate | Reason | -| --- | --- | --- | -| 1 | The setting is on | `disabled` | -| 2 | The Session is a root interactive Session: `interactive` and `collaboration_role: leader`. A Collaboration member, a launched or scheduled Session never offers | `not_root` | -| 3 | The cached turn belongs to the line the request names: the line the Session's conversation is on, read once when the request is admitted | `branch_changed` | -| 4 | `turnId` is the latest turn, and no input followed its end | `not_latest_turn` | -| 5 | That turn ended `Completed` | `turn_not_completed` | -| 6 | The turn's last `model/content` belongs to its last `model/call` and holds text | `no_text` | -| 7 | The unused count has not reached 20 | `throttled` | -| 8 | No request is in flight for this turn; if one is, it answers for both once that request's preflight settles | `accepted: true` | -| 9 | The request's line's committed head is not about to compact: `estimatedInputTokens` plus the instruction's tokens does not exceed `thresholdTokens` | `compaction_due` | - -Input that the running turn consumes, such as a steer, arrives before that turn's end and does not count as newer input: the turn that took it still offers. - -The unused counter: an offer shown and then cleared without an accept counts once; twenty in a row stop offering in that Session with `throttled`. The count resets on an accept and when the switch is turned on after being off, so turning suggestions off and on in `/settings` resumes them. The pause is Session-long on purpose: it stops spending requests on a user who does not use suggestions, and a user who ignores an offer is usually typing their own message. - -The context gate reads the request's line's usage through `ContextPreparation` exactly as `session.context.usage` reads it, before anything is built; the instruction's tokens are counted at four characters per token, since the part has no model counter. The suggestion never runs preparation and so never compacts: at a head where a real request would compact first, the suggestion is not sent, because it would be built on the prefix that request is about to replace. When the usage cannot be read (no compaction installed, no configuration yet), no compaction is imminent and the request proceeds as it is. - -A committed write that leaves the switch on cancels nothing: the shown offer and the request in flight were valid when they began, and the next request reads the new `maxChars`. - -Every accepted request carries its own invocation identity: a completion changes the slot and emits a notice only when the slot still holds that invocation, so a cancelled request that returns later changes nothing and announces nothing. - -A request registers in the slot, with its cancellation token, before its asynchronous preflight (`compaction_due`). A settings change, a new input, a dismissal and the Session's close cancel it there as they cancel one in flight; the start afterwards is decided again against the state and the settings as they are then, never against the values read before the preflight. A request cancelled during its preflight starts no model call, answers `{accepted: false, reason}` with the gate it now fails (or `dismissed`) and announces nothing. A request joining a preflight receives that invocation's result even if dismissal clears its slot or a newer invocation takes the slot before the owner returns. The joining request retains its own cancellation and Session shutdown handling. - -Cancellation always keeps the Session's one in-flight slot consistent, and each one emits `cleared` with its reason when an offer is showing or a request was accepted: - -| Trigger | Clearing reason | -| --- | --- | -| New input (`input/message`, `input/applied`) | `new_input` | -| A turn starts | `turn_started` | -| `session.suggestion.respond {action: dismiss}` | `dismissed` | -| `session.suggestion.respond {action: accept}` | `accepted` | -| The Session closes | `session_closed` | -| The 30 s deadline | `timeout` | -| The setting turns off | `disabled` | -| A `branch/default` moves the conversation | `branch_changed` | -| A model error, a tool call or a cancelled stream | `failed` | -| The validator rejects the reply | `invalid` | - -A request in flight that is cancelled emits `cleared` with the cancelling reason; a request that never produced an offer because it failed, timed out or was invalid emits `cleared` with `failed`, `timeout` or `invalid`. Every accepted request therefore ends in exactly one `offer` or one `cleared`. The notices are emitted under the part's state lock, so the order of notices matches the order of the state changes they report: an `offer` can never follow the `cleared` that withdrew it. - -Every reason is a stable `snake_case` code: `disabled`, `not_root`, `branch_changed`, `not_latest_turn`, `turn_not_completed`, `no_text`, `throttled`, `compaction_due`, `new_input`, `turn_started`, `dismissed`, `accepted`, `session_closed`, `timeout`, `failed`, `invalid`. - -## 9. Relation to Timeline branches - -The suggestion request is the first request a line cut at `main`'s head would send: the parent's prefix up to the cut, then the line's own input ([timeline branches §7.3](../timeline-branches.md#73-cache-prefix)). That is why the suggestion keeps the cache: it sends the same cut prefix a line would. - -The suggestion opens no line. A host line would, once per turn: - -- write `branch/create` on `main`; -- store its own events; -- run the Loop with the Session's tools; -- compact on its own near the threshold; -- appear in the lines panel. - -A line is also the same agent doing the work, and the suggestion plays the user ([§6](#6-the-instruction-and-the-validator)). Display-only state goes through a notice, never a line ([principles §4 rule 9](../../architecture/rust-agent/principles.md)). - -What the suggestion takes from branches is the cut and the shared prefix, and it writes nothing. - -The cached turn, the shown offer and the generation in flight belong to one line. `receive` follows `branch/default`: the committed move clears all three (a started generation is cancelled and announced as `cleared` with `branch_changed`), and the events of the new line replace them. Admission reads the line once and refuses a cached turn read from another one (`branch_changed`, before the part has seen the move; once `branch/default` is received the cache is empty and the request fails `not_latest_turn`); the compaction precheck reads that same line; and the completion re-reads it under the state lock before it publishes, so a generation that returns after a move offers nothing. The switch needs no new input and no new turn: a Session that moves back to an idle root simply has nothing cached to suggest from. - -## 10. Settings - -The process part declares one source: - -| Member | Type | Default | Range | -| --- | --- | --- | --- | -| `enabled` | boolean | `false` | - | -| `maxChars` | integer | `80` | 10 to 200 | - -`source: "prompt-suggestion"`, `userFile: "prompt-suggestion.json"`, no `projectFile`, `userOnly: []`: user scope only, with no project document. Unknown members are rejected. A project cannot turn on a feature that spends the user's tokens. Missing documents receive the defaults at the Settings boundary, and the value is read at each decision, so a change applies without a reload. - -## 11. Terminal client - -The CLI sends `session.suggestion.request` only after it witnessed a `turn/end` with `Completed` for that turn, and only when the composer is empty, no prompt or panel is open, no question or approval is pending and no goal is driving the Session. - -```text -scrollback, empty composer fullscreen, empty composer -┌──────────────────────────────┐ ┌──────────────────────────────┐ -│ › run the tests │ │ run the tests │ -│ │ │ │ -└──────────────────────────────┘ └──────────────────────────────┘ - the hint placeholder is the hint placeholder is - replaced by the offer replaced by the offer -``` - -The offer replaces the default hint placeholder with muted text in the empty composer row in both layouts, truncated with `…` to the text width and hidden below 20 columns. It never changes the composer's height and never wraps. - -| Input | Effect | -| --- | --- | -| `Right` | Accept: `set_draft` the text and send `respond accept`. Accepting never sends | -| `Tab` | Accept in the scrollback layout only, when the palette and mention picker are closed; in fullscreen `Tab` keeps card focus | -| `Enter` | Never sends the suggestion: an empty composer stays empty | -| `Esc` while idle | Hide the offer and send `respond dismiss` | -| Any edit | Hide the offer and send `respond dismiss` | -| A new turn or input | The offer is cleared by the daemon's notice | - -`/settings` gains a `Prompt suggestion` switch backed by the daemon's `settings.read`/`settings.update` on the `prompt-suggestion` source; its state is the source's `enabled`. The row and the read behind it exist only when the Session's method table lists the suggestion methods, read once per Session: a daemon without them is never probed and shows no row. The client reads the document in the capability's own type: a missing or malformed document, or a missing member, is an error the row shows, never a default the client invents. Every string the client adds exists in all ten locales. A request refused with `throttled` makes the client say once per Session that suggestions are paused and that turning the switch off and on resumes them; later refusals in the same Session stay quiet. - -## 12. Rule check - -Both parts are ordinary parts, not Capabilities: neither folds a branch's facts in sequence order nor writes a fact of its own domain ([principles §1](../../architecture/rust-agent/principles.md), [plugin contract §6](../plugin-contract.md#6-capability)). The Session part observes the Session broadcast, which is a bus event, not a Dispatcher subscription. - -| Rule | How this design complies | -| --- | --- | -| §1 (plugins and Capabilities are bounded) | One feature, two parts, each placed by the owner of its state; the App Server declares the Settings source and holds no feature logic; the offer is a notice, not a fact | -| §4 rule 1 (commands for others' state) | The part changes no other module's state: it reads public events and writes nothing; the Settings document is written by clients through `settings.update`, not by this feature | -| §4 rule 2 (handover) | Nothing is handed over; the part consumes `turn/end` after the loop wrote it, and never acts on an input | -| §4 rule 3 (`before` callbacks) | None | -| §4 rule 4 (no business meaning in core) | No core part knows PromptSuggestion; `ModelHost`, `ProviderConnectionResolver`, `sessionMethods` and `session.notice` are generic | -| §4 rule 5 (batches) | No Timeline write and no batch; notices have no sequence | -| §4 rule 6 (context from handed-over events) | The suggestion enters no model context. The offer is display-only and is never appended to history; the next real request is identical with and without it | -| §4 rule 7 (public events and services only) | Uses the public Session channel record, the public host ports, `sessionMethods` and `session_broadcast::notify`; reads no other part's state | -| §4 rule 8 (infrastructure unchanged) | No infrastructure change; [§13](#13-requirements-raised-to-mechanism-owners) raises nothing | -| §4 rule 9 (only facts later decisions use) | The offer is display-only and never read by a later decision, so it is a Session notice and not a Timeline event | -| Timeline branches | The suggestion shares a line's cut prefix ([§9](#9-relation-to-timeline-branches)) and opens no line: it writes no `branch/create`, stores no events, runs no Loop and appears in no lines panel | -| ADR 002 D1 (scope follows state) | The Settings document is process state shared by Sessions; the offer and the folded turn state belong to one Session | -| ADR 002 D2 (no wiring modules) | No wiring module; each part declares its dependencies by name, and the process part provides the source's port | -| ADR 002 D3 (dependencies follow scope) | Dependencies point from the Session part up to the process; no core part depends on this plugin, and an assembly without it behaves exactly as before | -| ADR 002 D4 (structural vs business configuration) | Installation is structural; `enabled` and `maxChars` are business configuration in the plugin's own source, read at use time, and changing them reloads nothing | -| ADR 002 D5 (language-neutral contracts) | The methods, the notice record and the Settings schema are data; the Rust types are the binding ([§7](#7-methods-and-notices)) | - -## 13. Requirements raised to mechanism owners - -None ([principles §4 rule 8](../../architecture/rust-agent/principles.md)). The feature is assembled from existing contracts: the Session broadcast ([Session broadcast notices](../appserver/session-notices.md)), the Session method table ([session boundary](../contracts/session-boundary.md)), `ModelHost`, `ProviderConnectionResolver`, the Settings source declaration and `SessionLifecycle`. - -## Appendix A. Interface details - -### A.1 Depended-on shapes - -| Service | Method or record | Kind | Request | Reply | -| --- | --- | --- | --- | --- | -| `ModelHost` | `invoke` | async | `{request, connection, cancel}` | A stream of `ModelChunk` | -| `ProviderConnectionResolver` | `resolve` | async | `{request, cancel}` | `{connection, failurePolicy, recovery}` (process models only; a local model sends `ModelConnection::Local`, and its assembly installs the part with `install_local` instead of `install`) | -| `SessionMethods` | `register` | sync | namespace `session.suggestion`, two declarations | The registrations end with this part's generation | -| `TreeCommands` | `get` | sync | `main` | The branch, whose `ContextPreparation::usage` the context gate reads | -| Session broadcast | record on `session/{sessionId}` | bus event | - | `Event {branchId, event}`, `Notice`, `Fence`, `Closed` | -| Settings source `prompt-suggestion` | `read` | async | user scope | `{enabled, maxChars}` | - -### A.2 Request shape - -```text -request.messages = turn.messages - + [assistant: turn content] - + [user: instruction] -request.{provider, model, capability snapshot, system, tools, config} - = turn's, unchanged -metadata: turnId and extensions.requestId gain "/suggestion" -``` - -### A.3 Reason codes - -| Code | Kind | -| --- | --- | -| `disabled` | gate; also cancellation when the setting turns off | -| `not_root` | gate | -| `branch_changed` | gate; also cancellation when `branch/default` moves the conversation | -| `not_latest_turn` | gate | -| `turn_not_completed` | gate | -| `no_text` | gate | -| `throttled` | gate | -| `compaction_due` | gate: the head would compact before this request | -| `new_input`, `turn_started`, `dismissed`, `accepted`, `session_closed` | cancellation of a shown offer or an accepted request | -| `timeout`, `failed`, `invalid` | an accepted request that produced no offer | - -## Appendix B. Acceptance - -Transport flows (`crates/dim-app-server/tests/transport_flow/prompt_suggestion.rs`): - -1. For each of `anthropic`, `openai-compatible` and `openai-responses`, a turn and a suggestion against a recording endpoint: the suggestion body's `system`, `tools` and every earlier message's text equal the turn's last request's, exactly the assistant message and the instruction follow, and `max_tokens`, reasoning, tool choice and service tier are equal. On `anthropic` the comparison ignores the automatic `cache_control` marker, which the converter places on the last user message and so moves to the instruction. -2. The branch's events are the same before and after a suggestion, and the next real request is identical with and without one. -3. One flow per gate: disabled, not the latest turn, no text in the last content, a non-root Session, and a cached turn from another line (`branch_changed`). A turn that took a steer still offers, and an input after a completed turn refuses that turn as `not_latest_turn`. -4. One flow per cancellation: new input, a turn start, a newer request, dismissal, Session close, and a `branch/default` that withdraws the generation in flight. The deadline is not pinned by waiting 30 s. The preflight is pinned too: a switch turned off or a dismissal while the usage check is pending starts no model call and refuses the request, and a cancelled predecessor returning after a newer request for the same turn announces nothing. -5. The validator: a multi-line reply, a leading `/`, ``, a refusal and a repeat of the last user message each clear with `invalid`. -6. The unused counter: 20 unused offers then `throttled`; an accept resets it, and so does turning the switch off and on. -7. The context gate: a model whose usage puts `main`'s head over its threshold makes `request` answer `compaction_due` and start no model request. -8. Settings: the default is off, `maxChars` is range-checked, project scope is refused, and a change applies without a reload; a `maxChars` rewrite keeps a shown offer, and turning the switch off clears it with `disabled`. - -CLI flows (`crates/dimcode/tests/cli_flow/prompt_suggestion.rs`) over a scripted daemon: the request is sent only after a completed turn with an empty composer; the offer is drawn in both layouts and truncated on a narrow terminal; `Right` inserts without sending; `Tab` accepts in scrollback and focuses a card in fullscreen; `Enter` on an empty composer does not send; `Esc` and an edit dismiss and send `respond dismiss`; `/settings` toggles the switch; a `throttled` refusal is announced once per Session. - -## Appendix C. Evaluation - -`xtask`'s `prompt-eval` measures the suggestion's accuracy over scripted sessions that a live model drives. The set under `xtask/scenario-eval/prompt-suggestion/` holds sixteen conversations of four to six user turns, in English and Chinese: twelve on small workspaces, three long sessions on the 131,072-token window whose first turn reads several large files, and one on a small window whose head crosses its compaction threshold during the run. The live phase drives each scenario as a client does and exports its Timeline; the replay phase predicts at every completed turn that has a next scripted message, twice: - -- arm A builds the request with `suggestion_request` over the recorded `model/call` and the content the recorded `model/content` or `step/*` events fold into, and asserts on every boundary that it is the recorded request plus exactly two messages, and that it equals the next real request up to its last message wherever the Context did not compact that request; -- arm T sends the first user message and the last six user and assistant messages, each cut to 2,000 characters, the same instruction, one fixed predictor system and no tools. - -Both arms pass the gates of [§8](#8-gates-cancellation-and-reasons), with the switch on and the document's default limit, and pass the reply through the validator of [§6](#6-the-instruction-and-the-validator). A fixed judge, blind to the arm, reads the conversation tail, the actual next message and the suggestion, and answers two 0/1 questions: whether the suggestion asks for what the actual next message asks for, and whether it is a plausible next message. The report gives every metric per arm and per prefix-size bucket, the skips per reason, the refusals per validator rule (a reply that is exactly `` counts as `sentinel`, the instruction's abstention, not as a format failure), the comparison of the arms with the test of [model-prompts §8.1](../model-prompts.md#81-the-rule), and the limits of the measurement. - -```text -cargo run --locked -p xtask -- prompt-eval --scenarios xtask/scenario-eval/prompt-suggestion \ - --model PROVIDER/MODEL --judge PROVIDER/MODEL --out DIR \ - --model-config WINDOW=FILE [--model-config WINDOW=FILE]... [--run SCENARIO]... \ - [--price INPUT,CACHED,OUTPUT --price-source TEXT] -``` - -`--price` gives the vendor's published list price in USD per million tokens for uncached input, cache-hit input and output; `--price-source` names where the rates were read, and the report charges each token class at its own rate and names the source. - -A run resumes where it stopped: a scenario with a saved session is not driven again, and a boundary whose two arms are saved is not predicted again. `cargo test -p xtask` replays a small committed fixture with a stub generator and no network. diff --git a/docs/design/plugins/Questions.md b/docs/design/plugins/Questions.md index 99084d6937..a166de1851 100644 --- a/docs/design/plugins/Questions.md +++ b/docs/design/plugins/Questions.md @@ -154,144 +154,7 @@ pub enum QuestionError { } ``` - -The model asks the user one or more questions through the `ask_user` tool and waits for the answer: single choice, multiple choice, several questions in one call, custom answer, or a decline. **The question is the pending tool call, and the answer is its tool result.** A client sees the question as the committed `step/tool-call` of `ask_user` that has no `step/tool-result` yet, answers it with the Session method `session.question.respond`, and the waiting handler returns the answer as its `ToolResult`; ToolExecutor publishes it in the batch's `step/tool-result` like any other tool output. The model learns the user's choice only from `ToolResult.content`. - -Questions defines **no Timeline events** and has **one part**, a Session Capability. It registers the `ask_user` tool with the Session's `toolRegistry` and provides the method `session.question.respond` by registering the namespace `session.question` with `sessionMethods` ([session-boundary](../contracts/session-boundary.md)), and holds, in memory, the waiters of the Session's running `ask_user` calls, as a running tool holds its I/O. Interrupt, close, reload, restart and fork are settled by the existing tool-call lifecycle of [ToolExecutor](../../architecture/rust-agent/plugins/ToolExecution.md#toolexecutor). - -Changes from the merged redesign ([#178](https://github.com/arcships/dim/pull/178)), all from checking it against current `main` and the ablation review (§11): - -- The branch part is removed. The waiter is part of the `ask_user` handler's own call, which already runs in the Session part, so the table moves there, keyed by `(branchId, requestId, callId)`. An entry lives exactly as long as its handler waits; the Dispatcher subscription on `step/tool-result` and the `already_answered` and `cancelled` replies go with it (§11). -- A waiting call is named by `(branchId, requestId, callId)`, where `requestId` is the `request_id` of the call's `step/tool-call`. Call ids may repeat in later model requests, so without it a late answer to a settled call could become a later call's result (§4.3). -- `exec` Sessions are interactive ([CLI commands](../cli-commands.md#execution-and-jsonl-output)); only `session.create {interactive: false}` and `sessions.launch` create non-interactive Sessions (§3.3). -- The text the model reads on interrupt and close is now specified (A.1), and a graceful restart is told apart from a crash or forced shutdown (§4.2). -- The Rust binding uses the implemented `SessionMethods` and `ToolHandler` (Appendix G). -- The client protocol is given with payloads (§3.4) and the CLI with an ASCII rendering (A.5). -- Former F1 now needs no new mechanism (C6 notices are implemented) and former F2 is Approval's, already decided ([CLI commands](../cli-commands.md#execution-and-jsonl-output), [sessions-service D10](../appserver/sessions-service.md)). - -## 1. Structure - -```mermaid -flowchart LR - subgraph P["Process scope"] - RPC["Rpc"] - end - subgraph S["Session scope"] - QS["QuestionsPlugin: tool ask_user, sessionMethods session.question, waiters (branchId, requestId, callId)"]:::new - TR["ToolRegistry"] - CFG["SessionConfig"] - SB["Session broadcast"] - end - subgraph B["Branch scope"] - TE["ToolExecutor"] - TL["Timeline + Dispatcher"] - end - QS -- "registers ask_user" --> TR - TE -- "execute(call, {branchId, requestId}, batch cancel token)" --> QS - RPC -- "sessionMethods session.question" --> QS - QS -- "reads interactive per call" --> CFG - TE -- "step/tool-call, step/tool-result" --> TL - TL -- "dispatched events" --> SB - SB -- "session.event" --> RPC - classDef new fill:#d3f9d8,stroke:#2b8a3e,color:#000 -``` - -Contracts are given in language-neutral form; the Rust form is [Appendix G](#appendix-g-rust-binding). - -| Part | Scope | Depends on | Provides | -| --- | --- | --- | --- | -| `QuestionsPlugin` | Session | `S:SessionConfig`, `S:ToolRegistry`, `S:SessionMethods`, `S:TreeCommands` | Registers `ask_user` with `toolRegistry` and `session.question` (`session.question.respond`, `session.question.pending`) with `sessionMethods` | - -Installation: the part is installed whenever the plugin is enabled; installation never reads `SessionConfig.interactive` ([session access §9.4](../contracts/session-access.md#94-optional-parts-per-enabled-plugin)), so every Session that mounts `ask_user` declares it whatever its `interactive` (a Session without a mount list mounts it, one with a list when the list names it), and a fork keeps the same tool set and prompt prefix. - -Contracts depended on, all implemented on `main`: - -| Contract | Owner | Status | -| --- | --- | --- | -| Tool registration with `toolRegistry`, offered while its registering part is loaded ([session-boundary A.5](../contracts/session-boundary.md#a5-tool-contribution)) | ToolRegistry | Implemented (#241, #382) | -| Tool call execution: the call's `ToolExecutionContext.branchId` and `requestId` (the `request_id` of its `step/tool-call`), one cancel token per batch cancelled by `stop/interrupt` and by ToolExecutor's unload, a returned result kept when the cancel comes later, `HostError::Cancelled(reason)` written as an error result with `reason` as its text, reload-settled results that fail the turn ([tool_executor.rs](../../../crates/dim-agent-capabilities/src/tool_executor.rs)) | ToolExecutor | Implemented | -| `sessionMethods` with `MethodDecl {name, mutating, interruption, progress}` ([session-boundary A.1](../contracts/session-boundary.md#a1-method-contributions)) | Rpc, runtime | Implemented (C1) | -| `SessionConfig.interactive`, absent means `true` ([session access A.3](../contracts/session-access.md#a3-sessionconfig-fields)) | Agents | Implemented (C2) | -| `step/tool-call` and `step/tool-result` data contracts (both carry `request_id`) and their `session.event` forwarding, every branch, v2 and v3 ([tree_protocol.rs](../../../crates/dim-app-server/src/tree_protocol.rs)); `session.history` per branch; `session.stop {sessionId, branchId}` | Timeline, Rpc | Implemented | -| Permission risk category `session` ([permission.rs](../../../crates/dim-agent-capabilities/src/permission.rs)) | Permission | Implemented | - -Contracts defined here: the `ask_user` tool (declaration, input schema, result text), `session.question.respond`, `session.question.pending`, their errors, and the pending-question rule. - -## 2. Data and state - -```mermaid -stateDiagram-v2 - [*] --> claimed: Loop calls claim, before step/tool-call is appended - claimed --> waiting: dispatch keeps the registration - claimed --> [*]: the claim drops (append refused, interrupt before dispatch, Loop error, reload) - waiting --> [*]: respond (answer sent; entry removed) - waiting --> [*]: batch cancel token fires (entry removed; Cancelled) - waiting --> [*]: part unloads (senders dropped; Cancelled capability reloading) -``` - -The part keeps one table, `(branchId, requestId, callId) → {questions, sender}`, under a mutex (no `StateCell`). `requestId` is the model request that proposed the call: `ToolExecutionContext.requestId`, the same value as the `request_id` of its `step/tool-call`. The key needs it because call ids repeat across requests (§4.3). Only waiting calls have entries; whoever removes the entry under the lock decides the call's output, so `respond` and cancellation never both win. The table is never carried across generations and is not rebuilt: an entry is an I/O wait on a human, and a call left waiting by a reload or restart is settled by ToolExecutor ([design rules](../../architecture/rust-agent/principles.md) §4 rule 9; AGENTS.md rule 4). - -### 2.1 The claim before the fact - -The registration must exist no later than the `step/tool-call` that shows it. Loop writes that fact -and ToolExecutor only consumes it afterwards, so a registration made in the handler leaves a window in -which a client holds a published question that `respond` refuses as `question_not_pending`. `ask_user` -therefore claims before the fact: `ToolHandler::claim` returns an owned guard whose `Drop` removes the -table entry, Loop creates the claims immediately before appending the batch, and ToolBinding holds them -with the request's tool snapshot. - -The guard covers every path that does not reach the call's dispatch, without a separate release step: -a refused append, `stop/interrupt` before dispatch, a refused admission, a cancelled task, a Loop error -and a capability reload all drop the snapshot's claims. A claim that reaches dispatch is taken by -ToolExecutor and consumed by `ToolClaim::dispatch`, which receives the call as resolved and approved -and keeps the registration until the answer or the cancel token ends the wait. A live `execute` called without a retained claim -claims for itself, so the handler has one registration path in both cases. - -An answer accepted between the claim and a refusal is delivered and then dropped with the claim: the -call's result is the refusal, and the question does not stay open. - -What the Timeline already holds, and why nothing else is written: - -| Need | Existing fact or channel | Why no Questions fact | -| --- | --- | --- | -| The question exists and is pending | The committed `step/tool-call` with an `ask_user` call (its `input` is the questions; its `data.request_id` and the call id name it) and no `step/tool-result` whose `call_event_id` is that event's `id` | Derivable from history and live `session.event`; clients already receive both | -| The answer reaches the model | The handler's `ToolResult`, committed by ToolExecutor in `step/tool-result` | `ToolResult.content` is the only text the model reads; a second copy decides nothing | -| Answer versus interrupt | ToolExecutor consumes `stop/interrupt` and cancels the batch token; Questions decides under its lock whether the answer or the cancel came first; a result returned before the cancel is kept, like any tool's | The answer is tool output, not a command to another module: no later decision reads it except the model, through the result (rules 1 and 9) | -| Prompt closes on other clients | `step/tool-result` of the batch | A notice before the batch settles is display only; rule 9 sends display through Session broadcast notices, and none is required (F1) | -| Answer survives a crash before the batch settles | — | After a restart the turn is already `Failed` and the batch reload-settled ([single-tree](../../architecture/rust-agent/single-tree.md) reload rules); a durable answer would be read by nothing. The same window exists for every tool | -| Interrupt, close, reload, restart outcome | ToolExecutor's `step/tool-result` | Owned by ToolExecutor | - -**Event declaration** ([ADR 001](../../adr/001-harness-foundation.md#events-and-ownership-issue-2)): Questions writes no events and has no Dispatcher subscription. The pending read depends on `step/tool-call` and `step/tool-result`. The waiters still depend only on their tool execution and cancellation contracts; the read neither rebuilds nor changes them. - -**Dynamic events ([#2](https://github.com/arcships/dim/issues/2)):** decided on 2026-10-20 ([ADR 001](../../adr/001-harness-foundation.md#events-and-ownership-issue-2), [#233](https://github.com/arcships/dim/pull/233)). Questions writes no events, so it needs neither an extension event type nor the future dynamic protocol; the previous draft's R1 stays withdrawn. - -## 3. Flows - -### 3.1 Ask and answer - -```mermaid -sequenceDiagram - participant M as Model (Loop) - participant TE as ToolExecutor - participant Q as Questions (Session) - participant C as Client - M->>TE: step/tool-call [ask_user {questions}] - Note over Q: claim before the append: lock, insert (branchId, requestId, callId) waiting - Note over C: session.event step/tool-call: show prompt - TE->>Q: dispatch(call, caller, cancel) - C->>Q: session.question.respond {sessionId, branchId, requestId, callId, answers} - Q->>Q: lock: validate, remove entry, send answer - Q-->>C: {} (the answer is the call's output) - Q-->>TE: ToolResult (content: the answers) - TE->>TE: other calls of the batch settle - Note over TE: step/tool-result committed - Note over C: session.event step/tool-result: prompt closed -``` - -The registration happens before the `step/tool-call` is appended, not when the call is dispatched -([Questions §2.1](#21-the-claim-before-the-fact)). A client may therefore answer a question it drew -from the published batch alone. `{}` means the answer was handed to the waiting call and will be its -result unless the batch is reload-settled (§4.2). +## Client attach and forks ### 3.2 Clients, attach and several clients @@ -303,99 +166,7 @@ history + live session.event, one branch seq 42 step/tool-result {call_event_id: e41, request_id: r1, results: [c1]} -> close prompt for (r1, c1) ``` -A client keeps the call's `requestId` with its prompt and sends it back with the answer. Several clients may answer; the first `respond` decides and the others get `question_not_pending`. A client that gets `question_not_pending` keeps its prompt until the batch's `step/tool-result` arrives, which closes it on every client (A.3, A12). - -### 3.3 Non-interactive Sessions - -`ask_user` is declared as in any Session. Its handler reads `SessionConfig.interactive` per call; when it is `false` (Sessions created by `session.create {interactive: false}` or by `sessions.launch`, which Scheduler and Workflow runs use), the call returns at once with an error result saying that no one can answer and the model should proceed without asking (A.1). No entry is registered, so `respond` finds nothing. - -`dimcode exec` creates and attaches to an **interactive** Session; it is that Session's interaction client and does not change `interactive` ([CLI commands](../cli-commands.md#execution-and-jsonl-output)). When it has no terminal input it treats a question as it treats an approval: it stops the turn and exits with code 3 (A.5, A8). Approvals in non-interactive Sessions keep Approval's existing owner-side policy ([sessions-service D10](../appserver/sessions-service.md)); Questions does not decide it. - -### 3.4 Client protocol - -No new notification; both methods use the Session method registry. All payloads are JSON-RPC over the existing connection. - -The question arrives as the existing `session.event` notice carrying the `step/tool-call` event in its existing wire form (shown abbreviated): - -```json -{"method": "session.event", "params": {"sessionId": "s1", "branchId": "main", - "event": {"type": "step", "name": "tool-call", "id": "e41", "sequence": 41, - "data": {"turn_id": "t1", "request_id": "r1", "calls": [ - {"id": "c1", "name": "ask_user", "input": {"questions": [ - {"header": "Database", "question": "Which database should the service use?", - "options": [{"label": "PostgreSQL", "description": "managed, relational"}, - {"label": "SQLite", "description": "single file"}]}]}}]}}}} -``` - -The client answers with `session.question.respond`: - -```json -{"id": 7, "method": "session.question.respond", "params": {"sessionId": "s1", "branchId": "main", - "requestId": "r1", "callId": "c1", "answers": [{"questionId": "1", "selected": ["PostgreSQL"]}]}} -{"id": 7, "result": {}} -``` - -`requestId` is the `request_id` of the `step/tool-call` that holds the call. A decline sends `"declined": true` and no `answers`. An error is the existing `MethodError` form with `error.data.appError` (A.3), for example `question_not_pending`. The prompt closes on the `session.event` notice of the `step/tool-result` whose `call_event_id` is `e41`; its `results[]` entry for `c1` carries the `ToolResult` (`content`, `structuredContent`, `isError`). `session.methods` lists `session.question.respond` in every Session where Questions is enabled. - -### 3.5 Pending-question read - -`session.question.pending {sessionId, branchId, through?, after?}` returns -`{branchId, through, batches, next}`. `through` is the branch's published cutoff; -every continuation supplies that same cutoff and the opaque `next` cursor as -`after`. A page selects at most 128 unresolved tool batches in ascending branch -position. It reads only that branch, not its inherited prefix. `next: null` ends -the inventory at this cutoff. - -Each batch contains `eventId` (the `step/tool-call` identity), `sequence`, -`requestId` and `calls` (only its `ask_user` calls, using the existing ToolCall -shape, with complete input). Clients retain those batch identities when merging -live results; call ids alone are not unique. A response accepted before the batch -result commits does not remove the batch from this read: §2 and A12 define -pending by the terminal fact, not by the private waiter table. - -The owner queries `step/tool-call` rows that contain an `ask_user` call and have -no `step/tool-result` naming their event id. The first query selects identities -and call names only. For each selected batch it reads the exact array positions -of its question calls at the same cutoff; arguments of other tools are not read. -The operation retains one page, has no history cache, and writes no facts. -The query plan and indexes must bound database work as well as returned bodies; -a small response alone is not performance acceptance. - -Unknown branches, invalid cutoffs or continuations, reload and storage errors use -the existing facade/method errors. A continuation without its original cutoff is -invalid. Cancellation releases the read without changing questions or waiters. - -## 4. Timing and conflicts - -### 4.1 Answer versus interrupt - -```mermaid -sequenceDiagram - participant TL as Timeline - participant TE as ToolExecutor - participant Q as Questions (Session) - participant C as Client - TL->>TE: stop/interrupt (seq n) - TE->>Q: batch cancel token fires - Q->>Q: lock: remove entry - Q-->>TE: Cancelled ("The question was cancelled before the user answered.") - C->>Q: respond (after the cancel) - Q-->>C: question_not_pending -``` - -Exactly one of `respond` and the cancel removes the entry. If `respond` wins, the handler returns the answer even when the cancel arrives a moment later; ToolExecutor keeps a returned result, and the turn still ends cancelled. If the cancel wins, `respond` replies `question_not_pending`, and the batch's `step/tool-result` shows the cancelled result. Either way the client's reply is the truth about the call's output, and only ToolExecutor writes the call's terminal fact. A stop that arrives before the batch is dispatched never reaches the handler: ToolExecutor writes its own "not executed" text (A.1). - -### 4.2 Reload, restart, close, delete - -| Scenario | Outcome | -| --- | --- | -| Questions part reloads while waiting | Unload drops the senders; handlers return Cancelled with `capability reloading`; the batch is reload-settled and the turn fails ([ADR 002](../../adr/002-plugin-scope.md) D3). ToolRegistry does not reload with it; the new generation registers again and the next request offers it, without a Session reload ([session-boundary A.5](../contracts/session-boundary.md#a5-tool-contribution)). Nothing is re-asked | -| ToolExecutor (branch) reloads while waiting | Its unload cancels the batch token; the handler removes its entry and returns; ToolExecutor writes reload-settled results and the turn fails | -| Graceful restart while waiting (SIGINT, SIGTERM, `daemon.shutdown` without `force`) | The App Server closes every loaded Session as `session.close` does (close row below); after the restart the call is already settled and is not asked again | -| Crash or forced shutdown while waiting | On restore, ToolExecutor's rebuild settles the open batch as not executed (`capability reloading`); the turn fails | -| Answered, then reload before `step/tool-result` | The batch is reload-settled; the answer is lost with it (accepted, as for every tool) | -| Branch close, `session.close`, Session delete | A business close, not an unload: it first writes a branch-scope `stop/interrupt`, ToolExecutor cancels the batch token, the waiting call ends cancelled (A.1), and the turn ends Cancelled before the branch is removed ([lifecycle §5](../../architecture/rust-agent/lifecycle.md#5-stop-与-close), [session deletion](../appserver/session-deletion-and-fork.md)). A close that finds the Dispatcher failed or the Loop reloading does not wait for these facts, and the unfinished turn settles as a reload does | -| Session unload while waiting | Does not happen: the turn is running, so the Session is not idle | +A client keeps the call's `requestId` with its prompt and sends it back with the answer. Several clients may answer; the first `respond` decides and the others get `question_not_pending`. A client that gets `question_not_pending` keeps its prompt until the batch's `step/tool-result` arrives, which closes it on every client. ### 4.3 Fork and branches @@ -415,328 +186,10 @@ branch main, two clients R2 step/tool-result {request_id: r2, results: [c1 "... Delete production data? -> No"]} ``` -Other key rows (full table: Appendix B): - | Scenario | Outcome | | --- | --- | | Client answers before the handler registered | `question_not_pending`; the batch has no result yet, so the client keeps the prompt and lets the user resend | | Two clients answer | First accepted; second `question_not_pending`; both prompts close at `step/tool-result` | | A late answer or decline to a settled call whose call id a later call reuses | `question_not_pending`: the `requestId` differs. The later call keeps waiting and accepts its own answer | -| `exec` without terminal input | The CLI stops the turn with exit code 3 (A8) | -| Steer, Queue, Append while waiting | No effect on the question; consumed after the batch or turn as usual (A11) | - -## 5. Context mapping - -| What the model sees | Form | Placement | -| --- | --- | --- | -| `ask_user` name, description, schema | Fixed tool declaration | Adopted `context/configured`, every Session that mounts it | -| Answers or decline | `ToolResult.content` (A.1) | Tool result position, after every call of the batch settles | -| No one can answer (non-interactive) | Error `ToolResult.content` | Same position | -| Cancellation, reload, not executed | Error text (A.1) | Same position | - -Never visible: the waiter table, `structuredContent`, client rendering. Compaction keeps the declaration and keeps answers only through the summary. - -Every text in the table is protocol except the policy sentences this paragraph marks ([model-facing prompts §4](../model-prompts.md#4-protocol-and-policy)), and two of them are mixed, marked sentence by sentence: in `User declined to answer. Proceed without these answers.` and `No one is available to answer questions in this session. Proceed without asking.`, the first sentence is protocol — it states what happened — and the `Proceed without …` sentence is policy: it is advice, and nothing parses it. The rest are protocol: the answers, `The question was cancelled before the user answered.`, and the invalid-input refusals `Invalid ask_user input: `. The answered form is a handle: `User answered:`, then one numbered line per question and its `->