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..047844ec7e 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}) → 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 @@ -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`, `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/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 new file mode 100644 index 0000000000..694d70a97f --- /dev/null +++ b/docs/design/plugins/Approval.md @@ -0,0 +1,216 @@ +# 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. + +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. +- 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, Cancelled, Failed, Closed +``` + +A client answers one request; the answer is accepted only while the request is pending: + +```rust +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? { + if request.approval_id == target { + approval.decide(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`, `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. + +### Errors + +| 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 + +| 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 | +| `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` 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. +- 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. + +## 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. + +## 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: + +- 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. + +## 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. | +| 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 + +- **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 + +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; +use dim_agent_runtime::PublicService; +use dim_agent_types::{ApprovalCallData, ApprovalDecision, ApprovalRequestData, BranchSource}; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct AdmitRequest { + pub source: BranchSource, + pub call: ApprovalCallData, + pub risk: Option, +} + +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "PascalCase")] +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")] + 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, 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 new file mode 100644 index 0000000000..42946bc017 --- /dev/null +++ b/docs/design/plugins/BackgroundExec.md @@ -0,0 +1,264 @@ +# 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. 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. +- 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 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` | + +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, Failed +``` + +The product reads the running task's preview and pages its file: + +```rust +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, Read, Closed +``` + +A client stops a task and waits for its terminal: + +```rust +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 + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `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 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), `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`, `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` | + +`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 | 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. | +| `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. | +| `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 + +| 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` | 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. +- 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. + +## 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 + +- `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 + +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 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. + +## 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 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. | +| §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. | +| 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), 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` is a `dim_agent_types` value. + +```rust +use crate::host::CancelledFn; +use dim_agent_runtime::PublicService; +use dim_agent_types::ExecEndedData; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +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", deny_unknown_fields)] +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", deny_unknown_fields)] +pub struct WaitRequest { + pub task_id: String, + pub timeout_ms: u64, +} + +#[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, + #[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")] + #[serde(rename = "invalidLimit")] + 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, +} + +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..27129a1a18 --- /dev/null +++ b/docs/design/plugins/FileReads.md @@ -0,0 +1,260 @@ +# 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. + +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. +- 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 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: canonical.clone(), + purpose: Purpose::Write, +}).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, + binding: new_binding, + established, +})?; // Closed, Failed +``` + +The `edit` tool asks with the edit purpose, which ignores compaction: + +```rust +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)), +}; +``` + +## 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 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 + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `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` | + +`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 | 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. 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 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. + +## 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. + +## 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: + +- 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, 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`. +- 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 + +| 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. | +| 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 + +- **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 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 + +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", deny_unknown_fields)] +pub struct BindingRequest { + /// The canonical path the file tool resolved. + pub path: String, + pub purpose: Purpose, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TextFileBinding { + /// Lowercase hex of the SHA-256 of the raw file bytes. + pub revision: String, + /// The codec's label: `utf8`, `utf16le`, `utf16be`, 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 { + NeverRead, + Compacted, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[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", deny_unknown_fields)] +pub struct RecordRequest { + /// The canonical path the file tool resolved. + pub path: String, + pub binding: TextFileBinding, + pub established: u64, +} + +#[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 {} + +#[rutis::service(name = "fileReads")] +impl FileReads { + pub async fn binding(&self, request: BindingRequest) -> Result { /* ... */ } + pub fn record(&self, request: RecordRequest) -> Result<(), FileReadsError> { /* ... */ } +} +``` 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 new file mode 100644 index 0000000000..56dcd3d235 --- /dev/null +++ b/docs/design/plugins/Permission.md @@ -0,0 +1,287 @@ +# 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. + +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. +- 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, 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. `advise` is synchronous, `caller: &Ctx` is the calling row: + +```rust +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 version = permission.update(UpdateRequest { expected_version: read.version, policy: next_policy }).await?; // Conflict, Failed, Closed +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `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 a target of #2093; it is stated in Requirements. + +### Operations + +| 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` | +| `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. Replies are positional. + +### Errors + +| 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 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 `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. +- 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`): 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 + +- `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: + +- 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. +- 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, 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. | +| §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 (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 ([#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 + +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, PermissionPolicy}; +use rutis::Ctx; + +#[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", deny_unknown_fields)] +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", deny_unknown_fields)] +pub struct UpdateRequest { + pub expected_version: u64, + pub policy: PermissionPolicy, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +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 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. +#[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, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "PascalCase")] +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}")] + 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 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 206ed6d609..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. @@ -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 | @@ -53,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 new file mode 100644 index 0000000000..77395a796d --- /dev/null +++ b/docs/design/plugins/ToolBinding.md @@ -0,0 +1,303 @@ +# ToolBinding + +Scope: branch. Issue: #2028. + +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, 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, 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. + +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: + +- 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. + +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; 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; 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. + +## 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. +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(), + }).await?, // AlreadyBound, Invalid, Unavailable, Closed + None => { + // No tool part: declare the registry's current host and contributed tools. + let current = registry.declarations()?; + binding.bind(BindRequest { + request_id: request.id.clone(), + turn_id: turn.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?; // 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. `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()?; +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; `transfer` is synchronous, and `release` and `retain_only` are awaited: + +```rust +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.clone())?; // NoRecord +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.clone())?.tools + .into_iter() + .filter(|tool| tool.name != CODEMODE_TOOL) + .collect(); +``` + +## Own contract + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `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 async and take the calling row; ToolBinding calls them only through these operations, and Loop 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`, `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`. Replies are positional, as the published faces are. + +### Errors + +| 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. + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `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 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 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 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 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 + +- `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: + +- 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 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. + +## 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 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. | +| §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. | +| §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`, `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. | +| 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. | +| ADR 027 | Not applicable: ToolBinding holds no cross-scope access; its caller Loop is a branch part. | + +## Requirements raised to mechanism owners + +- **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 + +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; +use dim_agent_runtime::PublicService; +use dim_agent_types::{ToolCall, ToolDefinition, ToolSourceVersion}; + +/// 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 Adopted { + pub adoption: String, + pub tools: Vec, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +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", deny_unknown_fields)] +pub struct ClaimRequest { + pub request_id: String, + pub calls: Vec, + pub context: ToolExecutionContext, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct TransferRequest { + pub from: String, + pub to: String, +} + +#[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 {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, +} + +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 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> { /* ... */ } +} +``` diff --git a/docs/design/plugins/ToolExecutor.md b/docs/design/plugins/ToolExecutor.md new file mode 100644 index 0000000000..9ec372c0ed --- /dev/null +++ b/docs/design/plugins/ToolExecutor.md @@ -0,0 +1,233 @@ +# 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. 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 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. +- 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 | `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. + +## Caller example + +Code Mode opens a gate for one outer call and invokes child tools through it: + +```rust +let gate = executor.open(&ctx, OpenRequest { + parent_call_id: outer_call_id.clone(), + context: execution.clone(), +}, cancelled.clone()).await?; // Closed, Interrupted, NoBatch, Cancelled +// The program's tools.call: +let result = executor.invoke(&ctx, InvokeRequest { + gate_id: gate.gate_id.clone(), + call, +}, 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 record owner, not the executor: + +```rust +let adopted = binding.adopted(execution.request_id.clone())?; // 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 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 + +### Dependencies + +| Service | Purpose | +| --- | --- | +| `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. | +| `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}` | `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. + +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 | 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 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 | + +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 + +- 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 + +- `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: + +- 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 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; 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 + +| 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`, `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. | +| 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. | +| ADR 027 | Not applicable: the executor is reached by the branch that runs it, not across scopes. | + +## Requirements raised to mechanism owners + +- **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 + +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, ToolExecutionContext}; +use dim_agent_runtime::PublicService; +use dim_agent_types::{ToolCall, ToolEffect, ToolResult}; +use rutis::Ctx; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +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", deny_unknown_fields)] +pub struct InvokeRequest { + pub gate_id: String, + pub call: ToolCall, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +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, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] +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, + #[error("the call was cancelled")] + Cancelled, +} + +impl PublicService for ToolExecutor {} + +#[rutis::service(name = "toolExecutor")] +impl ToolExecutor { + 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 定义操作面 |