From f210fb4991003c957397f9a7d3bf9175327fa379 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Mon, 23 Nov 2026 14:59:20 +0800 Subject: [PATCH 01/11] docs(design): target contracts for the branch tool chain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Six owner contracts under design rules §7: ToolBinding, ToolExecutor, Approval, Permission, BackgroundExec and FileReads. Each states its responsibility split, caller intents, operations, errors, flows, rule check and the requirements raised to ToolRegistry, Prompt, the Session access mechanism and HostPlatform. --- docs/design/plugins/Approval.md | 204 ++++++++++++++++++++ docs/design/plugins/BackgroundExec.md | 231 +++++++++++++++++++++++ docs/design/plugins/FileReads.md | 217 ++++++++++++++++++++++ docs/design/plugins/Permission.md | 255 +++++++++++++++++++++++++ docs/design/plugins/README.md | 6 + docs/design/plugins/ToolBinding.md | 257 ++++++++++++++++++++++++++ docs/design/plugins/ToolExecutor.md | 197 ++++++++++++++++++++ 7 files changed, 1367 insertions(+) create mode 100644 docs/design/plugins/Approval.md create mode 100644 docs/design/plugins/BackgroundExec.md create mode 100644 docs/design/plugins/FileReads.md create mode 100644 docs/design/plugins/Permission.md create mode 100644 docs/design/plugins/ToolBinding.md create mode 100644 docs/design/plugins/ToolExecutor.md diff --git a/docs/design/plugins/Approval.md b/docs/design/plugins/Approval.md new file mode 100644 index 0000000000..bc75c4ee24 --- /dev/null +++ b/docs/design/plugins/Approval.md @@ -0,0 +1,204 @@ +# Approval + +Scope: branch. Issue: #2028. + +Approval owns one call's admission and the approval questions it produces: it asks Permission for the policy decision, asks the user when the policy or an advisor requires it, waits for the answer, rechecks the policy before the call starts, and settles every request it left open when the generation ends. This document is the owner's target contract; the current implementation is described in the [Permission plugin page](../../architecture/rust-agent/plugins/Permission.md#approval). + +## Use and scope: responsibility split + +Approval owns: + +- **Admission.** One call's admission: the policy decision, the advisor advice, the user's answer when required, and the final allow or refusal. +- **Pending requests.** The committed approval requests that no answer or cancellation has ended, in request order, as their `approval/request` payloads. A request exists from its commit until the answer, a policy settlement or a cancellation ends it. +- **The answer path.** An answer commits `approval/respond` and settles the request; the owner answers the caller once the branch dispatched the answer. +- **Settlement on behalf of policy and lifecycle.** A policy change rechecks a waiting call; an allow ends the question with `approval/cancelled` and its reason. The generation's close cancels every request it still holds; a reload cancels the historical requests whose execution did not survive. + +Approval does not decide the policy (Permission does), run tools (ToolExecutor does), or notify clients: the client notifications are the App Server's projection of `approval/*` facts and its own attach ordering. + +Callers keep as business: + +- When a tool call is admitted, and what a refusal means for the turn. +- Which questions a client shows and when it retires them. +- The meaning of a "yes" beyond the call: a session grant is the grant owner's record. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Admit one call, waiting for the user when required | No: composing it in the executor would duplicate the recheck rule and hold the pending state across the wait | `admit` | +| Answer a pending request | No: the answer must be committed as a fact and accepted only while the request is pending | `decide` | +| List the pending requests of a line | No: the set is the owner's state | `pending` | +| Recheck the policy when it changes while a question is open | No: the owner subscribed to the published policy value; a caller cannot see every change it must react to | the owner does it; no caller operation | + +An operation exists only where its row says No. + +## Caller example + +ToolExecutor admits one call with the batch token; dropping the call is the caller's cancellation: + +```rust +approval.admit(AdmitRequest { + source: BranchSource::Tool { turn_id, request_id, call_id }, + call: ApprovalCallData { name: call.name.clone(), input: call.input.clone() }, + risk: risk.clone(), +}, cancelled.clone()).await?; // Denied { reason }, Cancelled, Closed +``` + +A client answers one request; the answer is accepted only while the request is pending: + +```rust +approval.decide(DecideRequest { + approval_id: request.approval_id, + decision: ApprovalDecision::Allow, +}).await?; // Unknown (answered, cancelled or never pending), Closed +``` + +Collaboration lists a member line's pending approvals and answers the one it was asked about: + +```rust +for request in approval.pending().await?.requests { + if request.approval_id == target { + approval.decide(DecideRequest { approval_id: target, decision }).await?; + } +} +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `B:Permission` | One policy decision for a call, with the call's source when it is an admission. | +| `B:Permission`'s published `PermissionState` | Observe a policy change while a question is open; the owner rechecks on a change. | +| `B:Timeline`, `B:Dispatcher` | Commit `approval/request`, `approval/respond` and `approval/cancelled`; recover abandoned requests. | + +The policy value is a read-only view Permission publishes (§7); Approval takes it and its change subscription, never Permission's internals. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `admit` | Admit one call, asking the user when required | `{source, call, risk}` | `{}` | The caller drops the call: the pending request is cancelled and the call ends `cancelled` | `denied {reason}`, `cancelled`, `closed` | +| `pending` | The requests no answer or cancellation ended, in request order | `{}` | `{requests}` | None | `closed` | +| `decide` | Answer a pending request | `{approvalId, decision}` | `{}` | None: an accepted answer is committed | `unknown` (not pending: answered, cancelled or never existed), `closed` | + +`risk` is the tool owner's declaration for the call, or absent. `source` identifies the caller and is passed to Permission for the admission decision. The reply to `decide` means the branch dispatched the answer, not that the tool started. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `denied` | `admit` | Do not run the call; the result carries the reason. | +| `cancelled` | `admit` | The batch token was dropped or the batch was interrupted; do not run the call. | +| `closed` | any | The generation is closing or reloading; stop. | +| `unknown` | `decide` | The request is no longer pending; retire the prompt and do not retry the answer. | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `admit` — allowed without a question | Ask Permission; an allow returns | The token is checked before the call starts | Nothing held | Refused with `closed` | Approval and Permission | +| `admit` — a question is required | Commit `approval/request`, register the pending request, wait for the answer or a policy change; on an allow, recheck the policy and return; on a deny, return the refusal | The pending request is removed and `approval/cancelled` is written; the call ends `cancelled` | The pending request is cancelled with the same terminal | Every pending request of the generation is cancelled; an in-flight wait ends `closed` | Approval: the request, its terminal and the waiter | +| `admit` — policy changed while waiting | Recheck through Permission; an allow without an advisor question ends the question with `approval/cancelled` and its reason; a deny ends it with the refusal; an ask keeps waiting | As above | As above | As above | Approval | +| `decide` | Commit `approval/respond`, answer the waiter once the branch dispatched it; the admission rechecks before the call starts | — | A committed answer stays; the admission may end `closed` | A response to a request of a closed generation is `unknown` | Approval | +| `pending` | One consistent read under the owner's lock | — | — | Answered at the state observed | Approval | + +A call that a policy change no longer requires is not restarted; an explicit advisor question stays pending until answered. The owner never fabricates a user answer. + +## Exceptions with reasons + +- `pending` is kept although the App Server's attach path no longer needs a lock-held replay: the Collaboration route in [runtime-owner-operations.md](../contracts/runtime-owner-operations.md) reads a member line's pending approvals, and one owner operation serves it. The App Server orders its own notifications; the owner promises only a point-in-time set. + +## Verification + +Flow tests on the owner: + +- An allow without a question returns without a request; an ask writes one request, and the call starts only after the answer and the recheck. +- A dropped admission removes its request and writes `approval/cancelled`; a policy change that allows the call ends it the same way and starts the call; a policy change that denies it returns the refusal. +- An advisor's question stays pending across a policy change; only an answer settles it. +- A second answer to the same request is `unknown`; an answer to a cancelled request is `unknown`. +- The generation's close cancels every pending request; a reload cancels the historical requests and rebuilds an empty pending set. +- The face and the Rust call answer the same requests and errors. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | Approval is one branch part and a Capability: it injects `dispatcher` and `timeline` and folds `approval/respond`. | +| §2 scopes | Branch: a call's admission belongs to the line that runs it. | +| §3 orthogonality | Permission's policy and decision are separate owners; Approval coordinates through their operations and the published value. | +| §4 rule 1 | The answer is a command (`approval/respond`); the owner consumes it and writes the outcome. | +| §4 rule 2 | A request handed to a client is not taken back; only the answer or a terminal ends it. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No business meaning in core or assembly. | +| §4 rule 5 | A terminal and the state it ends are one batch. | +| §4 rule 6 | Approval facts carry no model context; the tool result is the model's only outcome. | +| §4 rule 7 | Permission is asked through its operation; the policy value is a published read-only view. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | Requests and their terminals are facts later decisions use; client notifications stay broadcasts. | +| §7 resources and objects | Pending requests are the owner's state; no waiter handle or guard crosses. | +| §7 no proxy | The owner answers its own requests and returns its own state. | +| §7 one surface | `admit`, `pending`, `decide`; `respond` and `replay` are removed. | +| §7 cross-language | Every parameter and reply is data; cancellation is dropping the call. | +| §7 responsibility split | The caller keeps the turn's use of a refusal; the owner keeps the question, the recheck and the settlement. | +| ADR 002 D1 | Branch scope. | +| ADR 002 D2 | No wiring part. | +| ADR 002 D3 | Depends on Permission (branch) and the branch infrastructure. | +| ADR 002 D4 | No configuration. | +| ADR 002 D5 | Language-neutral operations and data. | + +## Requirements raised to mechanism owners + +- **Permission (#2028).** `decide` with the call's source and the published `PermissionState` are this board's own contract; see [Permission](Permission.md). +- **None other.** No Timeline, Dispatcher, loader or runtime change. + +## Binding appendix + +The service is marked on the owner type; the name stays `approval`. + +```rust +use crate::host::CancelledFn; +use dim_agent_runtime::PublicService; +use dim_agent_types::{ApprovalCallData, ApprovalDecision, ApprovalRequestData, BranchSource}; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdmitRequest { + pub source: BranchSource, + pub call: ApprovalCallData, + pub risk: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PendingReply { + pub requests: Vec, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DecideRequest { + pub approval_id: String, + pub decision: ApprovalDecision, +} + +#[derive(Debug, thiserror::Error)] +pub enum ApprovalError { + #[error("the call was denied: {reason}")] + Denied { reason: String }, + #[error("the call was cancelled")] + Cancelled, + #[error("the approval service is closing")] + Closed, + #[error("the approval is absent or already resolved")] + Unknown, +} + +impl PublicService for Approval {} + +#[rutis::service(name = "approval")] +impl Approval { + pub async fn admit(&self, request: AdmitRequest, cancelled: CancelledFn) -> Result<(), ApprovalError> { /* ... */ } + pub async fn pending(&self) -> Result { /* ... */ } + pub async fn decide(&self, request: DecideRequest) -> Result<(), ApprovalError> { /* ... */ } +} +``` diff --git a/docs/design/plugins/BackgroundExec.md b/docs/design/plugins/BackgroundExec.md new file mode 100644 index 0000000000..a839c47415 --- /dev/null +++ b/docs/design/plugins/BackgroundExec.md @@ -0,0 +1,231 @@ +# BackgroundExec + +Scope: branch. Issue: #2028. + +BackgroundExec owns the commands a line moved to the background: the task table, each task's terminal record and wake, and the task's registered output artifact. This document is the owner's target contract; the current implementation is described in the [WorkspaceTools plugin page](../../architecture/rust-agent/plugins/WorkspaceTools.md#backgroundexec). + +## Use and scope: responsibility split + +BackgroundExec owns: + +- **The task table.** One task per background command of the line: the task id, its description and title, the registered output path, the process it supervises, and its terminal record. +- **Supervision.** Wait for the process the host started, write `exec/ended` with its status and result, hold the Session until the terminal fact is appended, and wake the line with a bounded notice unless the end came from a stop, a branch close or an unload. +- **The output artifact.** The task's registered output file: the tail preview and its bounded pages, the truncation flag, and the unavailable answer when the file is gone. The bytes are appended by the process; the artifact reference and every read belong to this owner. +- **Recovery.** On load, write failed terminals for commands whose process did not survive, and post the wakes the previous generation lost. + +BackgroundExec does not create, start or kill processes. The host's process owner starts a command and issues its task id; BackgroundExec adopts the id, and stops the task by asking the host to kill that id. ShellSession owns the PTY and its own stop port; its commands' terminals are settled by the ShellSession owner through `exec/started`/`exec/ended`, and this owner consumes them. + +Callers keep as business: + +- Whether a command is moved to the background: the exec tool decides after its foreground wait. +- What a completion notice means for the turn. +- The command, its working directory and its environment: the host's process owner builds the process. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Supervise a command the host started | No: the supervision task, the terminal fact and the Session hold are one lifecycle; a caller holding the process would duplicate the settlement on every path | `adopt` | +| Stop a task by id | No: the stop must cancel the supervision, kill the process and write one terminal without a wake; a caller composing the steps could write two terminals | `stop` | +| Read the task's tail preview | No: the artifact is the owner's record and the read is bounded by the owner's policy | `output` | +| Read the task's output in pages | No: the page's cursor, the character boundary and the truncation flag are the owner's knowledge | `output_page` | +| Wait until a task ends | No: the wait must observe the dispatched terminal, not poll the record | `wait` | + +An operation exists only where its row says No. + +## Caller example + +The exec tool moves a foreground command to the background and answers its task id: + +```rust +// The host's process owner started the command and issued its task id. +let task_id = launch.task_id.clone(); +background.adopt(AdoptRequest { + task_id: task_id.clone(), + description: request.description.clone(), + title: request.title.clone(), + output_path: launch.output_path.clone(), +}).await?; // Closed, UnknownTask +``` + +The product reads the task's preview and pages: + +```rust +let preview = background.output(task_id.clone()).await?; // Unknown, Unavailable, Closed +let page = background.output_page(OutputPageRequest { + task_id, + cursor, + limit: 64 * 1024, +}).await?; // Unknown, Unavailable, InvalidLimit, Closed +``` + +A client stops a task and waits for its terminal: + +```rust +let ended = background.stop(task_id.clone()).await?; // Unknown, Closed +let ended = background.wait(WaitRequest { task_id, timeout_ms: 5_000 }, cancelled).await?; // Unknown, Timeout, Closed +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `P:HostPlatform` (process, #2032) | The started process by task id: wait for it, kill it, and answer its terminal status. | +| `S:SessionScope` (Session, #2093) | Hold the Session while a task runs; observe activation and closing. | +| `S:GuideEntries` (Session) | Register the exec notification's entry for this line until the part unloads. | +| `B:Timeline`, `B:Dispatcher` | Write and recover `exec/started`/`exec/ended`; consume terminals and interrupts; write the wake input. | + +The host's process-by-id operations are not defined yet; they are stated in Requirements. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `adopt` | Take over supervision of a command the host started | `{taskId, description, title?, outputPath}` | `{}` | The caller drops the call: nothing was adopted, and the host's process is killed | `closed`, `unknown_task` (the host has no live task with this id) | +| `output` | The task's tail preview | `{taskId}` | `{text}` | The caller drops the call; the read stops | `unknown`, `unavailable`, `closed` | +| `output_page` | One bounded page of the registered output file | `{taskId, cursor, limit}` | `{text, bytes, nextCursor?, truncated}` | The caller drops the call; the read stops | `unknown`, `unavailable`, `invalid_limit`, `closed` | +| `wait` | Wait until the task's terminal is dispatched | `{taskId, timeoutMs}` | `{terminal}` | The caller drops the call; the wait releases | `unknown`, `timeout`, `closed` | +| `stop` | Cancel a running task and answer its terminal | `{taskId}` | `{terminal}` | None: an admitted stop settles | `unknown`, `closed` | + +`nextCursor` is present only for a full page; a client advances by `bytes`. `wait` with `timeout_ms = 0` answers `timeout` for a running task and the terminal for an ended one. `stop` on an ended task answers its terminal and changes no wake. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `unknown_task` | `adopt` | The host has no such task; nothing was adopted and the command is not supervised. | +| `unknown` | `output`, `output_page`, `wait`, `stop` | This line has no such task; do not retry. | +| `unavailable` | `output`, `output_page` | The registered file is gone (cleaned or its Session deleted); report the loss, do not retry. | +| `invalid_limit` | `output_page` | Use a limit of at least one byte. | +| `timeout` | `wait` | The task is still running; wait again or stop it. | +| `closed` | any | The generation is closing or reloading; a replacement generation serves. | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `adopt` | Take the Session hold, write `exec/started`, spawn the supervision task, answer the id | Before `exec/started` is committed: nothing adopted; the host's process is killed | Nothing to release; the task is the line's | A reload refuses new adoptions and ends running tasks as stopped; an unfinished command gets a failed terminal | BackgroundExec for the task and the hold; the host for the process | +| supervision task | The host reports the process's end; write `exec/ended`, release the Session hold, wake the line unless the end is `cancelled` | — | — | The owner's unload cancels the task, kills the process and writes the cancelled terminal | BackgroundExec for the facts; the host for the process | +| `output`, `output_page` | Open the registered file, read the tail or one page, answer | The read stops; nothing changes | — | Pending reads answer `closed` | BackgroundExec | +| `wait` | Answer at once for an ended task; otherwise wait for the dispatched terminal | The wait releases; no state changes | — | Pending waits answer `closed` | BackgroundExec | +| `stop` | Cancel the supervision, ask the host to kill the process, write the cancelled terminal, answer it | — | — | A stop in flight settles before the generation closes | BackgroundExec for the terminal; the host for the process | + +## Exceptions with reasons + +- The registered output file's bytes are produced by the process, while the artifact reference and every read belong to this owner: the path is fixed in `exec/started`, the process only appends, and a read opens and closes within one call, so no file handle crosses an owner. +- ShellSession's commands appear in `exec/started` without an adopting caller: the PTY owner settles its own commands and writes their terminals; this owner consumes them for the notices and recovery, as it does for its own tasks. + +## Verification + +Flow tests on the owner: + +- A command moved to the background ends once, its terminal is written once, and the line wakes once; a stop cancels it without a wake; a branch close cancels it without a wake. +- A reload writes failed terminals for unfinished commands, posts the wakes the previous generation lost, and refuses a new adoption; a Session close settles the hold. +- The tail preview and its pages read the registered file in every state of the task; a page's cursor advances by its bytes; a limit of zero is `invalid_limit`; a deleted file is `unavailable`. +- `wait` answers an ended task at once, times out for a running task, and releases when dropped; an unknown task is `unknown` on every operation. +- The face and the Rust call answer the same previews, pages, terminals and errors. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | BackgroundExec is one branch part and a Capability: it injects `dispatcher` and `timeline`, writes `exec/ended` and folds the terminals. | +| §2 scopes | Branch: a task belongs to the line that started it; the process belongs to the host's process owner. | +| §3 orthogonality | The host's process, the Session's hold and the guide table are other owners' operations; no state is read directly. | +| §4 rule 1 | A stop and a close cancel the task; the owner writes the terminal. | +| §4 rule 2 | The process is handed over by id; the task is not taken back. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No business meaning in core or assembly. | +| §4 rule 5 | The terminal and its wake are separate commits: the terminal first, the wake after its dispatch. | +| §4 rule 6 | The notice is the model's input; the full output stays in the file and the result. | +| §4 rule 7 | The host's process and the Session's hold are operations; the guide entry is a registration. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | The terminal is a fact later decisions use; the notice is an input. | +| §7 resources and ids | The process is the host's, addressed by task id; the task's output artifact is the owner's; no handle crosses. | +| §7 no proxy | The owner serves its own tasks and their artifact; it does not return the host's process state. | +| §7 one surface | `adopt`, `output`, `output_page`, `wait`, `stop`; `start` with a live process is removed. | +| §7 cross-language | Every parameter and reply is data; cancellation is dropping the call. | +| §7 responsibility split | The caller keeps the command and the decision to background it; the owner keeps supervision, the terminal, the hold and the artifact. | +| ADR 002 D1 | Branch scope. | +| ADR 002 D2 | No wiring part. | +| ADR 002 D3 | Depends on the host's process owner and Session capabilities; nothing depends on BackgroundExec's internals. | +| ADR 002 D4 | No configuration. | +| ADR 002 D5 | Language-neutral operations and data. | + +## Requirements raised to mechanism owners + +- **HostPlatform (#2032).** The process owner must expose a started process by task id: `wait({taskId}, cancelled) → {status, exit}`, `kill({taskId}) → {}`, and the task id in its start reply. BackgroundExec adopts that id and never receives a process object. Until the host's id operations land, this board's `adopt` and `stop` cannot be implemented; the other owners' contracts are independent. +- **SessionScope (#2093).** `hold` returns the lease id, `release` ends it early, and `activated`/`closing` gate the watcher. +- **None other.** No Timeline, Dispatcher, loader or runtime change. + +## Binding appendix + +The service is marked on the owner type; the name stays `backgroundExec`. + +```rust +use crate::host::CancelledFn; +use dim_agent_runtime::PublicService; +use dim_agent_types::{ExecEndedData, ExecStatus}; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdoptRequest { + pub task_id: String, + pub description: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option, + pub output_path: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OutputPageRequest { + pub task_id: String, + pub cursor: u64, + pub limit: u64, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OutputPage { + pub text: String, + pub bytes: u64, + #[serde(skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, + pub truncated: bool, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WaitRequest { + pub task_id: String, + pub timeout_ms: u64, +} + +#[derive(Debug, thiserror::Error)] +pub enum BackgroundError { + #[error("the host has no live task with this id")] + UnknownTask, + #[error("no such task is known on this line")] + Unknown, + #[error("the task's output file is no longer available")] + Unavailable, + #[error("limit must be at least 1")] + InvalidLimit, + #[error("the task did not end before the timeout")] + Timeout, + #[error("the background exec service is closing")] + Closed, +} + +impl PublicService for BackgroundExec {} + +#[rutis::service(name = "backgroundExec")] +impl BackgroundExec { + pub async fn adopt(&self, request: AdoptRequest) -> Result<(), BackgroundError> { /* ... */ } + pub async fn output(&self, task_id: String) -> Result { /* ... */ } + pub async fn output_page(&self, request: OutputPageRequest) -> Result { /* ... */ } + pub async fn wait(&self, request: WaitRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn stop(&self, task_id: String) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/FileReads.md b/docs/design/plugins/FileReads.md new file mode 100644 index 0000000000..984053d68c --- /dev/null +++ b/docs/design/plugins/FileReads.md @@ -0,0 +1,217 @@ +# FileReads + +Scope: branch. Issue: #2028. + +FileReads owns one line's text bindings: which files the model has seen on this line, the raw byte revision and the text format each was read in, and whether the operation that established a binding is still in the model's context. This document is the owner's target contract; the current implementation is described in the [WorkspaceTools plugin page](../../architecture/rust-agent/plugins/WorkspaceTools.md#filereads). + +## Use and scope: responsibility split + +FileReads owns: + +- **The bindings.** One binding per canonical path: the SHA-256 of the raw bytes, the resolved encoding, its source, the byte-order mark and the line endings, with the sequence at which the operation that established it ran. +- **The context rule.** A binding whose establishing operation a completed compaction cut out of the model's context cannot justify replacing the file; the model reads the file again or uses `edit`. +- **The rebuild.** On load, the owner folds the line's committed file-tool results back into bindings, so a reload does not force a re-read of every file whose encoding is in the facts. +- **The edit's rule.** `edit` checks the model's `oldText` against the file itself, so its binding survives a compaction that cut the read out. + +FileReads does not open, read or write files: the file tools own path resolution and the bytes. FileReads does not decide whether a call is admitted: Permission and Approval do. + +Callers keep as business: + +- Which file a tool touches, its encoding override, and the tool's own result text. +- What "read the file again" means for the turn. +- The write's effect declarations and the mutation display. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Decide whether a `write` may replace an existing file | No: the binding's freshness against compaction is the owner's rule, and a caller holding the map would duplicate it | `binding` with `write` | +| Decide whether an `edit` may proceed | No: the same map, with a different rule | `binding` with `edit` | +| Record that an operation bound a file | No: the record and the operation's start sequence are one write; a caller that forgot the record would silently allow a later write | `record` | + +An operation exists only where its row says No. + +## Caller example + +The `write` tool asks before replacing an existing file, then records the operation it performed: + +```rust +let binding = reads.binding(BindingRequest { + path: display.clone(), + purpose: Purpose::Write, +}).await?; // Closed; the value says whether a binding is usable +match binding.binding { + Some(binding) => { /* preserve encoding and line endings; check the revision */ } + None => { + let reason = binding.unavailable.expect("one of binding or unavailable"); + return Ok(text_binding_required(reason)); // the model re-reads or edits + } +} +// ... write the bytes ... +reads.record(RecordRequest { + path: canonical.clone(), + binding: new_binding, + established, +}).await?; // Closed +``` + +The `edit` tool asks with the edit purpose, which ignores compaction: + +```rust +let binding = reads.binding(BindingRequest { path: display, purpose: Purpose::Edit }).await?; +let Some(binding) = binding.binding else { + return Ok(text_binding_required(binding.unavailable.expect("read first"))); +}; +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `B:Timeline` | The line's committed file-tool results, from which bindings are rebuilt, and the completed `context/compaction` facts that decide the context rule. | + +FileReads injects no other service. The Session's file tools reach this owner through the Session access mechanism by line id ([TimelineTree's route](TimelineTree.md#session-parts-reaching-a-lines-owners)); FileReads returns values and stores records, and no file handle crosses. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `binding` | Whether a file may be replaced or edited, and on which binding | `{path, purpose}` | `{binding?}` or `{unavailable: never_read\|compacted}` | None; the owner completes the read | `closed` | +| `record` | Note the binding an operation established, at the sequence the operation started | `{path, binding, established}` | `{}` | None | `closed` | + +`purpose` is `write` or `edit`; it selects the owner's rule, and a caller never evaluates compaction itself. `binding` is the value the file tool preserves: revision, encoding, encoding source, byte-order mark and line endings. `established` is the line's sequence when the operation started, taken by the caller after the call's fact committed; the owner compares it with the completed compaction's cut. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `closed` | `binding`, `record` | The line is closing or unloading; the tool call ends; the replacement generation rebuilds the bindings from the facts. | + +"Never read" and "compacted" are values, not errors: the file tool turns either into the model-facing `text_binding_required` result, and the model's next step is to re-read or edit. + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `binding` | Read the map; for `write`, check the latest completed compaction after the binding's sequence and whether the cut event still lies after it | None; the read is bounded | Nothing to release | Refused with `closed` | FileReads | +| `record` | Replace the path's binding with the new one and its sequence | None | Nothing to release | The new generation rebuilds from the facts; a record not yet committed is lost with the generation | FileReads | +| Load | Read the line's committed file-tool results at one cutoff, take each result's binding and its event sequence, and keep the latest per path | — | — | — | FileReads | + +The rebuild uses the result event's sequence: no legal compaction cut separates a call from its result, so the result's position is equivalent to the operation's start for the context rule. + +## Exceptions with reasons + +- `record` takes the operation's start sequence from the caller: the window belongs to the caller's operation, and an owner that sampled the sequence at record time would sample after the operation's own writes. + +## Verification + +Flow tests on the owner: + +- A read binds a file; a `write` after a compaction that cut the read out is refused with `compacted`; a compaction that kept the read leaves the write admitted; an `edit` proceeds after either. +- A write's binding replaces the read's for later operations; a failed offload does not bind. +- After a reload, the bindings are rebuilt from the line's facts and an existing file can be written without a new read; a file whose read a compaction cut out before the reload stays unavailable for `write`. +- The face and the Rust call answer the same binding or reason. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | FileReads is one branch part and a Capability: it injects `timeline` and folds the line's file-tool results on load. | +| §2 scopes | Branch: bindings are one line's; the file tools are Session parts that reach this owner by line id. | +| §3 orthogonality | No other owner's state is read; the facts are the line's Timeline. | +| §4 rule 1 | No command event: the owner writes nothing. | +| §4 rule 2 | No handoff. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No business meaning in core or assembly. | +| §4 rule 5 | No batch. | +| §4 rule 6 | No model-context input: the bindings are not context. | +| §4 rule 7 | The tool results are public facts; the owner folds them. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | No Timeline fact of its own; the bindings are a projection of public facts, and the projection is this owner's state. | +| §7 resources and objects | No resource; the owner stores values and returns values. | +| §7 no proxy | The owner answers its own bindings; it returns no file's bytes. | +| §7 one surface | `binding` and `record`; `get` and `write_binding` are removed. | +| §7 cross-language | Every parameter and reply is data; the caller is a Session part reached by line id. | +| §7 responsibility split | The caller keeps the file, its bytes and the result text; the owner keeps the bindings and the context rule. | +| ADR 002 D1 | Branch scope: a binding is one line's having seen a file. | +| ADR 002 D2 | No wiring part. | +| ADR 002 D3 | No dependency on callers; a composition without the file tools has no bindings. | +| ADR 002 D4 | No configuration. | +| ADR 002 D5 | Language-neutral operations and data. | + +## Requirements raised to mechanism owners + +- **Session access (#2025).** A Session part resolves a line's owner by line id: the mechanism named in [TimelineTree's route](TimelineTree.md#session-parts-reaching-a-lines-owners). The file tools use it to reach `binding` and `record`; FileReads adds no forwarding operation. +- **None other.** No Timeline, Dispatcher, loader or runtime change. + +## Binding appendix + +The service is marked on the owner type; the name stays `fileReads`. + +```rust +use dim_agent_runtime::PublicService; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Purpose { + Write, + Edit, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BindingRequest { + pub path: String, + pub purpose: Purpose, +} + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TextFileBinding { + pub revision: String, // SHA-256 of the raw bytes, lowercase hex + pub encoding: TextEncoding, + pub encoding_source: EncodingSource, + pub bom: Bom, + pub eol: Eol, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Unavailable { + NeverRead, + Compacted, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BindingReply { + #[serde(skip_serializing_if = "Option::is_none")] + pub binding: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub unavailable: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RecordRequest { + pub path: String, + pub binding: TextFileBinding, + pub established: u64, +} + +#[derive(Debug, thiserror::Error)] +pub enum FileReadsError { + #[error("the line is closing")] + Closed, +} + +impl PublicService for FileReads {} + +#[rutis::service(name = "fileReads")] +impl FileReads { + pub async fn binding(&self, request: BindingRequest) -> Result { /* ... */ } + pub fn record(&self, request: RecordRequest) -> Result<(), FileReadsError> { /* ... */ } +} +``` + +`TextEncoding`, `EncodingSource`, `Bom` and `Eol` are the existing value types of the file-tool codec; they cross as data and stay defined beside the codec, not here. diff --git a/docs/design/plugins/Permission.md b/docs/design/plugins/Permission.md new file mode 100644 index 0000000000..f19fcbe296 --- /dev/null +++ b/docs/design/plugins/Permission.md @@ -0,0 +1,255 @@ +# Permission + +Scope: branch. Issue: #2028. + +Permission owns the branch's permission policy and one call's decision: the preset and tool lists the branch adopted, the version those changes are counted in, the file-access facts a call's target is judged by, the user's command rules, and the branch's tool advisors. This document is the owner's target contract; the current implementation is described in the [Permission plugin page](../../architecture/rust-agent/plugins/Permission.md#permission). + +## Use and scope: responsibility split + +Permission owns: + +- **The policy value.** The preset and the two tool lists, folded from the Session's creation record and the branch's `permission/changed` facts, published as a read-only value with the version of the last local change. A client's update is a versioned write. +- **The decision.** One call's outcome — allow, ask with a reason, or deny with a reason — from the risk the tool owner declares, the policy, the file-access facts of the call's target, the command rules for an `execute_process` call, and the branch's advisors when the decision is an admission. +- **Tool advisors.** A branch part registers an advisor under a name while it runs; an admission asks the advisors registered at that moment, in name order. Advice is never asked on a recheck and never overrides a deny. +- **The decision's inputs' freshness.** The owner reads the facts and the rules at decision time; a policy change while waiting makes the decision start over. + +Permission does not ask the user, run tools, write approval facts or decide the model's declarations. Approval owns the question and the answer; ToolExecutor owns execution; ToolRegistry owns declarations. + +Callers keep as business: + +- What an ask means and when it is worth asking: Approval's admission and its recheck. +- What a deny means for the turn, and the model-facing text of a refusal. +- The user's command rules and their file: the rules owner reads them; Permission applies them. +- The workspace, system, owned-file and grant facts: the facts owner resolves and answers them. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Decide one call | No: the policy, the facts, the rules and the advisors are one decision, and composing them in the caller duplicates the policy's precedence rules | `decide` | +| Decide an admission, asking the branch's advisors | No: only the owner knows the advisors registered at that moment and how their advice combines | `decide` with the call's source | +| Recheck after an answer or a policy change | No: the recheck must see the current policy, not the snapshot the first decision used | `decide` without a source | +| Read the current policy and version | Yes: the published `PermissionState` | Business composition | +| Update the policy | No: the version check and the fact are one write | `update` | +| Register tool advice | No: the registration is bound to the registering part's lifetime and asked by name order | `advise` | + +An operation exists only where its row says No. + +## Caller example + +Approval asks for an admission and, after the answer, for a plain recheck: + +```rust +let admission = permission.decide(DecideRequest { + call: call.clone(), + risk: risk.cloned(), + source: Some(source.clone()), +}, cancelled.clone()).await?; // Cancelled, Closed +if admission.outcome == Outcome::Ask && !admission.advisor_question { + // ask the user; later, after the answer: + let recheck = permission.decide(DecideRequest { call, risk, source: None }, cancelled).await?; +} +``` + +Hooks registers advice for the lifetime of its branch part; the registration ends with the part: + +```rust +permission.advise(AdviseRequest { + name: "hooks".into(), + advise: Arc::new(HookAdvice { branch: self.clone() }), +}).await?; // Duplicate, Closed +``` + +A client updates the policy with the version it read: + +```rust +let next = permission.update(UpdateRequest { + expected_version: read.version, + policy: next_policy, +}).await?; // Conflict { current }, Closed +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `S:SessionScope` (Session, #2093) | The creation record's permission preset and working directory, and the Session id for facts queries. | +| `S:CommandRules` (Session port) | The user's command rules, read at decision time. | +| `S:FileAccessFacts` (Session owner, #2025) | Resolve the call's target and answer the workspace, system, owned and grant facts. | +| `B:Timeline`, `B:Dispatcher` | Fold `permission/changed`; commit an update. | + +The file-access facts operation that resolves the target is not defined yet; it is stated in Requirements. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `decide` | One call's outcome | `{call, risk?, source?}` | `{outcome: allow\|ask\|deny, reason?, advisorQuestion}` | The caller's token stops the facts or advice read; the decision is not made | `cancelled`, `closed` | +| `update` | Versioned policy write | `{expectedVersion, policy}` | `{version}` | None; one commit | `conflict {current}`, `closed` | +| `advise` | Register tool advice for the calling row's lifetime | `{name, advise}` | `{}` | None | `duplicate`, `closed` | +| `PermissionState` (published value) | Read the policy and its version | — | `{version, policy}` | None | — | + +`risk` is the tool owner's declaration (`read_filesystem`, `write_filesystem`, `execute_process`, `network`, `session`, or absent). `source` is present exactly for an admission; the owner asks the advisors only then, and `advisorQuestion` says whether an advisor required an explicit answer, so a policy change can end a policy question but never an advisor's. + +The policy is the preset and `allowedTools`/`disallowedTools`. A deny from the tool list, a file fact or a command rule wins over an allow; a command allow turns an ask into an allow for a command without shell separators; an absent `permissions` for a file call means the preset's access. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `cancelled` | `decide` | The call's batch was cancelled; do not run the call. | +| `closed` | any | The generation is closing or reloading; stop; a later generation serves. | +| `conflict` | `update` | Re-read the version from `PermissionState` and decide whether to retry the update with the new base. | +| `duplicate` | `advise` | The name is taken; pick another or withdraw the first registration. | + +An unreadable fact or rule is not an error: the owner denies the call with its reason, because the caller's next step is the same as for any refusal. + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `decide` | Read the policy, resolve the target and read the facts, read the rules for a command, ask the advisors for an admission, combine and answer | The facts or advice read stops; `cancelled`; nothing changes | The decision's future is the caller's; no resource is held | Refused with `closed`; an in-flight decision ends `closed` | Permission; the facts read by the facts owner | +| `update` | Commit `permission/changed` when the expected version matches, answer the new version once dispatched | None | The write is admitted or not; nothing to release | Refused with `closed` | Permission and the Timeline | +| `advise` | Register the callback under the name against the calling row | None | The row's unload withdraws the registration | Every registration of the generation is withdrawn | Permission | + +## Exceptions with reasons + +- A branch part registers a callback (`advise`): §7 allows a callback by reference; the owner never calls it inside the Timeline's commit lock, and the calling row's unload withdraws it. +- The policy value is published as a read-only view: Approval subscribes to it to recheck a waiting call, and the App Server reads it for the client; neither reads Permission's internals. + +## Verification + +Flow tests on the owner: + +- Presets decide by risk; `allowedTools` and `disallowedTools` refine the preset and a deny wins; an explicit disallow, a deny rule and a file denial are not lifted by an allow. +- A file call asks when its resolved target is outside the workspace; a read or write fact denial refuses the call; a command rule denies under every preset and an allow rule only answers an ask for a simple command. +- An admission asks the advisors in name order; an ask refines an allow; a deny wins over an ask and an allow; a recheck asks no advisor; a registration is withdrawn when its part unloads; a second registration of the same name is `duplicate`. +- An update with a stale version is `conflict` with the current version; a dispatched change is visible to the next decision and survives a reload. +- The published value's version is the last local change; the face and the Rust call answer the same decision. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | Permission is one branch part and a Capability: it injects `dispatcher` and `timeline` and folds `permission/changed`. | +| §2 scopes | Branch: a line's policy and decisions; the creation record and the facts are Session state it reads. | +| §3 orthogonality | Approval is a separate owner; the facts, rules and Session record are other owners' operations and values. | +| §4 rule 1 | A policy update is a command event; the owner writes the outcome fact. | +| §4 rule 2 | No handoff. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No business meaning in core or assembly. | +| §4 rule 5 | A policy change and its version are one batch. | +| §4 rule 6 | No model context input. | +| §4 rule 7 | The facts, rules and record are read through their owners' operations and values; the advisors are the branch's registrations. | +| §4 rule 8 | No infrastructure change; the facts operation is an owner operation. | +| §4 rule 9 | Policy changes are facts later decisions use; the version is theirs. | +| §7 resources and objects | No resource; no object crosses. Advice is a callback by reference. | +| §7 no proxy | The owner answers its own decision and publishes its own state. | +| §7 one surface | `decide`, `update`, `advise`, and the published value; `admit_decision`, `check` and the separate `decide` are removed. | +| §7 cross-language | Every parameter and reply is data; the decision is a value, not an error. | +| §7 responsibility split | The caller keeps the question and the turn; the owner keeps the policy, the facts' use and the advisors. | +| ADR 002 D1 | Branch scope. | +| ADR 002 D2 | No wiring part. | +| ADR 002 D3 | Depends on Session capabilities; nothing depends on Permission's internals. | +| ADR 002 D4 | The preset seed comes from the Session's creation record; no separate configuration. | +| ADR 002 D5 | Language-neutral operations and data. | + +## Requirements raised to mechanism owners + +- **File access facts (#2025).** The Session owner must publish one data operation, `check({sessionId, access, mode, path}, cancelled) → {target, workspace, system, owned, grant, discoveryError?}`, that resolves the call's path (`~`, cwd, `..`, links) and answers the facts under the effective access. Permission currently reads the owner's Rust object and a host `home` value; both disappear with this operation. +- **SessionScope (#2093).** `config` and `identity` are the target's operations; Permission's creation-record reads use them. +- **None other.** No Timeline, Dispatcher, loader or runtime change. + +## Binding appendix + +The service is marked on the owner type; the name stays `permission`. + +```rust +use crate::host::CancelledFn; +use dim_agent_runtime::PublicService; +use dim_agent_types::{ApprovalCallData, BranchSource, CommandRule, PermissionPolicy}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Outcome { + Allow, + Ask, + Deny, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DecideRequest { + pub call: ApprovalCallData, + pub risk: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DecisionReply { + pub outcome: Outcome, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + pub advisor_question: bool, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UpdateRequest { + pub expected_version: u64, + pub policy: PermissionPolicy, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdviseRequest { + pub name: String, + pub advise: AdviseFn, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PermissionState { + pub version: u64, + pub policy: PermissionPolicy, +} + +/// One advisor's answer: none, allow, ask with a reason, or deny with a reason. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Advice { + None, + Allow, + Ask { reason: String }, + Deny { reason: String }, +} + +pub type AdviseFn = std::sync::Arc< + dyn Fn(AdviceRequest) -> rutis::host::BoxFuture<'static, Result> + + Send + + Sync, +>; + +#[derive(Debug, thiserror::Error)] +pub enum PermissionError { + #[error("the decision was cancelled")] + Cancelled, + #[error("the permission service is closing")] + Closed, + #[error("permission version conflict; current version is {current}")] + Conflict { current: u64 }, + #[error("an advisor named {name} is already registered")] + Duplicate { name: String }, +} + +impl PublicService for Permission {} + +#[rutis::service(name = "permission")] +impl Permission { + pub async fn decide(&self, request: DecideRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn update(&self, request: UpdateRequest) -> Result { /* ... */ } + pub async fn advise(&self, request: AdviseRequest) -> Result<(), PermissionError> { /* ... */ } +} +``` diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 206ed6d609..c91165765d 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -8,6 +8,12 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Plugin | Process part | Session part | Branch part | Phase / issue | | --- | --- | --- | --- | --- | +| [ToolBinding](ToolBinding.md) (owner contract) | — | — | a request's adopted tool set, its claims and its pins behind the `toolBinding` operations | [#2028](https://github.com/arcships/dim/issues/2028) | +| [ToolExecutor](ToolExecutor.md) (owner contract) | — | — | one committed tool batch, its child-call gates and its terminal facts behind the `toolExecutor` operations | [#2028](https://github.com/arcships/dim/issues/2028) | +| [Approval](Approval.md) (owner contract) | — | — | a call's admission, the pending approval requests and the answer path behind the `approval` operations | [#2028](https://github.com/arcships/dim/issues/2028) | +| [Permission](Permission.md) (owner contract) | — | — | the branch's permission policy, one call's decision and its tool advisors behind the `permission` operations | [#2028](https://github.com/arcships/dim/issues/2028) | +| [BackgroundExec](BackgroundExec.md) (owner contract) | — | — | a line's background tasks, their terminals, wakes and output artifact behind the `backgroundExec` operations | [#2028](https://github.com/arcships/dim/issues/2028) | +| [FileReads](FileReads.md) (owner contract) | — | — | a line's text bindings and their context rule behind the `fileReads` operations | [#2028](https://github.com/arcships/dim/issues/2028) | | [Migration](Migration.md) | on-demand import tasks, source mappings, progress and retry records; unloaded after settlement | — | — | [Delivery plan](../../plan/analysis/legacy-migration.md) | | [Provider management](../appserver/provider-management.md) | existing Provider: configuration, catalogs, client preferences and management methods | — | — | #329 | | [Questions](Questions.md) | — | `ask_user` tool, `session.question.respond`, waiters of running `ask_user` calls; no events | — | M2; #262 | diff --git a/docs/design/plugins/ToolBinding.md b/docs/design/plugins/ToolBinding.md new file mode 100644 index 0000000000..77af6eaa7d --- /dev/null +++ b/docs/design/plugins/ToolBinding.md @@ -0,0 +1,257 @@ +# ToolBinding + +Scope: branch. Issue: #2028. + +ToolBinding owns the branch's record of each request's adopted tool set: the declarations the request's prefix declared, the source version ids the owner resolved them against, and the pins that keep a later prefix's versions resolvable. This document is the owner's target contract; the current implementation is described in the [ToolExecution plugin page](../../architecture/rust-agent/plugins/ToolExecution.md#toolbinding). + +## Use and scope: responsibility split + +ToolBinding owns: + +- **The request record.** One adopted value per request id: the declarations, the fixed tool names and the source version ids. A request id is bound once; a budget-recovery request takes over the record of the request it retries. +- **Pins.** The adopted sets a later request prefix may still declare, and their release. A pin is a value; ToolBinding asks the registry to retain the versions and drops the retention when the pin is released. +- **The claims of a request's published calls.** Before the batch fact is appended, ToolBinding asks the owner of the tool handlers to register each call's claim under the call's identity, and it releases every claim of the request at the request record's release. +- **The adopted value the executor passes back to the registry.** ToolBinding is the only place a request's adopted value is read after preparation. + +ToolBinding does not execute tools, decide admission, hold a handler or a claim guard, or write the adopted configuration. The adopted configuration fact (`context/configured`'s tool part) belongs to Prompt; execution, write-target resolution, ordering class and the claim guards belong to ToolRegistry. + +Callers keep as business: + +- Which declarations a request's prefix carries, and where the declaration comes from: the prefix's adopted configuration, the registry's current set, or a host's selection over the registry's declarations. +- When a request is prepared, retried or abandoned; whether a turn is failed; how a model request's declarations are shaped. +- The tool-call batch: which calls a request publishes and when. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Bind a request to the adopted tool set its prefix declared | No: the record must be released on every path that ends the request, and a caller that held the adopted value would have to release it itself on each error path | `bind` | +| Read the adopted value to execute a call | No: the adopted value is the record's state, and the registry retains the versions on the record's behalf | `adopted` | +| Read a request's declarations for a program that may only see them (Code Mode) | Yes: `adopted` answers the same value; the program takes the declaration part | Business composition | +| Register a published call's claim before the batch fact | No: the claim must exist before the fact and be released with the record on every non-dispatch path | `claim` | +| Release a request that will not execute again | No: only the caller knows the turn's decision; the record owner performs the release | `release` | +| Keep the same adopted set across a budget-recovery retry | No: the record moves to the new request id; composing it would copy and release records | `transfer` | +| Keep only the current request after a rebuild | No: a rebuild must drop every stale record in one step | `retain_only` | + +An operation exists only where its row says No. + +## Caller example + +Loop prepares a request from the prefix's adopted configuration and publishes a batch: + +```rust +// The prefix's adopted tool part, or none when the configuration carries none. +let adopted = match configuration.tools { + Some(tools) => binding.bind(BindRequest { + request_id: request.id.clone(), + through, + declared: tools.clone(), + sources: configuration.tool_sources.clone(), + }).await?, // AlreadyBound + None => { + // No tool part: declare the registry's current host and contributed tools. + let current = registry.declarations().await?; + binding.bind(BindRequest { + request_id: request.id.clone(), + through, + declared: current.tools, + sources: current.sources, + }).await? + } +}; + +// Before the batch fact, so a published question can already be answered. +binding.claim(ClaimRequest { + request_id: request.id.clone(), + calls: request.calls.clone(), + context: execution.clone(), +}).await?; +``` + +A host that selects tools over the registry's declarations composes the same three steps; the declarations it reads are the ones it passes on: + +```rust +let available = registry.declarations().await?; +let settings = host.prepare(turn_id, request_id, &history, &available.tools)?; +binding.bind(BindRequest { + request_id: request.id.clone(), + through, + declared: settings.tools.clone().unwrap_or_default(), + sources: available.sources, +}).await?; +``` + +ToolExecutor reads the adopted value once per call and hands it back to the registry, which resolves the handler for that version: + +```rust +let adopted = binding.adopted(&context.request_id).await?; // NoRecord +let outcome = registry.execute(ExecuteRequest { + adopted, + call: call.clone(), + context: context.clone(), +}, cancelled).await?; // the tool's own failure is a ToolResult, not an error +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `B:Prompt` (branch, #2027) | Adopt the tool part of the branch's model configuration when the registry's set changes. | +| `S:ToolRegistry` (Session, #2026) | Retain an adopted version set for a request, register a call's claim, and release a request's retention and claims. | +| `B:Timeline`, `B:Dispatcher` | Reconcile the prefix's last configuration at branch opening and after a reload. | +| `B:BranchLifecycle` | Gate the registry-change watcher on activation and closing. | + +The registry's adopt, retain, claim and release operations are not defined yet; they are stated in Requirements. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `bind` | Fix a request to one adopted tool set | `{requestId, through, declared, sources}` | `{}` | None; the owner completes the record | `already_bound`, `version_unavailable` (a declared source version is no longer retained), `no_handler` (a declared name has no implementation in the registry) | +| `adopted` | The request's adopted value | `{requestId}` | `{adopted}` | None | `no_record` | +| `claim` | Register the calls' claims before their batch fact | `{requestId, calls, context}` | `{}` | None | `no_record` | +| `release` | Drop a request's record, its retention and its claims | `{requestId}` | `{}` | None | None: an absent record is a no-op | +| `transfer` | Move a record to the request that retries it | `{from, to}` | `{}` | None | `no_record` | +| `retain_only` | Keep one request's record and drop every other | `{requestId}` | `{}` | None | None | + +`declared` is the request's full declaration list; `sources` is the prefix's `tool_sources` as version ids. `adopted` is the registry's adopted value: the declarations, the fixed tool names and the version ids the registry retained for the request. `context` is the call's execution context (`turnId`, `requestId`, `branchId`), the identity the registry keys claims by. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `already_bound` | `bind` | A caller bug: the request id was bound twice. Fail the turn as a fault. | +| `version_unavailable` | `bind` | The prefix declares a source version that is no longer retained; fail the turn, or re-prepare the request from the current declarations when the turn's policy allows a retry. | +| `no_handler` | `bind` | The declaration names a tool no source provides; fail the turn and report the declaration. | +| `no_record` | `adopted`, `claim`, `transfer` | The request has no record: a caller bug or a request released before its batch. Fail the turn as a fault. | +| `closed` | any operation | The branch is closing or unloading; the turn ends. | + +`bind` errors carry the declaration that failed (`name`, `key`, `version`); the owner never reports a failure the record cannot have. + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `bind` | Ask the registry to retain the versions and resolve the declarations, then insert the record; release pins no later prefix declares | None: the call is synchronous and bounded | Nothing to release; the record stays until `release` or the owner closes | A record in flight is refused with `closed`; the registry retention of an unfinished adopt is released by the registry | ToolBinding and ToolRegistry | +| `claim` | Ask the registry to register a guard per call under the call's identity; the record notes that the request has claims | None | The record's `release` drops the claims at the owner's close | Every claim of the generation is released; the registry drops its guards | ToolRegistry | +| `release` | Drop the record, ask the registry to release the request's retention and claims, then release pins whose prefix can no longer declare them | None | Nothing to release | The owner performs the same release on close | ToolBinding and ToolRegistry | +| `transfer` | Move the record to the new request id, asking the registry to move the retention | None | Nothing to release | Refused with `closed` once the generation closes | ToolBinding and ToolRegistry | +| `retain_only` | Release every other record, in one pass | None | Nothing to release | The owner performs the same release on close | ToolBinding and ToolRegistry | + +A record is released before the branch accepts closing work. A reload rebuilds the record from the prefix's last adopted configuration, exactly as a fresh branch would; a request that was in flight when the owner reloaded has no record, and its executor ends the batch as a reload settlement, not as a `no_record` error. + +## Exceptions with reasons + +- Pins are values, not handles: a pin is the set of version ids a later prefix may declare, and the registry keeps those versions resolvable while the record holds the ids. The joint retention rule is stated in Requirements; ToolBinding holds no handler and no guard. + +## Verification + +Flow tests on the owner: + +- A request binds to the prefix's declaration; a tool registered after the bind does not appear in `adopted` or in the executor's run; a later request adopts the new registry set and the earlier pin is released. +- A request whose declaration names a version the registry no longer retains fails `version_unavailable` and binds nothing. +- A published call's claim exists before the batch fact; a batch that never dispatches (append refused, interrupt before dispatch, admission refused, a Loop error, a reload) releases it with the record; a dispatched call's guard is consumed by the registry's execution. +- Budget recovery transfers the record, and the retried request executes the version its first attempt declared. +- After a reload, the branch rebinds its prefix's configuration before the first request; an in-flight batch ends as a reload settlement. +- Cross-language: the same operations run over the face and in process, with the same replies and errors. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | ToolBinding is one branch part and a Capability: it injects `dispatcher` and `timeline` and folds the branch's opening. | +| §2 scopes | Branch. The record and pins are the branch's; the registry's retained versions are Session state the branch requests by request id. | +| §3 orthogonality | ToolBinding reads the registry's public adopt/declarations operations and Prompt's adopt operation; no other owner's state is read. | +| §4 rule 1 | The round's decisions (bind, release, transfer) are commands to this owner; the observable facts stay with Prompt (`context/configured`) and the tools' results. | +| §4 rule 2 | No handoff: the request record is the owner's state. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No business meaning in core or assembly. | +| §4 rule 5 | No batch. | +| §4 rule 6 | Declarations reach the model only through the adopted configuration; the record reads the same values. | +| §4 rule 7 | Callers use the operations; no caller reads the record's internals. | +| §4 rule 8 | No infrastructure change; the registry retention is an owner operation, not a mechanism change. | +| §4 rule 9 | No Timeline fact of its own; the adopted configuration stays Prompt's fact. | +| §7 resources and objects | The record, pins and claims are ids and values; no handler or guard crosses. | +| §7 no proxy | ToolBinding returns its own record; execution is ToolRegistry's operation. | +| §7 one surface | The operations are on the owner type; `handler`, `take_claim`, `definitions` and the preparation entries are removed. | +| §7 cross-language | Every parameter and reply is data; the face and the Rust call use the same operations. | +| §7 responsibility split | The caller keeps the declaration source and the turn's decisions; the owner keeps the record, retention and claim lifecycle. | +| ADR 002 D1 | Branch scope: a request's tool set is one behavior line's state. | +| ADR 002 D2 | No wiring part; the service is on the owner. | +| ADR 002 D3 | The registry is a Session capability the branch depends on; the registry depends on no branch. | +| ADR 002 D4 | No configuration of its own; the adopted configuration is Prompt's fact. | +| ADR 002 D5 | Language-neutral operations and data. | + +## Requirements raised to mechanism owners + +- **ToolRegistry (#2026).** The owner needs, on the registry's contract: `adopt({requestId, declared, sources}) → {adopted}` that resolves the declarations, retains the version set for the request and answers the adopted value; `release_request({requestId})` that drops the request's retention and its claims; `claim({requestId, calls, context})` that registers a guard per call and keeps it until the call is dispatched or the request is released; `declarations() → {tools, sources}` that answers the current host and contributed declarations in one read; and `execute({adopted, call, context}, cancelled) → {result}` that resolves the handler for the adopted version, takes the call's claim, executes and settles it. These match the target shape in #2026's scan report; the registry's contract must state the claim's lifecycle and the retention rule ToolBinding relies on. +- **Prompt (#2027).** The owner needs Prompt's branch operation that adopts the tool part of the configuration (`{tools, sources} → {adopted|unchanged|superseded}`), because ToolBinding writes no configuration fact. +- **None other.** No Timeline, Dispatcher, loader or runtime change. + +## Binding appendix + +The service is marked on the owner type; the name stays `toolBinding`. `CancelledFn` is the crate's cancellation argument ([`host::CancelledFn`](../../../crates/dim-agent-capabilities/src/host.rs)); every operation here completes without waiting, so no operation takes it except the registry's execution. + +```rust +use dim_agent_runtime::PublicService; +use dim_agent_types::{ToolCall, ToolDefinition, ToolSourceVersion}; + +/// The registry's adopted value for one request: its declarations, its fixed +/// tools and the source versions retained for the request. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdoptedTools { + pub tools: Vec, + pub sources: Vec, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BindRequest { + pub request_id: String, + pub through: u64, + pub declared: Vec, + pub sources: Vec, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClaimRequest { + pub request_id: String, + pub calls: Vec, + pub context: ToolExecutionContext, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TransferRequest { + pub from: String, + pub to: String, +} + +#[derive(Debug, thiserror::Error)] +pub enum BindingError { + #[error("request {request_id} is already bound")] + AlreadyBound { request_id: String }, + #[error("tool source {key}@{version} is unavailable")] + VersionUnavailable { key: String, version: String }, + #[error("tool {name} has no handler")] + NoHandler { name: String }, + #[error("request {request_id} has no tool record")] + NoRecord { request_id: String }, + #[error("the branch is closing")] + Closed, +} + +impl PublicService for ToolBinding {} + +#[rutis::service(name = "toolBinding")] +impl ToolBinding { + pub async fn bind(&self, request: BindRequest) -> Result<(), BindingError> { /* ... */ } + pub fn adopted(&self, request_id: String) -> Result { /* ... */ } + pub async fn claim(&self, request: ClaimRequest) -> Result<(), BindingError> { /* ... */ } + pub fn release(&self, request_id: String) { /* ... */ } + pub fn transfer(&self, request: TransferRequest) -> Result<(), BindingError> { /* ... */ } + pub fn retain_only(&self, request_id: String) { /* ... */ } +} +``` diff --git a/docs/design/plugins/ToolExecutor.md b/docs/design/plugins/ToolExecutor.md new file mode 100644 index 0000000000..888eb5ab99 --- /dev/null +++ b/docs/design/plugins/ToolExecutor.md @@ -0,0 +1,197 @@ +# ToolExecutor + +Scope: branch. Issue: #2028. + +ToolExecutor owns one committed tool batch on a line: its cancellation, its interrupt state, the child calls a program makes through it, and the batch's terminal `step/tool-result`. This document is the owner's target contract; the current implementation is described in the [ToolExecution plugin page](../../architecture/rust-agent/plugins/ToolExecution.md#toolexecutor). + +## Use and scope: responsibility split + +ToolExecutor owns: + +- **The current batch.** One top-level batch at a time: its token, its interrupt state, the per-call admission and the ordered settlement of the calls. +- **Child calls.** A program's nested call is opened against the current batch, addressed by a gate id the owner issues; the owner writes the child's `step/tool-call`/`step/tool-result`, runs the same admission and execution path, and closes the gate and collects the child effects when the parent call settles. +- **The facts.** `step/tool-start` and `step/tool-completed` when progress is enabled, `step/tool-result` with the correlated results, and the child facts with their parent call id. +- **Reload and interrupt settlement.** An open batch settles as a reload settlement, or as not executed, when the generation reloads; an interrupt cancels the current batch. + +ToolExecutor does not declare tools, decide admission, resolve write targets, execute a handler or hold a handler. Declarations and the adopted value belong to ToolBinding; admission belongs to Approval; write-target resolution, ordering class, claims and execution belong to ToolRegistry. + +Callers keep as business: + +- When a batch's calls run, and what a failed call means for the turn. +- The program's own control flow: which child calls a program makes and how the program reacts to a child result. +- The model-facing text of a tool failure: the owner records the result it is given. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Run a committed batch | No: the batch's order, admission, cancellation and terminal fact are one state machine | Loop writes `step/tool-call`; the owner consumes it (no caller operation) | +| Open a child call against the current batch | No: a program's child must belong to the running parent call, and a caller-composed id could outlive or precede it | `open` | +| Run a child call and receive its result | No: the child must take the same admission and execution path, write its own facts and settle before the parent | `invoke` | +| Collect the child effects before the parent result | No: only the owner knows which gates belong to the parent call and when they settled | the owner merges at parent settlement; no caller operation | +| Read the request's declarations for the program | Yes: ToolBinding's `adopted` answers the declarations | Business composition | + +An operation exists only where its row says No. + +## Caller example + +Code Mode opens a gate for one outer call and invokes child tools through it: + +```rust +let gate = executor.open(OpenRequest { + parent_call_id: outer_call_id.clone(), + context: execution.clone(), +}, cancelled.clone()).await?; // Closed, Interrupted, NoBatch +// The program's tools.call: +let result = executor.invoke(InvokeRequest { + gate_id: gate.gate_id.clone(), + call, +}, cancelled.clone()).await?; // GateClosed, Closed; a tool failure is result.is_error +``` + +A program's declarations come from the pin owner, not the executor: + +```rust +let adopted = binding.adopted(&execution.request_id).await?; // NoRecord +let declared: Vec = adopted.tools + .into_iter() + .filter(|tool| tool.name != CODEMODE_TOOL) + .collect(); +``` + +The owner closes the gate when the parent call settles; a program that returns early needs no close, and the effects of every child call it made are merged into the parent call's result in invocation order. + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `S:ToolRegistry` (Session, #2026) | Resolve a call's write target and ordering class, and execute an admitted call for the request's adopted value. | +| `B:Approval` | Admit each call, including the user's answer and the policy recheck. | +| `B:Timeline`, `B:Dispatcher` | Commit progress and results; consume batches, interrupts and turn boundaries; report faults. | +| `B:TimelineIdentity` | The calling line's identity in the execution context and the span. | +| `B:BranchLifecycle` | Child tokens under the generation's lifetime. | + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `open` | Open a child-call gate for one outer call of the current batch | `{parentCallId, context}` | `{gateId}` | Before the gate id is issued; nothing was created | `closed`, `interrupted`, `no_batch` (no current batch, or the parent call does not belong to it) | +| `invoke` | Run one child call through the same admission and execution path | `{gateId, call}` | `{result}` | The gate's parent token; the child is cancelled and its result says so | `closed`, `gate_closed` (the gate was closed by its parent's settlement or by an interrupt) | + +`gateId` is bound to the calling row and the parent call; a call from another row is `gate_closed`. A child call's refusal, cancellation, unknown tool or tool failure is a `ToolResult` with `is_error: true`, not an operation error: the program decides what to do with it. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `closed` | `open`, `invoke` | The executor is closing or reloading; stop the program; its batch is settled. | +| `interrupted` | `open` | The turn was interrupted; stop the program. | +| `no_batch` | `open` | The parent call is not part of the current batch; a caller bug: stop the program and report it. | +| `gate_closed` | `invoke` | The gate's parent call settled or the batch was interrupted; stop the program. | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `open` | Check the current batch and the parent call, issue a gate id under the calling row, subscribe the gate to the parent token | Before the id is issued: nothing exists | The row's gates are closed with their child tasks | New calls are refused; every gate of the generation is closed | ToolExecutor | +| `invoke` | Write the child `step/tool-call` with the parent call id, prepare and admit the call, execute it, write the child `step/tool-result`, record its effects | The child is cancelled; its fact records the cancellation; the gate stays usable for the program's next call | The row's gates close; in-flight children end cancelled and are recorded | In-flight children end as reload settlements; the gate is closed | ToolExecutor for the facts and the gate; ToolRegistry for the handler and its claim; the calling row for the program future | +| Parent settlement | After the parent call's result is known, close every gate of the parent, wait for its children within the owner's grace, and merge their effects into the result in invocation order | — | — | — | ToolExecutor | + +The owner never hands out a gate: `gateId` names the gate only for `invoke`, and the owner closes it. A batch's calls settle in step order, each call's admission runs when the batch starts, and an interrupt cancels the current token: those rules stay as they are, and the caller sees only the results. + +## Exceptions with reasons + +- A child call's failure is a result, not an operation error: a program may catch it, and the model sees the same `ToolResult` text a top-level call would produce. + +## Verification + +Flow tests on the owner: + +- A child call writes its own `step/tool-call`/`step/tool-result` with the parent call id; its effects appear in the parent result in invocation order; the outer result is written after its children settle. +- A program that returns early still has its child effects merged; a child that ignores cancellation past the owner's grace leaves a result the parent result does not wait for. +- An interrupt cancels a running child and refuses a new gate; a reload settles an open child and an open parent, and a reload-settled result fails the turn. +- `open` refuses a parent call that is not in the current batch and a second batch while one runs; `gate_closed` answers a call after the parent settled. +- The same operations over the face and in process answer the same results and errors. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | ToolExecutor is one branch part and a Capability: it injects `dispatcher` and `timeline` and consumes `step/tool-call`. | +| §2 scopes | Branch: a committed batch is one line's work. | +| §3 orthogonality | The executor reads ToolRegistry's and Approval's operations; no other owner's state. | +| §4 rule 1 | The batch is a command; the executor consumes it and writes results. | +| §4 rule 2 | The batch is handed to the executor by `step/tool-call`; nothing is taken back. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No business meaning in core or assembly. | +| §4 rule 5 | One batch is one atomic result; the result is last. | +| §4 rule 6 | Results reach the model only through `step/tool-result`; child facts are excluded from context. | +| §4 rule 7 | Callers use the operations; handlers and claims stay with the registry. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | Progress and results are facts later decisions use; the batch's completion is consumed by Loop and the client. | +| §7 resources and objects | The gate is the owner's; only its id crosses, and the owner closes it. | +| §7 no proxy | No forwarding of declarations; Code Mode reads ToolBinding. | +| §7 one surface | `open` and `invoke` are the operations; `definitions` and the gate object are removed. | +| §7 cross-language | Both operations take and answer data; a program in another language uses the same ids. | +| §7 responsibility split | The caller keeps the program's control flow and its reaction to results; the owner keeps order, admission, cancellation and facts. | +| ADR 002 D1 | Branch scope. | +| ADR 002 D2 | No wiring part. | +| ADR 002 D3 | Depends on Session capabilities (the registry) and branch peers (Approval); nothing depends on the executor's internals. | +| ADR 002 D4 | No configuration. | +| ADR 002 D5 | Language-neutral operations and data. | + +## Requirements raised to mechanism owners + +- **ToolRegistry (#2026).** The owner needs `prepare({adopted, call}, cancelled) → {call, risk}` (resolve the write target and answer the ordering class and risk without side effects) and `execute({adopted, call, context}, cancelled) → {result}` (take the call's claim, run the handler and settle it). These are the registry's operations for the branch executor; the registry's contract states them. +- **Approval (#2028).** `admit` is this board's own operation (see [Approval](Approval.md)). +- **None other.** No Timeline, Dispatcher, loader or runtime change. + +## Binding appendix + +The service is marked on the owner type; the name stays `toolExecutor`. + +```rust +use crate::host::CancelledFn; +use dim_agent_runtime::PublicService; +use dim_agent_types::ToolCall; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OpenRequest { + pub parent_call_id: String, + pub context: ToolExecutionContext, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OpenReply { + pub gate_id: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct InvokeRequest { + pub gate_id: String, + pub call: ToolCall, +} + +#[derive(Debug, thiserror::Error)] +pub enum ExecutorError { + #[error("the tool executor is closing")] + Closed, + #[error("the turn was interrupted: {reason}")] + Interrupted { reason: String }, + #[error("no current tool batch accepts this child call")] + NoBatch, + #[error("the child gate is closed")] + GateClosed, +} + +impl PublicService for ToolExecutor {} + +#[rutis::service(name = "toolExecutor")] +impl ToolExecutor { + pub async fn open(&self, request: OpenRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn invoke(&self, request: InvokeRequest, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` From 5c9cdef806a66435189f4a4c761a4c8c06dbd917 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Mon, 23 Nov 2026 15:01:15 +0800 Subject: [PATCH 02/11] docs(design): link the sibling contracts from the tool chain contracts ToolRegistry (#2026), Prompt (#2027), SessionScope (#2093), TimelineTree (#2092), the Session access mechanism and HostPlatform (#2032). --- docs/design/plugins/BackgroundExec.md | 8 ++++---- docs/design/plugins/FileReads.md | 4 ++-- docs/design/plugins/Permission.md | 8 ++++---- docs/design/plugins/ToolBinding.md | 8 ++++---- docs/design/plugins/ToolExecutor.md | 4 ++-- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/docs/design/plugins/BackgroundExec.md b/docs/design/plugins/BackgroundExec.md index a839c47415..7efcd27199 100644 --- a/docs/design/plugins/BackgroundExec.md +++ b/docs/design/plugins/BackgroundExec.md @@ -70,8 +70,8 @@ let ended = background.wait(WaitRequest { task_id, timeout_ms: 5_000 }, cancelle | Service | Purpose | | --- | --- | -| `P:HostPlatform` (process, #2032) | The started process by task id: wait for it, kill it, and answer its terminal status. | -| `S:SessionScope` (Session, #2093) | Hold the Session while a task runs; observe activation and closing. | +| `P:HostPlatform` (process, [#2032](https://github.com/arcships/dim/issues/2032)) | The started process by task id: wait for it, kill it, and answer its terminal status. | +| `S:SessionScope` (Session, [#2093](https://github.com/arcships/dim/pull/2093)) | Hold the Session while a task runs; observe activation and closing. | | `S:GuideEntries` (Session) | Register the exec notification's entry for this line until the part unloads. | | `B:Timeline`, `B:Dispatcher` | Write and recover `exec/started`/`exec/ended`; consume terminals and interrupts; write the wake input. | @@ -154,8 +154,8 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -- **HostPlatform (#2032).** The process owner must expose a started process by task id: `wait({taskId}, cancelled) → {status, exit}`, `kill({taskId}) → {}`, and the task id in its start reply. BackgroundExec adopts that id and never receives a process object. Until the host's id operations land, this board's `adopt` and `stop` cannot be implemented; the other owners' contracts are independent. -- **SessionScope (#2093).** `hold` returns the lease id, `release` ends it early, and `activated`/`closing` gate the watcher. +- **HostPlatform ([#2032](https://github.com/arcships/dim/issues/2032)).** The process owner must expose a started process by task id: `wait({taskId}, cancelled) → {status, exit}`, `kill({taskId}) → {}`, and the task id in its start reply. BackgroundExec adopts that id and never receives a process object. Until the host's id operations land, this board's `adopt` and `stop` cannot be implemented; the other owners' contracts are independent. +- **SessionScope ([#2093](https://github.com/arcships/dim/pull/2093)).** `hold` returns the lease id, `release` ends it early, and `activated`/`closing` gate the watcher. - **None other.** No Timeline, Dispatcher, loader or runtime change. ## Binding appendix diff --git a/docs/design/plugins/FileReads.md b/docs/design/plugins/FileReads.md index 984053d68c..2ec6d6961a 100644 --- a/docs/design/plugins/FileReads.md +++ b/docs/design/plugins/FileReads.md @@ -70,7 +70,7 @@ let Some(binding) = binding.binding else { | --- | --- | | `B:Timeline` | The line's committed file-tool results, from which bindings are rebuilt, and the completed `context/compaction` facts that decide the context rule. | -FileReads injects no other service. The Session's file tools reach this owner through the Session access mechanism by line id ([TimelineTree's route](TimelineTree.md#session-parts-reaching-a-lines-owners)); FileReads returns values and stores records, and no file handle crosses. +FileReads injects no other service. The Session's file tools reach this owner through the Session access mechanism by line id ([TimelineTree's route (#2092)](https://github.com/arcships/dim/pull/2092)); FileReads returns values and stores records, and no file handle crosses. ### Operations @@ -141,7 +141,7 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -- **Session access (#2025).** A Session part resolves a line's owner by line id: the mechanism named in [TimelineTree's route](TimelineTree.md#session-parts-reaching-a-lines-owners). The file tools use it to reach `binding` and `record`; FileReads adds no forwarding operation. +- **Session access ([#2025](https://github.com/arcships/dim/issues/2025)).** A Session part resolves a line's owner by line id: the mechanism named in [TimelineTree's route (#2092)](https://github.com/arcships/dim/pull/2092). The file tools use it to reach `binding` and `record`; FileReads adds no forwarding operation. - **None other.** No Timeline, Dispatcher, loader or runtime change. ## Binding appendix diff --git a/docs/design/plugins/Permission.md b/docs/design/plugins/Permission.md index f19fcbe296..f0dd51ec87 100644 --- a/docs/design/plugins/Permission.md +++ b/docs/design/plugins/Permission.md @@ -73,9 +73,9 @@ let next = permission.update(UpdateRequest { | Service | Purpose | | --- | --- | -| `S:SessionScope` (Session, #2093) | The creation record's permission preset and working directory, and the Session id for facts queries. | +| `S:SessionScope` (Session, [#2093](https://github.com/arcships/dim/pull/2093)) | The creation record's permission preset and working directory, and the Session id for facts queries. | | `S:CommandRules` (Session port) | The user's command rules, read at decision time. | -| `S:FileAccessFacts` (Session owner, #2025) | Resolve the call's target and answer the workspace, system, owned and grant facts. | +| `S:FileAccessFacts` (Session owner, [#2025](https://github.com/arcships/dim/issues/2025)) | Resolve the call's target and answer the workspace, system, owned and grant facts. | | `B:Timeline`, `B:Dispatcher` | Fold `permission/changed`; commit an update. | The file-access facts operation that resolves the target is not defined yet; it is stated in Requirements. @@ -156,8 +156,8 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -- **File access facts (#2025).** The Session owner must publish one data operation, `check({sessionId, access, mode, path}, cancelled) → {target, workspace, system, owned, grant, discoveryError?}`, that resolves the call's path (`~`, cwd, `..`, links) and answers the facts under the effective access. Permission currently reads the owner's Rust object and a host `home` value; both disappear with this operation. -- **SessionScope (#2093).** `config` and `identity` are the target's operations; Permission's creation-record reads use them. +- **File access facts ([#2025](https://github.com/arcships/dim/issues/2025)).** The Session owner must publish one data operation, `check({sessionId, access, mode, path}, cancelled) → {target, workspace, system, owned, grant, discoveryError?}`, that resolves the call's path (`~`, cwd, `..`, links) and answers the facts under the effective access. Permission currently reads the owner's Rust object and a host `home` value; both disappear with this operation. +- **SessionScope ([#2093](https://github.com/arcships/dim/pull/2093)).** `config` and `identity` are the target's operations; Permission's creation-record reads use them. - **None other.** No Timeline, Dispatcher, loader or runtime change. ## Binding appendix diff --git a/docs/design/plugins/ToolBinding.md b/docs/design/plugins/ToolBinding.md index 77af6eaa7d..1c5fcbb4c5 100644 --- a/docs/design/plugins/ToolBinding.md +++ b/docs/design/plugins/ToolBinding.md @@ -96,8 +96,8 @@ let outcome = registry.execute(ExecuteRequest { | Service | Purpose | | --- | --- | -| `B:Prompt` (branch, #2027) | Adopt the tool part of the branch's model configuration when the registry's set changes. | -| `S:ToolRegistry` (Session, #2026) | Retain an adopted version set for a request, register a call's claim, and release a request's retention and claims. | +| `B:Prompt` (branch, [#2027](https://github.com/arcships/dim/issues/2027)) | Adopt the tool part of the branch's model configuration when the registry's set changes. | +| `S:ToolRegistry` (Session, [#2026](https://github.com/arcships/dim/issues/2026)) | Retain an adopted version set for a request, register a call's claim, and release a request's retention and claims. | | `B:Timeline`, `B:Dispatcher` | Reconcile the prefix's last configuration at branch opening and after a reload. | | `B:BranchLifecycle` | Gate the registry-change watcher on activation and closing. | @@ -184,8 +184,8 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -- **ToolRegistry (#2026).** The owner needs, on the registry's contract: `adopt({requestId, declared, sources}) → {adopted}` that resolves the declarations, retains the version set for the request and answers the adopted value; `release_request({requestId})` that drops the request's retention and its claims; `claim({requestId, calls, context})` that registers a guard per call and keeps it until the call is dispatched or the request is released; `declarations() → {tools, sources}` that answers the current host and contributed declarations in one read; and `execute({adopted, call, context}, cancelled) → {result}` that resolves the handler for the adopted version, takes the call's claim, executes and settles it. These match the target shape in #2026's scan report; the registry's contract must state the claim's lifecycle and the retention rule ToolBinding relies on. -- **Prompt (#2027).** The owner needs Prompt's branch operation that adopts the tool part of the configuration (`{tools, sources} → {adopted|unchanged|superseded}`), because ToolBinding writes no configuration fact. +- **ToolRegistry ([#2026](https://github.com/arcships/dim/issues/2026)).** The owner needs, on the registry's contract: `adopt({requestId, declared, sources}) → {adopted}` that resolves the declarations, retains the version set for the request and answers the adopted value; `release_request({requestId})` that drops the request's retention and its claims; `claim({requestId, calls, context})` that registers a guard per call and keeps it until the call is dispatched or the request is released; `declarations() → {tools, sources}` that answers the current host and contributed declarations in one read; and `execute({adopted, call, context}, cancelled) → {result}` that resolves the handler for the adopted version, takes the call's claim, executes and settles it. These match the target shape in #2026's scan report; the registry's contract must state the claim's lifecycle and the retention rule ToolBinding relies on. +- **Prompt ([#2027](https://github.com/arcships/dim/issues/2027)).** The owner needs Prompt's branch operation that adopts the tool part of the configuration (`{tools, sources} → {adopted|unchanged|superseded}`), because ToolBinding writes no configuration fact. - **None other.** No Timeline, Dispatcher, loader or runtime change. ## Binding appendix diff --git a/docs/design/plugins/ToolExecutor.md b/docs/design/plugins/ToolExecutor.md index 888eb5ab99..dcd06c08b2 100644 --- a/docs/design/plugins/ToolExecutor.md +++ b/docs/design/plugins/ToolExecutor.md @@ -65,7 +65,7 @@ The owner closes the gate when the parent call settles; a program that returns e | Service | Purpose | | --- | --- | -| `S:ToolRegistry` (Session, #2026) | Resolve a call's write target and ordering class, and execute an admitted call for the request's adopted value. | +| `S:ToolRegistry` (Session, [#2026](https://github.com/arcships/dim/issues/2026)) | Resolve a call's write target and ordering class, and execute an admitted call for the request's adopted value. | | `B:Approval` | Admit each call, including the user's answer and the policy recheck. | | `B:Timeline`, `B:Dispatcher` | Commit progress and results; consume batches, interrupts and turn boundaries; report faults. | | `B:TimelineIdentity` | The calling line's identity in the execution context and the span. | @@ -142,7 +142,7 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -- **ToolRegistry (#2026).** The owner needs `prepare({adopted, call}, cancelled) → {call, risk}` (resolve the write target and answer the ordering class and risk without side effects) and `execute({adopted, call, context}, cancelled) → {result}` (take the call's claim, run the handler and settle it). These are the registry's operations for the branch executor; the registry's contract states them. +- **ToolRegistry ([#2026](https://github.com/arcships/dim/issues/2026)).** The owner needs `prepare({adopted, call}, cancelled) → {call, risk}` (resolve the write target and answer the ordering class and risk without side effects) and `execute({adopted, call, context}, cancelled) → {result}` (take the call's claim, run the handler and settle it). These are the registry's operations for the branch executor; the registry's contract states them. - **Approval (#2028).** `admit` is this board's own operation (see [Approval](Approval.md)). - **None other.** No Timeline, Dispatcher, loader or runtime change. From 19d1421bd64290c0316eb56408134e0a295ea7d8 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Mon, 23 Nov 2026 15:17:51 +0800 Subject: [PATCH 03/11] docs(design): use the sibling owners' operation names ToolRegistry adopt/release/run/resolve_write/ordering/claim/release_claims, Prompt configure, PermissionRules rules, HostPlatform spawn/wait/kill/settle, and ToolExecutor close for Code Mode's effects. --- docs/design/plugins/BackgroundExec.md | 2 +- docs/design/plugins/Permission.md | 3 +- docs/design/plugins/ToolBinding.md | 157 ++++++++++++-------------- docs/design/plugins/ToolExecutor.md | 45 +++++--- 4 files changed, 107 insertions(+), 100 deletions(-) diff --git a/docs/design/plugins/BackgroundExec.md b/docs/design/plugins/BackgroundExec.md index 7efcd27199..3fabd85293 100644 --- a/docs/design/plugins/BackgroundExec.md +++ b/docs/design/plugins/BackgroundExec.md @@ -154,7 +154,7 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -- **HostPlatform ([#2032](https://github.com/arcships/dim/issues/2032)).** The process owner must expose a started process by task id: `wait({taskId}, cancelled) → {status, exit}`, `kill({taskId}) → {}`, and the task id in its start reply. BackgroundExec adopts that id and never receives a process object. Until the host's id operations land, this board's `adopt` and `stop` cannot be implemented; the other owners' contracts are independent. +- **HostPlatform ([#2032](https://github.com/arcships/dim/issues/2032)).** The process owner must expose a started process by task id: `spawn(...) → {taskId}`, `wait({taskId}, cancelled)`, `kill({taskId})`, `settle({taskId})`, and settle its task table on close or reload. BackgroundExec adopts that id and never receives a process object. Until the host's id operations land, this board's `adopt` and `stop` cannot be implemented; the other owners' contracts are independent. - **SessionScope ([#2093](https://github.com/arcships/dim/pull/2093)).** `hold` returns the lease id, `release` ends it early, and `activated`/`closing` gate the watcher. - **None other.** No Timeline, Dispatcher, loader or runtime change. diff --git a/docs/design/plugins/Permission.md b/docs/design/plugins/Permission.md index f0dd51ec87..af8f8403fd 100644 --- a/docs/design/plugins/Permission.md +++ b/docs/design/plugins/Permission.md @@ -74,7 +74,7 @@ let next = permission.update(UpdateRequest { | Service | Purpose | | --- | --- | | `S:SessionScope` (Session, [#2093](https://github.com/arcships/dim/pull/2093)) | The creation record's permission preset and working directory, and the Session id for facts queries. | -| `S:CommandRules` (Session port) | The user's command rules, read at decision time. | +| `S:PermissionRules` (Session, [#2094](https://github.com/arcships/dim/pull/2094)) | `permissionRules.rules` answers the user's command rules at decision time. | | `S:FileAccessFacts` (Session owner, [#2025](https://github.com/arcships/dim/issues/2025)) | Resolve the call's target and answer the workspace, system, owned and grant facts. | | `B:Timeline`, `B:Dispatcher` | Fold `permission/changed`; commit an update. | @@ -158,6 +158,7 @@ Flow tests on the owner: - **File access facts ([#2025](https://github.com/arcships/dim/issues/2025)).** The Session owner must publish one data operation, `check({sessionId, access, mode, path}, cancelled) → {target, workspace, system, owned, grant, discoveryError?}`, that resolves the call's path (`~`, cwd, `..`, links) and answers the facts under the effective access. Permission currently reads the owner's Rust object and a host `home` value; both disappear with this operation. - **SessionScope ([#2093](https://github.com/arcships/dim/pull/2093)).** `config` and `identity` are the target's operations; Permission's creation-record reads use them. +- **Permission rules ([#2017](https://github.com/arcships/dim/issues/2017)).** `permissionRules.rules` ([#2094](https://github.com/arcships/dim/pull/2094)) is the command-rules operation Permission reads; the `commandRules` name is removed. - **None other.** No Timeline, Dispatcher, loader or runtime change. ## Binding appendix diff --git a/docs/design/plugins/ToolBinding.md b/docs/design/plugins/ToolBinding.md index 1c5fcbb4c5..bd2dae9113 100644 --- a/docs/design/plugins/ToolBinding.md +++ b/docs/design/plugins/ToolBinding.md @@ -2,33 +2,31 @@ Scope: branch. Issue: #2028. -ToolBinding owns the branch's record of each request's adopted tool set: the declarations the request's prefix declared, the source version ids the owner resolved them against, and the pins that keep a later prefix's versions resolvable. This document is the owner's target contract; the current implementation is described in the [ToolExecution plugin page](../../architecture/rust-agent/plugins/ToolExecution.md#toolbinding). +ToolBinding owns the branch's record of each request's adopted tool generation: the declarations the request's prefix declared, the registry adoption that keeps their versions resolvable, and the pins that keep a later prefix's generation alive. This document is the owner's target contract; the current implementation is described in the [ToolExecution plugin page](../../architecture/rust-agent/plugins/ToolExecution.md#toolbinding). ## Use and scope: responsibility split ToolBinding owns: -- **The request record.** One adopted value per request id: the declarations, the fixed tool names and the source version ids. A request id is bound once; a budget-recovery request takes over the record of the request it retries. -- **Pins.** The adopted sets a later request prefix may still declare, and their release. A pin is a value; ToolBinding asks the registry to retain the versions and drops the retention when the pin is released. -- **The claims of a request's published calls.** Before the batch fact is appended, ToolBinding asks the owner of the tool handlers to register each call's claim under the call's identity, and it releases every claim of the request at the request record's release. -- **The adopted value the executor passes back to the registry.** ToolBinding is the only place a request's adopted value is read after preparation. +- **The request record.** One adopted generation per request id: the registry's adoption id and the declarations it was adopted for. A request id is bound once; a budget-recovery request takes over the record of the request it retries. +- **Pins.** The records whose prefix a later request may still declare, and their release. A pin is a value; ToolBinding asks the registry to release an adoption when no later prefix can name it. +- **The adopted value the executor runs and the program reads.** The adoption id and the declarations, read from the request record. -ToolBinding does not execute tools, decide admission, hold a handler or a claim guard, or write the adopted configuration. The adopted configuration fact (`context/configured`'s tool part) belongs to Prompt; execution, write-target resolution, ordering class and the claim guards belong to ToolRegistry. +ToolBinding does not execute tools, decide admission, hold a handler, or register a call's claim. The registry's `adopt` resolves the declarations and retains their versions; the registry's `claim`/`release_claims` register and drop a request's pre-publish claims for Loop; execution, write-target resolution and ordering class belong to the registry's `run`, `resolve_write` and `ordering`. The adopted configuration fact (`context/configured`'s tool part) belongs to Prompt. Callers keep as business: - Which declarations a request's prefix carries, and where the declaration comes from: the prefix's adopted configuration, the registry's current set, or a host's selection over the registry's declarations. - When a request is prepared, retried or abandoned; whether a turn is failed; how a model request's declarations are shaped. -- The tool-call batch: which calls a request publishes and when. +- The tool-call batch and the claims of its calls: Loop calls `claim` before the batch fact and `release_claims` on the paths that never dispatch. | Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | -| Bind a request to the adopted tool set its prefix declared | No: the record must be released on every path that ends the request, and a caller that held the adopted value would have to release it itself on each error path | `bind` | -| Read the adopted value to execute a call | No: the adopted value is the record's state, and the registry retains the versions on the record's behalf | `adopted` | -| Read a request's declarations for a program that may only see them (Code Mode) | Yes: `adopted` answers the same value; the program takes the declaration part | Business composition | -| Register a published call's claim before the batch fact | No: the claim must exist before the fact and be released with the record on every non-dispatch path | `claim` | +| Bind a request to the adopted generation its prefix declared | No: the adoption must be released on every path that ends the request, and a caller that held the adoption id would have to release it itself on each error path | `bind` | +| Read the adoption and declarations to run a call | No: the record is the owner's state; the registry's `run` takes the adoption id | `adopted` | +| Read a request's declarations for a program that may only see them (Code Mode) | Yes: `adopted` answers the same record; the program takes the declaration part | Business composition | | Release a request that will not execute again | No: only the caller knows the turn's decision; the record owner performs the release | `release` | -| Keep the same adopted set across a budget-recovery retry | No: the record moves to the new request id; composing it would copy and release records | `transfer` | +| Keep the same adopted generation across a budget-recovery retry | No: the record moves to the new request id; composing it would copy and release records | `transfer` | | Keep only the current request after a rebuild | No: a rebuild must drop every stale record in one step | `retain_only` | An operation exists only where its row says No. @@ -39,13 +37,13 @@ Loop prepares a request from the prefix's adopted configuration and publishes a ```rust // The prefix's adopted tool part, or none when the configuration carries none. -let adopted = match configuration.tools { +match configuration.tools { Some(tools) => binding.bind(BindRequest { request_id: request.id.clone(), through, declared: tools.clone(), sources: configuration.tool_sources.clone(), - }).await?, // AlreadyBound + }).await?, // AlreadyBound, Invalid, Unavailable, Closed None => { // No tool part: declare the registry's current host and contributed tools. let current = registry.declarations().await?; @@ -56,17 +54,12 @@ let adopted = match configuration.tools { sources: current.sources, }).await? } -}; - +} // Before the batch fact, so a published question can already be answered. -binding.claim(ClaimRequest { - request_id: request.id.clone(), - calls: request.calls.clone(), - context: execution.clone(), -}).await?; +registry.claim(ClaimCalls { request: request.id.clone(), calls: request.calls.clone() }).await?; ``` -A host that selects tools over the registry's declarations composes the same three steps; the declarations it reads are the ones it passes on: +A host that selects tools over the registry's declarations composes the same steps; the declarations it reads are the ones it binds: ```rust let available = registry.declarations().await?; @@ -79,79 +72,86 @@ binding.bind(BindRequest { }).await?; ``` -ToolExecutor reads the adopted value once per call and hands it back to the registry, which resolves the handler for that version: +ToolExecutor reads the adoption once per call and hands it to the registry, which resolves the version's handler: ```rust -let adopted = binding.adopted(&context.request_id).await?; // NoRecord -let outcome = registry.execute(ExecuteRequest { - adopted, - call: call.clone(), - context: context.clone(), +let adopted = binding.adopted(&context.request_id).await?; // Invalid +let call = registry.resolve_write(ResolveWrite { adoption: adopted.adoption.clone(), call }, cancelled).await?; +let outcome = registry.run(RunCall { + adoption: adopted.adoption, + call, + caller: context.clone(), }, cancelled).await?; // the tool's own failure is a ToolResult, not an error ``` +Code Mode reads the same record and takes only the declarations: + +```rust +let declared: Vec = binding.adopted(&execution.request_id).await?.tools + .into_iter() + .filter(|tool| tool.name != CODEMODE_TOOL) + .collect(); +``` + ## Own contract ### Dependencies | Service | Purpose | | --- | --- | +| `S:ToolRegistry` (Session, [#2026](https://github.com/arcships/dim/issues/2026)) | Adopt a declared generation, retaining its versions, and release it when the record ends. | | `B:Prompt` (branch, [#2027](https://github.com/arcships/dim/issues/2027)) | Adopt the tool part of the branch's model configuration when the registry's set changes. | -| `S:ToolRegistry` (Session, [#2026](https://github.com/arcships/dim/issues/2026)) | Retain an adopted version set for a request, register a call's claim, and release a request's retention and claims. | | `B:Timeline`, `B:Dispatcher` | Reconcile the prefix's last configuration at branch opening and after a reload. | | `B:BranchLifecycle` | Gate the registry-change watcher on activation and closing. | -The registry's adopt, retain, claim and release operations are not defined yet; they are stated in Requirements. - ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `bind` | Fix a request to one adopted tool set | `{requestId, through, declared, sources}` | `{}` | None; the owner completes the record | `already_bound`, `version_unavailable` (a declared source version is no longer retained), `no_handler` (a declared name has no implementation in the registry) | -| `adopted` | The request's adopted value | `{requestId}` | `{adopted}` | None | `no_record` | -| `claim` | Register the calls' claims before their batch fact | `{requestId, calls, context}` | `{}` | None | `no_record` | -| `release` | Drop a request's record, its retention and its claims | `{requestId}` | `{}` | None | None: an absent record is a no-op | -| `transfer` | Move a record to the request that retries it | `{from, to}` | `{}` | None | `no_record` | -| `retain_only` | Keep one request's record and drop every other | `{requestId}` | `{}` | None | None | +| `bind` | Fix a request to one adopted generation | `{requestId, through, declared, sources}` | `{}` | None; the owner completes the adoption and the record | `already_bound`, `invalid` (the registry refused the declarations), `unavailable` (a source version is gone), `closed` | +| `adopted` | The record's adoption id and declarations | `{requestId}` | `{adoption, tools}` | None | `invalid` (no record), `closed` | +| `release` | Drop a request's record and its adoption | `{requestId}` | `{}` | None | `closed` | +| `transfer` | Move a record to the request that retries it | `{from, to}` | `{}` | None | `invalid` (no record), `closed` | +| `retain_only` | Keep one request's record and drop every other | `{requestId}` | `{}` | None | `closed` | -`declared` is the request's full declaration list; `sources` is the prefix's `tool_sources` as version ids. `adopted` is the registry's adopted value: the declarations, the fixed tool names and the version ids the registry retained for the request. `context` is the call's execution context (`turnId`, `requestId`, `branchId`), the identity the registry keys claims by. +`declared` is the request's full declaration list; `sources` is the prefix's `tool_sources` as version ids. `through` is the prefix cutoff the record's pin is released against. `adoption` is the registry's id from `adopt`; the registry retains the version set until `release`. ### Errors | Kind | Operation | What the caller does next | | --- | --- | --- | | `already_bound` | `bind` | A caller bug: the request id was bound twice. Fail the turn as a fault. | -| `version_unavailable` | `bind` | The prefix declares a source version that is no longer retained; fail the turn, or re-prepare the request from the current declarations when the turn's policy allows a retry. | -| `no_handler` | `bind` | The declaration names a tool no source provides; fail the turn and report the declaration. | -| `no_record` | `adopted`, `claim`, `transfer` | The request has no record: a caller bug or a request released before its batch. Fail the turn as a fault. | -| `closed` | any operation | The branch is closing or unloading; the turn ends. | +| `invalid` | `bind` | The registry refused the declarations (a name has no handler, or its definition changed); fail the turn and report the declaration. | +| `unavailable` | `bind` | The prefix declares a source version the registry no longer retains; fail the turn, or re-prepare from the current declarations when the turn's policy allows a retry. | +| `invalid` | `adopted`, `transfer` | The request has no record: a caller bug or a request released before its batch. Fail the turn as a fault. | +| `closed` | any | The branch is closing or unloading; the turn ends. | -`bind` errors carry the declaration that failed (`name`, `key`, `version`); the owner never reports a failure the record cannot have. +`bind` errors carry the declaration that failed (`name`) or the source that is gone (`key`, `version`); the owner reports no failure the record cannot have. ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `bind` | Ask the registry to retain the versions and resolve the declarations, then insert the record; release pins no later prefix declares | None: the call is synchronous and bounded | Nothing to release; the record stays until `release` or the owner closes | A record in flight is refused with `closed`; the registry retention of an unfinished adopt is released by the registry | ToolBinding and ToolRegistry | -| `claim` | Ask the registry to register a guard per call under the call's identity; the record notes that the request has claims | None | The record's `release` drops the claims at the owner's close | Every claim of the generation is released; the registry drops its guards | ToolRegistry | -| `release` | Drop the record, ask the registry to release the request's retention and claims, then release pins whose prefix can no longer declare them | None | Nothing to release | The owner performs the same release on close | ToolBinding and ToolRegistry | -| `transfer` | Move the record to the new request id, asking the registry to move the retention | None | Nothing to release | Refused with `closed` once the generation closes | ToolBinding and ToolRegistry | +| `bind` | Ask the registry to adopt the declarations, insert the record, release the adoptions of pins no later prefix declares | None: the call is synchronous and bounded | Nothing to release; the record stays until `release` or the owner closes | A record in flight is refused with `closed`; an adoption the registry granted is released by the registry at the row's unload | ToolBinding and ToolRegistry | +| `adopted` | Read the record and answer its adoption and declarations | None | Nothing to release | Refused with `closed`; a reload rebuilds the record from the prefix's configuration | ToolBinding | +| `release` | Drop the record and ask the registry to release its adoption | None | Nothing to release | The owner performs the same release on close | ToolBinding and ToolRegistry | +| `transfer` | Move the record to the new request id | None | Nothing to release | Refused with `closed` once the generation closes | ToolBinding | | `retain_only` | Release every other record, in one pass | None | Nothing to release | The owner performs the same release on close | ToolBinding and ToolRegistry | -A record is released before the branch accepts closing work. A reload rebuilds the record from the prefix's last adopted configuration, exactly as a fresh branch would; a request that was in flight when the owner reloaded has no record, and its executor ends the batch as a reload settlement, not as a `no_record` error. +A record is released before the branch accepts closing work. A reload rebuilds the record from the prefix's last adopted configuration, exactly as a fresh branch would; a request that was in flight when the owner reloaded has no record, and its executor ends the batch as a reload settlement, not as an `invalid` error. ## Exceptions with reasons -- Pins are values, not handles: a pin is the set of version ids a later prefix may declare, and the registry keeps those versions resolvable while the record holds the ids. The joint retention rule is stated in Requirements; ToolBinding holds no handler and no guard. +- Pins are values, not handles: a pin is a record whose adoption a later prefix may still name, and the registry keeps those versions resolvable until the record releases the adoption. ToolBinding holds no handler and no guard. ## Verification Flow tests on the owner: -- A request binds to the prefix's declaration; a tool registered after the bind does not appear in `adopted` or in the executor's run; a later request adopts the new registry set and the earlier pin is released. -- A request whose declaration names a version the registry no longer retains fails `version_unavailable` and binds nothing. -- A published call's claim exists before the batch fact; a batch that never dispatches (append refused, interrupt before dispatch, admission refused, a Loop error, a reload) releases it with the record; a dispatched call's guard is consumed by the registry's execution. -- Budget recovery transfers the record, and the retried request executes the version its first attempt declared. +- A request binds to the prefix's declaration; a tool registered after the bind does not appear in `adopted` or in the executor's run; a later request adopts the new registry set and the earlier pin's adoption is released. +- A request whose declaration names a version the registry no longer retains fails `unavailable` and binds nothing. +- A request's claims exist before the batch fact and are released on every path that never dispatches (append refused, interrupt before dispatch, admission refused, a Loop error); a dispatched call's guard is consumed by the registry's run. The claims are the registry's `claim`/`release_claims`, driven by Loop. +- Budget recovery transfers the record, and the retried request runs the version its first attempt declared. - After a reload, the branch rebinds its prefix's configuration before the first request; an in-flight batch ends as a reload settlement. - Cross-language: the same operations run over the face and in process, with the same replies and errors. @@ -160,8 +160,8 @@ Flow tests on the owner: | Rule | Application | | --- | --- | | §1 parts and Capabilities | ToolBinding is one branch part and a Capability: it injects `dispatcher` and `timeline` and folds the branch's opening. | -| §2 scopes | Branch. The record and pins are the branch's; the registry's retained versions are Session state the branch requests by request id. | -| §3 orthogonality | ToolBinding reads the registry's public adopt/declarations operations and Prompt's adopt operation; no other owner's state is read. | +| §2 scopes | Branch. The record and pins are the branch's; the registry's adoption and retained versions are Session state the branch requests by id. | +| §3 orthogonality | ToolBinding reads the registry's public adopt/release operations and Prompt's configure operation; no other owner's state is read. | | §4 rule 1 | The round's decisions (bind, release, transfer) are commands to this owner; the observable facts stay with Prompt (`context/configured`) and the tools' results. | | §4 rule 2 | No handoff: the request record is the owner's state. | | §4 rule 3 | No before callback. | @@ -169,14 +169,14 @@ Flow tests on the owner: | §4 rule 5 | No batch. | | §4 rule 6 | Declarations reach the model only through the adopted configuration; the record reads the same values. | | §4 rule 7 | Callers use the operations; no caller reads the record's internals. | -| §4 rule 8 | No infrastructure change; the registry retention is an owner operation, not a mechanism change. | +| §4 rule 8 | No infrastructure change. | | §4 rule 9 | No Timeline fact of its own; the adopted configuration stays Prompt's fact. | -| §7 resources and objects | The record, pins and claims are ids and values; no handler or guard crosses. | -| §7 no proxy | ToolBinding returns its own record; execution is ToolRegistry's operation. | -| §7 one surface | The operations are on the owner type; `handler`, `take_claim`, `definitions` and the preparation entries are removed. | +| §7 resources and objects | The record, pins and adoption ids are values; no handler or guard crosses. | +| §7 no proxy | ToolBinding returns its own record; execution and claims are ToolRegistry's operations. | +| §7 one surface | The operations are on the owner type; `handler`, `take_claim`, `definitions`, `claim`, `prepare` and `bind_current` are removed. | | §7 cross-language | Every parameter and reply is data; the face and the Rust call use the same operations. | -| §7 responsibility split | The caller keeps the declaration source and the turn's decisions; the owner keeps the record, retention and claim lifecycle. | -| ADR 002 D1 | Branch scope: a request's tool set is one behavior line's state. | +| §7 responsibility split | The caller keeps the declaration source, the turn's decisions and the claims; the owner keeps the record, its adoption and its pins. | +| ADR 002 D1 | Branch scope: a request's tool generation is one behavior line's state. | | ADR 002 D2 | No wiring part; the service is on the owner. | | ADR 002 D3 | The registry is a Session capability the branch depends on; the registry depends on no branch. | | ADR 002 D4 | No configuration of its own; the adopted configuration is Prompt's fact. | @@ -184,25 +184,25 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -- **ToolRegistry ([#2026](https://github.com/arcships/dim/issues/2026)).** The owner needs, on the registry's contract: `adopt({requestId, declared, sources}) → {adopted}` that resolves the declarations, retains the version set for the request and answers the adopted value; `release_request({requestId})` that drops the request's retention and its claims; `claim({requestId, calls, context})` that registers a guard per call and keeps it until the call is dispatched or the request is released; `declarations() → {tools, sources}` that answers the current host and contributed declarations in one read; and `execute({adopted, call, context}, cancelled) → {result}` that resolves the handler for the adopted version, takes the call's claim, executes and settles it. These match the target shape in #2026's scan report; the registry's contract must state the claim's lifecycle and the retention rule ToolBinding relies on. -- **Prompt ([#2027](https://github.com/arcships/dim/issues/2027)).** The owner needs Prompt's branch operation that adopts the tool part of the configuration (`{tools, sources} → {adopted|unchanged|superseded}`), because ToolBinding writes no configuration fact. +- **ToolRegistry ([#2026](https://github.com/arcships/dim/issues/2026)).** The registry's contract ([#2103](https://github.com/arcships/dim/pull/2103)) defines `adopt`, `release`, `run`, `resolve_write`, `ordering`, `claim`, `release_claims` and `declarations`. ToolBinding uses `adopt` and `release` only; Loop uses `claim` and `release_claims`; ToolExecutor uses `run`, `resolve_write` and `ordering`. The registry's row-bound unload release is what makes the record's adoption safe to hold as a value. +- **Prompt ([#2027](https://github.com/arcships/dim/issues/2027)).** The owner needs Prompt's `configure({tools})` operation ([PromptAdoption](https://github.com/arcships/dim/pull/2102)), because ToolBinding writes no configuration fact; a tool-only adoption without an adopted model is Prompt's `invalid_model`. - **None other.** No Timeline, Dispatcher, loader or runtime change. ## Binding appendix -The service is marked on the owner type; the name stays `toolBinding`. `CancelledFn` is the crate's cancellation argument ([`host::CancelledFn`](../../../crates/dim-agent-capabilities/src/host.rs)); every operation here completes without waiting, so no operation takes it except the registry's execution. +The service is marked on the owner type; the name stays `toolBinding`. Every operation completes without waiting; the registry's operations take the cancellation argument. ```rust use dim_agent_runtime::PublicService; -use dim_agent_types::{ToolCall, ToolDefinition, ToolSourceVersion}; +use dim_agent_types::{ToolDefinition, ToolSourceVersion}; -/// The registry's adopted value for one request: its declarations, its fixed -/// tools and the source versions retained for the request. +/// One request's adopted generation: the registry's adoption and the +/// declarations it was adopted for. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct AdoptedTools { +pub struct Adopted { + pub adoption: String, pub tools: Vec, - pub sources: Vec, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -214,14 +214,6 @@ pub struct BindRequest { pub sources: Vec, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct ClaimRequest { - pub request_id: String, - pub calls: Vec, - pub context: ToolExecutionContext, -} - #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct TransferRequest { @@ -233,12 +225,10 @@ pub struct TransferRequest { pub enum BindingError { #[error("request {request_id} is already bound")] AlreadyBound { request_id: String }, + #[error("the tool declaration was refused: {reason}")] + Invalid { reason: String }, #[error("tool source {key}@{version} is unavailable")] - VersionUnavailable { key: String, version: String }, - #[error("tool {name} has no handler")] - NoHandler { name: String }, - #[error("request {request_id} has no tool record")] - NoRecord { request_id: String }, + Unavailable { key: String, version: String }, #[error("the branch is closing")] Closed, } @@ -248,8 +238,7 @@ impl PublicService for ToolBinding {} #[rutis::service(name = "toolBinding")] impl ToolBinding { pub async fn bind(&self, request: BindRequest) -> Result<(), BindingError> { /* ... */ } - pub fn adopted(&self, request_id: String) -> Result { /* ... */ } - pub async fn claim(&self, request: ClaimRequest) -> Result<(), BindingError> { /* ... */ } + pub fn adopted(&self, request_id: String) -> Result { /* ... */ } pub fn release(&self, request_id: String) { /* ... */ } pub fn transfer(&self, request: TransferRequest) -> Result<(), BindingError> { /* ... */ } pub fn retain_only(&self, request_id: String) { /* ... */ } diff --git a/docs/design/plugins/ToolExecutor.md b/docs/design/plugins/ToolExecutor.md index dcd06c08b2..3efb92cd8c 100644 --- a/docs/design/plugins/ToolExecutor.md +++ b/docs/design/plugins/ToolExecutor.md @@ -9,11 +9,11 @@ ToolExecutor owns one committed tool batch on a line: its cancellation, its inte ToolExecutor owns: - **The current batch.** One top-level batch at a time: its token, its interrupt state, the per-call admission and the ordered settlement of the calls. -- **Child calls.** A program's nested call is opened against the current batch, addressed by a gate id the owner issues; the owner writes the child's `step/tool-call`/`step/tool-result`, runs the same admission and execution path, and closes the gate and collects the child effects when the parent call settles. +- **Child calls.** A program's nested call is opened against the current batch, addressed by a gate id the owner issues; the owner writes the child's `step/tool-call`/`step/tool-result`, runs the same admission and execution path, and closes the gate and collects the child effects when the parent call settles. A program that ends early may close its gate and read the confirmed effects to word its result; the owner closes it again at the parent's settlement without effect. - **The facts.** `step/tool-start` and `step/tool-completed` when progress is enabled, `step/tool-result` with the correlated results, and the child facts with their parent call id. - **Reload and interrupt settlement.** An open batch settles as a reload settlement, or as not executed, when the generation reloads; an interrupt cancels the current batch. -ToolExecutor does not declare tools, decide admission, resolve write targets, execute a handler or hold a handler. Declarations and the adopted value belong to ToolBinding; admission belongs to Approval; write-target resolution, ordering class, claims and execution belong to ToolRegistry. +ToolExecutor does not declare tools, decide admission, resolve a write target's facts, execute a handler or hold a handler. The adoption and declarations belong to ToolBinding; admission belongs to Approval; write-target resolution (`resolve_write`), ordering class (`ordering`), claims and execution (`run`) belong to ToolRegistry. Callers keep as business: @@ -26,7 +26,7 @@ Callers keep as business: | Run a committed batch | No: the batch's order, admission, cancellation and terminal fact are one state machine | Loop writes `step/tool-call`; the owner consumes it (no caller operation) | | Open a child call against the current batch | No: a program's child must belong to the running parent call, and a caller-composed id could outlive or precede it | `open` | | Run a child call and receive its result | No: the child must take the same admission and execution path, write its own facts and settle before the parent | `invoke` | -| Collect the child effects before the parent result | No: only the owner knows which gates belong to the parent call and when they settled | the owner merges at parent settlement; no caller operation | +| Collect the child effects before the parent result | No: only the owner knows which gates belong to the parent call and when they settled | `close` returns the confirmed effects; the owner merges them again at parent settlement | | Read the request's declarations for the program | Yes: ToolBinding's `adopted` answers the declarations | Business composition | An operation exists only where its row says No. @@ -45,19 +45,21 @@ let result = executor.invoke(InvokeRequest { gate_id: gate.gate_id.clone(), call, }, cancelled.clone()).await?; // GateClosed, Closed; a tool failure is result.is_error +// The program ended: take the confirmed effects to word the result. +let effects = executor.close(CloseRequest { gate_id: gate.gate_id }).await?; // GateClosed, Closed ``` A program's declarations come from the pin owner, not the executor: ```rust -let adopted = binding.adopted(&execution.request_id).await?; // NoRecord +let adopted = binding.adopted(&execution.request_id).await?; // Invalid let declared: Vec = adopted.tools .into_iter() .filter(|tool| tool.name != CODEMODE_TOOL) .collect(); ``` -The owner closes the gate when the parent call settles; a program that returns early needs no close, and the effects of every child call it made are merged into the parent call's result in invocation order. +The owner closes the gate when the parent call settles; a program that returns early closes it early to read the effects, and the effects of every child call are merged into the parent call's result in invocation order either way. ## Own contract @@ -65,7 +67,7 @@ The owner closes the gate when the parent call settles; a program that returns e | Service | Purpose | | --- | --- | -| `S:ToolRegistry` (Session, [#2026](https://github.com/arcships/dim/issues/2026)) | Resolve a call's write target and ordering class, and execute an admitted call for the request's adopted value. | +| `S:ToolRegistry` (Session, [#2026](https://github.com/arcships/dim/issues/2026)) | `resolve_write` before admission, `ordering` for the batch's steps, and `run` for an admitted call. | | `B:Approval` | Admit each call, including the user's answer and the policy recheck. | | `B:Timeline`, `B:Dispatcher` | Commit progress and results; consume batches, interrupts and turn boundaries; report faults. | | `B:TimelineIdentity` | The calling line's identity in the execution context and the span. | @@ -77,27 +79,29 @@ The owner closes the gate when the parent call settles; a program that returns e | --- | --- | --- | --- | --- | --- | | `open` | Open a child-call gate for one outer call of the current batch | `{parentCallId, context}` | `{gateId}` | Before the gate id is issued; nothing was created | `closed`, `interrupted`, `no_batch` (no current batch, or the parent call does not belong to it) | | `invoke` | Run one child call through the same admission and execution path | `{gateId, call}` | `{result}` | The gate's parent token; the child is cancelled and its result says so | `closed`, `gate_closed` (the gate was closed by its parent's settlement or by an interrupt) | +| `close` | Close the gate now and answer the confirmed child effects | `{gateId}` | `{effects}` | None: the close settles | `closed`, `gate_closed` (the batch was interrupted or settled before the call) | -`gateId` is bound to the calling row and the parent call; a call from another row is `gate_closed`. A child call's refusal, cancellation, unknown tool or tool failure is a `ToolResult` with `is_error: true`, not an operation error: the program decides what to do with it. +`gateId` is bound to the calling row and the parent call; a call from another row is `gate_closed`. `close` is idempotent for the owner's own settlement: the parent's settlement closes the gate whether or not the program did, and the effects reach the parent result once. A child call's refusal, cancellation, unknown tool or tool failure is a `ToolResult` with `is_error: true`, not an operation error: the program decides what to do with it. ### Errors | Kind | Operation | What the caller does next | | --- | --- | --- | -| `closed` | `open`, `invoke` | The executor is closing or reloading; stop the program; its batch is settled. | +| `closed` | `open`, `invoke`, `close` | The executor is closing or reloading; stop the program; its batch is settled. | | `interrupted` | `open` | The turn was interrupted; stop the program. | | `no_batch` | `open` | The parent call is not part of the current batch; a caller bug: stop the program and report it. | -| `gate_closed` | `invoke` | The gate's parent call settled or the batch was interrupted; stop the program. | +| `gate_closed` | `invoke`, `close` | The gate's parent call settled or the batch was interrupted; stop the program; the parent result carries the effects already confirmed. | ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `open` | Check the current batch and the parent call, issue a gate id under the calling row, subscribe the gate to the parent token | Before the id is issued: nothing exists | The row's gates are closed with their child tasks | New calls are refused; every gate of the generation is closed | ToolExecutor | -| `invoke` | Write the child `step/tool-call` with the parent call id, prepare and admit the call, execute it, write the child `step/tool-result`, record its effects | The child is cancelled; its fact records the cancellation; the gate stays usable for the program's next call | The row's gates close; in-flight children end cancelled and are recorded | In-flight children end as reload settlements; the gate is closed | ToolExecutor for the facts and the gate; ToolRegistry for the handler and its claim; the calling row for the program future | +| `invoke` | Write the child `step/tool-call` with the parent call id, resolve the write target, admit the call, run it through the registry, write the child `step/tool-result`, record its effects | The child is cancelled; its fact records the cancellation; the gate stays usable for the program's next call | The row's gates close; in-flight children end cancelled and are recorded | In-flight children end as reload settlements; the gate is closed | ToolExecutor for the facts and the gate; ToolRegistry for the handler and its claim; the calling row for the program future | +| `close` | Mark the gate closed, refuse new children, wait for its running children within the owner's grace, answer the confirmed effects | The close waits; a child past the grace is outside the contract | The row's gates close with their children | A close in flight finishes; the parent settlement closes the gate again | ToolExecutor | | Parent settlement | After the parent call's result is known, close every gate of the parent, wait for its children within the owner's grace, and merge their effects into the result in invocation order | — | — | — | ToolExecutor | -The owner never hands out a gate: `gateId` names the gate only for `invoke`, and the owner closes it. A batch's calls settle in step order, each call's admission runs when the batch starts, and an interrupt cancels the current token: those rules stay as they are, and the caller sees only the results. +The owner never hands out a gate: `gateId` names the gate only for `invoke` and `close`, and the owner closes it. A batch's calls settle in step order, each call's admission runs when the batch starts, and an interrupt cancels the current token: those rules stay as they are, and the caller sees only the results. ## Exceptions with reasons @@ -108,7 +112,7 @@ The owner never hands out a gate: `gateId` names the gate only for `invoke`, and Flow tests on the owner: - A child call writes its own `step/tool-call`/`step/tool-result` with the parent call id; its effects appear in the parent result in invocation order; the outer result is written after its children settle. -- A program that returns early still has its child effects merged; a child that ignores cancellation past the owner's grace leaves a result the parent result does not wait for. +- A program that returns early still has its child effects merged; a `close` before the program ends answers the confirmed effects, and the same effects appear once in the parent result. - An interrupt cancels a running child and refuses a new gate; a reload settles an open child and an open parent, and a reload-settled result fails the turn. - `open` refuses a parent call that is not in the current batch and a second batch while one runs; `gate_closed` answers a call after the parent settled. - The same operations over the face and in process answer the same results and errors. @@ -131,7 +135,7 @@ Flow tests on the owner: | §4 rule 9 | Progress and results are facts later decisions use; the batch's completion is consumed by Loop and the client. | | §7 resources and objects | The gate is the owner's; only its id crosses, and the owner closes it. | | §7 no proxy | No forwarding of declarations; Code Mode reads ToolBinding. | -| §7 one surface | `open` and `invoke` are the operations; `definitions` and the gate object are removed. | +| §7 one surface | `open`, `invoke` and `close` are the operations; `definitions` and the gate object are removed. | | §7 cross-language | Both operations take and answer data; a program in another language uses the same ids. | | §7 responsibility split | The caller keeps the program's control flow and its reaction to results; the owner keeps order, admission, cancellation and facts. | | ADR 002 D1 | Branch scope. | @@ -142,7 +146,7 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -- **ToolRegistry ([#2026](https://github.com/arcships/dim/issues/2026)).** The owner needs `prepare({adopted, call}, cancelled) → {call, risk}` (resolve the write target and answer the ordering class and risk without side effects) and `execute({adopted, call, context}, cancelled) → {result}` (take the call's claim, run the handler and settle it). These are the registry's operations for the branch executor; the registry's contract states them. +- **ToolRegistry ([#2026](https://github.com/arcships/dim/issues/2026)).** The registry's contract ([#2103](https://github.com/arcships/dim/pull/2103)) defines `resolve_write({adoption, call})`, `ordering({adoption, call})` and `run({adoption, call, caller}, cancelled)`. The executor uses those three; the tool's own failure comes back as a `ToolResult`, not as an error kind. - **Approval (#2028).** `admit` is this board's own operation (see [Approval](Approval.md)). - **None other.** No Timeline, Dispatcher, loader or runtime change. @@ -175,6 +179,18 @@ pub struct InvokeRequest { pub call: ToolCall, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CloseRequest { + pub gate_id: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CloseReply { + pub effects: Vec, +} + #[derive(Debug, thiserror::Error)] pub enum ExecutorError { #[error("the tool executor is closing")] @@ -193,5 +209,6 @@ impl PublicService for ToolExecutor {} impl ToolExecutor { pub async fn open(&self, request: OpenRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn invoke(&self, request: InvokeRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn close(&self, request: CloseRequest) -> Result { /* ... */ } } ``` From 86e3c47fffe3be2ccb6258b67ed1d9287327f926 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Mon, 23 Nov 2026 15:26:50 +0800 Subject: [PATCH 04/11] docs(design): align permission's facts dependency with the Session owner fileAccessFacts.check takes {access, mode, path}; the service is resolved at the Session instance, so no Session id is a request field and Permission no longer needs SessionScope identity. --- docs/design/plugins/Permission.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/design/plugins/Permission.md b/docs/design/plugins/Permission.md index af8f8403fd..76421d79c1 100644 --- a/docs/design/plugins/Permission.md +++ b/docs/design/plugins/Permission.md @@ -73,9 +73,9 @@ let next = permission.update(UpdateRequest { | Service | Purpose | | --- | --- | -| `S:SessionScope` (Session, [#2093](https://github.com/arcships/dim/pull/2093)) | The creation record's permission preset and working directory, and the Session id for facts queries. | +| `S:SessionScope` (Session, [#2093](https://github.com/arcships/dim/pull/2093)) | The creation record's permission preset and working directory. | | `S:PermissionRules` (Session, [#2094](https://github.com/arcships/dim/pull/2094)) | `permissionRules.rules` answers the user's command rules at decision time. | -| `S:FileAccessFacts` (Session owner, [#2025](https://github.com/arcships/dim/issues/2025)) | Resolve the call's target and answer the workspace, system, owned and grant facts. | +| `S:FileAccessFacts` (Session owner, [#2025](https://github.com/arcships/dim/issues/2025)) | Resolve the call's target and answer the workspace, system, owned and grant facts; the caller resolves the service at the Session instance, so no Session id is a request field. | | `B:Timeline`, `B:Dispatcher` | Fold `permission/changed`; commit an update. | The file-access facts operation that resolves the target is not defined yet; it is stated in Requirements. @@ -156,8 +156,8 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -- **File access facts ([#2025](https://github.com/arcships/dim/issues/2025)).** The Session owner must publish one data operation, `check({sessionId, access, mode, path}, cancelled) → {target, workspace, system, owned, grant, discoveryError?}`, that resolves the call's path (`~`, cwd, `..`, links) and answers the facts under the effective access. Permission currently reads the owner's Rust object and a host `home` value; both disappear with this operation. -- **SessionScope ([#2093](https://github.com/arcships/dim/pull/2093)).** `config` and `identity` are the target's operations; Permission's creation-record reads use them. +- **File access facts ([#2025](https://github.com/arcships/dim/issues/2025)).** The Session owner publishes `check({access, mode, path}, cancelled) → {target, workspace, system, owned, grant, discoveryError?}` ([#2093](https://github.com/arcships/dim/pull/2093)), which resolves the call's path (`~`, cwd, `..`, links) and answers the facts under the effective access; `mode` is the grant mode the call asks for. Permission resolves the facts service at the Session instance; the Session id is not a request field. Errors are `invalid`, `unavailable`, `cancelled` and `closed`; a `discoveryError` is a field, not an error. Permission currently reads the owner's Rust object and a host `home` value; both disappear with this operation. +- **SessionScope ([#2093](https://github.com/arcships/dim/pull/2093)).** `config` is the target's operation; Permission's creation-record read (the preset seed and the working directory) uses it. `identity` is no longer needed: the facts service is Session-bound. - **Permission rules ([#2017](https://github.com/arcships/dim/issues/2017)).** `permissionRules.rules` ([#2094](https://github.com/arcships/dim/pull/2094)) is the command-rules operation Permission reads; the `commandRules` name is removed. - **None other.** No Timeline, Dispatcher, loader or runtime change. From 5cbdc43297d6f5d1c10ba975c02c6ca1250ec9f9 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Mon, 23 Nov 2026 15:32:06 +0800 Subject: [PATCH 05/11] docs(design): drop the Session id from permission's facts dependency fileAccessFacts.check takes {access, mode, path}; the service is resolved at the Session instance. --- docs/design/plugins/Permission.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design/plugins/Permission.md b/docs/design/plugins/Permission.md index 76421d79c1..be93e3955b 100644 --- a/docs/design/plugins/Permission.md +++ b/docs/design/plugins/Permission.md @@ -75,7 +75,7 @@ let next = permission.update(UpdateRequest { | --- | --- | | `S:SessionScope` (Session, [#2093](https://github.com/arcships/dim/pull/2093)) | The creation record's permission preset and working directory. | | `S:PermissionRules` (Session, [#2094](https://github.com/arcships/dim/pull/2094)) | `permissionRules.rules` answers the user's command rules at decision time. | -| `S:FileAccessFacts` (Session owner, [#2025](https://github.com/arcships/dim/issues/2025)) | Resolve the call's target and answer the workspace, system, owned and grant facts; the caller resolves the service at the Session instance, so no Session id is a request field. | +| `S:FileAccessFacts` (Session owner, [#2025](https://github.com/arcships/dim/issues/2025)) | `check({access, mode, path})` resolves the call's target and answers the workspace, system, owned and grant facts. | | `B:Timeline`, `B:Dispatcher` | Fold `permission/changed`; commit an update. | The file-access facts operation that resolves the target is not defined yet; it is stated in Requirements. From 40512f3314431a2d508179f8314f915ca65b4b63 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Mon, 23 Nov 2026 19:36:31 +0800 Subject: [PATCH 06/11] docs(design): make ToolBinding the branch's request-record interface The registry keeps the Session's resolvable generations; ToolBinding keeps a line's request record, its pins and its claims. bind/claim call the registry, transfer moves the record, and the owner settles the record and its claims from step/tool-result and turn/end instead of Loop releasing on every path. --- docs/design/plugins/ToolBinding.md | 100 ++++++++++++++++++----------- 1 file changed, 64 insertions(+), 36 deletions(-) diff --git a/docs/design/plugins/ToolBinding.md b/docs/design/plugins/ToolBinding.md index bd2dae9113..bd276ae456 100644 --- a/docs/design/plugins/ToolBinding.md +++ b/docs/design/plugins/ToolBinding.md @@ -2,32 +2,35 @@ Scope: branch. Issue: #2028. -ToolBinding owns the branch's record of each request's adopted tool generation: the declarations the request's prefix declared, the registry adoption that keeps their versions resolvable, and the pins that keep a later prefix's generation alive. This document is the owner's target contract; the current implementation is described in the [ToolExecution plugin page](../../architecture/rust-agent/plugins/ToolExecution.md#toolbinding). +ToolBinding owns the branch's record of each request's adopted tool generation: the registry adoption the request declared, the declarations it was adopted for, the pins that keep a later prefix's generation alive, and the claims of the request's published calls. This document is the owner's target contract; the current implementation is described in the [ToolExecution plugin page](../../architecture/rust-agent/plugins/ToolExecution.md#toolbinding). ## Use and scope: responsibility split ToolBinding owns: -- **The request record.** One adopted generation per request id: the registry's adoption id and the declarations it was adopted for. A request id is bound once; a budget-recovery request takes over the record of the request it retries. -- **Pins.** The records whose prefix a later request may still declare, and their release. A pin is a value; ToolBinding asks the registry to release an adoption when no later prefix can name it. -- **The adopted value the executor runs and the program reads.** The adoption id and the declarations, read from the request record. +- **The request record.** One adopted generation per request id: the registry's adoption id, the declarations it was adopted for, and the turn the request belongs to. A request id is bound once; a budget-recovery request takes over the record of the request it retries. +- **Pins.** The records whose prefix a later request may still declare, and their release. A pin is a value; the owner releases an adoption when no later prefix can name it. +- **The claims of a request's published calls.** Before the batch fact is appended, ToolBinding asks the registry to register each call's claim; it releases the request's claims when the request's batch result is committed, when the turn ends, or when the generation closes. +- **Settlement.** The record and its claims are settled by the owner from the line's facts: `step/tool-result` for the request's batch, `turn/end` for the turn's requests, and the generation's close. No caller releases on an end path. -ToolBinding does not execute tools, decide admission, hold a handler, or register a call's claim. The registry's `adopt` resolves the declarations and retains their versions; the registry's `claim`/`release_claims` register and drop a request's pre-publish claims for Loop; execution, write-target resolution and ordering class belong to the registry's `run`, `resolve_write` and `ordering`. The adopted configuration fact (`context/configured`'s tool part) belongs to Prompt. +ToolBinding does not execute tools, decide admission, hold a handler or a claim guard. The registry's `adopt`/`release`, `claim`/`release_claims` are the Session-side capability ToolBinding requests; execution, write-target resolution and ordering class belong to the registry's `run`, `resolve_write` and `ordering`. The adopted configuration fact (`context/configured`'s tool part) belongs to Prompt. + +**Why the registry and this owner stay separate.** The registry owns the Session's *resolvable generations*: the handlers and the version sets, shared by every line, with freshness from the registry's registrations; an adoption keeps its versions resolvable until released, and its id is bound to the adopting row. ToolBinding owns one line's *request record*: which adoption one request declared, and the claims of its calls, with freshness from that line's Timeline facts; the record ends at the request's terminal fact and the pin ends when a later prefix cannot name it. Merging would put a line's request state in the Session owner (forbidden by [ADR 002 D1](../../adr/002-plugin-scope.md)) or the contributors' handlers in the branch (the contributor's row owns them). The branch-facing interface is therefore ToolBinding's alone: Loop drives `bind`, `claim` and `transfer`, never the registry. Callers keep as business: - Which declarations a request's prefix carries, and where the declaration comes from: the prefix's adopted configuration, the registry's current set, or a host's selection over the registry's declarations. - When a request is prepared, retried or abandoned; whether a turn is failed; how a model request's declarations are shaped. -- The tool-call batch and the claims of its calls: Loop calls `claim` before the batch fact and `release_claims` on the paths that never dispatch. +- The tool-call batch: which calls a request publishes and when. | Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | | Bind a request to the adopted generation its prefix declared | No: the adoption must be released on every path that ends the request, and a caller that held the adoption id would have to release it itself on each error path | `bind` | | Read the adoption and declarations to run a call | No: the record is the owner's state; the registry's `run` takes the adoption id | `adopted` | | Read a request's declarations for a program that may only see them (Code Mode) | Yes: `adopted` answers the same record; the program takes the declaration part | Business composition | -| Release a request that will not execute again | No: only the caller knows the turn's decision; the record owner performs the release | `release` | +| Register a published call's claim before the batch fact | No: the claim must exist before the fact and be released on every path that never dispatches | `claim` | | Keep the same adopted generation across a budget-recovery retry | No: the record moves to the new request id; composing it would copy and release records | `transfer` | -| Keep only the current request after a rebuild | No: a rebuild must drop every stale record in one step | `retain_only` | +| Release a record when the request is done | No: the terminal fact is the line's, and the owner settles it without a caller call | owner settlement; no operation | An operation exists only where its row says No. @@ -40,6 +43,7 @@ Loop prepares a request from the prefix's adopted configuration and publishes a match configuration.tools { Some(tools) => binding.bind(BindRequest { request_id: request.id.clone(), + turn_id: turn.id.clone(), through, declared: tools.clone(), sources: configuration.tool_sources.clone(), @@ -49,6 +53,7 @@ match configuration.tools { let current = registry.declarations().await?; binding.bind(BindRequest { request_id: request.id.clone(), + turn_id: turn.id.clone(), through, declared: current.tools, sources: current.sources, @@ -56,7 +61,13 @@ match configuration.tools { } } // Before the batch fact, so a published question can already be answered. -registry.claim(ClaimCalls { request: request.id.clone(), calls: request.calls.clone() }).await?; +binding.claim(ClaimRequest { + request_id: request.id.clone(), + calls: request.calls.clone(), + context: execution.clone(), +}).await?; +// No release call: the owner settles the record and its claims when `step/tool-result` +// for this request, or `turn/end`, is dispatched. ``` A host that selects tools over the registry's declarations composes the same steps; the declarations it reads are the ones it binds: @@ -66,12 +77,19 @@ let available = registry.declarations().await?; let settings = host.prepare(turn_id, request_id, &history, &available.tools)?; binding.bind(BindRequest { request_id: request.id.clone(), + turn_id: turn.id.clone(), through, declared: settings.tools.clone().unwrap_or_default(), sources: available.sources, }).await?; ``` +A budget-recovery retry keeps the generation the first attempt declared: + +```rust +binding.transfer(TransferRequest { from: old_request_id, to: new_request_id }).await?; // Invalid +``` + ToolExecutor reads the adoption once per call and hands it to the registry, which resolves the version's handler: ```rust @@ -99,22 +117,23 @@ let declared: Vec = binding.adopted(&execution.request_id).await | Service | Purpose | | --- | --- | -| `S:ToolRegistry` (Session, [#2026](https://github.com/arcships/dim/issues/2026)) | Adopt a declared generation, retaining its versions, and release it when the record ends. | +| `S:ToolRegistry` (Session, [#2026](https://github.com/arcships/dim/issues/2026)) | Adopt a declared generation and retain its versions; register a request's claims; release an adoption, a request's claims and a request's retention. | | `B:Prompt` (branch, [#2027](https://github.com/arcships/dim/issues/2027)) | Adopt the tool part of the branch's model configuration when the registry's set changes. | -| `B:Timeline`, `B:Dispatcher` | Reconcile the prefix's last configuration at branch opening and after a reload. | +| `B:Timeline`, `B:Dispatcher` | Reconcile the prefix's last configuration at branch opening; consume `step/tool-result` and `turn/end` for settlement; write nothing. | | `B:BranchLifecycle` | Gate the registry-change watcher on activation and closing. | +The registry's `adopt`, `release`, `claim` and `release_claims` are called only by ToolBinding; Loop never calls the registry. + ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `bind` | Fix a request to one adopted generation | `{requestId, through, declared, sources}` | `{}` | None; the owner completes the adoption and the record | `already_bound`, `invalid` (the registry refused the declarations), `unavailable` (a source version is gone), `closed` | +| `bind` | Fix a request to one adopted generation | `{requestId, turnId, through, declared, sources}` | `{}` | None; the owner completes the adoption and the record | `already_bound`, `invalid` (the registry refused the declarations), `unavailable` (a source version is gone), `closed` | | `adopted` | The record's adoption id and declarations | `{requestId}` | `{adoption, tools}` | None | `invalid` (no record), `closed` | -| `release` | Drop a request's record and its adoption | `{requestId}` | `{}` | None | `closed` | +| `claim` | Register the calls' claims before their batch fact | `{requestId, calls, context}` | `{}` | None | `invalid` (no record), `closed` | | `transfer` | Move a record to the request that retries it | `{from, to}` | `{}` | None | `invalid` (no record), `closed` | -| `retain_only` | Keep one request's record and drop every other | `{requestId}` | `{}` | None | `closed` | -`declared` is the request's full declaration list; `sources` is the prefix's `tool_sources` as version ids. `through` is the prefix cutoff the record's pin is released against. `adoption` is the registry's id from `adopt`; the registry retains the version set until `release`. +`declared` is the request's full declaration list; `sources` is the prefix's `tool_sources` as version ids; `through` is the prefix cutoff the pin is released against; `turnId` is the turn the request belongs to and the key `turn/end` settles. `adoption` is the registry's id from `adopt`; the registry retains the version set until `release`. ### Errors @@ -123,7 +142,7 @@ let declared: Vec = binding.adopted(&execution.request_id).await | `already_bound` | `bind` | A caller bug: the request id was bound twice. Fail the turn as a fault. | | `invalid` | `bind` | The registry refused the declarations (a name has no handler, or its definition changed); fail the turn and report the declaration. | | `unavailable` | `bind` | The prefix declares a source version the registry no longer retains; fail the turn, or re-prepare from the current declarations when the turn's policy allows a retry. | -| `invalid` | `adopted`, `transfer` | The request has no record: a caller bug or a request released before its batch. Fail the turn as a fault. | +| `invalid` | `adopted`, `claim`, `transfer` | The request has no record: a caller bug or a request released before its batch. Fail the turn as a fault. | | `closed` | any | The branch is closing or unloading; the turn ends. | `bind` errors carry the declaration that failed (`name`) or the source that is gone (`key`, `version`); the owner reports no failure the record cannot have. @@ -132,17 +151,18 @@ let declared: Vec = binding.adopted(&execution.request_id).await | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `bind` | Ask the registry to adopt the declarations, insert the record, release the adoptions of pins no later prefix declares | None: the call is synchronous and bounded | Nothing to release; the record stays until `release` or the owner closes | A record in flight is refused with `closed`; an adoption the registry granted is released by the registry at the row's unload | ToolBinding and ToolRegistry | +| `bind` | Ask the registry to adopt the declarations, insert the record, release the adoptions of pins no later prefix declares | None: the call is synchronous and bounded | Nothing to release; the record is settled at the request's terminal fact or the close | A record in flight is refused with `closed`; the registry releases an adoption it granted at the row's unload | ToolBinding and ToolRegistry | | `adopted` | Read the record and answer its adoption and declarations | None | Nothing to release | Refused with `closed`; a reload rebuilds the record from the prefix's configuration | ToolBinding | -| `release` | Drop the record and ask the registry to release its adoption | None | Nothing to release | The owner performs the same release on close | ToolBinding and ToolRegistry | +| `claim` | Ask the registry to register a guard per call; the record notes that the request has claims | None | The close releases the request's claims | Every claim of the generation is released | ToolBinding and ToolRegistry | | `transfer` | Move the record to the new request id | None | Nothing to release | Refused with `closed` once the generation closes | ToolBinding | -| `retain_only` | Release every other record, in one pass | None | Nothing to release | The owner performs the same release on close | ToolBinding and ToolRegistry | +| Settlement | On the dispatched `step/tool-result` of the request: drop the record and ask the registry to release the request's claims; on `turn/end` of its turn: the same for every record of the turn; on close: every record and claim | — | — | The owner performs the same release on close | ToolBinding and ToolRegistry | -A record is released before the branch accepts closing work. A reload rebuilds the record from the prefix's last adopted configuration, exactly as a fresh branch would; a request that was in flight when the owner reloaded has no record, and its executor ends the batch as a reload settlement, not as an `invalid` error. +A record is settled before the branch accepts closing work. A reload rebuilds the record from the prefix's last adopted configuration, exactly as a fresh branch would; a request that was in flight when the owner reloaded has no record, and its executor ends the batch as a reload settlement, not as an `invalid` error. ## Exceptions with reasons -- Pins are values, not handles: a pin is a record whose adoption a later prefix may still name, and the registry keeps those versions resolvable until the record releases the adoption. ToolBinding holds no handler and no guard. +- Pins are values, not handles: a pin is a record whose adoption a later prefix may still name, and the registry keeps those versions resolvable until the owner releases the adoption at the next bind or the close. ToolBinding holds no handler and no guard. +- The record's settlement reads the line's facts (`step/tool-result`, `turn/end`) instead of a caller's release call: only the owner of the record can guarantee every end path, and the facts are public. ## Verification @@ -150,7 +170,7 @@ Flow tests on the owner: - A request binds to the prefix's declaration; a tool registered after the bind does not appear in `adopted` or in the executor's run; a later request adopts the new registry set and the earlier pin's adoption is released. - A request whose declaration names a version the registry no longer retains fails `unavailable` and binds nothing. -- A request's claims exist before the batch fact and are released on every path that never dispatches (append refused, interrupt before dispatch, admission refused, a Loop error); a dispatched call's guard is consumed by the registry's run. The claims are the registry's `claim`/`release_claims`, driven by Loop. +- A claim exists before the batch fact; the request's batch result, a turn end and a close each release the claims the request did not dispatch; a dispatched call's guard is consumed by the registry's run; Loop calls no release on any path. - Budget recovery transfers the record, and the retried request runs the version its first attempt declared. - After a reload, the branch rebinds its prefix's configuration before the first request; an in-flight batch ends as a reload settlement. - Cross-language: the same operations run over the face and in process, with the same replies and errors. @@ -159,10 +179,10 @@ Flow tests on the owner: | Rule | Application | | --- | --- | -| §1 parts and Capabilities | ToolBinding is one branch part and a Capability: it injects `dispatcher` and `timeline` and folds the branch's opening. | -| §2 scopes | Branch. The record and pins are the branch's; the registry's adoption and retained versions are Session state the branch requests by id. | -| §3 orthogonality | ToolBinding reads the registry's public adopt/release operations and Prompt's configure operation; no other owner's state is read. | -| §4 rule 1 | The round's decisions (bind, release, transfer) are commands to this owner; the observable facts stay with Prompt (`context/configured`) and the tools' results. | +| §1 parts and Capabilities | ToolBinding is one branch part and a Capability: it injects `dispatcher` and `timeline` and folds the branch's opening and its settlement facts. | +| §2 scopes | Branch. The record, pins and claims are the branch's; the registry's adoption and retained versions are Session state the branch requests by id. | +| §3 orthogonality | ToolBinding reads the registry's public adopt/release/claim operations and Prompt's configure operation; no other owner's state is read. | +| §4 rule 1 | Binding, settling and transferring are commands to this owner; the observable facts stay with Prompt (`context/configured`) and the tools' results. | | §4 rule 2 | No handoff: the request record is the owner's state. | | §4 rule 3 | No before callback. | | §4 rule 4 | No business meaning in core or assembly. | @@ -170,21 +190,21 @@ Flow tests on the owner: | §4 rule 6 | Declarations reach the model only through the adopted configuration; the record reads the same values. | | §4 rule 7 | Callers use the operations; no caller reads the record's internals. | | §4 rule 8 | No infrastructure change. | -| §4 rule 9 | No Timeline fact of its own; the adopted configuration stays Prompt's fact. | +| §4 rule 9 | No Timeline fact of its own; the adopted configuration stays Prompt's fact, and settlement reads public facts. | | §7 resources and objects | The record, pins and adoption ids are values; no handler or guard crosses. | -| §7 no proxy | ToolBinding returns its own record; execution and claims are ToolRegistry's operations. | -| §7 one surface | The operations are on the owner type; `handler`, `take_claim`, `definitions`, `claim`, `prepare` and `bind_current` are removed. | +| §7 no proxy | ToolBinding returns its own record; execution and claims are ToolRegistry's operations, requested by this owner. | +| §7 one surface | The branch-facing operations are `bind`, `adopted`, `claim` and `transfer`; `handler`, `take_claim`, `definitions`, `release`, `retain_only`, `prepare` and `bind_current` are removed. | | §7 cross-language | Every parameter and reply is data; the face and the Rust call use the same operations. | -| §7 responsibility split | The caller keeps the declaration source, the turn's decisions and the claims; the owner keeps the record, its adoption and its pins. | -| ADR 002 D1 | Branch scope: a request's tool generation is one behavior line's state. | -| ADR 002 D2 | No wiring part; the service is on the owner. | +| §7 responsibility split | The caller keeps the declaration source, the turn's decisions and the batch; the owner keeps the record, its pins, its claims and their settlement. | +| ADR 002 D1 | Branch scope for the request record; the registry's generations are Session state. | +| ADR 002 D2 | No wiring part; the two owners are split by scope, not by forwarding, and the branch-facing interface is this owner's. | | ADR 002 D3 | The registry is a Session capability the branch depends on; the registry depends on no branch. | | ADR 002 D4 | No configuration of its own; the adopted configuration is Prompt's fact. | | ADR 002 D5 | Language-neutral operations and data. | ## Requirements raised to mechanism owners -- **ToolRegistry ([#2026](https://github.com/arcships/dim/issues/2026)).** The registry's contract ([#2103](https://github.com/arcships/dim/pull/2103)) defines `adopt`, `release`, `run`, `resolve_write`, `ordering`, `claim`, `release_claims` and `declarations`. ToolBinding uses `adopt` and `release` only; Loop uses `claim` and `release_claims`; ToolExecutor uses `run`, `resolve_write` and `ordering`. The registry's row-bound unload release is what makes the record's adoption safe to hold as a value. +- **ToolRegistry ([#2026](https://github.com/arcships/dim/issues/2026)).** The registry's contract ([#2103](https://github.com/arcships/dim/pull/2103)) defines `adopt`, `release`, `claim`, `release_claims`, `run`, `resolve_write`, `ordering` and `declarations`. This owner calls `adopt`, `release`, `claim` and `release_claims`; `run`, `resolve_write` and `ordering` are ToolExecutor's. Loop calls this owner only. The split is the one stated under Use and scope: the registry keeps the Session's resolvable generations; this owner keeps the line's request record and claims. - **Prompt ([#2027](https://github.com/arcships/dim/issues/2027)).** The owner needs Prompt's `configure({tools})` operation ([PromptAdoption](https://github.com/arcships/dim/pull/2102)), because ToolBinding writes no configuration fact; a tool-only adoption without an adopted model is Prompt's `invalid_model`. - **None other.** No Timeline, Dispatcher, loader or runtime change. @@ -194,7 +214,7 @@ The service is marked on the owner type; the name stays `toolBinding`. Every ope ```rust use dim_agent_runtime::PublicService; -use dim_agent_types::{ToolDefinition, ToolSourceVersion}; +use dim_agent_types::{ToolCall, ToolDefinition, ToolSourceVersion}; /// One request's adopted generation: the registry's adoption and the /// declarations it was adopted for. @@ -209,11 +229,20 @@ pub struct Adopted { #[serde(rename_all = "camelCase")] pub struct BindRequest { pub request_id: String, + pub turn_id: String, pub through: u64, pub declared: Vec, pub sources: Vec, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClaimRequest { + pub request_id: String, + pub calls: Vec, + pub context: ToolExecutionContext, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct TransferRequest { @@ -239,8 +268,7 @@ impl PublicService for ToolBinding {} impl ToolBinding { pub async fn bind(&self, request: BindRequest) -> Result<(), BindingError> { /* ... */ } pub fn adopted(&self, request_id: String) -> Result { /* ... */ } - pub fn release(&self, request_id: String) { /* ... */ } + pub async fn claim(&self, request: ClaimRequest) -> Result<(), BindingError> { /* ... */ } pub fn transfer(&self, request: TransferRequest) -> Result<(), BindingError> { /* ... */ } - pub fn retain_only(&self, request_id: String) { /* ... */ } } ``` From e5db2cd1b1f8849b340d38f70ce2bc9ddb5ff21b Mon Sep 17 00:00:00 2001 From: eric8810 Date: Mon, 23 Nov 2026 21:33:53 +0800 Subject: [PATCH 07/11] docs(design): self-check the tool chain contracts against the round-3 rules Binding appendices: error enums serialize with snake_case codes matching the tables, caller: &Ctx on the row-bound operations, the advice callback is a direct parameter over defined request and answer types, and the examples match the signatures. Consistency: cancelled is defined per operation, BackgroundExec states one writer per command fact, and the README By scope lists the six branch parts. Supersedes sections and the existing documents' owner paragraphs replace the old shapes; line access follows ADR 027. --- docs/design/background-task-output.md | 7 +-- .../contracts/runtime-owner-operations.md | 10 ++-- docs/design/contracts/session-boundary.md | 2 +- docs/design/plugins/Approval.md | 11 ++++- docs/design/plugins/BackgroundExec.md | 26 ++++++---- docs/design/plugins/FileReads.md | 13 +++-- docs/design/plugins/Permission.md | 48 ++++++++++++------- docs/design/plugins/README.md | 2 +- docs/design/plugins/ToolBinding.md | 13 ++++- docs/design/plugins/ToolExecutor.md | 41 ++++++++++------ docs/design/service-faces.md | 20 ++++---- 11 files changed, 127 insertions(+), 66 deletions(-) diff --git a/docs/design/background-task-output.md b/docs/design/background-task-output.md index a4af157573..63077d4820 100644 --- a/docs/design/background-task-output.md +++ b/docs/design/background-task-output.md @@ -70,9 +70,10 @@ contain `session.exec.stop`; the sibling `session.exec.output` does not. WorkspaceTools registers the leaf; Rpc's built-in list and namespace checks are unchanged. -Each call resolves the named branch through WorkspaceTools' existing -`TreeCommands`, then asks that branch's BackgroundExec for the active task's -capture. No Session part retains branch business state. +Each call resolves the line with `line_owner::(line)` +([ADR 027](https://github.com/arcships/dim/pull/2029)), then asks that line's +BackgroundExec for the task's output artifact. No Session part retains branch +business state. **Task identity.** Every request resolves `taskId` inside the branch it names: `sessionId` admits the Session, `branchId` selects that Session's branch, and diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 3d36fd9d6d..dea9bd74de 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -23,7 +23,7 @@ | History RPC and line-read tools → timelineTree | `batchEnd(id, sequence) → void`, `pageEnd(id, after, limit, through) → sequence`, and `page` at the same cutoff. Preserve complete batches and the fixed head of ended lines. | | Context RPC → target branch | `agentLoop.compact` and `contextUsage.read`. | | Goal and Shell admission → timelineTree | `directory({id})` returns the matching directory entry or the unknown-branch error using a single-branch lookup. Goal reads ended history through `query`; writes retain the ended/unknown errors. | -| InputQueue and Collaboration approvals → target branch | `timelineTree.input`, `inputQueue.withdraw` after submission checks, and `approval.pending/decide` on the selected branch. | +| InputQueue and Collaboration approvals → target branch | `timelineTree.input`, `inputQueue.withdraw` after submission checks, and `approval.pending/decide` on the selected branch([Approval](../plugins/Approval.md)); the caller reaches the line's owner by line id ([ADR 027](https://github.com/arcships/dim/pull/2029)). | | PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `contextUsage.read`, `prompt.adoptedConfiguration({}) → adopted configuration or null`. Report also uses `timelineTree.query` at the selected head for evidence. | | Prompt and ToolBinding → `branchLifecycle` | `registerOpening(completion) → void`. Opening waits for admitted completions under its existing deadline and propagates their errors. | | Fault producers and Session observers → `sessionLifecycle` | `reportFault(error) → void`, `failure({}) → SessionFault or null`, `observeFault(listener) → id`, `release(id) → boolean`. The listener receives the current failure (initially null) and subsequent reports. Caller unload releases the observation. The first fault wins until a storage failure supersedes it; the first storage failure wins. | @@ -45,7 +45,7 @@ own methods. | --- | --- | | Context RPC / PromptSuggestion | `contextUsage.read`. The `compactAndWait` variant runs the existing compact RPC handler: it calls `agentLoop.compact` and waits for the compaction fact matching that command sequence and returns the existing completed/skipped/failed reply. The committed sequence watch and bounded query run inside the selected branch for that wait. | | Session language / Agent configuration / Report | `prompt.configure` or `prompt.adoptedConfiguration` with the existing source, model and outcome records. | -| InputQueue management / Collaboration | `inputQueue.withdraw` with the existing command; the caller runs the existing submit checks for steer before writing. `approval.pending` returns the branch's existing pending requests, and `approval.decide` settles the selected request. Collaboration retains its ended response on closed/ended/unknown detail lookup. | +| InputQueue management / Collaboration | `inputQueue.withdraw` with the existing command; the caller runs the existing submit checks for steer before writing. `approval.pending` returns the line's existing pending requests, and `approval.decide` settles the selected request([Approval](../plugins/Approval.md)). Collaboration retains its ended response on closed/ended/unknown detail lookup. | For a live main branch, Report captures its published head once at draft capture (`directory({id:"main"}).head`) and stores it as `conversationThrough` on that draft. Activity evidence and later opt-in @@ -60,7 +60,7 @@ substitutes a newer head. | --- | --- | | ToolBinding, Session language and Agent configuration → `prompt` | `prompt.initialCompletion({}) → void or opening error`; `prompt.configure({sources, model?}) → unchanged, adopted or superseded`. | | Prompt and guide adoption → `contextPreparation` | `contextPreparation.publish({adopted, changes, model?, toolAdoption?, inputs}) → sequence or null`; `awaitPublished({sequence}) → sequence`. Publication commits adoption atomically. | -| File read/edit/write tools → branch FileReads | `binding({path}) → TextFileBinding or null`, `writeBinding({path}) → absent, compacted or bound`, `record({path, binding, established}) → void`. The original read supplies the established sequence; file I/O stays on the file node. | +| File read/edit/write tools → branch FileReads | `binding({path, purpose}) → {binding?} or {unavailable: neverRead\|compacted}`, `record({path, binding, established}) → void`([FileReads](../plugins/FileReads.md)). The original read supplies the established sequence; file I/O stays on the file node. | ### Model preparation, history and tools @@ -73,5 +73,5 @@ substitutes a newer head. | Loop and ContextPreparation → HistoryRenderer | `context({branchId, through}) → ContextHistory`, `renderedContext({branchId, through}) → {context, history: HistoryEntry[]}`, `snapshot({context, retainFrom, anchor}) → RecoverySnapshot`, `streamCheckpoint({branchId, through, retainFrom, batch}) → ProjectionCheckpoint`. | | Loop and ModelProvider → ContextPreparation | `prepare({source: ContextPrepareData, projection?}, cancelled) → ModelRequest`, `validate({requestId, request}, cancelled) → void`. Reuse the prepared projection at the original cutoff. | | ContextPreparation and usage readers → ContextUsage | `read({through?}, cancelled) → {through, contextWindow, outputTokens, thresholdTokens, estimatedInputTokens, baselineSource}`. | -| Loop, ToolExecutor and Code Mode definition readers → `toolBinding` | `bind({requestId, through, tools, toolSources}) → void`, `bindCurrent({requestId, declared?}) → ToolDefinition[]`, `definitions({requestId}) → ToolDefinition[]`, `transfer({from, to}) → void`, `release({requestId}) → void`. ToolBinding retains the pinned handler generation. | -| Nested tool execution → `toolExecutor` | `open({parentCallId, context}, cancelled) → gateId`, `invoke({gateId, call}) → ToolResult`, `close({gateId}) → ToolEffect[]`. Close joins children in order; interruption releases the gate. | +| Loop, ToolExecutor and Code Mode readers → `toolBinding` | `bind({requestId, turnId, through, declared, sources}) → void`, `adopted({requestId}) → {adoption, tools}`, `claim({requestId, calls, context}) → void`, `transfer({from, to}) → void`([ToolBinding](../plugins/ToolBinding.md)). The record is settled from the line's `step/tool-result` and `turn/end`. | +| Nested tool execution → `toolExecutor` | `open({parentCallId, context}, cancelled) → gateId`, `invoke({gateId, call}, cancelled) → ToolResult`, `close({gateId}) → {effects}`([ToolExecutor](../plugins/ToolExecutor.md)). The owner closes the gate at the parent's settlement; interruption releases it. | diff --git a/docs/design/contracts/session-boundary.md b/docs/design/contracts/session-boundary.md index 0bbd6f4f3c..3604d9d178 100644 --- a/docs/design/contracts/session-boundary.md +++ b/docs/design/contracts/session-boundary.md @@ -388,7 +388,7 @@ No protocol version is added and persistence formats are unchanged. A Session part contributes a tool by registering it with the Session's `toolRegistry`, from any language. The registration belongs to the part that made it and is withdrawn when that part unloads (ADR 002 D3, D5). ToolRegistry does not depend on the parts that register; they depend on it, so when ToolRegistry reloads, the parts registered with it reload and register again. `SessionConfig.tools` is the Session's optional mount list, fixed at creation ([session-access A.3](session-access.md#a3-sessionconfig-fields)). Without one, the Session declares every host tool in the host's order and every registered tool by name, so a plugin's tools are usable once its part registers them, with no configuration edit (#364); with one, it declares the host and registered tools the list names, in its order, and `[]` declares none of them. Other sources' tools follow in both cases and are governed by their sources' own configuration, not by the mount list. Each mounted registered tool is a registry-owned versioned set keyed `#contributed:` (#241): it is declared while a part has it registered, withdrawn with the registration, and declared under a new version when a part registers it again. A version is a new UUID, never reused even across registry instances and processes, so a version persisted in `tool_sources` names one generation. Every read takes in what is registered then; once the Session is published, the registry's own task also rereads after every registration and withdrawal, until the Session starts closing. A tool the mount list names that no part has registered is not declared and is reported in diagnostics, and the Session still starts; the tool is declared from the next request after a part registers it, without a Session reload. Required dependency waiting rules are unchanged; an optional part registered when the Session opens settles before publication, and one that is Pending or Failed never fails Session readiness (#132, #207, ADR 006 D3). -ToolBinding reconciles the table through the existing Prompt / BranchLifecycle flow before the Session accepts input. A branch with adopted model configuration uses `Prompt::adopt_tools` when its tool part differs. For a request without adopted configuration, ToolBinding captures a registry snapshot before PrepareModelHost selects from the supplied definitions, then binds the selection against the same retained handlers. With adopted configuration but no tool part, `bind_current` declares and binds the registry's current tools on each request. Registration changes need no adoption in either request path. No new core readiness phase is needed. Source changes, including registered tools in a configuration with a tool part, go through the existing registry notification and Prompt adoption path (`context/configured` with `tool_sources`), and requests retain the handlers selected for their own prefix. A tool name follows `[A-Za-z0-9_-]{1,64}`; a name that is registered already or is a host tool's is refused. The mount list decides what is declared, and only duplicate names in it fail the Session ([tool contributions](../../architecture/rust-agent/tool-contributions.md)). Permission decides whether a declared tool's call runs: its preset and `allowedTools`/`disallowedTools` change live through `session.permission.update` and never change the declarations, which are part of the prompt prefix. To block a tool and keep the context stable, keep it mounted and deny it in Permission; to change what the model sees, create the Session with a different mount list. +ToolBinding's target contract is [ToolBinding](../plugins/ToolBinding.md): a request's record binds to the registry's adoption, claims its calls before the batch fact, and is settled by the owner from the branch's `step/tool-result` and `turn/end`; the adopted configuration fact stays Prompt's (`context/configured` with `tool_sources`). No new core readiness phase is needed. Source changes, including registered tools in a configuration with a tool part, go through the existing registry notification and Prompt adoption path. A tool name follows `[A-Za-z0-9_-]{1,64}`; a name that is registered already or is a host tool's is refused. The mount list decides what is declared, and only duplicate names in it fail the Session ([tool contributions](../../architecture/rust-agent/tool-contributions.md)). Permission decides whether a declared tool's call runs: its preset and `allowedTools`/`disallowedTools` change live through `session.permission.update` and never change the declarations, which are part of the prompt prefix. To block a tool and keep the context stable, keep it mounted and deny it in Permission; to change what the model sees, create the Session with a different mount list. | Method | Mode | Request | Reply | | --- | --- | --- | --- | diff --git a/docs/design/plugins/Approval.md b/docs/design/plugins/Approval.md index bc75c4ee24..0d933f99f6 100644 --- a/docs/design/plugins/Approval.md +++ b/docs/design/plugins/Approval.md @@ -108,6 +108,12 @@ A call that a policy change no longer requires is not restarted; an explicit adv - `pending` is kept although the App Server's attach path no longer needs a lock-held replay: the Collaboration route in [runtime-owner-operations.md](../contracts/runtime-owner-operations.md) reads a member line's pending approvals, and one owner operation serves it. The App Server orders its own notifications; the owner promises only a point-in-time set. +## Supersedes + +- `docs/design/service-faces.md` §3.4's `approval` row and its pointer to the implementation page. +- `docs/design/contracts/runtime-owner-operations.md`'s Collaboration-approval rows (`approval.pending/decide`). +- The current implementation page (`docs/architecture/rust-agent/plugins/Permission.md#approval`) keeps describing the implementation until this contract lands. + ## Verification Flow tests on the owner: @@ -153,7 +159,7 @@ Flow tests on the owner: ## Binding appendix -The service is marked on the owner type; the name stays `approval`. +The service is marked on the owner type; the name stays `approval`. `BranchSource`, `ApprovalCallData`, `ApprovalDecision` and `ApprovalRequestData` are `dim_agent_types` values. ```rust use crate::host::CancelledFn; @@ -181,7 +187,8 @@ pub struct DecideRequest { pub decision: ApprovalDecision, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] pub enum ApprovalError { #[error("the call was denied: {reason}")] Denied { reason: String }, diff --git a/docs/design/plugins/BackgroundExec.md b/docs/design/plugins/BackgroundExec.md index 3fabd85293..c6e9b81da7 100644 --- a/docs/design/plugins/BackgroundExec.md +++ b/docs/design/plugins/BackgroundExec.md @@ -61,7 +61,7 @@ A client stops a task and waits for its terminal: ```rust let ended = background.stop(task_id.clone()).await?; // Unknown, Closed -let ended = background.wait(WaitRequest { task_id, timeout_ms: 5_000 }, cancelled).await?; // Unknown, Timeout, Closed +let ended = background.wait(WaitRequest { task_id, timeout_ms: 5_000 }, cancelled).await?; // Unknown, Timeout, Closed, Cancelled ``` ## Own contract @@ -83,8 +83,8 @@ The host's process-by-id operations are not defined yet; they are stated in Requ | --- | --- | --- | --- | --- | --- | | `adopt` | Take over supervision of a command the host started | `{taskId, description, title?, outputPath}` | `{}` | The caller drops the call: nothing was adopted, and the host's process is killed | `closed`, `unknown_task` (the host has no live task with this id) | | `output` | The task's tail preview | `{taskId}` | `{text}` | The caller drops the call; the read stops | `unknown`, `unavailable`, `closed` | -| `output_page` | One bounded page of the registered output file | `{taskId, cursor, limit}` | `{text, bytes, nextCursor?, truncated}` | The caller drops the call; the read stops | `unknown`, `unavailable`, `invalid_limit`, `closed` | -| `wait` | Wait until the task's terminal is dispatched | `{taskId, timeoutMs}` | `{terminal}` | The caller drops the call; the wait releases | `unknown`, `timeout`, `closed` | +| `output_page` | One bounded page of the registered output file; a stateless offset read, with no pin or release | `{taskId, cursor, limit}` | `{text, bytes, nextCursor?, truncated}` | The caller drops the call; the read stops | `unknown`, `unavailable`, `invalid_limit`, `closed` | +| `wait` | Wait until the task's terminal is dispatched | `{taskId, timeoutMs}` | `{terminal}` | The caller drops the call; the wait releases and nothing changes | `unknown`, `timeout`, `closed`, `cancelled` | | `stop` | Cancel a running task and answer its terminal | `{taskId}` | `{terminal}` | None: an admitted stop settles | `unknown`, `closed` | `nextCursor` is present only for a full page; a client advances by `bytes`. `wait` with `timeout_ms = 0` answers `timeout` for a running task and the terminal for an ended one. `stop` on an ended task answers its terminal and changes no wake. @@ -98,6 +98,7 @@ The host's process-by-id operations are not defined yet; they are stated in Requ | `unavailable` | `output`, `output_page` | The registered file is gone (cleaned or its Session deleted); report the loss, do not retry. | | `invalid_limit` | `output_page` | Use a limit of at least one byte. | | `timeout` | `wait` | The task is still running; wait again or stop it. | +| `cancelled` | `wait` | The caller's token ended the wait; nothing changed. | | `closed` | any | The generation is closing or reloading; a replacement generation serves. | ### Flows @@ -113,7 +114,13 @@ The host's process-by-id operations are not defined yet; they are stated in Requ ## Exceptions with reasons - The registered output file's bytes are produced by the process, while the artifact reference and every read belong to this owner: the path is fixed in `exec/started`, the process only appends, and a read opens and closes within one call, so no file handle crosses an owner. -- ShellSession's commands appear in `exec/started` without an adopting caller: the PTY owner settles its own commands and writes their terminals; this owner consumes them for the notices and recovery, as it does for its own tasks. +- Each command's `exec/started` and `exec/ended` have exactly one writer: this owner for the tasks it adopts, and ShellSession for its PTY commands, which appear in `exec/started` without an adopting caller; this owner consumes those terminals for the notices and recovery. + +## Supersedes + +- `docs/design/service-faces.md` §3.4's `backgroundExec` row and the sentence about `backgroundExec.start`. +- `docs/design/background-task-output.md`'s `TreeCommands` lookup paragraph (the task read now goes by line id). +- The current implementation page (`docs/architecture/rust-agent/plugins/WorkspaceTools.md#backgroundexec`) keeps describing the implementation until this contract lands. ## Verification @@ -129,7 +136,7 @@ Flow tests on the owner: | Rule | Application | | --- | --- | -| §1 parts and Capabilities | BackgroundExec is one branch part and a Capability: it injects `dispatcher` and `timeline`, writes `exec/ended` and folds the terminals. | +| §1 parts and Capabilities | BackgroundExec is one branch part and a Capability: it injects `dispatcher` and `timeline`, writes its adopted tasks' `exec/started`/`exec/ended` and folds the terminals; ShellSession writes its own commands' facts, as the exception states. | | §2 scopes | Branch: a task belongs to the line that started it; the process belongs to the host's process owner. | | §3 orthogonality | The host's process, the Session's hold and the guide table are other owners' operations; no state is read directly. | | §4 rule 1 | A stop and a close cancel the task; the owner writes the terminal. | @@ -160,12 +167,12 @@ Flow tests on the owner: ## Binding appendix -The service is marked on the owner type; the name stays `backgroundExec`. +The service is marked on the owner type; the name stays `backgroundExec`. `ExecEndedData` and `ExecStatus` are `dim_agent_types` values. ```rust use crate::host::CancelledFn; use dim_agent_runtime::PublicService; -use dim_agent_types::{ExecEndedData, ExecStatus}; +use dim_agent_types::ExecEndedData; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] @@ -202,7 +209,8 @@ pub struct WaitRequest { pub timeout_ms: u64, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] pub enum BackgroundError { #[error("the host has no live task with this id")] UnknownTask, @@ -216,6 +224,8 @@ pub enum BackgroundError { Timeout, #[error("the background exec service is closing")] Closed, + #[error("the wait was cancelled")] + Cancelled, } impl PublicService for BackgroundExec {} diff --git a/docs/design/plugins/FileReads.md b/docs/design/plugins/FileReads.md index 2ec6d6961a..dba2853fc4 100644 --- a/docs/design/plugins/FileReads.md +++ b/docs/design/plugins/FileReads.md @@ -70,7 +70,7 @@ let Some(binding) = binding.binding else { | --- | --- | | `B:Timeline` | The line's committed file-tool results, from which bindings are rebuilt, and the completed `context/compaction` facts that decide the context rule. | -FileReads injects no other service. The Session's file tools reach this owner through the Session access mechanism by line id ([TimelineTree's route (#2092)](https://github.com/arcships/dim/pull/2092)); FileReads returns values and stores records, and no file handle crosses. +FileReads injects no other service. The Session's file tools reach this owner by line id with `line_owner::(line)` ([ADR 027](https://github.com/arcships/dim/pull/2029)); FileReads returns values and stores records, and no file handle crosses. ### Operations @@ -103,6 +103,12 @@ The rebuild uses the result event's sequence: no legal compaction cut separates - `record` takes the operation's start sequence from the caller: the window belongs to the caller's operation, and an owner that sampled the sequence at record time would sample after the operation's own writes. +## Supersedes + +- `docs/design/service-faces.md` §3.5's `fileReads` row. +- `docs/design/contracts/runtime-owner-operations.md`'s "File read/edit/write tools → branch FileReads" row. +- The current implementation page (`docs/architecture/rust-agent/plugins/WorkspaceTools.md#filereads`) keeps describing the implementation until this contract lands. + ## Verification Flow tests on the owner: @@ -199,7 +205,8 @@ pub struct RecordRequest { pub established: u64, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] pub enum FileReadsError { #[error("the line is closing")] Closed, @@ -214,4 +221,4 @@ impl FileReads { } ``` -`TextEncoding`, `EncodingSource`, `Bom` and `Eol` are the existing value types of the file-tool codec; they cross as data and stay defined beside the codec, not here. +`TextEncoding`, `EncodingSource`, `Bom` and `Eol` are the existing value types of the file-tool codec ([codec.rs](../../../crates/dim-agent-capabilities/src/workspace_tools/files/codec.rs)); they cross as data and stay defined beside the codec, not here. diff --git a/docs/design/plugins/Permission.md b/docs/design/plugins/Permission.md index be93e3955b..c172b2da16 100644 --- a/docs/design/plugins/Permission.md +++ b/docs/design/plugins/Permission.md @@ -31,7 +31,7 @@ Callers keep as business: | Update the policy | No: the version check and the fact are one write | `update` | | Register tool advice | No: the registration is bound to the registering part's lifetime and asked by name order | `advise` | -An operation exists only where its row says No. +An advisor's failure counts as no advice: its code and message are not forwarded, and the owner decides on its own result. An operation exists only where its row says No. ## Caller example @@ -52,10 +52,7 @@ if admission.outcome == Outcome::Ask && !admission.advisor_question { Hooks registers advice for the lifetime of its branch part; the registration ends with the part: ```rust -permission.advise(AdviseRequest { - name: "hooks".into(), - advise: Arc::new(HookAdvice { branch: self.clone() }), -}).await?; // Duplicate, Closed +permission.advise(&ctx, "hooks".into(), Arc::new(HookAdvice { branch: self.clone() })).await?; // Duplicate, Closed ``` A client updates the policy with the version it read: @@ -86,7 +83,7 @@ The file-access facts operation that resolves the target is not defined yet; it | --- | --- | --- | --- | --- | --- | | `decide` | One call's outcome | `{call, risk?, source?}` | `{outcome: allow\|ask\|deny, reason?, advisorQuestion}` | The caller's token stops the facts or advice read; the decision is not made | `cancelled`, `closed` | | `update` | Versioned policy write | `{expectedVersion, policy}` | `{version}` | None; one commit | `conflict {current}`, `closed` | -| `advise` | Register tool advice for the calling row's lifetime | `{name, advise}` | `{}` | None | `duplicate`, `closed` | +| `advise` | Register tool advice for the calling row's lifetime | `caller: &Ctx`, `name`, callback | `{}` | None | `duplicate`, `closed` | | `PermissionState` (published value) | Read the policy and its version | — | `{version, policy}` | None | — | `risk` is the tool owner's declaration (`read_filesystem`, `write_filesystem`, `execute_process`, `network`, `session`, or absent). `source` is present exactly for an admission; the owner asks the advisors only then, and `advisorQuestion` says whether an advisor required an explicit answer, so a policy change can end a policy question but never an advisor's. @@ -117,6 +114,11 @@ An unreadable fact or rule is not an error: the owner denies the call with its r - A branch part registers a callback (`advise`): §7 allows a callback by reference; the owner never calls it inside the Timeline's commit lock, and the calling row's unload withdraws it. - The policy value is published as a read-only view: Approval subscribes to it to recheck a waiting call, and the App Server reads it for the client; neither reads Permission's internals. +## Supersedes + +- `docs/design/service-faces.md` §3.4's `permission` row and its pointer to the implementation page. +- The current implementation page (`docs/architecture/rust-agent/plugins/Permission.md#permission`) keeps describing the implementation until this contract lands. + ## Verification Flow tests on the owner: @@ -163,12 +165,13 @@ Flow tests on the owner: ## Binding appendix -The service is marked on the owner type; the name stays `permission`. +The service is marked on the owner type; the name stays `permission`. `caller: &Ctx` is rutis's caller parameter: the dispatch fills it from the calling row, it is not a request field, and no caller sends or names a row. ```rust use crate::host::CancelledFn; use dim_agent_runtime::PublicService; -use dim_agent_types::{ApprovalCallData, BranchSource, CommandRule, PermissionPolicy}; +use dim_agent_types::{ApprovalCallData, BranchSource, PermissionPolicy}; +use rutis::Ctx; #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "lowercase")] @@ -205,16 +208,28 @@ pub struct UpdateRequest { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct AdviseRequest { - pub name: String, - pub advise: AdviseFn, +pub struct PermissionState { + pub version: u64, + pub policy: PermissionPolicy, } +/// What one advisor is asked: the call, its source, its risk and the owner's +/// own decision before advice (allow or ask; a deny asks no advisor). #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PermissionState { - pub version: u64, - pub policy: PermissionPolicy, +pub struct AdviceRequest { + pub source: BranchSource, + pub call: ApprovalCallData, + #[serde(skip_serializing_if = "Option::is_none")] + pub risk: Option, + pub decision: OwnDecision, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OwnDecision { + Allow, + Ask, } /// One advisor's answer: none, allow, ask with a reason, or deny with a reason. @@ -233,7 +248,8 @@ pub type AdviseFn = std::sync::Arc< + Sync, >; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] pub enum PermissionError { #[error("the decision was cancelled")] Cancelled, @@ -251,6 +267,6 @@ impl PublicService for Permission {} impl Permission { pub async fn decide(&self, request: DecideRequest, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn update(&self, request: UpdateRequest) -> Result { /* ... */ } - pub async fn advise(&self, request: AdviseRequest) -> Result<(), PermissionError> { /* ... */ } + pub fn advise(&self, caller: &Ctx, name: String, advise: AdviseFn) -> Result<(), PermissionError> { /* ... */ } } ``` diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index c91165765d..557cffd22f 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -59,4 +59,4 @@ A plugin is split by the owner of its state into parts, each placed in its owner | --- | --- | | Process parts | Provider (management supplement), Scheduler, Workflow, ExternalAgent, Modality, PluginManager, RuntimeManager, RemoteGateway, Skills (installation), PromptSuggestion (the Settings source), `CodeMode` when installed, light-ocr in the daemon, EventHub, Report; AcpGateway in its client host process; ClientView (the connection's viewed line) | | Session parts | Questions, ShellInput, Attachments, SessionTitle, Report, PromptSuggestion, Goal, Web, Recall, ImageUnderstanding, EventHub, Hooks, Scheduler, Workflow, PromptSources, Prompt (the entries table), Code Mode when enabled, SettingsTool (the one `settings` tool, registered by ExecutionSettings in v1) | -| Branch parts | Goal (with Pursuit), ModelRecovery (proposed), Hooks, Prompt, Code Mode when enabled, EnvironmentClientsBranch (registered by Connection), SettingsSnapshotBranch (registered by ExecutionSettings) | +| Branch parts | ToolBinding, ToolExecutor, Approval, Permission, BackgroundExec, FileReads, Goal (with Pursuit), ModelRecovery (proposed), Hooks, Prompt, Code Mode when enabled, EnvironmentClientsBranch (registered by Connection), SettingsSnapshotBranch (registered by ExecutionSettings) | diff --git a/docs/design/plugins/ToolBinding.md b/docs/design/plugins/ToolBinding.md index bd276ae456..cfff109ebd 100644 --- a/docs/design/plugins/ToolBinding.md +++ b/docs/design/plugins/ToolBinding.md @@ -164,6 +164,13 @@ A record is settled before the branch accepts closing work. A reload rebuilds th - Pins are values, not handles: a pin is a record whose adoption a later prefix may still name, and the registry keeps those versions resolvable until the owner releases the adoption at the next bind or the close. ToolBinding holds no handler and no guard. - The record's settlement reads the line's facts (`step/tool-result`, `turn/end`) instead of a caller's release call: only the owner of the record can guarantee every end path, and the facts are public. +## Supersedes + +- `docs/design/service-faces.md` §3.5's `toolBinding` row. +- `docs/design/contracts/runtime-owner-operations.md`'s "Loop, ToolExecutor and Code Mode readers → `toolBinding`" row. +- `docs/design/contracts/session-boundary.md` §A.5's ToolBinding adoption sentences. +- The current implementation page (`docs/architecture/rust-agent/plugins/ToolExecution.md#toolbinding`) and `tool-contributions.md` §7.5–7.6 keep describing the implementation until this contract lands. + ## Verification Flow tests on the owner: @@ -210,9 +217,10 @@ Flow tests on the owner: ## Binding appendix -The service is marked on the owner type; the name stays `toolBinding`. Every operation completes without waiting; the registry's operations take the cancellation argument. +The service is marked on the owner type; the name stays `toolBinding`. Every operation completes without waiting; the registry's operations take the cancellation argument. `ToolDefinition` and `ToolSourceVersion` are `dim_agent_types` values; `ToolExecutionContext` is the crate's existing execution context (`dim_agent_capabilities::host`), not a type of this owner. ```rust +use crate::host::ToolExecutionContext; use dim_agent_runtime::PublicService; use dim_agent_types::{ToolCall, ToolDefinition, ToolSourceVersion}; @@ -250,7 +258,8 @@ pub struct TransferRequest { pub to: String, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] pub enum BindingError { #[error("request {request_id} is already bound")] AlreadyBound { request_id: String }, diff --git a/docs/design/plugins/ToolExecutor.md b/docs/design/plugins/ToolExecutor.md index 3efb92cd8c..5596ecdaf0 100644 --- a/docs/design/plugins/ToolExecutor.md +++ b/docs/design/plugins/ToolExecutor.md @@ -36,17 +36,17 @@ An operation exists only where its row says No. Code Mode opens a gate for one outer call and invokes child tools through it: ```rust -let gate = executor.open(OpenRequest { +let gate = executor.open(&ctx, OpenRequest { parent_call_id: outer_call_id.clone(), context: execution.clone(), -}, cancelled.clone()).await?; // Closed, Interrupted, NoBatch +}, cancelled.clone()).await?; // Closed, Interrupted, NoBatch, Cancelled // The program's tools.call: -let result = executor.invoke(InvokeRequest { +let result = executor.invoke(&ctx, InvokeRequest { gate_id: gate.gate_id.clone(), call, }, cancelled.clone()).await?; // GateClosed, Closed; a tool failure is result.is_error // The program ended: take the confirmed effects to word the result. -let effects = executor.close(CloseRequest { gate_id: gate.gate_id }).await?; // GateClosed, Closed +let effects = executor.close(&ctx, CloseRequest { gate_id: gate.gate_id }).await?; // GateClosed, Closed ``` A program's declarations come from the pin owner, not the executor: @@ -77,11 +77,11 @@ The owner closes the gate when the parent call settles; a program that returns e | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `open` | Open a child-call gate for one outer call of the current batch | `{parentCallId, context}` | `{gateId}` | Before the gate id is issued; nothing was created | `closed`, `interrupted`, `no_batch` (no current batch, or the parent call does not belong to it) | -| `invoke` | Run one child call through the same admission and execution path | `{gateId, call}` | `{result}` | The gate's parent token; the child is cancelled and its result says so | `closed`, `gate_closed` (the gate was closed by its parent's settlement or by an interrupt) | +| `open` | Open a child-call gate for one outer call of the current batch | `{parentCallId, context}` | `{gateId}` | Before the gate id is issued; nothing was created | `closed`, `interrupted`, `no_batch` (no current batch, or the parent call does not belong to it), `cancelled` | +| `invoke` | Run one child call through the same admission and execution path | `{gateId, call}` | `{result}` | The caller's token before the child settles: the child is cancelled and its fact records it; the gate stays usable | `closed`, `gate_closed` (the gate was closed by its parent's settlement or by an interrupt), `cancelled` | | `close` | Close the gate now and answer the confirmed child effects | `{gateId}` | `{effects}` | None: the close settles | `closed`, `gate_closed` (the batch was interrupted or settled before the call) | -`gateId` is bound to the calling row and the parent call; a call from another row is `gate_closed`. `close` is idempotent for the owner's own settlement: the parent's settlement closes the gate whether or not the program did, and the effects reach the parent result once. A child call's refusal, cancellation, unknown tool or tool failure is a `ToolResult` with `is_error: true`, not an operation error: the program decides what to do with it. +`caller: &Ctx` is the binding's calling-row parameter: it is not a request field, and the gate id's row binding follows from it. `gateId` is bound to the calling row and the parent call; a call from another row is `gate_closed`. `close` is idempotent for the owner's own settlement: the parent's settlement closes the gate whether or not the program did, and the effects reach the parent result once. A child call's refusal, cancellation, unknown tool or tool failure is a `ToolResult` with `is_error: true`, not an operation error: the program decides what to do with it. ### Errors @@ -91,12 +91,13 @@ The owner closes the gate when the parent call settles; a program that returns e | `interrupted` | `open` | The turn was interrupted; stop the program. | | `no_batch` | `open` | The parent call is not part of the current batch; a caller bug: stop the program and report it. | | `gate_closed` | `invoke`, `close` | The gate's parent call settled or the batch was interrupted; stop the program; the parent result carries the effects already confirmed. | +| `cancelled` | `open`, `invoke` | The caller's token ended the call; for `invoke` the child's result records the cancellation and the gate stays usable. | ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `open` | Check the current batch and the parent call, issue a gate id under the calling row, subscribe the gate to the parent token | Before the id is issued: nothing exists | The row's gates are closed with their child tasks | New calls are refused; every gate of the generation is closed | ToolExecutor | +| `open` | Check the current batch and the parent call, issue a gate id under the calling row, subscribe the gate to the parent token | Before the id is issued: nothing exists, `cancelled` | The row's gates are closed with their child tasks | New calls are refused; every gate of the generation is closed | ToolExecutor | | `invoke` | Write the child `step/tool-call` with the parent call id, resolve the write target, admit the call, run it through the registry, write the child `step/tool-result`, record its effects | The child is cancelled; its fact records the cancellation; the gate stays usable for the program's next call | The row's gates close; in-flight children end cancelled and are recorded | In-flight children end as reload settlements; the gate is closed | ToolExecutor for the facts and the gate; ToolRegistry for the handler and its claim; the calling row for the program future | | `close` | Mark the gate closed, refuse new children, wait for its running children within the owner's grace, answer the confirmed effects | The close waits; a child past the grace is outside the contract | The row's gates close with their children | A close in flight finishes; the parent settlement closes the gate again | ToolExecutor | | Parent settlement | After the parent call's result is known, close every gate of the parent, wait for its children within the owner's grace, and merge their effects into the result in invocation order | — | — | — | ToolExecutor | @@ -107,6 +108,12 @@ The owner never hands out a gate: `gateId` names the gate only for `invoke` and - A child call's failure is a result, not an operation error: a program may catch it, and the model sees the same `ToolResult` text a top-level call would produce. +## Supersedes + +- `docs/design/service-faces.md` §3.5's `toolExecutor` row. +- `docs/design/contracts/runtime-owner-operations.md`'s "Nested tool execution → `toolExecutor`" row. +- The current implementation page (`docs/architecture/rust-agent/plugins/ToolExecution.md#toolexecutor`) keeps describing the implementation until this contract lands. + ## Verification Flow tests on the owner: @@ -152,12 +159,13 @@ Flow tests on the owner: ## Binding appendix -The service is marked on the owner type; the name stays `toolExecutor`. +The service is marked on the owner type; the name stays `toolExecutor`. `caller: &Ctx` is rutis's caller parameter: the dispatch fills it from the calling row, it is not a request field, and no caller sends or names a row. ```rust -use crate::host::CancelledFn; +use crate::host::{CancelledFn, ToolExecutionContext}; use dim_agent_runtime::PublicService; -use dim_agent_types::ToolCall; +use dim_agent_types::{ToolCall, ToolEffect, ToolResult}; +use rutis::Ctx; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] @@ -191,7 +199,8 @@ pub struct CloseReply { pub effects: Vec, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] pub enum ExecutorError { #[error("the tool executor is closing")] Closed, @@ -201,14 +210,16 @@ pub enum ExecutorError { NoBatch, #[error("the child gate is closed")] GateClosed, + #[error("the call was cancelled")] + Cancelled, } impl PublicService for ToolExecutor {} #[rutis::service(name = "toolExecutor")] impl ToolExecutor { - pub async fn open(&self, request: OpenRequest, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn invoke(&self, request: InvokeRequest, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn close(&self, request: CloseRequest) -> Result { /* ... */ } + pub async fn open(&self, caller: &Ctx, request: OpenRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn invoke(&self, caller: &Ctx, request: InvokeRequest, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn close(&self, caller: &Ctx, request: CloseRequest) -> Result { /* ... */ } } ``` diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 0cf6cd6437..3bc2109a49 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -136,13 +136,13 @@ Proposed target operations: [Resource and repository operations](contracts/resou | 名字 | 数据面 | 所有者保留的状态 | | --- | --- | --- | | `toolHost` | `execute(call, caller, cancelled)` | ToolDriver、工具声明 | -| `approval` | `pending()`、`decide(requestId, decision)` | 待处理请求、批次准入 | -| `permission` | `check(call, risk, cancelled)` | 预设、权限状态、advisor | +| `approval` | `admit(source, call, risk?, cancelled)`、`pending()`、`decide(requestId, decision)`([Approval](plugins/Approval.md)) | 待处理请求、准入与重查 | +| `permission` | `decide(call, risk?, source?, cancelled)`、`update(expectedVersion, policy)`、`advise(name, advise)`([Permission](plugins/Permission.md)) | 预设与版本、advisor 表、决策输入 | | `inputQueue` | `submit(input)`、`withdraw(command)` | 排序、恢复、InputSnapshot | | `wait` | `wait(taskId, timeoutMs, cancelled)` | 到达记录、单次等待槽 | -形状与错误见所有者:[Permission](../architecture/rust-agent/plugins/Permission.md#permission-data-face)、 -[Approval](../architecture/rust-agent/plugins/Permission.md#approval-data-face)、 +形状与错误见所有者:[Permission](plugins/Permission.md)、 +[Approval](plugins/Approval.md)、 [InputQueue](../architecture/rust-agent/plugins/InputQueue.md#data-face)、 [Wait](../architecture/rust-agent/plugins/Wait.md#data-face) 与 [toolHost](../architecture/rust-agent/tool-contributions.md#21-宿主工具的-toolhost-数据面)。 @@ -153,11 +153,11 @@ Proposed target operations: [Resource and repository operations](contracts/resou | 名字 | 数据面 | 所有者把什么留在内部 | | --- | --- | --- | | `mcpSession` | `state()`、`refresh()`、`widget(published)`、`call(server, tool, arguments)` | 连接代次、已发布工具、发现与重连 | -| `backgroundExec` | `output(taskId)`、`outputPage(taskId, cursor, limit)`、`wait(taskId, timeoutMs)`、`stop(taskId)` | 任务表、活进程、输出采集与唤醒 | +| `backgroundExec` | `adopt(taskId, …)`、`output(taskId)`、`outputPage(taskId, cursor, limit)`、`wait(taskId, timeoutMs)`、`stop(taskId)`([BackgroundExec](plugins/BackgroundExec.md)) | 任务表、活进程、输出采集与唤醒 | 形状与错误由所有者文档定义:[MCP Apps](appserver/mcp-apps.md#44-the-mcpsession-data-face)(`mcpSession`)和 -[WorkspaceTools](../architecture/rust-agent/plugins/WorkspaceTools.md#data-face)(`backgroundExec`)。 -`backgroundExec.start` 需要活的进程对象,仍是 `exec` 工具的操作,不在数据面上;`backgroundExec.stop` 是 kill。 +[BackgroundExec](plugins/BackgroundExec.md)(`backgroundExec`)。 +`backgroundExec.adopt` 按 task id 接管已启动的命令,进程创建归 HostPlatform(#2032);`backgroundExec.stop` 是 kill。 这些名字在 catalog 里是 `data`,Rust 类型仍由部件在同一实例按类型键读取。 `hostPlatform`、`fileStorage`、`timelineStore` 不按对象分类保留:数据面就是公开契约,`execHost`、`fsHost`、`store`、`timelineStore` 的操作就是它们的接口,旧名字是提供方和它的 Rust binding,调用方在进程内直接调这组操作,不再有第二套公开 API。凭据是操作内部用的能力,不是保留 `internal` 的理由。`hostPlatform`、`fileStorage` 的提供方在持有资源的那个 daemon(控制节点自己的插件,或 #1296 挂载的资源 leaf);`store` 在持有 Session 状态的那个 daemon,SQLite 还是 PostgreSQL 只是实现(#1298,[resource and store data faces](resource-faces.md) §6)。 @@ -175,11 +175,11 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow | `prompt` | branch | Prompt | hot-path | 待迁移;按 #1292 定义操作面 | | `contextPreparation` | branch | ContextPreparation | hot-path | 待迁移;按 #1292 定义操作面 | | `contextUsage` | branch | ContextUsage | hot-path | 本地请求计数器、请求引用与按序统计;`session.context.usage` 是 App Server RPC。按 #1292 确认是否需要独立插件操作。 | -| `toolBinding` | branch | ToolBinding | hot-path | 待迁移;按 #1292 定义操作面 | -| `toolExecutor` | branch | ToolExecutor | hot-path | 待迁移;按 #1292 定义操作面 | +| `toolBinding` | branch | ToolBinding | hot-path | 数据面见 [ToolBinding](plugins/ToolBinding.md) | +| `toolExecutor` | branch | ToolExecutor | hot-path | 数据面见 [ToolExecutor](plugins/ToolExecutor.md) | | `configurationPublisher` | branch | ContextPreparation | hot-path | 待迁移;按 #1292 定义操作面 | | `configureControl` | branch | Prompt | hot-path | 待迁移;按 #1292 定义操作面 | -| `fileReads` | branch | FileReads | hot-path | 待迁移;按 #1292 定义操作面 | +| `fileReads` | branch | FileReads | hot-path | 数据面见 [FileReads](plugins/FileReads.md) | | `historyRenderer` | session | SessionScope | hot-path | 待迁移;按 #1292 定义操作面 | | `contextModelHost` | session | SessionScope | hot-path | 待迁移;按 #1292 定义操作面 | | `prepareModelHost` | session | PrepareModelHost | hot-path | 待迁移;按 #1292 定义操作面 | From 038e60c917f44c57f7a18e03a941113e4d3e20e2 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Tue, 24 Nov 2026 11:26:10 +0800 Subject: [PATCH 08/11] docs(design): resolve the round-4 review of the tool chain contracts Owner failures get kinds (read, failed); claim carries its execution context and reports the contributor's refusal; FileReads keys by canonical path and defines wire DTOs; published faces keep their shapes or state the break in Client-visible changes; Loop gets declarations from the registry and ToolBinding provides the operations Loop requires; invoke separates the caller's cancellation from the child's result; examples, replies, recovery and the superseded documents follow. --- .../contracts/runtime-owner-operations.md | 2 +- docs/design/plugins/Approval.md | 75 ++++++------ docs/design/plugins/BackgroundExec.md | 106 +++++++++------- docs/design/plugins/FileReads.md | 114 ++++++++++++------ docs/design/plugins/Hooks.md | 26 ++-- docs/design/plugins/Permission.md | 81 ++++++++----- docs/design/plugins/README.md | 2 +- docs/design/plugins/ToolBinding.md | 110 ++++++++++------- docs/design/plugins/ToolExecutor.md | 60 +++++---- 9 files changed, 341 insertions(+), 235 deletions(-) diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index dea9bd74de..e11d51238f 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -60,7 +60,7 @@ substitutes a newer head. | --- | --- | | ToolBinding, Session language and Agent configuration → `prompt` | `prompt.initialCompletion({}) → void or opening error`; `prompt.configure({sources, model?}) → unchanged, adopted or superseded`. | | Prompt and guide adoption → `contextPreparation` | `contextPreparation.publish({adopted, changes, model?, toolAdoption?, inputs}) → sequence or null`; `awaitPublished({sequence}) → sequence`. Publication commits adoption atomically. | -| File read/edit/write tools → branch FileReads | `binding({path, purpose}) → {binding?} or {unavailable: neverRead\|compacted}`, `record({path, binding, established}) → void`([FileReads](../plugins/FileReads.md)). The original read supplies the established sequence; file I/O stays on the file node. | +| File read/edit/write tools → branch FileReads | `binding({path, purpose}) → BindingReply` (`bound {binding}` or `unavailable {reason: neverRead\|compacted}`; `path` is canonical), `record({path, binding, established}) → void`([FileReads](../plugins/FileReads.md)). The original read supplies the established sequence; file I/O stays on the file node. | ### Model preparation, history and tools diff --git a/docs/design/plugins/Approval.md b/docs/design/plugins/Approval.md index 0d933f99f6..73f4e2288a 100644 --- a/docs/design/plugins/Approval.md +++ b/docs/design/plugins/Approval.md @@ -15,6 +15,8 @@ Approval owns: Approval does not decide the policy (Permission does), run tools (ToolExecutor does), or notify clients: the client notifications are the App Server's projection of `approval/*` facts and its own attach ordering. +Targets: `permission` is this PR's; the mechanism obligation for cross-scope access is [#2127](https://github.com/arcships/dim/issues/2127). + Callers keep as business: - When a tool call is admitted, and what a refusal means for the turn. @@ -39,24 +41,21 @@ approval.admit(AdmitRequest { source: BranchSource::Tool { turn_id, request_id, call_id }, call: ApprovalCallData { name: call.name.clone(), input: call.input.clone() }, risk: risk.clone(), -}, cancelled.clone()).await?; // Denied { reason }, Cancelled, Closed +}, cancelled.clone()).await?; // Denied, Cancelled, Failed, Closed ``` A client answers one request; the answer is accepted only while the request is pending: ```rust -approval.decide(DecideRequest { - approval_id: request.approval_id, - decision: ApprovalDecision::Allow, -}).await?; // Unknown (answered, cancelled or never pending), Closed +approval.decide(request.approval_id, ApprovalDecision::Allow).await?; // Unknown, Failed, Closed ``` Collaboration lists a member line's pending approvals and answers the one it was asked about: ```rust -for request in approval.pending().await?.requests { +for request in approval.pending().await? { if request.approval_id == target { - approval.decide(DecideRequest { approval_id: target, decision }).await?; + approval.decide(target, decision).await?; } } ``` @@ -77,20 +76,21 @@ The policy value is a read-only view Permission publishes (§7); Approval takes | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `admit` | Admit one call, asking the user when required | `{source, call, risk}` | `{}` | The caller drops the call: the pending request is cancelled and the call ends `cancelled` | `denied {reason}`, `cancelled`, `closed` | -| `pending` | The requests no answer or cancellation ended, in request order | `{}` | `{requests}` | None | `closed` | -| `decide` | Answer a pending request | `{approvalId, decision}` | `{}` | None: an accepted answer is committed | `unknown` (not pending: answered, cancelled or never existed), `closed` | +| `admit` | Admit one call, asking the user when required | `{source, call, risk}` | `()` | The caller drops the call: the pending request is cancelled and the call ends `cancelled` | `denied`, `cancelled`, `failed`, `closed` | +| `pending` | The requests no answer or cancellation ended, in request order | `()` | `ApprovalRequestData[]` | None | `closed` | +| `decide` | Answer a pending request | `approvalId`, `decision` | `()` | None: an accepted answer is committed | `unknown` (not pending: answered, cancelled or never existed), `failed`, `closed` | -`risk` is the tool owner's declaration for the call, or absent. `source` identifies the caller and is passed to Permission for the admission decision. The reply to `decide` means the branch dispatched the answer, not that the tool started. +`risk` is the tool owner's declaration for the call, or absent. `source` identifies the caller and is passed to Permission for the admission decision. The reply to `decide` means the branch dispatched the answer, not that the tool started. Replies are positional, as the published face is. ### Errors -| Kind | Operation | What the caller does next | -| --- | --- | --- | -| `denied` | `admit` | Do not run the call; the result carries the reason. | -| `cancelled` | `admit` | The batch token was dropped or the batch was interrupted; do not run the call. | -| `closed` | any | The generation is closing or reloading; stop. | -| `unknown` | `decide` | The request is no longer pending; retire the prompt and do not retry the answer. | +| Kind | Operation | Retryable | What the caller does next | +| --- | --- | --- | --- | +| `denied` | `admit` | No | Do not run the call; the result carries the reason. | +| `cancelled` | `admit` | No | The batch token was dropped or the batch was interrupted; do not run the call. | +| `failed` | `admit`, `decide` | Yes, by a later attempt | The request or response could not be committed (storage or fact failure); nothing is pending for the call, or the answer did not take; the owner reports a fault and the turn fails. A repeated call is a new admission or a fresh answer. | +| `closed` | any | No, in this generation | The generation is closing or reloading; stop; a replacement generation serves the next request. | +| `unknown` | `decide` | No | The request is no longer pending; retire the prompt and do not retry the answer. A repeated answer is `unknown` too. | ### Flows @@ -99,11 +99,24 @@ The policy value is a read-only view Permission publishes (§7); Approval takes | `admit` — allowed without a question | Ask Permission; an allow returns | The token is checked before the call starts | Nothing held | Refused with `closed` | Approval and Permission | | `admit` — a question is required | Commit `approval/request`, register the pending request, wait for the answer or a policy change; on an allow, recheck the policy and return; on a deny, return the refusal | The pending request is removed and `approval/cancelled` is written; the call ends `cancelled` | The pending request is cancelled with the same terminal | Every pending request of the generation is cancelled; an in-flight wait ends `closed` | Approval: the request, its terminal and the waiter | | `admit` — policy changed while waiting | Recheck through Permission; an allow without an advisor question ends the question with `approval/cancelled` and its reason; a deny ends it with the refusal; an ask keeps waiting | As above | As above | As above | Approval | +| `admit` — the request commit fails | Nothing is pending; the call ends `failed`; the turn fails | — | — | — | Approval | | `decide` | Commit `approval/respond`, answer the waiter once the branch dispatched it; the admission rechecks before the call starts | — | A committed answer stays; the admission may end `closed` | A response to a request of a closed generation is `unknown` | Approval | +| `decide` — the response commit fails | The request stays pending; the answer reports `failed`; a repeated answer is accepted | — | — | — | Approval | | `pending` | One consistent read under the owner's lock | — | — | Answered at the state observed | Approval | A call that a policy change no longer requires is not restarted; an explicit advisor question stays pending until answered. The owner never fabricates a user answer. +## Client-visible changes + +The published `approval` face ([Permission plugin page](../../architecture/rust-agent/plugins/Permission.md#approval-data-face)) keeps `pending()` and `decide(requestId, decision)` positionally and keeps `ApprovalRequestData[]` as `pending`'s reply. It changes as follows, and the maintainer is asked to confirm: + +- `respond(requestId, decision)` is renamed `decide`; the callers are Hooks and the App Server's `approval.respond` built-in. The built-in keeps its name and settles through this operation; the client RPC is unchanged. +- `replay()` is removed; `pending()` answers the same set, and the App Server orders its attach notifications itself. +- Error codes change case with the standard binding spelling: `Unknown`/`Cancelled`/`Closed` become `unknown`/`cancelled`/`closed`; `denied` and `failed` are new. Callers match the codes by string; the change ships with the same release as the face. +- `admit` is new (additive). + +No Timeline event, notification name, request field of the client protocol or model-visible text changes. + ## Exceptions with reasons - `pending` is kept although the App Server's attach path no longer needs a lock-held replay: the Collaboration route in [runtime-owner-operations.md](../contracts/runtime-owner-operations.md) reads a member line's pending approvals, and one owner operation serves it. The App Server orders its own notifications; the owner promises only a point-in-time set. @@ -121,6 +134,7 @@ Flow tests on the owner: - An allow without a question returns without a request; an ask writes one request, and the call starts only after the answer and the recheck. - A dropped admission removes its request and writes `approval/cancelled`; a policy change that allows the call ends it the same way and starts the call; a policy change that denies it returns the refusal. - An advisor's question stays pending across a policy change; only an answer settles it. +- A request commit failure answers `failed`, leaves nothing pending and fails the turn; a response commit failure answers `failed`, leaves the request pending, and a repeated answer is accepted. - A second answer to the same request is `unknown`; an answer to a cancelled request is `unknown`. - The generation's close cancels every pending request; a reload cancels the historical requests and rebuilds an empty pending set. - The face and the Rust call answer the same requests and errors. @@ -151,10 +165,12 @@ Flow tests on the owner: | ADR 002 D3 | Depends on Permission (branch) and the branch infrastructure. | | ADR 002 D4 | No configuration. | | ADR 002 D5 | Language-neutral operations and data. | +| ADR 027 | Not applicable: the line's own part serves its callers; the Collaboration route uses the line access owned by ADR 027. | ## Requirements raised to mechanism owners - **Permission (#2028).** `decide` with the call's source and the published `PermissionState` are this board's own contract; see [Permission](Permission.md). +- **Cross-scope mechanism ([#2127](https://github.com/arcships/dim/issues/2127), target).** The Collaboration route reaches a member line's `pending`/`decide` through the line access; this owner states the operations, not the mechanism. - **None other.** No Timeline, Dispatcher, loader or runtime change. ## Binding appendix @@ -167,33 +183,22 @@ use dim_agent_runtime::PublicService; use dim_agent_types::{ApprovalCallData, ApprovalDecision, ApprovalRequestData, BranchSource}; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct AdmitRequest { pub source: BranchSource, pub call: ApprovalCallData, pub risk: Option, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PendingReply { - pub requests: Vec, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct DecideRequest { - pub approval_id: String, - pub decision: ApprovalDecision, -} - -#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "snake_case")] +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum ApprovalError { #[error("the call was denied: {reason}")] Denied { reason: String }, #[error("the call was cancelled")] Cancelled, + #[error("the approval record could not be written: {reason}")] + Failed { reason: String }, #[error("the approval service is closing")] Closed, #[error("the approval is absent or already resolved")] @@ -205,7 +210,7 @@ impl PublicService for Approval {} #[rutis::service(name = "approval")] impl Approval { pub async fn admit(&self, request: AdmitRequest, cancelled: CancelledFn) -> Result<(), ApprovalError> { /* ... */ } - pub async fn pending(&self) -> Result { /* ... */ } - pub async fn decide(&self, request: DecideRequest) -> Result<(), ApprovalError> { /* ... */ } + pub async fn pending(&self) -> Result, ApprovalError> { /* ... */ } + pub async fn decide(&self, approval_id: String, decision: ApprovalDecision) -> Result<(), ApprovalError> { /* ... */ } } ``` diff --git a/docs/design/plugins/BackgroundExec.md b/docs/design/plugins/BackgroundExec.md index c6e9b81da7..3c1550b251 100644 --- a/docs/design/plugins/BackgroundExec.md +++ b/docs/design/plugins/BackgroundExec.md @@ -8,13 +8,14 @@ BackgroundExec owns the commands a line moved to the background: the task table, BackgroundExec owns: -- **The task table.** One task per background command of the line: the task id, its description and title, the registered output path, the process it supervises, and its terminal record. -- **Supervision.** Wait for the process the host started, write `exec/ended` with its status and result, hold the Session until the terminal fact is appended, and wake the line with a bounded notice unless the end came from a stop, a branch close or an unload. -- **The output artifact.** The task's registered output file: the tail preview and its bounded pages, the truncation flag, and the unavailable answer when the file is gone. The bytes are appended by the process; the artifact reference and every read belong to this owner. -- **Recovery.** On load, write failed terminals for commands whose process did not survive, and post the wakes the previous generation lost. +- **The task table.** One task per background command of the line: the task id, its description and title, the registered output path, the process it supervises, and its terminal record. On load, the table is rebuilt from the line's `exec/started` and `exec/ended` facts at one cutoff; a task with a start and no end is written a failed terminal, and every ended task's id, description, title, output path and status come back, so historical reads answer without a live process. +- **Supervision.** Adopt the process the host started, wait for it, write `exec/ended` with its status and result, hold the Session until the terminal fact is appended, and wake the line with a bounded notice unless the end came from a stop, a branch close or an unload. +- **The output artifact.** The task's registered output file: the live task's tail preview, the bounded page read, the truncation flag, and the unavailable answer when the file is gone. The bytes are appended by the process; the artifact reference and every read belong to this owner. BackgroundExec does not create, start or kill processes. The host's process owner starts a command and issues its task id; BackgroundExec adopts the id, and stops the task by asking the host to kill that id. ShellSession owns the PTY and its own stop port; its commands' terminals are settled by the ShellSession owner through `exec/started`/`exec/ended`, and this owner consumes them. +Targets: the host's process operations are a target, pending [#2032](https://github.com/arcships/dim/issues/2032); the Session hold is a target, pending [#2093](https://github.com/arcships/dim/pull/2093); the line access is [ADR 027](https://github.com/arcships/dim/pull/2029) with the mechanism obligation [#2127](https://github.com/arcships/dim/issues/2127). + Callers keep as business: - Whether a command is moved to the background: the exec tool decides after its foreground wait. @@ -25,7 +26,7 @@ Callers keep as business: | --- | --- | --- | | Supervise a command the host started | No: the supervision task, the terminal fact and the Session hold are one lifecycle; a caller holding the process would duplicate the settlement on every path | `adopt` | | Stop a task by id | No: the stop must cancel the supervision, kill the process and write one terminal without a wake; a caller composing the steps could write two terminals | `stop` | -| Read the task's tail preview | No: the artifact is the owner's record and the read is bounded by the owner's policy | `output` | +| Read a running task's tail preview | No: the artifact is the owner's record and the read is bounded by the owner's policy | `output` | | Read the task's output in pages | No: the page's cursor, the character boundary and the truncation flag are the owner's knowledge | `output_page` | | Wait until a task ends | No: the wait must observe the dispatched terminal, not poll the record | `wait` | @@ -43,25 +44,25 @@ background.adopt(AdoptRequest { description: request.description.clone(), title: request.title.clone(), output_path: launch.output_path.clone(), -}).await?; // Closed, UnknownTask +}).await?; // Closed, UnknownTask, Failed ``` -The product reads the task's preview and pages: +The product reads the running task's preview and pages its file: ```rust -let preview = background.output(task_id.clone()).await?; // Unknown, Unavailable, Closed +let preview = background.output(task_id.clone()).await?; // Unknown, Closed; an ended task is unknown here let page = background.output_page(OutputPageRequest { task_id, cursor, limit: 64 * 1024, -}).await?; // Unknown, Unavailable, InvalidLimit, Closed +}).await?; // Unknown, Unavailable, InvalidLimit, Read, Closed ``` A client stops a task and waits for its terminal: ```rust -let ended = background.stop(task_id.clone()).await?; // Unknown, Closed -let ended = background.wait(WaitRequest { task_id, timeout_ms: 5_000 }, cancelled).await?; // Unknown, Timeout, Closed, Cancelled +let ended = background.stop(task_id.clone()).await?; // Unknown, Read, Closed +let ended = background.wait(WaitRequest { task_id, timeout_ms: 5_000 }, cancelled).await?; // Unknown, Timeout, Read, Closed, Cancelled ``` ## Own contract @@ -70,36 +71,38 @@ let ended = background.wait(WaitRequest { task_id, timeout_ms: 5_000 }, cancelle | Service | Purpose | | --- | --- | -| `P:HostPlatform` (process, [#2032](https://github.com/arcships/dim/issues/2032)) | The started process by task id: wait for it, kill it, and answer its terminal status. | -| `S:SessionScope` (Session, [#2093](https://github.com/arcships/dim/pull/2093)) | Hold the Session while a task runs; observe activation and closing. | +| `P:HostPlatform` (process, target, pending [#2032](https://github.com/arcships/dim/issues/2032)) | The started process by task id: wait for it, kill it, and answer its terminal status. | +| `S:SessionScope` (Session, target, pending [#2093](https://github.com/arcships/dim/pull/2093)) | Hold the Session while a task runs; observe activation and closing. | | `S:GuideEntries` (Session) | Register the exec notification's entry for this line until the part unloads. | | `B:Timeline`, `B:Dispatcher` | Write and recover `exec/started`/`exec/ended`; consume terminals and interrupts; write the wake input. | -The host's process-by-id operations are not defined yet; they are stated in Requirements. +The host's process-by-id operations are a target of #2032; they are stated in Requirements. ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `adopt` | Take over supervision of a command the host started | `{taskId, description, title?, outputPath}` | `{}` | The caller drops the call: nothing was adopted, and the host's process is killed | `closed`, `unknown_task` (the host has no live task with this id) | -| `output` | The task's tail preview | `{taskId}` | `{text}` | The caller drops the call; the read stops | `unknown`, `unavailable`, `closed` | -| `output_page` | One bounded page of the registered output file; a stateless offset read, with no pin or release | `{taskId, cursor, limit}` | `{text, bytes, nextCursor?, truncated}` | The caller drops the call; the read stops | `unknown`, `unavailable`, `invalid_limit`, `closed` | -| `wait` | Wait until the task's terminal is dispatched | `{taskId, timeoutMs}` | `{terminal}` | The caller drops the call; the wait releases and nothing changes | `unknown`, `timeout`, `closed`, `cancelled` | -| `stop` | Cancel a running task and answer its terminal | `{taskId}` | `{terminal}` | None: an admitted stop settles | `unknown`, `closed` | +| `adopt` | Take over supervision of a command the host started | `{taskId, description, title?, outputPath}` | `()` | The caller drops the call: nothing was adopted, and the host's process is killed | `closed`, `unknown_task` (the host has no live task with this id), `failed` (the `exec/started` fact could not be committed; nothing was adopted and the process is killed) | +| `output` | The running task's tail preview | `{taskId}` | `String` | The caller drops the call; the read stops | `unknown` (no such task, or the task has ended), `closed` | +| `output_page` | One bounded page of the registered output file; a stateless offset read, with no pin or release | `{taskId, cursor, limit}` | `OutputPage` | The caller drops the call; the read stops | `unknown`, `unavailable`, `invalid_limit`, `read` (the task facts could not be read or are inconsistent), `closed` | +| `wait` | Wait until the task's terminal is dispatched | `{taskId, timeoutMs}` | `ExecEndedData` | The caller drops the call; the wait releases and nothing changes | `unknown`, `timeout`, `read`, `closed`, `cancelled` | +| `stop` | Cancel a running task and answer its terminal | `{taskId}` | `ExecEndedData` | None: an admitted stop settles | `unknown`, `read`, `closed` | -`nextCursor` is present only for a full page; a client advances by `bytes`. `wait` with `timeout_ms = 0` answers `timeout` for a running task and the terminal for an ended one. `stop` on an ended task answers its terminal and changes no wake. +`next_cursor` is present only for a full page; a client advances by `bytes`. `wait` with `timeout_ms = 0` answers `timeout` for a running task and the terminal for an ended one. `stop` on an ended task answers its terminal and changes no wake. Replies are positional. ### Errors -| Kind | Operation | What the caller does next | -| --- | --- | --- | -| `unknown_task` | `adopt` | The host has no such task; nothing was adopted and the command is not supervised. | -| `unknown` | `output`, `output_page`, `wait`, `stop` | This line has no such task; do not retry. | -| `unavailable` | `output`, `output_page` | The registered file is gone (cleaned or its Session deleted); report the loss, do not retry. | -| `invalid_limit` | `output_page` | Use a limit of at least one byte. | -| `timeout` | `wait` | The task is still running; wait again or stop it. | -| `cancelled` | `wait` | The caller's token ended the wait; nothing changed. | -| `closed` | any | The generation is closing or reloading; a replacement generation serves. | +| Kind | Operation | Retryable | What the caller does next | +| --- | --- | --- | --- | +| `unknown_task` | `adopt` | No | The host has no such task; nothing was adopted and the command is not supervised. | +| `unknown` | `output`, `output_page`, `wait`, `stop` | No | This line has no such task; do not retry. `output` also answers `unknown` for an ended task, whose file stays readable by `output_page`. | +| `unavailable` | `output_page` | No | The registered file is gone (cleaned or its Session deleted); report the loss, do not retry. | +| `invalid_limit` | `output_page` | No | Use a limit of at least one byte. | +| `read` | `output_page`, `wait`, `stop` | Yes | The task facts could not be read or are inconsistent; retry the read; if it persists, the task's record is damaged and the caller reports a fault. | +| `timeout` | `wait` | Yes | The task is still running; wait again or stop it. | +| `failed` | `adopt` | Yes, by the exec tool retrying the launch | The `exec/started` fact could not be committed; nothing was adopted; the process is killed. | +| `cancelled` | `wait` | No | The caller's token ended the wait; nothing changed. | +| `closed` | any | No, in this generation | The generation is closing or reloading; a replacement generation serves. | ### Flows @@ -107,14 +110,26 @@ The host's process-by-id operations are not defined yet; they are stated in Requ | --- | --- | --- | --- | --- | --- | | `adopt` | Take the Session hold, write `exec/started`, spawn the supervision task, answer the id | Before `exec/started` is committed: nothing adopted; the host's process is killed | Nothing to release; the task is the line's | A reload refuses new adoptions and ends running tasks as stopped; an unfinished command gets a failed terminal | BackgroundExec for the task and the hold; the host for the process | | supervision task | The host reports the process's end; write `exec/ended`, release the Session hold, wake the line unless the end is `cancelled` | — | — | The owner's unload cancels the task, kills the process and writes the cancelled terminal | BackgroundExec for the facts; the host for the process | -| `output`, `output_page` | Open the registered file, read the tail or one page, answer | The read stops; nothing changes | — | Pending reads answer `closed` | BackgroundExec | +| `output` | Answer the running task's artifact tail; an ended task is `unknown` | The read stops; nothing changes | — | Pending reads answer `closed` | BackgroundExec | +| `output_page` | Open the registered file, read one page at the cursor, answer; works for running, ended and reloaded tasks | The read stops; nothing changes | — | Pending reads answer `closed` | BackgroundExec | | `wait` | Answer at once for an ended task; otherwise wait for the dispatched terminal | The wait releases; no state changes | — | Pending waits answer `closed` | BackgroundExec | | `stop` | Cancel the supervision, ask the host to kill the process, write the cancelled terminal, answer it | — | — | A stop in flight settles before the generation closes | BackgroundExec for the terminal; the host for the process | +| Load | Fold `exec/started` and `exec/ended` at one cutoff into the task table; write failed terminals for unfinished commands; post the wakes the previous generation lost | — | — | — | BackgroundExec | + +## Client-visible changes + +The published `backgroundExec` face ([WorkspaceTools plugin page](../../architecture/rust-agent/plugins/WorkspaceTools.md#data-face)) keeps `output`, `output_page`, `wait` and `stop` with their published shapes, and `start` stays off the face. The changes, which the maintainer is asked to confirm: + +- `adopt({taskId, description, title?, outputPath})` is new (additive); the exec tool uses it after the host starts the process. +- Error codes change case with the standard binding spelling: `invalidLimit` becomes `invalid_limit`; `read` is kept; `unknown_task`, `failed` and `cancelled` are new. +- `output` keeps its published promise: a running task's live tail preview, `unknown` once the task ends; `output_page` keeps reading the registered file for every state. +- No client RPC, notification name, request field or model-visible text changes. ## Exceptions with reasons - The registered output file's bytes are produced by the process, while the artifact reference and every read belong to this owner: the path is fixed in `exec/started`, the process only appends, and a read opens and closes within one call, so no file handle crosses an owner. - Each command's `exec/started` and `exec/ended` have exactly one writer: this owner for the tasks it adopts, and ShellSession for its PTY commands, which appear in `exec/started` without an adopting caller; this owner consumes those terminals for the notices and recovery. +- A historical task's `output_page`, `wait` and `stop` answer from the rebuilt table and the registered file; no historical task cache is kept beyond the table. ## Supersedes @@ -127,16 +142,17 @@ The host's process-by-id operations are not defined yet; they are stated in Requ Flow tests on the owner: - A command moved to the background ends once, its terminal is written once, and the line wakes once; a stop cancels it without a wake; a branch close cancels it without a wake. -- A reload writes failed terminals for unfinished commands, posts the wakes the previous generation lost, and refuses a new adoption; a Session close settles the hold. -- The tail preview and its pages read the registered file in every state of the task; a page's cursor advances by its bytes; a limit of zero is `invalid_limit`; a deleted file is `unavailable`. -- `wait` answers an ended task at once, times out for a running task, and releases when dropped; an unknown task is `unknown` on every operation. +- A reload writes failed terminals for unfinished commands, rebuilds every ended task with its output path, posts the wakes the previous generation lost, and refuses a new adoption; a Session close settles the hold. +- A historical task answers `output_page` and `stop` after a reload; `output` is `unknown` for it; `wait` answers its terminal at once. +- The tail preview and the pages read the artifact in every state of the task; a page's cursor advances by its bytes; a limit of zero is `invalid_limit`; a deleted file is `unavailable`; a failed task-fact read is `read`. +- `wait` answers an ended task at once, times out for a running task, and releases when dropped or cancelled; `adopt` answers `unknown_task` for an id the host does not have and `unknown` answers the other operations for a task this line does not know. - The face and the Rust call answer the same previews, pages, terminals and errors. ## Rule check | Rule | Application | | --- | --- | -| §1 parts and Capabilities | BackgroundExec is one branch part and a Capability: it injects `dispatcher` and `timeline`, writes its adopted tasks' `exec/started`/`exec/ended` and folds the terminals; ShellSession writes its own commands' facts, as the exception states. | +| §1 parts and Capabilities | BackgroundExec is one branch part and a Capability: it injects `dispatcher` and `timeline`, writes its adopted tasks' `exec/started`/`exec/ended` and folds them at load; ShellSession writes its own commands' facts, as the exception states. | | §2 scopes | Branch: a task belongs to the line that started it; the process belongs to the host's process owner. | | §3 orthogonality | The host's process, the Session's hold and the guide table are other owners' operations; no state is read directly. | | §4 rule 1 | A stop and a close cancel the task; the owner writes the terminal. | @@ -158,16 +174,18 @@ Flow tests on the owner: | ADR 002 D3 | Depends on the host's process owner and Session capabilities; nothing depends on BackgroundExec's internals. | | ADR 002 D4 | No configuration. | | ADR 002 D5 | Language-neutral operations and data. | +| ADR 027 | The Session's `session.exec.output*` methods reach a line's BackgroundExec by line id (`line_owner::(line)`); the task id stays in the request. | ## Requirements raised to mechanism owners -- **HostPlatform ([#2032](https://github.com/arcships/dim/issues/2032)).** The process owner must expose a started process by task id: `spawn(...) → {taskId}`, `wait({taskId}, cancelled)`, `kill({taskId})`, `settle({taskId})`, and settle its task table on close or reload. BackgroundExec adopts that id and never receives a process object. Until the host's id operations land, this board's `adopt` and `stop` cannot be implemented; the other owners' contracts are independent. -- **SessionScope ([#2093](https://github.com/arcships/dim/pull/2093)).** `hold` returns the lease id, `release` ends it early, and `activated`/`closing` gate the watcher. +- **HostPlatform ([#2032](https://github.com/arcships/dim/issues/2032), target).** The process owner must expose a started process by task id: `spawn(...) → {taskId}`, `wait({taskId}, cancelled)`, `kill({taskId})`, `settle({taskId})`, and settle its task table on close or reload. BackgroundExec adopts that id and never receives a process object. Until the host's id operations land, this board's `adopt` and `stop` cannot be implemented; the other owners' contracts are independent. +- **SessionScope ([#2093](https://github.com/arcships/dim/pull/2093), target).** `hold` returns the lease id, `release` ends it early, and `activated`/`closing` gate the watcher. +- **Cross-scope mechanism ([#2127](https://github.com/arcships/dim/issues/2127), target).** The Session's exec output methods reach a line's owner by line id per ADR 027; this owner states the operations, not the mechanism. - **None other.** No Timeline, Dispatcher, loader or runtime change. ## Binding appendix -The service is marked on the owner type; the name stays `backgroundExec`. `ExecEndedData` and `ExecStatus` are `dim_agent_types` values. +The service is marked on the owner type; the name stays `backgroundExec`. `ExecEndedData` is a `dim_agent_types` value. ```rust use crate::host::CancelledFn; @@ -175,7 +193,7 @@ use dim_agent_runtime::PublicService; use dim_agent_types::ExecEndedData; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct AdoptRequest { pub task_id: String, pub description: String, @@ -185,7 +203,7 @@ pub struct AdoptRequest { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct OutputPageRequest { pub task_id: String, pub cursor: u64, @@ -203,14 +221,14 @@ pub struct OutputPage { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct WaitRequest { pub task_id: String, pub timeout_ms: u64, } -#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "snake_case")] +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum BackgroundError { #[error("the host has no live task with this id")] UnknownTask, @@ -220,10 +238,14 @@ pub enum BackgroundError { Unavailable, #[error("limit must be at least 1")] InvalidLimit, + #[error("the task facts could not be read: {reason}")] + Read { reason: String }, #[error("the task did not end before the timeout")] Timeout, #[error("the background exec service is closing")] Closed, + #[error("the task could not be adopted: {reason}")] + Failed { reason: String }, #[error("the wait was cancelled")] Cancelled, } diff --git a/docs/design/plugins/FileReads.md b/docs/design/plugins/FileReads.md index dba2853fc4..74882bcdfa 100644 --- a/docs/design/plugins/FileReads.md +++ b/docs/design/plugins/FileReads.md @@ -15,6 +15,8 @@ FileReads owns: FileReads does not open, read or write files: the file tools own path resolution and the bytes. FileReads does not decide whether a call is admitted: Permission and Approval do. +Targets: the line access is [ADR 027](https://github.com/arcships/dim/pull/2029) with the mechanism obligation [#2127](https://github.com/arcships/dim/issues/2127); the file-tool codec's mapping is a requirement on its owner (target, pending [#2103](https://github.com/arcships/dim/pull/2103)). + Callers keep as business: - Which file a tool touches, its encoding override, and the tool's own result text. @@ -31,34 +33,35 @@ An operation exists only where its row says No. ## Caller example -The `write` tool asks before replacing an existing file, then records the operation it performed: +The file tool resolves the path first, then asks and records with that canonical path: ```rust +let canonical = resolve(request.path)?; // the tool's own resolution let binding = reads.binding(BindingRequest { - path: display.clone(), + path: canonical.clone(), purpose: Purpose::Write, -}).await?; // Closed; the value says whether a binding is usable -match binding.binding { - Some(binding) => { /* preserve encoding and line endings; check the revision */ } - None => { - let reason = binding.unavailable.expect("one of binding or unavailable"); +}).await?; // Closed, Failed +match binding { + BindingReply::Bound(binding) => { /* preserve encoding and line endings; check the revision */ } + BindingReply::Unavailable(reason) => { return Ok(text_binding_required(reason)); // the model re-reads or edits } } // ... write the bytes ... reads.record(RecordRequest { - path: canonical.clone(), + path: canonical, binding: new_binding, established, -}).await?; // Closed +})?; // Closed, Failed ``` The `edit` tool asks with the edit purpose, which ignores compaction: ```rust -let binding = reads.binding(BindingRequest { path: display, purpose: Purpose::Edit }).await?; -let Some(binding) = binding.binding else { - return Ok(text_binding_required(binding.unavailable.expect("read first"))); +let reply = reads.binding(BindingRequest { path: canonical, purpose: Purpose::Edit }).await?; +let binding = match reply { + BindingReply::Bound(binding) => binding, + BindingReply::Unavailable { reason } => return Ok(text_binding_required(reason)), }; ``` @@ -76,26 +79,27 @@ FileReads injects no other service. The Session's file tools reach this owner by | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `binding` | Whether a file may be replaced or edited, and on which binding | `{path, purpose}` | `{binding?}` or `{unavailable: never_read\|compacted}` | None; the owner completes the read | `closed` | -| `record` | Note the binding an operation established, at the sequence the operation started | `{path, binding, established}` | `{}` | None | `closed` | +| `binding` | Whether a file may be replaced or edited, and on which binding | `{path, purpose}` | `BindingReply` | None; the owner completes the read | `closed`, `failed` | +| `record` | Note the binding an operation established, at the sequence the operation started | `{path, binding, established}` | `()` | None | `closed`, `failed` | -`purpose` is `write` or `edit`; it selects the owner's rule, and a caller never evaluates compaction itself. `binding` is the value the file tool preserves: revision, encoding, encoding source, byte-order mark and line endings. `established` is the line's sequence when the operation started, taken by the caller after the call's fact committed; the owner compares it with the completed compaction's cut. +`path` is the canonical path the file tool resolved; the owner keys bindings by it. `purpose` is `write` or `edit`; it selects the owner's rule, and a caller never evaluates compaction itself. `binding` is the value the file tool preserves; `established` is the line's sequence when the operation started, taken by the caller after the call's fact committed; the owner compares it with the completed compaction's cut. ### Errors -| Kind | Operation | What the caller does next | -| --- | --- | --- | -| `closed` | `binding`, `record` | The line is closing or unloading; the tool call ends; the replacement generation rebuilds the bindings from the facts. | +| Kind | Operation | Retryable | What the caller does next | +| --- | --- | --- | --- | +| `closed` | `binding`, `record` | No, in this generation | The line is closing or unloading; the tool call ends; the replacement generation rebuilds the bindings from the facts. | +| `failed` | `binding`, `record` | Yes, by a later attempt | The line's facts could not be read or the binding could not be stored; nothing was decided or written; the owner reports a fault and the tool call ends. | -"Never read" and "compacted" are values, not errors: the file tool turns either into the model-facing `text_binding_required` result, and the model's next step is to re-read or edit. +"Never read" and "compacted" are values, not errors: the file tool turns either into the model-facing `text_binding_required` result, and the model's next step is to re-read or edit. A caller that matches the reply by hand does not fall through: every reply is one of the two variants. ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `binding` | Read the map; for `write`, check the latest completed compaction after the binding's sequence and whether the cut event still lies after it | None; the read is bounded | Nothing to release | Refused with `closed` | FileReads | -| `record` | Replace the path's binding with the new one and its sequence | None | Nothing to release | The new generation rebuilds from the facts; a record not yet committed is lost with the generation | FileReads | -| Load | Read the line's committed file-tool results at one cutoff, take each result's binding and its event sequence, and keep the latest per path | — | — | — | FileReads | +| `record` | Replace the canonical path's binding with the new one and its sequence | None | Nothing to release | The new generation rebuilds from the facts; a record not yet committed is lost with the generation | FileReads | +| Load | Read the line's committed file-tool results at one cutoff, map each result's binding and its event sequence, and keep the latest per path | — | — | — | FileReads | The rebuild uses the result event's sequence: no legal compaction cut separates a call from its result, so the result's position is equivalent to the operation's start for the context rule. @@ -114,9 +118,10 @@ The rebuild uses the result event's sequence: no legal compaction cut separates Flow tests on the owner: - A read binds a file; a `write` after a compaction that cut the read out is refused with `compacted`; a compaction that kept the read leaves the write admitted; an `edit` proceeds after either. -- A write's binding replaces the read's for later operations; a failed offload does not bind. +- A write's binding replaces the read's for later operations, keyed by the canonical path; a failed offload does not bind. - After a reload, the bindings are rebuilt from the line's facts and an existing file can be written without a new read; a file whose read a compaction cut out before the reload stays unavailable for `write`. -- The face and the Rust call answer the same binding or reason. +- A failed fact read answers `failed`; a closed line answers `closed`. +- The face and the Rust call answer the same reply variants and errors. ## Rule check @@ -144,10 +149,12 @@ Flow tests on the owner: | ADR 002 D3 | No dependency on callers; a composition without the file tools has no bindings. | | ADR 002 D4 | No configuration. | | ADR 002 D5 | Language-neutral operations and data. | +| ADR 027 | The file tools reach a line's FileReads with `line_owner::(line)`; the path and purpose stay in the request. | ## Requirements raised to mechanism owners -- **Session access ([#2025](https://github.com/arcships/dim/issues/2025)).** A Session part resolves a line's owner by line id: the mechanism named in [TimelineTree's route (#2092)](https://github.com/arcships/dim/pull/2092). The file tools use it to reach `binding` and `record`; FileReads adds no forwarding operation. +- **Cross-scope access ([ADR 027](https://github.com/arcships/dim/pull/2029), [#2127](https://github.com/arcships/dim/issues/2127), target).** A Session part reaches a line's data face by line id with `line_owner::(line)`. The file tools use it to reach `binding` and `record`; FileReads adds no forwarding operation. +- **File-tool codec ([#2103](https://github.com/arcships/dim/pull/2103), target).** The codec's `TextEncoding`, `EncodingSource`, `Bom`, `Eol` and `TextFileBinding` are not wire data (`TextEncoding::Legacy` holds an `encoding_rs` reference and `raw_revision` is `[u8; 32]`). The codec owner provides the mapping to the DTOs below: the encoding label (`utf-8`, `utf-16le`, `utf-16be`, or the requested legacy name lowercased), the revision as lowercase hex, and the three enums as their snake-case names; or derives serde on them with the same wire values. This owner does not change the codec. - **None other.** No Timeline, Dispatcher, loader or runtime change. ## Binding appendix @@ -165,22 +172,52 @@ pub enum Purpose { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct BindingRequest { + /// The canonical path the file tool resolved. pub path: String, pub purpose: Purpose, } -#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct TextFileBinding { - pub revision: String, // SHA-256 of the raw bytes, lowercase hex - pub encoding: TextEncoding, + /// Lowercase hex of the SHA-256 of the raw file bytes. + pub revision: String, + /// The codec's label: "utf-8", "utf-16le", "utf-16be", or the requested + /// legacy name lowercased. + pub encoding: String, pub encoding_source: EncodingSource, pub bom: Bom, pub eol: Eol, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum EncodingSource { + Bom, + User, + Utf8Policy, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Bom { + None, + Utf8, + Utf16Le, + Utf16Be, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Eol { + None, + Lf, + Crlf, + Mixed, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum Unavailable { @@ -189,27 +226,28 @@ pub enum Unavailable { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct BindingReply { - #[serde(skip_serializing_if = "Option::is_none")] - pub binding: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub unavailable: Option, +#[serde(rename_all = "camelCase", tag = "kind")] +pub enum BindingReply { + Bound { binding: TextFileBinding }, + Unavailable { reason: Unavailable }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct RecordRequest { + /// The canonical path the file tool resolved. pub path: String, pub binding: TextFileBinding, pub established: u64, } -#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "snake_case")] +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum FileReadsError { #[error("the line is closing")] Closed, + #[error("the binding could not be read or stored: {reason}")] + Failed { reason: String }, } impl PublicService for FileReads {} @@ -220,5 +258,3 @@ impl FileReads { pub fn record(&self, request: RecordRequest) -> Result<(), FileReadsError> { /* ... */ } } ``` - -`TextEncoding`, `EncodingSource`, `Bom` and `Eol` are the existing value types of the file-tool codec ([codec.rs](../../../crates/dim-agent-capabilities/src/workspace_tools/files/codec.rs)); they cross as data and stay defined beside the codec, not here. diff --git a/docs/design/plugins/Hooks.md b/docs/design/plugins/Hooks.md index 7f10a66063..55db028813 100644 --- a/docs/design/plugins/Hooks.md +++ b/docs/design/plugins/Hooks.md @@ -23,7 +23,7 @@ Each hook point was checked against what its owner exposes on `main`: | Hook point | Owner today | Gap | Resolution | | --- | --- | --- | --- | | `PreToolUse` | `Approval::admit(AdmitCall {source, call}, risk, cancel)` calls `Permission::decide(call, risk, cancel)` for the admission and again for the recheck after an allow; `decide` already awaits the command-rules port; a Deny becomes `HostError::failed(reason)`, the error text of the call's result | `decide` cannot ask anyone else, does not receive `source` (the call id is only in `AdmitCall.source`), and cannot tell the admission from the recheck | A.6.1: Approval passes `source` to the admission decision only; Permission calls its registered advisors there. ToolExecutor needs no change | -| `PermissionRequest` | `approval/request {approval_id, source, call, reason}`; `Approval::respond(approval_id, decision)` accepts the first consumed response, else `Unknown`/`Cancelled`/`Closed`; `approval/respond {approval_id, decision}` has no reason | No reason on a deny | Usable as is; a hook deny shows Approval's generic text (decision 7) | +| `PermissionRequest` | `approval/request {approval_id, source, call, reason}`; `Approval::respond(approval_id, decision)` accepts the first consumed response, else `Unknown`/`Cancelled`/`Closed`; `approval/respond {approval_id, decision}` has no reason | The target renames the operation to `approval.decide(approvalId, decision)` ([Approval](../plugins/Approval.md)); the fact and the client method keep their names | `decision` accepts the first consumed answer, else `unknown`; a hook deny shows Approval's generic text (decision 7) | | `UserPromptSubmit` | Rpc `session.submit {sessionId, submissionId?, branchId?, text? \| user?, mode?}` builds `InputMessageData` and calls `Session::input`; Rpc `session.branch_create {sessionId, parentBranchId, at, prompt}` creates a host branch whose first Queue input is the prompt, as the operator's words (TimelineTree `first_input`); InputQueue's `session.input.withdraw {…, steer?}` follows [Session access A.4](../contracts/session-access.md#a4-withdrawal). Other inputs (Goal, Scheduler, Collaboration, ShellInput, Hooks) enter through `Branch::input` from their owners | No entry asks anyone before writing. An input with `user` content whose first raw block is a `` marker reads as a source input (Goal A5), and history renders raw blocks before the user content, so context cannot be a raw block of the operator's input | A.6.2: the three entries call the checks registered with `submitChecks` first and append the returned context to the input's `user` content after the operator's own content, so the input stays operator input and needs no history or convention change | | `PostToolUse(Failure)` | `step/tool-result {turn_id, request_id, call_event_id?, results: [{call_id, result}]}`, `ToolResult.is_error` | None | Dispatcher subscription | | `Stop` | `turn/end {turn_id, status: completed \| failed \| cancelled}` | None | Dispatcher subscription, `completed` only | @@ -65,7 +65,7 @@ flowchart LR Rpc -->|"registered checks before Session::input or the branch"| HS IM -->|"registered checks before the withdrawal command"| HS HB --> HS - HB -->|"permission.registerAdvice(hooks)"| PM + HB -->|"permission.advise(hooks)"| PM AP -->|"admission decision with source"| PM PM -->|"registered advisors, at each admission"| HB HB -->|"respond(approval_id, decision)"| AP @@ -86,7 +86,7 @@ flowchart LR **Node.** On an offline resource node, spawning fails with `node_unavailable`; each hook point treats that as a hook failure (Appendix C). -**Contracts depended on:** `Approval::admit` and `AdmitCall.source`, `Permission::decide` and `permission.registerAdvice` (A.6.1); `Approval::respond` and the `approval/request`, `approval/respond`, `approval/cancelled` facts; Rpc `session.submit` and `session.branch_create`, and InputQueue's `session.input.withdraw {steer}`, with the Session table `submitChecks` (A.6.2); `InputMessageData.user` (context appended after the operator's own content); `step/tool-result`, `turn/start`, `turn/end`, `stop/interrupt`, `context/configured` (read only); source input conventions ([session access A.2](../contracts/session-access.md#a2-source-input-conventions)); Settings `BusinessDocument`, `settings.changed` and the authorized project root; FileStorage reads; App Server `ManagementMethods`; HostPlatform `build_process_spec`, process supervision and a process start whose stdin carries the given bytes (A.6.3). **Contracts defined here:** the hook document format, the command protocol, the advice and check replies of Hooks' `hooks` registrations, the `hooks.*` methods, `HookSources`, source name `hooks` (marker `dim-hooks`, key namespace `hooks:`). Hooks declares no event. +**Contracts depended on:** `approval.admit` and the call's `source`, `permission.decide` with that source and `permission.advise` (A.6.1; target contracts [Approval](../plugins/Approval.md), [Permission](../plugins/Permission.md)); `approval.decide` and the `approval/request`, `approval/respond`, `approval/cancelled` facts; Rpc `session.submit` and `session.branch_create`, and InputQueue's `session.input.withdraw {steer}`, with the Session table `submitChecks` (A.6.2); `InputMessageData.user` (context appended after the operator's own content); `step/tool-result`, `turn/start`, `turn/end`, `stop/interrupt`, `context/configured` (read only); source input conventions ([session access A.2](../contracts/session-access.md#a2-source-input-conventions)); Settings `BusinessDocument`, `settings.changed` and the authorized project root; FileStorage reads; App Server `ManagementMethods`; HostPlatform `build_process_spec`, process supervision and a process start whose stdin carries the given bytes (A.6.3). **Contracts defined here:** the hook document format, the command protocol, the advice and check replies of Hooks' `hooks` registrations, the `hooks.*` methods, `HookSources`, source name `hooks` (marker `dim-hooks`, key namespace `hooks:`). Hooks declares no event. ## 2. Data and state @@ -267,9 +267,9 @@ The model never sees hook configuration, commands, exit codes, diagnostics, a `U | Interface | Kind | Purpose | | --- | --- | --- | -| Advisor `hooks` (`permission.registerAdvice`) | Registered by `HooksBranch` with the branch's Permission while it runs; Permission calls it at each admission (A.6.1) | `PreToolUse` decision | +| Advisor `hooks` (`permission.advise`) | Registered by `HooksBranch` with the branch's Permission while it runs; Permission calls it at each admission (A.6.1) | `PreToolUse` decision | | Check `hooks` (`submitChecks.register`) | Registered by `HooksSession` with the Session's `submitChecks` (InputQueue) while it runs; the operator-input entries call it before writing (A.6.2) | `UserPromptSubmit` decision, and the warnings a failed run leaves | -| `Approval.respond` | Existing branch service | `PermissionRequest` outcome | +| `approval.decide` | Existing branch service | `PermissionRequest` outcome | | `input_blocked` | Rpc app error of `session.submit`, `session.branch_create` and `session.input.withdraw`; message `Hook : ` | A blocked submission | | `warnings` | Additive optional field of the `session.submit` and `session.branch_create` replies and of the `session.input.withdraw` reply; each element is `{check, message}` | Work a check did not do (A.6.2) | | `hooks.catalog`, `hooks.save`, `hooks.set_enabled` | App Server management methods (namespace `hooks`), like `mcp.*` | Effective hooks, user document writes, project enablement (A.7) | @@ -298,7 +298,7 @@ Rules: [principles §1 and §4](../../architecture/rust-agent/principles.md), [A | §4.4 No business meaning in core | Timeline, Dispatcher and before are unchanged; Permission's advisors and the Session's `submitChecks` are generic registrations with no Hooks semantics. | | §4.5 Read the whole batch | Observation hooks and rechecks run after the whole triggering batch; `PostToolUse(Failure)` writes one input per result batch. | | §4.6 Context only from handed-off events | A blocked submission is never written; prompt context enters as part of the adopted operator input; deny reasons enter through ToolExecutor's result; other output enters as adopted Hooks inputs. | -| §4.7 Public events and services only | Hooks reads public events and calls `Approval.respond` and `Branch::input`; Permission and the entries call the advisors and checks registered with them. No internal state is read. | +| §4.7 Public events and services only | Hooks reads public events and calls `approval.decide` and `Branch::input`; Permission and the entries call the advisors and checks registered with them. No internal state is read. | | §4.8 Infrastructure unchanged | No change to Timeline, Dispatcher, envelope, assembly, lifecycle or facades. Needs from business owners are in A.6 in this rule's format. | | §4.9 Only decision facts in the Timeline | Hooks adds no event type or snapshot. The necessary Stop input carries its continuation round in an existing envelope tag (§3.5); configuration lives in Settings, diagnostics in the catalog. | | §1 Capability and App Server boundary | `HooksSession` and `HooksBranch` are Capabilities in their own crate; `HooksSettings` lives in App Server next to Settings, like MCP's management, and binds `HookSources`. | @@ -306,14 +306,14 @@ Rules: [principles §1 and §4](../../architecture/rust-agent/principles.md), [A | ADR 002 D2 No wiring modules | Hooks attaches to owners through their own registrations and services; `HookSources` is the agent-side port of Hooks' own configuration owner, not an adapter for others. | | ADR 002 D3 Dependencies | Hooks depends on core parts (Approval, Permission, InputQueue's `submitChecks`, Timeline) and registers with them; Permission and the entries depend on no advisor or check and work without Hooks. | | ADR 002 D4 Configuration | Hook documents and enablement are business data in Settings sources, read at use; no reload. | -| ADR 002 D5 Language-neutral contracts | Document format, command protocol, `permission.registerAdvice`, `submitChecks`, `HookSources` and `hooks.*` are neutral; Rust binding is Appendix H. | +| ADR 002 D5 Language-neutral contracts | Document format, command protocol, `permission.advise`, `submitChecks`, `HookSources` and `hooks.*` are neutral; Rust binding is Appendix H. | | AGENTS 11 / ADR 003 | Hook commands need no approval and run when enabled; the project source starts disabled and only the user-local `hooks-projects` enables it; Approval and Permission keep governing only tool calls, and `allow` advice is authority from user-enabled configuration (§7). | ## 9. Requirements raised to mechanism owners None to the runtime or rutis: Hooks needs no infrastructure change, new event type, schema, query operation or service. It needs three generic capabilities from their owners, stated in A.6 in the five items of §4 rule 8 and listed in [overview Appendix B.1](../overview.md#b1-session-and-branch-capabilities): -- Permission and Approval: advisors registered with the branch's Permission (`permission.registerAdvice`) and called during the admission decision, with Approval passing the call's `source` (A.6.1). +- Permission and Approval: advisors registered with the branch's Permission (`permission.advise`) and called during the admission decision, with Approval passing the call's `source` (A.6.1). - InputQueue (the Session table `submitChecks` and `InputMethods` for `session.input.withdraw {steer}`), Rpc (`session.submit`, `session.branch_create`) and the native CLI: checks registered with `submitChecks` and called before operator input is written, the `input_blocked` error, and its place among the `session.submit` errors that guarantee nothing was committed (A.6.2). - HostPlatform: a process start whose stdin receives the given bytes and is then closed (A.6.3). @@ -501,7 +501,7 @@ Context and reasons are each at most 16 KiB per hook. Fields Dim does not suppor | --- | --- | | Blocked by | §4 rule 3 forbids waiting in a before callback, and rule 8 keeps Timeline unchanged, so a `PreToolUse` command cannot hold `step/tool-call`. Rule 7 forbids deciding for Permission. Permission is the owner of "may this call run" for every call, including calls its preset allows without asking. Today `Permission::decide(call, risk, cancel)` asks only its command-rules port, receives no call identity, and is called identically for the admission and for Approval's recheck after an allow. | | Existing mechanisms considered | Async before on `step/tool-call` (withdrawn, #21); a Dispatcher subscription to `step/tool-call` (runs after the handoff to ToolExecutor, races execution, rule 2); answering `approval/request` (only exists for calls that already ask); `CommandRules` (one Session port bound by the profile, only for commands of `execute_process` calls, and it decides by static rules). Registration with an owner, as tools register with ToolRegistry ([rutis usage R6](../rutis-usage.md#r6-contributions-register-with-their-owner)): reused for the advisors. | -| Generic capability | Approval's `admit` passes `AdmitCall.source` to Permission for the admission decision; the recheck stays a plain `decide`. Permission keeps the branch's advisors. A branch part registers an advisor with the branch's Permission while it runs: `permission.registerAdvice(name, advise)`. The registration belongs to the calling part and is withdrawn when it unloads; a second advisor of the same name fails. `HooksBranch` registers `hooks`. In the admission decision, after policy and command rules and only when the result is not Deny, Permission calls each advisor registered at that moment, in name order: `advise {source, name, input, risk, decision: "allow" \| "ask"}` → `{advice: "none" \| "allow" \| "ask" \| "deny", reason?}` (async; cancellation = Permission drops the call). Any deny → `Deny {reason}`; else any ask → `Ask {reason}`; else any allow → `Allow`; else Permission's own decision. A provider error counts as `none`. Permission depends on no advisor; `HooksBranch` depends on Permission. No business meaning: any branch part may register an advisor. Advice never overrides a Deny, since it is not asked then. ToolExecutor is unchanged: it already puts the call id in `AdmitCall.source`. | +| Generic capability | `approval.admit({source, call, risk}, cancelled)` passes the call's `source` to `permission.decide({call, risk, source}, cancelled)` for the admission; the recheck calls `decide` without a source and asks no advisor. Permission keeps the branch's advisors. A branch part registers an advisor with the branch's Permission while it runs: `permission.advise(&ctx, name, advise)`, a direct callback parameter over `AdviceRequest {source, call, risk, decision: "allow" \| "ask"}` → `Advice {none \| allow \| ask {reason} \| deny {reason}}` (async; cancellation = Permission drops the call). The registration belongs to the calling part and is withdrawn when it unloads; a second advisor of the same name is `duplicate`. `HooksBranch` registers `hooks`. In the admission decision, after policy and command rules and only when the result is not deny, Permission calls each advisor registered at that moment, in name order. Any deny → deny; else any ask → ask; else any allow → allow; else Permission's own decision. An advisor's failure counts as none and its code and message are not forwarded. Permission depends on no advisor; `HooksBranch` depends on Permission. No business meaning: any branch part may register an advisor. Advice never overrides a deny, since it is not asked then. `approval.admit` already carries the call's `source`. | | Effect on sequence, batch, interrupt, reload | Sequence and batch: no new event; a denied call's error text is in ToolExecutor's existing batch result; an allowed call writes no `approval/request`. Interrupt: the batch token cancels the decision and so the advice call. Reload: an advisor withdrawn mid-call has its pending advice dropped, counted as `none`; with no advisor registered, Permission decides from policy and command rules alone. Latency of a call's admission grows by the advice time. | | Owner and issue | Permission and Approval (`dim-agent-capabilities`); [#758](https://github.com/arcships/dim/issues/758) (§10.2). | @@ -586,7 +586,7 @@ The project file is edited in the repository, not through these methods. `hooks- | Unsupported event, handler type or handler field (`args`, `if`) | Listed `unsupported`; never runs | | Branch input rejected (branch closed) | Output dropped; diagnostic | | Timeline query fails | Observation or approval processing faults the Hooks consumer and writes no output; PreToolUse returns the read error through Permission. Hook command `onFailure` does not decide storage errors. | -| `Approval.respond` returns `Unknown`, `Cancelled` or `Closed` | Ignored | +| `approval.decide` returns `unknown`, `failed` or `closed` | Ignored | | `HookSources` read fails | Every source `invalid`; the hook point runs no hooks | | Project file read through FileStorage fails or does not parse | The project source is listed `invalid`; the user source still runs | | Unload with pending checks | Answered by `onFailure` before services are removed | @@ -684,12 +684,12 @@ Codex `apply_patch` has no alias: its input is a patch, while Dim's `write` and | Neutral | Rust | | --- | --- | -| Admission decision | `Permission::admit_decision(call, source: &BranchSource, risk, cancel)` used by `Approval::admit`; `decide` stays for the recheck | -| `permission.registerAdvice` | Trait `AdviseTool` with `advise(ToolAdviceRequest, CancellationToken) -> HostFuture`; `Permission::register_advice(ctx, name, Arc)` on the branch's `Keyed`, kept in a `Registrations` table and withdrawn with the caller; `HooksBranch` registers `hooks`; Permission calls the advisors it holds at each admission (A.6.1) | +| Admission decision | `Approval::admit(AdmitRequest, CancelledFn)` calls `Permission::decide(DecideRequest {call, risk, source}, CancelledFn)`; the recheck calls `decide` with `source: None` | +| `permission.advise` | `Permission::advise(&self, caller: &Ctx, name: String, advise: AdviseFn)` with `AdviseFn = Arc BoxFuture<'static, Result> + Send + Sync>` on the branch's `Keyed`, kept in a `Registrations` table and withdrawn with the caller; `HooksBranch` registers `hooks`; Permission calls the advisors it holds at each admission (A.6.1) | | `submitChecks` | Session service `SubmitChecks`, a name registered in the Session group and a `PublicService`, so Rpc reads it through `Session::session_service::()`; provided by InputQueue's Session part; `SubmitChecks::register(ctx, name, Arc)` with `check(SubmitCheckRequest, CancellationToken) -> HostFuture`, kept in a `Registrations` table and withdrawn with the caller; `HooksSession` registers `hooks` and Skills registers `skills` through `Keyed`; `Connection::submit`, `Connection::create_branch` and `InputMethods` call the registered checks before `Session::input`, `Session::branch` / admitting the withdrawal command (A.6.2) | | `input_blocked` | `RpcError::app(-32000, "input_blocked", message)`; `data` is `{appError}` only | | `warnings` | `SubmitWarning { check: String, message: String }` in `dim_agent_types::input`, serialized as `{check, message}` with no rename; carried by `SubmitResult` and `tree_protocol::CreateResult`, and set on the withdraw reply's `serde_json` object | -| `Approval.respond` | `Approval::respond(approval_id, ApprovalDecision)` from `Keyed` | +| `approval.decide` | `Approval::decide(approval_id: String, decision: ApprovalDecision)` from `Keyed` | | `HookSources` | Session port `HookSourcesHost(Arc)`, bound by App Server as `CommandRules` and `SkillSettingsHost` are | | `hooks`, `hooks-projects`, `hooks-plugins` | `BusinessDocument` types in App Server (`hooks`: `USER_FILE` `hooks.json`, no `PROJECT_FILE`; `hooks-projects`: `USER_FILE` `hooks-projects.json`; `hooks-plugins`: `USER_FILE` `hooks-plugins.json`, one `{dir, hooks}` entry per plugin id, as `McpPluginServers` in `mcp/config.rs`) | | `.dimcode/hooks.json` | Read by `HooksSettings` through `FileStorage::path(root, ".dimcode/hooks.json")` and `read_limited`, `root` from `SettingsService::project_root(cwd)`, parsed into the `hooks` document type | diff --git a/docs/design/plugins/Permission.md b/docs/design/plugins/Permission.md index c172b2da16..674932e9df 100644 --- a/docs/design/plugins/Permission.md +++ b/docs/design/plugins/Permission.md @@ -15,6 +15,8 @@ Permission owns: Permission does not ask the user, run tools, write approval facts or decide the model's declarations. Approval owns the question and the answer; ToolExecutor owns execution; ToolRegistry owns declarations. +Targets: the file-access facts are a target, pending [#2093](https://github.com/arcships/dim/pull/2093); the command rules are a target, pending [#2094](https://github.com/arcships/dim/pull/2094); the creation record is a target, pending [#2093](https://github.com/arcships/dim/pull/2093); the mechanism obligation for cross-scope access is [#2127](https://github.com/arcships/dim/issues/2127). + Callers keep as business: - What an ask means and when it is worth asking: Approval's admission and its recheck. @@ -31,7 +33,7 @@ Callers keep as business: | Update the policy | No: the version check and the fact are one write | `update` | | Register tool advice | No: the registration is bound to the registering part's lifetime and asked by name order | `advise` | -An advisor's failure counts as no advice: its code and message are not forwarded, and the owner decides on its own result. An operation exists only where its row says No. +An operation exists only where its row says No. ## Caller example @@ -42,26 +44,23 @@ let admission = permission.decide(DecideRequest { call: call.clone(), risk: risk.cloned(), source: Some(source.clone()), -}, cancelled.clone()).await?; // Cancelled, Closed +}, cancelled.clone()).await?; // Cancelled, Failed, Closed if admission.outcome == Outcome::Ask && !admission.advisor_question { // ask the user; later, after the answer: let recheck = permission.decide(DecideRequest { call, risk, source: None }, cancelled).await?; } ``` -Hooks registers advice for the lifetime of its branch part; the registration ends with the part: +Hooks registers advice for the lifetime of its branch part; the registration ends with the part. `advise` is synchronous, `caller: &Ctx` is the calling row: ```rust -permission.advise(&ctx, "hooks".into(), Arc::new(HookAdvice { branch: self.clone() })).await?; // Duplicate, Closed +permission.advise(&ctx, "hooks".into(), Arc::new(HookAdvice { branch: self.clone() }))?; // Duplicate, Closed ``` A client updates the policy with the version it read: ```rust -let next = permission.update(UpdateRequest { - expected_version: read.version, - policy: next_policy, -}).await?; // Conflict { current }, Closed +let version = permission.update(UpdateRequest { expected_version: read.version, policy: next_policy }).await?; // Conflict, Failed, Closed ``` ## Own contract @@ -70,45 +69,56 @@ let next = permission.update(UpdateRequest { | Service | Purpose | | --- | --- | -| `S:SessionScope` (Session, [#2093](https://github.com/arcships/dim/pull/2093)) | The creation record's permission preset and working directory. | -| `S:PermissionRules` (Session, [#2094](https://github.com/arcships/dim/pull/2094)) | `permissionRules.rules` answers the user's command rules at decision time. | -| `S:FileAccessFacts` (Session owner, [#2025](https://github.com/arcships/dim/issues/2025)) | `check({access, mode, path})` resolves the call's target and answers the workspace, system, owned and grant facts. | +| `S:SessionScope` (Session, target, pending [#2093](https://github.com/arcships/dim/pull/2093)) | The creation record's permission preset and working directory. | +| `P:PermissionRules` (process, target, pending [#2094](https://github.com/arcships/dim/pull/2094)) | `permissionRules.rules` answers the user's command rules at decision time. | +| `S:FileAccessFacts` (Session, target, pending [#2093](https://github.com/arcships/dim/pull/2093)) | `check({access, mode, path})` resolves the call's target and answers the workspace, system, owned and grant facts. | | `B:Timeline`, `B:Dispatcher` | Fold `permission/changed`; commit an update. | -The file-access facts operation that resolves the target is not defined yet; it is stated in Requirements. +The file-access facts operation that resolves the target is a target of #2093; it is stated in Requirements. ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `decide` | One call's outcome | `{call, risk?, source?}` | `{outcome: allow\|ask\|deny, reason?, advisorQuestion}` | The caller's token stops the facts or advice read; the decision is not made | `cancelled`, `closed` | -| `update` | Versioned policy write | `{expectedVersion, policy}` | `{version}` | None; one commit | `conflict {current}`, `closed` | -| `advise` | Register tool advice for the calling row's lifetime | `caller: &Ctx`, `name`, callback | `{}` | None | `duplicate`, `closed` | +| `decide` | One call's outcome | `{call, risk?, source?}` | `DecisionReply` | The caller's token stops the facts or advice read; the decision is not made | `cancelled`, `failed`, `closed` | +| `update` | Versioned policy write | `{expectedVersion, policy}` | `u64` (the new version) | None; one commit | `conflict`, `failed`, `closed` | +| `advise` | Register tool advice for the calling row's lifetime | `caller: &Ctx`, `name`, callback | `()` | None | `duplicate`, `closed` | | `PermissionState` (published value) | Read the policy and its version | — | `{version, policy}` | None | — | `risk` is the tool owner's declaration (`read_filesystem`, `write_filesystem`, `execute_process`, `network`, `session`, or absent). `source` is present exactly for an admission; the owner asks the advisors only then, and `advisorQuestion` says whether an advisor required an explicit answer, so a policy change can end a policy question but never an advisor's. -The policy is the preset and `allowedTools`/`disallowedTools`. A deny from the tool list, a file fact or a command rule wins over an allow; a command allow turns an ask into an allow for a command without shell separators; an absent `permissions` for a file call means the preset's access. +The policy is the preset and `allowedTools`/`disallowedTools`. A deny from the tool list, a file fact or a command rule wins over an allow; a command allow turns an ask into an allow for a command without shell separators; an absent `permissions` for a file call means the preset's access. Replies are positional. ### Errors -| Kind | Operation | What the caller does next | -| --- | --- | --- | -| `cancelled` | `decide` | The call's batch was cancelled; do not run the call. | -| `closed` | any | The generation is closing or reloading; stop; a later generation serves. | -| `conflict` | `update` | Re-read the version from `PermissionState` and decide whether to retry the update with the new base. | -| `duplicate` | `advise` | The name is taken; pick another or withdraw the first registration. | +| Kind | Operation | Retryable | What the caller does next | +| --- | --- | --- | --- | +| `cancelled` | `decide` | No | The call's batch was cancelled; do not run the call. | +| `failed` | `decide`, `update` | Yes, by a later attempt | A fact or rule read failed, or the `permission/changed` fact could not be committed; nothing was decided or written; the owner reports a fault; `decide`'s caller does not run the call, and `update`'s caller re-reads the version and may retry. | +| `closed` | any | No, in this generation | The generation is closing or reloading; stop; a later generation serves. | +| `conflict` | `update` | Yes, after re-reading | Re-read the version from `PermissionState` and decide whether to retry the update with the new base. | +| `duplicate` | `advise` | No | The name is taken; choose another name. The registration stays until the row unloads. | -An unreadable fact or rule is not an error: the owner denies the call with its reason, because the caller's next step is the same as for any refusal. +An unreadable fact or rule is not a decision: the owner reports `failed`, because the caller's next step is to retry or fail the turn, not to treat the call as denied. An advisor's failure counts as no advice: its code and message are not forwarded, and the owner decides on its own result. ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `decide` | Read the policy, resolve the target and read the facts, read the rules for a command, ask the advisors for an admission, combine and answer | The facts or advice read stops; `cancelled`; nothing changes | The decision's future is the caller's; no resource is held | Refused with `closed`; an in-flight decision ends `closed` | Permission; the facts read by the facts owner | +| `decide` — a fact or rule read fails | Answer `failed`; nothing is decided | — | — | — | Permission | | `update` | Commit `permission/changed` when the expected version matches, answer the new version once dispatched | None | The write is admitted or not; nothing to release | Refused with `closed` | Permission and the Timeline | | `advise` | Register the callback under the name against the calling row | None | The row's unload withdraws the registration | Every registration of the generation is withdrawn | Permission | +## Client-visible changes + +The published `permission` face ([Permission plugin page](../../architecture/rust-agent/plugins/Permission.md#permission-data-face)) publishes `check(call, risk, cancelled) -> {decision} | {decision, reason}` with errors `Failed`/`Cancelled`. It is replaced as follows, and the maintainer is asked to confirm: + +- `check` is removed; `decide({call, risk?, source?}, cancelled)` answers `{outcome: "allow"|"ask"|"deny", reason?, advisorQuestion}`. The admission case (advisors, source) moves into the same operation, so Approval no longer calls two operations. +- `update` and `advise` are new on the face; `PermissionState` keeps its `{version, policy}` shape. +- Error codes change case with the standard binding spelling: `Failed`/`Cancelled` become `failed`/`cancelled`; `conflict` and `duplicate` are new. +- The only caller of `check` is Approval, which this PR migrates; no client RPC, notification name, request field or model-visible text changes. + ## Exceptions with reasons - A branch part registers a callback (`advise`): §7 allows a callback by reference; the owner never calls it inside the Timeline's commit lock, and the calling row's unload withdraws it. @@ -126,7 +136,8 @@ Flow tests on the owner: - Presets decide by risk; `allowedTools` and `disallowedTools` refine the preset and a deny wins; an explicit disallow, a deny rule and a file denial are not lifted by an allow. - A file call asks when its resolved target is outside the workspace; a read or write fact denial refuses the call; a command rule denies under every preset and an allow rule only answers an ask for a simple command. - An admission asks the advisors in name order; an ask refines an allow; a deny wins over an ask and an allow; a recheck asks no advisor; a registration is withdrawn when its part unloads; a second registration of the same name is `duplicate`. -- An update with a stale version is `conflict` with the current version; a dispatched change is visible to the next decision and survives a reload. +- An update with a stale version is `conflict` with the current version; a dispatched change is visible to the next decision and survives a reload; a failed append answers `failed` and writes nothing. +- A failed fact read answers `failed`, not a denial. - The published value's version is the last local change; the face and the Rust call answer the same decision. ## Rule check @@ -134,7 +145,7 @@ Flow tests on the owner: | Rule | Application | | --- | --- | | §1 parts and Capabilities | Permission is one branch part and a Capability: it injects `dispatcher` and `timeline` and folds `permission/changed`. | -| §2 scopes | Branch: a line's policy and decisions; the creation record and the facts are Session state it reads. | +| §2 scopes | Branch: a line's policy and decisions; the creation record and the facts are Session state it reads, the command rules are process state it reads. | | §3 orthogonality | Approval is a separate owner; the facts, rules and Session record are other owners' operations and values. | | §4 rule 1 | A policy update is a command event; the owner writes the outcome fact. | | §4 rule 2 | No handoff. | @@ -152,15 +163,17 @@ Flow tests on the owner: | §7 responsibility split | The caller keeps the question and the turn; the owner keeps the policy, the facts' use and the advisors. | | ADR 002 D1 | Branch scope. | | ADR 002 D2 | No wiring part. | -| ADR 002 D3 | Depends on Session capabilities; nothing depends on Permission's internals. | +| ADR 002 D3 | Depends on Session capabilities (the creation record, the facts) and a process capability (the command rules); nothing depends on Permission's internals. | | ADR 002 D4 | The preset seed comes from the Session's creation record; no separate configuration. | | ADR 002 D5 | Language-neutral operations and data. | +| ADR 027 | Not applicable: the decision is served to the line that runs the call; the facts and rules are reached by their owners' faces. | ## Requirements raised to mechanism owners -- **File access facts ([#2025](https://github.com/arcships/dim/issues/2025)).** The Session owner publishes `check({access, mode, path}, cancelled) → {target, workspace, system, owned, grant, discoveryError?}` ([#2093](https://github.com/arcships/dim/pull/2093)), which resolves the call's path (`~`, cwd, `..`, links) and answers the facts under the effective access; `mode` is the grant mode the call asks for. Permission resolves the facts service at the Session instance; the Session id is not a request field. Errors are `invalid`, `unavailable`, `cancelled` and `closed`; a `discoveryError` is a field, not an error. Permission currently reads the owner's Rust object and a host `home` value; both disappear with this operation. -- **SessionScope ([#2093](https://github.com/arcships/dim/pull/2093)).** `config` is the target's operation; Permission's creation-record read (the preset seed and the working directory) uses it. `identity` is no longer needed: the facts service is Session-bound. -- **Permission rules ([#2017](https://github.com/arcships/dim/issues/2017)).** `permissionRules.rules` ([#2094](https://github.com/arcships/dim/pull/2094)) is the command-rules operation Permission reads; the `commandRules` name is removed. +- **File access facts ([#2093](https://github.com/arcships/dim/pull/2093), target).** The Session owner publishes `check({access, mode, path}, cancelled) → {target, workspace, system, owned, grant, discoveryError?}`, which resolves the call's path (`~`, cwd, `..`, links) and answers the facts under the effective access; `mode` is the grant mode the call asks for. Permission resolves the facts service at the Session instance; the Session id is not a request field. Errors are `invalid`, `unavailable`, `cancelled` and `closed`; a `discoveryError` is a field, not an error. +- **Permission rules ([#2094](https://github.com/arcships/dim/pull/2094), target).** `permissionRules.rules` is the process-scope command-rules read; the `commandRules` name is removed. +- **SessionScope ([#2093](https://github.com/arcships/dim/pull/2093), target).** `config` is the operation; Permission's creation-record read (the preset seed and the working directory) uses it. +- **Cross-scope mechanism ([#2127](https://github.com/arcships/dim/issues/2127), target).** The facts and the rules are reached by their owners' faces; this owner states the operations, not the mechanism. - **None other.** No Timeline, Dispatcher, loader or runtime change. ## Binding appendix @@ -182,7 +195,7 @@ pub enum Outcome { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct DecideRequest { pub call: ApprovalCallData, pub risk: Option, @@ -200,7 +213,7 @@ pub struct DecisionReply { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct UpdateRequest { pub expected_version: u64, pub policy: PermissionPolicy, @@ -248,11 +261,13 @@ pub type AdviseFn = std::sync::Arc< + Sync, >; -#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "snake_case")] +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum PermissionError { #[error("the decision was cancelled")] Cancelled, + #[error("the decision could not be made: {reason}")] + Failed { reason: String }, #[error("the permission service is closing")] Closed, #[error("permission version conflict; current version is {current}")] diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 557cffd22f..5613bfab8c 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -1,6 +1,6 @@ # Plugin designs -Designs of the new plugins and proposed supplements to existing plugins in the [overall design](../overview.md). Local-execution plugins and their capabilities are documented in [architecture/rust-agent/plugins](../../architecture/rust-agent/plugins/README.md). Rules: [design rules](../../architecture/rust-agent/principles.md) §1 and §4, [ADR 002](../../adr/002-plugin-scope.md), [plugin contract](../plugin-contract.md) ([ADR 006](../../adr/006-plugin-contract.md)). Shared contracts: [session-access](../contracts/session-access.md), [session-boundary](../contracts/session-boundary.md). +Designs of the new plugins and proposed supplements to existing plugins in the [overall design](../overview.md). Local-execution plugins and their capabilities are documented in [architecture/rust-agent/plugins](../../architecture/rust-agent/plugins/README.md). Rules: [design rules](../../architecture/rust-agent/principles.md) §1 and §4, [§7 owners and operations](https://github.com/arcships/dim/pull/2029) (target, pending #2029), [ADR 002](../../adr/002-plugin-scope.md), [plugin contract](../plugin-contract.md) ([ADR 006](../../adr/006-plugin-contract.md)). Shared contracts: [session-access](../contracts/session-access.md), [session-boundary](../contracts/session-boundary.md). A plugin is split by the owner of its state into parts, each placed in its owner's scope: the process, a Session or a branch. Which parts are Capabilities ([design rules §1](../../architecture/rust-agent/principles.md)) is stated in each design's Rule check. The columns below are scopes; they do not say which parts are Capabilities. Each document records its design; delivery status lives in the issue. The Phase / issue column is the plan and its tracking issue, not a delivery record. diff --git a/docs/design/plugins/ToolBinding.md b/docs/design/plugins/ToolBinding.md index cfff109ebd..8b7e68478e 100644 --- a/docs/design/plugins/ToolBinding.md +++ b/docs/design/plugins/ToolBinding.md @@ -10,12 +10,14 @@ ToolBinding owns: - **The request record.** One adopted generation per request id: the registry's adoption id, the declarations it was adopted for, and the turn the request belongs to. A request id is bound once; a budget-recovery request takes over the record of the request it retries. - **Pins.** The records whose prefix a later request may still declare, and their release. A pin is a value; the owner releases an adoption when no later prefix can name it. -- **The claims of a request's published calls.** Before the batch fact is appended, ToolBinding asks the registry to register each call's claim; it releases the request's claims when the request's batch result is committed, when the turn ends, or when the generation closes. -- **Settlement.** The record and its claims are settled by the owner from the line's facts: `step/tool-result` for the request's batch, `turn/end` for the turn's requests, and the generation's close. No caller releases on an end path. +- **The claims of a request's published calls.** Before the batch fact is appended, ToolBinding asks the registry to register each call's claim, passing the execution context the contributor's claim callback needs; it releases the request's claims when the request's batch result is committed, when the turn ends, when the caller asks, or when the generation closes. +- **Settlement.** The record and its claims are settled by the owner from the line's facts: `step/tool-result` for the request's batch, `turn/end` for the turn's requests, and the generation's close. `release` only settles a request sooner; no end path depends on a caller calling it. ToolBinding does not execute tools, decide admission, hold a handler or a claim guard. The registry's `adopt`/`release`, `claim`/`release_claims` are the Session-side capability ToolBinding requests; execution, write-target resolution and ordering class belong to the registry's `run`, `resolve_write` and `ordering`. The adopted configuration fact (`context/configured`'s tool part) belongs to Prompt. -**Why the registry and this owner stay separate.** The registry owns the Session's *resolvable generations*: the handlers and the version sets, shared by every line, with freshness from the registry's registrations; an adoption keeps its versions resolvable until released, and its id is bound to the adopting row. ToolBinding owns one line's *request record*: which adoption one request declared, and the claims of its calls, with freshness from that line's Timeline facts; the record ends at the request's terminal fact and the pin ends when a later prefix cannot name it. Merging would put a line's request state in the Session owner (forbidden by [ADR 002 D1](../../adr/002-plugin-scope.md)) or the contributors' handlers in the branch (the contributor's row owns them). The branch-facing interface is therefore ToolBinding's alone: Loop drives `bind`, `claim` and `transfer`, never the registry. +Loop calls ToolBinding for the request record (`bind`, `claim`, `transfer`, `retain_only`, `release`) and calls the registry only for `declarations`, which answers the current host and contributed declarations; that read is the fingerprint's too, and no adoption or claim goes through it. + +**Why the registry and this owner stay separate.** The registry owns the Session's *resolvable generations*: the handlers and the version sets, shared by every line, with freshness from the registry's registrations; an adoption keeps its versions resolvable until released, and its id is bound to the adopting row. ToolBinding owns one line's *request record*: which adoption one request declared, and the claims of its calls, with freshness from that line's Timeline facts; the record ends at the request's terminal fact and the pin ends when a later prefix cannot name it. Merging would put a line's request state in the Session owner (forbidden by [ADR 002 D1](../../adr/002-plugin-scope.md)) or the contributors' handlers in the branch (the contributor's row owns them). The branch-facing interface is therefore ToolBinding's alone. Callers keep as business: @@ -23,14 +25,17 @@ Callers keep as business: - When a request is prepared, retried or abandoned; whether a turn is failed; how a model request's declarations are shaped. - The tool-call batch: which calls a request publishes and when. +Targets: the sibling contracts this design depends on are unmerged. `toolRegistry` is a target, pending [#2103](https://github.com/arcships/dim/pull/2103); `prompt.configure` is a target, pending [#2102](https://github.com/arcships/dim/pull/2102); the mechanism obligation for cross-scope access is [#2127](https://github.com/arcships/dim/issues/2127). + | Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | | Bind a request to the adopted generation its prefix declared | No: the adoption must be released on every path that ends the request, and a caller that held the adoption id would have to release it itself on each error path | `bind` | | Read the adoption and declarations to run a call | No: the record is the owner's state; the registry's `run` takes the adoption id | `adopted` | | Read a request's declarations for a program that may only see them (Code Mode) | Yes: `adopted` answers the same record; the program takes the declaration part | Business composition | -| Register a published call's claim before the batch fact | No: the claim must exist before the fact and be released on every path that never dispatches | `claim` | +| Register a published call's claim before the batch fact | No: the claim must exist before the fact and be released on every path that never dispatches; the contributor's refusal is the claim's, not the caller's | `claim` | | Keep the same adopted generation across a budget-recovery retry | No: the record moves to the new request id; composing it would copy and release records | `transfer` | -| Release a record when the request is done | No: the terminal fact is the line's, and the owner settles it without a caller call | owner settlement; no operation | +| Release a record when the request is done | No: the terminal fact is the line's; the caller may settle sooner but cannot see every end path | `release` (optional) | +| Keep only the current request after a rebuild | No: a rebuild must drop every stale record in one step | `retain_only` | An operation exists only where its row says No. @@ -50,7 +55,7 @@ match configuration.tools { }).await?, // AlreadyBound, Invalid, Unavailable, Closed None => { // No tool part: declare the registry's current host and contributed tools. - let current = registry.declarations().await?; + let current = registry.declarations()?; binding.bind(BindRequest { request_id: request.id.clone(), turn_id: turn.id.clone(), @@ -65,15 +70,16 @@ binding.claim(ClaimRequest { request_id: request.id.clone(), calls: request.calls.clone(), context: execution.clone(), -}).await?; +}).await?; // Callback, NoRecord, Closed // No release call: the owner settles the record and its claims when `step/tool-result` -// for this request, or `turn/end`, is dispatched. +// for this request, or `turn/end`, is dispatched. `release` settles sooner if Loop +// knows the request cannot run again. ``` A host that selects tools over the registry's declarations composes the same steps; the declarations it reads are the ones it binds: ```rust -let available = registry.declarations().await?; +let available = registry.declarations()?; let settings = host.prepare(turn_id, request_id, &history, &available.tools)?; binding.bind(BindRequest { request_id: request.id.clone(), @@ -84,16 +90,16 @@ binding.bind(BindRequest { }).await?; ``` -A budget-recovery retry keeps the generation the first attempt declared: +A budget-recovery retry keeps the generation the first attempt declared; `transfer`, `release` and `retain_only` are synchronous: ```rust -binding.transfer(TransferRequest { from: old_request_id, to: new_request_id }).await?; // Invalid +binding.transfer(TransferRequest { from: old_request_id, to: new_request_id })?; // NoRecord ``` ToolExecutor reads the adoption once per call and hands it to the registry, which resolves the version's handler: ```rust -let adopted = binding.adopted(&context.request_id).await?; // Invalid +let adopted = binding.adopted(context.request_id.clone())?; // NoRecord let call = registry.resolve_write(ResolveWrite { adoption: adopted.adoption.clone(), call }, cancelled).await?; let outcome = registry.run(RunCall { adoption: adopted.adoption, @@ -105,7 +111,7 @@ let outcome = registry.run(RunCall { Code Mode reads the same record and takes only the declarations: ```rust -let declared: Vec = binding.adopted(&execution.request_id).await?.tools +let declared: Vec = binding.adopted(execution.request_id.clone())?.tools .into_iter() .filter(|tool| tool.name != CODEMODE_TOOL) .collect(); @@ -117,33 +123,36 @@ let declared: Vec = binding.adopted(&execution.request_id).await | Service | Purpose | | --- | --- | -| `S:ToolRegistry` (Session, [#2026](https://github.com/arcships/dim/issues/2026)) | Adopt a declared generation and retain its versions; register a request's claims; release an adoption, a request's claims and a request's retention. | -| `B:Prompt` (branch, [#2027](https://github.com/arcships/dim/issues/2027)) | Adopt the tool part of the branch's model configuration when the registry's set changes. | +| `S:ToolRegistry` (Session, target, pending [#2103](https://github.com/arcships/dim/pull/2103)) | Adopt a declared generation and retain its versions; register a request's claims with their execution context; release an adoption, a request's claims and a request's retention. | +| `B:Prompt` (branch, target, pending [#2102](https://github.com/arcships/dim/pull/2102)) | Adopt the tool part of the branch's model configuration when the registry's set changes. | | `B:Timeline`, `B:Dispatcher` | Reconcile the prefix's last configuration at branch opening; consume `step/tool-result` and `turn/end` for settlement; write nothing. | | `B:BranchLifecycle` | Gate the registry-change watcher on activation and closing. | -The registry's `adopt`, `release`, `claim` and `release_claims` are called only by ToolBinding; Loop never calls the registry. +The registry's `adopt`, `release`, `claim` and `release_claims` are called only by ToolBinding; Loop calls them through this owner and calls the registry only for `declarations`. ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `bind` | Fix a request to one adopted generation | `{requestId, turnId, through, declared, sources}` | `{}` | None; the owner completes the adoption and the record | `already_bound`, `invalid` (the registry refused the declarations), `unavailable` (a source version is gone), `closed` | -| `adopted` | The record's adoption id and declarations | `{requestId}` | `{adoption, tools}` | None | `invalid` (no record), `closed` | -| `claim` | Register the calls' claims before their batch fact | `{requestId, calls, context}` | `{}` | None | `invalid` (no record), `closed` | -| `transfer` | Move a record to the request that retries it | `{from, to}` | `{}` | None | `invalid` (no record), `closed` | +| `bind` | Fix a request to one adopted generation | `{requestId, turnId, through, declared, sources}` | `()` | None; the owner completes the adoption and the record | `already_bound`, `invalid`, `unavailable`, `closed` | +| `adopted` | The record's adoption id and declarations | `{requestId}` | `Adopted` | None | `no_record`, `closed` | +| `claim` | Register the calls' claims before their batch fact, with the context their callbacks need | `{requestId, calls, context}` | `()` | None | `no_record`, `callback`, `closed` | +| `release` | Settle a request now; the owner settles it at the terminal facts anyway | `{requestId}` | `()` | None | `closed` | +| `retain_only` | Keep one request's record and release every other | `{requestId}` | `()` | None | `closed` | +| `transfer` | Move a record to the request that retries it | `{from, to}` | `()` | None | `no_record`, `closed` | -`declared` is the request's full declaration list; `sources` is the prefix's `tool_sources` as version ids; `through` is the prefix cutoff the pin is released against; `turnId` is the turn the request belongs to and the key `turn/end` settles. `adoption` is the registry's id from `adopt`; the registry retains the version set until `release`. +`declared` is the request's full declaration list; `sources` is the prefix's `tool_sources` as version ids; `through` is the prefix cutoff the pin is released against; `turnId` is the turn the request belongs to and the key `turn/end` settles. `adoption` is the registry's id from `adopt`; the registry retains the version set until `release`. Replies are positional, as the published faces are. ### Errors -| Kind | Operation | What the caller does next | -| --- | --- | --- | -| `already_bound` | `bind` | A caller bug: the request id was bound twice. Fail the turn as a fault. | -| `invalid` | `bind` | The registry refused the declarations (a name has no handler, or its definition changed); fail the turn and report the declaration. | -| `unavailable` | `bind` | The prefix declares a source version the registry no longer retains; fail the turn, or re-prepare from the current declarations when the turn's policy allows a retry. | -| `invalid` | `adopted`, `claim`, `transfer` | The request has no record: a caller bug or a request released before its batch. Fail the turn as a fault. | -| `closed` | any | The branch is closing or unloading; the turn ends. | +| Kind | Operation | Retryable | What the caller does next | +| --- | --- | --- | --- | +| `already_bound` | `bind` | No | A caller bug: the request id was bound twice; fail the turn as a fault. | +| `invalid` | `bind` | No | The registry refused the declarations; the error names the declaration and the reason; fail the turn and report them. | +| `unavailable` | `bind` | Yes, after re-preparing | The prefix declares a source version the registry no longer retains; re-prepare from the current declarations, or fail the turn. | +| `no_record` | `adopted`, `claim`, `transfer` | No | The request has no record: a caller bug or a request released before its batch; fail the turn as a fault. A reload settlement is not this error. | +| `callback` | `claim` | Depends on the cause | The contributor's claim callback refused; the error carries the call id, and the callback's own code in `reason` and its message in `message`. The batch is not published; the turn fails unless the cause says the call may be retried in a later request. | +| `closed` | any | No, in this generation | The branch is closing or reloading; the turn ends; a replacement generation serves the next request. | `bind` errors carry the declaration that failed (`name`) or the source that is gone (`key`, `version`); the owner reports no failure the record cannot have. @@ -151,18 +160,20 @@ The registry's `adopt`, `release`, `claim` and `release_claims` are called only | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `bind` | Ask the registry to adopt the declarations, insert the record, release the adoptions of pins no later prefix declares | None: the call is synchronous and bounded | Nothing to release; the record is settled at the request's terminal fact or the close | A record in flight is refused with `closed`; the registry releases an adoption it granted at the row's unload | ToolBinding and ToolRegistry | +| `bind` | Check the record (a second bind adopts nothing), ask the registry to adopt the declarations, insert the record, release the adoptions of pins no later prefix declares | None: the call is synchronous and bounded | Nothing to release; the record is settled at the request's terminal fact or the close | A record in flight is refused with `closed`; the registry releases an adoption it granted at the row's unload | ToolBinding and ToolRegistry | | `adopted` | Read the record and answer its adoption and declarations | None | Nothing to release | Refused with `closed`; a reload rebuilds the record from the prefix's configuration | ToolBinding | -| `claim` | Ask the registry to register a guard per call; the record notes that the request has claims | None | The close releases the request's claims | Every claim of the generation is released | ToolBinding and ToolRegistry | +| `claim` | Ask the registry to register a guard per call with the request's execution context; a refusal answers `callback` and registers nothing | None | The close releases the request's claims | Every claim of the generation is released | ToolBinding and ToolRegistry | +| `release` | Drop the record and ask the registry to release its claims and adoption | None | Nothing to release | The owner performs the same release on close | ToolBinding and ToolRegistry | +| `retain_only` | Release every other record, in one pass | None | Nothing to release | The owner performs the same release on close | ToolBinding and ToolRegistry | | `transfer` | Move the record to the new request id | None | Nothing to release | Refused with `closed` once the generation closes | ToolBinding | -| Settlement | On the dispatched `step/tool-result` of the request: drop the record and ask the registry to release the request's claims; on `turn/end` of its turn: the same for every record of the turn; on close: every record and claim | — | — | The owner performs the same release on close | ToolBinding and ToolRegistry | +| Settlement | On the dispatched `step/tool-result` of the request: drop the record and release its claims; on `turn/end` of its turn: the same for every record of the turn; on close: every record and claim | — | — | The owner performs the same release on close | ToolBinding and ToolRegistry | -A record is settled before the branch accepts closing work. A reload rebuilds the record from the prefix's last adopted configuration, exactly as a fresh branch would; a request that was in flight when the owner reloaded has no record, and its executor ends the batch as a reload settlement, not as an `invalid` error. +A record is settled before the branch accepts closing work. A reload rebuilds the record from the prefix's last adopted configuration, exactly as a fresh branch would; a request that was in flight when the owner reloaded has no record, and its executor ends the batch as a reload settlement, not as a `no_record` error. ## Exceptions with reasons - Pins are values, not handles: a pin is a record whose adoption a later prefix may still name, and the registry keeps those versions resolvable until the owner releases the adoption at the next bind or the close. ToolBinding holds no handler and no guard. -- The record's settlement reads the line's facts (`step/tool-result`, `turn/end`) instead of a caller's release call: only the owner of the record can guarantee every end path, and the facts are public. +- The record's settlement reads the line's facts (`step/tool-result`, `turn/end`) instead of depending on a caller's release call: only the owner of the record can guarantee every end path, and the facts are public. `release` and `retain_only` exist for Loop's budget-recovery and rebuild steps, not as the only settlement. ## Supersedes @@ -176,9 +187,10 @@ A record is settled before the branch accepts closing work. A reload rebuilds th Flow tests on the owner: - A request binds to the prefix's declaration; a tool registered after the bind does not appear in `adopted` or in the executor's run; a later request adopts the new registry set and the earlier pin's adoption is released. +- A second `bind` for the same request is `already_bound` and adopts nothing; the first adoption stays. - A request whose declaration names a version the registry no longer retains fails `unavailable` and binds nothing. -- A claim exists before the batch fact; the request's batch result, a turn end and a close each release the claims the request did not dispatch; a dispatched call's guard is consumed by the registry's run; Loop calls no release on any path. -- Budget recovery transfers the record, and the retried request runs the version its first attempt declared. +- A claim exists before the batch fact and carries the request's `turnId`/`requestId`/`branchId`; a contributor that refuses answers `callback` with its own code and message and the batch is not published; the request's batch result, a turn end, a close and an explicit `release` each release the claims the request did not dispatch. +- Budget recovery transfers the record, and the retried request runs the version its first attempt declared; `retain_only` drops the other records. - After a reload, the branch rebinds its prefix's configuration before the first request; an in-flight batch ends as a reload settlement. - Cross-language: the same operations run over the face and in process, with the same replies and errors. @@ -200,7 +212,7 @@ Flow tests on the owner: | §4 rule 9 | No Timeline fact of its own; the adopted configuration stays Prompt's fact, and settlement reads public facts. | | §7 resources and objects | The record, pins and adoption ids are values; no handler or guard crosses. | | §7 no proxy | ToolBinding returns its own record; execution and claims are ToolRegistry's operations, requested by this owner. | -| §7 one surface | The branch-facing operations are `bind`, `adopted`, `claim` and `transfer`; `handler`, `take_claim`, `definitions`, `release`, `retain_only`, `prepare` and `bind_current` are removed. | +| §7 one surface | The branch-facing operations are `bind`, `adopted`, `claim`, `release`, `retain_only` and `transfer`; `handler`, `take_claim`, `definitions`, `prepare` and `bind_current` are removed. | | §7 cross-language | Every parameter and reply is data; the face and the Rust call use the same operations. | | §7 responsibility split | The caller keeps the declaration source, the turn's decisions and the batch; the owner keeps the record, its pins, its claims and their settlement. | | ADR 002 D1 | Branch scope for the request record; the registry's generations are Session state. | @@ -208,11 +220,13 @@ Flow tests on the owner: | ADR 002 D3 | The registry is a Session capability the branch depends on; the registry depends on no branch. | | ADR 002 D4 | No configuration of its own; the adopted configuration is Prompt's fact. | | ADR 002 D5 | Language-neutral operations and data. | +| ADR 027 | Not applicable: ToolBinding holds no cross-scope access; its caller Loop is a branch part. | ## Requirements raised to mechanism owners -- **ToolRegistry ([#2026](https://github.com/arcships/dim/issues/2026)).** The registry's contract ([#2103](https://github.com/arcships/dim/pull/2103)) defines `adopt`, `release`, `claim`, `release_claims`, `run`, `resolve_write`, `ordering` and `declarations`. This owner calls `adopt`, `release`, `claim` and `release_claims`; `run`, `resolve_write` and `ordering` are ToolExecutor's. Loop calls this owner only. The split is the one stated under Use and scope: the registry keeps the Session's resolvable generations; this owner keeps the line's request record and claims. -- **Prompt ([#2027](https://github.com/arcships/dim/issues/2027)).** The owner needs Prompt's `configure({tools})` operation ([PromptAdoption](https://github.com/arcships/dim/pull/2102)), because ToolBinding writes no configuration fact; a tool-only adoption without an adopted model is Prompt's `invalid_model`. +- **ToolRegistry ([#2103](https://github.com/arcships/dim/pull/2103), target).** The registry's claim must take the request's execution context (`{request, calls, context}`) so the contributor's claim callback receives the turn, request and branch, and it must answer a refusal as its `callback` error carrying the callback's own code and message; ToolBinding maps that to its `callback` error. Its `adopt`, `release`, `claim` and `release_claims` are called only by ToolBinding; `declarations` stays the one read Loop and the fingerprint make. +- **Prompt ([#2102](https://github.com/arcships/dim/pull/2102), target).** The owner needs Prompt's `configure({tools})` operation, because ToolBinding writes no configuration fact; a tool-only adoption without an adopted model is Prompt's `invalid_model`. +- **Cross-scope mechanism ([#2127](https://github.com/arcships/dim/issues/2127), target).** No obligation from this owner; it is listed because the series' Session-to-line access depends on it. - **None other.** No Timeline, Dispatcher, loader or runtime change. ## Binding appendix @@ -234,7 +248,7 @@ pub struct Adopted { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct BindRequest { pub request_id: String, pub turn_id: String, @@ -244,7 +258,7 @@ pub struct BindRequest { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ClaimRequest { pub request_id: String, pub calls: Vec, @@ -252,21 +266,25 @@ pub struct ClaimRequest { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct TransferRequest { pub from: String, pub to: String, } -#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "snake_case")] +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum BindingError { #[error("request {request_id} is already bound")] AlreadyBound { request_id: String }, - #[error("the tool declaration was refused: {reason}")] - Invalid { reason: String }, + #[error("the tool declaration {name} was refused: {reason}")] + Invalid { name: String, reason: String }, #[error("tool source {key}@{version} is unavailable")] Unavailable { key: String, version: String }, + #[error("request {request_id} has no tool record")] + NoRecord { request_id: String }, + #[error("the claim of call {call_id} was refused ({reason}): {message}")] + Callback { call_id: String, reason: String, message: String }, #[error("the branch is closing")] Closed, } @@ -278,6 +296,8 @@ impl ToolBinding { pub async fn bind(&self, request: BindRequest) -> Result<(), BindingError> { /* ... */ } pub fn adopted(&self, request_id: String) -> Result { /* ... */ } pub async fn claim(&self, request: ClaimRequest) -> Result<(), BindingError> { /* ... */ } + pub fn release(&self, request_id: String) { /* ... */ } + pub fn retain_only(&self, request_id: String) { /* ... */ } pub fn transfer(&self, request: TransferRequest) -> Result<(), BindingError> { /* ... */ } } ``` diff --git a/docs/design/plugins/ToolExecutor.md b/docs/design/plugins/ToolExecutor.md index 5596ecdaf0..02bad4fcc6 100644 --- a/docs/design/plugins/ToolExecutor.md +++ b/docs/design/plugins/ToolExecutor.md @@ -15,6 +15,8 @@ ToolExecutor owns: ToolExecutor does not declare tools, decide admission, resolve a write target's facts, execute a handler or hold a handler. The adoption and declarations belong to ToolBinding; admission belongs to Approval; write-target resolution (`resolve_write`), ordering class (`ordering`), claims and execution (`run`) belong to ToolRegistry. +Targets: `toolRegistry` is a target, pending [#2103](https://github.com/arcships/dim/pull/2103); `toolBinding` and `approval` are this PR's; the mechanism obligation for cross-scope access is [#2127](https://github.com/arcships/dim/issues/2127). + Callers keep as business: - When a batch's calls run, and what a failed call means for the turn. @@ -44,15 +46,15 @@ let gate = executor.open(&ctx, OpenRequest { let result = executor.invoke(&ctx, InvokeRequest { gate_id: gate.gate_id.clone(), call, -}, cancelled.clone()).await?; // GateClosed, Closed; a tool failure is result.is_error +}, cancelled.clone()).await?; // GateClosed, Closed, Cancelled; a tool failure is result.is_error // The program ended: take the confirmed effects to word the result. let effects = executor.close(&ctx, CloseRequest { gate_id: gate.gate_id }).await?; // GateClosed, Closed ``` -A program's declarations come from the pin owner, not the executor: +A program's declarations come from the record owner, not the executor: ```rust -let adopted = binding.adopted(&execution.request_id).await?; // Invalid +let adopted = binding.adopted(execution.request_id.clone())?; // NoRecord let declared: Vec = adopted.tools .into_iter() .filter(|tool| tool.name != CODEMODE_TOOL) @@ -67,7 +69,7 @@ The owner closes the gate when the parent call settles; a program that returns e | Service | Purpose | | --- | --- | -| `S:ToolRegistry` (Session, [#2026](https://github.com/arcships/dim/issues/2026)) | `resolve_write` before admission, `ordering` for the batch's steps, and `run` for an admitted call. | +| `S:ToolRegistry` (Session, target, pending [#2103](https://github.com/arcships/dim/pull/2103)) | `resolve_write` before admission, `ordering` for the batch's steps, and `run` for an admitted call. | | `B:Approval` | Admit each call, including the user's answer and the policy recheck. | | `B:Timeline`, `B:Dispatcher` | Commit progress and results; consume batches, interrupts and turn boundaries; report faults. | | `B:TimelineIdentity` | The calling line's identity in the execution context and the span. | @@ -77,28 +79,32 @@ The owner closes the gate when the parent call settles; a program that returns e | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `open` | Open a child-call gate for one outer call of the current batch | `{parentCallId, context}` | `{gateId}` | Before the gate id is issued; nothing was created | `closed`, `interrupted`, `no_batch` (no current batch, or the parent call does not belong to it), `cancelled` | -| `invoke` | Run one child call through the same admission and execution path | `{gateId, call}` | `{result}` | The caller's token before the child settles: the child is cancelled and its fact records it; the gate stays usable | `closed`, `gate_closed` (the gate was closed by its parent's settlement or by an interrupt), `cancelled` | -| `close` | Close the gate now and answer the confirmed child effects | `{gateId}` | `{effects}` | None: the close settles | `closed`, `gate_closed` (the batch was interrupted or settled before the call) | +| `open` | Open a child-call gate for one outer call of the current batch | `{parentCallId, context}` | `OpenReply` | The caller's token before the gate id is issued; nothing was created | `closed`, `interrupted`, `no_batch`, `cancelled` | +| `invoke` | Run one child call through the same admission and execution path | `{gateId, call}` | `ToolResult` | The caller's token before the child settles ends the call with `cancelled`; the child is cancelled and its fact records it; the gate stays usable | `closed`, `gate_closed`, `cancelled` | +| `close` | Close the gate now and answer the confirmed child effects | `{gateId}` | `CloseReply` | None: the close settles | `closed`, `gate_closed` (the batch was interrupted or settled before the call) | + +`caller: &Ctx` is rutis's caller parameter: the dispatch fills it from the calling row, it is not a request field, and no caller sends or names a row. `gateId` is bound to the calling row and the parent call; a call from another row is `gate_closed`. `close` is idempotent for the owner's own settlement: the parent's settlement closes the gate whether or not the program did, and the effects reach the parent result once. -`caller: &Ctx` is the binding's calling-row parameter: it is not a request field, and the gate id's row binding follows from it. `gateId` is bound to the calling row and the parent call; a call from another row is `gate_closed`. `close` is idempotent for the owner's own settlement: the parent's settlement closes the gate whether or not the program did, and the effects reach the parent result once. A child call's refusal, cancellation, unknown tool or tool failure is a `ToolResult` with `is_error: true`, not an operation error: the program decides what to do with it. +A child call's refusal, cancellation or failure is a `ToolResult` with `is_error: true`, not an operation error: the program decides what to do with it. `invoke`'s own `cancelled` is the caller's token, not the child's: the caller's call ends, the child's result carries the child's cancellation. ### Errors -| Kind | Operation | What the caller does next | -| --- | --- | --- | -| `closed` | `open`, `invoke`, `close` | The executor is closing or reloading; stop the program; its batch is settled. | -| `interrupted` | `open` | The turn was interrupted; stop the program. | -| `no_batch` | `open` | The parent call is not part of the current batch; a caller bug: stop the program and report it. | -| `gate_closed` | `invoke`, `close` | The gate's parent call settled or the batch was interrupted; stop the program; the parent result carries the effects already confirmed. | -| `cancelled` | `open`, `invoke` | The caller's token ended the call; for `invoke` the child's result records the cancellation and the gate stays usable. | +| Kind | Operation | Retryable | What the caller does next | +| --- | --- | --- | --- | +| `closed` | `open`, `invoke`, `close` | No, in this generation | The executor is closing or reloading; stop the program; its batch is settled; a replacement generation serves the next request. | +| `interrupted` | `open` | No | The turn was interrupted; stop the program. | +| `no_batch` | `open` | No | The parent call is not part of the current batch; a caller bug: stop the program and report it. | +| `gate_closed` | `invoke`, `close` | No | The gate's parent call settled or the batch was interrupted; stop the program; the parent result carries the effects already confirmed. | +| `cancelled` | `open`, `invoke` | No | The caller's token ended the call; nothing was created for `open`; for `invoke`, the child's result records the child's own cancellation and the gate stays usable. | + +Replies are positional: `open` answers the gate id, `invoke` the child's result, `close` the effects. ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `open` | Check the current batch and the parent call, issue a gate id under the calling row, subscribe the gate to the parent token | Before the id is issued: nothing exists, `cancelled` | The row's gates are closed with their child tasks | New calls are refused; every gate of the generation is closed | ToolExecutor | -| `invoke` | Write the child `step/tool-call` with the parent call id, resolve the write target, admit the call, run it through the registry, write the child `step/tool-result`, record its effects | The child is cancelled; its fact records the cancellation; the gate stays usable for the program's next call | The row's gates close; in-flight children end cancelled and are recorded | In-flight children end as reload settlements; the gate is closed | ToolExecutor for the facts and the gate; ToolRegistry for the handler and its claim; the calling row for the program future | +| `invoke` | Write the child `step/tool-call` with the parent call id, resolve the write target, admit the call, run it through the registry, write the child `step/tool-result`, record its effects | The call ends `cancelled`; the child is cancelled and its fact records the child's cancellation; the gate stays usable | The row's gates close; in-flight children end cancelled and are recorded | In-flight children end as reload settlements; the gate is closed | ToolExecutor for the facts and the gate; ToolRegistry for the handler and its claim; the calling row for the program future | | `close` | Mark the gate closed, refuse new children, wait for its running children within the owner's grace, answer the confirmed effects | The close waits; a child past the grace is outside the contract | The row's gates close with their children | A close in flight finishes; the parent settlement closes the gate again | ToolExecutor | | Parent settlement | After the parent call's result is known, close every gate of the parent, wait for its children within the owner's grace, and merge their effects into the result in invocation order | — | — | — | ToolExecutor | @@ -106,7 +112,7 @@ The owner never hands out a gate: `gateId` names the gate only for `invoke` and ## Exceptions with reasons -- A child call's failure is a result, not an operation error: a program may catch it, and the model sees the same `ToolResult` text a top-level call would produce. +- A child call's failure is a result, not an operation error: a program may catch it, and the model sees the same `ToolResult` text a top-level call would produce. The caller's own cancellation is the exception, and it ends the `invoke` call. ## Supersedes @@ -120,7 +126,8 @@ Flow tests on the owner: - A child call writes its own `step/tool-call`/`step/tool-result` with the parent call id; its effects appear in the parent result in invocation order; the outer result is written after its children settle. - A program that returns early still has its child effects merged; a `close` before the program ends answers the confirmed effects, and the same effects appear once in the parent result. -- An interrupt cancels a running child and refuses a new gate; a reload settles an open child and an open parent, and a reload-settled result fails the turn. +- An interrupt cancels a running child and refuses a new gate; a reload settles an open child and open parent, and a reload-settled result fails the turn. +- A dropped `invoke` ends with `cancelled` and leaves the child's fact recording the child's cancellation; the gate still accepts the program's next call; a child's own failure is `Ok(ToolResult { is_error: true })`. - `open` refuses a parent call that is not in the current batch and a second batch while one runs; `gate_closed` answers a call after the parent settled. - The same operations over the face and in process answer the same results and errors. @@ -150,11 +157,12 @@ Flow tests on the owner: | ADR 002 D3 | Depends on Session capabilities (the registry) and branch peers (Approval); nothing depends on the executor's internals. | | ADR 002 D4 | No configuration. | | ADR 002 D5 | Language-neutral operations and data. | +| ADR 027 | Not applicable: the executor is reached by the branch that runs it, not across scopes. | ## Requirements raised to mechanism owners -- **ToolRegistry ([#2026](https://github.com/arcships/dim/issues/2026)).** The registry's contract ([#2103](https://github.com/arcships/dim/pull/2103)) defines `resolve_write({adoption, call})`, `ordering({adoption, call})` and `run({adoption, call, caller}, cancelled)`. The executor uses those three; the tool's own failure comes back as a `ToolResult`, not as an error kind. -- **Approval (#2028).** `admit` is this board's own operation (see [Approval](Approval.md)). +- **ToolRegistry ([#2103](https://github.com/arcships/dim/pull/2103), target).** The registry's contract defines `resolve_write({adoption, call})`, `ordering({adoption, call})` and `run({adoption, call, caller}, cancelled)`. The executor uses those three; the tool's own failure comes back as a `ToolResult`, not as an error kind. +- **Cross-scope mechanism ([#2127](https://github.com/arcships/dim/issues/2127), target).** No obligation from this owner; it is listed because the series' Session-to-line access depends on it. - **None other.** No Timeline, Dispatcher, loader or runtime change. ## Binding appendix @@ -168,7 +176,7 @@ use dim_agent_types::{ToolCall, ToolEffect, ToolResult}; use rutis::Ctx; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct OpenRequest { pub parent_call_id: String, pub context: ToolExecutionContext, @@ -181,14 +189,14 @@ pub struct OpenReply { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct InvokeRequest { pub gate_id: String, pub call: ToolCall, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct CloseRequest { pub gate_id: String, } @@ -196,11 +204,11 @@ pub struct CloseRequest { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct CloseReply { - pub effects: Vec, + pub effects: Vec, } -#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "snake_case")] +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum ExecutorError { #[error("the tool executor is closing")] Closed, From a68b3228817056138357f7513f28363893fa9a80 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Tue, 24 Nov 2026 13:32:19 +0800 Subject: [PATCH 09/11] docs(design): resolve the round-5 review in the tool chain contracts Keep the published approval, permission and backgroundExec codes with their faces; remove the Rust-only respond method instead of renaming it; state the advise callback as a FromFunction value; align the FileReads DTO values with the codec labels; add the cross-row gate test; make the background tail preview state its live-only promise; return Result from release and retain_only. --- docs/design/plugins/Approval.md | 38 +++++++++++++-------------- docs/design/plugins/BackgroundExec.md | 9 ++++--- docs/design/plugins/FileReads.md | 8 +++--- docs/design/plugins/Permission.md | 38 +++++++++++++-------------- docs/design/plugins/ToolBinding.md | 4 +-- docs/design/plugins/ToolExecutor.md | 2 +- 6 files changed, 50 insertions(+), 49 deletions(-) diff --git a/docs/design/plugins/Approval.md b/docs/design/plugins/Approval.md index 73f4e2288a..b12003805f 100644 --- a/docs/design/plugins/Approval.md +++ b/docs/design/plugins/Approval.md @@ -76,9 +76,9 @@ The policy value is a read-only view Permission publishes (§7); Approval takes | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `admit` | Admit one call, asking the user when required | `{source, call, risk}` | `()` | The caller drops the call: the pending request is cancelled and the call ends `cancelled` | `denied`, `cancelled`, `failed`, `closed` | -| `pending` | The requests no answer or cancellation ended, in request order | `()` | `ApprovalRequestData[]` | None | `closed` | -| `decide` | Answer a pending request | `approvalId`, `decision` | `()` | None: an accepted answer is committed | `unknown` (not pending: answered, cancelled or never existed), `failed`, `closed` | +| `admit` | Admit one call, asking the user when required | `{source, call, risk}` | `()` | The caller drops the call: the pending request is cancelled and the call ends `Cancelled` | `Denied`, `Cancelled`, `Failed`, `Closed` | +| `pending` | The requests no answer or cancellation ended, in request order | `()` | `ApprovalRequestData[]` | None | `Closed` | +| `decide` | Answer a pending request | `approvalId`, `decision` | `()` | None: an accepted answer is committed | `Unknown` (not pending: answered, cancelled or never existed), `Failed`, `Closed` | `risk` is the tool owner's declaration for the call, or absent. `source` identifies the caller and is passed to Permission for the admission decision. The reply to `decide` means the branch dispatched the answer, not that the tool started. Replies are positional, as the published face is. @@ -86,22 +86,22 @@ The policy value is a read-only view Permission publishes (§7); Approval takes | Kind | Operation | Retryable | What the caller does next | | --- | --- | --- | --- | -| `denied` | `admit` | No | Do not run the call; the result carries the reason. | -| `cancelled` | `admit` | No | The batch token was dropped or the batch was interrupted; do not run the call. | -| `failed` | `admit`, `decide` | Yes, by a later attempt | The request or response could not be committed (storage or fact failure); nothing is pending for the call, or the answer did not take; the owner reports a fault and the turn fails. A repeated call is a new admission or a fresh answer. | -| `closed` | any | No, in this generation | The generation is closing or reloading; stop; a replacement generation serves the next request. | -| `unknown` | `decide` | No | The request is no longer pending; retire the prompt and do not retry the answer. A repeated answer is `unknown` too. | +| `Denied` | `admit` | No | Do not run the call; the result carries the reason. | +| `Cancelled` | `admit` | No | The batch token was dropped or the batch was interrupted; do not run the call. | +| `Failed` | `admit`, `decide` | Yes, by a later attempt | The request or response could not be committed (storage or fact failure); nothing is pending for the call, or the answer did not take; the owner reports a fault and the turn fails. A repeated call is a new admission or a fresh answer. | +| `Closed` | any | No, in this generation | The generation is closing or reloading; stop; a replacement generation serves the next request. | +| `Unknown` | `decide` | No | The request is no longer pending; retire the prompt and do not retry the answer. A repeated answer is `unknown` too. | ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `admit` — allowed without a question | Ask Permission; an allow returns | The token is checked before the call starts | Nothing held | Refused with `closed` | Approval and Permission | -| `admit` — a question is required | Commit `approval/request`, register the pending request, wait for the answer or a policy change; on an allow, recheck the policy and return; on a deny, return the refusal | The pending request is removed and `approval/cancelled` is written; the call ends `cancelled` | The pending request is cancelled with the same terminal | Every pending request of the generation is cancelled; an in-flight wait ends `closed` | Approval: the request, its terminal and the waiter | +| `admit` — allowed without a question | Ask Permission; an allow returns | The token is checked before the call starts | Nothing held | Refused with `Closed` | Approval and Permission | +| `admit` — a question is required | Commit `approval/request`, register the pending request, wait for the answer or a policy change; on an allow, recheck the policy and return; on a deny, return the refusal | The pending request is removed and `approval/cancelled` is written; the call ends `Cancelled` | The pending request is cancelled with the same terminal | Every pending request of the generation is cancelled; an in-flight wait ends `Closed` | Approval: the request, its terminal and the waiter | | `admit` — policy changed while waiting | Recheck through Permission; an allow without an advisor question ends the question with `approval/cancelled` and its reason; a deny ends it with the refusal; an ask keeps waiting | As above | As above | As above | Approval | -| `admit` — the request commit fails | Nothing is pending; the call ends `failed`; the turn fails | — | — | — | Approval | -| `decide` | Commit `approval/respond`, answer the waiter once the branch dispatched it; the admission rechecks before the call starts | — | A committed answer stays; the admission may end `closed` | A response to a request of a closed generation is `unknown` | Approval | -| `decide` — the response commit fails | The request stays pending; the answer reports `failed`; a repeated answer is accepted | — | — | — | Approval | +| `admit` — the request commit fails | Nothing is pending; the call ends `Failed`; the turn fails | — | — | — | Approval | +| `decide` | Commit `approval/respond`, answer the waiter once the branch dispatched it; the admission rechecks before the call starts | — | A committed answer stays; the admission may end `closed` | A response to a request of a closed generation is `Unknown` | Approval | +| `decide` — the response commit fails | The request stays pending; the answer reports `Failed`; a repeated answer is accepted | — | — | — | Approval | | `pending` | One consistent read under the owner's lock | — | — | Answered at the state observed | Approval | A call that a policy change no longer requires is not restarted; an explicit advisor question stays pending until answered. The owner never fabricates a user answer. @@ -110,9 +110,9 @@ A call that a policy change no longer requires is not restarted; an explicit adv The published `approval` face ([Permission plugin page](../../architecture/rust-agent/plugins/Permission.md#approval-data-face)) keeps `pending()` and `decide(requestId, decision)` positionally and keeps `ApprovalRequestData[]` as `pending`'s reply. It changes as follows, and the maintainer is asked to confirm: -- `respond(requestId, decision)` is renamed `decide`; the callers are Hooks and the App Server's `approval.respond` built-in. The built-in keeps its name and settles through this operation; the client RPC is unchanged. +- `respond` is removed: it is the Rust-only `#[service(skip)]` method (`crates/dim-agent-capabilities/src/approval.rs`), and `decide` is already the face's operation; the target keeps `decide` unchanged and removes the skip method with it. - `replay()` is removed; `pending()` answers the same set, and the App Server orders its attach notifications itself. -- Error codes change case with the standard binding spelling: `Unknown`/`Cancelled`/`Closed` become `unknown`/`cancelled`/`closed`; `denied` and `failed` are new. Callers match the codes by string; the change ships with the same release as the face. +- The published codes `Unknown`, `Cancelled` and `Closed` are kept, and `Denied` and `Failed` are added; the Appendix's `PascalCase` rename is what keeps them, so a caller matches the same strings as before. - `admit` is new (additive). No Timeline event, notification name, request field of the client protocol or model-visible text changes. @@ -134,8 +134,8 @@ Flow tests on the owner: - An allow without a question returns without a request; an ask writes one request, and the call starts only after the answer and the recheck. - A dropped admission removes its request and writes `approval/cancelled`; a policy change that allows the call ends it the same way and starts the call; a policy change that denies it returns the refusal. - An advisor's question stays pending across a policy change; only an answer settles it. -- A request commit failure answers `failed`, leaves nothing pending and fails the turn; a response commit failure answers `failed`, leaves the request pending, and a repeated answer is accepted. -- A second answer to the same request is `unknown`; an answer to a cancelled request is `unknown`. +- A request commit failure answers `Failed`, leaves nothing pending and fails the turn; a response commit failure answers `Failed`, leaves the request pending, and a repeated answer is accepted. +- A second answer to the same request is `Unknown`; an answer to a cancelled request is `Unknown`. - The generation's close cancels every pending request; a reload cancels the historical requests and rebuilds an empty pending set. - The face and the Rust call answer the same requests and errors. @@ -165,7 +165,7 @@ Flow tests on the owner: | ADR 002 D3 | Depends on Permission (branch) and the branch infrastructure. | | ADR 002 D4 | No configuration. | | ADR 002 D5 | Language-neutral operations and data. | -| ADR 027 | Not applicable: the line's own part serves its callers; the Collaboration route uses the line access owned by ADR 027. | +| ADR 027 D3 | Applicable: Collaboration reaches a member line's `pending`/`decide` with `line_owner::(line)`; the face is resolvable by line id and is not a registration point. | ## Requirements raised to mechanism owners @@ -191,7 +191,7 @@ pub struct AdmitRequest { } #[derive(Debug, serde::Serialize, thiserror::Error)] -#[serde(tag = "code", rename_all = "snake_case")] +#[serde(tag = "code", rename_all = "PascalCase")] pub enum ApprovalError { #[error("the call was denied: {reason}")] Denied { reason: String }, diff --git a/docs/design/plugins/BackgroundExec.md b/docs/design/plugins/BackgroundExec.md index 3c1550b251..42946bc017 100644 --- a/docs/design/plugins/BackgroundExec.md +++ b/docs/design/plugins/BackgroundExec.md @@ -84,7 +84,7 @@ The host's process-by-id operations are a target of #2032; they are stated in Re | --- | --- | --- | --- | --- | --- | | `adopt` | Take over supervision of a command the host started | `{taskId, description, title?, outputPath}` | `()` | The caller drops the call: nothing was adopted, and the host's process is killed | `closed`, `unknown_task` (the host has no live task with this id), `failed` (the `exec/started` fact could not be committed; nothing was adopted and the process is killed) | | `output` | The running task's tail preview | `{taskId}` | `String` | The caller drops the call; the read stops | `unknown` (no such task, or the task has ended), `closed` | -| `output_page` | One bounded page of the registered output file; a stateless offset read, with no pin or release | `{taskId, cursor, limit}` | `OutputPage` | The caller drops the call; the read stops | `unknown`, `unavailable`, `invalid_limit`, `read` (the task facts could not be read or are inconsistent), `closed` | +| `output_page` | One bounded page of the registered output file; a stateless offset read, with no pin or release | `{taskId, cursor, limit}` | `OutputPage` | The caller drops the call; the read stops | `unknown`, `unavailable`, `invalidLimit`, `read` (the task facts could not be read or are inconsistent), `closed` | | `wait` | Wait until the task's terminal is dispatched | `{taskId, timeoutMs}` | `ExecEndedData` | The caller drops the call; the wait releases and nothing changes | `unknown`, `timeout`, `read`, `closed`, `cancelled` | | `stop` | Cancel a running task and answer its terminal | `{taskId}` | `ExecEndedData` | None: an admitted stop settles | `unknown`, `read`, `closed` | @@ -97,7 +97,7 @@ The host's process-by-id operations are a target of #2032; they are stated in Re | `unknown_task` | `adopt` | No | The host has no such task; nothing was adopted and the command is not supervised. | | `unknown` | `output`, `output_page`, `wait`, `stop` | No | This line has no such task; do not retry. `output` also answers `unknown` for an ended task, whose file stays readable by `output_page`. | | `unavailable` | `output_page` | No | The registered file is gone (cleaned or its Session deleted); report the loss, do not retry. | -| `invalid_limit` | `output_page` | No | Use a limit of at least one byte. | +| `invalidLimit` | `output_page` | No | Use a limit of at least one byte. | | `read` | `output_page`, `wait`, `stop` | Yes | The task facts could not be read or are inconsistent; retry the read; if it persists, the task's record is damaged and the caller reports a fault. | | `timeout` | `wait` | Yes | The task is still running; wait again or stop it. | | `failed` | `adopt` | Yes, by the exec tool retrying the launch | The `exec/started` fact could not be committed; nothing was adopted; the process is killed. | @@ -121,7 +121,7 @@ The host's process-by-id operations are a target of #2032; they are stated in Re The published `backgroundExec` face ([WorkspaceTools plugin page](../../architecture/rust-agent/plugins/WorkspaceTools.md#data-face)) keeps `output`, `output_page`, `wait` and `stop` with their published shapes, and `start` stays off the face. The changes, which the maintainer is asked to confirm: - `adopt({taskId, description, title?, outputPath})` is new (additive); the exec tool uses it after the host starts the process. -- Error codes change case with the standard binding spelling: `invalidLimit` becomes `invalid_limit`; `read` is kept; `unknown_task`, `failed` and `cancelled` are new. +- The published codes `unknown`, `closed`, `unavailable`, `invalidLimit`, `read` and `timeout` are kept; the Appendix's explicit `invalidLimit` rename is what keeps that one, and `unknown_task`, `failed` and `cancelled` are new. - `output` keeps its published promise: a running task's live tail preview, `unknown` once the task ends; `output_page` keeps reading the registered file for every state. - No client RPC, notification name, request field or model-visible text changes. @@ -144,7 +144,7 @@ Flow tests on the owner: - A command moved to the background ends once, its terminal is written once, and the line wakes once; a stop cancels it without a wake; a branch close cancels it without a wake. - A reload writes failed terminals for unfinished commands, rebuilds every ended task with its output path, posts the wakes the previous generation lost, and refuses a new adoption; a Session close settles the hold. - A historical task answers `output_page` and `stop` after a reload; `output` is `unknown` for it; `wait` answers its terminal at once. -- The tail preview and the pages read the artifact in every state of the task; a page's cursor advances by its bytes; a limit of zero is `invalid_limit`; a deleted file is `unavailable`; a failed task-fact read is `read`. +- The pages read the artifact in every state of the task, and the tail preview only while the task runs; a page's cursor advances by its bytes; a limit of zero is `invalidLimit`; a deleted file is `unavailable`; a failed task-fact read is `read`. - `wait` answers an ended task at once, times out for a running task, and releases when dropped or cancelled; `adopt` answers `unknown_task` for an id the host does not have and `unknown` answers the other operations for a task this line does not know. - The face and the Rust call answer the same previews, pages, terminals and errors. @@ -237,6 +237,7 @@ pub enum BackgroundError { #[error("the task's output file is no longer available")] Unavailable, #[error("limit must be at least 1")] + #[serde(rename = "invalidLimit")] InvalidLimit, #[error("the task facts could not be read: {reason}")] Read { reason: String }, diff --git a/docs/design/plugins/FileReads.md b/docs/design/plugins/FileReads.md index 74882bcdfa..27129a1a18 100644 --- a/docs/design/plugins/FileReads.md +++ b/docs/design/plugins/FileReads.md @@ -42,8 +42,8 @@ let binding = reads.binding(BindingRequest { purpose: Purpose::Write, }).await?; // Closed, Failed match binding { - BindingReply::Bound(binding) => { /* preserve encoding and line endings; check the revision */ } - BindingReply::Unavailable(reason) => { + BindingReply::Bound { binding } => { /* preserve encoding and line endings; check the revision */ } + BindingReply::Unavailable { reason } => { return Ok(text_binding_required(reason)); // the model re-reads or edits } } @@ -154,7 +154,7 @@ Flow tests on the owner: ## Requirements raised to mechanism owners - **Cross-scope access ([ADR 027](https://github.com/arcships/dim/pull/2029), [#2127](https://github.com/arcships/dim/issues/2127), target).** A Session part reaches a line's data face by line id with `line_owner::(line)`. The file tools use it to reach `binding` and `record`; FileReads adds no forwarding operation. -- **File-tool codec ([#2103](https://github.com/arcships/dim/pull/2103), target).** The codec's `TextEncoding`, `EncodingSource`, `Bom`, `Eol` and `TextFileBinding` are not wire data (`TextEncoding::Legacy` holds an `encoding_rs` reference and `raw_revision` is `[u8; 32]`). The codec owner provides the mapping to the DTOs below: the encoding label (`utf-8`, `utf-16le`, `utf-16be`, or the requested legacy name lowercased), the revision as lowercase hex, and the three enums as their snake-case names; or derives serde on them with the same wire values. This owner does not change the codec. +- **File-tool codec ([#2103](https://github.com/arcships/dim/pull/2103), target).** The codec's `TextEncoding`, `EncodingSource`, `Bom`, `Eol` and `TextFileBinding` are not wire data (`TextEncoding::Legacy` holds an `encoding_rs` reference and `raw_revision` is `[u8; 32]`). The codec owner provides an explicit mapping to the DTOs below: the encoding label as the codec's current `utf8`, `utf16le`, `utf16be` or the requested legacy name lowercased; the revision as lowercase hex; `EncodingSource` as `bom`, `user` or `utf8Policy` (the codec's `utf8-policy` label maps to `utf8Policy`); and `Bom`/`Eol` as their camelCase wire names. `TextEncoding::Legacy` holds an `encoding_rs` reference, so deriving serde on the codec types is not a substitute; the mapping is the contract. This owner does not change the codec. - **None other.** No Timeline, Dispatcher, loader or runtime change. ## Binding appendix @@ -184,7 +184,7 @@ pub struct BindingRequest { pub struct TextFileBinding { /// Lowercase hex of the SHA-256 of the raw file bytes. pub revision: String, - /// The codec's label: "utf-8", "utf-16le", "utf-16be", or the requested + /// The codec's label: `utf8`, `utf16le`, `utf16be`, or the requested /// legacy name lowercased. pub encoding: String, pub encoding_source: EncodingSource, diff --git a/docs/design/plugins/Permission.md b/docs/design/plugins/Permission.md index 674932e9df..56dcd3d235 100644 --- a/docs/design/plugins/Permission.md +++ b/docs/design/plugins/Permission.md @@ -80,9 +80,9 @@ The file-access facts operation that resolves the target is a target of #2093; i | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `decide` | One call's outcome | `{call, risk?, source?}` | `DecisionReply` | The caller's token stops the facts or advice read; the decision is not made | `cancelled`, `failed`, `closed` | -| `update` | Versioned policy write | `{expectedVersion, policy}` | `u64` (the new version) | None; one commit | `conflict`, `failed`, `closed` | -| `advise` | Register tool advice for the calling row's lifetime | `caller: &Ctx`, `name`, callback | `()` | None | `duplicate`, `closed` | +| `decide` | One call's outcome | `{call, risk?, source?}` | `DecisionReply` | The caller's token stops the facts or advice read; the decision is not made | `Cancelled`, `Failed`, `Closed` | +| `update` | Versioned policy write | `{expectedVersion, policy}` | `u64` (the new version) | None; one commit | `Conflict`, `Failed`, `Closed` | +| `advise` | Register tool advice for the calling row's lifetime | `caller: &Ctx`, `name`, callback | `()` | None | `Duplicate`, `Closed` | | `PermissionState` (published value) | Read the policy and its version | — | `{version, policy}` | None | — | `risk` is the tool owner's declaration (`read_filesystem`, `write_filesystem`, `execute_process`, `network`, `session`, or absent). `source` is present exactly for an admission; the owner asks the advisors only then, and `advisorQuestion` says whether an advisor required an explicit answer, so a policy change can end a policy question but never an advisor's. @@ -93,35 +93,35 @@ The policy is the preset and `allowedTools`/`disallowedTools`. A deny from the t | Kind | Operation | Retryable | What the caller does next | | --- | --- | --- | --- | -| `cancelled` | `decide` | No | The call's batch was cancelled; do not run the call. | -| `failed` | `decide`, `update` | Yes, by a later attempt | A fact or rule read failed, or the `permission/changed` fact could not be committed; nothing was decided or written; the owner reports a fault; `decide`'s caller does not run the call, and `update`'s caller re-reads the version and may retry. | -| `closed` | any | No, in this generation | The generation is closing or reloading; stop; a later generation serves. | -| `conflict` | `update` | Yes, after re-reading | Re-read the version from `PermissionState` and decide whether to retry the update with the new base. | -| `duplicate` | `advise` | No | The name is taken; choose another name. The registration stays until the row unloads. | +| `Cancelled` | `decide` | No | The call's batch was cancelled; do not run the call. | +| `Failed` | `decide`, `update` | Yes, by a later attempt | A fact or rule read failed, or the `permission/changed` fact could not be committed; nothing was decided or written; the owner reports a fault; `decide`'s caller does not run the call, and `update`'s caller re-reads the version and may retry. | +| `Closed` | any | No, in this generation | The generation is closing or reloading; stop; a later generation serves. | +| `Conflict` | `update` | Yes, after re-reading | Re-read the version from `PermissionState` and decide whether to retry the update with the new base. | +| `Duplicate` | `advise` | No | The name is taken; choose another name. The registration stays until the row unloads. | -An unreadable fact or rule is not a decision: the owner reports `failed`, because the caller's next step is to retry or fail the turn, not to treat the call as denied. An advisor's failure counts as no advice: its code and message are not forwarded, and the owner decides on its own result. +An unreadable fact or rule is not a decision: the owner reports `Failed`, because the caller's next step is to retry or fail the turn, not to treat the call as denied. An advisor's failure counts as no advice: its code and message are not forwarded, and the owner decides on its own result. ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `decide` | Read the policy, resolve the target and read the facts, read the rules for a command, ask the advisors for an admission, combine and answer | The facts or advice read stops; `cancelled`; nothing changes | The decision's future is the caller's; no resource is held | Refused with `closed`; an in-flight decision ends `closed` | Permission; the facts read by the facts owner | -| `decide` — a fact or rule read fails | Answer `failed`; nothing is decided | — | — | — | Permission | -| `update` | Commit `permission/changed` when the expected version matches, answer the new version once dispatched | None | The write is admitted or not; nothing to release | Refused with `closed` | Permission and the Timeline | +| `decide` | Read the policy, resolve the target and read the facts, read the rules for a command, ask the advisors for an admission, combine and answer | The facts or advice read stops; `Cancelled`; nothing changes | The decision's future is the caller's; no resource is held | Refused with `Closed`; an in-flight decision ends `Closed` | Permission; the facts read by the facts owner | +| `decide` — a fact or rule read fails | Answer `Failed`; nothing is decided | — | — | — | Permission | +| `update` | Commit `permission/changed` when the expected version matches, answer the new version once dispatched | None | The write is admitted or not; nothing to release | Refused with `Closed` | Permission and the Timeline | | `advise` | Register the callback under the name against the calling row | None | The row's unload withdraws the registration | Every registration of the generation is withdrawn | Permission | ## Client-visible changes The published `permission` face ([Permission plugin page](../../architecture/rust-agent/plugins/Permission.md#permission-data-face)) publishes `check(call, risk, cancelled) -> {decision} | {decision, reason}` with errors `Failed`/`Cancelled`. It is replaced as follows, and the maintainer is asked to confirm: -- `check` is removed; `decide({call, risk?, source?}, cancelled)` answers `{outcome: "allow"|"ask"|"deny", reason?, advisorQuestion}`. The admission case (advisors, source) moves into the same operation, so Approval no longer calls two operations. +- `check` is removed; `decide({call, risk?, source?}, cancelled)` answers `DecisionReply` (`outcome`, `reason?`, `advisorQuestion`). The admission case (advisors, source) moves into the same operation, so Approval no longer calls two operations. - `update` and `advise` are new on the face; `PermissionState` keeps its `{version, policy}` shape. -- Error codes change case with the standard binding spelling: `Failed`/`Cancelled` become `failed`/`cancelled`; `conflict` and `duplicate` are new. +- The published codes `Failed` and `Cancelled` are kept, and `Closed`, `Conflict` and `Duplicate` are added; the Appendix's `PascalCase` rename is what keeps them, so a caller matches the same strings as before. - The only caller of `check` is Approval, which this PR migrates; no client RPC, notification name, request field or model-visible text changes. ## Exceptions with reasons -- A branch part registers a callback (`advise`): §7 allows a callback by reference; the owner never calls it inside the Timeline's commit lock, and the calling row's unload withdraws it. +- A branch part registers a callback (`advise`): the callback is a direct parameter and a function value (`rutis::FromFunction`), so the bridge carries it as a function and the method needs no `#[service(skip)]`; the owner never calls it inside the Timeline's commit lock, and the calling row's unload withdraws it. The current code's `#[service(skip)]` on `register_advice` is removed by this contract. - The policy value is published as a read-only view: Approval subscribes to it to recheck a waiting call, and the App Server reads it for the client; neither reads Permission's internals. ## Supersedes @@ -135,9 +135,9 @@ Flow tests on the owner: - Presets decide by risk; `allowedTools` and `disallowedTools` refine the preset and a deny wins; an explicit disallow, a deny rule and a file denial are not lifted by an allow. - A file call asks when its resolved target is outside the workspace; a read or write fact denial refuses the call; a command rule denies under every preset and an allow rule only answers an ask for a simple command. -- An admission asks the advisors in name order; an ask refines an allow; a deny wins over an ask and an allow; a recheck asks no advisor; a registration is withdrawn when its part unloads; a second registration of the same name is `duplicate`. -- An update with a stale version is `conflict` with the current version; a dispatched change is visible to the next decision and survives a reload; a failed append answers `failed` and writes nothing. -- A failed fact read answers `failed`, not a denial. +- An admission asks the advisors in name order; an ask refines an allow; a deny wins over an ask and an allow; a recheck asks no advisor; a registration is withdrawn when its part unloads; a second registration of the same name is `Duplicate`. +- An update with a stale version is `Conflict` with the current version; a dispatched change is visible to the next decision and survives a reload; a failed append answers `Failed` and writes nothing. +- A failed fact read answers `Failed`, not a denial. - The published value's version is the last local change; the face and the Rust call answer the same decision. ## Rule check @@ -262,7 +262,7 @@ pub type AdviseFn = std::sync::Arc< >; #[derive(Debug, serde::Serialize, thiserror::Error)] -#[serde(tag = "code", rename_all = "snake_case")] +#[serde(tag = "code", rename_all = "PascalCase")] pub enum PermissionError { #[error("the decision was cancelled")] Cancelled, diff --git a/docs/design/plugins/ToolBinding.md b/docs/design/plugins/ToolBinding.md index 8b7e68478e..fd1417c602 100644 --- a/docs/design/plugins/ToolBinding.md +++ b/docs/design/plugins/ToolBinding.md @@ -296,8 +296,8 @@ impl ToolBinding { pub async fn bind(&self, request: BindRequest) -> Result<(), BindingError> { /* ... */ } pub fn adopted(&self, request_id: String) -> Result { /* ... */ } pub async fn claim(&self, request: ClaimRequest) -> Result<(), BindingError> { /* ... */ } - pub fn release(&self, request_id: String) { /* ... */ } - pub fn retain_only(&self, request_id: String) { /* ... */ } + pub fn release(&self, request_id: String) -> Result<(), BindingError> { /* ... */ } + pub fn retain_only(&self, request_id: String) -> Result<(), BindingError> { /* ... */ } pub fn transfer(&self, request: TransferRequest) -> Result<(), BindingError> { /* ... */ } } ``` diff --git a/docs/design/plugins/ToolExecutor.md b/docs/design/plugins/ToolExecutor.md index 02bad4fcc6..9ec372c0ed 100644 --- a/docs/design/plugins/ToolExecutor.md +++ b/docs/design/plugins/ToolExecutor.md @@ -128,7 +128,7 @@ Flow tests on the owner: - A program that returns early still has its child effects merged; a `close` before the program ends answers the confirmed effects, and the same effects appear once in the parent result. - An interrupt cancels a running child and refuses a new gate; a reload settles an open child and open parent, and a reload-settled result fails the turn. - A dropped `invoke` ends with `cancelled` and leaves the child's fact recording the child's cancellation; the gate still accepts the program's next call; a child's own failure is `Ok(ToolResult { is_error: true })`. -- `open` refuses a parent call that is not in the current batch and a second batch while one runs; `gate_closed` answers a call after the parent settled. +- `open` refuses a parent call that is not in the current batch and a second batch while one runs; a call from another row is `gate_closed` for `invoke` and `close`, because the gate id is bound to the row that opened it; `gate_closed` answers a call after the parent settled. - The same operations over the face and in process answer the same results and errors. ## Rule check From c7ec39bee5ba7505e2e6b275438f0db490ca10e5 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 14:10:28 +0800 Subject: [PATCH 10/11] docs(tools): align ToolBinding with the registry and Loop --- docs/design/contracts/runtime-owner-operations.md | 2 +- docs/design/plugins/ToolBinding.md | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index e11d51238f..047844ec7e 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -73,5 +73,5 @@ substitutes a newer head. | Loop and ContextPreparation → HistoryRenderer | `context({branchId, through}) → ContextHistory`, `renderedContext({branchId, through}) → {context, history: HistoryEntry[]}`, `snapshot({context, retainFrom, anchor}) → RecoverySnapshot`, `streamCheckpoint({branchId, through, retainFrom, batch}) → ProjectionCheckpoint`. | | Loop and ModelProvider → ContextPreparation | `prepare({source: ContextPrepareData, projection?}, cancelled) → ModelRequest`, `validate({requestId, request}, cancelled) → void`. Reuse the prepared projection at the original cutoff. | | ContextPreparation and usage readers → ContextUsage | `read({through?}, cancelled) → {through, contextWindow, outputTokens, thresholdTokens, estimatedInputTokens, baselineSource}`. | -| Loop, ToolExecutor and Code Mode readers → `toolBinding` | `bind({requestId, turnId, through, declared, sources}) → void`, `adopted({requestId}) → {adoption, tools}`, `claim({requestId, calls, context}) → void`, `transfer({from, to}) → void`([ToolBinding](../plugins/ToolBinding.md)). The record is settled from the line's `step/tool-result` and `turn/end`. | +| Loop, ToolExecutor and Code Mode readers → `toolBinding` | `bind({requestId, turnId, through, declared, sources}) → void`, `adopted({requestId}) → {adoption, tools}`, `claim({requestId, calls, context}) → void`, `transfer({from, to}) → void`, `release({requestId}) → void`, `retain_only({requestId}) → void`([ToolBinding](../plugins/ToolBinding.md)). Settlement follows the line's `step/tool-result` and `turn/end`; `retain_only` is the Loop's own rebuild step. | | Nested tool execution → `toolExecutor` | `open({parentCallId, context}, cancelled) → gateId`, `invoke({gateId, call}, cancelled) → ToolResult`, `close({gateId}) → {effects}`([ToolExecutor](../plugins/ToolExecutor.md)). The owner closes the gate at the parent's settlement; interruption releases it. | diff --git a/docs/design/plugins/ToolBinding.md b/docs/design/plugins/ToolBinding.md index fd1417c602..77395a796d 100644 --- a/docs/design/plugins/ToolBinding.md +++ b/docs/design/plugins/ToolBinding.md @@ -90,7 +90,7 @@ binding.bind(BindRequest { }).await?; ``` -A budget-recovery retry keeps the generation the first attempt declared; `transfer`, `release` and `retain_only` are synchronous: +A budget-recovery retry keeps the generation the first attempt declared; `transfer` is synchronous, and `release` and `retain_only` are awaited: ```rust binding.transfer(TransferRequest { from: old_request_id, to: new_request_id })?; // NoRecord @@ -128,7 +128,7 @@ let declared: Vec = binding.adopted(execution.request_id.clone() | `B:Timeline`, `B:Dispatcher` | Reconcile the prefix's last configuration at branch opening; consume `step/tool-result` and `turn/end` for settlement; write nothing. | | `B:BranchLifecycle` | Gate the registry-change watcher on activation and closing. | -The registry's `adopt`, `release`, `claim` and `release_claims` are called only by ToolBinding; Loop calls them through this owner and calls the registry only for `declarations`. +The registry's `adopt`, `release`, `claim` and `release_claims` are async and take the calling row; ToolBinding calls them only through these operations, and Loop calls the registry only for `declarations`. ### Operations @@ -231,7 +231,7 @@ Flow tests on the owner: ## Binding appendix -The service is marked on the owner type; the name stays `toolBinding`. Every operation completes without waiting; the registry's operations take the cancellation argument. `ToolDefinition` and `ToolSourceVersion` are `dim_agent_types` values; `ToolExecutionContext` is the crate's existing execution context (`dim_agent_capabilities::host`), not a type of this owner. +The service is marked on the owner type; the name stays `toolBinding`. `adopted` and `transfer` read or move the record and complete without waiting; `bind`, `claim`, `release` and `retain_only` are async because they call the registry's async operations. None of them takes the cancellation argument, and an admitted operation completes. `ToolDefinition` and `ToolSourceVersion` are `dim_agent_types` values; `ToolExecutionContext` is the crate's existing execution context (`dim_agent_capabilities::host`), not a type of this owner. ```rust use crate::host::ToolExecutionContext; @@ -296,8 +296,8 @@ impl ToolBinding { pub async fn bind(&self, request: BindRequest) -> Result<(), BindingError> { /* ... */ } pub fn adopted(&self, request_id: String) -> Result { /* ... */ } pub async fn claim(&self, request: ClaimRequest) -> Result<(), BindingError> { /* ... */ } - pub fn release(&self, request_id: String) -> Result<(), BindingError> { /* ... */ } - pub fn retain_only(&self, request_id: String) -> Result<(), BindingError> { /* ... */ } + pub async fn release(&self, request_id: String) -> Result<(), BindingError> { /* ... */ } + pub async fn retain_only(&self, request_id: String) -> Result<(), BindingError> { /* ... */ } pub fn transfer(&self, request: TransferRequest) -> Result<(), BindingError> { /* ... */ } } ``` From 437266bffdc7ca40628a7100776805eca9cdc1ff Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 14:28:11 +0800 Subject: [PATCH 11/11] docs(tools): link ADR 027 instead of restating the data-face reach --- docs/design/plugins/Approval.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design/plugins/Approval.md b/docs/design/plugins/Approval.md index b12003805f..694d70a97f 100644 --- a/docs/design/plugins/Approval.md +++ b/docs/design/plugins/Approval.md @@ -165,7 +165,7 @@ Flow tests on the owner: | ADR 002 D3 | Depends on Permission (branch) and the branch infrastructure. | | ADR 002 D4 | No configuration. | | ADR 002 D5 | Language-neutral operations and data. | -| ADR 027 D3 | Applicable: Collaboration reaches a member line's `pending`/`decide` with `line_owner::(line)`; the face is resolvable by line id and is not a registration point. | +| ADR 027 | Applies: Collaboration reaches a member line's `pending`/`decide` with `line_owner::(line)` ([D1–D3](https://github.com/arcships/dim/pull/2029); the mechanism is [#2127](https://github.com/arcships/dim/issues/2127)). | ## Requirements raised to mechanism owners